-
Notifications
You must be signed in to change notification settings - Fork 45
/
docusign_models.py
2467 lines (2152 loc) · 127 KB
/
docusign_models.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
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
# Copyright The Linux Foundation and each contributor to CommunityBridge.
# SPDX-License-Identifier: MIT
"""
Easily perform signing workflows using DocuSign signing service with pydocusign.
NOTE: This integration uses DocuSign's Legacy Authentication REST API Integration.
https://developers.docusign.com/esign-rest-api/guides/post-go-live
"""
import io
import json
import boto3
import os
import urllib.request
import uuid
import xml.etree.ElementTree as ET
from typing import Any, Dict, List, Optional
from urllib.parse import urlparse
from datetime import datetime
import cla
import pydocusign # type: ignore
import requests
from attr import dataclass
from cla.controllers.lf_group import LFGroup
from cla.models import DoesNotExist, signing_service_interface
from cla.models.dynamo_models import (Company, Document, Event, Gerrit,
Project, Signature, User)
from cla.models.event_types import EventType
from cla.models.s3_storage import S3Storage
from cla.user_service import UserService
from cla.utils import (append_email_help_sign_off_content, get_corporate_url,
get_email_help_content, get_project_cla_group_instance)
from pydocusign.exceptions import DocuSignException # type: ignore
stage = os.environ.get('STAGE', '')
api_base_url = os.environ.get('CLA_API_BASE', '')
root_url = os.environ.get('DOCUSIGN_ROOT_URL', '')
username = os.environ.get('DOCUSIGN_USERNAME', '')
password = os.environ.get('DOCUSIGN_PASSWORD', '')
integrator_key = os.environ.get('DOCUSIGN_INTEGRATOR_KEY', '')
lf_group_client_url = os.environ.get('LF_GROUP_CLIENT_URL', '')
lf_group_client_id = os.environ.get('LF_GROUP_CLIENT_ID', '')
lf_group_client_secret = os.environ.get('LF_GROUP_CLIENT_SECRET', '')
lf_group_refresh_token = os.environ.get('LF_GROUP_REFRESH_TOKEN', '')
lf_group = LFGroup(lf_group_client_url, lf_group_client_id, lf_group_client_secret, lf_group_refresh_token)
signature_table = 'cla-{}-signatures'.format(stage)
class ProjectDoesNotExist(Exception):
pass
class CompanyDoesNotExist(Exception):
pass
class UserDoesNotExist(Exception):
pass
class CCLANotFound(Exception):
pass
class UserNotWhitelisted(Exception):
pass
class SigningError(Exception):
def __init__(self, response):
self.response = response
class DocuSign(signing_service_interface.SigningService):
"""
CLA signing service backed by DocuSign.
"""
TAGS = {'envelope_id': '{http://www.docusign.net/API/3.0}EnvelopeID',
'type': '{http://www.docusign.net/API/3.0}Type',
'email': '{http://www.docusign.net/API/3.0}Email',
'user_name': '{http://www.docusign.net/API/3.0}UserName',
'routing_order': '{http://www.docusign.net/API/3.0}RoutingOrder',
'sent': '{http://www.docusign.net/API/3.0}Sent',
'decline_reason': '{http://www.docusign.net/API/3.0}DeclineReason',
'status': '{http://www.docusign.net/API/3.0}Status',
'recipient_ip_address': '{http://www.docusign.net/API/3.0}RecipientIPAddress',
'client_user_id': '{http://www.docusign.net/API/3.0}ClientUserId',
'custom_fields': '{http://www.docusign.net/API/3.0}CustomFields',
'tab_statuses': '{http://www.docusign.net/API/3.0}TabStatuses',
'account_status': '{http://www.docusign.net/API/3.0}AccountStatus',
'recipient_id': '{http://www.docusign.net/API/3.0}RecipientId',
'recipient_statuses': '{http://www.docusign.net/API/3.0}RecipientStatuses',
'recipient_status': '{http://www.docusign.net/API/3.0}RecipientStatus',
'field_value': '{http://www.docusign.net/API/3.0}value',
'agreement_date': '{http://www.docusign.net/API/3.0}AgreementDate',
'signed_date': '{http://www.docusign.net/API/3.0}Signed',
}
def __init__(self):
self.client = None
self.s3storage = None
self.dynamo_client = None
def initialize(self, config):
self.dynamo_client = boto3.client('dynamodb')
self.client = pydocusign.DocuSignClient(root_url=root_url,
username=username,
password=password,
integrator_key=integrator_key)
try:
login_data = self.client.login_information()
login_account = login_data['loginAccounts'][0]
base_url = login_account['baseUrl']
account_id = login_account['accountId']
url = urlparse(base_url)
parsed_root_url = '{}://{}/restapi/v2'.format(url.scheme, url.netloc)
except Exception as e:
cla.log.error('Error logging in to DocuSign: {}'.format(e))
return {'errors': {'Error initializing DocuSign'}}
self.client = pydocusign.DocuSignClient(root_url=parsed_root_url,
account_url=base_url,
account_id=account_id,
username=username,
password=password,
integrator_key=integrator_key)
self.s3storage = S3Storage()
self.s3storage.initialize(None)
def request_individual_signature(self, project_id, user_id, return_url=None, return_url_type="github", callback_url=None,
preferred_email=None):
request_info = 'project: {project_id}, user: {user_id} with return_url: {return_url}'.format(
project_id=project_id, user_id=user_id, return_url=return_url)
cla.log.debug('Individual Signature - creating new signature for: {}'.format(request_info))
# Ensure this is a valid user
user_id = str(user_id)
try:
user = User(preferred_email=preferred_email)
user.load(user_id)
cla.log.debug('Individual Signature - loaded user name: {}, '
'user email: {}, gh user: {}, gh id: {}'.
format(user.get_user_name(), user.get_user_email(), user.get_github_username(),
user.get_user_github_id()))
except DoesNotExist as err:
cla.log.warning('Individual Signature - user ID was NOT found for: {}'.format(request_info))
return {'errors': {'user_id': str(err)}}
# Ensure the project exists
try:
project = Project()
project.load(project_id)
cla.log.debug('Individual Signature - loaded project id: {}, name: {}, '.
format(project.get_project_id(), project.get_project_name()))
except DoesNotExist as err:
cla.log.warning('Individual Signature - project ID NOT found for: {}'.format(request_info))
return {'errors': {'project_id': str(err)}}
# Check for active signature object with this project. If the user has
# signed the most recent major version, they do not need to sign again.
cla.log.debug('Individual Signature - loading latest user signature for user: {}, project: {}'.
format(user, project))
latest_signature = user.get_latest_signature(str(project_id))
cla.log.debug('Individual Signature - loaded latest user signature for user: {}, project: {}'.
format(user, project))
cla.log.debug('Individual Signature - loading latest individual document for project: {}'.
format(project))
last_document = project.get_latest_individual_document()
cla.log.debug('Individual Signature - loaded latest individual document for project: {}'.
format(project))
cla.log.debug('Individual Signature - creating default individual values for user: {}'.format(user))
default_cla_values = create_default_individual_values(user)
cla.log.debug('Individual Signature - created default individual values: {}'.format(default_cla_values))
# Generate signature callback url
cla.log.debug('Individual Signature - get active signature metadata')
signature_metadata = cla.utils.get_active_signature_metadata(user_id)
cla.log.debug('Individual Signature - get active signature metadata: {}'.format(signature_metadata))
cla.log.debug('Individual Signature - get individual signature callback url')
if return_url_type.lower() == "github":
callback_url = cla.utils.get_individual_signature_callback_url(user_id, signature_metadata)
elif return_url_type.lower() == "gitlab":
callback_url = cla.utils.get_individual_signature_callback_url_gitlab(user_id, signature_metadata)
cla.log.debug('Individual Signature - get individual signature callback url: {}'.format(callback_url))
if latest_signature is not None and \
last_document.get_document_major_version() == latest_signature.get_signature_document_major_version():
cla.log.debug('Individual Signature - user already has a signatures with this project: {}'.
format(latest_signature.get_signature_id()))
# Re-generate and set the signing url - this will update the signature record
self.populate_sign_url(latest_signature, callback_url, default_values=default_cla_values,
preferred_email=preferred_email)
return {'user_id': user_id,
'project_id': project_id,
'signature_id': latest_signature.get_signature_id(),
'sign_url': latest_signature.get_signature_sign_url()}
else:
cla.log.debug('Individual Signature - user does NOT have a signatures with this project: {}'.
format(project))
# Get signature return URL
if return_url is None:
return_url = cla.utils.get_active_signature_return_url(user_id, signature_metadata)
cla.log.debug('Individual Signature - setting signature return_url to {}'.format(return_url))
if return_url is None:
cla.log.warning('No active signature found for user - cannot generate '
'return_url without knowing where the user came from')
return {'user_id': str(user_id),
'project_id': str(project_id),
'signature_id': None,
'sign_url': None,
'error': 'No active signature found for user - cannot generate return_url without knowing where the user came from'}
# Get latest document
try:
cla.log.debug('Individual Signature - loading project latest individual document...')
document = project.get_latest_individual_document()
cla.log.debug('Individual Signature - loaded project latest individual document: {}'.format(document))
except DoesNotExist as err:
cla.log.warning('Individual Signature - project individual document does NOT exist for: {}'.
format(request_info))
return {'errors': {'project_id': project_id, 'message': str(err)}}
# If the CCLA/ICLA template is missing (not created in the project console), we won't have a document
# return an error
if not document:
return {'errors': {'project_id': project_id, 'message': 'missing template document'}}
# Create new Signature object
cla.log.debug('Individual Signature - creating new signature document '
'project_id: {}, user_id: {}, return_url: {}, callback_url: {}'.
format(project_id, user_id, return_url, callback_url))
signature = Signature(signature_id=str(uuid.uuid4()),
signature_project_id=project_id,
signature_document_major_version=document.get_document_major_version(),
signature_document_minor_version=document.get_document_minor_version(),
signature_reference_id=user_id,
signature_reference_type='user',
signature_reference_name=user.get_user_name(),
signature_type='cla',
signature_return_url_type=return_url_type,
signature_signed=False,
signature_approved=True,
signature_return_url=return_url,
signature_callback_url=callback_url)
# Set signature ACL
if return_url_type.lower() == "github":
acl = user.get_user_github_id()
elif return_url_type.lower() == "gitlab":
acl = user.get_user_gitlab_id()
cla.log.debug('Individual Signature - setting ACL using user {} id: {}'.format(return_url_type, acl))
signature.set_signature_acl('{}:{}'.format(return_url_type.lower(),acl))
# Populate sign url
self.populate_sign_url(signature, callback_url, default_values=default_cla_values,
preferred_email=preferred_email)
# Save signature
signature.save()
cla.log.debug('Individual Signature - Saved signature for: {}'.format(request_info))
response = {'user_id': str(user_id),
'project_id': project_id,
'signature_id': signature.get_signature_id(),
'sign_url': signature.get_signature_sign_url()}
cla.log.debug('Individual Signature - returning response: {}'.format(response))
return response
def request_individual_signature_gerrit(self, project_id, user_id, return_url=None):
request_info = 'project: {project_id}, user: {user_id} with return_url: {return_url}'.format(
project_id=project_id, user_id=user_id, return_url=return_url)
cla.log.info('Creating new Gerrit signature for {}'.format(request_info))
# Ensure this is a valid user
user_id = str(user_id)
try:
user = User()
user.load(user_id)
except DoesNotExist as err:
cla.log.warning('User ID does NOT found when requesting a signature for: {}'.format(request_info))
return {'errors': {'user_id': str(err)}}
# Ensure the project exists
try:
project = Project()
project.load(project_id)
except DoesNotExist as err:
cla.log.warning('Project ID does NOT found when requesting a signature for: {}'.format(request_info))
return {'errors': {'project_id': str(err)}}
callback_url = self._generate_individual_signature_callback_url_gerrit(user_id)
default_cla_values = create_default_individual_values(user)
# Check for active signature object with this project. If the user has
# signed the most recent major version, they do not need to sign again.
latest_signature = user.get_latest_signature(str(project_id))
last_document = project.get_latest_individual_document()
if latest_signature is not None and \
last_document.get_document_major_version() == latest_signature.get_signature_document_major_version():
cla.log.info('User already has a signatures with this project: %s', latest_signature.get_signature_id())
# Re-generate and set the signing url - this will update the signature record
self.populate_sign_url(latest_signature, callback_url, default_values=default_cla_values)
return {'user_id': user_id,
'project_id': project_id,
'signature_id': latest_signature.get_signature_id(),
'sign_url': latest_signature.get_signature_sign_url()}
# the github flow has an option to have the return_url as a blank field,
# and retrieves the return_url from the signature's metadata (github org id, PR id, etc.)
# It will return the user to the pull request page.
# For Gerrit users, we want the return_url to be the link to the Gerrit Instance's page.
# Since Gerrit users will be able to make changes once they are part of the LDAP Group,
# They do not need to be directed to a specific code submission on Gerrit.
# Ensure return_url is set to the Gerrit instance url
try:
gerrits = Gerrit().get_gerrit_by_project_id(project_id)
if len(gerrits) >= 1:
# Github sends the user back to the pull request.
# Gerrit should send it back to the Gerrit instance url.
return_url = gerrits[0].get_gerrit_url()
except DoesNotExist as err:
cla.log.error('Gerrit Instance not found by the given project ID: %s',
project_id)
return {'errors': {'project_id': str(err)}}
try:
document = project.get_project_individual_document()
except DoesNotExist as err:
cla.log.warning('Document does NOT exist when searching for ICLA for: {}'.format(request_info))
return {'errors': {'project_id': str(err)}}
# Create new Signature object
signature = Signature(signature_id=str(uuid.uuid4()),
signature_project_id=project_id,
signature_document_major_version=document.get_document_major_version(),
signature_document_minor_version=document.get_document_minor_version(),
signature_reference_id=user_id,
signature_reference_type='user',
signature_reference_name=user.get_user_name(),
signature_type='cla',
signature_return_url_type='Gerrit',
signature_signed=False,
signature_approved=True,
signature_return_url=return_url,
signature_callback_url=callback_url)
# Set signature ACL
signature.set_signature_acl(user.get_lf_username())
cla.log.info('Set the signature ACL for: {}'.format(request_info))
# Populate sign url
self.populate_sign_url(signature, callback_url, default_values=default_cla_values)
# Save signature
signature.save()
cla.log.info('Saved the signature for: {}'.format(request_info))
return {'user_id': str(user_id),
'project_id': project_id,
'signature_id': signature.get_signature_id(),
'sign_url': signature.get_signature_sign_url()}
@staticmethod
def check_and_prepare_employee_signature(project_id, company_id, user_id) -> dict:
# Before an employee begins the signing process, ensure that
# 1. The given project, company, and user exists
# 2. The company signatory has signed the CCLA for their company.
# 3. The user is included as part of the whitelist of the CCLA that the company signed.
# Returns an error if any of the above is false.
fn = 'docusign_models.check_and_prepare_employee_signature'
# Keep a variable with the actual company_id - may swap the original selected company id to use another
# company id if another signing entity name (another related company) is already signed
actual_company_id = company_id
request_info = f'project: {project_id}, company: {actual_company_id}, user: {user_id}'
cla.log.info(f'{fn} - check and prepare employee signature for {request_info}')
# Ensure the project exists
project = Project()
try:
cla.log.debug(f'{fn} - loading cla group by id: {project_id}...')
project.load(str(project_id))
cla.log.debug(f'{fn} - cla group {project.get_project_name()} exists for: {request_info}')
except DoesNotExist:
cla.log.warning(f'{fn} - project does NOT exist for: {request_info}')
return {'errors': {'project_id': f'Project ({project_id}) does not exist.'}}
# Ensure the company exists
company = Company()
try:
cla.log.debug(f'{fn} - loading company by id: {actual_company_id}...')
company.load(str(actual_company_id))
cla.log.debug(f'{fn} - company {company.get_company_name()} exists for: {request_info}')
except DoesNotExist:
cla.log.warning(f'{fn} - company does NOT exist for: {request_info}')
return {'errors': {'company_id': f'Company ({actual_company_id}) does not exist.'}}
# Ensure the user exists
user = User()
try:
cla.log.debug(f'{fn} - loading user by id: {user_id}...')
user.load(str(user_id))
cla.log.debug(f'{fn} - user {user.get_user_name()} exists for: {request_info}')
except DoesNotExist:
cla.log.warning(f'User does NOT exist for: {request_info}')
return {'errors': {'user_id': f'User ({user_id}) does not exist.'}}
# Ensure the company actually has a CCLA with this project.
# ccla_signatures = Signature().get_signatures_by_project(
# project_id,
# signature_reference_type='company',
# signature_reference_id=company.get_company_id()
# )
cla.log.debug(f'{fn} - loading CCLA signatures by cla group: {project.get_project_name()} '
f'and company id: {company.get_company_id()}...')
ccla_signatures = Signature().get_ccla_signatures_by_company_project(
company_id=company.get_company_id(),
project_id=project_id
)
if len(ccla_signatures) < 1:
# Save our message
msg = (f'{fn} - project {project.get_project_name()} and '
f'company {company.get_company_name()} does not have CCLA for: {request_info}')
cla.log.debug(msg)
return {'errors': {'missing_ccla': 'Company does not have CCLA with this project.',
'company_id': actual_company_id,
'company_name': company.get_company_name(),
'signing_entity_name': company.get_signing_entity_name(),
'company_external_id': company.get_company_external_id(),
}
}
# # Ok - long story here, we could have the tricky situation where now that we've added a concept of Signing
# # Entity Names we have, basically, a set of 'child' companies all under a common external_id (SFID). This
# # would have been so much simpler if SF supported Parent/Child company relationships to model things like
# # Subsidiary and Patten holding companies.
# #
# # Scenario:
# #
# # Deal Company (SFID: 123, CompanyID: AAA)
# # Deal Company Subsidiary 1 - (SFID: 123, CompanyID: BBB)
# # Deal Company Subsidiary 2 - (SFID: 123, CompanyID: CCC) - SIGNED!
# # Deal Company Subsidiary 3 - (SFID: 123, CompanyID: DDD)
# # Deal Company Subsidiary 4 - (SFID: 123, CompanyID: EEE)
# #
# # Now - the check-prepare-employee signature request could have come from any of the above companies with
# # different a company_id - the contributor may have selected the correct option (CCC), the one that was
# # signed and executed by a Signatory...or maybe none have been signed...or perhaps another one was signed
# # such as companyID BBB.
# #
# # Originally, we designed the system to keep track of all these sub-companies separately - different CLA
# # managers, different approval lists, etc.
# #
# # Later, the stakeholders wanted to group these all together as one but keep track of the signing entity
# # name for each project | company. They wanted to allow the users to select one for each (project |
# # organization) pair.
# #
# # So, we could have CLA signatories/managers wanting:
# #
# # - Project OpenCue + Deal Company Subsidiary 2
# # - Project OpenVDB + Deal Company Subsidiary 4
# # - Project OpenTelemetry + Deal Company
# #
# # As a result, we need to query the entire company family under the same external_id for a signed CCLA.
# # Currently, we only allow 1 of these to be signed for each Project | Company pair. Later, we may change
# # this behavior (it's been debated).
# #
# # Let's see if they signed the CCLA for another of the Company/Signed Entity Names for this
# # project - if so, let's return that one, if not, return the error
#
# # First, grab the current company's external ID/SFID
# company_external_id = company.get_company_external_id()
# # if missing, not much we can do...
# if company_external_id is None:
# cla.log.warning(f'{fn} - project {project.get_project_name()} and '
# f'company {company.get_company_name()} - company missing external id - '
# f'{request_info}')
# cla.log.warning(msg)
# return {'errors': {'missing_ccla': 'Company does not have CCLA with this project.',
# 'company_id': actual_company_id,
# 'company_name': company.get_company_name(),
# 'signing_entity_name': company.get_signing_entity_name(),
# 'company_external_id': company.get_company_external_id(),
# }
# }
#
# # Lookup the other companies by external id...will have 1 or more (current record plus possibly others)...
# company_list = company.get_company_by_external_id(company_external_id)
# # This shouldn't happen, let's trap for it anyway
# if not company_list:
# cla.log.warning(f'{fn} - project {project.get_project_name()} and '
# f'company {company.get_company_name()} - unable to lookup companies by external id: '
# f'{company_external_id} - {request_info}')
# cla.log.warning(msg)
# return {'errors': {'missing_ccla': 'Company does not have CCLA with this project.',
# 'company_id': actual_company_id,
# 'company_name': company.get_company_name(),
# 'signing_entity_name': company.get_signing_entity_name(),
# 'company_external_id': company.get_company_external_id(),
# }
# }
#
# # As we loop, let's use a flag to keep track if we find a CCLA
# found_ccla = False
# for other_company in company_list:
# cla.log.debug(f'{fn} - loading CCLA signatures by cla group: {project.get_project_name()} '
# f'and company id: {other_company.get_company_id()}...')
# ccla_signatures = Signature().get_ccla_signatures_by_company_project(
# company_id=other_company.get_company_id(),
# project_id=project_id
# )
#
# # Do we have a signed CCLA for this project|company ? If so, we found it - use it! Should NOT have
# # more than one of the companies with Signed CCLAs
# if len(ccla_signatures) > 0:
# found_ccla = True
# # Need to load the correct company record
# try:
# # Reset the actual company id value since we found a CCLA under a related signing entity name
# # company
# actual_company_id = ccla_signatures[0].get_signature_reference_id()
# # Reset the request_info string with the updated company_id, will use it for debug/warning below
# request_info = f'project: {project_id}, company: {actual_company_id}, user: {user_id}'
# cla.log.debug(f'{fn} - loading correct signed CCLA company by id: '
# f'{ccla_signatures[0].get_signature_reference_id()} '
# f'with signed entity name: {ccla_signatures[0].get_signing_entity_name()} ...')
# company.load(ccla_signatures[0].get_signature_reference_id())
# cla.log.debug(f'{fn} - loaded company {company.get_company_name()} '
# f'with signing entity name: {company.get_signing_entity_name()} '
# f'for {request_info}.')
# except DoesNotExist:
# cla.log.warning(f'{fn} - company does NOT exist '
# f'using company_id: {ccla_signatures[0].get_signature_reference_id()} '
# f'for: {request_info}')
# return {'errors': {'company_id': f'Company ({ccla_signatures[0].get_signature_reference_id()}) '
# 'does not exist.'}}
# break
#
# # if we didn't fine a signed CCLA under any of the other companies...
# if not found_ccla:
# # Give up
# cla.log.warning(msg)
# return {'errors': {'missing_ccla': 'Company does not have CCLA with this project.',
# 'company_id': actual_company_id,
# 'company_name': company.get_company_name(),
# 'signing_entity_name': company.get_signing_entity_name(),
# 'company_external_id': company.get_company_external_id(),
# }
# }
# Add a note in the log if we have more than 1 signed and approved CCLA signature
if len(ccla_signatures) > 1:
cla.log.warning(f'{fn} - project {project.get_project_name()} and '
f'company {company.get_company_name()} has more than 1 CCLA '
f'signature: {len(ccla_signatures)}')
cla.log.debug(f'{fn} CLA Group {project.get_project_name()} and company {company.get_company_name()} has '
f'{len(ccla_signatures)} CCLAs for: {request_info}')
# TODO - DAD: why only grab the first one???
ccla_signature = ccla_signatures[0]
# Ensure user is approved for this company.
if not user.is_approved(ccla_signature):
# TODO: DAD - update this warning message
cla.log.warning(f'{fn} - user is not authorized for this CCLA: {request_info}')
return {'errors': {'ccla_approval_list': 'user not authorized for this ccla',
'company_id': actual_company_id,
'company_name': company.get_company_name(),
'signing_entity_name': company.get_signing_entity_name(),
'company_external_id': company.get_company_external_id(),
}
}
cla.log.info(f'{fn} - user is approved for this CCLA: {request_info}')
# Assume this company is the user's employer. Associated the company with the user in the EasyCLA user record
# For v2, we make the association with the platform via the platform project service via a separate API
# call from the UI
# TODO: DAD - we should check to see if they already have a company id assigned
if user.get_user_company_id() != actual_company_id:
user.set_user_company_id(str(actual_company_id))
event_data = (f'The user {user.get_user_name()} with GitHub username '
f'{user.get_github_username()} ('
f'{user.get_user_github_id()}) and user ID '
f'{user.get_user_id()} '
f'is now associated with company {company.get_company_name()} for '
f'project {project.get_project_name()}')
event_summary = (f'User {user.get_user_name()} with GitHub username '
f'{user.get_github_username()} '
f'is now associated with company {company.get_company_name()} for '
f'project {project.get_project_name()}.')
Event.create_event(
event_type=EventType.UserAssociatedWithCompany,
event_company_id=actual_company_id,
event_company_name=company.get_company_name(),
event_cla_group_id=project_id,
event_project_name=project.get_project_name(),
event_user_id=user.get_user_id(),
event_user_name=user.get_user_name() if user else None,
event_data=event_data,
event_summary=event_summary,
contains_pii=True,
)
# Take a moment to update the user record's github information
github_username = user.get_user_github_username()
github_id = user.get_user_github_id()
if github_username is None and github_id is not None:
github_username = cla.utils.lookup_user_github_username(github_id)
if github_username is not None:
cla.log.debug(f'{fn} - updating user record - adding github username: {github_username}')
user.set_user_github_username(github_username)
# Attempt to fetch the github id based on the github username
if github_id is None and github_username is not None:
github_username = github_username.strip()
github_id = cla.utils.lookup_user_github_id(github_username)
if github_id is not None:
cla.log.debug(f'{fn} - updating user record - adding github id: {github_id}')
user.set_user_github_id(github_id)
user.save()
cla.log.info(f'{fn} - assigned company ID to user. Employee is ready to sign the CCLA: {request_info}')
return {'success': {'the employee is ready to sign the CCLA'}}
def request_employee_signature(self, project_id, company_id, user_id, return_url=None, return_url_type="github"):
fn = 'docusign_models.check_and_prepare_employee_signature'
request_info = f'cla group: {project_id}, company: {company_id}, user: {user_id} with return_url: {return_url}'
cla.log.info(f'{fn} - processing request_employee_signature request with {request_info}')
check_and_prepare_signature = self.check_and_prepare_employee_signature(project_id, company_id, user_id)
# Check if there are any errors while preparing the signature.
if 'errors' in check_and_prepare_signature:
cla.log.warning(f'{fn} - error in check_and_prepare_signature with: {request_info} - '
f'signatures: {check_and_prepare_signature}')
return check_and_prepare_signature
employee_signature = Signature().get_employee_signature_by_company_project(
company_id=company_id, project_id=project_id, user_id=user_id)
# Return existing signature if employee has signed it
if employee_signature is not None:
cla.log.info(f'{fn} - employee has previously acknowledged their company affiliation '
f'for request_info: {request_info} - signature: {employee_signature}')
return employee_signature.to_dict()
cla.log.info(f'{fn} - employee has NOT previously acknowledged their company affiliation for : {request_info}')
# Requires us to know where the user came from.
signature_metadata = cla.utils.get_active_signature_metadata(user_id)
if return_url is None:
cla.log.debug(f'{fn} - no return URL for: {request_info}')
return_url = cla.utils.get_active_signature_return_url(user_id, signature_metadata)
cla.log.debug(f'{fn} - set return URL for: {request_info} to: {return_url}')
# project has already been checked from check_and_prepare_employee_signature. Load project with project ID.
project = Project()
cla.log.info(f'{fn} - loading cla group details for: {request_info}')
project.load(project_id)
cla.log.info(f'{fn} - loaded cla group details for: {request_info}')
# company has already been checked from check_and_prepare_employee_signature. Load company with company ID.
company = Company()
cla.log.info(f'{fn} - loading company details for: {request_info}')
company.load(company_id)
cla.log.info(f'{fn} - loaded company details for: {request_info}')
# user has already been checked from check_and_prepare_employee_signature. Load user with user ID.
user = User()
user.load(str(user_id))
# Get project's latest corporate document to get major/minor version numbers.
last_document = project.get_latest_corporate_document()
cla.log.info(f'{fn} - loaded the current cla document document details for: {request_info}')
# return_url may still be empty at this point - the console will deal with it
cla.log.info(f'{fn} - creating a new signature document for: {request_info}')
new_signature = Signature(signature_id=str(uuid.uuid4()),
signature_project_id=project_id,
signature_document_minor_version=last_document.get_document_minor_version(),
signature_document_major_version=last_document.get_document_major_version(),
signature_reference_id=user_id,
signature_reference_type='user',
signature_reference_name=user.get_user_name(),
signature_type='cla',
signature_signed=True,
signature_approved=True,
signature_return_url=return_url,
signature_user_ccla_company_id=company_id)
cla.log.info(f'{fn} - created new signature document for: {request_info} - signature: {new_signature}')
# Set signature ACL
if return_url_type.lower() == "github":
acl_value = f'github:{user.get_user_github_id()}'
elif return_url_type.lower() == "gitlab":
acl_value = f'gitlab:{user.get_user_gitlab_id()}'
cla.log.info(f'{fn} - assigning signature acl with value: {acl_value} for: {request_info}')
new_signature.set_signature_acl(acl_value)
# Save signature
# new_signature.save()
self._save_employee_signature(new_signature)
cla.log.info(f'{fn} - saved signature for: {request_info}')
event_data = (f'The user {user.get_user_name()} acknowledged the CLA employee affiliation for '
f'company {company.get_company_name()} with ID {company.get_company_id()}, '
f'cla group {project.get_project_name()} with ID {project.get_project_id()}.')
event_summary = (f'The user {user.get_user_name()} acknowledged the CLA employee affiliation for '
f'company {company.get_company_name()} and '
f'cla group {project.get_project_name()}.')
Event.create_event(
event_type=EventType.EmployeeSignatureCreated,
event_company_id=company_id,
event_cla_group_id=project_id,
event_user_id=user_id,
event_user_name=user.get_user_name() if user else None,
event_data=event_data,
event_summary=event_summary,
contains_pii=True,
)
# If the project does not require an ICLA to be signed, update the pull request and remove the active
# signature metadata.
if not project.get_project_ccla_requires_icla_signature():
cla.log.info(f'{fn} - cla group does not require a separate ICLA signature from the employee - updating PR')
if return_url_type.lower() == "github":
# Get repository
github_repository_id = signature_metadata['repository_id']
change_request_id = signature_metadata['pull_request_id']
installation_id = cla.utils.get_installation_id_from_github_repository(github_repository_id)
if installation_id is None:
return {'errors': {'github_repository_id': 'The given github repository ID does not exist. '}}
update_repository_provider(installation_id, github_repository_id, change_request_id)
elif return_url_type.lower() == "gitlab":
gitlab_repository_id = int(signature_metadata['repository_id'])
merge_request_id = int(signature_metadata['merge_request_id'])
organization_id = cla.utils.get_organization_id_from_gitlab_repository(gitlab_repository_id)
self._update_gitlab_mr(organization_id, gitlab_repository_id, merge_request_id)
if organization_id is None:
return {'errors': {'gitlab_repository_id': 'The given github repository ID does not exist. '}}
cla.utils.delete_active_signature_metadata(user_id)
else:
cla.log.info(f'{fn} - cla group requires ICLA signature from employee - PR has been left unchanged')
cla.log.info(f'{fn} - returning new signature for: {request_info} - signature: {new_signature}')
return new_signature.to_dict()
def _save_employee_signature(self,signature):
cla.log.info(f'Saving signature record (boto3): {signature}')
item = {
'signature_id' : {'S': signature.get_signature_id()},
'signature_project_id': {'S': signature.get_signature_project_id()},
'signature_document_minor_version': {'N': str(signature.get_signature_document_minor_version())},
'signature_document_major_version': {'N': str(signature.get_signature_document_major_version())},
'signature_reference_id': {'S': signature.get_signature_reference_id()},
'signature_reference_type': {'S': signature.get_signature_reference_type()},
'signature_type': {'S': signature.get_signature_type()},
'signature_signed': {'BOOL': signature.get_signature_signed()},
'signature_approved': {'BOOL': signature.get_signature_approved()},
'signature_acl': {'SS': list(signature.get_signature_acl())},
'signature_user_ccla_company_id': {'S': signature.get_signature_user_ccla_company_id()},
'date_modified': {'S': datetime.now().isoformat()},
'date_created': {'S': datetime.now().isoformat()}
}
if signature.get_signature_return_url() is not None:
item['signature_return_url'] = {'S': signature.get_signature_return_url()}
if signature.get_signature_reference_name() is not None:
item['signature_reference_name'] = {'S': signature.get_signature_reference_name()}
try:
self.dynamo_client.put_item(TableName=signature_table, Item=item)
except Exception as e:
cla.log.error(f'Error while saving signature record (boto3): {e}')
raise e
cla.log.info(f'Saved signature record (boto3): {signature}')
return signature.get_signature_id()
def request_employee_signature_gerrit(self, project_id, company_id, user_id, return_url=None):
fn = 'docusign_models.request_employee_signature_gerrit'
request_info = f'cla group: {project_id}, company: {company_id}, user: {user_id} with return_url: {return_url}'
cla.log.info(f'{fn} - processing request_employee_signature_gerrit request with {request_info}')
check_and_prepare_signature = self.check_and_prepare_employee_signature(project_id, company_id, user_id)
# Check if there are any errors while preparing the signature.
if 'errors' in check_and_prepare_signature:
cla.log.warning(f'{fn} - error in request_employee_signature_gerrit with: {request_info} - '
f'signatures: {check_and_prepare_signature}')
return check_and_prepare_signature
# Ensure user hasn't already signed this signature.
employee_signature = Signature().get_employee_signature_by_company_project(
company_id=company_id, project_id=project_id, user_id=user_id)
# Return existing signature if employee has signed it
if employee_signature is not None:
cla.log.info(f'{fn} - employee has signed for company: {company_id}, '
f'request_info: {request_info} - signature: {employee_signature}')
return employee_signature.to_dict()
cla.log.info(f'{fn} - employee has NOT previously acknowledged their company affiliation for : {request_info}')
# Retrieve Gerrits by Project reference ID
try:
cla.log.info(f'{fn} - loading gerrits for: {request_info}')
gerrits = Gerrit().get_gerrit_by_project_id(project_id)
except DoesNotExist as err:
cla.log.error(f'{fn} - cannot load Gerrit instance for: {request_info}')
return {'errors': {'missing_gerrit': str(err)}}
# project has already been checked from check_and_prepare_employee_signature. Load project with project ID.
project = Project()
cla.log.info(f'{fn} - loading cla group for: {request_info}')
project.load(project_id)
cla.log.info(f'{fn} - loaded cla group for: {request_info}')
# company has already been checked from check_and_prepare_employee_signature. Load company with company ID.
company = Company()
cla.log.info(f'{fn} - loading company details for: {request_info}')
company.load(company_id)
cla.log.info(f'{fn} - loaded company details for: {request_info}')
# user has already been checked from check_and_prepare_employee_signature. Load user with user ID.
user = User()
user.load(str(user_id))
# Get project's latest corporate document to get major/minor version numbers.
last_document = project.get_latest_corporate_document()
new_signature = Signature(signature_id=str(uuid.uuid4()),
signature_project_id=project_id,
signature_document_minor_version=last_document.get_document_minor_version(),
signature_document_major_version=last_document.get_document_major_version(),
signature_reference_id=user_id,
signature_reference_type='user',
signature_reference_name=user.get_user_name(),
signature_type='cla',
signature_signed=True,
signature_approved=True,
signature_return_url=return_url,
signature_user_ccla_company_id=company_id)
# Set signature ACL (user already validated in 'check_and_prepare_employee_signature')
new_signature.set_signature_acl(user.get_lf_username())
# Save signature before adding user to the LDAP Group.
cla.log.debug(f'{fn} - saving signature...{new_signature.to_dict()}')
try:
self._save_employee_signature(new_signature)
except Exception as ex:
cla.log.error(f'{fn} - unable to save signature error: {ex}')
return
cla.log.info(f'{fn} - saved signature for: {request_info}')
event_data = (f'The user {user.get_user_name()} acknowledged the CLA company affiliation for '
f'company {company.get_company_name()} with ID {company.get_company_id()}, '
f'project {project.get_project_name()} with ID {project.get_project_id()}.')
event_summary = (f'The user {user.get_user_name()} acknowledged the CLA company affiliation for '
f'company {company.get_company_name()} and '
f'project {project.get_project_name()}.')
Event.create_event(
event_type=EventType.EmployeeSignatureCreated,
event_company_id=company_id,
event_cla_group_id=project_id,
event_user_id=user_id,
event_user_name=user.get_user_name() if user else None,
event_data=event_data,
event_summary=event_summary,
contains_pii=True,
)
for gerrit in gerrits:
# For every Gerrit Instance of this project, add the user to the LDAP Group.
# this way we are able to keep track of signed signatures when user fails to be added to the LDAP GROUP.
group_id = gerrit.get_group_id_ccla()
# Add the user to the LDAP Group
try:
cla.log.debug(f'{fn} - adding user to group: {group_id}')
lf_group.add_user_to_group(group_id, user.get_lf_username())
except Exception as e:
cla.log.error(f'{fn} - failed in adding user to the LDAP group.{e} - {request_info}')
return
return new_signature.to_dict()
def _generate_individual_signature_callback_url_gerrit(self, user_id):
"""
Helper function to get a user's active signature callback URL for Gerrit
"""
return os.path.join(api_base_url, 'v2/signed/gerrit/individual', str(user_id))
def _get_corporate_signature_callback_url(self, project_id, company_id):
"""
Helper function to get the callback_url of a CCLA signature.
:param project_id: The ID of the project this CCLA is for.
:type project_id: string
:param company_id: The ID of the company signing the CCLA.
:type company_id: string
:return: The callback URL hit by the signing provider once the signature is complete.
:rtype: string
"""
return os.path.join(api_base_url, 'v2/signed/corporate', str(project_id), str(company_id))
def handle_signing_new_corporate_signature(self, signature, project, company, user,
signatory_name=None, signatory_email=None,
send_as_email=False, return_url_type=None, return_url=None):
fn = 'models.docusign_models.handle_signing_new_corporate_signature'
cla.log.debug(f'{fn} - Handle signing of new corporate signature - '
f'project: {project}, '
f'company: {company}, '
f'user id: {user}, '
f'signatory name: {signatory_name}, '
f'signatory email: {signatory_email} '
f'send email: {send_as_email}')
# Set the CLA Managers in the schedule
scheduleA = generate_manager_and_contributor_list([(signatory_name, signatory_email)])
# Signatory and the Initial CLA Manager
cla_template_values = create_default_company_values(
company, signatory_name, signatory_email,
user.get_user_name(), user.get_user_email(), scheduleA)
# Ensure the project/CLA group has a corporate template document
last_document = project.get_latest_corporate_document()
if last_document is None or \
last_document.get_document_major_version() is None or \
last_document.get_document_minor_version() is None:
cla.log.info(f'{fn} - CLA Group {project} does not have a CCLA')
return {'errors': {'project_id': 'Contract Group does not support CCLAs.'}}
# No signature exists, create the new Signature.
cla.log.info(f'{fn} - Creating new signature for project {project} on company {company}')
if signature is None:
signature = Signature(signature_id=str(uuid.uuid4()),
signature_project_id=project.get_project_id(),
signature_document_minor_version=last_document.get_document_minor_version(),
signature_document_major_version=last_document.get_document_major_version(),
signature_reference_id=company.get_company_id(),
signature_reference_type='company',
signature_reference_name=company.get_company_name(),
signature_type='ccla',
signatory_name=signatory_name,
signing_entity_name=company.get_signing_entity_name(),
signature_signed=False,
signature_approved=True)
callback_url = self._get_corporate_signature_callback_url(project.get_project_id(), company.get_company_id())
cla.log.info(f'{fn} - Setting callback_url: %s', callback_url)
signature.set_signature_callback_url(callback_url)
if not send_as_email: # get return url only for manual signing through console
cla.log.info(f'{fn} - Setting signature return_url to %s', return_url)
signature.set_signature_return_url(return_url)
# Set signature ACL
signature.set_signature_acl(user.get_lf_username())
self.populate_sign_url(signature, callback_url,
signatory_name, signatory_email,
send_as_email,
user.get_user_name(),
user.get_user_email(),
cla_template_values)
# Save the signature
signature.save()
response_model = {'company_id': company.get_company_id(),
'project_id': project.get_project_id(),