Skip to content

Commit d03052a

Browse files
dandyecopybara-github
authored andcommitted
v1alpha sample to search alerts
PiperOrigin-RevId: 698142943
1 parent a92b7c2 commit d03052a

File tree

1 file changed

+161
-0
lines changed

1 file changed

+161
-0
lines changed
Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
#!/usr/bin/env python3
2+
3+
# Copyright 2024 Google LLC
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
#
17+
r"""Executable sample for getting a list of generated alerts.
18+
19+
Sample Command (run from api_samples_python dir):
20+
python3 -m detect.v1alpha.search_rules_alerts \
21+
--region=$REGION \
22+
--project_id=$PROJECT_ID \
23+
--project_instance=$PROJECT_INSTANCE \
24+
--credentials_file=$CREDENTIALS_FILE \
25+
--start_time="2024-11-11T13:37:32Z" \
26+
--start_time="2024-11-19T13:37:32Z" \
27+
--rule_status=ALL \
28+
--page_size=10
29+
--
30+
31+
API reference:
32+
https://cloud.google.com/chronicle/docs/reference/rest/v1alpha/projects.locations.instances.legacy/legacySearchRulesAlerts
33+
"""
34+
import argparse
35+
import datetime
36+
import json
37+
from typing import Any, Mapping
38+
from common import chronicle_auth
39+
from common import project_id
40+
from common import project_instance
41+
from common import regions
42+
from google.auth.transport import requests
43+
44+
CHRONICLE_API_BASE_URL = "https://chronicle.googleapis.com"
45+
46+
SCOPES = [
47+
"https://www.googleapis.com/auth/cloud-platform",
48+
]
49+
50+
RULE_STATUS = (
51+
"ACTIVE",
52+
"ARCHIVED",
53+
"ALL",
54+
)
55+
56+
57+
def search_rules_alerts(
58+
http_session: requests.AuthorizedSession,
59+
proj_region: str,
60+
proj_id: str,
61+
proj_instance: str,
62+
start_time: str,
63+
end_time: str,
64+
rule_status: str,
65+
page_size: int,
66+
) -> Mapping[str, Any]:
67+
"""...
68+
69+
Args:
70+
http_session: Authorized session for HTTP requests.
71+
proj_region: region in which the target project is located
72+
proj_id: GCP project id or number which the target instance belongs to
73+
proj_instance: uuid of the instance (with dashes)
74+
start_time: A timestamp in RFC3339 UTC "Zulu" format, with nanosecond
75+
resolution and up to nine fractional digits.
76+
end_time: A timestamp in RFC3339 UTC "Zulu" format, with nanosecond
77+
resolution and up to nine fractional digits.
78+
rule_status: "ACTIVE", "ARCHIVED", or "ALL"
79+
page_size: if provided, ask for a specific amount of detections
80+
81+
Returns:
82+
a list of detections
83+
84+
Raises:
85+
requests.exceptions.HTTPError: HTTP request resulted in an error
86+
(response.status_code >= 400).
87+
"""
88+
base_url_with_region = regions.url_always_prepend_region(
89+
CHRONICLE_API_BASE_URL, args.region
90+
)
91+
# pylint: disable-next=line-too-long
92+
instance = f"projects/{proj_id}/locations/{proj_region}/instances/{proj_instance}"
93+
url = f"{base_url_with_region}/v1alpha/{instance}/legacy:legacySearchRulesAlerts"
94+
params = {"timeRange.start_time": start_time, "timeRange.end_time": end_time}
95+
if rule_status:
96+
pass
97+
if page_size:
98+
params["maxNumAlertsToReturn"] = page_size
99+
100+
# See API reference links at top of this file, for response format.
101+
response = http_session.request("GET", url, params=params)
102+
if response.status_code >= 400:
103+
print(response.text)
104+
response.raise_for_status()
105+
return response.json()
106+
107+
108+
if __name__ == "__main__":
109+
now = datetime.datetime.now()
110+
yesterday = now - datetime.timedelta(hours=24)
111+
# Format the datetime object into the desired string
112+
start_time_string = yesterday.strftime("%Y-%m-%dT%H:%M:%SZ")
113+
114+
parser = argparse.ArgumentParser()
115+
chronicle_auth.add_argument_credentials_file(parser)
116+
regions.add_argument_region(parser)
117+
project_instance.add_argument_project_instance(parser)
118+
project_id.add_argument_project_id(parser)
119+
parser.add_argument(
120+
"--start_time",
121+
type=str,
122+
required=False,
123+
default=start_time_string,
124+
)
125+
parser.add_argument(
126+
"--end_time",
127+
type=str,
128+
required=False,
129+
default=now.strftime("%Y-%m-%dT%H:%M:%SZ"),
130+
)
131+
parser.add_argument(
132+
"--rule_status",
133+
choices=RULE_STATUS,
134+
required=False,
135+
default="ALL",
136+
)
137+
parser.add_argument(
138+
"--page_size",
139+
type=int,
140+
required=False,
141+
default=10,
142+
)
143+
args = parser.parse_args()
144+
auth_session = chronicle_auth.initialize_http_session(
145+
args.credentials_file, SCOPES
146+
)
147+
print(
148+
json.dumps(
149+
search_rules_alerts(
150+
auth_session,
151+
args.region,
152+
args.project_id,
153+
args.project_instance,
154+
args.start_time,
155+
args.end_time,
156+
args.rule_status,
157+
args.page_size,
158+
),
159+
indent=2,
160+
)
161+
)

0 commit comments

Comments
 (0)