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

Elastic #171

Closed
wants to merge 22 commits into from
Closed

Elastic #171

wants to merge 22 commits into from

Conversation

gitworkflows
Copy link
Contributor

@gitworkflows gitworkflows 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


Description

  • Introduced multiple enhancements including new analyzers, ingestors, and serializers for improved functionality.
  • Added extensive tests for new and existing components to ensure reliability and performance.
  • Implemented configuration changes across various modules, including migrations and settings adjustments.
  • Improved documentation with changelog formatting and content updates.
  • Enhanced code formatting for consistency and readability across multiple files.

Changes walkthrough 📝

Relevant files
Enhancement
62 files
mixins.py
Introduced VirusTotal API interaction mixins for analyzers

api_app/mixins.py

  • Added VirusTotalv3BaseMixin and VirusTotalv3AnalyzerMixin classes for
    interacting with VirusTotal API.
  • Implemented methods for performing GET and POST requests to VirusTotal
    API.
  • Added functionality to handle VirusTotal API responses and errors.
  • Introduced methods to extract relationships and scan results from
    VirusTotal.
  • +585/-0 
    virus_total.py
    Implemented VirusTotal ingestor for intelligence search and IOCs
    extraction

    api_app/ingestors_manager/ingestors/virus_total.py

  • Added VirusTotal class inheriting from Ingestor and
    VirusTotalv3BaseMixin.
  • Implemented run method to perform intelligence search and extract IOCs
    or download files.
  • Added mock responses for testing purposes.
  • +316/-0 
    doc_info.py
    Enhanced document analysis with URL extraction and macro analysis

    api_app/analyzers_manager/file_analyzers/doc_info.py

  • Enhanced DocInfo class to extract URLs and analyze macros.
  • Added methods to extract external relationships and document URLs.
  • Improved error handling and logging.
  • +169/-27
    vt3_intelligence_search.py
    Refactored VirusTotal intelligence search analyzer with mixin

    api_app/analyzers_manager/observable_analyzers/vt/vt3_intelligence_search.py

  • Refactored VirusTotalv3Intelligence class to use
    VirusTotalv3AnalyzerMixin.
  • Simplified run method to utilize mixin's intelligence search.
  • Updated mock responses for testing.
  • +152/-31
    nvd_cve.py
    Implemented NVDDetails analyzer for CVE data retrieval     

    api_app/analyzers_manager/observable_analyzers/nvd_cve.py

  • Implemented NVDDetails class for fetching CVE details from NVD API.
  • Added CVE format validation and API request handling.
  • Included mock responses for testing.
  • +133/-0 
    serializers.py
    Updated serializers for ingestor configuration and report

    api_app/ingestors_manager/serializers.py

  • Updated IngestorConfigSerializerForMigration to exclude specific
    fields.
  • Modified IngestorReportBISerializer to include additional fields.
  • +19/-2   
    0121_analyzer_config_lnk_info.py
    Add migration for Lnk_Info analyzer configuration.             

    api_app/analyzers_manager/migrations/0121_analyzer_config_lnk_info.py

  • Added a new migration file for AnalyzerConfig related to Lnk_Info.
  • Defined a plugin configuration for Lnk_Info.
  • Implemented migration and reverse migration functions.
  • +120/-0 
    basic_observable_analyzer.py
    Implement BasicObservableAnalyzer for observable analysis.

    api_app/analyzers_manager/observable_analyzers/basic_observable_analyzer.py

  • Introduced BasicObservableAnalyzer class for analyzing observables.
  • Implemented methods for running and updating the analyzer.
  • Added support for HTTP requests with optional authentication and
    certificate verification.
  • +105/-0 
    serializers.py
    Enhance PivotConfigSerializer with related configurations.

    api_app/pivots_manager/serializers.py

  • Updated PivotConfigSerializer to include related analyzer and
    connector configurations.
  • Added validation for related configurations.
  • Implemented create and update methods for plugin configuration.
  • +68/-3   
    strings_info.py
    Enhance StringsInfo analyzer with URL extraction.               

    api_app/analyzers_manager/file_analyzers/strings_info.py

  • Added URL extraction from strings in specific file types.
  • Implemented the update method.
  • Disabled mockup connections for the class.
  • +49/-0   
    boxjs_scan.py
    Enhance BoxJS analyzer with logging and URL extraction.   

    api_app/analyzers_manager/file_analyzers/boxjs_scan.py

  • Added logging and URL extraction to BoxJS analyzer.
  • Implemented the update method.
  • Disabled mockup connections for the class.
  • +34/-1   
    0123_basic_observable_analyzer.py
    Add migration for BasicObservableAnalyzer module.               

    api_app/analyzers_manager/migrations/0123_basic_observable_analyzer.py

  • Added migration for BasicObservableAnalyzer Python module.
  • Defined parameters for the analyzer.
  • Implemented migration and reverse migration functions.
  • +87/-0   
    serializers.py
    Enhance AnalyzerConfigSerializer with plugin configuration handling.

    api_app/analyzers_manager/serializers.py

  • Updated AnalyzerConfigSerializer to handle plugin configurations.
  • Implemented create and update methods for plugin configuration.
  • +43/-0   
    views.py
    Add rescan action to job viewset.                                               

    api_app/views.py

  • Added a new rescan action for job viewset.
  • Implemented logic to create a new job based on an existing one.
  • +32/-1   
    serializers.py
    Enhance PlaybookConfigSerializer with visualizers and editable flag.

    api_app/playbooks_manager/serializers.py

  • Updated PlaybookConfigSerializer to include visualizers and make type
    field optional.
  • Renamed is_deletable to is_editable.
  • +11/-5   
    plugin.py
    Add PivotConfig type and update PythonConfigSerializer.   

    api_app/serializers/plugin.py

  • Added PivotConfig as a new plugin type.
  • Made parameters field optional in PythonConfigSerializer.
  • +5/-6     
    signals.py
    Update signal handlers for cache refresh and logging.       

    api_app/signals.py

  • Updated signal handlers to refresh cache keys for PythonConfig.
  • Added logging for LogEntry post-save signal.
  • +23/-1   
    views.py
    Enhance PivotConfigViewSet with mixins and permissions.   

    api_app/pivots_manager/views.py

  • Enhanced PivotConfigViewSet with additional mixins and permissions.
  • Implemented queryset prefetching for related configurations.
  • +36/-4   
    admin.py
    Register LogEntry model in admin with restrictions.           

    api_app/admin.py

  • Registered LogEntry model in admin with restricted permissions.
  • Configured list display and filters for LogEntry.
  • +25/-0   
    artifacts.py
    Simplify Artifacts analyzer run method.                                   

    api_app/analyzers_manager/file_analyzers/artifacts.py

  • Simplified run method by removing conditional logic.
  • Updated command arguments for artifact analysis.
  • +2/-11   
    0051_add_lnk_info_analyzer_free_to_use.py
    Add Lnk_Info analyzer to FREE_TO_USE_ANALYZERS.                   

    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.
  • Implemented migration and reverse migration functions.
  • +34/-0   
    analyzer_extractor.py
    Add check for rrdata in Robtex reports.                                   

    api_app/visualizers_manager/visualizers/passive_dns/analyzer_extractor.py

  • Added check for rrdata key in Robtex reports.
  • Prevented processing of reports without rrdata.
  • +15/-14 
    compare.py
    Simplify Compare pivot logic with get_value method.           

    api_app/pivots_manager/pivots/compare.py

  • Replaced _get_value method with get_value from related reports.
  • Simplified should_run method logic.
  • +1/-24   
    lnk_info.py
    Add LnkInfo analyzer for LNK file analysis.                           

    api_app/analyzers_manager/file_analyzers/lnk_info.py

  • Added LnkInfo analyzer for extracting URIs from LNK files.
  • Implemented parsing logic using pylnk3.
  • +37/-0   
    elastic_templates.py
    Add command for Elasticsearch index template management. 

    api_app/management/commands/elastic_templates.py

  • Added management command to create or update Elasticsearch index
    templates.
  • Implemented logic to handle Elasticsearch connection and template
    update.
  • +39/-0   
    pdf_info.py
    Enhance PDFInfo analyzer with URI extraction.                       

    api_app/analyzers_manager/file_analyzers/pdf_info.py

  • Added URI extraction to PDFInfo analyzer.
  • Updated results structure to include URIs.
  • +5/-4     
    views.py
    Enhance AnalyzerConfigViewSet with mixins and permissions.

    api_app/analyzers_manager/views.py

  • Enhanced AnalyzerConfigViewSet with additional mixins and permissions.
  • Implemented queryset for AnalyzerConfig.
  • +17/-2   
    constants.py
    Add HTTPMethods constants and update domain regex.             

    api_app/analyzers_manager/constants.py

  • Added HTTPMethods class for HTTP method constants.
  • Updated domain regex to include underscores.
  • +10/-2   
    classes.py
    Update health_check method with status code handling.       

    api_app/classes.py

  • Updated health_check method to handle specific HTTP status codes.
  • Improved logging for health check failures.
  • +8/-1     
    onenote.py
    Add OneNoteInfo analyzer for OneNote file analysis.           

    api_app/analyzers_manager/file_analyzers/onenote.py

  • Added OneNoteInfo analyzer for extracting content from OneNote files.
  • Implemented base64 encoding for non-image content.
  • +10/-0   
    0122_alter_soft_time_limit.py
    Alter 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 functions.
  • +34/-0   
    views.py
    Add debug logging and parent job handling in playbook views.

    api_app/playbooks_manager/views.py

  • Added debug logging for request data in playbook views.
  • Implemented parent job handling in analyze_multiple_files.
  • +4/-1     
    app.py
    Improve error handling in intercept_box_js_result.             

    integrations/malware_tools_analyzers/app.py

  • Improved error handling in intercept_box_js_result.
  • Added check for directory existence before processing.
  • +10/-5   
    dumpplugin.py
    Add support for reverse descriptors in dumpplugin.             

    api_app/management/commands/dumpplugin.py

  • Added support for reverse descriptors in _get_obj function.
  • Updated imports to include reverse descriptors.
  • +9/-2     
    models.py
    Add get_value method to Job model.                                             

    api_app/models.py

  • Added get_value method to Job model for retrieving report values.
  • Implemented logic to handle nested field access.
  • +18/-0   
    download_file_from_uri.py
    Change stored_base64 to list in download_file_from_uri.   

    api_app/analyzers_manager/observable_analyzers/download_file_from_uri.py

  • Changed stored_base64 to a list for multiple content storage.
  • Updated logic to append base64 encoded content.
  • +3/-3     
    any_compare.py
    Simplify AnyCompare pivot logic with get_value method.     

    api_app/pivots_manager/pivots/any_compare.py

  • Replaced _get_value method with get_value from related reports.
  • Simplified should_run method logic.
  • +10/-7   
    abuse_submitter.py
    Add exception handling for missing parent job in abuse_submitter.

    api_app/connectors_manager/connectors/abuse_submitter.py

  • Added exception handling for missing parent job.
  • Implemented logic to raise AnalyzerRunException.
  • +6/-0     
    0034_changed_resubmitdownloadedfile_playbook_to_execute.py
    Change 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 function to update playbook.
  • +25/-0   
    load_file.py
    Update get_value_to_pivot_to method for list handling.     

    api_app/pivots_manager/pivots/load_file.py

  • Updated get_value_to_pivot_to method to handle lists.
  • Implemented logic to decode base64 content from lists.
  • +11/-2   
    job.py
    Add is_sample field and fix ZIP MIME type check.                 

    api_app/serializers/job.py

  • Added is_sample field to JobSerializer.
  • Corrected MIME type check for ZIP files.
  • +2/-1     
    vt3_get.py
    Add update method to VirusTotalv3 analyzer.                           

    api_app/analyzers_manager/observable_analyzers/vt/vt3_get.py

  • Added update method to VirusTotalv3 analyzer.
  • Implemented placeholder method for future updates.
  • +5/-2     
    signals.py
    Add 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   
    classes.py
    Add logging for ingestor start and finish.                             

    api_app/ingestors_manager/classes.py

  • Added logging for start and finish of ingestor runs.
  • Implemented before_run and after_run methods.
  • +5/-0     
    models.py
    Add LNK MIME type to MimeTypes enum.                                         

    api_app/analyzers_manager/models.py

  • Added LNK MIME type to MimeTypes enum.
  • Updated _calculate_from_filename method for LNK files.
  • +1/-0     
    malware_bazaar.py
    Simplify logging in get_recent_samples method.                     

    api_app/ingestors_manager/ingestors/malware_bazaar.py

  • Simplified logging message in get_recent_samples.
  • Removed redundant string concatenation.
  • +1/-1     
    droidlysis.py
    Increase max_tries for DroidLysis analyzer.                           

    api_app/analyzers_manager/file_analyzers/droidlysis.py

  • Increased max_tries for HTTP request polling.
  • Updated configuration for DroidLysis analyzer.
  • +1/-1     
    permissions.py
    Add PivotActionsPermission for pivot actions.                       

    api_app/pivots_manager/permissions.py

  • Added PivotActionsPermission class for pivot actions.
  • Implemented permission logic for admin and superuser.
  • +10/-0   
    permissions.py
    Add isPluginActionsPermission for plugin actions.               

    api_app/permissions.py

  • Added isPluginActionsPermission class for plugin actions.
  • Implemented permission logic for admin and superuser.
  • +10/-0   
    mwdb_scan.py
    Add error handling for MWDB queries in mwdb_scan.               

    api_app/analyzers_manager/file_analyzers/mwdb_scan.py

  • Added handling for ObjectNotFoundError in run method.
  • Improved error handling for MWDB queries.
  • +1/-1     
    secrets.py
    Exclude AWS_REGION from secret retrieval in get_secret.   

    threat_matrix/secrets.py

  • Added condition to exclude AWS_REGION from secret retrieval.
  • Improved logic for AWS secrets handling.
  • +1/-1     
    tasks.py
    Simplify execute_ingestor function call.                                 

    threat_matrix/tasks.py

  • Simplified execute_ingestor function call.
  • Removed redundant parameter comments.
  • +1/-1     
    signals.py
    Use rest_framework ValidationError in signals.                     

    api_app/playbooks_manager/signals.py

  • Changed ValidationError import to use rest_framework.
  • Ensured consistent exception handling across the module.
  • +1/-1     
    observables.js
    Update observableValidators for default value handling.   

    frontend/src/utils/observables.js

  • Updated observableValidators to handle default values.
  • Ensured consistent classification for phone and date types.
  • +16/-12 
    miscConst.js
    Add HTTPMethods constant for HTTP method types.                   

    frontend/src/constants/miscConst.js

  • Added HTTPMethods constant for HTTP method types.
  • Defined HTTP methods as a frozen object.
  • +8/-0     
    pluginConst.js
    Add AllPluginSupportedTypes constant for plugin types.     

    frontend/src/constants/pluginConst.js

  • Added AllPluginSupportedTypes constant for plugin types.
  • Defined supported plugin types as a frozen object.
  • +9/-0     
    utils.js
    Add is_sample property to job node creation.                         

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

  • Added is_sample property to job node creation.
  • Updated job node structure with new property.
  • +1/-0     
    ScanForm.jsx
    Refactor ScanForm component for improved readability.       

    frontend/src/components/scan/ScanForm.jsx

  • Refactored ScanForm component for improved readability.
  • Extracted dropdown inputs into separate components.
  • Simplified observable type selection logic.
  • +82/-338
    AnalyzerConfigForm.jsx
    New Analyzer Configuration Form Component                               

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

  • Added a new React component AnalyzerConfigForm for configuring
    analyzers.
  • Implemented form validation using Formik.
  • Included JSON input handling for headers and parameters.
  • Integrated API calls for creating and editing plugin configurations.
  • +615/-0 
    PlaybookConfigForm.jsx
    New Playbook Configuration Form Component                               

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

  • Added a new React component PlaybookConfigForm for configuring
    playbooks.
  • Implemented form validation and submission logic with Formik.
  • Included multi-select dropdowns for analyzers, connectors, and
    visualizers.
  • Managed runtime configuration with JSON input.
  • +443/-0 
    PivotConfigForm.jsx
    New Pivot Configuration Form Component                                     

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

  • Added a new React component PivotConfigForm for configuring pivots.
  • Implemented form validation with Formik.
  • Included dropdowns for selecting analyzers, connectors, and playbooks.
  • Managed pivot type selection and related configurations.
  • +442/-0 
    PluginData.jsx
    Support for Ingestors in Plugin Data Component                     

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

  • Updated PluginData component to include ingestors in plugin
    configurations.
  • Added retrieval logic for ingestors configuration.
  • Adjusted refetch logic to include ingestors.
  • +12/-1   
    Configuration changes
    15 files
    0025_ingestor_config_virustotal_example_query.py
    Added migration for VirusTotal example query ingestor configuration

    api_app/ingestors_manager/migrations/0025_ingestor_config_virustotal_example_query.py

  • Added migration for VirusTotal example query ingestor configuration.
  • Defined parameters and values for the ingestor configuration.
  • Implemented migration and reverse migration functions.
  • +272/-0 
    0120_alter_analyzerconfig_not_supported_filetypes_and_more.py
    Updated AnalyzerConfig model filetype fields and choices 

    api_app/analyzers_manager/migrations/0120_alter_analyzerconfig_not_supported_filetypes_and_more.py

  • Altered AnalyzerConfig model fields for supported and not supported
    filetypes.
  • Updated choices for filetypes in the model.
  • +180/-0 
    0033_pivot_config_extractedonenotefiles.py
    Added migration for ExtractedOneNoteFiles pivot configuration

    api_app/pivots_manager/migrations/0033_pivot_config_extractedonenotefiles.py

  • Added migration for ExtractedOneNoteFiles pivot configuration.
  • Defined parameters and values for the pivot configuration.
  • Implemented migration and reverse migration functions.
  • +149/-0 
    0130_analyzer_config_nvd_cve.py
    Added migration for NVD_CVE analyzer configuration             

    api_app/analyzers_manager/migrations/0130_analyzer_config_nvd_cve.py

  • Added migration for NVD_CVE analyzer configuration.
  • Defined parameters for the NVD API key.
  • Implemented migration and reverse migration functions.
  • +136/-0 
    0052_playbook_config_uris.py
    Added migration for Uris playbook configuration                   

    api_app/playbooks_manager/migrations/0052_playbook_config_uris.py

  • Added migration for Uris playbook configuration.
  • Defined analyzers and pivots included in the playbook.
  • Implemented migration and reverse migration functions.
  • +118/-0 
    .prettierignore
    Added .prettierignore file for artifact exclusion               

    frontend/.prettierignore

    • Added .prettierignore file to ignore specific artifacts.
    +2/-0     
    __init__.py
    Add import for a_secrets module in settings.                         

    threat_matrix/settings/init.py

  • Added import for a_secrets module.
  • Ensured proper import order for settings modules.
  • +1/-0     
    a_secrets.py
    Add a_secrets module for AWS region configuration.             

    threat_matrix/settings/a_secrets.py

  • Added a_secrets module for AWS region configuration.
  • Implemented logic to retrieve AWS region from secrets.
  • +7/-0     
    mail.py
    Change AWS_REGION import to use a_secrets.                             

    threat_matrix/settings/mail.py

  • Changed import of AWS_REGION to use a_secrets.
  • Updated import path for AWS region configuration.
  • +1/-1     
    db.py
    Change AWS_REGION import to use a_secrets.                             

    threat_matrix/settings/db.py

  • Changed import of AWS_REGION to use a_secrets.
  • Updated import path for AWS region configuration.
  • +2/-1     
    celery.py
    Add task_default_priority to Celery configuration.             

    threat_matrix/celery.py

  • Added task_default_priority to Celery configuration.
  • Updated task queues with priority settings.
  • +1/-0     
    celery_ingestor.sh
    Update Celery worker arguments for AWS SQS support.           

    docker/entrypoints/celery_ingestor.sh

  • Updated Celery worker arguments for AWS SQS support.
  • Added conditional logic for queue names based on AWS SQS.
  • +9/-1     
    celery_default.sh
    Update Celery worker arguments for AWS SQS support.           

    docker/entrypoints/celery_default.sh

  • Updated Celery worker arguments for AWS SQS support.
  • Added conditional logic for queue names based on AWS SQS.
  • +10/-1   
    celery_long.sh
    Update Celery worker arguments for AWS SQS support.           

    docker/entrypoints/celery_long.sh

  • Updated Celery worker arguments for AWS SQS support.
  • Added conditional logic for queue names based on AWS SQS.
  • +8/-1     
    celery_local.sh
    Update Celery worker arguments for AWS SQS support.           

    docker/entrypoints/celery_local.sh

  • Updated Celery worker arguments for AWS SQS support.
  • Added conditional logic for queue names based on AWS SQS.
  • +7/-1     
    Tests
    19 files
    test_api.py
    Added tests for job rescan functionality and permissions 

    tests/api_app/test_api.py

  • Added tests for job rescan functionality with various configurations.
  • Implemented tests for permission checks on job rescans.
  • +211/-0 
    test_mixins.py
    Added tests for VirusTotal API mixins                                       

    tests/api_app/test_mixins.py

  • Added tests for VirusTotalv3BaseMixin and VirusTotalv3AnalyzerMixin.
  • Implemented test cases for request parameters and URI generation.
  • +191/-0 
    test_views.py
    Added tests for analyzer configuration CRUD operations     

    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 tests for creating, updating, and deleting pivot configurations.
  • Implemented permission checks for pivot operations.
  • +148/-1 
    test_doc_info.py
    Added tests for DocInfo analyzer covering multiple scenarios

    tests/api_app/analyzers_manager/file_analyzers/test_doc_info.py

  • Added tests for DocInfo analyzer focusing on Follina, macros, CVEs,
    and URLs.
  • Implemented test cases for various document analysis scenarios.
  • +112/-0 
    test_classes.py
    Update test classes for new file types and configurations.

    tests/api_app/analyzers_manager/test_classes.py

  • Added tests for handling new file types and configurations.
  • Implemented job creation and analysis methods for tests.
  • +12/-5   
    __init__.py
    Add job creation and analysis methods in tests.                   

    tests/init.py

  • Added methods for creating jobs and analyzing samples in tests.
  • Updated test setup with new job creation logic.
  • +32/-1   
    test_strings_info.py
    Add test case for StringsInfo analyzer.                                   

    tests/api_app/analyzers_manager/file_analyzers/test_strings_info.py

  • Added test case for StringsInfo analyzer.
  • Verified URL extraction from PDF files.
  • +40/-0   
    test_serializers.py
    Add tests for PivotConfig creation with plugin config.     

    tests/api_app/pivots_manager/test_serializers.py

  • Added tests for creating PivotConfig with and without plugin
    configuration.
  • Verified serializer behavior for different configurations.
  • +37/-0   
    test_iocextract.py
    Add test case for IocExtract analyzer.                                     

    tests/api_app/analyzers_manager/file_analyzers/test_iocextract.py

  • Added test case for IocExtract analyzer.
  • Verified extraction of IOCs from text files.
  • +33/-0   
    test_boxjs.py
    Add test case for BoxJS analyzer.                                               

    tests/api_app/analyzers_manager/file_analyzers/test_boxjs.py

  • Added test case for BoxJS analyzer.
  • Verified URL extraction from JavaScript files.
  • +37/-0   
    test_onenote_info.py
    Add test case for OneNoteInfo analyzer.                                   

    tests/api_app/analyzers_manager/file_analyzers/test_onenote_info.py

  • Added test case for OneNoteInfo analyzer.
  • Verified extraction of base64 content from OneNote files.
  • +33/-0   
    test_pdf_info.py
    Add test case for PDFInfo analyzer.                                           

    tests/api_app/analyzers_manager/file_analyzers/test_pdf_info.py

  • Added test case for PDFInfo analyzer.
  • Verified URI extraction from PDF files.
  • +34/-0   
    test_nvd_cve.py
    Add test cases for NVDDetails analyzer.                                   

    tests/api_app/analyzers_manager/observable_analyzers/test_nvd_cve.py

  • Added test cases for NVDDetails analyzer.
  • Verified handling of valid and invalid CVE formats.
  • +28/-0   
    test_lnk_info.py
    Add test case for LnkInfo analyzer.                                           

    tests/api_app/analyzers_manager/file_analyzers/test_lnk_info.py

  • Added test case for LnkInfo analyzer.
  • Verified URI extraction from LNK files.
  • +29/-0   
    observables.test.js
    Update observable validators tests with new cases.             

    frontend/tests/utils/observables.test.js

  • Updated tests for observable validators with new cases.
  • Ensured classification consistency for invalid inputs.
  • +35/-18 
    mock.js
    Add new mock implementations for auth and organization stores.

    frontend/tests/mock.js

  • Added new mock implementations for auth store.
  • Updated organization store mock with new properties.
  • +21/-2   
    JobActionBar.test.jsx
    Update JobActionsBar tests with new rescan logic.               

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

  • Updated tests for JobActionsBar with new rescan logic.
  • Simplified axios mock implementation for rescan tests.
  • +18/-100
    PlaybookConfigForm.test.jsx
    Tests for Playbook Configuration Form Component                   

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

  • Added tests for PlaybookConfigForm component.
  • Mocked necessary modules and API calls.
  • Verified form fields, validation, and submission logic.
  • +418/-0 
    Formatting
    7 files
    test_auth.py
    Ensure newline consistency in test_auth.py.                           

    tests/auth/test_auth.py

  • Ensured newline consistency at the end of the file.
  • Minor formatting adjustments for test assertions.
  • +1/-1     
    environment.js
    Reformat THREATMATRIX_DOCS_URL for consistency.                   

    frontend/src/constants/environment.js

  • Reformatted THREATMATRIX_DOCS_URL for consistency.
  • Ensured consistent line breaks in constants.
  • +2/-1     
    verify-email.html
    Improve formatting in verify-email.html template.               

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

  • Improved formatting and spacing in email template.
  • Ensured consistent HTML structure and indentation.
  • +12/-12 
    reset-password.html
    Improve formatting in reset-password.html template.           

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

  • Improved formatting and spacing in email template.
  • Ensured consistent HTML structure and indentation.
  • +5/-6     
    duplicate-email.html
    Improve formatting in duplicate-email.html template.         

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

  • Improved formatting and spacing in email template.
  • Ensured consistent HTML structure and indentation.
  • +5/-6     
    base.html
    Improve formatting in base email template.                             

    authentication/templates/authentication/emails/base.html

  • Improved formatting and spacing in base email template.
  • Ensured consistent HTML structure and indentation.
  • +2/-4     
    UserMenu.jsx
    Remove unused import from UserMenu component.                       

    frontend/src/layouts/widgets/UserMenu.jsx

  • Removed unused import from UserMenu component.
  • Simplified import statements for icons.
  • +1/-5     
    Documentation
    1 files
    CHANGELOG.md
    Changelog formatting and content improvements                       

    .github/CHANGELOG.md

  • Removed unnecessary blank lines between entries.
  • Changed bullet points from '-' to '*' for consistency.
  • Updated URLs to reflect new sponsorship and project links.
  • Improved formatting and readability of the changelog entries.
  • +172/-233
    Additional files (token-limit)
    71 files
    package-lock.json
    ...                                                                                                           

    frontend/package-lock.json

    ...

    +26635/-1
    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

    ...

    +14/-15 
    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

    ...

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

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

    ...

    +18/-0   
    traefik_prod.yml
    ...                                                                                                           

    docker/traefik_prod.yml

    ...

    +14/-14 
    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   
    project-requirements.txt
    ...                                                                                                           

    requirements/project-requirements.txt

    ...

    +8/-6     
    pluginsApi.jsx
    ...                                                                                                           

    frontend/src/components/plugins/pluginsApi.jsx

    ...

    +76/-0   
    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 
    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     
    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   
    investigationTableColumns.jsx
    ...                                                                                                           

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

    ...

    +15/-6   
    jobApi.jsx
    ...                                                                                                           

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

    ...

    +27/-0   
    compose.yml
    ...                                                                                                           

    integrations/phoneinfoga/compose.yml

    ...

    +13/-13 
    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     
    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     
    postgres.override.yml
    ...                                                                                                           

    docker/postgres.override.yml

    ...

    +4/-1     
    SECURITY.md
    ...                                                                                                           

    .github/SECURITY.md

    ...

    +4/-5     
    release_template.md
    ...                                                                                                           

    .github/release_template.md

    ...

    +1/-2     
    GuideWrapper.jsx
    ...                                                                                                           

    frontend/src/components/GuideWrapper.jsx

    ...

    +2/-2     
    traefik_local.yml
    ...                                                                                                           

    docker/traefik_local.yml

    ...

    +5/-5     
    PluginWrapper.jsx
    ...                                                                                                           

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

    ...

    +2/-2     
    compose.yml
    ...                                                                                                           

    integrations/cyberchef/compose.yml

    ...

    +2/-2     
    pull_request_automation.yml
    ...                                                                                                           

    .github/workflows/pull_request_automation.yml

    ...

    +1/-1     
    issue_template.md
    ...                                                                                                           

    .github/ISSUE_TEMPLATE/issue_template.md

    ...

    +4/-4     
    Pivots.jsx
    ...                                                                                                           

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

    ...

    +1/-1     
    new_connector.md
    ...                                                                                                           

    .github/ISSUE_TEMPLATE/new_connector.md

    ...

    +4/-2     
    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     
    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     
    FUNDING.yml
    ...                                                                                                           

    .github/FUNDING.yml

    ...

    +2/-2     
    compose.yml
    ...                                                                                                           

    integrations/malware_tools_analyzers/compose.yml

    ...

    +1/-0     
    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     

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

    khulnasoft-bot and others added 19 commits October 6, 2024 01:55
    Signed-off-by: KhulnaSoft bot <43526132+khulnasoft-bot@users.noreply.github.com>
    Signed-off-by: KhulnaSoft bot <43526132+khulnasoft-bot@users.noreply.github.com>
    Signed-off-by: KhulnaSoft bot <43526132+khulnasoft-bot@users.noreply.github.com>
    Signed-off-by: KhulnaSoft bot <43526132+khulnasoft-bot@users.noreply.github.com>
    Signed-off-by: KhulnaSoft bot <43526132+khulnasoft-bot@users.noreply.github.com>
    Signed-off-by: KhulnaSoft bot <43526132+khulnasoft-bot@users.noreply.github.com>
    Signed-off-by: KhulnaSoft bot <43526132+khulnasoft-bot@users.noreply.github.com>
    Signed-off-by: KhulnaSoft bot <43526132+khulnasoft-bot@users.noreply.github.com>
    Signed-off-by: gitworkflows <118260833+gitworkflows@users.noreply.github.com>
    * isort fix
    
    * Fix/frontend (#148)
    
    * isort fix
    
    * isort fix
    
    * Fix/prettier (#149)
    
    * isort fix
    
    * isort fix
    
    * isort fix
    
    ---------
    
    Signed-off-by: gitworkflows <118260833+gitworkflows@users.noreply.github.com>
    
    ---------
    
    Signed-off-by: gitworkflows <118260833+gitworkflows@users.noreply.github.com>
    * fix: test_min_password_lenght_400
    
    * Delete integrations/pcap_analyzers/config/suricata/rules/classification.config
    
    Signed-off-by: gitworkflows <118260833+gitworkflows@users.noreply.github.com>
    
    * Delete integrations/pcap_analyzers/config/suricata/rules/suricata.rules
    
    Signed-off-by: gitworkflows <118260833+gitworkflows@users.noreply.github.com>
    
    ---------
    
    Signed-off-by: gitworkflows <118260833+gitworkflows@users.noreply.github.com>
    Signed-off-by: KhulnaSoft bot <43526132+khulnasoft-bot@users.noreply.github.com>
    Signed-off-by: KhulnaSoft bot <43526132+khulnasoft-bot@users.noreply.github.com>
    Signed-off-by: KhulnaSoft bot <43526132+khulnasoft-bot@users.noreply.github.com>
    Signed-off-by: KhulnaSoft bot <43526132+khulnasoft-bot@users.noreply.github.com>
    Copy link

    sourcery-ai bot commented Nov 12, 2024

    Reviewer's Guide by Sourcery

    This PR introduces significant changes to improve the plugin management system in ThreatMatrix, particularly around Analyzers, Pivots and Playbooks. The main changes include adding new UI forms for creating/editing plugins, refactoring the runtime configuration handling, improving the VT integration, and adding support for new file types. The changes also include various bug fixes and improvements to the codebase.

    Class diagram for VirusTotalv3BaseMixin and VirusTotalv3AnalyzerMixin

    classDiagram
        class VirusTotalv3BaseMixin {
            +url: str
            +url_sub_path: str
            +_api_key_name: str
            +headers() dict
            +config(runtime_configuration: Dict)
            +_perform_get_request(uri: str, ignore_404: bool, **kwargs) Dict
            +_perform_post_request(uri: str, ignore_404: bool, **kwargs)
            +_perform_request(uri: str, method: str, ignore_404: bool, **kwargs) 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[Dict, str, List]
            +_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 {
            +max_tries: int
            +poll_distance: int
            +rescan_max_tries: int
            +rescan_poll_distance: int
            +include_behaviour_summary: bool
            +include_sigma_analyses: bool
            +force_active_scan_if_old: bool
            +days_to_say_that_a_scan_is_old: int
            +relationships_to_request: list
            +relationships_elements: int
            +_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[str, str]
            +_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 {
            -searchParams
            -observableParam
            -isSampleParam
            -investigationIdParam
            -parentIdParam
            -guideState
            -setGuideState
            -formik
            -organizationPluginsState
            -visualizersLoading
            -pivotsLoading
            -analyzersError
            -connectorsError
            -playbooksError
            -playbooks
            -selectObservableType(value)
            -updateAdvancedConfig(tags, newClassification, oldClassification)
        }
        ScanForm --> AnalyzersMultiSelectDropdownInput
        ScanForm --> ConnectorsMultiSelectDropdownInput
        ScanForm --> PlaybookMultiSelectDropdownInput
        ScanForm --> TLPSelectInput
        ScanForm --> ScanConfigSelectInput
    
    Loading

    File-Level Changes

    Change Details Files
    Added new UI forms for creating and editing plugins
    • Created new AnalyzerConfigForm component for creating/editing analyzer configurations
    • Created new PivotConfigForm component for creating/editing pivot configurations
    • Created new PlaybookConfigForm component for creating/editing playbook configurations
    • Added support for customizing plugin parameters and runtime configurations through the UI
    • Added validation and error handling for plugin configuration forms
    frontend/src/components/plugins/forms/AnalyzerConfigForm.jsx
    frontend/src/components/plugins/forms/PivotConfigForm.jsx
    frontend/src/components/plugins/forms/PlaybookConfigForm.jsx
    Refactored runtime configuration handling
    • Extracted runtime configuration logic into separate components
    • Added support for editing runtime configurations through a JSON editor
    • Improved validation and error handling for runtime configurations
    • Added support for displaying parameter descriptions and types
    frontend/src/components/common/form/runtimeConfigurationInput.jsx
    frontend/src/components/common/form/pluginsMultiSelectDropdownInput.jsx
    Enhanced VirusTotal integration
    • Added new VirusTotal ingestor for automated sample collection
    • Improved IOC extraction from VirusTotal results
    • Added support for customizing VirusTotal queries
    • Added better error handling and validation for VirusTotal API responses
    api_app/ingestors_manager/ingestors/virus_total.py
    api_app/mixins.py
    api_app/analyzers_manager/observable_analyzers/vt/vt3_get.py
    Added support for new file types and improved file analysis
    • Added support for LNK files
    • Improved URL extraction from PDF and Office documents
    • Enhanced OneNote file analysis capabilities
    • Added better MIME type detection and validation
    api_app/analyzers_manager/file_analyzers/doc_info.py
    api_app/analyzers_manager/file_analyzers/pdf_info.py
    api_app/analyzers_manager/file_analyzers/onenote.py
    api_app/analyzers_manager/models.py
    Improved plugin management and permissions
    • Added support for plugin deletion and editing based on user roles
    • Improved plugin health check functionality
    • Added better validation for plugin configurations
    • Added support for organization-level plugin management
    api_app/permissions.py
    api_app/pivots_manager/permissions.py
    api_app/views.py
    api_app/pivots_manager/views.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 2 secrets 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 secrets in your pull request
    GitGuardian id GitGuardian status Secret Commit Filename
    14262919 Triggered Username Password 2d9ca9e tests/auth/test_auth.py View secret
    13180230 Triggered Username Password 85780e0 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 secrets safely. Learn here the best practices.
    3. Revoke and rotate these secrets.
    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.

    97 files out of 181 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 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..8f3835d. View details on DeepSource ↗.

    Analysis Summary

    AnalyzerStatusSummaryLink
    DeepSource Python LogoPython❌ Failure
    ❗ 198 occurences introduced
    🎯 114 occurences resolved
    View Check ↗
    DeepSource Docker LogoDocker❌ Failure
    ❗ 17 occurences introduced
    🎯 9 occurences resolved
    View Check ↗

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

    Signed-off-by: gitworkflows <118260833+gitworkflows@users.noreply.github.com>
    Signed-off-by: gitworkflows <118260833+gitworkflows@users.noreply.github.com>
    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 error logging in api_app/mixins.py could potentially expose sensitive information in error messages that are logged. Consider sanitizing error details before logging.

    ⚡ Recommended focus areas for review

    Error Handling
    The error handling in _perform_request() could be improved. Currently it catches all exceptions generically and may mask specific errors. Consider catching specific exceptions and providing more detailed error messages.

    Security Risk
    The regex pattern for URL extraction could potentially be exploited with carefully crafted input. Consider adding input validation and length limits.

    Performance Issue
    The URL regex pattern is complex and could be resource intensive on large inputs. Consider optimizing the pattern or adding limits to prevent DoS.

    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 @gitworkflows - I've reviewed your changes - here's some feedback:

    Overall Comments:

    • Consider consolidating common plugin configuration patterns into shared utilities to reduce code duplication across different plugin types
    • Error handling could be more consistent - suggest standardizing error message formats and detail levels across the codebase
    Here's what I looked at during the review
    • 🟡 General issues: 3 issues found
    • 🟢 Security: all looks good
    • 🟡 Testing: 3 issues found
    • 🟡 Complexity: 1 issue 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.

    raise NotImplementedError()
    logger.info(f"requests done to: {response.request.url} ")
    logger.debug(f"text: {response.text}")
    result = response.json()
    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): Error handling could be improved to handle JSON parsing failures separately

    The error variable is used in the error message before we know if json parsing succeeded. Consider handling the JSON parsing in a separate try-except block.

    Suggested change
    result = response.json()
    try:
    result = response.json()
    except ValueError:
    logger.error(f"Invalid JSON response from {response.request.url}")
    raise

    )
    return attrs

    def create(self, validated_data):
    Copy link

    Choose a reason for hiding this comment

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

    suggestion: Duplicated plugin config handling logic in create and update methods

    Consider extracting the plugin config handling logic into a helper method to avoid code duplication between create and update.

        def _handle_plugin_config(self, validated_data):
            return validated_data.pop("plugin_config", {})
    
        def create(self, validated_data):
            plugin_config = self._handle_plugin_config(validated_data)
            pc = super().create(validated_data)

    # optional certificate
    verify = True # defualt
    if hasattr(self, "_certificate") and self._certificate:
    self.__cert_file = NamedTemporaryFile(mode="w")
    Copy link

    Choose a reason for hiding this comment

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

    issue: Temporary certificate file should be properly managed and cleaned up

    Use a context manager (with statement) to ensure the temporary file is properly closed and removed. Consider using the delete=True parameter with NamedTemporaryFile.

    Comment on lines +77 to +86
    def test_create(self):
    # invalid fields
    response = self.client.post(
    self.URL,
    data={
    "name": "TestCreate",
    "python_module": "basic_observable_analyzer.BasicObservableAnalyzer",
    },
    format="json",
    )
    Copy link

    Choose a reason for hiding this comment

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

    suggestion (testing): Consider adding test for invalid plugin configuration

    While the test covers basic creation and plugin configuration, it would be valuable to add a test case for invalid plugin configuration to ensure proper error handling.

        def test_create(self):
            # Test invalid fields
            response = self.client.post(
                self.URL,
                data={
                    "name": "TestCreate",
                    "python_module": "basic_observable_analyzer.BasicObservableAnalyzer",
                    "plugin_config": {"invalid_key": "invalid_value"}
                },
                format="json",
            )
            self.assertEqual(response.status_code, 400)

    screen.getByText(
    `${pluginType_} with name ${pluginName} deleted with success`,
    ),
    ).toBeInTheDocument();
    Copy link

    Choose a reason for hiding this comment

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

    suggestion (testing): Add test for successful playbook edit

    The test only covers the loading state. Consider adding a test case that verifies the successful editing of a playbook configuration.


    from api_app.analyzers_manager.file_analyzers.iocextract import IocExtract
    from api_app.models import Job
    from tests import CustomTestCase
    Copy link

    Choose a reason for hiding this comment

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

    issue (code-quality): Don't import test modules. (dont-import-test-modules)

    ExplanationDon't import test modules.

    Tests should be self-contained and don't depend on each other.

    If a helper function is used by multiple tests,
    define it in a helper module,
    instead of importing one test from the other.


    from api_app.analyzers_manager.file_analyzers.lnk_info import LnkInfo
    from api_app.models import Job
    from tests import CustomTestCase
    Copy link

    Choose a reason for hiding this comment

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

    issue (code-quality): Don't import test modules. (dont-import-test-modules)

    ExplanationDon't import test modules.

    Tests should be self-contained and don't depend on each other.

    If a helper function is used by multiple tests,
    define it in a helper module,
    instead of importing one test from the other.


    from api_app.analyzers_manager.file_analyzers.onenote import OneNoteInfo
    from api_app.models import Job
    from tests import CustomTestCase
    Copy link

    Choose a reason for hiding this comment

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

    issue (code-quality): Don't import test modules. (dont-import-test-modules)

    ExplanationDon't import test modules.

    Tests should be self-contained and don't depend on each other.

    If a helper function is used by multiple tests,
    define it in a helper module,
    instead of importing one test from the other.


    from api_app.analyzers_manager.file_analyzers.pdf_info import PDFInfo
    from api_app.models import Job
    from tests import CustomTestCase
    Copy link

    Choose a reason for hiding this comment

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

    issue (code-quality): Don't import test modules. (dont-import-test-modules)

    ExplanationDon't import test modules.

    Tests should be self-contained and don't depend on each other.

    If a helper function is used by multiple tests,
    define it in a helper module,
    instead of importing one test from the other.


    from api_app.analyzers_manager.file_analyzers.strings_info import StringsInfo
    from api_app.models import Job
    from tests import CustomTestCase
    Copy link

    Choose a reason for hiding this comment

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

    issue (code-quality): Don't import test modules. (dont-import-test-modules)

    ExplanationDon't import test modules.

    Tests should be self-contained and don't depend on each other.

    If a helper function is used by multiple tests,
    define it in a helper module,
    instead of importing one test from the other.

    Copy link
    Contributor

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Score
    Best practice
    Add request timeout to prevent indefinite waiting on slow responses

    Add a timeout parameter to requests to prevent hanging on slow responses. This is
    especially important for external API calls.

    api_app/mixins.py [116-118]

     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 external API requests is a critical security and reliability practice to prevent request hanging and resource exhaustion. This is particularly important for VirusTotal API integration.

    8
    Ensure proper cleanup of temporary files by using try-finally blocks

    Add error handling and cleanup for the temporary certificate file in a finally block
    to ensure it's properly closed and removed, even if an exception occurs.

    api_app/analyzers_manager/observable_analyzers/basic_observable_analyzer.py [65-69]

     if hasattr(self, "_certificate") and self._certificate:
         self.__cert_file = NamedTemporaryFile(mode="w")
    -    self.__cert_file.write(self._clean_certificate(self._certificate))
    -    self.__cert_file.flush()
    -    verify = self.__cert_file.name
    +    try:
    +        self.__cert_file.write(self._clean_certificate(self._certificate))
    +        self.__cert_file.flush()
    +        verify = self.__cert_file.name
    +    finally:
    +        self.__cert_file.close()
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    Why: Important security improvement to prevent potential file descriptor leaks and ensure proper cleanup of sensitive certificate files, even in case of exceptions.

    8
    Use context manager for proper resource cleanup when downloading files

    Use a context manager for file download to ensure proper resource cleanup and file
    handle closure.

    api_app/mixins.py [252-254]

    -response = requests.get(endpoint, headers=self.headers)
    -if not isinstance(response.content, bytes):
    -    raise ValueError("VT downloaded file is not instance of bytes")
    +with requests.get(endpoint, headers=self.headers, stream=True) as response:
    +    content = response.content
    +    if not isinstance(content, bytes):
    +        raise ValueError("VT downloaded file is not instance of bytes")
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why: Using a context manager with stream=True ensures proper cleanup of network resources and memory management when downloading files, which is important for handling potentially large files.

    7
    Ensure proper cleanup of test data by using try-finally blocks

    Add cleanup in a try-finally block to ensure test objects are deleted even if
    assertions fail.

    tests/api_app/test_mixins.py [191-205]

    -ac = AnalyzerConfig(
    -    name="test",
    -    description="test delete",
    -    python_module=PythonModule.objects.filter(
    -        base_path=PythonModuleBasePaths.ObservableAnalyzer.value
    -    ).first(),
    -)
    -ac.save()
    -ac1 = AnalyzerConfig(
    -    name="test1",
    -    description="test delete",
    -    python_module=PythonModule.objects.filter(
    -        base_path=PythonModuleBasePaths.ObservableAnalyzer.value
    -    ).first(),
    -)
    -ac1.save()
    +try:
    +    ac = AnalyzerConfig(
    +        name="test",
    +        description="test delete",
    +        python_module=PythonModule.objects.filter(
    +            base_path=PythonModuleBasePaths.ObservableAnalyzer.value
    +        ).first(),
    +    )
    +    ac.save()
    +    ac1 = AnalyzerConfig(
    +        name="test1",
    +        description="test delete",
    +        python_module=PythonModule.objects.filter(
    +            base_path=PythonModuleBasePaths.ObservableAnalyzer.value
    +        ).first(),
    +    )
    +    ac1.save()
    • Apply this suggestion
    Suggestion importance[1-10]: 6

    Why: Adding try-finally blocks ensures test objects are properly cleaned up even if tests fail, preventing test data pollution and potential side effects in subsequent tests.

    6
    Security
    Improve security by avoiding empty string passwords in user configurations

    Consider using a more secure default password policy by setting 'password' to None
    or a secure hashed value instead of an empty string in the user profile
    configuration.

    api_app/ingestors_manager/migrations/0025_ingestor_config_virustotal_example_query.py [39-49]

     "profile": {
         "user": {
    -        "username": "VirusTotal_Example_QueryIngestor",
    +        "username": "VirusTotal_Example_QueryIngestor", 
             "email": "",
             "first_name": "",
             "last_name": "",
    -        "password": "",
    +        "password": None,
             "is_active": True,
         },
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    Why: Empty string passwords are a security risk as they could potentially be exploited. Using None or a secure hashed value is a better security practice for default password configurations.

    8
    Possible issue
    Add comprehensive error handling for document parsing operations

    Add error handling for potential zipfile.BadZipFile exceptions when reading specific
    files from the docx document.

    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 (KeyError, zipfile.BadZipFile, IndexError) as e:
    +    logger.warning(f"Failed to read pages count: {e}")
    +    pages_count = 0
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why: The improved error handling covers multiple potential failure points in document parsing, preventing crashes and providing better logging of issues.

    7
    Validate API key format before using it in authentication

    Add input validation for the API key to ensure it's not empty or malformed before
    using it in authentication.

    api_app/analyzers_manager/observable_analyzers/basic_observable_analyzer.py [51-58]

    -if hasattr(self, "_api_key_name") and self._api_key_name:
    +if hasattr(self, "_api_key_name"):
    +    if not self._api_key_name or not isinstance(self._api_key_name, str):
    +        raise AnalyzerConfigurationException("Invalid API key format")
         api_key = self._api_key_name
         if (
             "Authorization" in self.headers.keys()
             and self.headers["Authorization"].split(" ")[0] == "Basic"
         ):
             api_key = base64.b64encode(self._api_key_name.encode()).decode()
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why: Important security check to validate API key format early and prevent potential authentication issues or security vulnerabilities.

    7
    Enhancement
    Implement rate limiting to prevent API throttling

    Add rate limiting mechanism to prevent hitting API limits when making multiple
    requests in sequence.

    api_app/mixins.py [109-111]

     def _perform_request(
         self, uri: str, method: str, ignore_404: bool = False, **kwargs
     ) -> Dict:
    +    time.sleep(1)  # Add 1 second delay between requests
    • Apply this suggestion
    Suggestion importance[1-10]: 6

    Why: Adding rate limiting helps prevent hitting API rate limits and ensures more reliable API interactions, though the specific delay value might need adjustment based on API requirements.

    6
    Performance
    Improve performance by precompiling regular expressions used in loops

    Cache the compiled regex pattern outside the loop to improve performance when
    extracting URLs from multiple strings.

    api_app/analyzers_manager/file_analyzers/strings_info.py [88-95]

    +url_pattern = re.compile(
    +    r"[a-z]{1,5}://[a-z\d-]{1,200}"
    +    r"(?:\.[a-zA-Z\d\u2044\u2215!#$&(-;=?-\[\]_~]{1,200})+"
    +    r"(?::\d{2,6})?"
    +    r"(?:/[a-zA-Z\d\u2044\u2215!#$&(-;=?-\[\]_~]{1,200})*"
    +    r"(?:\.\w+)?"
    +)
     for d in result["data"]:
         if ObservableTypes.calculate(d) == ObservableTypes.URL:
    -        extracted_urls = re.findall(
    -            r"[a-z]{1,5}://[a-z\d-]{1,200}"
    -            r"(?:\.[a-zA-Z\d\u2044\u2215!#$&(-;=?-\[\]_~]{1,200})+"
    -            r"(?::\d{2,6})?"
    -            r"(?:/[a-zA-Z\d\u2044\u2215!#$&(-;=?-\[\]_~]{1,200})*"
    -            r"(?:\.\w+)?",
    -            d,
    -        )
    +        extracted_urls = url_pattern.findall(d)
    • Apply this suggestion
    Suggestion importance[1-10]: 6

    Why: Performance optimization that avoids recompiling the regex pattern on each iteration when processing multiple strings.

    6

    💡 Need additional feedback ? start a PR chat

    @NxPKG NxPKG closed this Nov 12, 2024
    @NxPKG NxPKG deleted the elastic branch November 12, 2024 07:45
    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.

    3 participants