Repository navigation
Expand file tree
/
Copy pathtest_dsql.py
More file actions
3381 lines (3028 loc) · 142 KB
/
Copy pathtest_dsql.py
File metadata and controls
3381 lines (3028 loc) · 142 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
"""
Integration tests for the Aurora DSQL control-plane emulator, plus
validator unit tests and live data-plane (wire proxy) tests.
"""
import asyncio
import logging
import os
import re
import socket
import struct
import threading
import time
from urllib.parse import urlparse
import pytest
from botocore.exceptions import ClientError
from ministack.core import pgproxy
# Raw HTTP calls here must hit the same server the boto3 fixtures use. Hardcoding
# 4566 silently fails everywhere except a default-port run (CI), which is exactly
# the kind of test that looks green until someone runs the suite on another port.
_ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")
_ENDPOINT_HOST = urlparse(_ENDPOINT).hostname or "localhost"
_ENDPOINT_PORT = urlparse(_ENDPOINT).port or 4566
ID_RE = re.compile(r"^[a-z0-9]{26}$")
def _create(dsql, **kwargs):
resp = dsql.create_cluster(**kwargs)
return resp["identifier"]
def _cleanup(dsql, identifier):
try:
dsql.update_cluster(identifier=identifier, deletionProtectionEnabled=False)
except ClientError:
pass
try:
dsql.delete_cluster(identifier=identifier)
except ClientError:
pass
def _wait_active(dsql, identifier, timeout=60):
"""Poll GetCluster until the cluster is ACTIVE (backend may spin up async)."""
deadline = time.time() + timeout
while time.time() < deadline:
cluster = dsql.get_cluster(identifier=identifier)
if cluster["status"] == "ACTIVE":
return cluster
time.sleep(1)
raise TimeoutError(f"cluster {identifier} not ACTIVE after {timeout}s")
class TestClusterLifecycle:
def test_create_get_list_update_delete(self, dsql):
resp = dsql.create_cluster()
identifier = resp["identifier"]
assert ID_RE.match(identifier)
assert resp["arn"].endswith(f":cluster/{identifier}")
assert ":dsql:us-east-1:" in resp["arn"]
# CREATING while the backend spins up (Docker), ACTIVE without it.
assert resp["status"] in ("CREATING", "ACTIVE")
assert resp["deletionProtectionEnabled"] is True # AWS default: on
assert resp["creationTime"] is not None
assert resp["endpoint"].startswith("localhost:")
got = _wait_active(dsql, identifier)
assert got["identifier"] == identifier
assert got["tags"] == {}
listed = dsql.list_clusters()
assert any(c["identifier"] == identifier for c in listed["clusters"])
summary = next(c for c in listed["clusters"] if c["identifier"] == identifier)
assert summary["arn"] == resp["arn"]
updated = dsql.update_cluster(identifier=identifier, deletionProtectionEnabled=True)
assert updated["identifier"] == identifier
assert updated["status"] == "ACTIVE"
assert dsql.get_cluster(identifier=identifier)["deletionProtectionEnabled"] is True
dsql.update_cluster(identifier=identifier, deletionProtectionEnabled=False)
deleted = dsql.delete_cluster(identifier=identifier)
assert deleted["identifier"] == identifier
assert deleted["status"] == "DELETING"
with pytest.raises(ClientError) as exc:
dsql.get_cluster(identifier=identifier)
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
def test_create_with_multi_region_properties_echoed(self, dsql):
identifier = _create(
dsql,
multiRegionProperties={"witnessRegion": "us-west-2", "clusters": []},
)
try:
got = dsql.get_cluster(identifier=identifier)
assert got["multiRegionProperties"] == {
"witnessRegion": "us-west-2",
"clusters": [],
}
finally:
_cleanup(dsql, identifier)
def test_encryption_details_default_aws_owned(self, dsql):
resp = dsql.create_cluster()
try:
enc = resp["encryptionDetails"]
assert enc["encryptionType"] == "AWS_OWNED_KMS_KEY"
assert enc["encryptionStatus"] == "ENABLED"
assert ":key/aws/dsql" in enc["kmsKeyArn"]
finally:
_cleanup(dsql, resp["identifier"])
def test_encryption_details_customer_managed(self, dsql, kms_client):
key_arn = kms_client.create_key()["KeyMetadata"]["Arn"]
resp = dsql.create_cluster(kmsEncryptionKey=key_arn)
identifier = resp["identifier"]
try:
enc = resp["encryptionDetails"]
assert enc["encryptionType"] == "CUSTOMER_MANAGED_KMS_KEY"
assert enc["kmsKeyArn"] == key_arn
assert enc["encryptionStatus"] == "ENABLED"
# UpdateCluster with a new key updates encryptionDetails
new_key = kms_client.create_key()["KeyMetadata"]["Arn"]
dsql.update_cluster(identifier=identifier, kmsEncryptionKey=new_key)
got = dsql.get_cluster(identifier=identifier)
assert got["encryptionDetails"]["kmsKeyArn"] == new_key
assert got["encryptionDetails"]["encryptionType"] == "CUSTOMER_MANAGED_KMS_KEY"
finally:
_cleanup(dsql, identifier)
def test_kms_key_validated_against_kms_service(self, dsql, kms_client):
bogus = "arn:aws:kms:us-east-1:000000000000:key/12345678-1234-1234-1234-123456789012"
with pytest.raises(ClientError) as exc:
dsql.create_cluster(kmsEncryptionKey=bogus)
assert exc.value.response["Error"]["Code"] == "ValidationException"
# A real key (by id, ARN, or alias) is accepted.
key = kms_client.create_key()["KeyMetadata"]
kms_client.create_alias(AliasName="alias/dsql-test", TargetKeyId=key["KeyId"])
for ref in (key["KeyId"], key["Arn"], "alias/dsql-test"):
resp = dsql.create_cluster(kmsEncryptionKey=ref)
identifier = resp["identifier"]
try:
enc = resp["encryptionDetails"]
assert enc["encryptionType"] == "CUSTOMER_MANAGED_KMS_KEY"
# bare ids/aliases expand to a full key ARN
assert enc["kmsKeyArn"].startswith("arn:aws:kms:")
finally:
_cleanup(dsql, identifier)
# UpdateCluster validates too.
identifier = _create(dsql)
try:
with pytest.raises(ClientError) as exc:
dsql.update_cluster(identifier=identifier, kmsEncryptionKey=bogus)
assert exc.value.response["Error"]["Code"] == "ValidationException"
finally:
_cleanup(dsql, identifier)
def test_kms_aws_managed_alias_accepted(self, dsql):
# AWS-managed aliases exist by definition — no KMS store entry needed.
resp = dsql.create_cluster(kmsEncryptionKey="alias/aws/dsql")
try:
assert resp["encryptionDetails"]["encryptionType"] == "CUSTOMER_MANAGED_KMS_KEY"
finally:
_cleanup(dsql, resp["identifier"])
def test_endpoints_get_unique_ports(self, dsql):
a = dsql.create_cluster()
b = dsql.create_cluster()
try:
assert a["endpoint"] != b["endpoint"]
assert a["endpoint"].split(":")[1].isdigit()
finally:
_cleanup(dsql, a["identifier"])
_cleanup(dsql, b["identifier"])
def test_deletion_protection_blocks_delete(self, dsql):
identifier = _create(dsql, deletionProtectionEnabled=True)
try:
with pytest.raises(ClientError) as exc:
dsql.delete_cluster(identifier=identifier)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert "deletion protection" in err["Message"].lower()
assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
# Disable protection, then delete succeeds.
dsql.update_cluster(identifier=identifier, deletionProtectionEnabled=False)
deleted = dsql.delete_cluster(identifier=identifier)
assert deleted["status"] == "DELETING"
finally:
_cleanup(dsql, identifier)
def test_unknown_cluster_id(self, dsql):
unknown = "a" * 26
for call in (
lambda: dsql.get_cluster(identifier=unknown),
lambda: dsql.update_cluster(identifier=unknown, deletionProtectionEnabled=True),
lambda: dsql.delete_cluster(identifier=unknown),
):
with pytest.raises(ClientError) as exc:
call()
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
def test_client_token_idempotency(self, dsql):
token = "test-idempotency-token-12345"
first = dsql.create_cluster(clientToken=token)
second = dsql.create_cluster(clientToken=token)
try:
assert second["identifier"] == first["identifier"]
assert second["arn"] == first["arn"]
finally:
_cleanup(dsql, first["identifier"])
def test_list_clusters_pagination(self, dsql):
ids = {_create(dsql), _create(dsql)}
try:
seen = []
kwargs = {"maxResults": 1}
pages = 0
while True:
resp = dsql.list_clusters(**kwargs)
assert len(resp["clusters"]) <= 1
seen.extend(c["identifier"] for c in resp["clusters"])
pages += 1
token = resp.get("nextToken")
if not token:
break
kwargs["nextToken"] = token
assert ids.issubset(set(seen))
assert pages >= 2
finally:
for identifier in ids:
_cleanup(dsql, identifier)
def test_list_clusters_invalid_next_token(self, dsql):
with pytest.raises(ClientError) as exc:
dsql.list_clusters(nextToken="not-a-valid-token")
assert exc.value.response["Error"]["Code"] == "ValidationException"
def test_list_clusters_max_results_out_of_range(self):
# botocore validates maxResults (model min 1 / max 100) client-side,
# so exercise the server-side validation with a raw HTTP call.
import urllib.error
import urllib.request
for bad in (0, 101):
req = urllib.request.Request(
f"{_ENDPOINT}/cluster?max-results={bad}",
headers={"Host": "dsql.us-east-1.localhost"},
)
with pytest.raises(urllib.error.HTTPError) as exc:
urllib.request.urlopen(req, timeout=10)
assert exc.value.code == 400, bad
assert exc.value.headers["x-amzn-errortype"] == "ValidationException"
def test_update_cluster_empty_body_rejected(self, dsql):
identifier = _create(dsql)
try:
with pytest.raises(ClientError) as exc:
dsql.update_cluster(identifier=identifier)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
finally:
_cleanup(dsql, identifier)
def test_delete_cluster_client_token_idempotency(self, dsql):
identifier = _create(dsql)
try:
dsql.update_cluster(identifier=identifier, deletionProtectionEnabled=False)
token = "delete-idempotency-token-abc"
first = dsql.delete_cluster(identifier=identifier, clientToken=token)
assert first["identifier"] == identifier
assert first["status"] == "DELETING"
# Second delete with same token returns idempotent success
second = dsql.delete_cluster(identifier=identifier, clientToken=token)
assert second["identifier"] == identifier
assert second["status"] == "DELETING"
assert second["arn"] == first["arn"]
assert second["creationTime"] == first["creationTime"]
finally:
_cleanup(dsql, identifier)
class TestTags:
def test_tags_via_create_and_tag_ops(self, dsql):
resp = dsql.create_cluster(tags={"env": "test", "team": "data"})
identifier = resp["identifier"]
arn = resp["arn"]
try:
got = dsql.get_cluster(identifier=identifier)
assert got["tags"] == {"env": "test", "team": "data"}
listed = dsql.list_tags_for_resource(resourceArn=arn)
assert listed["tags"] == {"env": "test", "team": "data"}
dsql.tag_resource(resourceArn=arn, tags={"owner": "alice", "env": "prod"})
listed = dsql.list_tags_for_resource(resourceArn=arn)
assert listed["tags"] == {"env": "prod", "team": "data", "owner": "alice"}
dsql.untag_resource(resourceArn=arn, tagKeys=["team", "owner"])
listed = dsql.list_tags_for_resource(resourceArn=arn)
assert listed["tags"] == {"env": "prod"}
finally:
_cleanup(dsql, identifier)
def test_tag_ops_unknown_arn(self, dsql):
unknown_arn = "arn:aws:dsql:us-east-1:000000000000:cluster/" + "z" * 26
with pytest.raises(ClientError) as exc:
dsql.list_tags_for_resource(resourceArn=unknown_arn)
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
with pytest.raises(ClientError) as exc:
dsql.tag_resource(resourceArn=unknown_arn, tags={"k": "v"})
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
with pytest.raises(ClientError) as exc:
dsql.untag_resource(resourceArn=unknown_arn, tagKeys=["k"])
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
class TestClusterPolicy:
POLICY = '{"Version":"2012-10-17","Statement":[]}'
def test_policy_put_get_delete(self, dsql):
identifier = _create(dsql)
try:
with pytest.raises(ClientError) as exc:
dsql.get_cluster_policy(identifier=identifier)
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
put = dsql.put_cluster_policy(identifier=identifier, policy=self.POLICY)
assert put["policyVersion"] == "1"
got = dsql.get_cluster_policy(identifier=identifier)
assert got["policy"] == self.POLICY
assert got["policyVersion"] == "1"
put2 = dsql.put_cluster_policy(
identifier=identifier, policy=self.POLICY, expectedPolicyVersion="1"
)
assert put2["policyVersion"] == "2"
deleted = dsql.delete_cluster_policy(identifier=identifier)
assert deleted["policyVersion"] == "2"
with pytest.raises(ClientError) as exc:
dsql.get_cluster_policy(identifier=identifier)
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
finally:
_cleanup(dsql, identifier)
def test_policy_version_conflict(self, dsql):
identifier = _create(dsql)
try:
dsql.put_cluster_policy(identifier=identifier, policy=self.POLICY)
with pytest.raises(ClientError) as exc:
dsql.put_cluster_policy(
identifier=identifier, policy=self.POLICY, expectedPolicyVersion="99"
)
assert exc.value.response["Error"]["Code"] == "ConflictException"
assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 409
finally:
_cleanup(dsql, identifier)
def test_policy_on_unknown_cluster(self, dsql):
unknown = "z" * 26
with pytest.raises(ClientError) as exc:
dsql.put_cluster_policy(identifier=unknown, policy=self.POLICY)
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
def test_create_cluster_with_policy(self, dsql):
resp = dsql.create_cluster(policy=self.POLICY)
identifier = resp["identifier"]
try:
got = dsql.get_cluster_policy(identifier=identifier)
assert got["policy"] == self.POLICY
assert got["policyVersion"] == "1"
finally:
_cleanup(dsql, identifier)
def test_delete_policy_with_expected_version_success(self, dsql):
identifier = _create(dsql)
try:
dsql.put_cluster_policy(identifier=identifier, policy=self.POLICY)
deleted = dsql.delete_cluster_policy(
identifier=identifier, expectedPolicyVersion="1"
)
assert deleted["policyVersion"] == "1"
finally:
_cleanup(dsql, identifier)
def test_delete_policy_expected_version_conflict(self, dsql):
identifier = _create(dsql)
try:
dsql.put_cluster_policy(identifier=identifier, policy=self.POLICY)
with pytest.raises(ClientError) as exc:
dsql.delete_cluster_policy(
identifier=identifier, expectedPolicyVersion="99"
)
assert exc.value.response["Error"]["Code"] == "ConflictException"
assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 409
finally:
_cleanup(dsql, identifier)
class TestStreams:
"""CDC streams (GA 2026-07-08): metadata only — nothing is delivered."""
ROLE_ARN = "arn:aws:iam::000000000000:role/dsql-cdc"
def _target(self, kin, name):
try:
kin.create_stream(StreamName=name, ShardCount=1)
except ClientError as e:
if e.response["Error"]["Code"] != "ResourceInUseException":
raise
arn = kin.describe_stream(StreamName=name)["StreamDescription"]["StreamARN"]
return {"kinesis": {"streamArn": arn, "roleArn": self.ROLE_ARN}}
def test_stream_lifecycle(self, dsql, kin):
identifier = _create(dsql)
try:
target = self._target(kin, "dsql-cdc-life")
created = dsql.create_stream(
clusterIdentifier=identifier,
targetDefinition=target,
ordering="UNORDERED",
format="JSON",
tags={"env": "test"},
)
stream_id = created["streamIdentifier"]
assert ID_RE.match(stream_id)
assert created["status"] == "ACTIVE"
assert created["arn"] == (
f"arn:aws:dsql:us-east-1:000000000000:cluster/{identifier}"
f"/stream/{stream_id}"
)
got = dsql.get_stream(
clusterIdentifier=identifier, streamIdentifier=stream_id
)
assert got["targetDefinition"] == target
assert got["ordering"] == "UNORDERED"
assert got["format"] == "JSON"
assert got["tags"] == {"env": "test"}
assert "statusReason" not in got
listed = dsql.list_streams(clusterIdentifier=identifier)["streams"]
assert [st["streamIdentifier"] for st in listed] == [stream_id]
deleted = dsql.delete_stream(
clusterIdentifier=identifier, streamIdentifier=stream_id
)
assert deleted["status"] == "DELETING"
with pytest.raises(ClientError) as exc:
dsql.get_stream(
clusterIdentifier=identifier, streamIdentifier=stream_id
)
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
finally:
_cleanup(dsql, identifier)
def test_stream_tags_and_client_token(self, dsql, kin):
identifier = _create(dsql)
try:
target = self._target(kin, "dsql-cdc-tags")
created = dsql.create_stream(
clusterIdentifier=identifier,
targetDefinition=target,
ordering="UNORDERED",
format="JSON",
clientToken="tok-cdc",
)
repeat = dsql.create_stream(
clusterIdentifier=identifier,
targetDefinition=target,
ordering="UNORDERED",
format="JSON",
clientToken="tok-cdc",
)
assert repeat["streamIdentifier"] == created["streamIdentifier"]
dsql.tag_resource(resourceArn=created["arn"], tags={"team": "data"})
assert dsql.list_tags_for_resource(resourceArn=created["arn"])["tags"] == {
"team": "data"
}
dsql.untag_resource(resourceArn=created["arn"], tagKeys=["team"])
assert dsql.list_tags_for_resource(resourceArn=created["arn"])["tags"] == {}
finally:
_cleanup(dsql, identifier)
def test_missing_kinesis_target_lands_failed(self, dsql):
identifier = _create(dsql)
try:
created = dsql.create_stream(
clusterIdentifier=identifier,
targetDefinition={"kinesis": {
"streamArn": "arn:aws:kinesis:us-east-1:000000000000:stream/absent",
"roleArn": self.ROLE_ARN,
}},
ordering="UNORDERED",
format="JSON",
)
assert created["status"] == "FAILED"
got = dsql.get_stream(
clusterIdentifier=identifier,
streamIdentifier=created["streamIdentifier"],
)
assert got["statusReason"]["error"] == "KINESIS_STREAM_NOT_FOUND"
finally:
_cleanup(dsql, identifier)
def test_stream_limit_per_cluster(self, dsql, kin):
identifier = _create(dsql)
try:
target = self._target(kin, "dsql-cdc-limit")
for _ in range(5):
dsql.create_stream(
clusterIdentifier=identifier,
targetDefinition=target,
ordering="UNORDERED",
format="JSON",
)
with pytest.raises(ClientError) as exc:
dsql.create_stream(
clusterIdentifier=identifier,
targetDefinition=target,
ordering="UNORDERED",
format="JSON",
)
assert exc.value.response["Error"]["Code"] == "ServiceQuotaExceededException"
assert "stream limit" in exc.value.response["Error"]["Message"]
finally:
_cleanup(dsql, identifier)
def test_stream_on_unknown_cluster(self, dsql):
unknown = "z" * 26
with pytest.raises(ClientError) as exc:
dsql.list_streams(clusterIdentifier=unknown)
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
def test_deleting_a_cluster_takes_its_streams(self, dsql, kin):
identifier = _create(dsql)
target = self._target(kin, "dsql-cdc-gone")
created = dsql.create_stream(
clusterIdentifier=identifier,
targetDefinition=target,
ordering="UNORDERED",
format="JSON",
)
_cleanup(dsql, identifier)
with pytest.raises(ClientError) as exc:
dsql.get_stream(
clusterIdentifier=identifier,
streamIdentifier=created["streamIdentifier"],
)
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
def test_stream_active_waiter(self, dsql, kin):
identifier = _create(dsql)
try:
target = self._target(kin, "dsql-cdc-waiter")
created = dsql.create_stream(
clusterIdentifier=identifier,
targetDefinition=target,
ordering="UNORDERED",
format="JSON",
)
dsql.get_waiter("stream_active").wait(
clusterIdentifier=identifier,
streamIdentifier=created["streamIdentifier"],
WaiterConfig={"Delay": 1, "MaxAttempts": 3},
)
finally:
_cleanup(dsql, identifier)
class TestVpcEndpointServiceName:
def test_service_name_is_stable_per_cluster(self, dsql):
identifier = _create(dsql)
try:
first = dsql.get_vpc_endpoint_service_name(identifier=identifier)
assert re.match(
r"^com\.amazonaws\.us-east-1\.dsql-[a-f0-9]{6}$", first["serviceName"]
)
second = dsql.get_vpc_endpoint_service_name(identifier=identifier)
assert second["serviceName"] == first["serviceName"]
finally:
_cleanup(dsql, identifier)
def test_unknown_cluster(self, dsql):
with pytest.raises(ClientError) as exc:
dsql.get_vpc_endpoint_service_name(identifier="z" * 26)
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
class TestBotoParity:
"""Waiters, paginators, and structured error members (botocore model)."""
def test_cluster_active_and_not_exists_waiters(self, dsql):
identifier = _create(dsql)
dsql.get_waiter("cluster_active").wait(
identifier=identifier, WaiterConfig={"Delay": 1, "MaxAttempts": 60}
)
assert dsql.get_cluster(identifier=identifier)["status"] == "ACTIVE"
dsql.update_cluster(identifier=identifier, deletionProtectionEnabled=False)
dsql.delete_cluster(identifier=identifier)
dsql.get_waiter("cluster_not_exists").wait(
identifier=identifier, WaiterConfig={"Delay": 1, "MaxAttempts": 10}
)
def test_list_clusters_paginator(self, dsql):
ids = {_create(dsql), _create(dsql)}
try:
paginator = dsql.get_paginator("list_clusters")
seen = []
for page in paginator.paginate(PaginationConfig={"PageSize": 1}):
seen.extend(c["identifier"] for c in page["clusters"])
assert ids.issubset(set(seen))
assert len(seen) >= 2
finally:
for identifier in ids:
_cleanup(dsql, identifier)
def test_error_members_not_found(self, dsql):
unknown = "z" * 26
with pytest.raises(ClientError) as exc:
dsql.get_cluster(identifier=unknown)
resp = exc.value.response
assert resp["Error"]["Code"] == "ResourceNotFoundException"
# botocore parses modeled error members at the response top level
assert resp["resourceId"] == unknown
assert resp["resourceType"] == "cluster"
def test_error_members_deletion_protection(self, dsql):
identifier = _create(dsql, deletionProtectionEnabled=True)
try:
with pytest.raises(ClientError) as exc:
dsql.delete_cluster(identifier=identifier)
resp = exc.value.response
assert resp["Error"]["Code"] == "ValidationException"
assert resp["reason"] == "deletionProtectionEnabled"
finally:
_cleanup(dsql, identifier)
def test_update_delete_response_shape(self, dsql):
identifier = _create(dsql)
try:
updated = dsql.update_cluster(
identifier=identifier, deletionProtectionEnabled=False
)
assert set(updated) == {
"identifier", "arn", "status", "creationTime", "ResponseMetadata",
}
finally:
deleted = dsql.delete_cluster(identifier=identifier)
assert set(deleted) == {
"identifier", "arn", "status", "creationTime", "ResponseMetadata",
}
class TestAuthTokens:
def test_generate_db_connect_auth_token(self, dsql):
token = dsql.generate_db_connect_auth_token("localhost", "us-east-1")
assert isinstance(token, str)
assert "Action=DbConnect" in token
def test_generate_db_connect_admin_auth_token(self, dsql):
token = dsql.generate_db_connect_admin_auth_token("localhost", "us-east-1")
assert isinstance(token, str)
assert "Action=DbConnectAdmin" in token
# ---------------------------------------------------------------------------
# Validator unit tests (no server, no Postgres needed)
# ---------------------------------------------------------------------------
class TestClassifyStatement:
@pytest.mark.parametrize(
"sql,expected",
[
("CREATE TABLE t (a int)", "ddl"),
("alter table t add column b int", "ddl"),
("DROP INDEX idx", "ddl"),
("INSERT INTO t VALUES (1)", "dml"),
("update t set a = 1", "dml"),
("DELETE FROM t", "dml"),
("BEGIN", "tcl_begin"),
("START TRANSACTION", "tcl_begin"),
("COMMIT", "tcl_end"),
("END", "tcl_end"),
("ROLLBACK", "tcl_end"),
("ABORT", "tcl_end"),
("SELECT 1", "other"),
("SET search_path TO public", "other"),
("SHOW server_version", "other"),
("GRANT SELECT ON t TO r", "other"),
("REVOKE SELECT ON t FROM r", "other"),
# Leading comments must not hide the statement keyword.
("-- migration 004\nCREATE TABLE t (a int)", "ddl"),
("/* flyway */ INSERT INTO t VALUES (1)", "dml"),
("/* a /* nested */ b */ COMMIT", "tcl_end"),
("\n\n-- one\n-- two\nBEGIN", "tcl_begin"),
# CTE-leading writes are still writes.
("WITH x AS (SELECT 1) INSERT INTO t SELECT 1", "dml"),
("WITH x AS (SELECT 1) UPDATE t SET a = 1", "dml"),
("WITH x AS (SELECT 1) DELETE FROM t", "dml"),
("WITH RECURSIVE x AS (SELECT 1) INSERT INTO t SELECT 1", "dml"),
("WITH x (a, b) AS (SELECT 1, 2) INSERT INTO t SELECT 1", "dml"),
("WITH x AS MATERIALIZED (SELECT 1) INSERT INTO t SELECT 1", "dml"),
("WITH a AS (SELECT 1), b AS (SELECT 2) INSERT INTO t SELECT 1", "dml"),
("WITH x AS (SELECT 1) SELECT * FROM x", "other"),
# EXPLAIN ANALYZE executes; plain EXPLAIN only plans.
("EXPLAIN ANALYZE INSERT INTO t VALUES (1)", "dml"),
("EXPLAIN (ANALYZE, BUFFERS) DELETE FROM t", "dml"),
("EXPLAIN INSERT INTO t VALUES (1)", "other"),
("EXPLAIN SELECT 1", "other"),
],
)
def test_classify(self, sql, expected):
assert pgproxy.classify_statement(sql) == expected
class TestSqlLexing:
"""Statement splitting and comment stripping must not be fooled by
literals — a ';' or ')' inside a string used to truncate the text a
validation rule saw, so the rule passed on the fragment."""
@pytest.mark.parametrize(
"sql,expected",
[
("SELECT 1; SELECT 2", ["SELECT 1", "SELECT 2"]),
("SELECT 'a;b'", ["SELECT 'a;b'"]),
("SELECT 'it''s; fine'", ["SELECT 'it''s; fine'"]),
("SELECT $$a;b$$", ["SELECT $$a;b$$"]),
("SELECT $tag$a;b$tag$", ["SELECT $tag$a;b$tag$"]),
('SELECT "we;ird"', ['SELECT "we;ird"']),
("SELECT 1 -- c;omment\n; SELECT 2", ["SELECT 1 -- c;omment", "SELECT 2"]),
("SELECT 1 /* c;omment */; SELECT 2", ["SELECT 1 /* c;omment */", "SELECT 2"]),
("SELECT E'a\\';b'", ["SELECT E'a\\';b'"]),
("SELECT 1;", ["SELECT 1"]),
(" ; ", []),
],
)
def test_split_statements(self, sql, expected):
assert pgproxy.split_statements(sql) == expected
@pytest.mark.parametrize(
"sql,expected",
[
("-- x\nSELECT 1", "SELECT 1"),
("/* x */SELECT 1", "SELECT 1"),
("/* a /* b */ c */ SELECT 1", "SELECT 1"),
(" \n\t-- a\n /* b */\nSELECT 1", "SELECT 1"),
("SELECT 1 -- trailing", "SELECT 1 -- trailing"),
("'-- not a comment'", "'-- not a comment'"),
],
)
def test_strip_leading_comments(self, sql, expected):
assert pgproxy.strip_leading_comments(sql) == expected
def test_semicolon_in_literal_does_not_hide_a_bad_column(self):
# The fragment left by a naive ';' split had unbalanced parens, so the
# column-type rule silently passed and `serial` got through.
err = pgproxy.validate(
"CREATE TABLE t (a text DEFAULT 'x;y', b serial)"
)
assert isinstance(err, pgproxy.DsqlError)
assert "serial" in err.message
def test_paren_in_literal_does_not_hide_a_bad_column(self):
err = pgproxy.validate("CREATE TABLE t (a text DEFAULT ')(', b serial)")
assert isinstance(err, pgproxy.DsqlError)
assert "serial" in err.message
@pytest.mark.parametrize(
"sql",
[
"-- migration\nCREATE EXTENSION pgcrypto",
"/* tooling */ TRUNCATE t",
"\n-- a\n/* b */ CREATE TEMP TABLE t (a int)",
],
)
def test_leading_comment_does_not_bypass_the_denylist(self, sql):
assert isinstance(pgproxy.validate(sql), pgproxy.DsqlError)
class TestDenylist:
@pytest.mark.parametrize(
"sql",
[
"CREATE DATABASE foo",
"CREATE TYPE mood AS ENUM ('sad')",
"CREATE EXTENSION pgcrypto",
"CREATE TRIGGER trg AFTER INSERT ON t EXECUTE FUNCTION f()",
"CREATE PROCEDURE p() LANGUAGE sql AS $$ SELECT 1 $$",
"CREATE TABLESPACE ts LOCATION '/tmp/x'",
"CREATE TEMP TABLE t (a int)",
"CREATE TEMPORARY TABLE t (a int)",
"CREATE UNLOGGED TABLE t (a int)",
"COPY t FROM STDIN",
"LISTEN chan",
"NOTIFY chan",
"UNLISTEN chan",
"TRUNCATE t",
"DO $$ BEGIN NULL; END $$",
"SAVEPOINT sp",
"LOCK TABLE t IN ACCESS EXCLUSIVE MODE",
"CREATE FUNCTION f() RETURNS int LANGUAGE plpgsql AS $$ BEGIN RETURN 1; END $$",
"CREATE FUNCTION f() RETURNS int LANGUAGE C AS 'x'",
"CREATE MATERIALIZED VIEW mv AS SELECT 1",
"CREATE TABLE t (a int) PARTITION BY RANGE (a)",
"CREATE TABLE p (a int, EXCLUDE (a WITH =))",
"CREATE RULE r AS ON DELETE TO t DO INSTEAD NOTHING",
"CREATE AGGREGATE a (int) (sfunc = f, stype = int)",
"CREATE DOMAIN d AS int",
"CREATE CAST (int AS text) WITH FUNCTION f(int)",
"CREATE COLLATION c (locale = 'en_US')",
"CREATE OPERATOR + (leftarg = int, rightarg = int, function = f)",
"CREATE PUBLICATION p FOR ALL TABLES",
"CREATE SUBSCRIPTION s CONNECTION 'x' PUBLICATION p",
"CREATE FOREIGN TABLE ft (a int) SERVER s",
"CREATE SERVER s FOREIGN DATA WRAPPER w",
"VACUUM t",
"VACUUM FULL ANALYZE t",
"CLUSTER t USING idx",
"REINDEX TABLE t",
"ALTER SYSTEM SET work_mem = '4MB'",
"PREPARE TRANSACTION 'gid'",
"COMMIT PREPARED 'gid'",
"ROLLBACK PREPARED 'gid'",
],
)
def test_denied(self, sql):
err = pgproxy.validate(sql, pgproxy.TxnState())
assert isinstance(err, pgproxy.DsqlError), sql
assert err.sqlstate == "0A000"
assert "is not supported" in err.message
@pytest.mark.parametrize(
"sql,message",
[
("ALTER TABLE t ADD COLUMN c int DEFAULT 0",
"ALTER TABLE ADD COLUMN with constraint not supported"),
("ALTER TABLE t ADD COLUMN c text NOT NULL",
"ALTER TABLE ADD COLUMN with constraint not supported"),
("ALTER TABLE t ADD COLUMN c int UNIQUE",
"ALTER TABLE ADD COLUMN with constraint not supported"),
("ALTER TABLE t ADD COLUMN c int CHECK (c > 0)",
"ALTER TABLE ADD COLUMN with constraint not supported"),
("ALTER TABLE t ADD COLUMN c int REFERENCES o",
"ALTER TABLE ADD COLUMN with constraint not supported"),
("ALTER TABLE t ADD COLUMN c text GENERATED ALWAYS AS (lower(e)) STORED",
"ALTER TABLE ADD COLUMN with constraint not supported"),
("ALTER TABLE t ADD COLUMN c bigint GENERATED BY DEFAULT AS IDENTITY "
"(CACHE 1)",
"ALTER TABLE ADD COLUMN with constraint not supported"),
('ALTER TABLE t ADD COLUMN c text COLLATE "C"',
"COLLATE clause not supported"),
],
)
def test_add_column_takes_no_constraint(self, sql, message):
err = pgproxy.validate(sql, pgproxy.TxnState())
assert isinstance(err, pgproxy.DsqlError), sql
assert err.sqlstate == "0A000"
assert err.message == message, sql
def test_create_function_language_sql_allowed(self):
sql = "CREATE FUNCTION f() RETURNS int LANGUAGE sql AS $$ SELECT 1 $$"
assert pgproxy.validate(sql, pgproxy.TxnState()) is None
class TestColumnTypes:
@pytest.mark.parametrize(
"typ",
[
"serial", "bigserial", "smallserial",
"money", "xml", "inet", "cidr", "macaddr", "macaddr8",
"bit", "bit varying", "varbit",
"point", "line", "lseg", "box", "path", "polygon", "circle",
"hstore",
"int[]", "text[]",
],
)
def test_unsupported_types_denied(self, typ):
err = pgproxy.validate(
f"CREATE TABLE t (id int, c {typ})", pgproxy.TxnState()
)
assert isinstance(err, pgproxy.DsqlError), typ
assert err.sqlstate == "0A000"
assert 'type "' in err.message and "is not supported" in err.message
def test_unsupported_type_in_alter_add_column(self):
err = pgproxy.validate(
"ALTER TABLE t ADD COLUMN c serial", pgproxy.TxnState()
)
assert isinstance(err, pgproxy.DsqlError)
assert err.sqlstate == "0A000"
assert '"serial"' in err.message
@pytest.mark.parametrize(
"typ",
[
"smallint", "int2", "integer", "int", "int4", "bigint", "int8",
"real", "float4", "double precision", "float8",
"numeric", "decimal", "dec", "numeric(18,6)", "dec(10,2)",
"char(1)", "character(1)", "bpchar", "varchar(255)",
"character varying(10)", "text",
"date", "time", "time with time zone", "timetz",
"timestamp", "timestamp with time zone", "timestamptz",
"interval", "interval year", "interval day to second",
"interval year to month", "interval second", "boolean", "bool", "bytea", "uuid", "json", "jsonb",
],
)
def test_supported_types_allowed(self, typ):
assert pgproxy.validate(
f"CREATE TABLE t (id int, c {typ})", pgproxy.TxnState()
) is None
def test_table_constraints_skipped(self):
sql = "CREATE TABLE t (id int PRIMARY KEY, c text UNIQUE, CHECK (id > 0))"
assert pgproxy.validate(sql, pgproxy.TxnState()) is None
def test_storage_modifier_allowed(self):
assert pgproxy.validate(
"CREATE TABLE t (id int, j jsonb STORAGE PLAIN)", pgproxy.TxnState()
) is None
assert pgproxy.validate(
"ALTER TABLE t ADD COLUMN j jsonb STORAGE EXTERNAL", pgproxy.TxnState()
) is None
assert pgproxy.validate(
"ALTER TABLE t ADD COLUMN j jsonb STORAGE DEFAULT", pgproxy.TxnState()
) is None
def test_bogus_interval_fields_rejected(self):
err = pgproxy.validate(
"CREATE TABLE t (id int, c interval foo)", pgproxy.TxnState()
)
assert isinstance(err, pgproxy.DsqlError)
assert err.sqlstate == "0A000"
class TestAlterTableSubset:
"""ALTER TABLE action subset per the AWS alter-table-syntax-support doc."""
@pytest.mark.parametrize(
"sql",
[
"ALTER TABLE t ALTER COLUMN c TYPE text",
"ALTER TABLE t ALTER COLUMN c SET DATA TYPE text",
"ALTER TABLE t ALTER COLUMN c SET NOT NULL",
"ALTER TABLE t ADD CONSTRAINT pk PRIMARY KEY (id)",
"ALTER TABLE t ADD PRIMARY KEY (id)",
"ALTER TABLE t ADD CONSTRAINT u UNIQUE (a)",
"ALTER TABLE t ADD CONSTRAINT c CHECK (a > 0)", # missing NOT VALID
"ALTER TABLE t ALTER COLUMN c ADD GENERATED BY DEFAULT AS IDENTITY", # no CACHE
],
)
def test_unsupported_actions_denied(self, sql):
err = pgproxy.validate(sql, pgproxy.TxnState())
assert isinstance(err, pgproxy.DsqlError), sql
assert err.sqlstate == "0A000"
@pytest.mark.parametrize(
"sql",
[
"ALTER TABLE t DROP COLUMN c",
"ALTER TABLE t DROP COLUMN IF EXISTS c CASCADE",
"ALTER TABLE t ALTER COLUMN c SET DEFAULT 0",
"ALTER TABLE t ALTER COLUMN c DROP DEFAULT",
"ALTER TABLE t ALTER COLUMN c DROP NOT NULL",
"ALTER TABLE t ALTER COLUMN c SET STORAGE PLAIN",
"ALTER TABLE t RENAME COLUMN a TO b",
"ALTER TABLE t RENAME TO t2",
"ALTER TABLE t SET SCHEMA app",
"ALTER TABLE t ADD CONSTRAINT c CHECK (a > 0) NOT VALID",
"ALTER TABLE t ADD CONSTRAINT u UNIQUE USING INDEX idx",
"ALTER TABLE t DROP CONSTRAINT c",
"ALTER TABLE t ALTER COLUMN c ADD GENERATED BY DEFAULT AS IDENTITY (CACHE 1)",
"ALTER TABLE t ADD COLUMN c integer",
"ALTER TABLE t ADD COLUMN j jsonb STORAGE PLAIN",
"ALTER TABLE t ADD COLUMN c int NULL",
"ALTER TABLE t ADD COLUMN IF NOT EXISTS c numeric(18,6)",
"ALTER TABLE t ADD COLUMN a int, ADD COLUMN b text",
],
)