cartography 0.103.0rc1__py3-none-any.whl → 0.104.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 (75) hide show
  1. cartography/_version.py +2 -2
  2. cartography/cli.py +97 -1
  3. cartography/config.py +28 -0
  4. cartography/graph/cleanupbuilder.py +151 -41
  5. cartography/intel/anthropic/__init__.py +62 -0
  6. cartography/intel/anthropic/apikeys.py +72 -0
  7. cartography/intel/anthropic/users.py +75 -0
  8. cartography/intel/anthropic/util.py +51 -0
  9. cartography/intel/anthropic/workspaces.py +95 -0
  10. cartography/intel/aws/cloudtrail.py +3 -38
  11. cartography/intel/aws/cloudwatch.py +93 -0
  12. cartography/intel/aws/ec2/load_balancer_v2s.py +4 -1
  13. cartography/intel/aws/resources.py +2 -0
  14. cartography/intel/aws/secretsmanager.py +150 -3
  15. cartography/intel/aws/ssm.py +71 -0
  16. cartography/intel/cloudflare/__init__.py +74 -0
  17. cartography/intel/cloudflare/accounts.py +57 -0
  18. cartography/intel/cloudflare/dnsrecords.py +64 -0
  19. cartography/intel/cloudflare/members.py +75 -0
  20. cartography/intel/cloudflare/roles.py +65 -0
  21. cartography/intel/cloudflare/zones.py +64 -0
  22. cartography/intel/entra/ou.py +21 -5
  23. cartography/intel/openai/__init__.py +86 -0
  24. cartography/intel/openai/adminapikeys.py +89 -0
  25. cartography/intel/openai/apikeys.py +96 -0
  26. cartography/intel/openai/projects.py +97 -0
  27. cartography/intel/openai/serviceaccounts.py +82 -0
  28. cartography/intel/openai/users.py +75 -0
  29. cartography/intel/openai/util.py +45 -0
  30. cartography/intel/tailscale/__init__.py +77 -0
  31. cartography/intel/tailscale/acls.py +146 -0
  32. cartography/intel/tailscale/devices.py +127 -0
  33. cartography/intel/tailscale/postureintegrations.py +81 -0
  34. cartography/intel/tailscale/tailnets.py +76 -0
  35. cartography/intel/tailscale/users.py +80 -0
  36. cartography/intel/tailscale/utils.py +132 -0
  37. cartography/models/anthropic/__init__.py +0 -0
  38. cartography/models/anthropic/apikey.py +90 -0
  39. cartography/models/anthropic/organization.py +19 -0
  40. cartography/models/anthropic/user.py +48 -0
  41. cartography/models/anthropic/workspace.py +90 -0
  42. cartography/models/aws/cloudtrail/trail.py +24 -0
  43. cartography/models/aws/cloudwatch/__init__.py +0 -0
  44. cartography/models/aws/cloudwatch/loggroup.py +52 -0
  45. cartography/models/aws/secretsmanager/__init__.py +0 -0
  46. cartography/models/aws/secretsmanager/secret_version.py +116 -0
  47. cartography/models/aws/ssm/parameters.py +84 -0
  48. cartography/models/cloudflare/__init__.py +0 -0
  49. cartography/models/cloudflare/account.py +25 -0
  50. cartography/models/cloudflare/dnsrecord.py +55 -0
  51. cartography/models/cloudflare/member.py +82 -0
  52. cartography/models/cloudflare/role.py +44 -0
  53. cartography/models/cloudflare/zone.py +59 -0
  54. cartography/models/core/nodes.py +15 -2
  55. cartography/models/openai/__init__.py +0 -0
  56. cartography/models/openai/adminapikey.py +90 -0
  57. cartography/models/openai/apikey.py +84 -0
  58. cartography/models/openai/organization.py +17 -0
  59. cartography/models/openai/project.py +89 -0
  60. cartography/models/openai/serviceaccount.py +50 -0
  61. cartography/models/openai/user.py +49 -0
  62. cartography/models/tailscale/__init__.py +0 -0
  63. cartography/models/tailscale/device.py +95 -0
  64. cartography/models/tailscale/group.py +86 -0
  65. cartography/models/tailscale/postureintegration.py +58 -0
  66. cartography/models/tailscale/tag.py +102 -0
  67. cartography/models/tailscale/tailnet.py +29 -0
  68. cartography/models/tailscale/user.py +52 -0
  69. cartography/sync.py +8 -0
  70. {cartography-0.103.0rc1.dist-info → cartography-0.104.0.dist-info}/METADATA +8 -4
  71. {cartography-0.103.0rc1.dist-info → cartography-0.104.0.dist-info}/RECORD +75 -19
  72. {cartography-0.103.0rc1.dist-info → cartography-0.104.0.dist-info}/WHEEL +1 -1
  73. {cartography-0.103.0rc1.dist-info → cartography-0.104.0.dist-info}/entry_points.txt +0 -0
  74. {cartography-0.103.0rc1.dist-info → cartography-0.104.0.dist-info}/licenses/LICENSE +0 -0
  75. {cartography-0.103.0rc1.dist-info → cartography-0.104.0.dist-info}/top_level.txt +0 -0
cartography/_version.py CHANGED
@@ -17,5 +17,5 @@ __version__: str
17
17
  __version_tuple__: VERSION_TUPLE
18
18
  version_tuple: VERSION_TUPLE
19
19
 
20
- __version__ = version = '0.103.0rc1'
21
- __version_tuple__ = version_tuple = (0, 103, 0, 'rc1')
20
+ __version__ = version = '0.104.0'
21
+ __version_tuple__ = version_tuple = (0, 104, 0)
cartography/cli.py CHANGED
@@ -561,7 +561,7 @@ class CLI:
561
561
  type=str,
562
562
  default=None,
563
563
  help=(
564
- "Your SnipeIT base URI"
564
+ "Your SnipeIT base URI. "
565
565
  "Required if you are using the SnipeIT intel module. Ignored otherwise."
566
566
  ),
567
567
  )
@@ -577,6 +577,66 @@ class CLI:
577
577
  default=None,
578
578
  help="An ID for the SnipeIT tenant.",
579
579
  )
580
+ parser.add_argument(
581
+ "--cloudflare-token-env-var",
582
+ type=str,
583
+ default=None,
584
+ help="The name of an environment variable containing ApiKey with which to authenticate to Cloudflare.",
585
+ )
586
+ parser.add_argument(
587
+ "--tailscale-token-env-var",
588
+ type=str,
589
+ default=None,
590
+ help=(
591
+ "The name of an environment variable containing a Tailscale API token. "
592
+ "Required if you are using the Tailscale intel module. Ignored otherwise."
593
+ ),
594
+ )
595
+ parser.add_argument(
596
+ "--tailscale-org",
597
+ type=str,
598
+ default=None,
599
+ help=(
600
+ "The name of the Tailscale organization to sync. "
601
+ "Required if you are using the Tailscale intel module. Ignored otherwise."
602
+ ),
603
+ )
604
+ parser.add_argument(
605
+ "--tailscale-base-url",
606
+ type=str,
607
+ default="https://api.tailscale.com/api/v2",
608
+ help=(
609
+ "The base URL for the Tailscale API. "
610
+ "Required if you are using the Tailscale intel module. Ignored otherwise."
611
+ ),
612
+ )
613
+ parser.add_argument(
614
+ "--openai-apikey-env-var",
615
+ type=str,
616
+ default=None,
617
+ help=(
618
+ "The name of an environment variable containing a OpenAI API Key. "
619
+ "Required if you are using the OpenAI intel module. Ignored otherwise."
620
+ ),
621
+ )
622
+ parser.add_argument(
623
+ "--openai-org-id",
624
+ type=str,
625
+ default=None,
626
+ help=(
627
+ "The ID of the OpenAI organization to sync. "
628
+ "Required if you are using the OpenAI intel module. Ignored otherwise."
629
+ ),
630
+ )
631
+ parser.add_argument(
632
+ "--anthropic-apikey-env-var",
633
+ type=str,
634
+ default=None,
635
+ help=(
636
+ "The name of an environment variable containing an Anthropic API Key. "
637
+ "Required if you are using the Anthropic intel module. Ignored otherwise."
638
+ ),
639
+ )
580
640
 
581
641
  return parser
582
642
 
@@ -859,6 +919,42 @@ class CLI:
859
919
  logger.warning("A SnipeIT base URI was not provided.")
860
920
  config.snipeit_base_uri = None
861
921
 
922
+ # Tailscale config
923
+ if config.tailscale_token_env_var:
924
+ logger.debug(
925
+ f"Reading Tailscale API token from environment variable {config.tailscale_token_env_var}",
926
+ )
927
+ config.tailscale_token = os.environ.get(config.tailscale_token_env_var)
928
+ else:
929
+ config.tailscale_token = None
930
+
931
+ # Cloudflare config
932
+ if config.cloudflare_token_env_var:
933
+ logger.debug(
934
+ f"Reading Cloudflare ApiKey from environment variable {config.cloudflare_token_env_var}",
935
+ )
936
+ config.cloudflare_token = os.environ.get(config.cloudflare_token_env_var)
937
+ else:
938
+ config.cloudflare_token = None
939
+
940
+ # OpenAI config
941
+ if config.openai_apikey_env_var:
942
+ logger.debug(
943
+ f"Reading OpenAI API key from environment variable {config.openai_apikey_env_var}",
944
+ )
945
+ config.openai_apikey = os.environ.get(config.openai_apikey_env_var)
946
+ else:
947
+ config.openai_apikey = None
948
+
949
+ # Anthropic config
950
+ if config.anthropic_apikey_env_var:
951
+ logger.debug(
952
+ f"Reading Anthropic API key from environment variable {config.anthropic_apikey_env_var}",
953
+ )
954
+ config.anthropic_apikey = os.environ.get(config.anthropic_apikey_env_var)
955
+ else:
956
+ config.anthropic_apikey = None
957
+
862
958
  # Run cartography
863
959
  try:
864
960
  return cartography.sync.run_with_config(self.sync, config)
cartography/config.py CHANGED
@@ -123,6 +123,20 @@ class Config:
123
123
  :param snipeit_token: Token used to authenticate to the SnipeIT data provider. Optional.
124
124
  :type snipeit_tenant_id: string
125
125
  :param snipeit_tenant_id: Token used to authenticate to the SnipeIT data provider. Optional.
126
+ :type tailscale_token: str
127
+ :param tailscale_token: Tailscale API token. Optional.
128
+ :type tailscale_org: str
129
+ :param tailscale_org: Tailscale organization name. Optional.
130
+ :type tailscale_base_url: str
131
+ :param tailscale_base_url: Tailscale API base URL. Optional.
132
+ :type cloudflare_token: string
133
+ :param cloudflare_token: Cloudflare API key. Optional.
134
+ :type openai_apikey: string
135
+ :param openai_apikey: OpenAI API key. Optional.
136
+ :type openai_org_id: string
137
+ :param openai_org_id: OpenAI organization id. Optional.
138
+ :type anthropic_apikey: string
139
+ :param anthropic_apikey: Anthropic API key. Optional.
126
140
  """
127
141
 
128
142
  def __init__(
@@ -188,6 +202,13 @@ class Config:
188
202
  snipeit_base_uri=None,
189
203
  snipeit_token=None,
190
204
  snipeit_tenant_id=None,
205
+ tailscale_token=None,
206
+ tailscale_org=None,
207
+ tailscale_base_url=None,
208
+ cloudflare_token=None,
209
+ openai_apikey=None,
210
+ openai_org_id=None,
211
+ anthropic_apikey=None,
191
212
  ):
192
213
  self.neo4j_uri = neo4j_uri
193
214
  self.neo4j_user = neo4j_user
@@ -250,3 +271,10 @@ class Config:
250
271
  self.snipeit_base_uri = snipeit_base_uri
251
272
  self.snipeit_token = snipeit_token
252
273
  self.snipeit_tenant_id = snipeit_tenant_id
274
+ self.tailscale_token = tailscale_token
275
+ self.tailscale_org = tailscale_org
276
+ self.tailscale_base_url = tailscale_base_url
277
+ self.cloudflare_token = cloudflare_token
278
+ self.openai_apikey = openai_apikey
279
+ self.openai_org_id = openai_org_id
280
+ self.anthropic_apikey = anthropic_apikey
@@ -15,33 +15,40 @@ from cartography.models.core.relationships import TargetNodeMatcher
15
15
  def build_cleanup_queries(node_schema: CartographyNodeSchema) -> List[str]:
16
16
  """
17
17
  Generates queries to clean up stale nodes and relationships from the given CartographyNodeSchema.
18
+ Properly handles cases where a node schema has a scoped cleanup or not.
18
19
  Note that auto-cleanups for a node with no relationships is not currently supported.
19
-
20
- Algorithm:
21
- 1. If node_schema has no relationships at all, return empty.
22
-
23
- Otherwise,
24
-
25
- 1. If node_schema doesn't have a sub_resource relationship, generate queries only to clean up its other
26
- relationships. No nodes will be cleaned up.
27
-
28
- Otherwise,
29
-
30
- 1. First delete all stale nodes attached to the node_schema's sub resource
31
- 2. Delete all stale node to sub resource relationships
32
- - We don't expect this to be very common (never for AWS resources, at least), but in case it is possible for an
33
- asset to change sub resources, we want to handle it properly.
34
- 3. For all relationships defined on the node schema, delete all stale ones.
35
20
  :param node_schema: The given CartographyNodeSchema
36
21
  :return: A list of Neo4j queries to clean up nodes and relationships.
37
22
  """
23
+ # If the node has no relationships, do not delete the node. Leave this behind for the user to manage.
24
+ # Oftentimes these are SyncMetadata nodes.
38
25
  if (
39
26
  not node_schema.sub_resource_relationship
40
27
  and not node_schema.other_relationships
41
28
  ):
42
29
  return []
43
30
 
44
- if not node_schema.sub_resource_relationship:
31
+ # Case 1 [Standard]: the node has a sub resource and scoped cleanup is true => clean up stale nodes
32
+ # of this type, scoped to the sub resource. Continue on to clean up the other_relationships too.
33
+ if node_schema.sub_resource_relationship and node_schema.scoped_cleanup:
34
+ queries = _build_cleanup_node_and_rel_queries(
35
+ node_schema,
36
+ node_schema.sub_resource_relationship,
37
+ )
38
+
39
+ # Case 2: The node has a sub resource but scoped cleanup is false => this does not make sense
40
+ # because if have a sub resource, we are implying that we are doing scoped cleanup.
41
+ elif node_schema.sub_resource_relationship and not node_schema.scoped_cleanup:
42
+ raise ValueError(
43
+ f"This is not expected: {node_schema.label} has a sub_resource_relationship but scoped_cleanup=False."
44
+ "Please check the class definition for this node schema. It doesn't make sense for a node to have a "
45
+ "sub resource relationship and an unscoped cleanup. Doing this will cause all stale nodes of this type "
46
+ "to be deleted regardless of the sub resource they are attached to."
47
+ )
48
+
49
+ # Case 3: The node has no sub resource but scoped cleanup is true => do not delete any nodes, but clean up stale relationships.
50
+ # Return early.
51
+ elif not node_schema.sub_resource_relationship and node_schema.scoped_cleanup:
45
52
  queries = []
46
53
  other_rels = (
47
54
  node_schema.other_relationships.rels
@@ -53,17 +60,20 @@ def build_cleanup_queries(node_schema: CartographyNodeSchema) -> List[str]:
53
60
  queries.append(query)
54
61
  return queries
55
62
 
56
- result = _build_cleanup_node_and_rel_queries(
57
- node_schema,
58
- node_schema.sub_resource_relationship,
59
- )
63
+ # Case 4: The node has no sub resource and scoped cleanup is false => clean up the stale nodes. Continue on to clean up the other_relationships too.
64
+ else:
65
+ queries = [_build_cleanup_node_query_unscoped(node_schema)]
66
+
60
67
  if node_schema.other_relationships:
61
68
  for rel in node_schema.other_relationships.rels:
62
- # [0] is the delete node query, [1] is the delete relationship query. We only want the latter.
63
- _, rel_query = _build_cleanup_node_and_rel_queries(node_schema, rel)
64
- result.append(rel_query)
69
+ if node_schema.scoped_cleanup:
70
+ # [0] is the delete node query, [1] is the delete relationship query. We only want the latter.
71
+ _, rel_query = _build_cleanup_node_and_rel_queries(node_schema, rel)
72
+ queries.append(rel_query)
73
+ else:
74
+ queries.append(_build_cleanup_rel_queries_unscoped(node_schema, rel))
65
75
 
66
- return result
76
+ return queries
67
77
 
68
78
 
69
79
  def _build_cleanup_rel_query_no_sub_resource(
@@ -94,6 +104,46 @@ def _build_cleanup_rel_query_no_sub_resource(
94
104
  )
95
105
 
96
106
 
107
+ def _build_match_statement_for_cleanup(node_schema: CartographyNodeSchema) -> str:
108
+ """
109
+ Helper function to build a MATCH statement for a given node schema for cleanup.
110
+ """
111
+ if not node_schema.sub_resource_relationship and not node_schema.scoped_cleanup:
112
+ template = Template("MATCH (n:$node_label)")
113
+ return template.safe_substitute(
114
+ node_label=node_schema.label,
115
+ )
116
+
117
+ # if it has a sub resource relationship defined, we need to match on the sub resource to make sure we only delete
118
+ # nodes that are attached to the sub resource.
119
+ template = Template(
120
+ "MATCH (n:$node_label)$sub_resource_link(:$sub_resource_label{$match_sub_res_clause})"
121
+ )
122
+ sub_resource_link = ""
123
+ sub_resource_label = ""
124
+ match_sub_res_clause = ""
125
+
126
+ if node_schema.sub_resource_relationship:
127
+ # Draw sub resource rel with correct direction
128
+ if node_schema.sub_resource_relationship.direction == LinkDirection.INWARD:
129
+ sub_resource_link_template = Template("<-[s:$SubResourceRelLabel]-")
130
+ else:
131
+ sub_resource_link_template = Template("-[s:$SubResourceRelLabel]->")
132
+ sub_resource_link = sub_resource_link_template.safe_substitute(
133
+ SubResourceRelLabel=node_schema.sub_resource_relationship.rel_label,
134
+ )
135
+ sub_resource_label = node_schema.sub_resource_relationship.target_node_label
136
+ match_sub_res_clause = _build_match_clause(
137
+ node_schema.sub_resource_relationship.target_node_matcher,
138
+ )
139
+ return template.safe_substitute(
140
+ node_label=node_schema.label,
141
+ sub_resource_link=sub_resource_link,
142
+ sub_resource_label=sub_resource_label,
143
+ match_sub_res_clause=match_sub_res_clause,
144
+ )
145
+
146
+
97
147
  def _build_cleanup_node_and_rel_queries(
98
148
  node_schema: CartographyNodeSchema,
99
149
  selected_relationship: CartographyRelSchema,
@@ -120,15 +170,6 @@ def _build_cleanup_node_and_rel_queries(
120
170
  "verify the node class definition for the relationships that it has.",
121
171
  )
122
172
 
123
- # Draw sub resource rel with correct direction
124
- if node_schema.sub_resource_relationship.direction == LinkDirection.INWARD:
125
- sub_resource_link_template = Template("<-[s:$SubResourceRelLabel]-")
126
- else:
127
- sub_resource_link_template = Template("-[s:$SubResourceRelLabel]->")
128
- sub_resource_link = sub_resource_link_template.safe_substitute(
129
- SubResourceRelLabel=node_schema.sub_resource_relationship.rel_label,
130
- )
131
-
132
173
  # The cleanup node query must always be before the cleanup rel query
133
174
  delete_action_clauses = [
134
175
  """
@@ -161,19 +202,14 @@ def _build_cleanup_node_and_rel_queries(
161
202
  # Ensure the node is attached to the sub resource and delete the node
162
203
  query_template = Template(
163
204
  """
164
- MATCH (n:$node_label)$sub_resource_link(:$sub_resource_label{$match_sub_res_clause})
205
+ $match_statement
165
206
  $selected_rel_clause
166
207
  $delete_action_clause
167
208
  """,
168
209
  )
169
210
  return [
170
211
  query_template.safe_substitute(
171
- node_label=node_schema.label,
172
- sub_resource_link=sub_resource_link,
173
- sub_resource_label=node_schema.sub_resource_relationship.target_node_label,
174
- match_sub_res_clause=_build_match_clause(
175
- node_schema.sub_resource_relationship.target_node_matcher,
176
- ),
212
+ match_statement=_build_match_statement_for_cleanup(node_schema),
177
213
  selected_rel_clause=(
178
214
  ""
179
215
  if selected_relationship == node_schema.sub_resource_relationship
@@ -185,6 +221,80 @@ def _build_cleanup_node_and_rel_queries(
185
221
  ]
186
222
 
187
223
 
224
+ def _build_cleanup_node_query_unscoped(
225
+ node_schema: CartographyNodeSchema,
226
+ ) -> str:
227
+ """
228
+ Generates a cleanup query for a node_schema to allow unscoped cleanup.
229
+ """
230
+ if node_schema.scoped_cleanup:
231
+ raise ValueError(
232
+ f"_build_cleanup_node_query_for_unscoped_cleanup() failed: '{node_schema.label}' does not have "
233
+ "scoped_cleanup=False, so we cannot generate a query to clean it up. Please verify that the class "
234
+ "definition is what you expect.",
235
+ )
236
+
237
+ # The cleanup node query must always be before the cleanup rel query
238
+ delete_action_clause = """
239
+ WHERE n.lastupdated <> $UPDATE_TAG
240
+ WITH n LIMIT $LIMIT_SIZE
241
+ DETACH DELETE n;
242
+ """
243
+
244
+ # Ensure the node is attached to the sub resource and delete the node
245
+ query_template = Template(
246
+ """
247
+ $match_statement
248
+ $delete_action_clause
249
+ """,
250
+ )
251
+ return query_template.safe_substitute(
252
+ match_statement=_build_match_statement_for_cleanup(node_schema),
253
+ delete_action_clause=delete_action_clause,
254
+ )
255
+
256
+
257
+ def _build_cleanup_rel_queries_unscoped(
258
+ node_schema: CartographyNodeSchema,
259
+ selected_relationship: CartographyRelSchema,
260
+ ) -> str:
261
+ """
262
+ Generates relationship cleanup query for a node_schema with scoped_cleanup=False.
263
+ """
264
+ if node_schema.scoped_cleanup:
265
+ raise ValueError(
266
+ f"_build_cleanup_node_and_rel_queries_unscoped() failed: '{node_schema.label}' does not have "
267
+ "scoped_cleanup=False, so we cannot generate a query to clean it up. Please verify that the class "
268
+ "definition is what you expect.",
269
+ )
270
+ if not rel_present_on_node_schema(node_schema, selected_relationship):
271
+ raise ValueError(
272
+ f"_build_cleanup_node_query(): Attempted to build cleanup query for node '{node_schema.label}' and "
273
+ f"relationship {selected_relationship.rel_label} but that relationship is not present on the node. Please "
274
+ "verify the node class definition for the relationships that it has.",
275
+ )
276
+
277
+ # The cleanup node query must always be before the cleanup rel query
278
+ delete_action_clause = """WHERE r.lastupdated <> $UPDATE_TAG
279
+ WITH r LIMIT $LIMIT_SIZE
280
+ DELETE r;
281
+ """
282
+
283
+ # Ensure the node is attached to the sub resource and delete the node
284
+ query_template = Template(
285
+ """
286
+ $match_statement
287
+ $selected_rel_clause
288
+ $delete_action_clause
289
+ """,
290
+ )
291
+ return query_template.safe_substitute(
292
+ match_statement=_build_match_statement_for_cleanup(node_schema),
293
+ selected_rel_clause=_build_selected_rel_clause(selected_relationship),
294
+ delete_action_clause=delete_action_clause,
295
+ )
296
+
297
+
188
298
  def _build_selected_rel_clause(selected_relationship: CartographyRelSchema) -> str:
189
299
  """
190
300
  Draw selected relationship with correct direction. Returns a string that looks like either
@@ -0,0 +1,62 @@
1
+ import logging
2
+
3
+ import neo4j
4
+ import requests
5
+
6
+ import cartography.intel.anthropic.apikeys
7
+ import cartography.intel.anthropic.users
8
+ import cartography.intel.anthropic.workspaces
9
+ from cartography.config import Config
10
+ from cartography.util import timeit
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ @timeit
16
+ def start_anthropic_ingestion(neo4j_session: neo4j.Session, config: Config) -> None:
17
+ """
18
+ If this module is configured, perform ingestion of Anthropic data. Otherwise warn and exit
19
+ :param neo4j_session: Neo4J session for database interface
20
+ :param config: A cartography.config object
21
+ :return: None
22
+ """
23
+
24
+ if not config.anthropic_apikey:
25
+ logger.info(
26
+ "Anthropic import is not configured - skipping this module. "
27
+ "See docs to configure.",
28
+ )
29
+ return
30
+
31
+ # Create requests sessions
32
+ api_session = requests.session()
33
+ api_session.headers.update(
34
+ {
35
+ "X-Api-Key": config.anthropic_apikey,
36
+ "anthropic-version": "2023-06-01",
37
+ }
38
+ )
39
+
40
+ common_job_parameters = {
41
+ "UPDATE_TAG": config.update_tag,
42
+ "BASE_URL": "https://api.anthropic.com/v1",
43
+ }
44
+
45
+ # Organization node is created during the users sync
46
+ cartography.intel.anthropic.users.sync(
47
+ neo4j_session,
48
+ api_session,
49
+ common_job_parameters,
50
+ )
51
+
52
+ cartography.intel.anthropic.workspaces.sync(
53
+ neo4j_session,
54
+ api_session,
55
+ common_job_parameters,
56
+ )
57
+
58
+ cartography.intel.anthropic.apikeys.sync(
59
+ neo4j_session,
60
+ api_session,
61
+ common_job_parameters,
62
+ )
@@ -0,0 +1,72 @@
1
+ import logging
2
+ from typing import Any
3
+ from typing import Tuple
4
+
5
+ import neo4j
6
+ import requests
7
+
8
+ from cartography.client.core.tx import load
9
+ from cartography.graph.job import GraphJob
10
+ from cartography.intel.anthropic.util import paginated_get
11
+ from cartography.models.anthropic.apikey import AnthropicApiKeySchema
12
+ from cartography.util import timeit
13
+
14
+ logger = logging.getLogger(__name__)
15
+ # Connect and read timeouts of 60 seconds each; see https://requests.readthedocs.io/en/master/user/advanced/#timeouts
16
+ _TIMEOUT = (60, 60)
17
+
18
+
19
+ @timeit
20
+ def sync(
21
+ neo4j_session: neo4j.Session,
22
+ api_session: requests.Session,
23
+ common_job_parameters: dict[str, Any],
24
+ ) -> None:
25
+ org_id, apikeys = get(
26
+ api_session,
27
+ common_job_parameters["BASE_URL"],
28
+ )
29
+ common_job_parameters["ORG_ID"] = org_id
30
+ load_apikeys(
31
+ neo4j_session,
32
+ apikeys,
33
+ org_id,
34
+ common_job_parameters["UPDATE_TAG"],
35
+ )
36
+ cleanup(neo4j_session, common_job_parameters)
37
+
38
+
39
+ @timeit
40
+ def get(
41
+ api_session: requests.Session,
42
+ base_url: str,
43
+ ) -> Tuple[str, list[dict[str, Any]]]:
44
+ return paginated_get(
45
+ api_session, f"{base_url}/organizations/api_keys", timeout=_TIMEOUT
46
+ )
47
+
48
+
49
+ @timeit
50
+ def load_apikeys(
51
+ neo4j_session: neo4j.Session,
52
+ data: list[dict[str, Any]],
53
+ ORG_ID: str,
54
+ update_tag: int,
55
+ ) -> None:
56
+ logger.info("Loading %d Anthropic ApiKey into Neo4j.", len(data))
57
+ load(
58
+ neo4j_session,
59
+ AnthropicApiKeySchema(),
60
+ data,
61
+ lastupdated=update_tag,
62
+ ORG_ID=ORG_ID,
63
+ )
64
+
65
+
66
+ @timeit
67
+ def cleanup(
68
+ neo4j_session: neo4j.Session, common_job_parameters: dict[str, Any]
69
+ ) -> None:
70
+ GraphJob.from_node_schema(AnthropicApiKeySchema(), common_job_parameters).run(
71
+ neo4j_session
72
+ )
@@ -0,0 +1,75 @@
1
+ import logging
2
+ from typing import Any
3
+ from typing import Tuple
4
+
5
+ import neo4j
6
+ import requests
7
+
8
+ from cartography.client.core.tx import load
9
+ from cartography.graph.job import GraphJob
10
+ from cartography.intel.anthropic.util import paginated_get
11
+ from cartography.models.anthropic.organization import AnthropicOrganizationSchema
12
+ from cartography.models.anthropic.user import AnthropicUserSchema
13
+ from cartography.util import timeit
14
+
15
+ logger = logging.getLogger(__name__)
16
+ # Connect and read timeouts of 60 seconds each; see https://requests.readthedocs.io/en/master/user/advanced/#timeouts
17
+ _TIMEOUT = (60, 60)
18
+
19
+
20
+ @timeit
21
+ def sync(
22
+ neo4j_session: neo4j.Session,
23
+ api_session: requests.Session,
24
+ common_job_parameters: dict[str, Any],
25
+ ) -> str:
26
+ org_id, users = get(
27
+ api_session,
28
+ common_job_parameters["BASE_URL"],
29
+ )
30
+ common_job_parameters["ORG_ID"] = org_id
31
+ load_users(neo4j_session, users, org_id, common_job_parameters["UPDATE_TAG"])
32
+ cleanup(neo4j_session, common_job_parameters)
33
+ return org_id
34
+
35
+
36
+ @timeit
37
+ def get(
38
+ api_session: requests.Session,
39
+ base_url: str,
40
+ ) -> Tuple[str, list[dict[str, Any]]]:
41
+ return paginated_get(
42
+ api_session, f"{base_url}/organizations/users", timeout=_TIMEOUT
43
+ )
44
+
45
+
46
+ @timeit
47
+ def load_users(
48
+ neo4j_session: neo4j.Session,
49
+ data: list[dict[str, Any]],
50
+ ORG_ID: str,
51
+ update_tag: int,
52
+ ) -> None:
53
+ load(
54
+ neo4j_session,
55
+ AnthropicOrganizationSchema(),
56
+ [{"id": ORG_ID}],
57
+ lastupdated=update_tag,
58
+ )
59
+ logger.info("Loading %d Anthropic User into Neo4j.", len(data))
60
+ load(
61
+ neo4j_session,
62
+ AnthropicUserSchema(),
63
+ data,
64
+ lastupdated=update_tag,
65
+ ORG_ID=ORG_ID,
66
+ )
67
+
68
+
69
+ @timeit
70
+ def cleanup(
71
+ neo4j_session: neo4j.Session, common_job_parameters: dict[str, Any]
72
+ ) -> None:
73
+ GraphJob.from_node_schema(AnthropicUserSchema(), common_job_parameters).run(
74
+ neo4j_session
75
+ )
@@ -0,0 +1,51 @@
1
+ from typing import Any
2
+
3
+ import requests
4
+
5
+
6
+ def paginated_get(
7
+ api_session: requests.Session,
8
+ url: str,
9
+ timeout: tuple[int, int],
10
+ after: str | None = None,
11
+ ) -> tuple[str, list[dict[str, Any]]]:
12
+ """Helper function to get paginated data from the Anthropic API.
13
+
14
+ This function handles the pagination of the API requests and returns
15
+ the results in a list. It also retrieves the organization ID from the
16
+ response headers. The function will continue to make requests until
17
+ all pages of data have been retrieved. The results are returned as a
18
+ list of dictionaries, where each dictionary represents a single
19
+ entity.
20
+
21
+ Args:
22
+ api_session (requests.Session): The requests session to use for making API calls.
23
+ url (str): The URL to make the API call to.
24
+ timeout (tuple[int, int]): The timeout for the API call.
25
+ after (str | None): The ID of the last item retrieved in the previous request.
26
+ If None, the first page of results will be retrieved.
27
+ Returns:
28
+ tuple[str, list[dict[str, Any]]]: A tuple containing the organization ID and a list of
29
+ dictionaries representing the results.
30
+ """
31
+ results: list[dict[str, Any]] = []
32
+ params = {"after_id": after} if after else {}
33
+ req = api_session.get(
34
+ url,
35
+ params=params,
36
+ timeout=timeout,
37
+ )
38
+ req.raise_for_status()
39
+ # Get organization_id from the headers
40
+ organization_id = req.headers.get("anthropic-organization-id", "")
41
+ result = req.json()
42
+ results.extend(result.get("data", []))
43
+ if result.get("has_more"):
44
+ _, next_results = paginated_get(
45
+ api_session,
46
+ url,
47
+ timeout=timeout,
48
+ after=result.get("last_id"),
49
+ )
50
+ results.extend(next_results)
51
+ return organization_id, results