Skip to content
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

Develop #175

Closed
wants to merge 21 commits into from
Closed

Develop #175

wants to merge 21 commits into from

Conversation

NxPKG
Copy link
Contributor

@NxPKG NxPKG commented Nov 12, 2024

User description

(Please add to the PR name the issue/s that this PR would close if merged by using a Github keyword. Example: <feature name>. Closes #999. If your PR is made by a single commit, please add that clause in the commit too. This is all required to automate the closure of related issues.)

Description

Please include a summary of the change and link to the related issue.

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue).
  • New feature (non-breaking change which adds functionality).
  • Breaking change (fix or feature that would cause existing functionality to not work as expected).

Checklist

  • I have read and understood the rules about how to Contribute to this project
  • The pull request is for the branch develop
  • A new plugin (analyzer, connector, visualizer, playbook, pivot or ingestor) was added or changed, in which case:
    • I strictly followed the documentation "How to create a Plugin"
    • Usage file was updated.
    • Advanced-Usage was updated (in case the plugin provides additional optional configuration).
    • I have dumped the configuration from Django Admin using the dumpplugin command and added it in the project as a data migration. ("How to share a plugin with the community")
    • If a File analyzer was added and it supports a mimetype which is not already supported, you added a sample of that type inside the archive test_files.zip and you added the default tests for that mimetype in test_classes.py.
    • If you created a new analyzer and it is free (does not require any API key), please add it in the FREE_TO_USE_ANALYZERS playbook by following this guide.
    • Check if it could make sense to add that analyzer/connector to other freely available playbooks.
    • I have provided the resulting raw JSON of a finished analysis and a screenshot of the results.
    • If the plugin interacts with an external service, I have created an attribute called precisely url that contains this information. This is required for Health Checks.
    • If the plugin requires mocked testing, _monkeypatch() was used in its class to apply the necessary decorators.
    • I have added that raw JSON sample to the MockUpResponse of the _monkeypatch() method. This serves us to provide a valid sample for testing.
  • If external libraries/packages with restrictive licenses were used, they were added in the Legal Notice section.
  • Linters (Black, Flake, Isort) gave 0 errors. If you have correctly installed pre-commit, it does these checks and adjustments on your behalf.
  • I have added tests for the feature/bug I solved (see tests folder). All the tests (new and old ones) gave 0 errors.
  • If changes were made to an existing model/serializer/view, the docs were updated and regenerated (check CONTRIBUTE.md).
  • If the GUI has been modified:
    • I have a provided a screenshot of the result in the PR.
    • I have created new frontend tests for the new component or updated existing ones.
  • After you had submitted the PR, if DeepSource, Django Doctors or other third-party linters have triggered any alerts during the CI checks, I have solved those alerts.

Important Rules

  • If you miss to compile the Checklist properly, your PR won't be reviewed by the maintainers.
  • Everytime you make changes to the PR and you think the work is done, you should explicitly ask for a review. After being reviewed and received a "change request", you should explicitly ask for a review again once you have made the requested changes.

PR Type

Enhancement, Tests, Configuration changes, Documentation, Formatting, Error handling, Security, Dependencies


Description

  • Introduced multiple enhancements including new analyzers, serializers, and API integrations.
  • Added extensive test coverage for new and existing functionalities.
  • Implemented configuration changes for improved security and AWS integration.
  • Updated documentation URLs and improved formatting for better readability.
  • Enhanced error handling and security settings across various modules.
  • Refactored code for better maintainability and performance.
  • Updated frontend components with new utilities and improved logic.

Changes walkthrough 📝

Relevant files
Enhancement
55 files
mixins.py
Introduced VirusTotal API interaction mixin classes.         

api_app/mixins.py

  • Added imports for abc, base64, time, datetime, timedelta, and typing
    utilities.
  • Introduced VirusTotalv3BaseMixin class with methods for VirusTotal API
    interactions.
  • Implemented _perform_request method for handling HTTP requests.
  • Added methods for fetching behavior summaries and sigma analyses.
  • +585/-0 
    virus_total.py
    Implemented VirusTotal ingestor for sample and IOC extraction.

    api_app/ingestors_manager/ingestors/virus_total.py

  • Created VirusTotal class inheriting from Ingestor and
    VirusTotalv3BaseMixin.
  • Implemented run method to execute queries and download samples or
    IOCs.
  • Added _monkeypatch method for mocking HTTP requests in tests.
  • +316/-0 
    doc_info.py
    Enhanced document analysis with URL and CVE extraction.   

    api_app/analyzers_manager/file_analyzers/doc_info.py

  • Added imports for docxpy and oletools modules.
  • Enhanced run method to extract URLs and CVEs from documents.
  • Implemented methods for extracting external relationships and URLs
    from documents.
  • +169/-27
    vt3_intelligence_search.py
    Refactored VirusTotal intelligence search analyzer.           

    api_app/analyzers_manager/observable_analyzers/vt/vt3_intelligence_search.py

  • Refactored VirusTotalv3Intelligence class to use
    VirusTotalv3AnalyzerMixin.
  • Simplified run method to utilize _vt_intelligence_search.
  • Updated mock responses for testing.
  • +152/-31
    views.py
    Added job rescan and plugin report query functionalities.

    api_app/views.py

  • Added rescan action to JobViewSet for rescanning jobs.
  • Implemented plugin_report_queries view for querying plugin reports.
  • Integrated Elasticsearch queries for plugin reports.
  • +125/-1 
    basic_observable_analyzer.py
    Implemented basic observable analyzer with HTTP request handling.

    api_app/analyzers_manager/observable_analyzers/basic_observable_analyzer.py

  • Introduced BasicObservableAnalyzer class for analyzing observables.
  • Implemented HTTP request handling with optional authentication and
    certificates.
  • Added _monkeypatch method for mocking HTTP requests in tests.
  • +105/-0 
    tasks.py
    Added task to send plugin reports to Elasticsearch.           

    threat_matrix/tasks.py

  • Added send_plugin_report_to_elastic task to send plugin reports to
    Elasticsearch.
  • Implemented logic to convert reports to Elasticsearch documents and
    handle exceptions.
  • +98/-2   
    serializers.py
    Enhanced PivotConfigSerializer with additional fields and logic.

    api_app/pivots_manager/serializers.py

  • Added fields for related_analyzer_configs, related_connector_configs,
    and plugin_config.
  • Implemented validation, creation, and update logic for
    PivotConfigSerializer.
  • +68/-3   
    strings_info.py
    Enhanced StringsInfo analyzer with URL extraction.             

    api_app/analyzers_manager/file_analyzers/strings_info.py

  • Added URL extraction logic to StringsInfo analyzer.
  • Implemented update method and disabled mockup connections.
  • +49/-0   
    boxjs_scan.py
    Enhanced BoxJS analyzer with URL extraction.                         

    api_app/analyzers_manager/file_analyzers/boxjs_scan.py

  • Added URL extraction logic to BoxJS analyzer.
  • Implemented update method and disabled mockup connections.
  • +34/-1   
    serializers.py
    Enhanced PlaybookConfigSerializer with visualizers and editability.

    api_app/playbooks_manager/serializers.py

  • Updated PlaybookConfigSerializer to include visualizers and
    is_editable fields.
  • Refactored logic for determining playbook editability.
  • +11/-5   
    nerd.py
    Added NERD observable analyzer with API integration.         

    api_app/analyzers_manager/observable_analyzers/nerd.py

  • Added NERD observable analyzer class.
  • Implemented logic for running NERD analysis with API requests.
  • +68/-0   
    elastic.py
    Added serializers for Elasticsearch request and response handling.

    api_app/serializers/elastic.py

  • Added serializers for handling Elasticsearch requests and responses.
  • Defined ElasticRequest dataclass and corresponding serializer.
  • +67/-0   
    plugin.py
    Enhanced PluginConfigSerializer with PivotConfig support.

    api_app/serializers/plugin.py

  • Added PivotConfig to PluginConfigSerializer.
  • Updated PythonConfigSerializer to handle optional parameters.
  • +5/-6     
    signals.py
    Added signal handlers for cache refresh and logging.         

    api_app/signals.py

  • Added signal handlers for cache key refresh on PythonConfig save and
    delete.
  • Implemented logging for LogEntry post-save signal.
  • +23/-1   
    models.py
    Enhanced models with report value retrieval and singleton pattern.

    api_app/models.py

  • Added get_value method to AbstractReport for retrieving nested report
    values.
  • Introduced SingletonModel and LastElasticReportUpdate for singleton
    pattern.
  • +44/-0   
    __init__.py
    Added utility methods for job creation and sample analysis.

    tests/init.py

  • Added method to create jobs from file samples.
  • Implemented _analyze_sample method for sample analysis.
  • +32/-1   
    dshield.py
    Added DShield observable analyzer with API integration.   

    api_app/analyzers_manager/observable_analyzers/dshield.py

  • Added DShield observable analyzer class.
  • Implemented logic for running DShield analysis with API requests.
  • +53/-0   
    views.py
    Enhanced PivotConfigViewSet with CRUD operations and permissions.

    api_app/pivots_manager/views.py

  • Added mixins for create, update, and destroy operations in
    PivotConfigViewSet.
  • Implemented permission checks for pivot configuration actions.
  • +36/-4   
    admin.py
    Registered LogEntry model in admin with read-only access.

    api_app/admin.py

  • Registered LogEntry model in admin with read-only permissions.
  • Configured list display and search fields for LogEntry.
  • +25/-0   
    artifacts.py
    Simplified artifact analysis command arguments.                   

    api_app/analyzers_manager/file_analyzers/artifacts.py

  • Simplified run method by removing conflicting options.
  • Adjusted command arguments for artifact analysis.
  • +2/-11   
    analyzer_extractor.py
    Improved Robtex report extraction with key validation.     

    api_app/visualizers_manager/visualizers/passive_dns/analyzer_extractor.py

  • Added check for rrdata key in Robtex reports before processing.
  • Ensured only valid reports are converted to PDNSReport.
  • +15/-14 
    compare.py
    Simplified value retrieval in Compare pivot.                         

    api_app/pivots_manager/pivots/compare.py

  • Removed _get_value method and used get_value from AbstractReport.
  • Simplified logic for retrieving values to compare.
  • +1/-24   
    lnk_info.py
    Added LnkInfo analyzer for LNK file URL extraction.           

    api_app/analyzers_manager/file_analyzers/lnk_info.py

  • Added LnkInfo analyzer class for extracting URLs from LNK files.
  • Implemented logic to parse LNK files and extract URLs.
  • +37/-0   
    elastic_templates.py
    Added command for managing Elasticsearch index templates.

    api_app/management/commands/elastic_templates.py

  • Added management command to create or update Elasticsearch index
    templates.
  • Implemented logic to load and apply template from JSON file.
  • +39/-0   
    pdf_info.py
    Enhanced PDFInfo analyzer with URI extraction.                     

    api_app/analyzers_manager/file_analyzers/pdf_info.py

  • Added URI extraction logic to PDFInfo analyzer.
  • Ensured URIs are extracted only when conditions are met.
  • +5/-4     
    androguard.py
    Added AndroguardAnalyzer for APK file analysis.                   

    api_app/analyzers_manager/file_analyzers/androguard.py

  • Added AndroguardAnalyzer class for analyzing APK files.
  • Implemented logic to extract APK metadata and properties.
  • +35/-0   
    views.py
    Enhanced AnalyzerConfigViewSet with CRUD operations and permissions.

    api_app/analyzers_manager/views.py

  • Added mixins for create, update, and destroy operations in
    AnalyzerConfigViewSet.
  • Implemented permission checks for analyzer configuration actions.
  • +17/-2   
    documents.py
    Updated JobDocument with logging and field adjustments.   

    api_app/documents.py

  • Added logging setup and TODO comment for potential refactoring.
  • Updated JobDocument field definitions.
  • +10/-2   
    constants.py
    Enhanced constants with updated URL regex and HTTP methods.

    api_app/analyzers_manager/constants.py

  • Updated regex pattern for URL classification in ObservableTypes.
  • Added HTTPMethods class for HTTP method choices.
  • +10/-2   
    classes.py
    Enhanced health check logic for authentication-protected endpoints.

    api_app/classes.py

  • Improved health check logic to handle authentication-protected
    endpoints.
  • Added comments explaining the logic for handling HTTP status codes.
  • +8/-1     
    onenote.py
    Enhanced OneNoteInfo analyzer with base64 encoding for files.

    api_app/analyzers_manager/file_analyzers/onenote.py

  • Added base64 encoding for non-image files in OneNoteInfo analyzer.
  • Implemented logic to store encoded content in results.
  • +10/-0   
    views.py
    Added debug logging and parent job handling in playbook views.

    api_app/playbooks_manager/views.py

  • Added debug logging for request data in analyze_multiple_observables
    and analyze_multiple_files.
  • Implemented logic to handle parent job in file analysis.
  • +4/-1     
    app.py
    Enhanced error handling in intercept_box_js_result function.

    integrations/malware_tools_analyzers/app.py

  • Improved error handling in intercept_box_js_result function.
  • Added check for directory existence before processing results.
  • +10/-5   
    serializers.py
    Refined serializers for ingestor configuration and reports.

    api_app/ingestors_manager/serializers.py

  • Updated IngestorConfigSerializerForMigration to exclude certain
    fields.
  • Refined fields in IngestorReportBISerializer.
  • +19/-2   
    download_file_from_uri.py
    Modified stored_base64 handling in DownloadFileFromUri analyzer.

    api_app/analyzers_manager/observable_analyzers/download_file_from_uri.py

  • Changed stored_base64 field to a list in DownloadFileFromUri analyzer.
  • Implemented logic to append base64 content to the list.
  • +3/-3     
    any_compare.py
    Refactored field existence check in AnyCompare pivot.       

    api_app/pivots_manager/pivots/any_compare.py

  • Refactored should_run method to iterate over related reports.
  • Improved logic for checking field existence in reports.
  • +10/-7   
    load_file.py
    Enhanced base64 decoding logic in LoadFile pivot.               

    api_app/pivots_manager/pivots/load_file.py

  • Modified get_value_to_pivot_to method to handle lists of values.
  • Implemented logic to decode base64 values from lists.
  • +11/-2   
    queryset.py
    Updated Elasticsearch client references in queryset logic.

    api_app/queryset.py

  • Updated Elasticsearch client references to ELASTICSEARCH_BI_CLIENT.
  • Adjusted logic for creating index templates and sending data to
    Elasticsearch.
  • +2/-2     
    job.py
    Enhanced JobResponseSerializer with sample field and fixed MIME type
    check.

    api_app/serializers/job.py

  • Added is_sample field to JobResponseSerializer.
  • Fixed typo in MIME type check for ZIP files.
  • +2/-1     
    vt3_get.py
    Added update method to VirusTotalv3 analyzer.                       

    api_app/analyzers_manager/observable_analyzers/vt/vt3_get.py

  • Added update method to VirusTotalv3 analyzer.
  • Ensured consistency with other analyzer classes.
  • +5/-2     
    exceptions.py
    Added NotImplementedException for unsupported services.   

    api_app/exceptions.py

  • Added NotImplementedException class for unsupported services.
  • Extended APIException to provide custom status and detail.
  • +7/-1     
    dumpplugin.py
    Enhanced plugin dumping with reverse relationship handling.

    api_app/management/commands/dumpplugin.py

  • Added imports for reverse relationship descriptors.
  • Updated logic to handle reverse relationships in plugin dumping.
  • +9/-2     
    signals.py
    Added signal handler for playbooks_choice changes in PivotConfig.

    api_app/pivots_manager/signals.py

  • Added signal handler for changes in playbooks_choice of PivotConfig.
  • Implemented logic to update description on changes.
  • +17/-0   
    models.py
    Add LNK MIME type to MimeTypes class                                         

    api_app/analyzers_manager/models.py

    • Added a new MIME type LNK to the MimeTypes class.
    +1/-0     
    droidlysis.py
    Increase max_tries for HTTP request polling in DroidLysis

    api_app/analyzers_manager/file_analyzers/droidlysis.py

    • Increased the max_tries for HTTP request polling from 10 to 30.
    +1/-1     
    permissions.py
    Add PivotActionsPermission class for pivot actions             

    api_app/pivots_manager/permissions.py

  • Added a new PivotActionsPermission class to handle permissions for
    pivot actions.
  • +10/-0   
    classes.py
    Add logging for start and finish of ingestor                         

    api_app/ingestors_manager/classes.py

  • Added logging statements in before_run and after_run methods to log
    start and finish of ingestor.
  • +5/-0     
    permissions.py
    Add isPluginActionsPermission class for plugin actions     

    api_app/permissions.py

  • Added a new isPluginActionsPermission class to handle permissions for
    plugin actions.
  • +10/-0   
    urls.py
    Add plugin_report_queries path to urlpatterns                       

    api_app/urls.py

    • Added a new path plugin_report_queries to the urlpatterns.
    +2/-0     
    observables.js
    Refactor observableValidators to use generic classification

    frontend/src/utils/observables.js

  • Updated observableValidators to return a default value with generic
    classification.
  • Refactored code to remove null returns and use default value.
  • +16/-12 
    miscConst.js
    Add HTTPMethods constant to miscConst                                       

    frontend/src/constants/miscConst.js

    • Added HTTPMethods constant with common HTTP methods.
    +8/-0     
    pluginConst.js
    Add AllPluginSupportedTypes constant to pluginConst           

    frontend/src/constants/pluginConst.js

  • Added AllPluginSupportedTypes constant with supported plugin types.
  • +9/-0     
    utils.js
    Add is_sample property to job node in addJobNode                 

    frontend/src/components/investigations/flow/utils.js

    • Added is_sample property to job node in addJobNode function.
    +1/-0     
    ScanForm.jsx
    Refactor ScanForm component with new form utilities           

    frontend/src/components/scan/ScanForm.jsx

  • Refactored ScanForm component to use new form components and
    utilities.
  • Simplified observable type selection logic.
  • +82/-338
    Tests
    17 files
    test_tasks.py
    Added tests for Elasticsearch plugin report integration. 

    tests/threat_matrix/test_tasks.py

  • Added a new test case SendElasticTestCase for testing Elasticsearch
    integration.
  • Mocked current time and Elasticsearch connection for testing.
  • Implemented tests for sending plugin reports to Elasticsearch.
  • +397/-0 
    test_api.py
    Added tests for job rescan functionality and permissions.

    tests/api_app/test_api.py

  • Added tests for job rescan functionality for observable analyzers and
    playbooks.
  • Implemented tests for permission checks during job rescans.
  • +211/-0 
    test_mixins.py
    Added tests for VirusTotal mixin classes.                               

    tests/api_app/test_mixins.py

  • Added test cases for VirusTotalv3BaseMixin and
    VirusTotalv3AnalyzerMixin.
  • Implemented tests for request parameter and URI generation.
  • Mocked HTTP responses for testing.
  • +191/-0 
    test_views.py
    Added tests for analyzer configuration management.             

    tests/api_app/analyzers_manager/test_views.py

  • Added tests for creating, updating, and deleting analyzer
    configurations.
  • Implemented permission checks for analyzer operations.
  • +154/-1 
    test_views.py
    Added tests for pivot configuration CRUD operations.         

    tests/api_app/pivots_manager/test_views.py

  • Added imports for AnalyzerConfig, Parameter, PluginConfig, Membership,
    and Organization.
  • Implemented test_create, test_update, and test_delete methods for
    testing pivot configurations.
  • Added logic to test creation, update, and deletion of pivot
    configurations with various conditions.
  • +148/-1 
    test_doc_info.py
    Added tests for DocInfo analyzer functionality.                   

    tests/api_app/analyzers_manager/file_analyzers/test_doc_info.py

  • Added test cases for DocInfo analyzer.
  • Implemented tests for Follina, macro, CVE, and URL extraction.
  • +112/-0 
    test_classes.py
    Added test job creation and health check logic.                   

    tests/api_app/analyzers_manager/test_classes.py

  • Added test job creation for .lnk files.
  • Implemented logic to skip tests if health check fails.
  • +12/-5   
    test_strings_info.py
    Added test for URL extraction in StringsInfo analyzer.     

    tests/api_app/analyzers_manager/file_analyzers/test_strings_info.py

  • Added test case for URL extraction in StringsInfo analyzer.
  • Implemented logic to verify extracted URLs from PDF files.
  • +40/-0   
    test_serializers.py
    Added tests for PivotConfig creation with plugin configuration.

    tests/api_app/pivots_manager/test_serializers.py

  • Added tests for creating PivotConfig with and without plugin
    configuration.
  • Implemented logic to validate and save pivot configurations.
  • +37/-0   
    test_iocextract.py
    Added test for IOC extraction in IocExtract analyzer.       

    tests/api_app/analyzers_manager/file_analyzers/test_iocextract.py

  • Added test case for IocExtract analyzer.
  • Implemented logic to verify extracted IOCs from text files.
  • +33/-0   
    test_boxjs.py
    Added test for URL extraction in BoxJS analyzer.                 

    tests/api_app/analyzers_manager/file_analyzers/test_boxjs.py

  • Added test case for URL extraction in BoxJS analyzer.
  • Implemented logic to verify extracted URLs from JavaScript files.
  • +37/-0   
    test_onenote_info.py
    Added test for base64 extraction in OneNoteInfo analyzer.

    tests/api_app/analyzers_manager/file_analyzers/test_onenote_info.py

  • Added test case for OneNoteInfo analyzer.
  • Implemented logic to verify extracted base64 content from OneNote
    files.
  • +33/-0   
    test_pdf_info.py
    Added test for URL extraction in PDFInfo analyzer.             

    tests/api_app/analyzers_manager/file_analyzers/test_pdf_info.py

  • Added test case for URL extraction in PDFInfo analyzer.
  • Implemented logic to verify extracted URLs from PDF files.
  • +34/-0   
    test_lnk_info.py
    Added test for URL extraction in LnkInfo analyzer.             

    tests/api_app/analyzers_manager/file_analyzers/test_lnk_info.py

  • Added test case for URL extraction in LnkInfo analyzer.
  • Implemented logic to verify extracted URLs from LNK files.
  • +29/-0   
    observables.test.js
    Update observable validators tests for generic classification

    frontend/tests/utils/observables.test.js

  • Updated tests to use generic classification instead of returning null
    for invalid domains and hashes.
  • Added new test cases for invalid domains and valid phone numbers.
  • +35/-18 
    mock.js
    Update mock stores with new properties and functions         

    frontend/tests/mock.js

  • Added new mock functions and properties to mockedUseAuthStore.
  • Updated mockedUseOrganizationStoreNoOrg and
    mockedUseOrganizationStoreOwner with isInOrganization.
  • +21/-2   
    JobActionBar.test.jsx
    Update JobActionsBar tests for new rescan API endpoint     

    frontend/tests/components/jobs/result/utils/JobActionBar.test.jsx

  • Updated tests for JobActionsBar to use new API endpoint for
    rescanning.
  • +18/-100
    Configuration changes
    28 files
    0025_ingestor_config_virustotal_example_query.py
    Added migration for VirusTotal ingestor configuration.     

    api_app/ingestors_manager/migrations/0025_ingestor_config_virustotal_example_query.py

  • Added migration for creating a new VirusTotal ingestor configuration.
  • Defined parameters and values for the ingestor configuration.
  • Implemented migration functions to apply and reverse the changes.
  • +272/-0 
    0120_alter_analyzerconfig_not_supported_filetypes_and_more.py
    Updated analyzer configuration for file type support.       

    api_app/analyzers_manager/migrations/0120_alter_analyzerconfig_not_supported_filetypes_and_more.py

  • Altered AnalyzerConfig model fields for supported and not supported
    file types.
  • Updated choices for file types in the model.
  • +180/-0 
    0126_analyzer_config_nerd_analyzer.py
    Added migration for NERD analyzer configuration.                 

    api_app/analyzers_manager/migrations/0126_analyzer_config_nerd_analyzer.py

  • Added migration for creating a new NERD analyzer configuration.
  • Defined parameters and values for the NERD analyzer.
  • Implemented migration functions to apply and reverse the changes.
  • +163/-0 
    0033_pivot_config_extractedonenotefiles.py
    Added migration for ExtractedOneNoteFiles pivot configuration.

    api_app/pivots_manager/migrations/0033_pivot_config_extractedonenotefiles.py

  • Added migration script to create a new PivotConfig for
    ExtractedOneNoteFiles.
  • Defined parameters and values for the new pivot configuration.
  • Implemented migration and reverse migration functions.
  • +149/-0 
    0124_analyzer_config_androguard.py
    Added migration for Androguard analyzer configuration.     

    api_app/analyzers_manager/migrations/0124_analyzer_config_androguard.py

  • Added migration script for Androguard analyzer configuration.
  • Defined plugin details and migration logic.
  • +129/-0 
    0127_analyzer_config_dshield.py
    Added migration for DShield analyzer configuration.           

    api_app/analyzers_manager/migrations/0127_analyzer_config_dshield.py

  • Added migration script for DShield analyzer configuration.
  • Defined plugin details and migration logic.
  • +124/-0 
    0052_playbook_config_uris.py
    Added migration for Uris playbook configuration.                 

    api_app/playbooks_manager/migrations/0052_playbook_config_uris.py

  • Added migration script for Uris playbook configuration.
  • Defined playbook details and migration logic.
  • +118/-0 
    0121_analyzer_config_lnk_info.py
    Added migration for Lnk_Info analyzer configuration.         

    api_app/analyzers_manager/migrations/0121_analyzer_config_lnk_info.py

  • Added migration script for Lnk_Info analyzer configuration.
  • Defined plugin details and migration logic.
  • +120/-0 
    elasticsearch.py
    Enhanced Elasticsearch client configuration with security settings.

    threat_matrix/settings/elasticsearch.py

  • Updated Elasticsearch client configuration with authentication and
    certificate settings.
  • Added checks for Elasticsearch host configuration.
  • +34/-12 
    0123_basic_observable_analyzer.py
    Added migration for BasicObservableAnalyzer module.           

    api_app/analyzers_manager/migrations/0123_basic_observable_analyzer.py

  • Added migration script for BasicObservableAnalyzer Python module.
  • Defined parameters for the module and implemented migration logic.
  • +87/-0   
    0125_update_yara_repo.py
    Updated Yara repository URLs in migration script.               

    api_app/analyzers_manager/migrations/0125_update_yara_repo.py

  • Added migration script to update Yara repository URLs.
  • Implemented migration and reverse migration logic.
  • +40/-0   
    0051_add_lnk_info_analyzer_free_to_use.py
    Added Lnk_Info analyzer to FREE_TO_USE_ANALYZERS playbook.

    api_app/playbooks_manager/migrations/0051_add_lnk_info_analyzer_free_to_use.py

  • Added migration to include Lnk_Info analyzer in FREE_TO_USE_ANALYZERS
    playbook.
  • Implemented migration and reverse migration logic.
  • +34/-0   
    0053_add_androguard_to_free_to_use_analyzers.py
    Added Androguard analyzer to FREE_TO_USE_ANALYZERS playbook.

    api_app/playbooks_manager/migrations/0053_add_androguard_to_free_to_use_analyzers.py

  • Added migration to include Androguard analyzer in
    FREE_TO_USE_ANALYZERS playbook.
  • Implemented migration and reverse migration logic.
  • +34/-0   
    0122_alter_soft_time_limit.py
    Altered soft time limit for Droidlysis analyzer.                 

    api_app/analyzers_manager/migrations/0122_alter_soft_time_limit.py

  • Added migration to alter soft_time_limit for Droidlysis analyzer.
  • Implemented migration and reverse migration logic.
  • +34/-0   
    0063_singleton_and_elastic_report.py
    Added migration for LastElasticReportUpdate singleton model.

    api_app/migrations/0063_singleton_and_elastic_report.py

  • Added migration to create LastElasticReportUpdate model with singleton
    constraint.
  • Implemented logic to enforce single instance of the model.
  • +39/-0   
    aws.py
    Added validation for AWS_USER_NUMBER in AWS settings.       

    threat_matrix/settings/aws.py

  • Added check for AWS_USER_NUMBER when AWS_SQS is enabled.
  • Implemented exit logic if user number is not specified.
  • +7/-2     
    celery.py
    Scheduled send_plugin_report_to_elastic task in Celery.   

    threat_matrix/celery.py

  • Added send_plugin_report_to_elastic task to Celery beat schedule.
  • Configured task options and schedule for periodic execution.
  • +9/-0     
    0034_changed_resubmitdownloadedfile_playbook_to_execute.py
    Changed playbook for ResubmitDownloadedFile pivot.             

    api_app/pivots_manager/migrations/0034_changed_resubmitdownloadedfile_playbook_to_execute.py

  • Added migration to change playbook for ResubmitDownloadedFile pivot.
  • Implemented migration logic to update playbook configuration.
  • +25/-0   
    __init__.py
    Import settings from a_secrets in settings init                   

    threat_matrix/settings/init.py

    • Imported settings from a_secrets.
    +1/-0     
    a_secrets.py
    Add a_secrets.py for AWS_REGION configuration                       

    threat_matrix/settings/a_secrets.py

  • Added a new settings file a_secrets.py with AWS_REGION configuration.
  • +7/-0     
    mail.py
    Import AWS_REGION from a_secrets in mail settings               

    threat_matrix/settings/mail.py

    • Changed import of AWS_REGION from aws to a_secrets.
    +1/-1     
    db.py
    Import AWS_REGION from a_secrets in db settings                   

    threat_matrix/settings/db.py

    • Changed import of AWS_REGION from aws to a_secrets.
    +2/-1     
    environment.js
    Update THREATMATRIX_DOCS_URL to new documentation site     

    frontend/src/constants/environment.js

    • Updated THREATMATRIX_DOCS_URL to the new documentation site URL.
    +1/-1     
    celery_ingestor.sh
    Add conditional queue logic for AWS_SQS in celery_ingestor

    docker/entrypoints/celery_ingestor.sh

  • Added conditional logic to set queues based on AWS_SQS environment
    variable.
  • +9/-1     
    celery_default.sh
    Add conditional queue logic for AWS_SQS in celery_default

    docker/entrypoints/celery_default.sh

  • Added conditional logic to set queues based on AWS_SQS environment
    variable.
  • +10/-1   
    celery_long.sh
    Add conditional queue logic for AWS_SQS in celery_long     

    docker/entrypoints/celery_long.sh

  • Added conditional logic to set queues based on AWS_SQS environment
    variable.
  • +8/-1     
    celery_local.sh
    Add conditional queue logic for AWS_SQS in celery_local   

    docker/entrypoints/celery_local.sh

  • Added conditional logic to set queues based on AWS_SQS environment
    variable.
  • +7/-1     
    uwsgi.sh
    Add ELASTIC_TEMPLATE_COMMAND to uwsgi entrypoint script   

    docker/entrypoints/uwsgi.sh

    • Added ELASTIC_TEMPLATE_COMMAND to the uwsgi entrypoint script.
    +3/-0     
    Error handling
    3 files
    secrets.py
    Refactored AWS secret retrieval exception handling.           

    threat_matrix/secrets.py

  • Refactored exception handling using match statement for AWS secret
    retrieval.
  • Added logging for unexpected exceptions.
  • +30/-24 
    abuse_submitter.py
    Added exception handling for missing parent job in AbuseSubmitter.

    api_app/connectors_manager/connectors/abuse_submitter.py

  • Added exception handling for missing parent job in AbuseSubmitter.
  • Implemented logic to raise exception if parent job is not found.
  • +6/-0     
    mwdb_scan.py
    Enhance exception handling in mwdb_scan run method             

    api_app/analyzers_manager/file_analyzers/mwdb_scan.py

  • Added mwdblib.exc.ObjectNotFoundError to the exception handling in run
    method.
  • +1/-1     
    Formatting
    6 files
    celery.py
    Cleaned up imports in Celery settings.                                     

    threat_matrix/settings/celery.py

    • Removed unused import statement.
    • Cleaned up AWS-related imports.
    +1/-6     
    malware_bazaar.py
    Simplify logger.info statement in malware_bazaar                 

    api_app/ingestors_manager/ingestors/malware_bazaar.py

    • Removed redundant string concatenation in logger.info statement.
    +1/-1     
    verify-email.html
    Format verify-email HTML template                                               

    authentication/templates/authentication/emails/verify-email.html

    • Minor formatting changes to the HTML structure.
    +12/-12 
    reset-password.html
    Format reset-password HTML template                                           

    authentication/templates/authentication/emails/reset-password.html

    • Minor formatting changes to the HTML structure.
    +5/-6     
    duplicate-email.html
    Format duplicate-email HTML template                                         

    authentication/templates/authentication/emails/duplicate-email.html

    • Minor formatting changes to the HTML structure.
    +5/-6     
    base.html
    Format base HTML template                                                               

    authentication/templates/authentication/emails/base.html

    • Minor formatting changes to the HTML structure.
    +2/-4     
    Documentation
    3 files
    ldap_config.py
    Update LDAP configuration documentation URL                           

    configuration/ldap_config.py

    • Updated the URL in the comment to the new documentation site.
    +1/-1     
    CHANGELOG.md
    Update documentation URLs and format changelog                     

    .github/CHANGELOG.md

  • Updated documentation URLs to the new site.
  • Reformatted lists and improved readability.
  • +209/-270
    Pivots.jsx
    Update description text for Pivots component                         

    frontend/src/components/plugins/types/Pivots.jsx

    • Updated description text for Pivots component.
    +1/-1     
    Dependencies
    1 files
    signals.py
    Use DRF ValidationError in signals                                             

    api_app/playbooks_manager/signals.py

  • Changed import from django.core.exceptions.ValidationError to
    rest_framework.exceptions.ValidationError.
  • +1/-1     
    Security
    1 files
    security.py
    Add CSRF_TRUSTED_ORIGINS setting for CSRF protection         

    threat_matrix/settings/security.py

    • Added CSRF_TRUSTED_ORIGINS setting for CSRF protection.
    +1/-0     
    Additional files (token-limit)
    90 files
    AnalyzerConfigForm.jsx
    ...                                                                                                           

    frontend/src/components/plugins/forms/AnalyzerConfigForm.jsx

    ...

    +615/-0 
    PlaybookConfigForm.test.jsx
    ...                                                                                                           

    frontend/tests/components/plugins/types/forms/PlaybookConfigForm.test.jsx

    ...

    +418/-0 
    PlaybookConfigForm.jsx
    ...                                                                                                           

    frontend/src/components/plugins/forms/PlaybookConfigForm.jsx

    ...

    +443/-0 
    PivotConfigForm.jsx
    ...                                                                                                           

    frontend/src/components/plugins/forms/PivotConfigForm.jsx

    ...

    +442/-0 
    AnalyzerConfigForm.test.jsx
    ...                                                                                                           

    frontend/tests/components/plugins/types/forms/AnalyzerConfigForm.test.jsx

    ...

    +386/-0 
    PivotConfigForm.test.jsx
    ...                                                                                                           

    frontend/tests/components/plugins/types/forms/PivotConfigForm.test.jsx

    ...

    +296/-0 
    pluginsMultiSelectDropdownInput.jsx
    ...                                                                                                           

    frontend/src/components/common/form/pluginsMultiSelectDropdownInput.jsx

    ...

    +343/-0 
    pluginActionsButtons.jsx
    ...                                                                                                           

    frontend/src/components/plugins/types/pluginActionsButtons.jsx

    ...

    +183/-31
    RuntimeConfigurationModal.jsx
    ...                                                                                                           

    frontend/src/components/scan/utils/RuntimeConfigurationModal.jsx

    ...

    +43/-212
    runtimeConfigurationInput.jsx
    ...                                                                                                           

    frontend/src/components/common/form/runtimeConfigurationInput.jsx

    ...

    +257/-0 
    AppHeader.test.jsx
    ...                                                                                                           

    frontend/tests/layouts/AppHeader.test.jsx

    ...

    +209/-0 
    pull_request_template.md
    ...                                                                                                           

    .github/pull_request_template.md

    ...

    +16/-18 
    PluginsContainer.jsx
    ...                                                                                                           

    frontend/src/components/plugins/PluginsContainer.jsx

    ...

    +68/-63 
    AppHeader.jsx
    ...                                                                                                           

    frontend/src/layouts/AppHeader.jsx

    ...

    +73/-35 
    InvestigationFlow.test.jsx
    ...                                                                                                           

    frontend/tests/components/investigations/flow/InvestigationFlow.test.jsx

    ...

    +49/-7   
    pluginActionsButtons.test.jsx
    ...                                                                                                           

    frontend/tests/components/plugins/types/pluginActionsButtons.test.jsx

    ...

    +87/-14 
    package.json
    ...                                                                                                           

    frontend/package.json

    ...

    +21/-21 
    PluginsContainers.test.jsx
    ...                                                                                                           

    frontend/tests/components/plugins/PluginsContainers.test.jsx

    ...

    +18/-0   
    traefik_prod.yml
    ...                                                                                                           

    docker/traefik_prod.yml

    ...

    +14/-14 
    project-requirements.txt
    ...                                                                                                           

    requirements/project-requirements.txt

    ...

    +11/-8   
    pluginTableColumns.jsx
    ...                                                                                                           

    frontend/src/components/plugins/types/pluginTableColumns.jsx

    ...

    +33/-5   
    TLPSelectInput.jsx
    ...                                                                                                           

    frontend/src/components/common/form/TLPSelectInput.jsx

    ...

    +91/-0   
    ScanConfigSelectInput.jsx
    ...                                                                                                           

    frontend/src/components/common/form/ScanConfigSelectInput.jsx

    ...

    +89/-0   
    pluginsApi.jsx
    ...                                                                                                           

    frontend/src/components/plugins/pluginsApi.jsx

    ...

    +76/-0   
    PluginData.jsx
    ...                                                                                                           

    frontend/src/components/user/config/PluginData.jsx

    ...

    +12/-1   
    Home.jsx
    ...                                                                                                           

    frontend/src/components/home/Home.jsx

    ...

    +4/-4     
    JobActionBar.jsx
    ...                                                                                                           

    frontend/src/components/jobs/result/bar/JobActionBar.jsx

    ...

    +5/-29   
    CODE_OF_CONDUCT.md
    ...                                                                                                           

    .github/CODE_OF_CONDUCT.md

    ...

    +11/-11 
    elasticsearch.override.yml
    ...                                                                                                           

    docker/elasticsearch.override.yml

    ...

    +22/-11 
    api.jsx
    ...                                                                                                           

    frontend/src/utils/api.jsx

    ...

    +5/-5     
    SaveAsPlaybooksForm.jsx
    ...                                                                                                           

    frontend/src/components/jobs/result/bar/SaveAsPlaybooksForm.jsx

    ...

    +17/-3   
    ci.override.yml
    ...                                                                                                           

    docker/ci.override.yml

    ...

    +9/-8     
    create_elastic_certs
    ...                                                                                                           

    create_elastic_certs

    ...

    +20/-0   
    Dockerfile
    ...                                                                                                           

    integrations/malware_tools_analyzers/Dockerfile

    ...

    +4/-4     
    OrgConfig.jsx
    ...                                                                                                           

    frontend/src/components/organization/OrgConfig.jsx

    ...

    +5/-5     
    jobTableColumns.jsx
    ...                                                                                                           

    frontend/src/components/jobs/table/jobTableColumns.jsx

    ...

    +11/-7   
    pull_request_automation.yml
    ...                                                                                                           

    .github/workflows/pull_request_automation.yml

    ...

    +6/-4     
    investigationTableColumns.jsx
    ...                                                                                                           

    frontend/src/components/investigations/table/investigationTableColumns.jsx

    ...

    +15/-6   
    plugin_report.json
    ...                                                                                                           

    configuration/elastic_search_mappings/plugin_report.json

    ...

    +45/-0   
    jobApi.jsx
    ...                                                                                                           

    frontend/src/components/jobs/result/jobApi.jsx

    ...

    +27/-0   
    compose.yml
    ...                                                                                                           

    integrations/phoneinfoga/compose.yml

    ...

    +13/-13 
    UserMenu.jsx
    ...                                                                                                           

    frontend/src/layouts/widgets/UserMenu.jsx

    ...

    +1/-5     
    ScanForm.advanced.test.jsx
    ...                                                                                                           

    frontend/tests/components/scan/ScanForm/ScanForm.advanced.test.jsx

    ...

    +16/-0   
    useOrganizationStore.jsx
    ...                                                                                                           

    frontend/src/stores/useOrganizationStore.jsx

    ...

    +3/-3     
    MyOrgPage.jsx
    ...                                                                                                           

    frontend/src/components/organization/MyOrgPage.jsx

    ...

    +4/-4     
    README.md
    ...                                                                                                           

    frontend/README.md

    ...

    +1/-1     
    CustomJobNode.jsx
    ...                                                                                                           

    frontend/src/components/investigations/flow/CustomJobNode.jsx

    ...

    +5/-2     
    scanApi.jsx
    ...                                                                                                           

    frontend/src/components/scan/scanApi.jsx

    ...

    +6/-2     
    default.yml
    ...                                                                                                           

    docker/default.yml

    ...

    +3/-1     
    start
    ...                                                                                                           

    start

    ...

    +2/-1     
    postgres.override.yml
    ...                                                                                                           

    docker/postgres.override.yml

    ...

    +4/-1     
    notifications.jsx
    ...                                                                                                           

    frontend/src/components/jobs/notifications.jsx

    ...

    +4/-7     
    SECURITY.md
    ...                                                                                                           

    .github/SECURITY.md

    ...

    +4/-5     
    release_template.md
    ...                                                                                                           

    .github/release_template.md

    ...

    +1/-2     
    PluginWrapper.jsx
    ...                                                                                                           

    frontend/src/components/plugins/types/PluginWrapper.jsx

    ...

    +3/-3     
    GuideWrapper.jsx
    ...                                                                                                           

    frontend/src/components/GuideWrapper.jsx

    ...

    +2/-2     
    traefik_local.yml
    ...                                                                                                           

    docker/traefik_local.yml

    ...

    +5/-5     
    TokenPage.jsx
    ...                                                                                                           

    frontend/src/components/user/token/TokenPage.jsx

    ...

    +2/-2     
    TokenAccess.jsx
    ...                                                                                                           

    frontend/src/components/user/token/TokenAccess.jsx

    ...

    +2/-3     
    .env
    ...                                                                                                           

    docker/.env

    ...

    +1/-1     
    compose.yml
    ...                                                                                                           

    integrations/cyberchef/compose.yml

    ...

    +2/-2     
    issue_template.md
    ...                                                                                                           

    .github/ISSUE_TEMPLATE/issue_template.md

    ...

    +4/-4     
    new_connector.md
    ...                                                                                                           

    .github/ISSUE_TEMPLATE/new_connector.md

    ...

    +4/-2     
    env_file_app_template
    ...                                                                                                           

    docker/env_file_app_template

    ...

    +1/-0     
    new_analyzer.md
    ...                                                                                                           

    .github/ISSUE_TEMPLATE/new_analyzer.md

    ...

    +4/-2     
    ScanForm.observable.test.jsx
    ...                                                                                                           

    frontend/tests/components/scan/ScanForm/requests/ScanForm.observable.test.jsx

    ...

    +1/-1     
    MultipleObservablesModal.jsx
    ...                                                                                                           

    frontend/src/components/scan/utils/MultipleObservablesModal.jsx

    ...

    +1/-1     
    new_ingestor.md
    ...                                                                                                           

    .github/ISSUE_TEMPLATE/new_ingestor.md

    ...

    +4/-1     
    test-requirements.txt
    ...                                                                                                           

    requirements/test-requirements.txt

    ...

    +2/-2     
    new_playbook.md
    ...                                                                                                           

    .github/ISSUE_TEMPLATE/new_playbook.md

    ...

    +7/-1     
    new_visualizer.md
    ...                                                                                                           

    .github/ISSUE_TEMPLATE/new_visualizer.md

    ...

    +5/-1     
    redis.override.yml
    ...                                                                                                           

    docker/redis.override.yml

    ...

    +1/-1     
    env_file_app_ci
    ...                                                                                                           

    docker/env_file_app_ci

    ...

    +1/-0     
    Ingestors.test.jsx
    ...                                                                                                           

    frontend/tests/components/plugins/types/Ingestors.test.jsx

    ...

    +1/-1     
    TagSelectInput.jsx
    ...                                                                                                           

    frontend/src/components/common/form/TagSelectInput.jsx

    ...

    +1/-1     
    test.multi-queue.override.yml
    ...                                                                                                           

    docker/test.multi-queue.override.yml

    ...

    +1/-1     
    threat_matrix_bi.json
    ...                                                                                                           

    configuration/elastic_search_mappings/threat_matrix_bi.json

    ...

    +3/-1     
    test.flower.override.yml
    ...                                                                                                           

    docker/test.flower.override.yml

    ...

    +1/-1     
    compose-tests.yml
    ...                                                                                                           

    integrations/malware_tools_analyzers/compose-tests.yml

    ...

    +1/-1     
    compose-tests.yml
    ...                                                                                                           

    integrations/tor_analyzers/compose-tests.yml

    ...

    +1/-1     
    compose.yml
    ...                                                                                                           

    integrations/tor_analyzers/compose.yml

    ...

    +1/-1     
    CONTRIBUTING.md
    ...                                                                                                           

    .github/CONTRIBUTING.md

    ...

    +1/-1     
    compose.yml
    ...                                                                                                           

    integrations/malware_tools_analyzers/compose.yml

    ...

    +1/-0     
    FUNDING.yml
    ...                                                                                                           

    .github/FUNDING.yml

    ...

    +1/-1     
    test.override.yml
    ...                                                                                                           

    docker/test.override.yml

    ...

    +1/-1     
    flower.override.yml
    ...                                                                                                           

    docker/flower.override.yml

    ...

    +1/-1     
    compose-tests.yml
    ...                                                                                                           

    integrations/cyberchef/compose-tests.yml

    ...

    +1/-1     
    env_file_elasticsearch_template
    ...                                                                                                           

    docker/env_file_elasticsearch_template

    ...

    +1/-0     
    elasticsearch_instances.yml
    ...                                                                                                           

    elasticsearch_instances.yml

    ...

    +2/-0     
    .prettierignore
    ...                                                                                                           

    frontend/.prettierignore

    ...

    +2/-0     

    💡 PR-Agent usage: Comment /help "your question" on any pull request to receive relevant information

    gitworkflows and others added 4 commits November 8, 2024 16:11
    Signed-off-by: NxPKG <iconmamundentist@gmail.com>
    Copy link

    sourcery-ai bot commented Nov 12, 2024

    Reviewer's Guide by Sourcery

    This PR introduces several major changes and improvements to the ThreatMatrix project, including new features for plugin management, improved documentation links, enhanced error handling, and various bug fixes. The changes span across both frontend and backend components, with significant updates to the analyzer, pivot, and playbook functionalities.

    Class diagram for VirusTotalv3BaseMixin and VirusTotalv3AnalyzerMixin

    classDiagram
        class VirusTotalv3BaseMixin {
            +str url
            +str url_sub_path
            +str _api_key_name
            +headers() dict
            +config(runtime_configuration: Dict)
            +_perform_get_request(uri: str, ignore_404: bool) Dict
            +_perform_post_request(uri: str, ignore_404: bool)
            +_perform_request(uri: str, method: str, ignore_404: bool) Dict
            +_get_relationship_for_classification(obs_clfn: str, iocs: bool) List
            +_get_requests_params_and_uri(obs_clfn: str, observable_name: str, iocs: bool) Tuple
            +_fetch_behaviour_summary(observable_name: str) Dict
            +_fetch_sigma_analyses(observable_name: str) Dict
            +_vt_download_file(file_hash: str) bytes
            +_vt_intelligence_search(query: str, limit: int, order_by: str) Dict
            +_vt_get_iocs_from_file(sample_hash: str) Dict
        }
        class VirusTotalv3AnalyzerMixin {
            +int max_tries
            +int poll_distance
            +int rescan_max_tries
            +int rescan_poll_distance
            +bool include_behaviour_summary
            +bool include_sigma_analyses
            +bool force_active_scan_if_old
            +int days_to_say_that_a_scan_is_old
            +list relationships_to_request
            +int relationships_elements
            +_get_relationship_limit(relationship: str) int
            +_vt_get_relationships(observable_name: str, relationships_requested: list, uri: str, result: dict)
            +_get_url_prefix_postfix(result: Dict) Tuple
            +_vt_scan_file(md5: str, rescan_instead: bool) Dict
            +_vt_poll_for_report(observable_name: str, params: Dict, uri: str, obs_clfn: str) Dict
            +_vt_include_behaviour_summary(result: Dict, observable_name: str) Dict
            +_vt_include_sigma_analyses(result: Dict, observable_name: str) Dict
            +_vt_get_report(obs_clfn: str, observable_name: str) Dict
        }
        VirusTotalv3AnalyzerMixin --|> VirusTotalv3BaseMixin
    
    Loading

    Class diagram for ScanForm component

    classDiagram
        class ScanForm {
            +DangerErrorMessage(fieldName)
            +selectObservableType(value)
            +updateAdvancedConfig(tags, oldClassification, newClassification)
        }
        ScanForm o-- AnalyzersMultiSelectDropdownInput
        ScanForm o-- ConnectorsMultiSelectDropdownInput
        ScanForm o-- PlaybookMultiSelectDropdownInput
        ScanForm o-- TLPSelectInput
        ScanForm o-- ScanConfigSelectInput
        ScanForm o-- usePluginConfigurationStore
        ScanForm o-- useGuideContext
        ScanForm o-- createJob
        ScanForm o-- sanitizeObservable
        ScanForm o-- SpinnerIcon
        ScanForm o-- JobTypes
        ScanForm o-- ObservableClassifications
        ScanForm o-- ScanTypes
        ScanForm o-- Loader
        ScanForm o-- MultiSelectDropdownInput
        ScanForm o-- ReactSelect
        ScanForm o-- TLPTag
        ScanForm o-- TLPColors
        ScanForm o-- TLPDescriptions
        ScanForm o-- MdInfoOutline
        ScanForm o-- UncontrolledTooltip
        ScanForm o-- FormText
        ScanForm o-- FormGroup
        ScanForm o-- Label
        ScanForm o-- Col
        ScanForm o-- Input
        ScanForm o-- Field
        ScanForm o-- Collapse
        ScanForm o-- Button
        ScanForm o-- Link
        ScanForm o-- JobTag
        ScanForm o-- markdownToHtml
    
    Loading

    File-Level Changes

    Change Details Files
    Added new plugin management features including creation, editing and deletion capabilities
    • Added new forms for creating and editing analyzers, pivots and playbooks
    • Implemented plugin deletion functionality with proper permissions handling
    • Added UI components for plugin configuration management
    • Added validation and error handling for plugin forms
    frontend/src/components/plugins/forms/AnalyzerConfigForm.jsx
    frontend/src/components/plugins/forms/PlaybookConfigForm.jsx
    frontend/src/components/plugins/forms/PivotConfigForm.jsx
    api_app/permissions.py
    api_app/pivots_manager/permissions.py
    Improved documentation links and references throughout the codebase
    • Updated all documentation links to point to new docs domain
    • Fixed broken links in templates and documentation files
    • Updated contribution guidelines and templates
    .github/CONTRIBUTING.md
    .github/pull_request_template.md
    frontend/src/constants/environment.js
    Enhanced error handling and validation across the application
    • Added better error handling for API requests
    • Improved validation for plugin configurations
    • Added proper error messages for failed operations
    frontend/src/utils/api.jsx
    api_app/exceptions.py
    api_app/analyzers_manager/observable_analyzers/basic_observable_analyzer.py
    Added new features for job management and analysis
    • Added rescan functionality for jobs
    • Improved job result visualization
    • Enhanced job history tracking
    • Added support for elastic search integration
    api_app/views.py
    frontend/src/components/jobs/result/JobActionBar.jsx
    threat_matrix/tasks.py
    docker/elasticsearch.override.yml
    Improved plugin architecture and configuration management
    • Added new basic observable analyzer class
    • Enhanced plugin configuration serialization
    • Improved plugin state management
    • Added support for plugin health checks
    api_app/analyzers_manager/observable_analyzers/basic_observable_analyzer.py
    api_app/serializers/plugin.py
    api_app/models.py

    Tips and commands

    Interacting with Sourcery

    • Trigger a new review: Comment @sourcery-ai review on the pull request.
    • Continue discussions: Reply directly to Sourcery's review comments.
    • Generate a GitHub issue from a review comment: Ask Sourcery to create an
      issue from a review comment by replying to it.
    • Generate a pull request title: Write @sourcery-ai anywhere in the pull
      request title to generate a title at any time.
    • Generate a pull request summary: Write @sourcery-ai summary anywhere in
      the pull request body to generate a PR summary at any time. You can also use
      this command to specify where the summary should be inserted.

    Customizing Your Experience

    Access your dashboard to:

    • Enable or disable review features such as the Sourcery-generated pull request
      summary, the reviewer's guide, and others.
    • Change the review language.
    • Add, remove or edit custom review instructions.
    • Adjust other review settings.

    Getting Help

    Copy link

    gitguardian bot commented Nov 12, 2024

    ⚠️ GitGuardian has uncovered 1 secret following the scan of your pull request.

    Please consider investigating the findings and remediating the incidents. Failure to do so may lead to compromising the associated services or software components.

    🔎 Detected hardcoded secret in your pull request
    GitGuardian id GitGuardian status Secret Commit Filename
    13180230 Triggered Username Password 6ca0a96 tests/auth/test_auth.py View secret
    🛠 Guidelines to remediate hardcoded secrets
    1. Understand the implications of revoking this secret by investigating where it is used in your code.
    2. Replace and store your secret safely. Learn here the best practices.
    3. Revoke and rotate this secret.
    4. If possible, rewrite git history. Rewriting git history is not a trivial act. You might completely break other contributing developers' workflow and you risk accidentally deleting legitimate data.

    To avoid such incidents in the future consider


    🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request.

    Copy link

    coderabbitai bot commented Nov 12, 2024

    Important

    Review skipped

    More than 25% of the files skipped due to max files limit. The review is being skipped to prevent a low-quality review.

    152 files out of 292 files are above the max files limit of 75. Please upgrade to Pro plan to get higher limits.

    You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


    Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

    ❤️ Share
    🪧 Tips

    Chat

    There are 3 ways to chat with CodeRabbit:

    • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
      • I pushed a fix in commit <commit_id>, please review it.
      • Generate unit testing code for this file.
      • Open a follow-up GitHub issue for this discussion.
    • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
      • @coderabbitai generate unit testing code for this file.
      • @coderabbitai modularize this function.
    • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
      • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
      • @coderabbitai read src/utils.ts and generate unit testing code.
      • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
      • @coderabbitai help me debug CodeRabbit configuration file.

    Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

    CodeRabbit Commands (Invoked using PR comments)

    • @coderabbitai pause to pause the reviews on a PR.
    • @coderabbitai resume to resume the paused reviews.
    • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
    • @coderabbitai full review to do a full review from scratch and review all the files again.
    • @coderabbitai summary to regenerate the summary of the PR.
    • @coderabbitai generate docstrings to generate docstrings for this PR. (Experiment)
    • @coderabbitai resolve resolve all the CodeRabbit review comments.
    • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
    • @coderabbitai help to get help.

    Other keywords and placeholders

    • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
    • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
    • Add @coderabbitai anywhere in the PR title to generate the title automatically.

    CodeRabbit Configuration File (.coderabbit.yaml)

    • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
    • Please see the configuration documentation for more information.
    • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

    Documentation and Community

    • Visit our Documentation for detailed information on how to use CodeRabbit.
    • Join our Discord Community to get help, request features, and share feedback.
    • Follow us on X/Twitter for updates and announcements.

    Copy link

    deepsource-io bot commented Nov 12, 2024

    Here's the code health analysis summary for commits d7f231f..66983d2. View details on DeepSource ↗.

    Analysis Summary

    AnalyzerStatusSummaryLink
    DeepSource Python LogoPython❌ Failure
    ❗ 387 occurences introduced
    🎯 147 occurences resolved
    View Check ↗
    DeepSource Docker LogoDocker❌ Failure
    ❗ 19 occurences introduced
    🎯 9 occurences resolved
    View Check ↗

    💡 If you’re a repository administrator, you can configure the quality gates from the settings.

    Copy link

    @sourcery-ai sourcery-ai bot left a comment

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    Hey @NxPKG - I've reviewed your changes - here's some feedback:

    Overall Comments:

    • Please expand the PR description to better explain the motivation and impact of these changes, particularly around the new elastic search integration and plugin management features.
    • Consider adding more documentation around the elastic search functionality given its complexity and importance for the system.
    Here's what I looked at during the review
    • 🟡 General issues: 5 issues found
    • 🟢 Security: all looks good
    • 🟡 Testing: 8 issues found
    • 🟡 Complexity: 4 issues found
    • 🟢 Documentation: all looks good

    Sourcery is free for open source - if you like our reviews please consider sharing them ✨
    Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

    logger.debug(f"text: {response.text}")
    result = response.json()
    # https://developers.virustotal.com/reference/errors
    error = result.get("error", {})
    Copy link

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    suggestion: Consider enhancing error handling to provide more context about the specific VT API error

    The error object from VT API contains additional fields like code and message that could be included in the error message to help with debugging.

    Suggested change
    error = result.get("error", {})
    error = result.get("error", {})
    error_code = error.get("code", "unknown")
    error_message = error.get("message", "no message")
    error_context = f"VT API Error - Code: {error_code}, Message: {error_message}"

    if "IOC.json" in report and isinstance(report["IOC.json"], List):
    for ioc in report["IOC.json"]:
    try:
    if "url" in ioc["type"].lower():
    Copy link

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    suggestion: Add explicit error handling for malformed IOC data structure

    The IOC parsing could fail if 'type' is missing. Consider adding validation of the IOC structure before accessing fields.

    Suggested change
    if "url" in ioc["type"].lower():
    if "type" in ioc and "url" in ioc["type"].lower():

    )
    pdns_reports.append(pdns_report)
    if "rrdata" in report.keys():
    pdns_report = PDNSReport(
    Copy link

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    suggestion (bug_risk): Consider creating PDNSReport objects only after validating all required fields

    Validate all required fields before object creation to avoid creating partial objects that may need to be discarded.

    Suggested change
    pdns_report = PDNSReport(
    required_fields = ["rrdata", "time_last"]
    if all(field in report for field in required_fields):
    pdns_report = PDNSReport(

    Comment on lines +78 to +87
    const formik = useFormik({
    initialValues: {
    name: pivotConfig?.name || "",
    description: pivotConfig?.description || "<generated automatically>",
    python_module:
    {
    value: pivotConfig?.python_module,
    label:
    pythonModuleOptions.find(
    (element) => element.value === pivotConfig?.python_module,
    Copy link

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    issue: Consider handling edge cases in form initialization

    The form initialization doesn't handle cases where pivotConfig contains unexpected or malformed data. Consider adding validation and fallback values.

    errors.name = "This field is required.";
    } else if (values.name.length < minLength) {
    errors.name = `This field must be at least ${minLength} characters long`;
    }
    Copy link

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    suggestion (bug_risk): Add type validation for payload construction

    The payload construction assumes all required fields will be present and correctly typed. Consider adding type validation to prevent runtime errors.

    const onSubmit = React.useCallback(
      async (values: FormValues, formik) => {
        if (!values?.name || !values?.description) {
          throw new Error('Required fields are missing');
        }
        const payloadData = {
          name: values.name,
          description: values.description,

    : "Edit playbook config"
    }
    onClick={() => {
    if (!pluginsLoading) setShowModal(true);
    Copy link

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    suggestion (code-quality): Use block braces for ifs, whiles, etc. (use-braces)

    Suggested change
    if (!pluginsLoading) setShowModal(true);
    if (!pluginsLoading) {


    ExplanationIt is recommended to always use braces and create explicit statement blocks.

    Using the allowed syntax to just write a single statement can lead to very confusing
    situations, especially where subsequently a developer might add another statement
    while forgetting to add the braces (meaning that this wouldn't be included in the condition).

    Comment on lines +27 to 30
    if (validationValue.classification !== "generic")
    observables[validationValue.classification].push(
    validationValue.observable,
    );
    Copy link

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    suggestion (code-quality): Use block braces for ifs, whiles, etc. (use-braces)

    Suggested change
    if (validationValue.classification !== "generic")
    observables[validationValue.classification].push(
    validationValue.observable,
    );
    if (validationValue.classification !== "generic") {
    observables[validationValue.classification].push(
    validationValue.observable,
    );
    }


    ExplanationIt is recommended to always use braces and create explicit statement blocks.

    Using the allowed syntax to just write a single statement can lead to very confusing
    situations, especially where subsequently a developer might add another statement
    while forgetting to add the braces (meaning that this wouldn't be included in the condition).

    // remove domain if stringEnd is a number
    if (!Number.isNaN(parseInt(stringEnd, 10))) return null;
    if (!Number.isNaN(parseInt(stringEnd, 10))) return defaultValue;
    Copy link

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    suggestion (code-quality): Use block braces for ifs, whiles, etc. (use-braces)

    Suggested change
    if (!Number.isNaN(parseInt(stringEnd, 10))) return defaultValue;
    if (!Number.isNaN(parseInt(stringEnd, 10))) {


    ExplanationIt is recommended to always use braces and create explicit statement blocks.

    Using the allowed syntax to just write a single statement can lead to very confusing
    situations, especially where subsequently a developer might add another statement
    while forgetting to add the braces (meaning that this wouldn't be included in the condition).

    Comment on lines 77 to +78
    if (!Object.values(hashTypesLength).includes(sanitizedString.length))
    return null;
    return defaultValue;
    Copy link

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    suggestion (code-quality): Use block braces for ifs, whiles, etc. (use-braces)

    Suggested change
    if (!Object.values(hashTypesLength).includes(sanitizedString.length))
    return null;
    return defaultValue;
    if (!Object.values(hashTypesLength).includes(sanitizedString.length)) {
    return defaultValue;
    }


    ExplanationIt is recommended to always use braces and create explicit statement blocks.

    Using the allowed syntax to just write a single statement can lead to very confusing
    situations, especially where subsequently a developer might add another statement
    while forgetting to add the braces (meaning that this wouldn't be included in the condition).

    Comment on lines +81 to +85
    if (["phone", "date"].includes(stringClassification))
    return {
    classification: ObservableClassifications.GENERIC,
    observable: sanitizedString,
    };
    Copy link

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    suggestion (code-quality): Use block braces for ifs, whiles, etc. (use-braces)

    Suggested change
    if (["phone", "date"].includes(stringClassification))
    return {
    classification: ObservableClassifications.GENERIC,
    observable: sanitizedString,
    };
    if (["phone", "date"].includes(stringClassification)) {
    return {
    classification: ObservableClassifications.GENERIC,
    observable: sanitizedString,
    };
    }


    ExplanationIt is recommended to always use braces and create explicit statement blocks.

    Using the allowed syntax to just write a single statement can lead to very confusing
    situations, especially where subsequently a developer might add another statement
    while forgetting to add the braces (meaning that this wouldn't be included in the condition).

    Copy link
    Contributor

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    ⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
    🧪 PR contains tests
    🔒 Security concerns

    Sensitive information exposure:
    The code logs potentially sensitive information in debug mode, including request URLs and response text (api_app/mixins.py line 121-122). Consider removing or masking sensitive data in logs.

    ⚡ Recommended focus areas for review

    Error Handling
    The error handling in _perform_request() could be improved. Currently it catches all exceptions and wraps them in AnalyzerRunException, but may want to handle specific exceptions differently.

    Security Risk
    The analyze_macro_results loop excludes 'Hex String' and 'Base64 String' types but does not validate the content of other types. Consider additional validation of macro content.

    Error Handling
    The extract_urls_from_IOCs() method creates a new VBA parser but does not properly handle exceptions that may occur during parsing.

    Copy link
    Contributor

    codiumai-pr-agent-free bot commented Nov 12, 2024

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Score
    Best practice
    Add request timeout to prevent hanging on slow network responses

    Add a timeout parameter to the requests.get() and requests.post() calls to prevent
    hanging on slow responses. A reasonable timeout value like 30 seconds should be
    used.

    api_app/mixins.py [116-119]

     if method == "GET":
    -    response = requests.get(url, headers=self.headers, **kwargs)
    +    response = requests.get(url, headers=self.headers, timeout=30, **kwargs)
     elif method == "POST":
    -    response = requests.post(url, headers=self.headers, **kwargs)
    +    response = requests.post(url, headers=self.headers, timeout=30, **kwargs)
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    Why: Adding timeouts to HTTP requests is a critical security and reliability practice to prevent request hanging and potential DoS vulnerabilities. The suggestion addresses a real operational concern.

    8
    Add error handling around external API calls to handle failures gracefully

    Add error handling around the VT API calls to gracefully handle rate limits, network
    errors and other potential API failures. Catch specific exceptions and log
    appropriate error messages.

    api_app/ingestors_manager/ingestors/virus_total.py [32-33]

    -data = self._vt_intelligence_search(self.query, 300, "").get("data", {})
    -logger.info(f"Retrieved {len(data)} items from the query")
    +try:
    +    data = self._vt_intelligence_search(self.query, 300, "").get("data", {})
    +    logger.info(f"Retrieved {len(data)} items from the query")
    +except Exception as e:
    +    logger.error(f"Error querying VT API: {str(e)}")
    +    return []
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    Why: Adding proper error handling for the VT API calls is critical for production reliability. The suggestion helps prevent crashes and provides better logging for troubleshooting.

    8
    Use context manager to properly close file resources

    Close the zipfile object after use to prevent resource leaks by using a context
    manager (with statement).

    api_app/analyzers_manager/file_analyzers/doc_info.py [277]

     try:
    -    document = zipfile.ZipFile(self.filepath)
    +    with zipfile.ZipFile(self.filepath) as document:
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why: Using context managers for file operations is important to ensure proper resource cleanup. This prevents file handle leaks that could impact system stability.

    7
    Ensure proper cleanup of OLE file resources

    Close the OleFileIO object after use to prevent resource leaks by using a
    try/finally block or context manager.

    api_app/analyzers_manager/file_analyzers/doc_info.py [234]

    -ole = olefile.OleFileIO(self.filepath)
    -for entry in sorted(ole.listdir(storages=True)):
    +try:
    +    ole = olefile.OleFileIO(self.filepath)
    +    for entry in sorted(ole.listdir(storages=True)):
    +        # existing code
    +finally:
    +    ole.close()
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why: Properly closing OLE file resources is important to prevent resource leaks. The suggestion adds necessary cleanup code that was missing.

    7
    Possible issue
    Add error handling for Elasticsearch query failures to prevent unhandled exceptions

    Add error handling for Elasticsearch connection failures in the
    plugin_report_queries view to gracefully handle cases where Elasticsearch is
    unreachable or returns errors.

    api_app/views.py [1645-1648]

    -hits = Search(index="plugin-report-*").query(QElastic("bool", filter=filter_list))
    -serialize_response = ElasticResponseSerializer(data=hits)
    -serialize_response.is_valid(raise_exception=True)
    -response_data = serialize_response.validated_data
    +try:
    +    hits = Search(index="plugin-report-*").query(QElastic("bool", filter=filter_list))
    +    serialize_response = ElasticResponseSerializer(data=hits)
    +    serialize_response.is_valid(raise_exception=True)
    +    response_data = serialize_response.validated_data
    +except Exception as e:
    +    logger.error(f"Error querying Elasticsearch: {str(e)}")
    +    return Response({"error": "Error querying data"}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    Why: The suggestion adds critical error handling for Elasticsearch operations, preventing unhandled exceptions that could crash the application and providing proper error responses to clients.

    8
    Validate required configuration parameters before making external API calls

    Add a check to validate that the API key is not empty/None before making requests to
    avoid unnecessary API calls.

    api_app/ingestors_manager/ingestors/virus_total.py [28-31]

     def run(self) -> Iterable[Any]:
    +    if not self._api_key_name:
    +        logger.error("VT API key not configured")
    +        return []
         if "fs:" not in self.query:
             delta_hours = timezone.datetime.now() - timezone.timedelta(hours=self.hours)
             self.query = f"fs:{delta_hours.strftime('%Y-%m-%d%H:%M:%S')}+ " + self.query
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why: Early validation of the API key prevents unnecessary API calls and provides clearer error messages when configuration is missing.

    7
    Add error handling for XML parsing operations

    Add error handling around the XML parsing to catch potential XML parsing errors that
    could occur with malformed documents.

    api_app/analyzers_manager/file_analyzers/doc_info.py [284-290]

    -dxml = document.read("docProps/app.xml")
    -pages_count = int(
    -    parseString(dxml)
    -    .getElementsByTagName("Pages")[0]
    -    .childNodes[0]
    -    .nodeValue
    -)
    +try:
    +    dxml = document.read("docProps/app.xml")
    +    pages_count = int(
    +        parseString(dxml)
    +        .getElementsByTagName("Pages")[0]
    +        .childNodes[0]
    +        .nodeValue
    +    )
    +except (xml.parsers.expat.ExpatError, IndexError) as e:
    +    logger.warning(f"Failed to parse XML document properties: {e}")
    +    pages_count = 0
    • Apply this suggestion
    Suggestion importance[1-10]: 6

    Why: Adding specific XML parsing error handling improves code robustness when dealing with malformed documents. The suggestion provides better error recovery.

    6
    Performance
    Add batching to bulk indexing operations to optimize memory usage

    Add a batch size parameter to the bulk indexing operation to prevent potential
    memory issues when processing large numbers of reports.

    threat_matrix/tasks.py [482]

    -bulk(connections.get_connection(), all_report_document_list)
    +bulk(connections.get_connection(), all_report_document_list, chunk_size=500)
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why: Adding chunk_size parameter to bulk indexing is an important optimization that prevents memory issues when processing large datasets, improving reliability and performance.

    7
    Add pagination support to prevent performance issues with large result sets

    Add pagination to the plugin_report_queries endpoint to prevent potential
    performance issues when returning large result sets.

    api_app/views.py [1650-1651]

    -result = {"data": response_data}
    +page_size = elastic_request_params.page_size or 100
    +page = elastic_request_params.page or 1
    +start = (page - 1) * page_size
    +hits = hits[start:start+page_size]
    +result = {
    +    "data": response_data,
    +    "page": page,
    +    "page_size": page_size,
    +    "total": hits.count()
    +}
     return Response(result)
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why: Implementing pagination is crucial for handling large result sets efficiently, preventing performance bottlenecks and excessive memory usage on both server and client sides.

    7
    Implement result set size limits to prevent memory issues with large datasets

    Add a limit check to prevent potential memory issues when processing large result
    sets. Consider implementing pagination or a maximum result limit.

    api_app/ingestors_manager/ingestors/virus_total.py [34-35]

    -samples_hashes = [d["id"] for d in data]
    +max_samples = 1000  # Configure appropriate limit
    +samples_hashes = [d["id"] for d in data][:max_samples]
    +if len(data) > max_samples:
    +    logger.warning(f"Retrieved {len(data)} samples, processing only first {max_samples}")
     for sample_hash in samples_hashes:
    • Apply this suggestion
    Suggestion importance[1-10]: 6

    Why: Adding a limit on processed results helps prevent potential memory issues when dealing with large datasets from VT API.

    6

    💡 Need additional feedback ? start a PR chat


    except Exception as e:
    logging.exception(
    f"Error: {e}. Secret: {secret_name}"

    Check failure

    Code scanning / CodeQL

    Clear-text logging of sensitive information High

    This expression logs
    sensitive data (secret)
    as clear text.

    Copilot Autofix AI about 1 month ago

    To fix the problem, we should avoid logging sensitive information directly. Instead, we can log a generic message that does not include the sensitive secret_name. This way, we still capture the occurrence of an error without exposing sensitive data.

    • Replace the logging statements that include secret_name with more generic messages.
    • Ensure that the functionality of error logging is maintained without exposing sensitive information.
    Suggested changeset 1
    threat_matrix/secrets.py

    Autofix patch

    Autofix patch
    Run the following command in your local git repository to apply this patch
    cat << 'EOF' | git apply
    diff --git a/threat_matrix/secrets.py b/threat_matrix/secrets.py
    --- a/threat_matrix/secrets.py
    +++ b/threat_matrix/secrets.py
    @@ -85,3 +85,3 @@
                 logging.error(
    -                f"Failed retrieving of secret {secret_name}. Error: {e}."
    +                f"Failed retrieving of secret. Error: {e}."
                 )  # lgtm [py/clear-text-logging-sensitive-data]
    @@ -89,3 +89,3 @@
                 logging.error(
    -                f"Error: {e}. Secret: {secret_name}"
    +                f"Error: {e}. Failed to retrieve secret."
                 )  # lgtm [py/clear-text-logging-sensitive-data]
    @@ -93,3 +93,3 @@
                 logging.exception(
    -                f"Error: {e}. Secret: {secret_name}"
    +                f"Error: {e}. Failed to retrieve secret."
                 )  # lgtm [py/clear-text-logging-sensitive-data]
    EOF
    @@ -85,3 +85,3 @@
    logging.error(
    f"Failed retrieving of secret {secret_name}. Error: {e}."
    f"Failed retrieving of secret. Error: {e}."
    ) # lgtm [py/clear-text-logging-sensitive-data]
    @@ -89,3 +89,3 @@
    logging.error(
    f"Error: {e}. Secret: {secret_name}"
    f"Error: {e}. Failed to retrieve secret."
    ) # lgtm [py/clear-text-logging-sensitive-data]
    @@ -93,3 +93,3 @@
    logging.exception(
    f"Error: {e}. Secret: {secret_name}"
    f"Error: {e}. Failed to retrieve secret."
    ) # lgtm [py/clear-text-logging-sensitive-data]
    Copilot is powered by AI and may make mistakes. Always verify output.
    Positive Feedback
    Negative Feedback

    Provide additional feedback

    Please help us improve GitHub Copilot by sharing more details about this comment.

    Please select one or more of the options
    NxPKG and others added 15 commits November 12, 2024 13:54
    Signed-off-by: NxPKG <iconmamundentist@gmail.com>
    Signed-off-by: NxPKG <iconmamundentist@gmail.com>
    Signed-off-by: NxPKG <iconmamundentist@gmail.com>
    Signed-off-by: NxPKG <iconmamundentist@gmail.com>
    Signed-off-by: NxPKG <iconmamundentist@gmail.com>
    Signed-off-by: NxPKG <iconmamundentist@gmail.com>
    Signed-off-by: NxPKG <iconmamundentist@gmail.com>
    Signed-off-by: NxPKG <iconmamundentist@gmail.com>
    Signed-off-by: NxPKG <iconmamundentist@gmail.com>
    Signed-off-by: NxPKG <iconmamundentist@gmail.com>
    Signed-off-by: NxPKG <iconmamundentist@gmail.com>
    Signed-off-by: NxPKG <iconmamundentist@gmail.com>
    Signed-off-by: NxPKG <iconmamundentist@gmail.com>
    Copy link
    Contributor

    codiumai-pr-agent-free bot commented Nov 29, 2024

    CI Failure Feedback 🧐

    (Checks updated until commit 66983d2)

    Action: dependency-review

    Failed stage: Dependency Review [❌]

    Failed test name: ""

    Failure summary:

    The action failed due to the detection of vulnerable packages in the dependency review:

  • Django@4.2.16 has a high severity SQL injection vulnerability in HasKey(lhs, rhs) on Oracle.
  • Django@4.2.16 has a moderate severity denial-of-service vulnerability in
    django.utils.html.strip_tags().
    These vulnerabilities were identified in the
    requirements/project-requirements.txt file.

  • Relevant error logs:
    1:  ##[group]Operating System
    2:  Ubuntu
    ...
    
    100:  with:
    101:  repo-token: ***
    102:  ##[endgroup]
    103:  ##[group]Vulnerabilities
    104:  �[1mrequirements/project-requirements.txt » Django@4.2.16�[22m – Django SQL injection in HasKey(lhs, rhs) on Oracle �[31m(high severity)�[39m
    105:  ↪ https://github.com/advisories/GHSA-m9g8-fxxm-xg86
    106:  �[1mrequirements/project-requirements.txt » Django@4.2.16�[22m – Django denial-of-service in django.utils.html.strip_tags() �[33m(moderate severity)�[39m
    107:  ↪ https://github.com/advisories/GHSA-8498-2h75-472j
    108:  ##[error]Dependency review detected vulnerable packages.
    ...
    
    268:  npm/node-addon-api: OpenSSF Scorecard Score: 8.8
    269:  npm/node-releases: OpenSSF Scorecard Score: 4.1
    270:  npm/object-is: OpenSSF Scorecard Score: 4.4
    271:  npm/object.entries: OpenSSF Scorecard Score: 4.4
    272:  npm/object.fromentries: OpenSSF Scorecard Score: 4.4
    273:  npm/object.groupby: OpenSSF Scorecard Score: undefined
    274:  npm/object.values: OpenSSF Scorecard Score: 4.4
    275:  npm/prettier: OpenSSF Scorecard Score: 6.4
    276:  npm/react-error-boundary: OpenSSF Scorecard Score: 4.1
    ...
    
    306:  npm/@types/jest: OpenSSF Scorecard Score: 6.9
    307:  npm/axios: OpenSSF Scorecard Score: 5.9
    308:  npm/eslint: OpenSSF Scorecard Score: 6.9
    309:  npm/eslint-plugin-import: OpenSSF Scorecard Score: 6
    310:  npm/eslint-plugin-jsx-a11y: OpenSSF Scorecard Score: 6
    311:  npm/eslint-plugin-react: OpenSSF Scorecard Score: 5.8
    312:  npm/eslint-plugin-react-hooks: OpenSSF Scorecard Score: 5.3
    313:  npm/prettier: OpenSSF Scorecard Score: 6.4
    314:  npm/react-error-boundary: OpenSSF Scorecard Score: 4.1
    ...
    
    508:  �[32m+ node-addon-api@7.1.1�[39m
    509:  �[32m+ node-releases@2.0.18�[39m
    510:  �[32m+ object-is@1.1.5�[39m
    511:  �[32m+ object.entries@1.1.8�[39m
    512:  �[32m+ object.fromentries@2.0.8�[39m
    513:  �[32m+ object.groupby@1.0.3�[39m
    514:  �[32m+ object.values@1.2.0�[39m
    515:  �[32m+ prettier@3.3.3�[39m
    516:  �[32m+ react-error-boundary@4.1.0�[39m
    ...
    
    685:  �[31m- node-releases@2.0.14�[39m
    686:  �[31m- object-is@1.1.5�[39m
    687:  �[31m- object.entries@1.1.7�[39m
    688:  �[31m- object.fromentries@2.0.7�[39m
    689:  �[31m- object.groupby@1.0.1�[39m
    690:  �[31m- object.hasown@1.1.4�[39m
    691:  �[31m- object.values@1.1.7�[39m
    692:  �[31m- prettier@3.2.5�[39m
    693:  �[31m- react-error-boundary@4.0.13�[39m
    ...
    
    716:  �[32m+ @types/jest@^29.5.14�[39m
    717:  �[32m+ axios@^1.7.7�[39m
    718:  �[32m+ eslint@^8.57.1�[39m
    719:  �[32m+ eslint-plugin-import@^2.31.0�[39m
    720:  �[32m+ eslint-plugin-jsx-a11y@^6.10.0�[39m
    721:  �[32m+ eslint-plugin-react@^7.37.1�[39m
    722:  �[32m+ eslint-plugin-react-hooks@^4.6.2�[39m
    723:  �[32m+ prettier@^3.3.3�[39m
    724:  �[32m+ react-error-boundary@^4.1.0�[39m
    ...
    
    736:  �[31m- @testing-library/jest-dom@^6.4.2�[39m
    737:  �[31m- axios@^1.7.4�[39m
    738:  �[31m- eslint@^8.48.0�[39m
    739:  �[31m- eslint-plugin-import@^2.29.1�[39m
    740:  �[31m- eslint-plugin-jsx-a11y@^6.8.0�[39m
    741:  �[31m- eslint-plugin-react@^7.34.1�[39m
    742:  �[31m- eslint-plugin-react-hooks@^4.5.0�[39m
    743:  �[31m- prettier@^3.2.5�[39m
    744:  �[31m- react-error-boundary@^4.0.13�[39m
    

    ✨ CI feedback usage guide:

    The CI feedback tool (/checks) automatically triggers when a PR has a failed check.
    The tool analyzes the failed checks and provides several feedbacks:

    • Failed stage
    • Failed test name
    • Failure summary
    • Relevant error logs

    In addition to being automatically triggered, the tool can also be invoked manually by commenting on a PR:

    /checks "https://github.com/{repo_name}/actions/runs/{run_number}/job/{job_number}"
    

    where {repo_name} is the name of the repository, {run_number} is the run number of the failed check, and {job_number} is the job number of the failed check.

    Configuration options

    • enable_auto_checks_feedback - if set to true, the tool will automatically provide feedback when a check is failed. Default is true.
    • excluded_checks_list - a list of checks to exclude from the feedback, for example: ["check1", "check2"]. Default is an empty list.
    • enable_help_text - if set to true, the tool will provide a help message with the feedback. Default is true.
    • persistent_comment - if set to true, the tool will overwrite a previous checks comment with the new feedback. Default is true.
    • final_update_message - if persistent_comment is true and updating a previous checks message, the tool will also create a new message: "Persistent checks updated to latest commit". Default is true.

    See more information about the checks tool in the docs.

    * Update compose-tests.yml
    
    Signed-off-by: NxPKG <iconmamundentist@gmail.com>
    
    * Update compose.yml
    
    Signed-off-by: NxPKG <iconmamundentist@gmail.com>
    
    * Update compose-tests.yml
    
    Signed-off-by: NxPKG <iconmamundentist@gmail.com>
    
    * Update compose.yml
    
    Signed-off-by: NxPKG <iconmamundentist@gmail.com>
    
    * Update compose-tests.yml
    
    Signed-off-by: NxPKG <iconmamundentist@gmail.com>
    
    * Update compose.yml
    
    Signed-off-by: NxPKG <iconmamundentist@gmail.com>
    
    * Update compose.yml
    
    Signed-off-by: NxPKG <iconmamundentist@gmail.com>
    
    * Update compose-tests.yml
    
    Signed-off-by: NxPKG <iconmamundentist@gmail.com>
    
    * Update compose.yml
    
    Signed-off-by: NxPKG <iconmamundentist@gmail.com>
    
    ---------
    
    Signed-off-by: NxPKG <iconmamundentist@gmail.com>
    * fixed dashboard backend unittest
    
    * black format
    
    * fix isort
    
    * prettier:write fix
    
    * Update test_auth.py
    
    Signed-off-by: gitworkflows <118260833+gitworkflows@users.noreply.github.com>
    
    ---------
    
    Signed-off-by: gitworkflows <118260833+gitworkflows@users.noreply.github.com>
    upper_case=True,
    lower_case=True,
    )
    logger.info(f"Generated fake password input {self.FAKE_PASSWORD_INPUT}")

    Check failure

    Code scanning / CodeQL

    Clear-text logging of sensitive information High

    This expression logs
    sensitive data (password)
    as clear text.

    Copilot Autofix AI 8 days ago

    To fix the problem, we should avoid logging sensitive information such as passwords, even if they are fake. Instead, we can log a generic message indicating that the fake password input has been generated without including the actual value. This approach maintains the functionality of the code while ensuring that sensitive information is not exposed in the logs.

    • Update the logging statements to avoid including sensitive information.
    • Specifically, change the logging statement on line 95 to a more generic message.
    • Ensure that similar changes are made to other logging statements that include sensitive information.
    Suggested changeset 1
    api_app/analyzers_manager/file_analyzers/phishing/phishing_form_compiler.py

    Autofix patch

    Autofix patch
    Run the following command in your local git repository to apply this patch
    cat << 'EOF' | git apply
    diff --git a/api_app/analyzers_manager/file_analyzers/phishing/phishing_form_compiler.py b/api_app/analyzers_manager/file_analyzers/phishing/phishing_form_compiler.py
    --- a/api_app/analyzers_manager/file_analyzers/phishing/phishing_form_compiler.py
    +++ b/api_app/analyzers_manager/file_analyzers/phishing/phishing_form_compiler.py
    @@ -82,7 +82,5 @@
             }
    -        logger.info(
    -            f"Generated name text input mapping {self._name_text_input_mapping}"
    -        )
    +        logger.info("Generated name text input mapping.")
             self.FAKE_EMAIL_INPUT: str = fake.email()
    -        logger.info(f"Generated fake email input {self.FAKE_EMAIL_INPUT}")
    +        logger.info("Generated fake email input.")
             self.FAKE_PASSWORD_INPUT: str = fake.password(
    @@ -94,5 +92,5 @@
             )
    -        logger.info(f"Generated fake password input {self.FAKE_PASSWORD_INPUT}")
    +        logger.info("Generated fake password input.")
             self.FAKE_TEL_INPUT: str = fake.phone_number()
    -        logger.info(f"Generated fake tel input {self.FAKE_TEL_INPUT}")
    +        logger.info("Generated fake tel input.")
     
    EOF
    @@ -82,7 +82,5 @@
    }
    logger.info(
    f"Generated name text input mapping {self._name_text_input_mapping}"
    )
    logger.info("Generated name text input mapping.")
    self.FAKE_EMAIL_INPUT: str = fake.email()
    logger.info(f"Generated fake email input {self.FAKE_EMAIL_INPUT}")
    logger.info("Generated fake email input.")
    self.FAKE_PASSWORD_INPUT: str = fake.password(
    @@ -94,5 +92,5 @@
    )
    logger.info(f"Generated fake password input {self.FAKE_PASSWORD_INPUT}")
    logger.info("Generated fake password input.")
    self.FAKE_TEL_INPUT: str = fake.phone_number()
    logger.info(f"Generated fake tel input {self.FAKE_TEL_INPUT}")
    logger.info("Generated fake tel input.")

    Copilot is powered by AI and may make mistakes. Always verify output.
    Positive Feedback
    Negative Feedback

    Provide additional feedback

    Please help us improve GitHub Copilot by sharing more details about this comment.

    Please select one or more of the options
    )

    logger.info(
    f"Job #{self.job_id}: Sending value {value_to_set} for {input_name=}"

    Check failure

    Code scanning / CodeQL

    Clear-text logging of sensitive information High

    This expression logs
    sensitive data (password)
    as clear text.

    Copilot Autofix AI 8 days ago

    To fix the problem, we should avoid logging sensitive information such as passwords, emails, and telephone numbers. Instead, we can log a generic message indicating that a value has been set without including the actual value. This way, we maintain the logging functionality for debugging purposes without exposing sensitive information.

    • Replace the logging statement on line 169 to avoid logging the actual value of value_to_set.
    • Replace the logging statement on line 176 to avoid logging the actual parameters being sent.
    Suggested changeset 1
    api_app/analyzers_manager/file_analyzers/phishing/phishing_form_compiler.py

    Autofix patch

    Autofix patch
    Run the following command in your local git repository to apply this patch
    cat << 'EOF' | git apply
    diff --git a/api_app/analyzers_manager/file_analyzers/phishing/phishing_form_compiler.py b/api_app/analyzers_manager/file_analyzers/phishing/phishing_form_compiler.py
    --- a/api_app/analyzers_manager/file_analyzers/phishing/phishing_form_compiler.py
    +++ b/api_app/analyzers_manager/file_analyzers/phishing/phishing_form_compiler.py
    @@ -168,3 +168,3 @@
                 logger.info(
    -                f"Job #{self.job_id}: Sending value {value_to_set} for {input_name=}"
    +                f"Job #{self.job_id}: Sending value for {input_name=}"
                 )
    @@ -175,3 +175,3 @@
             params, dest_url = self.compile_form_field(form)
    -        logger.info(f"Job #{self.job_id}: Sending {params=} to submit url {dest_url}")
    +        logger.info(f"Job #{self.job_id}: Submitting form to url {dest_url}")
             return requests.post(
    EOF
    @@ -168,3 +168,3 @@
    logger.info(
    f"Job #{self.job_id}: Sending value {value_to_set} for {input_name=}"
    f"Job #{self.job_id}: Sending value for {input_name=}"
    )
    @@ -175,3 +175,3 @@
    params, dest_url = self.compile_form_field(form)
    logger.info(f"Job #{self.job_id}: Sending {params=} to submit url {dest_url}")
    logger.info(f"Job #{self.job_id}: Submitting form to url {dest_url}")
    return requests.post(
    Copilot is powered by AI and may make mistakes. Always verify output.
    Positive Feedback
    Negative Feedback

    Provide additional feedback

    Please help us improve GitHub Copilot by sharing more details about this comment.

    Please select one or more of the options
    @gitworkflows
    Copy link
    Contributor

    Snyk checks have failed. 7 issues have been found so far.

    Icon Severity Issues
    Critical 1
    High 6
    Medium 0
    Low 0

    security/snyk check is complete. 7 issues have been found. (View Details)

    @gitworkflows gitworkflows deleted the develop branch December 10, 2024 06:16
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Projects
    None yet
    Development

    Successfully merging this pull request may close these issues.

    2 participants