-
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
Open
ishree-dev
wants to merge
1
commit into
google:main
Choose a base branch
from
ishree-dev:cli-changes
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,159 @@ | ||
| # 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 | ||
| import re | ||
|
|
||
| from secops.exceptions import APIError, SecOpsError | ||
|
|
||
| if TYPE_CHECKING: | ||
| from secops.chronicle.client import ChronicleClient | ||
|
|
||
|
|
||
| def trigger_github_checks( | ||
| client: "ChronicleClient", | ||
| associated_pr: str, | ||
ishree-dev marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| 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 not re.match( | ||
| r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-" | ||
| r"[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", | ||
| customer_id, | ||
| ): | ||
| raise SecOpsError( | ||
| "customer_id must be a valid UUID string" | ||
| ) | ||
| if not isinstance(associated_pr, str) or not associated_pr.strip(): | ||
| raise SecOpsError("associated_pr must be a non-empty string") | ||
|
|
||
| pr_parts = associated_pr.split("/") | ||
| if len(pr_parts) != 4 or pr_parts[2] != "pull" or not pr_parts[3].isdigit(): | ||
| raise SecOpsError( | ||
| "associated_pr must be in the format 'owner/repo/pull/<number>'" | ||
| ) | ||
| 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) | ||
ishree-dev marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| 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() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,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: | ||
ishree-dev marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| 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) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.