Debian Codegraph @

ansible_collections/amazon/aws/extensions/eda/plugins/event_source/aws_cloudtrail.py

raw
1 import asyncio
2 import datetime
3 import json
4 from typing import TYPE_CHECKING, Any, cast
5
6 from aiobotocore.session import get_session
7 from botocore.client import BaseClient
8
9 if TYPE_CHECKING:
10 from collections.abc import Awaitable
11
12 DOCUMENTATION = r"""
13 ---
14 short_description: Receive events from an AWS CloudTrail
15 description:
16 - An ansible-rulebook event source module for getting events from an AWS CloudTrail.
17 - >
18 This supports all the authentication methods supported by boto3 library:
19 U(https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html).
20 options:
21 access_key:
22 description:
23 - Optional AWS access key ID.
24 type: str
25 secret_key:
26 description:
27 - Optional AWS secret access key.
28 type: str
29 session_token:
30 description:
31 - Optional STS session token for use with temporary credentials.
32 type: str
33 endpoint_url:
34 description:
35 - Optional URL to connect to instead of the default AWS endpoints.
36 type: str
37 region:
38 description:
39 - Optional AWS region to use.
40 type: str
41 delay_seconds:
42 description:
43 - The number of seconds to wait between polling.
44 type: int
45 default: 10
46 lookup_attributes:
47 description:
48 - The optional list of lookup attributes.
49 - A lookup attribute is a dictionary containing an AttributeKey (string),
50 which specifies the attribute used to filter returned events, and an
51 AttributeValue (string), which defines the value for the specified AttributeKey.
52 type: list
53 elements: str
54 event_category:
55 description:
56 - The optional event category to return. (e.g. 'insight')
57 type: str
58 """
59
60 EXAMPLES = r"""
61 - amazon.aws.aws_cloudtrail:
62 region: us-east-1
63 lookup_attributes:
64 - AttributeKey: 'EventSource'
65 AttributeValue: 'ec2.amazonaws.com'
66 - AttributeKey: 'ReadOnly'
67 AttributeValue: 'true'
68 event_category: management
69 """
70
71
72 def _cloudtrail_event_to_dict(event: dict[str, Any]) -> dict[str, Any]:
73 event["EventTime"] = event["EventTime"].isoformat()
74 event["CloudTrailEvent"] = json.loads(event["CloudTrailEvent"])
75 return event
76
77
78 def _get_events(
79 events: list[dict[str, Any]],
80 last_event_ids: list[str],
81 ) -> tuple[list[dict[str, Any]], Any, list[str]]:
82 event_time = None
83 event_ids = []
84 result = []
85 for event in events:
86 # skip last event
87 if last_event_ids and event["EventId"] in last_event_ids:
88 continue
89 if event_time is None or event_time < event["EventTime"]:
90 event_time = event["EventTime"]
91 event_ids = [event["EventId"]]
92 elif event_time == event["EventTime"]:
93 event_ids.append(event["EventId"])
94 result.append(event)
95 return result, event_time, event_ids
96
97
98 async def _get_cloudtrail_events(
99 client: BaseClient,
100 params: dict[str, Any],
101 ) -> list[dict[str, Any]]:
102 paginator = client.get_paginator("lookup_events")
103 results: dict[str, Any] = await cast(
104 "Awaitable[dict[str, Any]]",
105 paginator.paginate(**params).build_full_result(),
106 )
107 events = results.get("Events", [])
108 # type guards:
109 if not isinstance(events, list):
110 err_msg = "Events is not a list"
111 raise TypeError(err_msg)
112 for event in events:
113 if not isinstance(event, dict):
114 err_msg = "Event is not a dictionary"
115 raise TypeError(err_msg)
116 return events
117
118
119 ARGS_MAPPING = {
120 "lookup_attributes": "LookupAttributes",
121 "event_category": "EventCategory",
122 }
123
124
125 async def main(queue: asyncio.Queue[Any], args: dict[str, Any]) -> None:
126 """Receive events via AWS CloudTrail."""
127 delay = int(args.get("delay_seconds", 10))
128
129 session = get_session()
130 params = {}
131 for key, value in ARGS_MAPPING.items():
132 if args.get(key) is not None:
133 params[value] = args.get(key)
134
135 params["StartTime"] = datetime.datetime.now(tz=datetime.timezone.utc)
136
137 async with session.create_client("cloudtrail", **connection_args(args)) as client:
138 event_time = None
139 event_ids: list[str] = []
140 while True:
141 if event_time is not None:
142 params["StartTime"] = event_time
143 events = await _get_cloudtrail_events(client, params)
144
145 events, c_event_time, c_event_ids = _get_events(events, event_ids)
146 for event in events:
147 await queue.put(_cloudtrail_event_to_dict(event))
148
149 event_ids = c_event_ids or event_ids
150 event_time = c_event_time or event_time
151
152 await asyncio.sleep(delay)
153
154
155 def connection_args(args: dict[str, Any]) -> dict[str, Any]:
156 """Provide connection arguments to AWS CloudTrail."""
157 selected_args = {}
158
159 # Best Practice: get credentials from ~/.aws/credentials or the environment
160 # However the following method are still possible
161 if "access_key" in args:
162 selected_args["aws_access_key_id"] = args["access_key"]
163 if "secret_key" in args:
164 selected_args["aws_secret_access_key"] = args["secret_key"]
165 if "session_token" in args:
166 selected_args["aws_session_token"] = args["session_token"]
167
168 if "endpoint_url" in args:
169 selected_args["endpoint_url"] = args["endpoint_url"]
170 if "region" in args:
171 selected_args["region_name"] = args["region"]
172 return selected_args
173
174
175 if __name__ == "__main__":
176 """MockQueue if running directly."""
177
178 class MockQueue(asyncio.Queue[Any]):
179 """A fake queue."""
180
181 async def put(self: "MockQueue", event: dict[str, Any]) -> None:
182 """Print the event."""
183 print(event) # noqa: T201
184
185 asyncio.run(main(MockQueue(), {}))