-
Notifications
You must be signed in to change notification settings - Fork 132
/
auth_test.py
3252 lines (2766 loc) · 163 KB
/
auth_test.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
import random
import string
import time
from collections import namedtuple
from datetime import datetime, timedelta
from distutils.version import LooseVersion
import re
import pytest
import logging
from cassandra import AuthenticationFailed, InvalidRequest, Unauthorized
from cassandra.cluster import NoHostAvailable
from cassandra.protocol import SyntaxException
from dtest_setup_overrides import DTestSetupOverrides
from dtest import Tester
from tools.assertions import (assert_all, assert_exception, assert_invalid,
assert_length_equal, assert_one,
assert_unauthorized)
from tools.jmxutils import (JolokiaAgent, make_mbean)
from tools.metadata_wrapper import UpdatingKeyspaceMetadataWrapper
from tools.misc import ImmutableMapping
since = pytest.mark.since
logger = logging.getLogger(__name__)
class AbstractTestAuth(Tester):
def role_creator_permissions(self, creator, role):
if self.dtest_config.cassandra_version_from_build >= '3.0':
permissions = ('ALTER', 'DROP', 'DESCRIBE', 'AUTHORIZE')
else:
permissions = ('ALTER', 'DROP', 'DESCRIBE')
return [(creator, role, perm) for perm in permissions]
def cluster_version_has_masking_permissions(self):
return self.cluster.version() >= LooseVersion('5.0')
def data_resource_creator_permissions(self, creator, resource):
"""
Assemble a list of all permissions needed to create data on a given resource
@param creator User who needs permissions
@param resource The resource to grant permissions on
@return A list of permissions for creator on resource
"""
permissions = []
for perm in 'SELECT', 'MODIFY', 'ALTER', 'DROP', 'AUTHORIZE':
permissions.append((creator, resource, perm))
if self.cluster_version_has_masking_permissions():
permissions.append((creator, resource, 'UNMASK'))
permissions.append((creator, resource, 'SELECT_MASKED'))
if resource.startswith("<keyspace "):
permissions.append((creator, resource, 'CREATE'))
keyspace = resource[10:-1]
# also grant the creator of a ks perms on functions in that ks
for perm in 'CREATE', 'ALTER', 'DROP', 'AUTHORIZE', 'EXECUTE':
permissions.append((creator, '<all functions in %s>' % keyspace, perm))
return permissions
class TestAuth(AbstractTestAuth):
@pytest.fixture(autouse=True)
def fixture_add_additional_log_patterns(self, fixture_dtest_setup):
fixture_dtest_setup.ignore_log_patterns = (
# This one occurs if we do a non-rolling upgrade, the node
# it's trying to send the migration to hasn't started yet,
# and when it does, it gets replayed and everything is fine.
r'Can\'t send migration request: node.*is down',
)
def test_system_auth_ks_is_alterable(self):
"""
* Launch a three node cluster
* Verify the default RF of system_auth is 1
* Increase the system_auth RF to 3
* Run repair, see 10655
* Restart the cluster
* Check that each node agrees on the system_auth RF
@jira_ticket CASSANDRA-10655
"""
self.prepare(nodes=3)
logger.debug("nodes started")
session = self.get_session(user='cassandra', password='cassandra')
auth_metadata = UpdatingKeyspaceMetadataWrapper(
cluster=session.cluster,
ks_name='system_auth',
max_schema_agreement_wait=60 # 6x the default of 10
)
assert 1 == auth_metadata.replication_strategy.replication_factor
session.execute("""
ALTER KEYSPACE system_auth
WITH replication = {'class':'SimpleStrategy', 'replication_factor':3};
""")
assert 3 == auth_metadata.replication_strategy.replication_factor
# Run repair to workaround read repair issues caused by CASSANDRA-10655
logger.debug("Repairing before altering RF")
self.cluster.repair()
logger.debug("Shutting down client cluster")
session.cluster.shutdown()
# make sure schema change is persistent
logger.debug("Stopping cluster..")
self.cluster.stop()
logger.debug("Restarting cluster..")
self.cluster.start()
# check each node directly
for i in range(3):
logger.debug('Checking node: {i}'.format(i=i))
node = self.cluster.nodelist()[i]
exclusive_auth_metadata = UpdatingKeyspaceMetadataWrapper(
cluster=self.patient_exclusive_cql_connection(node, user='cassandra', password='cassandra').cluster,
ks_name='system_auth'
)
assert 3 == exclusive_auth_metadata.replication_strategy.replication_factor
def test_login(self):
"""
* Launch a one node cluster
* Connect as the default user/password
* Verify that default user w/ bad password gives AuthenticationFailed exception
* Verify that bad user gives AuthenticationFailed exception
"""
# also tests default user creation (cassandra/cassandra)
self.prepare()
self.get_session(user='cassandra', password='cassandra')
try:
self.get_session(user='cassandra', password='badpassword')
except NoHostAvailable as e:
assert isinstance(list(e.errors.values())[0], AuthenticationFailed)
try:
self.get_session(user='doesntexist', password='doesntmatter')
except NoHostAvailable as e:
assert isinstance(list(e.errors.values())[0], AuthenticationFailed)
# from 2.2 role creation is granted by CREATE_ROLE permissions, not superuser status
@since('1.2', max_version='2.1.x')
def test_only_superuser_can_create_users(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Verify we can create a user, 'jackob', as the default superuser
* Connect as the new user, 'jackob'
* Verify we cannot create a second user as 'jackob'
"""
self.prepare()
cassandra = self.get_session(user='cassandra', password='cassandra')
cassandra.execute("CREATE USER jackob WITH PASSWORD '12345' NOSUPERUSER")
jackob = self.get_session(user='jackob', password='12345')
assert_unauthorized(jackob, "CREATE USER james WITH PASSWORD '54321' NOSUPERUSER", 'Only superusers are allowed to perform CREATE (\\[ROLE\\|USER\\]|USER) queries', )
@since('1.2', max_version='2.1.x')
def test_password_authenticator_create_user_requires_password(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Verify we cannot create a new user without specifying a password for them
* Verify we can create the new user if the password is specified
"""
self.prepare()
session = self.get_session(user='cassandra', password='cassandra')
assert_invalid(session, "CREATE USER jackob NOSUPERUSER", 'PasswordAuthenticator requires PASSWORD option')
session.execute("CREATE USER jackob WITH PASSWORD '12345' NOSUPERUSER")
def test_cant_create_existing_user(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Create a new user
* Verify that attempting to create a duplicate user fails with InvalidRequest
"""
self.prepare()
session = self.get_session(user='cassandra', password='cassandra')
session.execute("CREATE USER 'james@example.com' WITH PASSWORD '12345' NOSUPERUSER")
assert_invalid(session, "CREATE USER 'james@example.com' WITH PASSWORD '12345' NOSUPERUSER", 'james@example.com already exists')
def test_list_users(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Create two new users, and two new superusers.
* Verify that LIST USERS shows all five users.
* Verify that the correct users are listed as super users.
* Connect as one of the new users, and check that the LIST USERS behavior is also correct there.
"""
self.prepare()
session = self.get_session(user='cassandra', password='cassandra')
session.execute("CREATE USER alex WITH PASSWORD '12345' NOSUPERUSER")
session.execute("CREATE USER bob WITH PASSWORD '12345' SUPERUSER")
session.execute("CREATE USER cathy WITH PASSWORD '12345' NOSUPERUSER")
session.execute("CREATE USER dave WITH PASSWORD '12345' SUPERUSER")
rows = list(session.execute("LIST USERS"))
assert 5 == len(rows)
# {username: isSuperuser} dict.
users = dict([(r[0], r[1]) for r in rows])
assert users['cassandra']
assert not users['alex']
assert users['bob']
assert not users['cathy']
assert users['dave']
self.get_session(user='dave', password='12345')
rows = list(session.execute("LIST USERS"))
assert 5 == len(rows)
# {username: isSuperuser} dict.
users = dict([(r[0], r[1]) for r in rows])
assert users['cassandra']
assert not users['alex']
assert users['bob']
assert not users['cathy']
assert users['dave']
@since('2.2')
def test_handle_corrupt_role_data(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Create a new role
* Confirm that there exists 2 users
* Manually corrupt / delete the is_superuser cell of that role
* Confirm that listing users shows an invalid request
* Confirm that corrupted user can no longer login
@jira_ticket CASSANDRA-12700
"""
self.prepare()
session = self.get_session(user='cassandra', password='cassandra')
session.execute("CREATE USER bob WITH PASSWORD '12345' SUPERUSER")
bob = self.get_session(user='bob', password='12345')
rows = list(bob.execute("LIST USERS"))
assert_length_equal(rows, 2)
session.execute("UPDATE system_auth.roles SET is_superuser=null WHERE role='bob'")
self.fixture_dtest_setup.ignore_log_patterns = list(self.fixture_dtest_setup.ignore_log_patterns) + [
r'Invalid metadata has been detected for role bob']
assert_exception(session, "LIST USERS", "Invalid metadata has been detected for role", expected=(NoHostAvailable))
try:
self.get_session(user='bob', password='12345')
except NoHostAvailable as e:
assert isinstance(list(e.errors.values())[0], AuthenticationFailed)
def test_user_cant_drop_themselves(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Verify the superuser can't drop themselves
"""
self.prepare()
session = self.get_session(user='cassandra', password='cassandra')
# handle different error messages between versions pre and post 2.2.0
assert_invalid(session, "DROP USER cassandra", "(Users aren't allowed to DROP themselves|Cannot DROP primary role for current login)")
# from 2.2 role deletion is granted by DROP_ROLE permissions, not superuser status
@since('1.2', max_version='2.1.x')
def test_only_superusers_can_drop_users(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Create two new users
* Verify all users are present with LIST USERS
* Connect as one of the new users, 'cathy'
* Verify that 'cathy', not being a superuser, cannot drop other users, and gets an Unauthorized exception
* Verify the default superuser can drop other users
"""
self.prepare()
cassandra = self.get_session(user='cassandra', password='cassandra')
cassandra.execute("CREATE USER cathy WITH PASSWORD '12345' NOSUPERUSER")
cassandra.execute("CREATE USER dave WITH PASSWORD '12345' NOSUPERUSER")
rows = list(cassandra.execute("LIST USERS"))
assert 3 == len(rows)
cathy = self.get_session(user='cathy', password='12345')
assert_unauthorized(cathy, 'DROP USER dave', 'Only superusers are allowed to perform DROP (\\[ROLE\\|USER\\]|USER) queries')
rows = list(cassandra.execute("LIST USERS"))
assert 3 == len(rows)
cassandra.execute('DROP USER dave')
rows = list(cassandra.execute("LIST USERS"))
assert 2 == len(rows)
def test_dropping_nonexistent_user_throws_exception(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Verify that dropping a nonexistent user throws InvalidRequest
"""
self.prepare()
session = self.get_session(user='cassandra', password='cassandra')
assert_invalid(session, 'DROP USER nonexistent', "nonexistent doesn't exist")
def test_drop_user_case_sensitive(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Create a user, 'Test'
* Verify that the drop user statement is case sensitive
"""
self.prepare()
cassandra = self.get_session(user='cassandra', password='cassandra')
cassandra.execute("CREATE USER Test WITH PASSWORD '12345'")
# Should be invalid, as 'test' does not exist
assert_invalid(cassandra, "DROP USER test")
cassandra.execute("DROP USER Test")
rows = [x[0] for x in list(cassandra.execute("LIST USERS"))]
assert rows == ['cassandra']
cassandra.execute("CREATE USER test WITH PASSWORD '12345'")
# Should be invalid, as 'TEST' does not exist
assert_invalid(cassandra, "DROP USER TEST")
cassandra.execute("DROP USER test")
rows = [x[0] for x in list(cassandra.execute("LIST USERS"))]
assert rows == ['cassandra']
def test_alter_user_case_sensitive(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Create a user, 'Test'
* Verify that ALTER statements on the user are case sensitive
"""
self.prepare()
cassandra = self.get_session(user='cassandra', password='cassandra')
cassandra.execute("CREATE USER Test WITH PASSWORD '12345'")
cassandra.execute("ALTER USER Test WITH PASSWORD '54321'")
assert_invalid(cassandra, "ALTER USER test WITH PASSWORD '12345'")
assert_invalid(cassandra, "ALTER USER TEST WITH PASSWORD '12345'")
cassandra.execute('DROP USER Test')
cassandra.execute("CREATE USER test WITH PASSWORD '12345'")
assert_invalid(cassandra, "ALTER USER Test WITH PASSWORD '12345'")
assert_invalid(cassandra, "ALTER USER TEST WITH PASSWORD '12345'")
cassandra.execute("ALTER USER test WITH PASSWORD '54321'")
def test_regular_users_can_alter_their_passwords_only(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Create two users, 'cathy' and 'bob'
* Connect as 'cathy'
* Verify 'cathy' can alter her own password
* Verify that if 'cathy' tries to alter bob's password, it throws Unauthorized
"""
self.prepare()
cassandra = self.get_session(user='cassandra', password='cassandra')
cassandra.execute("CREATE USER cathy WITH PASSWORD '12345'")
cassandra.execute("CREATE USER bob WITH PASSWORD '12345'")
cathy = self.get_session(user='cathy', password='12345')
cathy.execute("ALTER USER cathy WITH PASSWORD '54321'")
cathy = self.get_session(user='cathy', password='54321')
assert_unauthorized(cathy, "ALTER USER bob WITH PASSWORD 'cantchangeit'",
"You aren't allowed to alter this user|User cathy does not have sufficient privileges to perform the requested operation")
def test_users_cant_alter_their_superuser_status(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Attempt to remove our own superuser status. Assert this throws Unauthorized
"""
self.prepare()
session = self.get_session(user='cassandra', password='cassandra')
assert_unauthorized(session, "ALTER USER cassandra NOSUPERUSER", "You aren't allowed to alter your own superuser status")
def test_only_superuser_alters_superuser_status(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Create a new user, 'cathy'
* Connect as 'cathy'
* Verify that Unauthorized is thrown if cathy attempts to alter another user's superuser status
* Verify that the default superuser can alter cathy's superuser status
"""
self.prepare()
cassandra = self.get_session(user='cassandra', password='cassandra')
cassandra.execute("CREATE USER cathy WITH PASSWORD '12345'")
cathy = self.get_session(user='cathy', password='12345')
assert_unauthorized(cathy, "ALTER USER cassandra NOSUPERUSER", "Only superusers are allowed to alter superuser status")
cassandra.execute("ALTER USER cathy SUPERUSER")
def test_altering_nonexistent_user_throws_exception(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Assert that altering a nonexistent user throws InvalidRequest
"""
self.prepare()
session = self.get_session(user='cassandra', password='cassandra')
assert_invalid(session, "ALTER USER nonexistent WITH PASSWORD 'doesn''tmatter'", "nonexistent doesn't exist")
def test_conditional_create_drop_user(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Attempt to create a user twice, using IF NOT EXISTS
* Verify neither query fails, but the user is only created once
* Attempt to DROP USER IF EXISTS, twice. Ensure both succeed.
* Verify only the default superuser remains
"""
self.prepare()
session = self.get_session(user='cassandra', password='cassandra')
if self.dtest_config.cassandra_version_from_build >= '4.0':
assert_one(session, "LIST USERS", ['cassandra', True, 'ALL'])
else:
assert_one(session, "LIST USERS", ['cassandra', True])
session.execute("CREATE USER IF NOT EXISTS aleksey WITH PASSWORD 'sup'")
session.execute("CREATE USER IF NOT EXISTS aleksey WITH PASSWORD 'ignored'")
self.get_session(user='aleksey', password='sup')
if self.dtest_config.cassandra_version_from_build >= '4.0':
assert_all(session, "LIST USERS", [['aleksey', False, 'ALL'], ['cassandra', True, 'ALL']])
else:
assert_all(session, "LIST USERS", [['aleksey', False], ['cassandra', True]])
session.execute("DROP USER IF EXISTS aleksey")
if self.dtest_config.cassandra_version_from_build >= '4.0':
assert_one(session, "LIST USERS", ['cassandra', True, 'ALL'])
else:
assert_one(session, "LIST USERS", ['cassandra', True])
session.execute("DROP USER IF EXISTS aleksey")
if self.dtest_config.cassandra_version_from_build >= '4.0':
assert_one(session, "LIST USERS", ['cassandra', True, 'ALL'])
else:
assert_one(session, "LIST USERS", ['cassandra', True])
def test_create_ks_auth(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Create a new user, 'cathy', with no permissions
* Connect as 'cathy'
* Assert that trying to create a ks as 'cathy' throws Unauthorized
* Grant 'cathy' create permissions
* Assert that 'cathy' can create a ks
"""
self.prepare()
cassandra = self.get_session(user='cassandra', password='cassandra')
cassandra.execute("CREATE USER cathy WITH PASSWORD '12345'")
cathy = self.get_session(user='cathy', password='12345')
assert_unauthorized(cathy,
"CREATE KEYSPACE ks WITH replication = {'class':'SimpleStrategy', 'replication_factor':1}",
"User cathy has no CREATE permission on <all keyspaces> or any of its parents")
cassandra.execute("GRANT CREATE ON ALL KEYSPACES TO cathy")
cathy.execute("""CREATE KEYSPACE ks WITH replication = {'class':'SimpleStrategy', 'replication_factor':1}""")
def test_create_cf_auth(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Create a new user, 'cathy', with no permissions
* Connect as 'cathy'
* Assert that trying to create a table as 'cathy' throws Unauthorized
* Grant 'cathy' create permissions
* Assert that 'cathy' can create a table
"""
self.prepare()
cassandra = self.get_session(user='cassandra', password='cassandra')
cassandra.execute("CREATE USER cathy WITH PASSWORD '12345'")
cassandra.execute("CREATE KEYSPACE ks WITH replication = {'class':'SimpleStrategy', 'replication_factor':1}")
cathy = self.get_session(user='cathy', password='12345')
assert_unauthorized(cathy, "CREATE TABLE ks.cf (id int primary key)",
"User cathy has no CREATE permission on <keyspace ks> or any of its parents")
cassandra.execute("GRANT CREATE ON KEYSPACE ks TO cathy")
cathy.execute("CREATE TABLE ks.cf (id int primary key)")
def test_alter_ks_auth(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Create a new user, 'cathy', with no permissions
* Connect as 'cathy'
* Assert that trying to alter a ks as 'cathy' throws Unauthorized
* Grant 'cathy' alter permissions
* Assert that 'cathy' can alter a ks
"""
self.prepare()
cassandra = self.get_session(user='cassandra', password='cassandra')
cassandra.execute("CREATE USER cathy WITH PASSWORD '12345'")
cassandra.execute("CREATE KEYSPACE ks WITH replication = {'class':'SimpleStrategy', 'replication_factor':1}")
cathy = self.get_session(user='cathy', password='12345')
assert_unauthorized(cathy,
"ALTER KEYSPACE ks WITH replication = {'class':'SimpleStrategy', 'replication_factor':2}",
"User cathy has no ALTER permission on <keyspace ks> or any of its parents")
cassandra.execute("GRANT ALTER ON KEYSPACE ks TO cathy")
cathy.execute("ALTER KEYSPACE ks WITH replication = {'class':'SimpleStrategy', 'replication_factor':2}")
def test_alter_cf_auth(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Create a new user, 'cathy', with no permissions
* Connect as 'cathy'
* Assert that trying to alter a table as 'cathy' throws Unauthorized
* Grant 'cathy' alter permissions
* Assert that 'cathy' can alter a table
* Revoke cathy's alter permissions
* Assert that trying to alter a table as 'cathy' throws Unauthorized
* Repeat the grant/revoke loop two more times
"""
self.prepare()
cassandra = self.get_session(user='cassandra', password='cassandra')
cassandra.execute("CREATE USER cathy WITH PASSWORD '12345'")
cassandra.execute("CREATE KEYSPACE ks WITH replication = {'class':'SimpleStrategy', 'replication_factor':1}")
cassandra.execute("CREATE TABLE ks.cf (id int primary key)")
cathy = self.get_session(user='cathy', password='12345')
assert_unauthorized(cathy, "ALTER TABLE ks.cf ADD val int", "User cathy has no ALTER permission on <table ks.cf> or any of its parents")
cassandra.execute("GRANT ALTER ON ks.cf TO cathy")
cathy.execute("ALTER TABLE ks.cf ADD val int")
cassandra.execute("REVOKE ALTER ON ks.cf FROM cathy")
assert_unauthorized(cathy, "CREATE INDEX ON ks.cf(val)", "User cathy has no ALTER permission on <table ks.cf> or any of its parents")
cassandra.execute("GRANT ALTER ON ks.cf TO cathy")
cathy.execute("CREATE INDEX ON ks.cf(val)")
cassandra.execute("REVOKE ALTER ON ks.cf FROM cathy")
cathy.execute("USE ks")
assert_unauthorized(cathy, "DROP INDEX cf_val_idx", "User cathy has no ALTER permission on <table ks.cf> or any of its parents")
cassandra.execute("GRANT ALTER ON ks.cf TO cathy")
cathy.execute("DROP INDEX cf_val_idx")
@since('3.0')
def test_materialized_views_auth(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Create a new user, 'cathy', with no permissions
* Create a ks, table
* Connect as cathy
* Try CREATE MV without ALTER permission on base table, assert throws Unauthorized
* Grant cathy ALTER permissions, then CREATE MV successfully
* Try to SELECT from the mv, assert throws Unauthorized
* Grant cathy SELECT permissions, and read from the MV successfully
* Revoke cathy's ALTER permissions, assert DROP MV throws Unauthorized
* Restore cathy's ALTER permissions, DROP MV successfully
"""
self.prepare()
cassandra = self.get_session(user='cassandra', password='cassandra')
cassandra.execute("CREATE USER cathy WITH PASSWORD '12345'")
cassandra.execute("CREATE KEYSPACE ks WITH replication = {'class':'SimpleStrategy', 'replication_factor':1}")
cassandra.execute("CREATE TABLE ks.cf (id int primary key, value text)")
# Try CREATE MV without ALTER permission on base table
create_mv = "CREATE MATERIALIZED VIEW ks.mv1 AS SELECT * FROM ks.cf WHERE id IS NOT NULL " \
"AND value IS NOT NULL PRIMARY KEY (value, id)"
cathy = self.get_session(user='cathy', password='12345')
assert_unauthorized(cathy, create_mv, "User cathy has no ALTER permission on <table ks.cf> or any of its parents")
# Grant ALTER permission and CREATE MV
cassandra.execute("GRANT ALTER ON ks.cf TO cathy")
cathy.execute(create_mv)
# TRY SELECT MV without SELECT permission on base table
assert_unauthorized(cathy, "SELECT * FROM ks.mv1", "User cathy has no SELECT permission on <table ks.cf> or any of its parents")
# Grant SELECT permission and CREATE MV
cassandra.execute("GRANT SELECT ON ks.cf TO cathy")
cathy.execute("SELECT * FROM ks.mv1")
# Revoke ALTER permission and try DROP MV
cassandra.execute("REVOKE ALTER ON ks.cf FROM cathy")
cathy.execute("USE ks")
assert_unauthorized(cathy, "DROP MATERIALIZED VIEW mv1", "User cathy has no ALTER permission on <table ks.cf> or any of its parents")
# GRANT ALTER permission and DROP MV
cassandra.execute("GRANT ALTER ON ks.cf TO cathy")
cathy.execute("DROP MATERIALIZED VIEW mv1")
def test_drop_ks_auth(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Create user 'cathy', with no permissions
* Create a new keyspace, 'ks'
* Connect as cathy
* Try to DROP ks, assert throws Unauthorized
* Grant DROP permission to cathy, drop ks successfully
"""
self.prepare()
cassandra = self.get_session(user='cassandra', password='cassandra')
cassandra.execute("CREATE USER cathy WITH PASSWORD '12345'")
cassandra.execute("CREATE KEYSPACE ks WITH replication = {'class':'SimpleStrategy', 'replication_factor':1}")
cathy = self.get_session(user='cathy', password='12345')
assert_unauthorized(cathy, "DROP KEYSPACE ks", "User cathy has no DROP permission on <keyspace ks> or any of its parents")
cassandra.execute("GRANT DROP ON KEYSPACE ks TO cathy")
cathy.execute("DROP KEYSPACE ks")
def test_drop_cf_auth(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Create user 'cathy', with no permissions
* Create a new table, 'ks.cf'
* Connect as cathy
* Try to DROP ks.cf, assert throws Unauthorized
* Grant DROP permission to cathy, drop ks.cf successfully
"""
self.prepare()
cassandra = self.get_session(user='cassandra', password='cassandra')
cassandra.execute("CREATE USER cathy WITH PASSWORD '12345'")
cassandra.execute("CREATE KEYSPACE ks WITH replication = {'class':'SimpleStrategy', 'replication_factor':1}")
cassandra.execute("CREATE TABLE ks.cf (id int primary key)")
cathy = self.get_session(user='cathy', password='12345')
assert_unauthorized(cathy, "DROP TABLE ks.cf", "User cathy has no DROP permission on <table ks.cf> or any of its parents")
cassandra.execute("GRANT DROP ON ks.cf TO cathy")
cathy.execute("DROP TABLE ks.cf")
def test_modify_and_select_auth(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Create a new user, 'cathy', with no permissions
* Create table ks.cf
* Connect as cathy
* Asserting selecting from cf throws Unauthorized
* Grant SELECT to cathy, verify she can read from cf
* Assert insert, update, delete, and truncate all throw Unauthorized
* Grant MODIFY to cathy, verify she can now perform all modification queries
"""
self.prepare()
cassandra = self.get_session(user='cassandra', password='cassandra')
cassandra.execute("CREATE USER cathy WITH PASSWORD '12345'")
cassandra.execute("CREATE KEYSPACE ks WITH replication = {'class':'SimpleStrategy', 'replication_factor':1}")
cassandra.execute("CREATE TABLE ks.cf (id int primary key, val int)")
cathy = self.get_session(user='cathy', password='12345')
assert_unauthorized(cathy, "SELECT * FROM ks.cf", "User cathy has no SELECT permission on <table ks.cf> or any of its parents")
cassandra.execute("GRANT SELECT ON ks.cf TO cathy")
rows = list(cathy.execute("SELECT * FROM ks.cf"))
assert 0 == len(rows)
assert_unauthorized(cathy, "INSERT INTO ks.cf (id, val) VALUES (0, 0)", "User cathy has no MODIFY permission on <table ks.cf> or any of its parents")
assert_unauthorized(cathy, "UPDATE ks.cf SET val = 1 WHERE id = 1", "User cathy has no MODIFY permission on <table ks.cf> or any of its parents")
assert_unauthorized(cathy, "DELETE FROM ks.cf WHERE id = 1", "User cathy has no MODIFY permission on <table ks.cf> or any of its parents")
assert_unauthorized(cathy, "TRUNCATE ks.cf", "User cathy has no MODIFY permission on <table ks.cf> or any of its parents")
cassandra.execute("GRANT MODIFY ON ks.cf TO cathy")
cathy.execute("INSERT INTO ks.cf (id, val) VALUES (0, 0)")
cathy.execute("UPDATE ks.cf SET val = 1 WHERE id = 1")
rows = list(cathy.execute("SELECT * FROM ks.cf"))
assert 2 == len(rows)
cathy.execute("DELETE FROM ks.cf WHERE id = 1")
rows = list(cathy.execute("SELECT * FROM ks.cf"))
assert 1 == len(rows)
rows = list(cathy.execute("TRUNCATE ks.cf"))
assert rows == []
@since('2.2')
def test_grant_revoke_without_ks_specified(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Create table ks.cf
* Create a new users, 'cathy' and 'bob', with no permissions
* Grant ALL on ks.cf to cathy
* As cathy, try granting SELECT on cf to bob, without specifying the ks; verify it fails
* As cathy, USE ks, try again, verify it works this time
"""
self.prepare()
cassandra = self.get_session(user='cassandra', password='cassandra')
cassandra.execute("CREATE KEYSPACE ks WITH replication = {'class':'SimpleStrategy', 'replication_factor':1}")
cassandra.execute("CREATE TABLE ks.cf (id int primary key, val int)")
cassandra.execute("CREATE USER cathy WITH PASSWORD '12345'")
cassandra.execute("CREATE USER bob WITH PASSWORD '12345'")
cassandra.execute("GRANT ALL ON ks.cf TO cathy")
cathy = self.get_session(user='cathy', password='12345')
bob = self.get_session(user='bob', password='12345')
assert_invalid(cathy, "GRANT SELECT ON cf TO bob", "No keyspace has been specified. USE a keyspace, or explicitly specify keyspace.tablename")
assert_unauthorized(bob, "SELECT * FROM ks.cf", "User bob has no SELECT permission on <table ks.cf> or any of its parents")
cathy.execute("USE ks")
cathy.execute("GRANT SELECT ON cf TO bob")
bob.execute("SELECT * FROM ks.cf")
def test_grant_revoke_auth(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Create two new users, 'cathy' and 'bob'
* Connect as cathy
* Verify Unauthorized is thrown if cathy tries to grant bob SELECT permissions
* Grant cathy AUTHORIZE
* Verify Unauthorized is still thrown if cathy tries to grant bob SELECT permissions
* Grant cathy SELECT
* Verify she can grant bob SELECT
# Verify bob can SELECT
"""
self.prepare()
cassandra = self.get_session(user='cassandra', password='cassandra')
cassandra.execute("CREATE USER cathy WITH PASSWORD '12345'")
cassandra.execute("CREATE USER bob WITH PASSWORD '12345'")
cassandra.execute("CREATE KEYSPACE ks WITH replication = {'class':'SimpleStrategy', 'replication_factor':1}")
cassandra.execute("CREATE TABLE ks.cf (id int primary key, val int)")
cathy = self.get_session(user='cathy', password='12345')
# missing both SELECT and AUTHORIZE
assert_unauthorized(cathy, "GRANT SELECT ON ALL KEYSPACES TO bob", "User cathy has no AUTHORIZE permission on <all keyspaces> or any of its parents")
cassandra.execute("GRANT AUTHORIZE ON ALL KEYSPACES TO cathy")
# still missing SELECT
assert_unauthorized(cathy, "GRANT SELECT ON ALL KEYSPACES TO bob", "User cathy has no SELECT permission on <all keyspaces> or any of its parents")
cassandra.execute("GRANT SELECT ON ALL KEYSPACES TO cathy")
# should succeed now with both SELECT and AUTHORIZE
cathy.execute("GRANT SELECT ON ALL KEYSPACES TO bob")
bob = self.get_session(user='bob', password='12345')
bob.execute("SELECT * FROM ks.cf")
def test_grant_revoke_nonexistent_user_or_ks(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Create a keyspace, 'ks', and a new user, 'cathy'
* Grant and Revoke permissions to cathy on a nonexistent keyspace, assert throws InvalidRequest
* Grant and Revoke permissions to a nonexistent user to ks, assert throws InvalidRequest
"""
self.prepare()
cassandra = self.get_session(user='cassandra', password='cassandra')
cassandra.execute("CREATE USER cathy WITH PASSWORD '12345'")
cassandra.execute("CREATE KEYSPACE ks WITH replication = {'class':'SimpleStrategy', 'replication_factor':1}")
assert_invalid(cassandra, "GRANT ALL ON KEYSPACE nonexistent TO cathy", "<keyspace nonexistent> doesn't exist")
assert_invalid(cassandra, "GRANT ALL ON KEYSPACE ks TO nonexistent", "(User|Role) nonexistent doesn't exist")
assert_invalid(cassandra, "REVOKE ALL ON KEYSPACE nonexistent FROM cathy", "<keyspace nonexistent> doesn't exist")
assert_invalid(cassandra, "REVOKE ALL ON KEYSPACE ks FROM nonexistent", "(User|Role) nonexistent doesn't exist")
def test_grant_revoke_cleanup(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Create a table, ks.cf
* Create a new user, 'cathy', grant her ALL permissions on ks.cf
* Verify she can read/write from the table
* DROP and CREATE cathy
* Assert her permissions are gone, and operations throw Unauthorized
* Grant ALL permissions back to cathy, verify she can read/write
* DROP and CREATE ks.cf
* Verify cathy's permissions on ks.cf are gone, and operations throw Unauthorized
"""
self.prepare()
cassandra = self.get_session(user='cassandra', password='cassandra')
cassandra.execute("CREATE USER cathy WITH PASSWORD '12345'")
cassandra.execute("CREATE KEYSPACE ks WITH replication = {'class':'SimpleStrategy', 'replication_factor':1}")
cassandra.execute("CREATE TABLE ks.cf (id int primary key, val int)")
cassandra.execute("GRANT ALL ON ks.cf TO cathy")
cathy = self.get_session(user='cathy', password='12345')
cathy.execute("INSERT INTO ks.cf (id, val) VALUES (0, 0)")
rows = list(cathy.execute("SELECT * FROM ks.cf"))
assert 1 == len(rows)
# drop and recreate the user, make sure permissions are gone
cassandra.execute("DROP USER cathy")
cassandra.execute("CREATE USER cathy WITH PASSWORD '12345'")
assert_unauthorized(cathy, "INSERT INTO ks.cf (id, val) VALUES (0, 0)", "User cathy has no MODIFY permission on <table ks.cf> or any of its parents")
assert_unauthorized(cathy, "SELECT * FROM ks.cf", "User cathy has no SELECT permission on <table ks.cf> or any of its parents")
# grant all the permissions back
cassandra.execute("GRANT ALL ON ks.cf TO cathy")
cathy.execute("INSERT INTO ks.cf (id, val) VALUES (0, 0)")
rows = list(cathy.execute("SELECT * FROM ks.cf"))
assert 1 == len(rows)
# drop and recreate the keyspace, make sure permissions are gone
cassandra.execute("DROP KEYSPACE ks")
cassandra.execute("CREATE KEYSPACE ks WITH replication = {'class':'SimpleStrategy', 'replication_factor':1}")
cassandra.execute("CREATE TABLE ks.cf (id int primary key, val int)")
assert_unauthorized(cathy, "INSERT INTO ks.cf (id, val) VALUES (0, 0)", "User cathy has no MODIFY permission on <table ks.cf> or any of its parents")
assert_unauthorized(cathy, "SELECT * FROM ks.cf", "User cathy has no SELECT permission on <table ks.cf> or any of its parents")
def test_permissions_caching(self):
"""
* Launch a one node cluster, with a 2s permission cache
* Connect as the default superuser
* Create a new user, 'cathy'
* Create a table, ks.cf
* Connect as cathy in two separate sessions
* Grant SELECT to cathy
* Verify that reading from ks.cf throws Unauthorized until the cache expires
* Verify that after the cache expires, we can eventually read with both sessions
@jira_ticket CASSANDRA-8194
"""
self.prepare(permissions_validity=2000)
cassandra = self.get_session(user='cassandra', password='cassandra')
cassandra.execute("CREATE USER cathy WITH PASSWORD '12345'")
cassandra.execute("CREATE KEYSPACE ks WITH replication = {'class':'SimpleStrategy', 'replication_factor':1}")
cassandra.execute("CREATE TABLE ks.cf (id int primary key, val int)")
cathy = self.get_session(user='cathy', password='12345')
# another user to make sure the cache is at user level
cathy2 = self.get_session(user='cathy', password='12345')
cathys = [cathy, cathy2]
assert_unauthorized(cathy, "SELECT * FROM ks.cf", "User cathy has no SELECT permission on <table ks.cf> or any of its parents")
def check_caching(attempt=0):
attempt += 1
if attempt > 3:
pytest.fail("Unable to verify cache expiry in 3 attempts, failing")
logger.debug("Attempting to verify cache expiry, attempt #{i}".format(i=attempt))
# grant SELECT to cathy
cassandra.execute("GRANT SELECT ON ks.cf TO cathy")
grant_time = datetime.now()
# selects should still fail after 1 second, but if execution was
# delayed for some reason such that the cache expired, retry
time.sleep(1.0)
for c in cathys:
try:
c.execute("SELECT * FROM ks.cf")
# this should still fail, but if the cache has expired while we paused, try again
delta = datetime.now() - grant_time
if delta > timedelta(seconds=2):
# try again
cassandra.execute("REVOKE SELECT ON ks.cf FROM cathy")
time.sleep(2.5)
check_caching(attempt)
else:
# legit failure
pytest.fail("Expecting query to raise an exception, but nothing was raised.")
except Unauthorized as e:
assert re.search("User cathy has no SELECT permission on <table ks.cf> or any of its parents", str(e))
check_caching()
# wait until the cache definitely expires and retry - should succeed now
time.sleep(1.5)
# refresh of user permissions is done asynchronously, the first request
# will trigger the refresh, but we'll continue to use the cached set until
# that completes (CASSANDRA-8194).
# make a request to trigger the refresh
try:
cathy.execute("SELECT * FROM ks.cf")
except Unauthorized:
pass
# once the async refresh completes, both clients should have the granted permissions
success = False
cnt = 0
while not success and cnt < 10:
try:
for c in cathys:
rows = list(c.execute("SELECT * FROM ks.cf"))
assert 0 == len(rows)
success = True
except Unauthorized:
pass
cnt += 1
time.sleep(0.1)
assert success
def test_list_permissions(self):
"""
* Launch a one node cluster
* Connect as the default superuser
* Create two users, 'cathy' and 'bob'
* Create two tables, ks.cf and ks.cf2
* Grant a number of permissions to each user
* Verify that LIST PERMISSIONS shows correct permissions for each user
* Verify that only the superuser can LIST PERMISSIONS
@jira_ticket CASSANDRA-7216
"""
self.prepare()
cassandra = self.get_session(user='cassandra', password='cassandra')
cassandra.execute("CREATE USER cathy WITH PASSWORD '12345'")
cassandra.execute("CREATE USER bob WITH PASSWORD '12345'")
cassandra.execute("CREATE KEYSPACE ks WITH replication = {'class':'SimpleStrategy', 'replication_factor':1}")
cassandra.execute("CREATE TABLE ks.cf (id int primary key, val int)")
cassandra.execute("CREATE TABLE ks.cf2 (id int primary key, val int)")
cassandra.execute("GRANT CREATE ON ALL KEYSPACES TO cathy")
cassandra.execute("GRANT ALTER ON KEYSPACE ks TO bob")
cassandra.execute("GRANT MODIFY ON ks.cf TO cathy")
cassandra.execute("GRANT DROP ON ks.cf TO bob")
cassandra.execute("GRANT MODIFY ON ks.cf2 TO bob")
cassandra.execute("GRANT SELECT ON ks.cf2 TO cathy")
all_permissions = [('cathy', '<all keyspaces>', 'CREATE'),
('cathy', '<table ks.cf>', 'MODIFY'),
('cathy', '<table ks.cf2>', 'SELECT'),
('bob', '<keyspace ks>', 'ALTER'),
('bob', '<table ks.cf>', 'DROP'),
('bob', '<table ks.cf2>', 'MODIFY')]
# CASSANDRA-7216 automatically grants permissions on a role to its creator
if self.cluster.cassandra_version() >= '2.2.0':
all_permissions.extend(self.data_resource_creator_permissions('cassandra', '<keyspace ks>'))
all_permissions.extend(self.data_resource_creator_permissions('cassandra', '<table ks.cf>'))
all_permissions.extend(self.data_resource_creator_permissions('cassandra', '<table ks.cf2>'))
all_permissions.extend(self.role_creator_permissions('cassandra', '<role bob>'))
all_permissions.extend(self.role_creator_permissions('cassandra', '<role cathy>'))
self.assertPermissionsListed(all_permissions, cassandra, "LIST ALL PERMISSIONS")
self.assertPermissionsListed([('cathy', '<all keyspaces>', 'CREATE'),
('cathy', '<table ks.cf>', 'MODIFY'),
('cathy', '<table ks.cf2>', 'SELECT')],
cassandra, "LIST ALL PERMISSIONS OF cathy")
expected_permissions = [('cathy', '<table ks.cf>', 'MODIFY'), ('bob', '<table ks.cf>', 'DROP')]
if self.cluster.cassandra_version() >= '2.2.0':
expected_permissions.extend(self.data_resource_creator_permissions('cassandra', '<table ks.cf>'))
self.assertPermissionsListed(expected_permissions, cassandra, "LIST ALL PERMISSIONS ON ks.cf NORECURSIVE")
expected_permissions = [('cathy', '<table ks.cf2>', 'SELECT')]
# CASSANDRA-7216 automatically grants permissions on a role to its creator
if self.cluster.cassandra_version() >= '2.2.0':
expected_permissions.append(('cassandra', '<table ks.cf2>', 'SELECT'))
expected_permissions.append(('cassandra', '<keyspace ks>', 'SELECT'))
self.assertPermissionsListed(expected_permissions, cassandra, "LIST SELECT ON ks.cf2")