cartography 0.106.0rc2__py3-none-any.whl → 0.107.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of cartography might be problematic. Click here for more details.

Files changed (92) hide show
  1. cartography/_version.py +2 -2
  2. cartography/cli.py +131 -2
  3. cartography/config.py +42 -0
  4. cartography/driftdetect/cli.py +3 -2
  5. cartography/intel/airbyte/__init__.py +105 -0
  6. cartography/intel/airbyte/connections.py +120 -0
  7. cartography/intel/airbyte/destinations.py +81 -0
  8. cartography/intel/airbyte/organizations.py +59 -0
  9. cartography/intel/airbyte/sources.py +78 -0
  10. cartography/intel/airbyte/tags.py +64 -0
  11. cartography/intel/airbyte/users.py +106 -0
  12. cartography/intel/airbyte/util.py +122 -0
  13. cartography/intel/airbyte/workspaces.py +63 -0
  14. cartography/intel/aws/__init__.py +1 -0
  15. cartography/intel/aws/cloudtrail_management_events.py +364 -0
  16. cartography/intel/aws/cloudwatch.py +77 -0
  17. cartography/intel/aws/codebuild.py +132 -0
  18. cartography/intel/aws/ec2/subnets.py +1 -1
  19. cartography/intel/aws/ecs.py +17 -0
  20. cartography/intel/aws/inspector.py +77 -48
  21. cartography/intel/aws/resources.py +4 -0
  22. cartography/intel/aws/sns.py +62 -2
  23. cartography/intel/entra/users.py +84 -42
  24. cartography/intel/scaleway/__init__.py +127 -0
  25. cartography/intel/scaleway/iam/__init__.py +0 -0
  26. cartography/intel/scaleway/iam/apikeys.py +71 -0
  27. cartography/intel/scaleway/iam/applications.py +71 -0
  28. cartography/intel/scaleway/iam/groups.py +71 -0
  29. cartography/intel/scaleway/iam/users.py +71 -0
  30. cartography/intel/scaleway/instances/__init__.py +0 -0
  31. cartography/intel/scaleway/instances/flexibleips.py +86 -0
  32. cartography/intel/scaleway/instances/instances.py +92 -0
  33. cartography/intel/scaleway/projects.py +79 -0
  34. cartography/intel/scaleway/storage/__init__.py +0 -0
  35. cartography/intel/scaleway/storage/snapshots.py +86 -0
  36. cartography/intel/scaleway/storage/volumes.py +84 -0
  37. cartography/intel/scaleway/utils.py +37 -0
  38. cartography/intel/sentinelone/__init__.py +69 -0
  39. cartography/intel/sentinelone/account.py +140 -0
  40. cartography/intel/sentinelone/agent.py +139 -0
  41. cartography/intel/sentinelone/api.py +113 -0
  42. cartography/intel/sentinelone/application.py +248 -0
  43. cartography/intel/sentinelone/utils.py +28 -0
  44. cartography/models/airbyte/__init__.py +0 -0
  45. cartography/models/airbyte/connection.py +138 -0
  46. cartography/models/airbyte/destination.py +75 -0
  47. cartography/models/airbyte/organization.py +19 -0
  48. cartography/models/airbyte/source.py +75 -0
  49. cartography/models/airbyte/stream.py +74 -0
  50. cartography/models/airbyte/tag.py +69 -0
  51. cartography/models/airbyte/user.py +111 -0
  52. cartography/models/airbyte/workspace.py +46 -0
  53. cartography/models/aws/cloudtrail/management_events.py +64 -0
  54. cartography/models/aws/cloudwatch/log_metric_filter.py +79 -0
  55. cartography/models/aws/codebuild/__init__.py +0 -0
  56. cartography/models/aws/codebuild/project.py +49 -0
  57. cartography/models/aws/ec2/networkinterfaces.py +2 -0
  58. cartography/models/aws/ec2/subnet_instance.py +2 -0
  59. cartography/models/aws/ec2/subnet_networkinterface.py +2 -0
  60. cartography/models/aws/ecs/containers.py +19 -0
  61. cartography/models/aws/ecs/task_definitions.py +38 -0
  62. cartography/models/aws/ecs/tasks.py +24 -1
  63. cartography/models/aws/inspector/findings.py +37 -0
  64. cartography/models/aws/inspector/packages.py +1 -31
  65. cartography/models/aws/sns/topic_subscription.py +74 -0
  66. cartography/models/entra/user.py +17 -51
  67. cartography/models/scaleway/__init__.py +0 -0
  68. cartography/models/scaleway/iam/__init__.py +0 -0
  69. cartography/models/scaleway/iam/apikey.py +96 -0
  70. cartography/models/scaleway/iam/application.py +52 -0
  71. cartography/models/scaleway/iam/group.py +95 -0
  72. cartography/models/scaleway/iam/user.py +60 -0
  73. cartography/models/scaleway/instance/__init__.py +0 -0
  74. cartography/models/scaleway/instance/flexibleip.py +52 -0
  75. cartography/models/scaleway/instance/instance.py +118 -0
  76. cartography/models/scaleway/organization.py +19 -0
  77. cartography/models/scaleway/project.py +48 -0
  78. cartography/models/scaleway/storage/__init__.py +0 -0
  79. cartography/models/scaleway/storage/snapshot.py +78 -0
  80. cartography/models/scaleway/storage/volume.py +51 -0
  81. cartography/models/sentinelone/__init__.py +1 -0
  82. cartography/models/sentinelone/account.py +40 -0
  83. cartography/models/sentinelone/agent.py +50 -0
  84. cartography/models/sentinelone/application.py +44 -0
  85. cartography/models/sentinelone/application_version.py +96 -0
  86. cartography/sync.py +11 -4
  87. {cartography-0.106.0rc2.dist-info → cartography-0.107.0.dist-info}/METADATA +20 -16
  88. {cartography-0.106.0rc2.dist-info → cartography-0.107.0.dist-info}/RECORD +92 -28
  89. {cartography-0.106.0rc2.dist-info → cartography-0.107.0.dist-info}/WHEEL +0 -0
  90. {cartography-0.106.0rc2.dist-info → cartography-0.107.0.dist-info}/entry_points.txt +0 -0
  91. {cartography-0.106.0rc2.dist-info → cartography-0.107.0.dist-info}/licenses/LICENSE +0 -0
  92. {cartography-0.106.0rc2.dist-info → cartography-0.107.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,364 @@
1
+ import json
2
+ import logging
3
+ from datetime import datetime
4
+ from datetime import timedelta
5
+ from typing import Any
6
+ from typing import Dict
7
+ from typing import List
8
+
9
+ import boto3
10
+ import neo4j
11
+
12
+ from cartography.client.core.tx import load_matchlinks
13
+ from cartography.graph.job import GraphJob
14
+ from cartography.intel.aws.ec2.util import get_botocore_config
15
+ from cartography.models.aws.cloudtrail.management_events import AssumedRoleMatchLink
16
+ from cartography.util import aws_handle_regions
17
+ from cartography.util import timeit
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ @timeit
23
+ @aws_handle_regions
24
+ def get_assume_role_events(
25
+ boto3_session: boto3.Session, region: str, lookback_hours: int
26
+ ) -> List[Dict[str, Any]]:
27
+ """
28
+ Fetch CloudTrail AssumeRole events from the specified time period.
29
+
30
+ Focuses specifically on standard AssumeRole events, excluding SAML and WebIdentity variants.
31
+
32
+ :type boto3_session: boto3.Session
33
+ :param boto3_session: The boto3 session to use for API calls
34
+ :type region: str
35
+ :param region: The AWS region to fetch events from
36
+ :type lookback_hours: int
37
+ :param lookback_hours: Number of hours back to retrieve events from
38
+ :rtype: List[Dict[str, Any]]
39
+ :return: List of CloudTrail AssumeRole events
40
+ """
41
+ client = boto3_session.client(
42
+ "cloudtrail", region_name=region, config=get_botocore_config()
43
+ )
44
+
45
+ # Calculate time range
46
+ end_time = datetime.utcnow()
47
+ start_time = end_time - timedelta(hours=lookback_hours)
48
+
49
+ logger.info(
50
+ f"Fetching CloudTrail AssumeRole events for region '{region}' "
51
+ f"from {start_time} to {end_time} ({lookback_hours} hours)"
52
+ )
53
+
54
+ paginator = client.get_paginator("lookup_events")
55
+
56
+ page_iterator = paginator.paginate(
57
+ LookupAttributes=[
58
+ {"AttributeKey": "EventName", "AttributeValue": "AssumeRole"}
59
+ ],
60
+ StartTime=start_time,
61
+ EndTime=end_time,
62
+ PaginationConfig={
63
+ "MaxItems": 10000, # Reasonable limit to prevent excessive API calls
64
+ "PageSize": 50, # CloudTrail API limit per page
65
+ },
66
+ )
67
+
68
+ all_events = []
69
+ for page in page_iterator:
70
+ all_events.extend(page.get("Events", []))
71
+
72
+ logger.info(f"Retrieved {len(all_events)} AssumeRole events from region '{region}'")
73
+
74
+ return all_events
75
+
76
+
77
+ @timeit
78
+ def transform_assume_role_events_to_role_assumptions(
79
+ events: List[Dict[str, Any]],
80
+ region: str,
81
+ current_aws_account_id: str,
82
+ ) -> List[Dict[str, Any]]:
83
+ """
84
+ Transform raw CloudTrail AssumeRole events into aggregated role assumption relationships.
85
+
86
+ Focuses specifically on standard AssumeRole events, providing optimized processing
87
+ for the most common role assumption scenario.
88
+
89
+ This function performs the complete transformation pipeline:
90
+ 1. Extract role assumption events from CloudTrail AssumeRole data
91
+ 2. Aggregate events by (source_principal, destination_principal) pairs
92
+ 3. Return aggregated relationships ready for loading
93
+
94
+ :type events: List[Dict[str, Any]]
95
+ :param events: List of raw CloudTrail AssumeRole events from lookup_events API
96
+ :type region: str
97
+ :param region: The AWS region where events were retrieved from
98
+ :type current_aws_account_id: str
99
+ :param current_aws_account_id: The AWS account ID being synced
100
+ :rtype: List[Dict[str, Any]]
101
+ :return: List of aggregated role assumption relationships ready for loading
102
+ """
103
+ aggregated: Dict[tuple, Dict[str, Any]] = {}
104
+ logger.info(
105
+ f"Transforming {len(events)} CloudTrail AssumeRole events to role assumptions for region '{region}'"
106
+ )
107
+
108
+ for event in events:
109
+
110
+ cloudtrail_event = json.loads(event["CloudTrailEvent"])
111
+
112
+ if cloudtrail_event.get("userIdentity", {}).get("arn"):
113
+ source_principal = cloudtrail_event["userIdentity"]["arn"]
114
+ destination_principal = cloudtrail_event["requestParameters"]["roleArn"]
115
+ else:
116
+ logger.debug(
117
+ f"Skipping CloudTrail AssumeRole event due to missing UserIdentity.arn. Event: {event.get('EventId', 'unknown')}"
118
+ )
119
+ continue
120
+
121
+ destination_principal = cloudtrail_event["requestParameters"]["roleArn"]
122
+
123
+ normalized_source_principal = _convert_assumed_role_arn_to_role_arn(
124
+ source_principal
125
+ )
126
+ normalized_destination_principal = _convert_assumed_role_arn_to_role_arn(
127
+ destination_principal
128
+ )
129
+ event_time = event.get("EventTime")
130
+
131
+ key = (normalized_source_principal, normalized_destination_principal)
132
+
133
+ if key in aggregated:
134
+ aggregated[key]["times_used"] += 1
135
+ aggregated[key]["assume_role_count"] += 1 # All events are AssumeRole
136
+ # Handle None values safely for time comparisons
137
+ if event_time:
138
+ existing_first = aggregated[key]["first_seen_in_time_window"]
139
+ existing_last = aggregated[key]["last_used"]
140
+
141
+ if existing_first is None or event_time < existing_first:
142
+ aggregated[key]["first_seen_in_time_window"] = event_time
143
+ if existing_last is None or event_time > existing_last:
144
+ aggregated[key]["last_used"] = event_time
145
+ else:
146
+ aggregated[key] = {
147
+ "source_principal_arn": normalized_source_principal,
148
+ "destination_principal_arn": normalized_destination_principal,
149
+ "times_used": 1,
150
+ "first_seen_in_time_window": event_time,
151
+ "last_used": event_time,
152
+ "event_types": ["AssumeRole"],
153
+ "assume_role_count": 1,
154
+ "saml_count": 0,
155
+ "web_identity_count": 0,
156
+ }
157
+
158
+ return list(aggregated.values())
159
+
160
+
161
+ @timeit
162
+ def load_role_assumptions(
163
+ neo4j_session: neo4j.Session,
164
+ aggregated_role_assumptions: List[Dict[str, Any]],
165
+ current_aws_account_id: str,
166
+ aws_update_tag: int,
167
+ ) -> None:
168
+ """
169
+ Load aggregated role assumption relationships into Neo4j using MatchLink pattern.
170
+
171
+ Creates direct ASSUMED_ROLE relationships with aggregated properties:
172
+ (AWSUser|AWSRole|AWSPrincipal)-[:ASSUMED_ROLE {lastused, times_used, first_seen_in_time_window, last_seen}]->(AWSRole)
173
+
174
+ Assumes that both source principals and destination roles already exist in the graph.
175
+
176
+ :type neo4j_session: neo4j.Session
177
+ :param neo4j_session: The Neo4j session to use for database operations
178
+ :type aggregated_role_assumptions: List[Dict[str, Any]]
179
+ :param aggregated_role_assumptions: List of aggregated role assumption relationships from transform function
180
+ :type current_aws_account_id: str
181
+ :param current_aws_account_id: The AWS account ID being synced
182
+ :type aws_update_tag: int
183
+ :param aws_update_tag: Timestamp tag for tracking data freshness
184
+ :rtype: None
185
+ """
186
+ # Use MatchLink to create relationships between existing nodes
187
+ matchlink_schema = AssumedRoleMatchLink()
188
+
189
+ load_matchlinks(
190
+ neo4j_session,
191
+ matchlink_schema,
192
+ aggregated_role_assumptions,
193
+ lastupdated=aws_update_tag,
194
+ _sub_resource_label="AWSAccount",
195
+ _sub_resource_id=current_aws_account_id,
196
+ )
197
+
198
+ logger.info(
199
+ f"Successfully loaded {len(aggregated_role_assumptions)} role assumption relationships"
200
+ )
201
+
202
+
203
+ def _convert_assumed_role_arn_to_role_arn(assumed_role_arn: str) -> str:
204
+ """
205
+ Convert an assumed role ARN to the original role ARN.
206
+
207
+ Example:
208
+ Input: "arn:aws:sts::123456789012:assumed-role/MyRole/session-name"
209
+ Output: "arn:aws:iam::123456789012:role/MyRole"
210
+ """
211
+
212
+ # Split the ARN into parts
213
+ arn_parts = assumed_role_arn.split(":")
214
+ if len(arn_parts) >= 6 and arn_parts[2] == "sts" and "assumed-role" in arn_parts[5]:
215
+ # Extract account ID and role name
216
+ account_id = arn_parts[4]
217
+ resource_part = arn_parts[5] # "assumed-role/MyRole/session-name"
218
+ role_name = resource_part.split("/")[1] # Extract "MyRole"
219
+
220
+ # Construct the IAM role ARN
221
+ return f"arn:aws:iam::{account_id}:role/{role_name}"
222
+
223
+ # Return original ARN if conversion fails
224
+ return assumed_role_arn
225
+
226
+
227
+ @timeit
228
+ def cleanup(
229
+ neo4j_session: neo4j.Session, current_aws_account_id: str, update_tag: int
230
+ ) -> None:
231
+ """
232
+ Run CloudTrail management events cleanup job to remove stale ASSUMED_ROLE relationships.
233
+
234
+ :type neo4j_session: neo4j.Session
235
+ :param neo4j_session: The Neo4j session to use for database operations
236
+ :type current_aws_account_id: str
237
+ :param current_aws_account_id: The AWS account ID being synced
238
+ :type update_tag: int
239
+ :param update_tag: Timestamp tag for tracking data freshness
240
+ :rtype: None
241
+ """
242
+ logger.info("Running CloudTrail management events cleanup job.")
243
+
244
+ matchlink_schema = AssumedRoleMatchLink()
245
+ cleanup_job = GraphJob.from_matchlink(
246
+ matchlink_schema,
247
+ "AWSAccount",
248
+ current_aws_account_id,
249
+ update_tag,
250
+ )
251
+ cleanup_job.run(neo4j_session)
252
+
253
+
254
+ @timeit
255
+ def sync_assume_role_events(
256
+ neo4j_session: neo4j.Session,
257
+ boto3_session: boto3.Session,
258
+ regions: List[str],
259
+ current_aws_account_id: str,
260
+ update_tag: int,
261
+ common_job_parameters: Dict[str, Any],
262
+ ) -> None:
263
+ """
264
+ Sync CloudTrail management events to create ASSUMED_ROLE relationships.
265
+
266
+ This function orchestrates the complete process:
267
+ 1. Fetch CloudTrail management events region by region
268
+ 2. Transform events into role assumption records per region
269
+ 3. Load role assumption relationships into Neo4j for each region
270
+ 4. Run cleanup after processing all regions
271
+
272
+ The resulting graph contains direct relationships like:
273
+ (AWSUser|AWSRole|AWSPrincipal)-[:ASSUMED_ROLE {times_used, first_seen_in_time_window, last_used, lastused}]->(AWSRole)
274
+
275
+ :type neo4j_session: neo4j.Session
276
+ :param neo4j_session: The Neo4j session
277
+ :type boto3_session: boto3.Session
278
+ :param boto3_session: The boto3 session to use for API calls
279
+ :type regions: List[str]
280
+ :param regions: List of AWS regions to sync
281
+ :type current_aws_account_id: str
282
+ :param current_aws_account_id: The AWS account ID being synced
283
+ :type aws_update_tag: int
284
+ :param aws_update_tag: Timestamp tag for tracking data freshness
285
+ :rtype: None
286
+ """
287
+ # Extract lookback hours from common_job_parameters (set by CLI parameter)
288
+ lookback_hours = common_job_parameters.get(
289
+ "aws_cloudtrail_management_events_lookback_hours"
290
+ )
291
+
292
+ if not lookback_hours:
293
+ logger.info(
294
+ "CloudTrail management events sync skipped - no lookback period specified"
295
+ )
296
+ return
297
+
298
+ logger.info(
299
+ f"Syncing {len(regions)} regions with {lookback_hours} hour lookback period"
300
+ )
301
+
302
+ total_role_assumptions = 0
303
+
304
+ # Process events region by region
305
+ for region in regions:
306
+ logger.info(f"Processing CloudTrail events for region {region}")
307
+
308
+ # Process AssumeRole events specifically
309
+ logger.info(f"Fetching AssumeRole events specifically for region {region}")
310
+ assume_role_events = get_assume_role_events(
311
+ boto3_session=boto3_session,
312
+ region=region,
313
+ lookback_hours=lookback_hours,
314
+ )
315
+
316
+ # Transform AssumeRole events to role assumptions
317
+ assume_role_assumptions = transform_assume_role_events_to_role_assumptions(
318
+ events=assume_role_events,
319
+ region=region,
320
+ current_aws_account_id=current_aws_account_id,
321
+ )
322
+
323
+ # Load AssumeRole assumptions for this region
324
+ load_role_assumptions(
325
+ neo4j_session=neo4j_session,
326
+ aggregated_role_assumptions=assume_role_assumptions,
327
+ current_aws_account_id=current_aws_account_id,
328
+ aws_update_tag=update_tag,
329
+ )
330
+ total_role_assumptions += len(assume_role_assumptions)
331
+ logger.info(
332
+ f"Loaded {len(assume_role_assumptions)} AssumeRole assumptions for region {region}"
333
+ )
334
+
335
+ # Run cleanup for stale relationships after processing all regions
336
+ cleanup(neo4j_session, current_aws_account_id, update_tag)
337
+
338
+ logger.info(
339
+ f"CloudTrail management events sync completed successfully. "
340
+ f"Processed {total_role_assumptions} total role assumption events across {len(regions)} regions."
341
+ )
342
+
343
+
344
+ # Main sync function for when we decide to add more event types
345
+ @timeit
346
+ def sync(
347
+ neo4j_session: neo4j.Session,
348
+ boto3_session: boto3.Session,
349
+ regions: List[str],
350
+ current_aws_account_id: str,
351
+ update_tag: int,
352
+ common_job_parameters: Dict[str, Any],
353
+ ) -> None:
354
+ """
355
+ Main sync function for CloudTrail management events.
356
+ """
357
+ sync_assume_role_events(
358
+ neo4j_session=neo4j_session,
359
+ boto3_session=boto3_session,
360
+ regions=regions,
361
+ current_aws_account_id=current_aws_account_id,
362
+ update_tag=update_tag,
363
+ common_job_parameters=common_job_parameters,
364
+ )
@@ -9,6 +9,9 @@ import neo4j
9
9
  from cartography.client.core.tx import load
10
10
  from cartography.graph.job import GraphJob
11
11
  from cartography.intel.aws.ec2.util import get_botocore_config
12
+ from cartography.models.aws.cloudwatch.log_metric_filter import (
13
+ CloudWatchLogMetricFilterSchema,
14
+ )
12
15
  from cartography.models.aws.cloudwatch.loggroup import CloudWatchLogGroupSchema
13
16
  from cartography.util import aws_handle_regions
14
17
  from cartography.util import timeit
@@ -31,6 +34,47 @@ def get_cloudwatch_log_groups(
31
34
  return logGroups
32
35
 
33
36
 
37
+ @timeit
38
+ @aws_handle_regions
39
+ def get_cloudwatch_log_metric_filters(
40
+ boto3_session: boto3.Session, region: str
41
+ ) -> List[Dict[str, Any]]:
42
+ logs_client = boto3_session.client(
43
+ "logs", region_name=region, config=get_botocore_config()
44
+ )
45
+ paginator = logs_client.get_paginator("describe_metric_filters")
46
+ metric_filters = []
47
+
48
+ for page in paginator.paginate():
49
+ metric_filters.extend(page.get("metricFilters", []))
50
+
51
+ return metric_filters
52
+
53
+
54
+ def transform_metric_filters(
55
+ metric_filters: List[Dict[str, Any]], region: str
56
+ ) -> List[Dict[str, Any]]:
57
+ """
58
+ Transform CloudWatch log metric filter data for ingestion into Neo4j.
59
+ Ensures that the 'id' field is a unique combination of logGroupName and filterName.
60
+ """
61
+ transformed_filters = []
62
+ for filter in metric_filters:
63
+ transformed_filter = {
64
+ "id": f"{filter['logGroupName']}:{filter['filterName']}",
65
+ "arn": f"{filter['logGroupName']}:{filter['filterName']}",
66
+ "filterName": filter["filterName"],
67
+ "filterPattern": filter.get("filterPattern"),
68
+ "logGroupName": filter["logGroupName"],
69
+ "metricName": filter["metricTransformations"][0]["metricName"],
70
+ "metricNamespace": filter["metricTransformations"][0]["metricNamespace"],
71
+ "metricValue": filter["metricTransformations"][0]["metricValue"],
72
+ "Region": region,
73
+ }
74
+ transformed_filters.append(transformed_filter)
75
+ return transformed_filters
76
+
77
+
34
78
  @timeit
35
79
  def load_cloudwatch_log_groups(
36
80
  neo4j_session: neo4j.Session,
@@ -52,6 +96,27 @@ def load_cloudwatch_log_groups(
52
96
  )
53
97
 
54
98
 
99
+ @timeit
100
+ def load_cloudwatch_log_metric_filters(
101
+ neo4j_session: neo4j.Session,
102
+ data: List[Dict[str, Any]],
103
+ region: str,
104
+ current_aws_account_id: str,
105
+ aws_update_tag: int,
106
+ ) -> None:
107
+ logger.info(
108
+ f"Loading CloudWatch {len(data)} log metric filters for region '{region}' into graph.",
109
+ )
110
+ load(
111
+ neo4j_session,
112
+ CloudWatchLogMetricFilterSchema(),
113
+ data,
114
+ lastupdated=aws_update_tag,
115
+ Region=region,
116
+ AWS_ID=current_aws_account_id,
117
+ )
118
+
119
+
55
120
  @timeit
56
121
  def cleanup(
57
122
  neo4j_session: neo4j.Session,
@@ -62,6 +127,9 @@ def cleanup(
62
127
  CloudWatchLogGroupSchema(), common_job_parameters
63
128
  )
64
129
  cleanup_job.run(neo4j_session)
130
+ GraphJob.from_node_schema(
131
+ CloudWatchLogMetricFilterSchema(), common_job_parameters
132
+ ).run(neo4j_session)
65
133
 
66
134
 
67
135
  @timeit
@@ -90,4 +158,13 @@ def sync(
90
158
  update_tag,
91
159
  )
92
160
 
161
+ metric_filters = get_cloudwatch_log_metric_filters(boto3_session, region)
162
+ transformed_filters = transform_metric_filters(metric_filters, region)
163
+ load_cloudwatch_log_metric_filters(
164
+ neo4j_session,
165
+ transformed_filters,
166
+ region,
167
+ current_aws_account_id,
168
+ update_tag,
169
+ )
93
170
  cleanup(neo4j_session, common_job_parameters)
@@ -0,0 +1,132 @@
1
+ import logging
2
+ from typing import Any
3
+ from typing import Dict
4
+ from typing import List
5
+
6
+ import boto3
7
+ import neo4j
8
+
9
+ from cartography.client.core.tx import load
10
+ from cartography.graph.job import GraphJob
11
+ from cartography.intel.aws.ec2.util import get_botocore_config
12
+ from cartography.models.aws.codebuild.project import CodeBuildProjectSchema
13
+ from cartography.util import aws_handle_regions
14
+ from cartography.util import timeit
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ @timeit
20
+ @aws_handle_regions
21
+ def get_all_codebuild_projects(
22
+ boto3_session: boto3.Session, region: str
23
+ ) -> List[Dict[str, Any]]:
24
+
25
+ client = boto3_session.client(
26
+ "codebuild", region_name=region, config=get_botocore_config()
27
+ )
28
+ paginator = client.get_paginator("list_projects")
29
+
30
+ all_projects = []
31
+
32
+ for page in paginator.paginate():
33
+ project_names = page.get("projects", [])
34
+ if not project_names:
35
+ continue
36
+
37
+ # AWS batch_get_projects accepts up to 100 project names per call as per AWS documentation.
38
+ for i in range(0, len(project_names), 100):
39
+ batch = project_names[i : i + 100]
40
+ response = client.batch_get_projects(names=batch)
41
+ projects = response.get("projects", [])
42
+ all_projects.extend(projects)
43
+ return all_projects
44
+
45
+
46
+ def transform_codebuild_projects(
47
+ projects: List[Dict[str, Any]], region: str
48
+ ) -> List[Dict[str, Any]]:
49
+ """
50
+ Transform CodeBuild project data for ingestion into Neo4j.
51
+
52
+ - Includes all environment variable names.
53
+ - Variables of type 'PLAINTEXT' retain their values.
54
+ - Other types (e.g., 'PARAMETER_STORE', 'SECRETS_MANAGER') have their values redacted.
55
+ """
56
+ transformed_codebuild_projects = []
57
+ for project in projects:
58
+ env_vars = project.get("environment", {}).get("environmentVariables", [])
59
+ env_var_strings = [
60
+ f"{var.get('name')}={var.get('value') if var.get('type') == 'PLAINTEXT' else '<REDACTED>'}"
61
+ for var in env_vars
62
+ ]
63
+ transformed_project = {
64
+ "arn": project["arn"],
65
+ "created": project.get("created"),
66
+ "environmentVariables": env_var_strings,
67
+ "sourceType": project.get("source", {}).get("type"),
68
+ "sourceLocation": project.get("source", {}).get("location"),
69
+ }
70
+ transformed_codebuild_projects.append(transformed_project)
71
+
72
+ return transformed_codebuild_projects
73
+
74
+
75
+ @timeit
76
+ def load_codebuild_projects(
77
+ neo4j_session: neo4j.Session,
78
+ data: List[Dict[str, Any]],
79
+ region: str,
80
+ current_aws_account_id: str,
81
+ aws_update_tag: int,
82
+ ) -> None:
83
+ logger.info(
84
+ f"Loading CodeBuild {len(data)} projects for region '{region}' into graph.",
85
+ )
86
+ load(
87
+ neo4j_session,
88
+ CodeBuildProjectSchema(),
89
+ data,
90
+ lastupdated=aws_update_tag,
91
+ Region=region,
92
+ AWS_ID=current_aws_account_id,
93
+ )
94
+
95
+
96
+ @timeit
97
+ def cleanup(
98
+ neo4j_session: neo4j.Session,
99
+ common_job_parameters: Dict[str, Any],
100
+ ) -> None:
101
+ logger.debug("Running Efs cleanup job.")
102
+ GraphJob.from_node_schema(CodeBuildProjectSchema(), common_job_parameters).run(
103
+ neo4j_session
104
+ )
105
+
106
+
107
+ @timeit
108
+ def sync(
109
+ neo4j_session: neo4j.Session,
110
+ boto3_session: boto3.session.Session,
111
+ regions: List[str],
112
+ current_aws_account_id: str,
113
+ update_tag: int,
114
+ common_job_parameters: Dict[str, Any],
115
+ ) -> None:
116
+ for region in regions:
117
+ logger.info(
118
+ f"Syncing CodeBuild for region '{region}' in account '{current_aws_account_id}'.",
119
+ )
120
+
121
+ projects = get_all_codebuild_projects(boto3_session, region)
122
+ transformed_projects = transform_codebuild_projects(projects, region)
123
+
124
+ load_codebuild_projects(
125
+ neo4j_session,
126
+ transformed_projects,
127
+ region,
128
+ current_aws_account_id,
129
+ update_tag,
130
+ )
131
+
132
+ cleanup(neo4j_session, common_job_parameters)
@@ -53,7 +53,7 @@ def load_subnets(
53
53
  snet.state = subnet.State, snet.assignipv6addressoncreation = subnet.AssignIpv6AddressOnCreation,
54
54
  snet.map_public_ip_on_launch = subnet.MapPublicIpOnLaunch, snet.subnet_arn = subnet.SubnetArn,
55
55
  snet.availability_zone = subnet.AvailabilityZone, snet.availability_zone_id = subnet.AvailabilityZoneId,
56
- snet.subnetid = subnet.SubnetId
56
+ snet.subnet_id = subnet.SubnetId
57
57
  """
58
58
 
59
59
  ingest_subnet_vpc_relations = """
@@ -169,6 +169,22 @@ def _get_containers_from_tasks(tasks: list[dict[str, Any]]) -> list[dict[str, An
169
169
  return containers
170
170
 
171
171
 
172
+ def transform_ecs_tasks(tasks: list[dict[str, Any]]) -> list[dict[str, Any]]:
173
+ """
174
+ Extract network interface ID from task attachments.
175
+ """
176
+ for task in tasks:
177
+ for attachment in task.get("attachments", []):
178
+ if attachment.get("type") == "ElasticNetworkInterface":
179
+ details = attachment.get("details", [])
180
+ for detail in details:
181
+ if detail.get("name") == "networkInterfaceId":
182
+ task["networkInterfaceId"] = detail.get("value")
183
+ break
184
+ break
185
+ return tasks
186
+
187
+
172
188
  @timeit
173
189
  def load_ecs_clusters(
174
190
  neo4j_session: neo4j.Session,
@@ -407,6 +423,7 @@ def _sync_ecs_task_and_container_defns(
407
423
  boto3_session,
408
424
  region,
409
425
  )
426
+ tasks = transform_ecs_tasks(tasks)
410
427
  containers = _get_containers_from_tasks(tasks)
411
428
  load_ecs_tasks(
412
429
  neo4j_session,