- 
                Notifications
    You must be signed in to change notification settings 
- Fork 55
CM-25773 - Support TF Plan scans #153
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Merged
      
      
    
  
     Merged
                    Changes from 33 commits
      Commits
    
    
            Show all changes
          
          
            36 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      082730c
              
                CM-25773- initial commit
              
              
                EfratIsrael 12b8a5c
              
                lint fix
              
              
                EfratIsrael a09ff32
              
                remove new line
              
              
                EfratIsrael 197e459
              
                add try-except
              
              
                EfratIsrael 14d1c52
              
                change list to List
              
              
                EfratIsrael c03bb27
              
                key error exception handler
              
              
                EfratIsrael 11ca913
              
                prettier
              
              
                EfratIsrael 84242b9
              
                encoding
              
              
                EfratIsrael d13d518
              
                fix path
              
              
                EfratIsrael 803c275
              
                lint
              
              
                EfratIsrael d32568d
              
                review fixing
              
              
                EfratIsrael 763622e
              
                renaming + typo fixing
              
              
                EfratIsrael 2bf1ded
              
                remove redundant json load check
              
              
                EfratIsrael 7bda660
              
                change soft fail
              
              
                EfratIsrael f8d4933
              
                add json.loads wrapper
              
              
                EfratIsrael 046b08d
              
                lint
              
              
                EfratIsrael a8050ea
              
                remove constructor
              
              
                EfratIsrael 184c9d8
              
                refactor iac parsing
              
              
                EfratIsrael 97f1b03
              
                handle null after + add test
              
              
                EfratIsrael 7c3296a
              
                Fix error handling
              
              
                MarshalX f9042bf
              
                Fix replacement of files
              
              
                MarshalX f2a5ea5
              
                fix iac doc manipulation
              
              
                EfratIsrael d4cd8f9
              
                revert iac manipultaion outside pre scan doc
              
              
                EfratIsrael 1d6a90a
              
                adding tests for different plans +
              
              
                EfratIsrael f0249e3
              
                fix readme
              
              
                EfratIsrael 27d4505
              
                fix readme
              
              
                EfratIsrael dab3f92
              
                fixing
              
              
                EfratIsrael 4c3784c
              
                pr fixing
              
              
                EfratIsrael 1e1ac2d
              
                pr fixing
              
              
                EfratIsrael 9ab3334
              
                lint
              
              
                EfratIsrael 921b047
              
                test fix
              
              
                EfratIsrael 805b0f6
              
                add test for generate document
              
              
                EfratIsrael b68e68f
              
                lint
              
              
                EfratIsrael fa0196e
              
                update test
              
              
                EfratIsrael cfb3b88
              
                typo fix
              
              
                EfratIsrael b0435d6
              
                move \n
              
              
                EfratIsrael File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
|  | @@ -16,18 +16,20 @@ | |
| from cycode.cli.ci_integrations import get_commit_range | ||
| from cycode.cli.config import configuration_manager | ||
| from cycode.cli.exceptions import custom_exceptions | ||
| from cycode.cli.helpers import sca_code_scanner | ||
| from cycode.cli.helpers import sca_code_scanner, tf_content_generator | ||
| from cycode.cli.models import CliError, CliErrors, Document, DocumentDetections, LocalScanResult, Severity | ||
| from cycode.cli.printers import ConsolePrinter | ||
| from cycode.cli.user_settings.config_file_manager import ConfigFileManager | ||
| from cycode.cli.utils import scan_utils | ||
| from cycode.cli.utils.path_utils import ( | ||
| change_filename_extension, | ||
| get_file_content, | ||
| get_file_size, | ||
| get_path_by_os, | ||
| get_relevant_files_in_path, | ||
| is_binary_file, | ||
| is_sub_path, | ||
| load_json, | ||
| ) | ||
| from cycode.cli.utils.progress_bar import ProgressBarSection | ||
| from cycode.cli.utils.progress_bar import logger as progress_bar_logger | ||
|  | @@ -328,18 +330,22 @@ def scan_disk_files(context: click.Context, path: str, files_to_scan: List[str]) | |
|  | ||
| is_git_diff = False | ||
|  | ||
| documents: List[Document] = [] | ||
| for file in files_to_scan: | ||
| progress_bar.update(ProgressBarSection.PREPARE_LOCAL_FILES) | ||
| try: | ||
| documents: List[Document] = [] | ||
| for file in files_to_scan: | ||
| progress_bar.update(ProgressBarSection.PREPARE_LOCAL_FILES) | ||
|  | ||
| content = get_file_content(file) | ||
| if not content: | ||
| continue | ||
| content = get_file_content(file) | ||
| if not content: | ||
| continue | ||
|  | ||
| documents.append(_generate_document(file, scan_type, content, is_git_diff)) | ||
|  | ||
| documents.append(Document(file, content, is_git_diff)) | ||
| perform_pre_scan_documents_actions(context, scan_type, documents, is_git_diff) | ||
| scan_documents(context, documents, is_git_diff=is_git_diff, scan_parameters=scan_parameters) | ||
|  | ||
| perform_pre_scan_documents_actions(context, scan_type, documents, is_git_diff) | ||
| scan_documents(context, documents, is_git_diff=is_git_diff, scan_parameters=scan_parameters) | ||
| except Exception as e: | ||
| _handle_exception(context, e) | ||
|  | ||
|  | ||
| def set_issue_detected_by_scan_results(context: click.Context, scan_results: List[LocalScanResult]) -> None: | ||
|  | @@ -574,7 +580,7 @@ def perform_pre_scan_documents_actions( | |
| context: click.Context, scan_type: str, documents_to_scan: List[Document], is_git_diff: bool = False | ||
| ) -> None: | ||
| if scan_type == consts.SCA_SCAN_TYPE: | ||
| logger.debug('Perform pre scan document actions') | ||
| logger.debug('Perform pre scan document add_dependencies_tree_document action') | ||
| sca_code_scanner.add_dependencies_tree_document(context, documents_to_scan, is_git_diff) | ||
|  | ||
|  | ||
|  | @@ -1099,6 +1105,37 @@ def _is_file_extension_supported(scan_type: str, filename: str) -> bool: | |
| return not filename.endswith(consts.SECRET_SCAN_FILE_EXTENSIONS_TO_IGNORE) | ||
|  | ||
|  | ||
| def _generate_document(file: str, scan_type: str, content: str, is_git_diff: bool) -> Document: | ||
| if _is_iac(scan_type) and _is_tfplan_file(file, content): | ||
| return _handle_tfplan_file(file, content, is_git_diff) | ||
| return Document(file, content, is_git_diff) | ||
|  | ||
|  | ||
| def _handle_tfplan_file(file: str, content: str, is_git_diff: bool) -> Document: | ||
| document_name = _generate_tfplan_document_name(file) | ||
| tf_content = tf_content_generator.generate_tf_content_from_tfplan(file, content) | ||
| return Document(document_name, tf_content, is_git_diff) | ||
|  | ||
|  | ||
| def _generate_tfplan_document_name(path: str) -> str: | ||
| document_name = change_filename_extension(path, '.tf') | ||
| timestamp = int(time.time()) | ||
| return f'{timestamp}-{document_name}' | ||
|  | ||
|  | ||
| def _is_iac(scan_type: str) -> bool: | ||
| return scan_type == consts.INFRA_CONFIGURATION_SCAN_TYPE | ||
|  | ||
|  | ||
| def _is_tfplan_file(file: str, content: str) -> bool: | ||
| if not file.endswith('.json'): | ||
| return False | ||
| tf_plan = load_json(content) | ||
| if not isinstance(tf_plan, dict): | ||
| return False | ||
| return 'resource_changes' in tf_plan | ||
|  | ||
|  | ||
| def _does_file_exceed_max_size_limit(filename: str) -> bool: | ||
| return get_file_size(filename) > consts.FILE_MAX_SIZE_LIMIT_IN_BYTES | ||
|  | ||
|  | @@ -1157,6 +1194,14 @@ def _handle_exception(context: click.Context, e: Exception, *, return_exception: | |
| 'Please try ignoring irrelevant paths using the `cycode ignore --by-path` command ' | ||
| 'and execute the scan again', | ||
| ), | ||
| custom_exceptions.TfplanKeyError: CliError( | ||
| soft_fail=True, | ||
| code='key_error', | ||
| message=f'\n{e!s}' | ||
|          | ||
| 'A crucial field is missing in your terraform plan file. ' | ||
| 'Please make sure that your file is well formed ' | ||
| 'and execute the scan again', | ||
| ), | ||
| InvalidGitRepositoryError: CliError( | ||
| soft_fail=False, | ||
| code='invalid_git_error', | ||
|  | ||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| import json | ||
| from typing import List | ||
|  | ||
| from cycode.cli.exceptions.custom_exceptions import TfplanKeyError | ||
| from cycode.cli.models import ResourceChange | ||
| from cycode.cli.utils.path_utils import load_json | ||
|  | ||
| ACTIONS_TO_OMIT_RESOURCE = ['delete'] | ||
|  | ||
|  | ||
| def generate_tf_content_from_tfplan(filename: str, tfplan: str) -> str: | ||
| planned_resources = _extract_resources(tfplan, filename) | ||
| return _generate_tf_content(planned_resources) | ||
|  | ||
|  | ||
| def _generate_tf_content(resource_changes: List[ResourceChange]) -> str: | ||
| tf_content = '' | ||
| for resource_change in resource_changes: | ||
| if not any(item in resource_change.actions for item in ACTIONS_TO_OMIT_RESOURCE): | ||
| tf_content += _generate_resource_content(resource_change) | ||
| return tf_content | ||
|  | ||
|  | ||
| def _generate_resource_content(resource_change: ResourceChange) -> str: | ||
| resource_content = f'resource "{resource_change.resource_type}" "{resource_change.name}" {{\n' | ||
| if resource_change.values is not None: | ||
| for key, value in resource_change.values.items(): | ||
| resource_content += f' {key} = {json.dumps(value)}\n' | ||
| resource_content += '}\n\n' | ||
| return resource_content | ||
|  | ||
|  | ||
| def _extract_resources(tfplan: str, filename: str) -> List[ResourceChange]: | ||
| tfplan_json = load_json(tfplan) | ||
|         
                  EfratIsrael marked this conversation as resolved.
              Show resolved
            Hide resolved | ||
| resources: List[ResourceChange] = [] | ||
| try: | ||
| resource_changes = tfplan_json['resource_changes'] | ||
| for resource_change in resource_changes: | ||
|         
                  EfratIsrael marked this conversation as resolved.
              Show resolved
            Hide resolved | ||
| resources.append( | ||
| ResourceChange( | ||
| resource_type=resource_change['type'], | ||
| name=resource_change['name'], | ||
| actions=resource_change['change']['actions'], | ||
| values=resource_change['change']['after'], | ||
| ) | ||
| ) | ||
| except (KeyError, TypeError) as e: | ||
| raise TfplanKeyError(filename) from e | ||
| return resources | ||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
              Empty file.
          
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| import os | ||
|  | ||
| from cycode.cli.helpers import tf_content_generator | ||
| from cycode.cli.utils.path_utils import get_file_content, get_immediate_subdirectories | ||
| from tests.conftest import TEST_FILES_PATH | ||
|  | ||
| _PATH_TO_EXAMPLES = os.path.join(TEST_FILES_PATH, 'tf_content_generator_files') | ||
|  | ||
|  | ||
| def test_generate_tf_content_from_tfplan() -> None: | ||
| examples_directories = get_immediate_subdirectories(_PATH_TO_EXAMPLES) | ||
| for example in examples_directories: | ||
| tfplan_content = get_file_content(os.path.join(_PATH_TO_EXAMPLES, example, 'tfplan.json')) | ||
| tf_expected_content = get_file_content(os.path.join(_PATH_TO_EXAMPLES, example, 'tf_content.txt')) | ||
| tf_content = tf_content_generator.generate_tf_content_from_tfplan(example, tfplan_content) | ||
| assert tf_content == tf_expected_content | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.