Repository navigation
Expand file tree
/
Copy pathcheckpoint.py
More file actions
5034 lines (4369 loc) · 197 KB
/
Copy pathcheckpoint.py
File metadata and controls
5034 lines (4369 loc) · 197 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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
IAM support and troubleshooting tools
"""
import datetime
import logging
import re
import sqlite3
from base64 import b64encode
from email.errors import InvalidHeaderDefect
from email.headerregistry import Address
from hashlib import file_digest
from json import dumps, loads
from os import environ
from re import IGNORECASE, fullmatch
from sqlite3 import connect
from typing import Any, Dict, Final, List, Union
from urllib.parse import urlparse, urlunparse
from zoneinfo import ZoneInfo
from authlib.integrations.flask_client import OAuth
from authlib.integrations.requests_client import OAuth2Session
from celery import Celery, Task, shared_task
from flask import Flask, g, render_template, request, session
from flask.helpers import get_debug_flag, redirect, url_for
from flask_caching import Cache
from google.oauth2 import service_account
from googleapiclient.discovery import build # type: ignore
from ldap3 import (
Connection,
DEREF_ALWAYS,
SUBTREE,
Server,
)
from ldap3.operation.search import search_operation
from requests import get, post
import sentry_sdk
from sentry_sdk import set_user
from sentry_sdk.integrations.flask import FlaskIntegration
from sentry_sdk.integrations.pure_eval import PureEvalIntegration
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
from slack_sdk.models.blocks import ContextBlock, SectionBlock, TextObject
from slack_sdk.signature import SignatureVerifier
from square import Square
from werkzeug.exceptions import BadRequest, Forbidden, InternalServerError, NotFound, Unauthorized
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
req_log = logging.getLogger("urllib3")
req_log.setLevel(logging.DEBUG)
req_log.propagate = True
GEORGIA_TECH_USERNAME_REGEX: Final[str] = r"[a-zA-Z]+[0-9]+"
EMAIL_ADDRESS_REGEX: Final[str] = r"[\w.+-]+@[\w-]+(?:\.[\w-]+)*\.[A-Za-z]{2,}"
ACCESS_OVERRIDE_TIMESTAMP_REGEX: Final[str] = r"(?P<timestamp>\d{4}-\d{2}-\d{2})"
NUMBER_IN_QUOTES_REGEX: Final[str] = r"\"(?P<user_id>\d+)\""
PAYMENT_METHOD_REGEX: Final[str] = r"\"method\".+\"(?P<method>[a-z]+)\".+\"amount\""
CLIENT_NAME_REGEX: Final[str] = r"\"client_name\".+?\"(?P<client_name>.+?)\""
USER_AGENT: Final[str] = (
"Checkpoint/"
+ environ.get("NOMAD_TASK_NAME", "local")
+ "/"
+ environ.get("NOMAD_SHORT_ALLOC_ID", "local")
)
# Square error code descriptions from API documentation, to show to technicians
SQUARE_ERROR_CODE_DESCRIPTIONS: Final[Dict[str, str]] = {
"INTERNAL_SERVER_ERROR": "A general server error occurred.",
"UNAUTHORIZED": "A general authorization error occurred.",
"ACCESS_TOKEN_EXPIRED": "The provided access token has expired.",
"ACCESS_TOKEN_REVOKED": "The provided access token has been revoked.",
"CLIENT_DISABLED": "The provided client has been disabled.",
"FORBIDDEN": "A general access error occurred.",
"INSUFFICIENT_SCOPES": "The provided access token does not have permission to execute the requested action.",
"APPLICATION_DISABLED": "The calling application was disabled.",
"V1_APPLICATION": "The calling application was created prior to 2016-03-30 and is not compatible with v2 Square API calls.",
"V1_ACCESS_TOKEN": "The calling application is using an access token created prior to 2016-03-30 and is not compatible with v2 Square API calls.",
"CARD_PROCESSING_NOT_ENABLED": "The location provided in the API call is not enabled for credit card processing.",
"MERCHANT_SUBSCRIPTION_NOT_FOUND": "A required subscription was not found for the merchant.",
"BAD_REQUEST": "A general error occurred with the request.",
"MISSING_REQUIRED_PARAMETER": "The request is missing a required path, query, or body parameter.",
"INCORRECT_TYPE": "The value provided in the request is the wrong type. For example, a string instead of an integer.",
"INVALID_TIME": "Formatting for the provided time value is incorrect.",
"INVALID_TIME_RANGE": "The time range provided in the request is invalid. For example, the end time is before the start time.",
"INVALID_VALUE": "The provided value is invalid. For example, including % in a phone number.",
"INVALID_CURSOR": "The pagination cursor included in the request is invalid.",
"UNKNOWN_QUERY_PARAMETER": "The query parameters provided are invalid for the requested endpoint.",
"CONFLICTING_PARAMETERS": "One or more of the request parameters conflict with each other.",
"EXPECTED_JSON_BODY": "The request body is not a JSON object.",
"INVALID_SORT_ORDER": "The provided sort order is not a valid key. Currently, sort order must be ASC or DESC.",
"VALUE_REGEX_MISMATCH": "The provided value does not match an expected regular expression.",
"VALUE_TOO_SHORT": "The provided string value is shorter than the minimum length allowed.",
"VALUE_TOO_LONG": "The provided string value is longer than the maximum length allowed.",
"VALUE_TOO_LOW": "The provided value is less than the supported minimum.",
"VALUE_TOO_HIGH": "The provided value is greater than the supported maximum.",
"VALUE_EMPTY": "The provided value has a default (empty) value such as a blank string.",
"ARRAY_LENGTH_TOO_LONG": "The provided array has too many elements.",
"ARRAY_LENGTH_TOO_SHORT": "The provided array has too few elements.",
"ARRAY_EMPTY": "The provided array is empty.",
"EXPECTED_BOOLEAN": "The endpoint expected the provided value to be a boolean.",
"EXPECTED_INTEGER": "The endpoint expected the provided value to be an integer.",
"EXPECTED_FLOAT": "The endpoint expected the provided value to be a float.",
"EXPECTED_STRING": "The endpoint expected the provided value to be a string.",
"EXPECTED_OBJECT": "The endpoint expected the provided value to be a JSON object.",
"EXPECTED_ARRAY": "The endpoint expected the provided value to be an array or list.",
"EXPECTED_MAP": "The endpoint expected the provided value to be a map or associative array.",
"EXPECTED_BASE64_ENCODED_BYTE_ARRAY": "The endpoint expected the provided value to be an array encoded in base64.",
"INVALID_ARRAY_VALUE": "One or more objects in the array does not match the array type.",
"INVALID_ENUM_VALUE": "The provided static string is not valid for the field.",
"INVALID_CONTENT_TYPE": "Invalid content type header.",
"INVALID_FORM_VALUE": "Only relevant for applications created prior to 2016-03-30. Indicates there was an error while parsing form values.",
"CUSTOMER_NOT_FOUND": "The provided customer ID can't be found in the merchant's customers list.",
"ONE_INSTRUMENT_EXPECTED": "A general error occurred.",
"NO_FIELDS_SET": "A general error occurred.",
"TOO_MANY_MAP_ENTRIES": "Too many entries in the map field.",
"MAP_KEY_LENGTH_TOO_SHORT": "The length of one of the provided keys in the map is too short.",
"MAP_KEY_LENGTH_TOO_LONG": "The length of one of the provided keys in the map is too long.",
"CUSTOMER_MISSING_NAME": "The provided customer does not have a recorded name.",
"CUSTOMER_MISSING_EMAIL": "The provided customer does not have a recorded email.",
"INVALID_PAUSE_LENGTH": "The subscription cannot be paused longer than the duration of the current phase.",
"INVALID_DATE": "The subscription cannot be paused/resumed on the given date.",
"UNSUPPORTED_COUNTRY": "The API request references an unsupported country.",
"UNSUPPORTED_CURRENCY": "The API request references an unsupported currency.",
"APPLE_TTP_PIN_TOKEN": "The payment was declined by the card issuer during an Apple Tap to Pay (TTP) transaction with a request for the card's PIN. This code will be returned alongside CARD_DECLINED_VERIFICATION_REQUIRED as a supplemental error, and will include an issuer-provided token in the details field that is needed to initiate the PIN collection flow on the iOS device.",
"CARD_EXPIRED": "The card issuer declined the request because the card is expired.",
"INVALID_EXPIRATION": "The expiration date for the payment card is invalid. For example, it indicates a date in the past.",
"INVALID_EXPIRATION_YEAR": "The expiration year for the payment card is invalid. For example, it indicates a year in the past or contains invalid characters.",
"INVALID_EXPIRATION_DATE": "The expiration date for the payment card is invalid. For example, it contains invalid characters.",
"UNSUPPORTED_CARD_BRAND": "The credit card provided is not from a supported issuer.",
"UNSUPPORTED_ENTRY_METHOD": "The entry method for the credit card (swipe, dip, tap) is not supported.",
"INVALID_ENCRYPTED_CARD": "The encrypted card information is invalid.",
"INVALID_CARD": "The credit card cannot be validated based on the provided details.",
"PAYMENT_AMOUNT_MISMATCH": "The payment was declined because there was a payment amount mismatch. The money amount Square was expecting does not match the amount provided.",
"GENERIC_DECLINE": "Square received a decline without any additional information. If the payment information seems correct, the buyer can contact their issuer to ask for more information.",
"CVV_FAILURE": "The card issuer declined the request because the CVV value is invalid.",
"ADDRESS_VERIFICATION_FAILURE": "The card issuer declined the request because the postal code is invalid.",
"INVALID_ACCOUNT": "The issuer was not able to locate the account on record.",
"CURRENCY_MISMATCH": "The currency associated with the payment is not valid for the provided funding source. For example, a gift card funded in USD cannot be used to process payments in GBP.",
"INSUFFICIENT_FUNDS": "The funding source has insufficient funds to cover the payment.",
"INSUFFICIENT_PERMISSIONS": "The Square account does not have the permissions to accept this payment. For example, Square may limit which merchants are allowed to receive gift card payments.",
"CARDHOLDER_INSUFFICIENT_PERMISSIONS": "The card issuer has declined the transaction due to restrictions on where the card can be used. For example, a gift card is limited to a single merchant.",
"INVALID_LOCATION": "The Square account cannot take payments in the specified region. A Square account can take payments only from the region where the account was created.",
"TRANSACTION_LIMIT": "The card issuer has determined the payment amount is either too high or too low. The API returns the error code mostly for credit cards (for example, the card reached the credit limit). However, sometimes the issuer bank can indicate the error for debit or prepaid cards (for example, card has insufficient funds).",
"VOICE_FAILURE": "The card issuer declined the request because the issuer requires voice authorization from the cardholder. The seller should ask the customer to contact the card issuing bank to authorize the payment.",
"PAN_FAILURE": "The specified card number is invalid. For example, it is of incorrect length or is incorrectly formatted.",
"EXPIRATION_FAILURE": "The card expiration date is either invalid or indicates that the card is expired.",
"CARD_NOT_SUPPORTED": "The card is not supported either in the geographic region or by the merchant category code (MCC).",
"READER_DECLINED": "The Square Card Reader declined the payment for an unknown reason.",
"INVALID_PIN": "The card issuer declined the request because the PIN is invalid.",
"MISSING_PIN": "The payment is missing a required PIN.",
"MISSING_ACCOUNT_TYPE": "The payment is missing a required ACCOUNT_TYPE parameter.",
"INVALID_POSTAL_CODE": "The postal code is incorrectly formatted.",
"INVALID_FEES": "The app_fee_money on a payment is too high.",
"MANUALLY_ENTERED_PAYMENT_NOT_SUPPORTED": "The card must be swiped, tapped, or dipped. Payments attempted by manually entering the card number are declined.",
"PAYMENT_LIMIT_EXCEEDED": "Square declined the request because the payment amount exceeded the processing limit for this merchant.",
"GIFT_CARD_AVAILABLE_AMOUNT": "Provides the available balance on a Square gift card when a gift card payment fails due to insufficient funds. This error is returned with an INSUFFICIENT_FUNDS error and contains the balance in the smallest denomination of the applicable currency.",
"ACCOUNT_UNUSABLE": "The account provided cannot carry out transactions.",
"BUYER_REFUSED_PAYMENT": "Bank account rejected or was not authorized for the payment.",
"DELAYED_TRANSACTION_EXPIRED": "The application tried to update a delayed-capture payment that has expired.",
"DELAYED_TRANSACTION_CANCELED": "The application tried to cancel a delayed-capture payment that was already cancelled.",
"DELAYED_TRANSACTION_CAPTURED": "The application tried to capture a delayed-capture payment that was already captured.",
"DELAYED_TRANSACTION_FAILED": "The application tried to update a delayed-capture payment that failed.",
"CARD_TOKEN_EXPIRED": "The provided card token (nonce) has expired.",
"CARD_TOKEN_USED": "The provided card token (nonce) was already used to process the payment or refund.",
"AMOUNT_TOO_HIGH": "The requested payment amount is too high for the provided payment source.",
"UNSUPPORTED_INSTRUMENT_TYPE": "The API request references an unsupported instrument type.",
"REFUND_AMOUNT_INVALID": "The requested refund amount exceeds the amount available to refund.",
"REFUND_ALREADY_PENDING": "The payment already has a pending refund.",
"PAYMENT_NOT_REFUNDABLE": "The payment is not refundable. For example, the payment is too old to be refunded.",
"PAYMENT_NOT_REFUNDABLE_DUE_TO_DISPUTE": "The payment is not refundable because it has been disputed.",
"REFUND_ERROR_PAYMENT_NEEDS_COMPLETION": "The payment is not refundable because the payment is approved and needs to be completed first before the refund is issued.",
"REFUND_DECLINED": "Request failed - The card issuer declined the refund.",
"INSUFFICIENT_PERMISSIONS_FOR_REFUND": "The Square account does not have the permissions to process this refund.",
"INVALID_CARD_DATA": "Generic error - the provided card data is invalid.",
"SOURCE_USED": "The provided source ID was already used to create a card.",
"SOURCE_EXPIRED": "The provided source ID has expired.",
"UNSUPPORTED_LOYALTY_REWARD_TIER": "The referenced loyalty program reward tier is not supported. This could happen if the reward tier created in a first party application is incompatible with the Loyalty API.",
"LOCATION_MISMATCH": "Generic error - the given location does not match what is expected.",
"ORDER_UNPAID_NOT_RETURNABLE": "The order attempting to be returned is not yet paid and cannot be returned.",
"PARTIAL_PAYMENT_DELAY_CAPTURE_NOT_SUPPORTED": "Delay capture of a partial payment is not supported.",
"IDEMPOTENCY_KEY_REUSED": "The provided idempotency key has already been used.",
"UNEXPECTED_VALUE": "General error - the value provided was unexpected.",
"SANDBOX_NOT_SUPPORTED": "The API request is not supported in sandbox.",
"INVALID_EMAIL_ADDRESS": "The provided email address is invalid.",
"INVALID_PHONE_NUMBER": "The provided phone number is invalid.",
"CHECKOUT_EXPIRED": "The provided checkout URL has expired.",
"BAD_CERTIFICATE": "Bad certificate.",
"INVALID_SQUARE_VERSION_FORMAT": "The provided Square-Version is incorrectly formatted.",
"API_VERSION_INCOMPATIBLE": "The provided Square-Version is incompatible with the requested action.",
"CARD_PRESENCE_REQUIRED": "The transaction requires that a card be present.",
"UNSUPPORTED_SOURCE_TYPE": "The API request references an unsupported source type.",
"CARD_MISMATCH": "The provided card does not match what is expected.",
"PLAID_ERROR": "Generic Plaid error.",
"PLAID_ERROR_ITEM_LOGIN_REQUIRED": "Plaid error - ITEM_LOGIN_REQUIRED.",
"PLAID_ERROR_RATE_LIMIT": "Plaid error - RATE_LIMIT.",
"PAYMENT_SOURCE_NOT_ENABLED_FOR_TARGET": "The provided merchant or location is not enabled to accept the requested payment source.",
"CARD_DECLINED": "The card was declined.",
"VERIFY_CVV_FAILURE": "The CVV could not be verified.",
"VERIFY_AVS_FAILURE": "The AVS could not be verified.",
"CARD_DECLINED_CALL_ISSUER": "The payment card was declined with a request for the cardholder to call the issuer.",
"CARD_DECLINED_VERIFICATION_REQUIRED": "The payment card was declined with a request for additional verification.",
"BAD_EXPIRATION": "The card expiration date is either missing or incorrectly formatted.",
"CHIP_INSERTION_REQUIRED": "The card issuer requires that the card be read using a chip reader.",
"ALLOWABLE_PIN_TRIES_EXCEEDED": "The card has exhausted its available PIN entry retries set by the card issuer. Resolving the error typically requires the cardholder to contact the card issuer.",
"RESERVATION_DECLINED": "The card issuer declined the refund.",
"UNKNOWN_BODY_PARAMETER": "The body parameter is not recognized by the requested endpoint.",
"NOT_FOUND": "Not Found - a general error occurred.",
"APPLE_PAYMENT_PROCESSING_CERTIFICATE_HASH_NOT_FOUND": "Square could not find the associated Apple Pay certificate.",
"METHOD_NOT_ALLOWED": "Method Not Allowed - a general error occurred.",
"NOT_ACCEPTABLE": "Not Acceptable - a general error occurred.",
"REQUEST_TIMEOUT": "Request Timeout - a general error occurred.",
"CONFLICT": "Conflict - a general error occurred.",
"GONE": "The target resource is no longer available and this condition is likely to be permanent.",
"REQUEST_ENTITY_TOO_LARGE": "Request Entity Too Large - a general error occurred.",
"UNSUPPORTED_MEDIA_TYPE": "Unsupported Media Type - a general error occurred.",
"UNPROCESSABLE_ENTITY": "Unprocessable Entity - a general error occurred.",
"RATE_LIMITED": "Rate Limited - a general error occurred.",
"NOT_IMPLEMENTED": "Not Implemented - a general error occurred.",
"BAD_GATEWAY": "Bad Gateway - a general error occurred.",
"SERVICE_UNAVAILABLE": "Service Unavailable - a general error occurred.",
"TEMPORARY_ERROR": "A temporary internal error occurred. You can safely retry your call using the same idempotency key.",
"GATEWAY_TIMEOUT": "Gateway Timeout - a general error occurred.",
}
VERIFICATION_CUSTOMER_MESSAGE: Final[str] = (
"Your card issuer requested additional verification for this payment. Contact your card issuer for help."
)
# Square error code messages to show to customers
SQUARE_ERROR_CODE_CUSTOMER_MESSAGES: Final[Dict[str, str]] = {
"GENERIC_DECLINE": "This payment was declined by your card issuer. Unfortunately, we don't have more details on our side. Contact your card issuer for help.",
"CARD_DECLINED_VERIFICATION_REQUIRED": VERIFICATION_CUSTOMER_MESSAGE,
"TRANSACTION_LIMIT": "This payment was declined by your card issuer due to insufficient funds. Check your balance, or contact your card issuer for help.",
"CVV_FAILURE": "The CVV you provided is incorrect. Make sure you typed it correctly.",
"ADDRESS_VERIFICATION_FAILURE": "The ZIP code you provided doesn't match your card's billing address. Make sure you typed it correctly.",
"PAN_FAILURE": "The card number you provided is incorrect. Make sure you typed it correctly.",
"CARD_EXPIRED": "Your card is expired. Try again with a different card.",
"VOICE_FAILURE": VERIFICATION_CUSTOMER_MESSAGE,
"CARDHOLDER_INSUFFICIENT_PERMISSIONS": "This payment was declined by your card issuer due to restrictions on where this card can be used. Contact your card issuer for help.",
}
def traces_sampler(sampling_context: Dict[str, Dict[str, str]]) -> bool:
"""
Ignore ping events, sample all other events
"""
try:
request_uri = sampling_context["wsgi_environ"]["REQUEST_URI"]
except KeyError:
return False
return request_uri != "/ping"
def init_celery(flask: Flask) -> Celery:
"""
Initialize Celery
"""
class FlaskTask(Task): # type: ignore # pylint: disable=abstract-method
"""
Extend default Task class to have Flask context available
https://flask.palletsprojects.com/en/stable/patterns/celery/
"""
def __call__(self, *args, **kwargs): # type: ignore
with flask.app_context():
return self.run(*args, **kwargs)
new_celery_app = Celery("checkpoint", task_cls=FlaskTask)
new_celery_app.config_from_object(flask.config, namespace="CELERY")
new_celery_app.set_default()
flask.extensions["celery"] = new_celery_app
return new_celery_app # type: ignore
sentry_sdk.init(
debug=get_debug_flag(),
integrations=[
FlaskIntegration(),
PureEvalIntegration(),
],
traces_sampler=traces_sampler,
attach_stacktrace=True,
max_request_body_size="always",
in_app_include=[
"checkpoint",
],
profiles_sample_rate=1.0,
)
app = Flask(__name__)
app.config.from_prefixed_env()
celery_app = init_celery(app)
oauth = OAuth(app) # type: ignore
oauth.register( # type: ignore
name="keycloak",
server_metadata_url=app.config["KEYCLOAK_METADATA_URL"],
client_kwargs={"scope": "openid email profile"},
)
keycloak = OAuth2Session(
client_id=app.config["KEYCLOAK_ADMIN_CLIENT_ID"],
client_secret=app.config["KEYCLOAK_ADMIN_CLIENT_SECRET"],
token_endpoint=urlunparse(
(
urlparse(app.config["KEYCLOAK_METADATA_URL"]).scheme,
urlparse(app.config["KEYCLOAK_METADATA_URL"]).netloc,
"/realms/master/protocol/openid-connect/token",
"",
"",
"",
)
),
leeway=5,
)
keycloak.headers["User-Agent"] = USER_AGENT
keycloak.fetch_token()
apiary = OAuth2Session(
client_id=app.config["APIARY_CLIENT_ID"],
client_secret=app.config["APIARY_CLIENT_SECRET"],
token_endpoint=app.config["APIARY_BASE_URL"] + "/oauth/token",
)
apiary.headers["User-Agent"] = USER_AGENT
apiary.headers["Accept"] = "application/json"
apiary.fetch_token()
cache = Cache(app)
slack = WebClient(token=app.config["SLACK_BOT_TOKEN"])
def generate_subresource_integrity_hash(file: str) -> str:
"""
Calculate the subresource integrity hash for a given file
"""
with open(file[1:], "rb") as f:
d = file_digest(f, "sha512")
return "sha512-" + b64encode(d.digest()).decode("utf-8")
app.jinja_env.globals["calculate_integrity"] = generate_subresource_integrity_hash
@cache.cached(key_prefix="majors")
def get_majors() -> Dict[str, str]:
"""
Fetch majors from Apiary and return as a map of whitepages_ou to display_name
"""
response = apiary.get(app.config["APIARY_BASE_URL"] + "/api/v1/majors")
response.raise_for_status()
data = response.json()
return {major["whitepages_ou"]: major["display_name"] for major in data["majors"]}
@cache.cached(key_prefix="grouper_groups")
def get_grouper_groups() -> List[str]:
"""
Fetch all Grouper groups under gt:services:robojackets and return extension names
"""
response = post(
url=app.config["GROUPER_BASE_URL"] + "/grouper-ws/servicesRest/v4_0_000/groups",
auth=(app.config["GROUPER_USERNAME"], app.config["GROUPER_PASSWORD"]),
headers={
"User-Agent": USER_AGENT,
},
json={
"WsRestFindGroupsLiteRequest": {
"stemName": "gt:services:robojackets",
"queryFilterType": "FIND_BY_STEM_NAME",
}
},
timeout=(5, 30),
)
response.raise_for_status()
return [group["extension"] for group in response.json()["WsFindGroupsResults"]["groupResults"]]
def build_ldap_filter(**kwargs: str) -> str:
"""
Builds up an LDAP filter from kwargs
:param kwargs: Dict of attribute name, value pairs
:return: LDAP search filter representation of the dict
"""
search_filter = ""
for name, value in kwargs.items():
search_filter = f"{search_filter}({name}={value})"
if len(kwargs) > 1:
search_filter = f"(&{search_filter})"
return search_filter
def build_keycloak_filter(**kwargs: str) -> str:
"""
Builds up a Keycloak filter from kwargs
:param kwargs: Dict of attribute name, value pairs
:return: Keycloak search query representation of the dict
"""
filters = []
for name, value in kwargs.items():
filters.append(f"{name}:{value}")
return " ".join(filters)
def get_attribute_value(
attribute_name: str, entry: Dict[str, Dict[str, List[str]]]
) -> Union[str, None]:
"""
Get a given attribute value from a Whitepages entry or Keycloak account, if it exists
"""
if (
"attributes" in entry
and attribute_name in entry["attributes"]
and entry["attributes"][attribute_name] is not None
and len(entry["attributes"][attribute_name]) > 0
):
return entry["attributes"][attribute_name][0]
return None
def get_gted_primary_account(**kwargs: str) -> Union[Dict[str, Any], None]:
"""
Get the primary account for a user matching the provided kwargs
"""
accounts = search_gted(**kwargs)
if len(accounts) == 0:
return None
return [
account for account in accounts if account["uid"] == account["gtPrimaryGTAccountUsername"]
][0]
def search_gted(**kwargs: str) -> List[Dict[str, Any]]:
"""
Search GTED (via BuzzAPI) for accounts matching criteria specified in kwargs
"""
buzzapi_response = post(
url="https://api.gatech.edu/apiv3/central.iam.gted.accounts/search",
json={
"api_app_id": app.config["BUZZAPI_USERNAME"],
"api_app_password": app.config["BUZZAPI_PASSWORD"],
"api_request_mode": "sync",
"api_log_level": "debug",
"requested_attributes": [
"gtGTID",
"mail",
"sn",
"givenName",
"eduPersonPrimaryAffiliation",
"gtPrimaryGTAccountUsername",
"uid",
"gtEmplId",
"gtEmployeeHomeDepartmentName",
"eduPersonScopedAffiliation",
"gtCurriculum",
"gtAccessCardNumber",
"gtAccountEntitlement",
"gtSecondaryMailAddress",
],
}
| kwargs,
timeout=(5, 30),
headers={
"User-Agent": USER_AGENT,
},
)
buzzapi_response.raise_for_status()
if "api_result_data" not in buzzapi_response.json():
return []
for account in buzzapi_response.json()["api_result_data"]:
if (
account.get("gtPersonDirectoryId") is None
or account.get("gtGTID") is None
or account.get("gtPrimaryGTAccountUsername") is None
):
continue
db().execute(
(
"INSERT INTO crosswalk (gt_person_directory_id, gtid, primary_username)"
" VALUES (:gt_person_directory_id, :gtid, :primary_username) ON CONFLICT DO NOTHING" # noqa
),
{
"gt_person_directory_id": account["gtPersonDirectoryId"],
"gtid": account["gtGTID"],
"primary_username": account["gtPrimaryGTAccountUsername"],
},
)
if account.get("mail") is not None:
db().execute(
(
"INSERT INTO crosswalk_email_address (email_address, gt_person_directory_id)" # noqa
" VALUES (:email_address, :gt_person_directory_id)"
" ON CONFLICT DO UPDATE SET gt_person_directory_id = (:gt_person_directory_id) WHERE email_address = (:email_address)" # noqa
),
{
"email_address": account["mail"],
"gt_person_directory_id": account["gtPersonDirectoryId"],
},
)
return buzzapi_response.json()["api_result_data"] # type: ignore
@cache.memoize()
def search_whitepages(**kwargs: str) -> List[Dict[str, Dict[str, List[str]]]]:
"""
Search Whitepages with a given LDAP filter
"""
whitepages_port = app.config.get("WHITEPAGES_PORT")
with sentry_sdk.start_span(op="whitepages.connect"):
whitepages = Connection(
Server(
app.config.get("WHITEPAGES_HOST", "whitepages.gatech.edu"),
port=int(whitepages_port) if whitepages_port is not None else None,
connect_timeout=1,
),
auto_bind=True,
raise_exceptions=True,
receive_timeout=1,
return_empty_attributes=False,
)
with sentry_sdk.start_span(op="whitepages.search"):
# the normal .search function does not allow sending blank attributes in the request,
# which is the easiest way to get all attributes back from whitepages
# there is some munging inside the .search function, and then it calls the below two
# internal functions (among other things)
ldap_request = search_operation(
search_base="dc=whitepages,dc=gatech,dc=edu",
search_filter=build_ldap_filter(**kwargs),
search_scope=SUBTREE,
dereference_aliases=DEREF_ALWAYS,
attributes=[],
size_limit=0,
time_limit=0,
types_only=False,
auto_escape=False,
auto_encode=False,
schema=None,
validator=None,
check_names=False,
)
whitepages.post_send_search(whitepages.send("searchRequest", ldap_request, []))
records = []
for entry in whitepages.entries:
record = loads(entry.entry_to_json())
records.append(record)
username = get_attribute_value("primaryUid", record)
mail = get_attribute_value("mail", record)
if username is not None and mail is not None:
cursor = db().execute(
"SELECT gt_person_directory_id FROM crosswalk WHERE primary_username = (:username)",
{"username": username},
)
row = cursor.fetchone()
if row is not None:
db().execute(
(
"INSERT INTO crosswalk_email_address (email_address, gt_person_directory_id)" # noqa
" VALUES (:email_address, :gt_person_directory_id)"
" ON CONFLICT DO UPDATE SET gt_person_directory_id = (:gt_person_directory_id) WHERE email_address = (:email_address)" # noqa
),
{
"email_address": mail,
"gt_person_directory_id": row[0],
},
)
return records
@cache.memoize()
def search_gtad(uid: str) -> Union[Dict[str, List[str]], None]:
"""
Look up an account in GTAD by uid and return its title/department attributes
"""
gtad_port = app.config.get("GTAD_PORT")
with sentry_sdk.start_span(op="gtad.connect"):
ldap = Connection(
Server(
app.config.get("GTAD_HOST", "campusad.ad.gatech.edu"),
port=int(gtad_port) if gtad_port is not None else None,
connect_timeout=1,
),
user=app.config["GTAD_BIND_DN"],
password=app.config["GTAD_BIND_PASSWORD"],
auto_bind=True,
raise_exceptions=True,
receive_timeout=1,
)
with sentry_sdk.start_span(op="gtad.search"):
result = ldap.search(
search_base="dc=ad,dc=gatech,dc=edu",
search_filter="(uid=" + uid + ")",
attributes=["title", "department"],
)
if result is True:
for entry in ldap.entries:
attributes: Dict[str, List[str]] = loads(entry.entry_to_json()).get(
"attributes", {}
)
return attributes
return None
@cache.cached(key_prefix="realms")
def get_realms() -> List[Dict[str, Any]]:
"""
Get realm information from Keycloak
"""
keycloak_response = keycloak.get(
url=urlunparse(
(
urlparse(app.config["KEYCLOAK_METADATA_URL"]).scheme,
urlparse(app.config["KEYCLOAK_METADATA_URL"]).netloc,
"/admin/realms",
"",
"",
"",
)
),
timeout=(5, 5),
)
keycloak_response.raise_for_status()
return keycloak_response.json() # type: ignore
@cache.memoize()
def get_actor(**kwargs: str) -> Dict[str, Union[str, None]]:
"""
Get the display name and link for an event actor
"""
if (
"full_name" in kwargs
and "gtPersonDirectoryId" in kwargs
and kwargs["gtPersonDirectoryId"] is not None
):
return {
"actorDisplayName": kwargs["full_name"],
"actorLink": "/view/" + kwargs["gtPersonDirectoryId"],
}
if (
"full_name" in kwargs
and "id" in kwargs
and kwargs["id"] is not None
and "is_service_account" in kwargs
and kwargs["is_service_account"] is True # type: ignore
):
display_name = kwargs["full_name"]
if display_name.startswith("Service Account for "):
display_name = display_name[len("Service Account for ") :] # noqa
return {
"actorDisplayName": display_name,
"actorLink": app.config["APIARY_BASE_URL"] + "/nova/resources/users/" + kwargs["id"],
}
if "gtPersonDirectoryId" in kwargs or "uid" in kwargs:
gted_account = get_gted_primary_account(**kwargs)
if gted_account is None:
raise InternalServerError(
"Failed to locate GTED account with given " + list(dict.keys(kwargs))[0]
)
return {
"actorDisplayName": gted_account["givenName"] + " " + gted_account["sn"],
"actorLink": "/view/" + gted_account["gtPersonDirectoryId"],
}
if "impersonator" in kwargs and "impersonator_realm" in kwargs:
for realm in get_realms():
if kwargs["impersonator_realm"] == realm["realm"]:
keycloak_response = keycloak.get(
url=urlunparse(
(
urlparse(app.config["KEYCLOAK_METADATA_URL"]).scheme,
urlparse(app.config["KEYCLOAK_METADATA_URL"]).netloc,
"/admin/realms/" + realm["realm"] + "/users",
"",
"",
"",
)
),
params={
"username": kwargs["impersonator"],
"exact": True,
},
timeout=(5, 5),
)
keycloak_response.raise_for_status()
keycloak_accounts = keycloak_response.json()
if len(keycloak_accounts) == 0:
raise InternalServerError(
"Failed to locate Keycloak account for impersonator "
+ kwargs["impersonator"]
+ " in realm "
+ kwargs["impersonator_realm"]
)
return get_actor( # type: ignore
realmId=realm["id"], userId=keycloak_accounts[0]["id"]
)
if "realmId" in kwargs and "userId" in kwargs:
for realm in get_realms():
if kwargs["realmId"] == realm["id"]:
keycloak_response = keycloak.get(
url=urlunparse(
(
urlparse(app.config["KEYCLOAK_METADATA_URL"]).scheme,
urlparse(app.config["KEYCLOAK_METADATA_URL"]).netloc,
"/admin/realms/" + realm["realm"] + "/users/" + kwargs["userId"],
"",
"",
"",
)
),
timeout=(5, 5),
)
keycloak_response.raise_for_status()
keycloak_account = keycloak_response.json()
if (
fullmatch(
GEORGIA_TECH_USERNAME_REGEX,
keycloak_account["username"],
IGNORECASE,
)
is not None
):
return get_actor(uid=keycloak_account["username"]) # type: ignore
actor_display_name = keycloak_account["username"]
if actor_display_name.startswith("service-account-"):
actor_display_name = actor_display_name[len("service-account-") :] # noqa
return {
"actorDisplayName": actor_display_name,
"actorLink": urlunparse(
(
urlparse(app.config["KEYCLOAK_METADATA_URL"]).scheme,
urlparse(app.config["KEYCLOAK_METADATA_URL"]).netloc,
"/admin/master/console/",
"",
"",
"/" + realm["realm"] + "/users/" + keycloak_account["id"] + "/settings",
)
),
}
if "apiary_user_id" in kwargs:
user = search_apiary(apiary_user_id=kwargs["apiary_user_id"])
if user is not None and user.get("full_name") is not None:
return {
"actorDisplayName": user["full_name"],
}
if "email" in kwargs:
email_results = search_by_email(
Address(addr_spec=kwargs["email"]), with_gted=False, with_title_and_organization=False
)
if len(email_results["results"]) > 0:
return {
"actorDisplayName": email_results["results"][0]["givenName"]
+ " "
+ email_results["results"][0]["surname"],
"actorLink": "/view/" + email_results["results"][0]["directoryId"],
}
if "customer_id" in kwargs:
credentials = service_account.Credentials.from_service_account_info( # type: ignore
info=app.config["GOOGLE_SERVICE_ACCOUNT_CREDENTIALS"],
scopes=[
"https://www.googleapis.com/auth/admin.directory.user.readonly",
"https://www.googleapis.com/auth/admin.directory.customer.readonly",
],
subject=app.config["GOOGLE_SUBJECT"],
)
directory = build(serviceName="admin", version="directory_v1", credentials=credentials)
customer_details = (
directory.customers().get(customerKey=kwargs["customer_id"]).execute()
)
user_details = directory.users().get(userKey=kwargs["email"]).execute()
return {
"actorDisplayName": user_details["name"]["fullName"],
"actorLink": "https://www.google.com/a/"
+ customer_details["customerDomain"]
+ "/ServiceLogin?continue=https://admin.google.com/ac/search?query="
+ user_details["primaryEmail"],
}
if (
"callerType" in kwargs
and "key" in kwargs
and kwargs["callerType"] == "KEY"
and kwargs["key"] == "SYSTEM"
):
return {
"actorDisplayName": "system",
"actorLink": None,
}
raise InternalServerError("Unable to identify actor, given: " + dumps(kwargs))
def get_client_display_name(**kwargs: str) -> str:
"""
Get the display name for a client from a Keycloak event
"""
if "realmId" in kwargs and "clientId" in kwargs:
for realm in get_realms():
if kwargs["realmId"] == realm["id"]:
keycloak_response = keycloak.get(
url=urlunparse(
(
urlparse(app.config["KEYCLOAK_METADATA_URL"]).scheme,
urlparse(app.config["KEYCLOAK_METADATA_URL"]).netloc,
"/admin/realms/" + realm["realm"] + "/clients/" + kwargs["clientId"],
"",
"",
"",
)
),
timeout=(5, 5),
)
keycloak_response.raise_for_status()
print(keycloak_response.text)
return keycloak_response.json()["clientId"] # type: ignore
raise InternalServerError("Unable to identify client")
def search_keycloak(**kwargs: Union[str, bool]) -> List[Dict[str, Any]]:
"""
Search Keycloak for accounts matching criteria specified in kwargs
"""
keycloak_response = keycloak.get(
url=urlunparse(
(
urlparse(app.config["KEYCLOAK_METADATA_URL"]).scheme,
urlparse(app.config["KEYCLOAK_METADATA_URL"]).netloc,
"/admin/realms/" + app.config["KEYCLOAK_REALM"] + "/users",
"",
"",
"",
)
),
params=kwargs,
timeout=(5, 5),
)
keycloak_response.raise_for_status()
for account in keycloak_response.json():
cursor = db().execute(
"SELECT gt_person_directory_id FROM crosswalk WHERE primary_username = (:username)",
{"username": account["username"]},
)
row = cursor.fetchone()
if row is not None:
db().execute(
(
"UPDATE crosswalk SET keycloak_user_id = (:keycloak_user_id) WHERE gt_person_directory_id = (:gt_person_directory_id)" # noqa
),
{
"keycloak_user_id": account["id"],
"gt_person_directory_id": row[0],
},
)
db().execute(
(
"INSERT INTO crosswalk_email_address (email_address, gt_person_directory_id)"
" VALUES (:email_address, :gt_person_directory_id)"
" ON CONFLICT DO UPDATE SET gt_person_directory_id = (:gt_person_directory_id) WHERE email_address = (:email_address)" # noqa
),
{
"email_address": account["email"],
"gt_person_directory_id": row[0],
},
)
workspace_email = get_attribute_value("googleWorkspaceAccount", account)
if workspace_email is not None:
db().execute(
(
"INSERT INTO crosswalk_email_address (email_address, gt_person_directory_id)" # noqa
" VALUES (:email_address, :gt_person_directory_id)"
" ON CONFLICT DO UPDATE SET gt_person_directory_id = (:gt_person_directory_id) WHERE email_address = (:email_address)" # noqa
),
{
"email_address": workspace_email,
"gt_person_directory_id": row[0],
},
)
ramp_email = get_attribute_value("rampLoginEmailAddress", account)
if ramp_email is not None:
db().execute(
(
"INSERT INTO crosswalk_email_address (email_address, gt_person_directory_id)" # noqa
" VALUES (:email_address, :gt_person_directory_id)"
" ON CONFLICT DO UPDATE SET gt_person_directory_id = (:gt_person_directory_id) WHERE email_address = (:email_address)" # noqa
),
{
"email_address": ramp_email,
"gt_person_directory_id": row[0],
},
)
return keycloak_response.json() # type: ignore
@cache.memoize(
response_filter=lambda result: result is not None,
args_to_ignore=["force_refresh"],
forced_update=lambda *args, force_refresh=False, **kwargs: force_refresh,
)
def search_apiary( # pylint: disable=too-many-arguments
*,
directory_id: Union[str, None] = None,
gtid: Union[str, int, None] = None,
uid: Union[str, None] = None,
apiary_user_id: Union[str, int, None] = None,
email: Union[str, None] = None,
include: Union[List[str], None] = None,
force_refresh: bool = False,
) -> Union[Dict[str, Any], None]:
"""
Look up a single user in Apiary by one of the supported identifiers and update Crosswalk
with the returned identifiers (gtPersonDirectoryId, gtid, primary_username, email addresses).
Exactly one of directory_id, gtid, uid, apiary_user_id, email must be provided. On 404 for
a directory_id or uid lookup, automatically retry with a gtid resolved from Crosswalk
(falling back to GTED) if available.
"""
provided = {
"directory_id": directory_id,
"gtid": gtid,
"uid": uid,
"apiary_user_id": apiary_user_id,