forked from quay/quay
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_api_usage.py
More file actions
5052 lines (3890 loc) · 176 KB
/
test_api_usage.py
File metadata and controls
5052 lines (3890 loc) · 176 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
# coding=utf-8
import unittest
import datetime
import logging
import time
import re
import json as py_json
from mock import patch
from calendar import timegm
from contextlib import contextmanager
from httmock import urlmatch, HTTMock, all_requests
from urllib import urlencode
from urlparse import urlparse, urlunparse, parse_qs
from playhouse.test_utils import assert_query_count, _QueryLogHandler
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend
from endpoints.api import api_bp, api
from endpoints.building import PreparedBuild
from endpoints.webhooks import webhooks
from app import (
app,
config_provider,
all_queues,
dockerfile_build_queue,
notification_queue,
storage,
docker_v2_signing_key,
)
from buildtrigger.basehandler import BuildTriggerHandler
from initdb import setup_database_for_testing, finished_database_for_testing
from data import database, model, appr_model
from data.appr_model.models import NEW_MODELS
from data.database import RepositoryActionCount, Repository as RepositoryTable
from data.logs_model import logs_model
from data.registry_model import registry_model
from test.helpers import assert_action_logged, log_queries, check_transitive_modifications
from util.secscan.fake import fake_security_scanner
from endpoints.api.team import (
TeamMember,
TeamMemberList,
TeamMemberInvite,
OrganizationTeam,
TeamPermissions,
InviteTeamMember,
)
from endpoints.api.tag import RepositoryTagImages, RepositoryTag, RestoreTag, ListRepositoryTags
from endpoints.api.search import EntitySearch, ConductSearch
from endpoints.api.image import RepositoryImage, RepositoryImageList
from endpoints.api.build import RepositoryBuildStatus, RepositoryBuildList, RepositoryBuildResource
from endpoints.api.robot import (
UserRobotList,
OrgRobot,
OrgRobotList,
UserRobot,
RegenerateUserRobot,
RegenerateOrgRobot,
)
from endpoints.api.trigger import (
BuildTriggerActivate,
BuildTriggerSources,
BuildTriggerSubdirs,
TriggerBuildList,
ActivateBuildTrigger,
BuildTrigger,
BuildTriggerList,
BuildTriggerAnalyze,
BuildTriggerFieldValues,
BuildTriggerSourceNamespaces,
)
from endpoints.api.repoemail import RepositoryAuthorizedEmail
from endpoints.api.repositorynotification import (
RepositoryNotification,
RepositoryNotificationList,
TestRepositoryNotification,
)
from endpoints.api.user import (
PrivateRepositories,
ConvertToOrganization,
Signout,
Signin,
User,
UserAuthorizationList,
UserAuthorization,
UserNotification,
UserNotificationList,
StarredRepositoryList,
StarredRepository,
)
from endpoints.api.repotoken import RepositoryToken, RepositoryTokenList
from endpoints.api.prototype import PermissionPrototype, PermissionPrototypeList
from endpoints.api.logs import (
UserLogs,
OrgLogs,
OrgAggregateLogs,
UserAggregateLogs,
RepositoryLogs,
RepositoryAggregateLogs,
)
from endpoints.api.billing import UserCard, UserPlan, ListPlans, OrganizationCard, OrganizationPlan
from endpoints.api.discovery import DiscoveryResource
from endpoints.api.error import Error
from endpoints.api.organization import (
OrganizationList,
OrganizationMember,
OrgPrivateRepositories,
OrganizationMemberList,
Organization,
ApplicationInformation,
OrganizationApplications,
OrganizationApplicationResource,
OrganizationApplicationResetClientSecret,
Organization,
)
from endpoints.api.repository import RepositoryList, RepositoryVisibility, Repository
from endpoints.api.repository_models_pre_oci import REPOS_PER_PAGE
from endpoints.api.permission import (
RepositoryUserPermission,
RepositoryTeamPermission,
RepositoryTeamPermissionList,
RepositoryUserPermissionList,
)
from endpoints.api.superuser import (
SuperUserLogs,
SuperUserManagement,
SuperUserServiceKeyManagement,
SuperUserServiceKey,
SuperUserServiceKeyApproval,
SuperUserTakeOwnership,
)
from endpoints.api.globalmessages import (
GlobalUserMessage,
GlobalUserMessages,
)
from endpoints.api.secscan import RepositoryImageSecurity, RepositoryManifestSecurity
from endpoints.api.manifest import RepositoryManifestLabels, ManageRepositoryManifestLabel
from util.morecollections import AttrDict
try:
app.register_blueprint(api_bp, url_prefix="/api")
except ValueError:
# This blueprint was already registered
pass
app.register_blueprint(webhooks, url_prefix="/webhooks")
# The number of queries we run for guests on API calls.
BASE_QUERY_COUNT = 0
# The number of queries we run for logged in users on API calls.
BASE_LOGGEDIN_QUERY_COUNT = BASE_QUERY_COUNT + 1
# The number of queries we run for logged in users on API calls that check
# access permissions.
BASE_PERM_ACCESS_QUERY_COUNT = BASE_LOGGEDIN_QUERY_COUNT + 2
NO_ACCESS_USER = "freshuser"
READ_ACCESS_USER = "reader"
ADMIN_ACCESS_USER = "devtable"
PUBLIC_USER = "public"
ADMIN_ACCESS_EMAIL = "jschorr@devtable.com"
ORG_REPO = "orgrepo"
ORGANIZATION = "buynlarge"
NEW_USER_DETAILS = {
"username": "bobby",
"password": "password",
"email": "bobby@tables.com",
}
FAKE_APPLICATION_CLIENT_ID = "deadbeef"
CSRF_TOKEN_KEY = "_csrf_token"
class AppConfigChange(object):
"""
AppConfigChange takes a dictionary that overrides the global app config for a given block of
code.
The values are restored on exit.
"""
def __init__(self, changes=None):
self._changes = changes or {}
self._originals = {}
self._to_rm = []
def __enter__(self):
for key in self._changes.keys():
try:
self._originals[key] = app.config[key]
except KeyError:
self._to_rm.append(key)
app.config[key] = self._changes[key]
def __exit__(self, type, value, traceback):
for key in self._originals.keys():
app.config[key] = self._originals[key]
for key in self._to_rm:
del app.config[key]
class ApiTestCase(unittest.TestCase):
maxDiff = None
def _add_csrf(self, without_csrf, explicit_csrf=None):
parts = urlparse(without_csrf)
query = parse_qs(parts[4])
with self.app.session_transaction() as sess:
if explicit_csrf is not None:
query[CSRF_TOKEN_KEY] = explicit_csrf
else:
sess[CSRF_TOKEN_KEY] = "something"
query[CSRF_TOKEN_KEY] = sess[CSRF_TOKEN_KEY]
return urlunparse(list(parts[0:4]) + [urlencode(query)] + list(parts[5:]))
def url_for(self, resource_name, params=None, skip_csrf=False, explicit_csrf=None):
params = params or {}
url = api.url_for(resource_name, **params)
if not skip_csrf:
url = self._add_csrf(url, explicit_csrf)
return url
def setUp(self):
setup_database_for_testing(self)
self.app = app.test_client()
self.ctx = app.test_request_context()
self.ctx.__enter__()
def tearDown(self):
finished_database_for_testing(self)
config_provider.clear()
self.ctx.__exit__(True, None, None)
def setCsrfToken(self, token):
with self.app.session_transaction() as sess:
sess[CSRF_TOKEN_KEY] = token
@contextmanager
def toggleFeature(self, name, enabled):
import features
previous_value = getattr(features, name)
setattr(features, name, enabled)
yield
setattr(features, name, previous_value)
def getJsonResponse(self, resource_name, params={}, expected_code=200):
rv = self.app.get(api.url_for(resource_name, **params))
self.assertEquals(expected_code, rv.status_code)
data = rv.data
parsed = py_json.loads(data)
return parsed
def postResponse(
self, resource_name, params={}, data={}, file=None, headers=None, expected_code=200
):
data = py_json.dumps(data)
headers = headers or {}
headers.update({"Content-Type": "application/json"})
if file is not None:
data = {"file": file}
headers = None
rv = self.app.post(self.url_for(resource_name, params), data=data, headers=headers)
self.assertEquals(rv.status_code, expected_code)
return rv.data
def getResponse(self, resource_name, params={}, expected_code=200):
rv = self.app.get(api.url_for(resource_name, **params))
self.assertEquals(rv.status_code, expected_code)
return rv.data
def putResponse(self, resource_name, params={}, data={}, expected_code=200):
rv = self.app.put(
self.url_for(resource_name, params),
data=py_json.dumps(data),
headers={"Content-Type": "application/json"},
)
self.assertEquals(rv.status_code, expected_code)
return rv.data
def deleteResponse(self, resource_name, params={}, expected_code=204):
rv = self.app.delete(self.url_for(resource_name, params))
if rv.status_code != expected_code:
print "Mismatch data for resource DELETE %s: %s" % (resource_name, rv.data)
self.assertEquals(rv.status_code, expected_code)
return rv.data
def deleteEmptyResponse(self, resource_name, params={}, expected_code=204):
rv = self.app.delete(self.url_for(resource_name, params))
self.assertEquals(rv.status_code, expected_code)
self.assertEquals(rv.data, "") # ensure response body empty
return
def postJsonResponse(self, resource_name, params={}, data={}, expected_code=200):
rv = self.app.post(
self.url_for(resource_name, params),
data=py_json.dumps(data),
headers={"Content-Type": "application/json"},
)
if rv.status_code != expected_code:
print "Mismatch data for resource POST %s: %s" % (resource_name, rv.data)
self.assertEquals(rv.status_code, expected_code)
data = rv.data
parsed = py_json.loads(data)
return parsed
def putJsonResponse(
self,
resource_name,
params={},
data={},
expected_code=200,
skip_csrf=False,
explicit_csrf=None,
):
rv = self.app.put(
self.url_for(resource_name, params, skip_csrf, explicit_csrf),
data=py_json.dumps(data),
headers={"Content-Type": "application/json"},
)
if rv.status_code != expected_code:
print "Mismatch data for resource PUT %s: %s" % (resource_name, rv.data)
self.assertEquals(rv.status_code, expected_code)
data = rv.data
parsed = py_json.loads(data)
return parsed
def assertNotInTeam(self, data, membername):
for memberData in data["members"]:
if memberData["name"] == membername:
self.fail(membername + " found in team: " + data["name"])
def assertInTeam(self, data, membername):
for member_data in data["members"]:
if member_data["name"] == membername:
return
self.fail(membername + " not found in team: " + data["name"])
def login(self, username, password="password"):
return self.postJsonResponse(Signin, data=dict(username=username, password=password))
class TestCSRFFailure(ApiTestCase):
def test_csrf_failure(self):
self.login(READ_ACCESS_USER)
# Make sure a simple post call succeeds.
self.putJsonResponse(User, data=dict(password="newpasswordiscool"))
# Change the session's CSRF token.
self.setCsrfToken("someinvalidtoken")
# Verify that the call now fails.
self.putJsonResponse(
User, data=dict(password="newpasswordiscool"), expected_code=403, explicit_csrf="foobar"
)
def test_csrf_failure_empty_token(self):
self.login(READ_ACCESS_USER)
# Change the session's CSRF token to be empty.
self.setCsrfToken("")
# Verify that the call now fails.
self.putJsonResponse(
User, data=dict(password="newpasswordiscool"), expected_code=403, explicit_csrf="foobar"
)
def test_csrf_failure_missing_token(self):
self.login(READ_ACCESS_USER)
# Make sure a simple post call without a token at all fails.
self.putJsonResponse(
User, data=dict(password="newpasswordiscool"), skip_csrf=True, expected_code=403
)
# Change the session's CSRF token to be empty.
self.setCsrfToken("")
# Verify that the call still fails.
self.putJsonResponse(
User,
data=dict(password="newpasswordiscool"),
skip_csrf=True,
expected_code=403,
explicit_csrf="foobar",
)
class TestDiscovery(ApiTestCase):
def test_discovery(self):
json = self.getJsonResponse(DiscoveryResource)
assert "paths" in json
class TestErrorDescription(ApiTestCase):
def test_get_error(self):
json = self.getJsonResponse(Error, params=dict(error_type="not_found"))
assert json["title"] == "not_found"
assert "type" in json
assert "description" in json
class TestPlans(ApiTestCase):
def test_plans(self):
json = self.getJsonResponse(ListPlans)
found = set([])
for method_info in json["plans"]:
found.add(method_info["stripeId"])
assert "free" in found
class TestLoggedInUser(ApiTestCase):
def test_guest(self):
self.getJsonResponse(User, expected_code=401)
def test_user(self):
self.login(READ_ACCESS_USER)
json = self.getJsonResponse(User)
assert json["anonymous"] == False
assert json["username"] == READ_ACCESS_USER
class TestUserStarredRepositoryList(ApiTestCase):
def test_get_stars_guest(self):
self.getJsonResponse(StarredRepositoryList, expected_code=401)
def test_get_stars_user(self):
self.login(READ_ACCESS_USER)
# Queries: Base + the list query
with assert_query_count(BASE_LOGGEDIN_QUERY_COUNT + 1):
self.getJsonResponse(StarredRepositoryList, expected_code=200)
def test_star_repo_guest(self):
self.postJsonResponse(
StarredRepositoryList,
data={"namespace": "public", "repository": "publicrepo",},
expected_code=401,
)
def test_star_and_unstar_repo_user(self):
self.login(READ_ACCESS_USER)
# Queries: Base + the list query
with assert_query_count(BASE_LOGGEDIN_QUERY_COUNT + 1):
json = self.getJsonResponse(StarredRepositoryList)
assert json["repositories"] == []
json = self.postJsonResponse(
StarredRepositoryList,
data={"namespace": "public", "repository": "publicrepo",},
expected_code=201,
)
assert json["namespace"] == "public"
assert json["repository"] == "publicrepo"
self.deleteEmptyResponse(
StarredRepository, params=dict(repository="public/publicrepo"), expected_code=204
)
json = self.getJsonResponse(StarredRepositoryList)
assert json["repositories"] == []
class TestUserNotification(ApiTestCase):
def test_get(self):
self.login(ADMIN_ACCESS_USER)
json = self.getJsonResponse(UserNotificationList)
# Make sure each notification can be retrieved.
for notification in json["notifications"]:
njson = self.getJsonResponse(UserNotification, params=dict(uuid=notification["id"]))
self.assertEquals(notification["id"], njson["id"])
# Update a notification.
assert json["notifications"]
assert not json["notifications"][0]["dismissed"]
notification = json["notifications"][0]
pjson = self.putJsonResponse(
UserNotification, params=dict(uuid=notification["id"]), data=dict(dismissed=True)
)
self.assertEquals(True, pjson["dismissed"])
def test_org_notifications(self):
# Create a notification on the organization.
org = model.user.get_user_or_org(ORGANIZATION)
model.notification.create_notification("test_notification", org, {"org": "notification"})
# Ensure it is visible to the org admin.
self.login(ADMIN_ACCESS_USER)
json = self.getJsonResponse(UserNotificationList)
notification = json["notifications"][0]
self.assertEquals(notification["kind"], "test_notification")
self.assertEquals(notification["metadata"], {"org": "notification"})
# Ensure it is not visible to an org member.
self.login(READ_ACCESS_USER)
json = self.getJsonResponse(UserNotificationList)
self.assertEquals(0, len(json["notifications"]))
class TestGetUserPrivateAllowed(ApiTestCase):
def test_nonallowed(self):
self.login(READ_ACCESS_USER)
json = self.getJsonResponse(PrivateRepositories)
assert json["privateCount"] == 0
assert not json["privateAllowed"]
def test_allowed(self):
self.login(ADMIN_ACCESS_USER)
# Change the subscription of the namespace.
self.putJsonResponse(UserPlan, data=dict(plan="personal-2018"))
json = self.getJsonResponse(PrivateRepositories)
assert json["privateCount"] >= 6
assert not json["privateAllowed"]
# Change the subscription of the namespace.
self.putJsonResponse(UserPlan, data=dict(plan="bus-large-2018"))
json = self.getJsonResponse(PrivateRepositories)
assert json["privateAllowed"]
class TestConvertToOrganization(ApiTestCase):
def test_sameadminuser(self):
self.login(READ_ACCESS_USER)
json = self.postJsonResponse(
ConvertToOrganization,
data={"adminUser": READ_ACCESS_USER, "adminPassword": "password", "plan": "free"},
expected_code=400,
)
self.assertEqual("The admin user is not valid", json["detail"])
def test_sameadminuser_by_email(self):
self.login(READ_ACCESS_USER)
json = self.postJsonResponse(
ConvertToOrganization,
data={"adminUser": "no1@thanks.com", "adminPassword": "password", "plan": "free"},
expected_code=400,
)
self.assertEqual("The admin user is not valid", json["detail"])
def test_invalidadminuser(self):
self.login(READ_ACCESS_USER)
json = self.postJsonResponse(
ConvertToOrganization,
data={"adminUser": "unknownuser", "adminPassword": "password", "plan": "free"},
expected_code=400,
)
self.assertEqual("The admin user credentials are not valid", json["detail"])
def test_invalidadminpassword(self):
self.login(READ_ACCESS_USER)
json = self.postJsonResponse(
ConvertToOrganization,
data={"adminUser": ADMIN_ACCESS_USER, "adminPassword": "invalidpass", "plan": "free"},
expected_code=400,
)
self.assertEqual("The admin user credentials are not valid", json["detail"])
def test_convert(self):
self.login(READ_ACCESS_USER)
# Add at least one permission for the read-user.
read_user = model.user.get_user(READ_ACCESS_USER)
simple_repo = model.repository.get_repository(ADMIN_ACCESS_USER, "simple")
read_role = database.Role.get(name="read")
database.RepositoryPermission.create(user=read_user, repository=simple_repo, role=read_role)
# Convert the read user into an organization.
json = self.postJsonResponse(
ConvertToOrganization,
data={"adminUser": ADMIN_ACCESS_USER, "adminPassword": "password", "plan": "free"},
)
self.assertEqual(True, json["success"])
# Verify the organization exists.
organization = model.organization.get_organization(READ_ACCESS_USER)
assert organization is not None
# Verify the admin user is the org's admin.
self.login(ADMIN_ACCESS_USER)
json = self.getJsonResponse(Organization, params=dict(orgname=READ_ACCESS_USER))
self.assertEquals(READ_ACCESS_USER, json["name"])
self.assertEquals(True, json["is_admin"])
# Verify the now-org has no permissions.
count = (
database.RepositoryPermission.select()
.where(database.RepositoryPermission.user == organization)
.count()
)
self.assertEquals(0, count)
def test_convert_via_email(self):
self.login(READ_ACCESS_USER)
json = self.postJsonResponse(
ConvertToOrganization,
data={"adminUser": ADMIN_ACCESS_EMAIL, "adminPassword": "password", "plan": "free"},
)
self.assertEqual(True, json["success"])
# Verify the organization exists.
organization = model.organization.get_organization(READ_ACCESS_USER)
assert organization is not None
# Verify the admin user is the org's admin.
self.login(ADMIN_ACCESS_USER)
json = self.getJsonResponse(Organization, params=dict(orgname=READ_ACCESS_USER))
self.assertEquals(READ_ACCESS_USER, json["name"])
self.assertEquals(True, json["is_admin"])
class TestChangeUserDetails(ApiTestCase):
def test_changepassword(self):
self.login(READ_ACCESS_USER)
self.putJsonResponse(User, data=dict(password="newpasswordiscool"))
self.login(READ_ACCESS_USER, password="newpasswordiscool")
def test_changepassword_unicode(self):
self.login(READ_ACCESS_USER)
self.putJsonResponse(User, data=dict(password=u"someunicode北京市pass"))
self.login(READ_ACCESS_USER, password=u"someunicode北京市pass")
def test_changeeemail(self):
self.login(READ_ACCESS_USER)
self.putJsonResponse(User, data=dict(email="test+foo@devtable.com"))
def test_changeinvoiceemail(self):
self.login(READ_ACCESS_USER)
json = self.putJsonResponse(User, data=dict(invoice_email=True))
self.assertEquals(True, json["invoice_email"])
json = self.putJsonResponse(User, data=dict(invoice_email=False))
self.assertEquals(False, json["invoice_email"])
def test_changeusername_temp(self):
self.login(READ_ACCESS_USER)
user = model.user.get_user(READ_ACCESS_USER)
model.user.create_user_prompt(user, "confirm_username")
self.assertTrue(model.user.has_user_prompt(user, "confirm_username"))
# Add a robot under the user's namespace.
model.user.create_robot("somebot", user)
# Rename the user.
json = self.putJsonResponse(User, data=dict(username="someotherusername"))
# Ensure the username was changed.
self.assertEquals("someotherusername", json["username"])
self.assertFalse(model.user.has_user_prompt(user, "confirm_username"))
# Ensure the robot was changed.
self.assertIsNone(model.user.get_user(READ_ACCESS_USER + "+somebot"))
self.assertIsNotNone(model.user.get_user("someotherusername+somebot"))
def test_changeusername_temp_samename(self):
self.login(READ_ACCESS_USER)
user = model.user.get_user(READ_ACCESS_USER)
model.user.create_user_prompt(user, "confirm_username")
self.assertTrue(model.user.has_user_prompt(user, "confirm_username"))
json = self.putJsonResponse(User, data=dict(username=READ_ACCESS_USER))
# Ensure the username was not changed but they are no longer temporarily named.
self.assertEquals(READ_ACCESS_USER, json["username"])
self.assertFalse(model.user.has_user_prompt(user, "confirm_username"))
def test_changeusername_notallowed(self):
with self.toggleFeature("USER_RENAME", False):
self.login(ADMIN_ACCESS_USER)
user = model.user.get_user(ADMIN_ACCESS_USER)
self.assertFalse(model.user.has_user_prompt(user, "confirm_username"))
json = self.putJsonResponse(User, data=dict(username="someotherusername"))
self.assertEquals(ADMIN_ACCESS_USER, json["username"])
self.assertTrue("prompts" in json)
self.assertIsNone(model.user.get_user("someotherusername"))
self.assertIsNotNone(model.user.get_user(ADMIN_ACCESS_USER))
def test_changeusername_allowed(self):
with self.toggleFeature("USER_RENAME", True):
self.login(ADMIN_ACCESS_USER)
user = model.user.get_user(ADMIN_ACCESS_USER)
self.assertFalse(model.user.has_user_prompt(user, "confirm_username"))
json = self.putJsonResponse(User, data=dict(username="someotherusername"))
self.assertEquals("someotherusername", json["username"])
self.assertTrue("prompts" in json)
self.assertIsNotNone(model.user.get_user("someotherusername"))
self.assertIsNone(model.user.get_user(ADMIN_ACCESS_USER))
def test_changeusername_already_used(self):
self.login(READ_ACCESS_USER)
user = model.user.get_user(READ_ACCESS_USER)
model.user.create_user_prompt(user, "confirm_username")
self.assertTrue(model.user.has_user_prompt(user, "confirm_username"))
# Try to change to a used username.
self.putJsonResponse(User, data=dict(username=ADMIN_ACCESS_USER), expected_code=400)
# Change to a new username.
self.putJsonResponse(User, data=dict(username="unusedusername"))
class TestCreateNewUser(ApiTestCase):
def test_existingusername(self):
json = self.postJsonResponse(
User,
data=dict(username=READ_ACCESS_USER, password="password", email="test@example.com"),
expected_code=400,
)
self.assertEquals("The username already exists", json["detail"])
def test_trycreatetooshort(self):
json = self.postJsonResponse(
User,
data=dict(username="a", password="password", email="test@example.com"),
expected_code=400,
)
self.assertEquals(
"Invalid namespace a: Namespace must be between 2 and 255 characters in length",
json["detail"],
)
def test_trycreateregexmismatch(self):
json = self.postJsonResponse(
User,
data=dict(username="auserName", password="password", email="test@example.com"),
expected_code=400,
)
self.assertEquals(
"Invalid namespace auserName: Namespace must match expression ^([a-z0-9]+(?:[._-][a-z0-9]+)*)$",
json["detail"],
)
def test_createuser(self):
data = self.postJsonResponse(User, data=NEW_USER_DETAILS, expected_code=200)
self.assertEquals(True, data["awaiting_verification"])
def test_createuser_captcha(self):
@urlmatch(netloc=r"(.*\.)?google.com", path="/recaptcha/api/siteverify")
def captcha_endpoint(url, request):
if url.query.find("response=somecode") > 0:
return {"status_code": 200, "content": py_json.dumps({"success": True})}
else:
return {"status_code": 400, "content": py_json.dumps({"success": False})}
with HTTMock(captcha_endpoint):
with self.toggleFeature("RECAPTCHA", True):
# Try with a missing captcha.
self.postResponse(User, data=NEW_USER_DETAILS, expected_code=400)
# Try with an invalid captcha.
details = dict(NEW_USER_DETAILS)
details["recaptcha_response"] = "someinvalidcode"
self.postResponse(User, data=details, expected_code=400)
# Try with a valid captcha.
details = dict(NEW_USER_DETAILS)
details["recaptcha_response"] = "somecode"
self.postResponse(User, data=details, expected_code=200)
def test_createuser_withteaminvite(self):
inviter = model.user.get_user(ADMIN_ACCESS_USER)
team = model.team.get_organization_team(ORGANIZATION, "owners")
invite = model.team.add_or_invite_to_team(inviter, team, None, NEW_USER_DETAILS["email"])
details = {"invite_code": invite.invite_token}
details.update(NEW_USER_DETAILS)
data = self.postJsonResponse(User, data=details, expected_code=200)
# Make sure the user is verified since the email address of the user matches
# that of the team invite.
self.assertFalse("awaiting_verification" in data)
# Make sure the user was not (yet) added to the team.
self.login(ADMIN_ACCESS_USER)
json = self.getJsonResponse(
TeamMemberList, params=dict(orgname=ORGANIZATION, teamname="owners")
)
self.assertNotInTeam(json, NEW_USER_DETAILS["username"])
def test_createuser_withteaminvite_differentemails(self):
inviter = model.user.get_user(ADMIN_ACCESS_USER)
team = model.team.get_organization_team(ORGANIZATION, "owners")
invite = model.team.add_or_invite_to_team(inviter, team, None, "differentemail@example.com")
details = {"invite_code": invite.invite_token}
details.update(NEW_USER_DETAILS)
data = self.postJsonResponse(User, data=details, expected_code=200)
# Make sure the user is *not* verified since the email address of the user
# does not match that of the team invite.
self.assertTrue(data["awaiting_verification"])
# Make sure the user was not (yet) added to the team.
self.login(ADMIN_ACCESS_USER)
json = self.getJsonResponse(
TeamMemberList, params=dict(orgname=ORGANIZATION, teamname="owners")
)
self.assertNotInTeam(json, NEW_USER_DETAILS["username"])
def test_createuser_withmultipleteaminvites(self):
inviter = model.user.get_user(ADMIN_ACCESS_USER)
owners_team = model.team.get_organization_team(ORGANIZATION, "owners")
readers_team = model.team.get_organization_team(ORGANIZATION, "readers")
other_owners_team = model.team.get_organization_team("library", "owners")
owners_invite = model.team.add_or_invite_to_team(
inviter, owners_team, None, NEW_USER_DETAILS["email"]
)
readers_invite = model.team.add_or_invite_to_team(
inviter, readers_team, None, NEW_USER_DETAILS["email"]
)
other_owners_invite = model.team.add_or_invite_to_team(
inviter, other_owners_team, None, NEW_USER_DETAILS["email"]
)
# Create the user and ensure they have a verified email address.
details = {"invite_code": owners_invite.invite_token}
details.update(NEW_USER_DETAILS)
data = self.postJsonResponse(User, data=details, expected_code=200)
# Make sure the user is verified since the email address of the user matches
# that of the team invite.
self.assertFalse("awaiting_verification" in data)
# Make sure the user was not (yet) added to the teams.
self.login(ADMIN_ACCESS_USER)
json = self.getJsonResponse(
TeamMemberList, params=dict(orgname=ORGANIZATION, teamname="owners")
)
self.assertNotInTeam(json, NEW_USER_DETAILS["username"])
json = self.getJsonResponse(
TeamMemberList, params=dict(orgname=ORGANIZATION, teamname="readers")
)
self.assertNotInTeam(json, NEW_USER_DETAILS["username"])
json = self.getJsonResponse(
TeamMemberList, params=dict(orgname="library", teamname="owners")
)
self.assertNotInTeam(json, NEW_USER_DETAILS["username"])
# Accept the first invitation.
self.login(NEW_USER_DETAILS["username"])
self.putJsonResponse(TeamMemberInvite, params=dict(code=owners_invite.invite_token))
# Make sure both codes are now invalid.
self.putResponse(
TeamMemberInvite, params=dict(code=owners_invite.invite_token), expected_code=400
)
self.putResponse(
TeamMemberInvite, params=dict(code=readers_invite.invite_token), expected_code=400
)
# Make sure the user is now in the two invited teams under the organization, but not
# in the other org's team.
self.login(ADMIN_ACCESS_USER)
json = self.getJsonResponse(
TeamMemberList, params=dict(orgname=ORGANIZATION, teamname="owners")
)
self.assertInTeam(json, NEW_USER_DETAILS["username"])
json = self.getJsonResponse(
TeamMemberList, params=dict(orgname=ORGANIZATION, teamname="readers")
)
self.assertInTeam(json, NEW_USER_DETAILS["username"])
json = self.getJsonResponse(
TeamMemberList, params=dict(orgname="library", teamname="owners")
)
self.assertNotInTeam(json, NEW_USER_DETAILS["username"])
# Accept the second invitation.
self.login(NEW_USER_DETAILS["username"])
self.putJsonResponse(TeamMemberInvite, params=dict(code=other_owners_invite.invite_token))
# Make sure the user was added to the other organization.
self.login(ADMIN_ACCESS_USER)
json = self.getJsonResponse(
TeamMemberList, params=dict(orgname="library", teamname="owners")
)
self.assertInTeam(json, NEW_USER_DETAILS["username"])
# Make sure the invitation codes are now invalid.
self.putResponse(
TeamMemberInvite, params=dict(code=other_owners_invite.invite_token), expected_code=400
)
class TestDeleteNamespace(ApiTestCase):
def test_deletenamespaces(self):
self.login(ADMIN_ACCESS_USER)
# Try to first delete the user. Since they are the sole admin of three orgs, it should fail.
with check_transitive_modifications():
self.deleteResponse(User, expected_code=400)
# Delete the three orgs, checking in between.
with check_transitive_modifications():
self.deleteEmptyResponse(
Organization, params=dict(orgname=ORGANIZATION), expected_code=204
)
self.deleteResponse(User, expected_code=400) # Should still fail.
self.deleteEmptyResponse(
Organization, params=dict(orgname="library"), expected_code=204
)
self.deleteResponse(User, expected_code=400) # Should still fail.
self.deleteEmptyResponse(Organization, params=dict(orgname="titi"), expected_code=204)
# Add some queue items for the user.
notification_queue.put([ADMIN_ACCESS_USER, "somerepo", "somename"], "{}")
dockerfile_build_queue.put([ADMIN_ACCESS_USER, "anotherrepo"], "{}")
# Now delete the user.
with check_transitive_modifications():
self.deleteEmptyResponse(User, expected_code=204)
# Ensure the queue items are gone.
self.assertIsNone(notification_queue.get())
self.assertIsNone(dockerfile_build_queue.get())
def test_delete_federateduser(self):
self.login(PUBLIC_USER)
# Add some federated logins.
user = model.user.get_user(PUBLIC_USER)
model.user.attach_federated_login(user, "github", "something", {})
with check_transitive_modifications():
self.deleteEmptyResponse(User, expected_code=204)
def test_delete_prompted_user(self):
self.login("randomuser")
with check_transitive_modifications():
self.deleteEmptyResponse(User, expected_code=204)
class TestSignin(ApiTestCase):
def test_signin_unicode(self):
self.postResponse(
Signin,
data=dict(username=u"\xe5\x8c\x97\xe4\xba\xac\xe5\xb8\x82", password="password"),
expected_code=403,