|
| 1 | +# Copyright 2026 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +# |
| 15 | +"""Chronicle parser validation functionality.""" |
| 16 | + |
| 17 | +from typing import TYPE_CHECKING, Any |
| 18 | +import logging |
| 19 | + |
| 20 | +from secops.exceptions import APIError, SecOpsError |
| 21 | + |
| 22 | +if TYPE_CHECKING: |
| 23 | + from secops.chronicle.client import ChronicleClient |
| 24 | + |
| 25 | + |
| 26 | +def trigger_github_checks( |
| 27 | + client: "ChronicleClient", |
| 28 | + associated_pr: str, |
| 29 | + log_type: str, |
| 30 | + customer_id: str | None = None, |
| 31 | + timeout: int = 60, |
| 32 | +) -> dict[str, Any]: |
| 33 | + """Trigger GitHub checks for a parser. |
| 34 | +
|
| 35 | + Args: |
| 36 | + client: ChronicleClient instance |
| 37 | + associated_pr: The PR string (e.g., "owner/repo/pull/123"). |
| 38 | + log_type: The string name of the LogType enum. |
| 39 | + customer_id: Optional. The customer UUID string. Defaults to client |
| 40 | + configured ID. |
| 41 | + timeout: Optional RPC timeout in seconds (default: 60). |
| 42 | +
|
| 43 | + Returns: |
| 44 | + Dictionary containing the response details. |
| 45 | +
|
| 46 | + Raises: |
| 47 | + SecOpsError: If input is invalid. |
| 48 | + APIError: If the API request fails. |
| 49 | + """ |
| 50 | + if not isinstance(log_type, str) or len(log_type.strip()) < 2: |
| 51 | + raise SecOpsError("log_type must be a valid string of length >= 2") |
| 52 | + if customer_id is not None: |
| 53 | + if not isinstance(customer_id, str) or len(customer_id.strip()) < 2: |
| 54 | + raise SecOpsError( |
| 55 | + "customer_id must be a valid string of length >= 2" |
| 56 | + ) |
| 57 | + if not isinstance(associated_pr, str) or not associated_pr.strip(): |
| 58 | + raise SecOpsError("associated_pr must be a non-empty string") |
| 59 | + if not isinstance(timeout, int) or timeout < 0: |
| 60 | + raise SecOpsError("timeout must be a non-negative integer") |
| 61 | + |
| 62 | + eff_customer_id = customer_id or client.customer_id |
| 63 | + instance_id = client.instance_id |
| 64 | + if eff_customer_id and eff_customer_id != client.customer_id: |
| 65 | + # Dev and staging use 'us' as the location |
| 66 | + region = "us" if client.region in ["dev", "staging"] else client.region |
| 67 | + instance_id = ( |
| 68 | + f"projects/{client.project_id}/locations/" |
| 69 | + f"{region}/instances/{eff_customer_id}" |
| 70 | + ) |
| 71 | + |
| 72 | + # The backend expects the resource name to be in the format: |
| 73 | + # projects/*/locations/*/instances/*/logTypes/*/parsers/<UUID> |
| 74 | + base_url = client.base_url(version="v1alpha") |
| 75 | + |
| 76 | + # First get the list of parsers for this log_type to find a valid |
| 77 | + # parser UUID |
| 78 | + parsers_url = f"{base_url}/{instance_id}/logTypes/{log_type}/parsers" |
| 79 | + parsers_resp = client.session.get(parsers_url, timeout=timeout) |
| 80 | + if not parsers_resp.ok: |
| 81 | + raise APIError( |
| 82 | + f"Failed to fetch parsers for log type {log_type}: " |
| 83 | + f"{parsers_resp.text}" |
| 84 | + ) |
| 85 | + |
| 86 | + parsers_data = parsers_resp.json() |
| 87 | + parsers = parsers_data.get("parsers") |
| 88 | + if not parsers: |
| 89 | + logging.info( |
| 90 | + "No parsers found for log type %s. Using fallback parser ID.", |
| 91 | + log_type, |
| 92 | + ) |
| 93 | + parser_name = f"{instance_id}/logTypes/{log_type}/parsers/-" |
| 94 | + else: |
| 95 | + if len(parsers) > 1: |
| 96 | + logging.warning( |
| 97 | + "Multiple parsers found for log type %s. Using the first one.", |
| 98 | + log_type, |
| 99 | + ) |
| 100 | + |
| 101 | + # Use the first parser's name (which includes the UUID) |
| 102 | + parser_name = parsers[0]["name"] |
| 103 | + |
| 104 | + url = f"{base_url}/{parser_name}:runAnalysis" |
| 105 | + payload = { |
| 106 | + "report_type": "GITHUB_PARSER_VALIDATION", |
| 107 | + "pull_request": associated_pr, |
| 108 | + } |
| 109 | + |
| 110 | + response = client.session.post(url, json=payload, timeout=timeout) |
| 111 | + |
| 112 | + if not response.ok: |
| 113 | + raise APIError(f"API call failed: {response.text}") |
| 114 | + |
| 115 | + return response.json() |
| 116 | + |
| 117 | + |
| 118 | +def get_analysis_report( |
| 119 | + client: "ChronicleClient", |
| 120 | + name: str, |
| 121 | + timeout: int = 60, |
| 122 | +) -> dict[str, Any]: |
| 123 | + """Get a parser analysis report. |
| 124 | + Args: |
| 125 | + client: ChronicleClient instance |
| 126 | + name: The full resource name of the analysis report. |
| 127 | + timeout: Optional timeout in seconds (default: 60). |
| 128 | + Returns: |
| 129 | + Dictionary containing the analysis report. |
| 130 | + Raises: |
| 131 | + SecOpsError: If input is invalid. |
| 132 | + APIError: If the API request fails. |
| 133 | + """ |
| 134 | + if not isinstance(name, str) or len(name.strip()) < 5: |
| 135 | + raise SecOpsError("name must be a valid string") |
| 136 | + if not isinstance(timeout, int) or timeout < 0: |
| 137 | + raise SecOpsError("timeout must be a non-negative integer") |
| 138 | + |
| 139 | + # The name includes 'projects/...', so we just append it to base_url |
| 140 | + base_url = client.base_url(version="v1alpha") |
| 141 | + url = f"{base_url}/{name}" |
| 142 | + |
| 143 | + response = client.session.get(url, timeout=timeout) |
| 144 | + |
| 145 | + if not response.ok: |
| 146 | + raise APIError(f"API call failed: {response.text}") |
| 147 | + |
| 148 | + return response.json() |
0 commit comments