-
Notifications
You must be signed in to change notification settings - Fork 36
Add parser validation APIs and log-type CLI commands #201
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,148 @@ | ||
| # Copyright 2026 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # | ||
| """Chronicle parser validation functionality.""" | ||
|
|
||
| from typing import TYPE_CHECKING, Any | ||
| import logging | ||
|
|
||
| from secops.exceptions import APIError, SecOpsError | ||
|
|
||
| if TYPE_CHECKING: | ||
| from secops.chronicle.client import ChronicleClient | ||
|
|
||
|
|
||
| def trigger_github_checks( | ||
| client: "ChronicleClient", | ||
| associated_pr: str, | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Lets add proper validations for the structure of this string, validate by breaking the path and number of substrings, valid pr number. |
||
| log_type: str, | ||
| customer_id: str | None = None, | ||
| timeout: int = 60, | ||
| ) -> dict[str, Any]: | ||
| """Trigger GitHub checks for a parser. | ||
|
|
||
| Args: | ||
| client: ChronicleClient instance | ||
| associated_pr: The PR string (e.g., "owner/repo/pull/123"). | ||
| log_type: The string name of the LogType enum. | ||
| customer_id: Optional. The customer UUID string. Defaults to client | ||
| configured ID. | ||
| timeout: Optional RPC timeout in seconds (default: 60). | ||
|
|
||
| Returns: | ||
| Dictionary containing the response details. | ||
|
|
||
| Raises: | ||
| SecOpsError: If input is invalid. | ||
| APIError: If the API request fails. | ||
| """ | ||
| if not isinstance(log_type, str) or len(log_type.strip()) < 2: | ||
| raise SecOpsError("log_type must be a valid string of length >= 2") | ||
| if customer_id is not None: | ||
| if not isinstance(customer_id, str) or len(customer_id.strip()) < 2: | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Lets use pattern matching for Customer Id as its a UUID |
||
| raise SecOpsError( | ||
| "customer_id must be a valid string of length >= 2" | ||
| ) | ||
| if not isinstance(associated_pr, str) or not associated_pr.strip(): | ||
| raise SecOpsError("associated_pr must be a non-empty string") | ||
| if not isinstance(timeout, int) or timeout < 0: | ||
| raise SecOpsError("timeout must be a non-negative integer") | ||
|
|
||
| eff_customer_id = customer_id or client.customer_id | ||
| instance_id = client.instance_id | ||
| if eff_customer_id and eff_customer_id != client.customer_id: | ||
| # Dev and staging use 'us' as the location | ||
| region = "us" if client.region in ["dev", "staging"] else client.region | ||
| instance_id = ( | ||
| f"projects/{client.project_id}/locations/" | ||
| f"{region}/instances/{eff_customer_id}" | ||
| ) | ||
|
|
||
| # The backend expects the resource name to be in the format: | ||
| # projects/*/locations/*/instances/*/logTypes/*/parsers/<UUID> | ||
| base_url = client.base_url(version="v1alpha") | ||
|
|
||
| # First get the list of parsers for this log_type to find a valid | ||
| # parser UUID | ||
| parsers_url = f"{base_url}/{instance_id}/logTypes/{log_type}/parsers" | ||
| parsers_resp = client.session.get(parsers_url, timeout=timeout) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can't we use the some information from metadata.json file instead of fetching the parsers for this logtype and then using the first available name?
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. we are expecting log_type from the cli command There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Correct. |
||
| if not parsers_resp.ok: | ||
| raise APIError( | ||
| f"Failed to fetch parsers for log type {log_type}: " | ||
| f"{parsers_resp.text}" | ||
| ) | ||
|
|
||
| parsers_data = parsers_resp.json() | ||
| parsers = parsers_data.get("parsers") | ||
| if not parsers: | ||
| logging.info( | ||
| "No parsers found for log type %s. Using fallback parser ID.", | ||
| log_type, | ||
| ) | ||
| parser_name = f"{instance_id}/logTypes/{log_type}/parsers/-" | ||
| else: | ||
| if len(parsers) > 1: | ||
| logging.warning( | ||
| "Multiple parsers found for log type %s. Using the first one.", | ||
| log_type, | ||
| ) | ||
|
|
||
| # Use the first parser's name (which includes the UUID) | ||
| parser_name = parsers[0]["name"] | ||
|
|
||
| url = f"{base_url}/{parser_name}:runAnalysis" | ||
| payload = { | ||
| "report_type": "GITHUB_PARSER_VALIDATION", | ||
| "pull_request": associated_pr, | ||
| } | ||
|
|
||
| response = client.session.post(url, json=payload, timeout=timeout) | ||
|
|
||
| if not response.ok: | ||
| raise APIError(f"API call failed: {response.text}") | ||
|
|
||
| return response.json() | ||
|
|
||
|
|
||
| def get_analysis_report( | ||
| client: "ChronicleClient", | ||
| name: str, | ||
ishree-dev marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| timeout: int = 60, | ||
| ) -> dict[str, Any]: | ||
| """Get a parser analysis report. | ||
| Args: | ||
| client: ChronicleClient instance | ||
| name: The full resource name of the analysis report. | ||
| timeout: Optional timeout in seconds (default: 60). | ||
| Returns: | ||
| Dictionary containing the analysis report. | ||
| Raises: | ||
| SecOpsError: If input is invalid. | ||
| APIError: If the API request fails. | ||
| """ | ||
| if not isinstance(name, str) or len(name.strip()) < 5: | ||
| raise SecOpsError("name must be a valid string") | ||
| if not isinstance(timeout, int) or timeout < 0: | ||
| raise SecOpsError("timeout must be a non-negative integer") | ||
|
|
||
| # The name includes 'projects/...', so we just append it to base_url | ||
| base_url = client.base_url(version="v1alpha") | ||
| url = f"{base_url}/{name}" | ||
|
|
||
| response = client.session.get(url, timeout=timeout) | ||
|
|
||
| if not response.ok: | ||
| raise APIError(f"API call failed: {response.text}") | ||
|
|
||
| return response.json() | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| # Copyright 2026 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # | ||
| """CLI for ParserValidationToolingService under Log Type command group""" | ||
|
|
||
| import sys | ||
|
|
||
| from secops.cli.utils.formatters import output_formatter | ||
| from secops.exceptions import APIError, SecOpsError | ||
|
|
||
|
|
||
| def setup_log_type_commands(subparsers): | ||
| """Set up the log_type service commands for Parser Validation.""" | ||
| log_type_parser = subparsers.add_parser( | ||
| "log-type", help="Log Type related operations (including Parser Validation)" | ||
| ) | ||
|
|
||
| log_type_subparsers = log_type_parser.add_subparsers( | ||
| title="Log Type Commands", | ||
| dest="log_type_command", | ||
| help="Log Type sub-command to execute" | ||
| ) | ||
|
|
||
| if sys.version_info >= (3, 7): | ||
| log_type_subparsers.required = True | ||
|
|
||
| log_type_parser.set_defaults( | ||
| func=lambda args, chronicle: log_type_parser.print_help() | ||
| ) | ||
|
|
||
| # --- trigger-checks command --- | ||
| trigger_github_checks_parser = log_type_subparsers.add_parser( | ||
| "trigger-checks", help="Trigger GitHub checks for a parser" | ||
| ) | ||
| trigger_github_checks_parser.add_argument( | ||
| "--associated-pr", | ||
| "--associated_pr", | ||
| required=True, | ||
| help='The PR string (e.g., "owner/repo/pull/123").' | ||
| ) | ||
| trigger_github_checks_parser.add_argument( | ||
| "--log-type", | ||
| "--log_type", | ||
| required=True, | ||
| help='The string name of the LogType enum (e.g., "DUMMY_LOGTYPE").' | ||
| ) | ||
| trigger_github_checks_parser.set_defaults(func=handle_trigger_checks_command) | ||
|
|
||
| # --- get-analysis-report command --- | ||
| get_report_parser = log_type_subparsers.add_parser( | ||
| "get-analysis-report", help="Get a parser analysis report" | ||
| ) | ||
| get_report_parser.add_argument( | ||
| "--name", | ||
| required=True, | ||
| help="The full resource name of the analysis report." | ||
| ) | ||
| get_report_parser.set_defaults(func=handle_get_analysis_report_command) | ||
|
|
||
|
|
||
| def handle_trigger_checks_command(args, chronicle): | ||
| """Handle trigger checks command.""" | ||
| try: | ||
| result = chronicle.trigger_github_checks( | ||
| associated_pr=args.associated_pr, | ||
| log_type=args.log_type, | ||
| ) | ||
| output_formatter(result, args.output) | ||
| except APIError as e: | ||
| print(f"Error: {e}", file=sys.stderr) | ||
| sys.exit(1) | ||
| except SecOpsError as e: | ||
| print(f"Error: {e}", file=sys.stderr) | ||
| sys.exit(1) | ||
| except Exception as e: # pylint: disable=broad-exception-caught | ||
| print(f"Error triggering GitHub checks: {e}", file=sys.stderr) | ||
| sys.exit(1) | ||
|
|
||
|
|
||
| def handle_get_analysis_report_command(args, chronicle): | ||
| """Handle get analysis report command.""" | ||
| try: | ||
| result = chronicle.get_analysis_report(name=args.name) | ||
| output_formatter(result, args.output) | ||
| except APIError as e: | ||
| print(f"Error: {e}", file=sys.stderr) | ||
| sys.exit(1) | ||
| except SecOpsError as e: | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. When will this error come?
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This SecOpsError is caught because chronicle.get_analysis_report(name=args.name) performs local input validation before sending the request. If the user passes an empty or invalid name |
||
| print(f"Error: {e}", file=sys.stderr) | ||
| sys.exit(1) | ||
| except Exception as e: # pylint: disable=broad-exception-caught | ||
| print(f"Error fetching analysis report: {e}", file=sys.stderr) | ||
| sys.exit(1) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| """Test parser validation methods on ChronicleClient.""" | ||
|
|
||
| from unittest.mock import MagicMock | ||
| import pytest | ||
|
|
||
| from secops.chronicle.client import ChronicleClient | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def mock_client(): | ||
| """Create a mock ChronicleClient.""" | ||
| client = ChronicleClient( | ||
| project_id="test-project", | ||
| customer_id="test-customer", | ||
| auth=MagicMock(), | ||
| ) | ||
| # Mock the parser validation service stub | ||
| client.parser_validation_service_stub = MagicMock() | ||
| return client | ||
|
|
||
|
|
||
| def test_trigger_github_checks(mock_client, monkeypatch): | ||
| """Test ChronicleClient.trigger_github_checks.""" | ||
| # Mock the underlying implementation to avoid gRPC dependency in tests | ||
| mock_impl = MagicMock(return_value={"message": "Success", "details": "Started"}) | ||
| monkeypatch.setattr( | ||
| "secops.chronicle.client._trigger_github_checks", mock_impl | ||
| ) | ||
|
|
||
| result = mock_client.trigger_github_checks( | ||
| associated_pr="owner/repo/pull/123", | ||
| log_type="DUMMY_LOGTYPE", | ||
| ) | ||
|
|
||
| assert result == {"message": "Success", "details": "Started"} | ||
| mock_impl.assert_called_once_with( | ||
| mock_client, | ||
| associated_pr="owner/repo/pull/123", | ||
| log_type="DUMMY_LOGTYPE", | ||
| customer_id=None, | ||
| ) | ||
|
|
||
|
|
||
| def test_get_analysis_report(mock_client, monkeypatch): | ||
| """Test ChronicleClient.get_analysis_report.""" | ||
| # Mock the underlying implementation | ||
| mock_impl = MagicMock(return_value={"reportId": "123"}) | ||
| monkeypatch.setattr( | ||
| "secops.chronicle.client._get_analysis_report", mock_impl | ||
| ) | ||
|
|
||
| result = mock_client.get_analysis_report( | ||
| name="projects/test/locations/us/instances/test/logTypes/DEF/parsers/XYZ/analysisReports/123" | ||
| ) | ||
|
|
||
| assert result == {"reportId": "123"} | ||
| mock_impl.assert_called_once_with( | ||
| mock_client, | ||
| "projects/test/locations/us/instances/test/logTypes/DEF/parsers/XYZ/analysisReports/123", | ||
| ) |
Uh oh!
There was an error while loading. Please reload this page.