forked from demisto/content
-
Notifications
You must be signed in to change notification settings - Fork 13
/
MicrosoftGraphAPI.py
189 lines (160 loc) · 7.06 KB
/
MicrosoftGraphAPI.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
from MicrosoftApiModule import * # noqa: E402
import urllib3
from typing import Any
urllib3.disable_warnings()
class MsGraphClient:
def __init__(self,
app_id: str,
scope: str,
app_secret: str,
tenant_id: str,
verify: bool,
proxy: bool,
azure_cloud: AzureCloud,
certificate_thumbprint: str | None = None,
private_key: str | None = None,
managed_identities_client_id: str | None = None,
):
client_args = {
'base_url': azure_cloud.endpoints.microsoft_graph_resource_id.rstrip("/"),
'auth_id': app_id,
'scope': Scopes.graph,
'enc_key': app_secret,
'tenant_id': tenant_id,
'verify': verify,
'proxy': proxy,
'self_deployed': True,
'grant_type': CLIENT_CREDENTIALS,
'ok_codes': (200, 201, 204),
'azure_ad_endpoint': azure_cloud.endpoints.active_directory,
'private_key': private_key,
'certificate_thumbprint': certificate_thumbprint,
'managed_identities_client_id': managed_identities_client_id,
'managed_identities_resource_uri': Resources.graph,
'azure_cloud': azure_cloud,
'command_prefix': "msgraph-api",
}
if not (app_secret and tenant_id):
client_args['grant_type'] = DEVICE_CODE
client_args['token_retrieval_url'] = urljoin(azure_cloud.endpoints.active_directory,
'/organizations/oauth2/v2.0/token')
client_args['scope'] = scope
self.ms_client = MicrosoftClient(**client_args) # type: ignore[arg-type]
def generic_request(
self,
resource: str,
http_method: str = 'GET',
api_version: str = 'v1.0',
odata: str | None = None,
request_body: dict | None = None,
):
url_suffix = urljoin(api_version, resource)
if odata:
url_suffix += f'?{odata}'
res = self.ms_client.http_request(
method=http_method,
url_suffix=url_suffix,
json_data=request_body,
resp_type='resp',
)
return res.json() if res.content else None
def start_auth(client: MsGraphClient) -> CommandResults: # pragma: no cover
result = client.ms_client.start_auth('!msgraph-api-auth-complete')
return CommandResults(readable_output=result)
def complete_auth(client: MsGraphClient): # pragma: no cover
client.ms_client.get_access_token()
return 'Authorization completed successfully.'
def test_module(client: MsGraphClient,
app_secret: str,
tenant_id: str,
managed_identities_client_id: str | None) -> str: # pragma: no cover
if (app_secret and tenant_id) or managed_identities_client_id:
client.ms_client.get_access_token()
return 'ok'
else:
raise ValueError('The test module is not functional when using Cortex XSOAR Azure app, '
'run the msgraph-test command instead.')
def test_command(client: MsGraphClient) -> CommandResults: # pragma: no cover
client.ms_client.get_access_token()
return CommandResults(readable_output='```✅ Success!```')
def generic_command(client: MsGraphClient, args: dict[str, Any]) -> CommandResults:
request_body = args.get('request_body')
results: dict
if request_body and isinstance(request_body, str):
try:
request_body = json.loads(request_body)
except json.decoder.JSONDecodeError as e:
raise ValueError(f'Invalid request body - {str(e)}')
http_method = args.get('http_method', 'GET')
response = client.generic_request(
resource=args.get('resource', ''),
http_method=http_method,
api_version=args.get('api_version', 'v1.0'),
odata=args.get('odata', ''),
request_body=request_body,
)
if not response:
results = {
'readable_output': 'The API query ran successfully and returned no content.',
}
else:
results = {'raw_response': response}
if argToBoolean(args.get('populate_context', 'true')):
outputs = get_response_outputs(response)
if outputs is True:
return CommandResults(readable_output='The API query ran successfully and returned no content.')
results['outputs'] = outputs
results['outputs_prefix'] = 'MicrosoftGraph'
return CommandResults(**results) # type: ignore[arg-type]
def get_response_outputs(response: dict) -> Union[dict, list]:
if 'value' in response:
return response['value']
res = dict(response)
res.pop('@odata.context', None)
return res
def main() -> None: # pragma: no cover
params = demisto.params()
command = demisto.command()
demisto.debug(f'Command being called is {command}')
scope = 'offline_access '
if params.get('scope'):
scope += params.get('scope')
azure_cloud = get_azure_cloud(params, 'MicrosoftGraphAPI')
app_secret = params.get('app_secret') or (params.get('credentials') or {}).get('password')
app_secret = app_secret if isinstance(app_secret, str) else ''
certificate_thumbprint = params.get('creds_certificate', {}).get('identifier') or params.get('certificate_thumbprint')
private_key = replace_spaces_in_credential(params.get('creds_certificate', {}).get('password')) or params.get('private_key')
managed_identities_client_id = get_azure_managed_identities_client_id(params)
try:
client = MsGraphClient(
app_id=params.get('app_id'),
scope=scope,
app_secret=app_secret,
tenant_id=params.get('tenant_id'),
verify=not params.get('insecure', False),
proxy=params.get('proxy', False),
azure_cloud=azure_cloud,
certificate_thumbprint=certificate_thumbprint,
private_key=private_key,
managed_identities_client_id=managed_identities_client_id,
)
if command == 'test-module':
result = test_module(client, app_secret, params.get('tenant_id'), managed_identities_client_id)
return_results(result)
elif command == 'msgraph-api-request':
return_results(generic_command(client, demisto.args()))
elif command == 'msgraph-api-auth-start':
return_results(start_auth(client))
elif command == 'msgraph-api-auth-complete':
return_results(complete_auth(client))
elif command == 'msgraph-api-test':
return_results(test_command(client))
elif command == 'msgraph-api-auth-reset':
return_results(reset_auth())
except Exception as e:
return_error(f'Failed to execute {demisto.command()} command. Error: {str(e)}')
if __name__ in ('__main__', '__builtin__', 'builtins'):
main()