forked from canada-ca/tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtracker_client.py
More file actions
442 lines (364 loc) · 12.7 KB
/
Copy pathtracker_client.py
File metadata and controls
442 lines (364 loc) · 12.7 KB
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
import os
import json
from slugify import slugify
from gql import gql, Client
from gql.transport.aiohttp import AIOHTTPTransport
SIGNIN_MUTATION = gql(
"""
mutation signIn($creds: SignInInput!) {
signIn (input: $creds) {
result {
... on RegularSignInResult {
authResult {
authToken
}
}
}
}
}
"""
)
ALL_DOMAINS_QUERY = gql(
"""
query getAllDomains {
findMyOrganizations(first: 100) {
edges {
node {
acronym
domains(first: 100){
edges{
node{
domain
}
}
}
}
}
}
}
"""
)
DOMAINS_BY_SLUG = gql(
"""
query orgBySlug($org: Slug!){
findOrganizationBySlug(orgSlug: $org){
domains(first: 100){
edges{
node{
domain
}
}
}
}
}
"""
)
DMARC_SUMMARY = gql(
"""
query domainDMARCSummary(
$domain: DomainScalar!
$month: PeriodEnums!
$year: Year!
) {
findDomainByDomain(domain: $domain) {
domain
dmarcSummaryByPeriod(month: $month, year: $year) {
month
year
categoryPercentages {
fullPassPercentage
passSpfOnlyPercentage
passDkimOnlyPercentage
failPercentage
totalMessages
}
}
}
}
"""
)
DMARC_YEARLY_SUMMARIES = gql(
"""
query domainAllDMARCSummaries($domain: DomainScalar!) {
findDomainByDomain(domain: $domain) {
domain
yearlyDmarcSummaries {
month
year
categoryPercentages {
fullPassPercentage
passSpfOnlyPercentage
passDkimOnlyPercentage
failPercentage
totalMessages
}
}
}
}
"""
)
ALL_ORG_SUMMARIES = gql(
"""
query getAllSummaries {
findMyOrganizations(first: 100) {
edges {
node {
acronym
domainCount
summaries{
web{
total
categories{
name
count
percentage
}
}
mail{
total
categories{
name
count
percentage
}
}
}
}
}
}
}
"""
)
SUMMARY_BY_SLUG = gql(
"""
query getSummaryBySlug($orgSlug: Slug!) {
findOrganizationBySlug(orgSlug: $orgSlug) {
acronym
domainCount
summaries {
web {
total
categories {
name
count
percentage
}
}
mail {
total
categories {
name
count
percentage
}
}
}
}
}
"""
)
def create_transport(url, auth_token=None):
"""Create and return a gql transport object
Arguments:
url -- the Tracker GraphQL endpoint url
auth_token -- JWT auth token string, omit when initially obtaining the token
"""
if auth_token is None:
transport = AIOHTTPTransport(url=url)
else:
transport = AIOHTTPTransport(
url="https://tracker.alpha.canada.ca/graphql",
headers={"authorization": auth_token},
)
return transport
def create_client(url, auth_token=None):
"""Create and return a gql client object
Arguments:
url -- the Tracker GraphQL endpoint url
auth_token -- JWT auth token string, omit when initially obtaining the token
"""
client = Client(
transport=create_transport(url=url, auth_token=auth_token),
fetch_schema_from_transport=True,
)
return client
def get_auth_token():
"""Takes in environment variables "TRACKER_UNAME" and "TRACKER_PASS", returns an auth token"""
client = create_client(url="https://tracker.alpha.canada.ca/graphql")
username = os.environ.get("TRACKER_UNAME")
password = os.environ.get("TRACKER_PASS")
params = {"creds": {"userName": username, "password": password}}
result = client.execute(SIGNIN_MUTATION, variable_values=params)
auth_token = result["signIn"]["result"]["authResult"]["authToken"]
return auth_token
def get_all_domains(client):
"""Returns lists of all domains you have ownership of, with org as key
Arguments:
client -- a GQL Client object
"""
result = client.execute(ALL_DOMAINS_QUERY)
formatted_result = format_all_domains(result)
return json.dumps(formatted_result, indent=4)
def format_all_domains(result):
""" Formats the dict obtained by ALL_DOMAINS_QUERY """
# Extract the list of nodes from the resulting dict
result = result["findMyOrganizations"]["edges"]
# Move the dict value of "node" up a level
result = [n["node"] for n in result]
# For each dict element of the list, change the value of "domains"
# to the list of domains contained in the nodes of its edges
for x in result:
x["domains"] = x["domains"]["edges"]
x["domains"] = [n["node"] for n in x["domains"]]
x["domains"] = [n["domain"] for n in x["domains"]]
# Create a new dict in the desired format to return
result = {x["acronym"]: {"domains": x["domains"]} for x in result}
return result
def get_domains_by_acronym(acronym, client):
"""Return the domains belonging to the organization identified by acronym
Arguments:
acronym -- string containing an acronym belonging to an organization
client -- a GQL Client object
"""
# API doesn't allow query by acronym so we filter the get_all_domains result
result = client.execute(ALL_DOMAINS_QUERY)
formatted_result = format_acronym_domains(acronym, result)
return json.dumps(formatted_result, indent=4)
def format_acronym_domains(acronym, result):
""" Formats the dict obtained by ALL_DOMAINS_QUERY to show only one org"""
result = format_all_domains(result)
result = result[acronym.upper()]
return result
def get_domains_by_name(name, client):
"""Return the domains belonging to the organization identified by full name
Arguments:
name -- string containing the name of an organization
client -- a GQL Client object
"""
slugified_name = slugify(name) # API expects a slugified string for name
params = {"org": slugified_name}
result = client.execute(DOMAINS_BY_SLUG, variable_values=params)
formatted_result = format_name_domains(result)
return json.dumps(formatted_result, indent=4)
def format_name_domains(result):
"""Formats the dict obtained by DOMAINS_BY_SLUG"""
result = result["findOrganizationBySlug"]
result["domains"] = result["domains"]["edges"]
result["domains"] = [n["node"] for n in result["domains"]]
result["domains"] = [n["domain"] for n in result["domains"]]
return result
def get_dmarc_summary(domain, month, year, client):
"""Return the DMARC summary for the specified domain and month
Arguments:
domain -- domain name string
month -- string containing the full name of a month
year -- positive integer representing a year
client -- a GQL Client object
"""
params = {"domain": domain, "month": month.upper(), "year": str(year)}
result = client.execute(DMARC_SUMMARY, variable_values=params)
formatted_result = format_dmarc_monthly(result)
return json.dumps(formatted_result, indent=4)
def format_dmarc_monthly(result):
"""Formats the dict obtained by DMARC_SUMMARY"""
result = result["findDomainByDomain"]
result[result.pop("domain")] = result.pop("dmarcSummaryByPeriod")
return result
def get_yearly_dmarc_summaries(domain, client):
"""Return yearly DMARC summaries for a domain
Arguments:
domain -- domain name string
client -- a GQL Client object
"""
params = {"domain": domain}
result = client.execute(DMARC_YEARLY_SUMMARIES, variable_values=params)
formatted_result = format_dmarc_yearly(result)
return json.dumps(formatted_result, indent=4)
def format_dmarc_yearly(result):
"""Formats the dict obtained by DMARC_YEARLY_SUMMARIES"""
result = result["findDomainByDomain"]
result[result.pop("domain")] = result.pop("yearlyDmarcSummaries")
return result
def get_all_summaries(client):
"""Returns summary metrics for all organizations you are a member of.
Arguments:
client -- a GQL Client object
"""
result = client.execute(ALL_ORG_SUMMARIES)
formatted_result = format_all_summaries(result)
return json.dumps(formatted_result, indent=4)
def format_all_summaries(result):
"""Formats the dict obtained by ALL_ORG_SUMMARIES"""
result = result["findMyOrganizations"]["edges"]
result = {x["node"].pop("acronym"): x["node"] for x in result}
return result
def get_summary_by_acronym(acronym, client):
"""Returns summary metrics for the organization identified by acronym
Arguments:
acronym -- string containing an acronym belonging to an organization
client -- a GQL Client object
"""
# API doesn't allow query by acronym so we filter the get_all_summaries result
result = client.execute(ALL_ORG_SUMMARIES)
formatted_result = format_acronym_summary(result, acronym)
return json.dumps(formatted_result, indent=4)
def format_acronym_summary(result, acronym):
"""Formats the dict obtained by ALL_ORG_SUMMARIES to show only one org"""
result = format_all_summaries(result)
# dict in assignment is to keep the org identified in the return value
result = {acronym.upper(): result[acronym.upper()]}
return result
def get_summary_by_name(name, client):
"""Return summary metrics for the organization identified by name
Arguments:
name -- string containing the name of an organization
client -- a GQL Client object
"""
slugified_name = slugify(name) # API expects a slugified string for name
params = {"orgSlug": slugified_name}
result = client.execute(SUMMARY_BY_SLUG, variable_values=params)
formatted_result = format_name_summary(result)
return json.dumps(formatted_result, indent=4)
def format_name_summary(result):
"""Formats the dict obtained by SUMMARY_BY_SLUG"""
result = {
result["findOrganizationBySlug"].pop("acronym"): result[
"findOrganizationBySlug"
]
}
return result
def main():
"""main() currently tries all implemented functions and prints results
for diagnostic purposes and to demo available features.
"""
print("Tracker account: " + os.environ.get("TRACKER_UNAME"))
client = create_client("https://tracker.alpha.canada.ca/graphql", get_auth_token())
print("Getting all your domains...")
domains = get_all_domains(client)
print(domains)
acronym = "cse"
print("Getting domains by acronym " + acronym + "...")
domains = get_domains_by_acronym("cse", client)
print(domains)
name = "Communications Security Establishment Canada"
print("Getting domains by name " + name + "...")
domains = get_domains_by_name(name, client)
print(domains)
domain = "cse-cst.gc.ca"
print("Getting a dmarc summary for " + domain + "...")
result = get_dmarc_summary(domain, "november", 2020, client)
print(result)
print("Getting yearly dmarc summary for " + domain + "...")
result = get_yearly_dmarc_summaries("cse-cst.gc.ca", client)
print(result)
print("Getting summaries for all your organizations...")
summaries = get_all_summaries(client)
print(summaries)
print("Getting summary by acronym " + acronym + "...")
summaries = get_summary_by_acronym("cse", client)
print(summaries)
print("Getting summary by name " + name + "...")
summaries = get_summary_by_name(name, client)
print(summaries)
if __name__ == "__main__":
main()