File: test_s3_copyobject.py

package info (click to toggle)
python-moto 5.1.18-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 116,520 kB
  • sloc: python: 636,725; javascript: 181; makefile: 39; sh: 3
file content (1030 lines) | stat: -rw-r--r-- 34,206 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
import datetime
from uuid import uuid4

import boto3
import pytest
from botocore.client import ClientError

from moto import mock_aws
from moto.s3.responses import DEFAULT_REGION_NAME
from tests.test_s3 import generate_content_md5
from tests.test_s3.test_s3 import enable_versioning

from . import s3_aws_verified


@pytest.mark.parametrize(
    "key_name",
    [
        "the-key",
        "the-unicode-💩-key",
        "key-with?question-mark",
        "key-with%2Fembedded%2Furl%2Fencoding",
    ],
)
@mock_aws
def test_copy_key(key_name):
    s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    s3_resource.create_bucket(Bucket="foobar")

    key = s3_resource.Object("foobar", key_name)
    key.put(Body=b"some value")

    key2 = s3_resource.Object("foobar", "new-key")
    key2.copy_from(CopySource=f"foobar/{key_name}")

    resp = client.get_object(Bucket="foobar", Key=key_name)
    assert resp["Body"].read() == b"some value"
    resp = client.get_object(Bucket="foobar", Key="new-key")
    assert resp["Body"].read() == b"some value"


@pytest.mark.aws_verified
@s3_aws_verified
def test_copy_key_with_args(bucket_name=None):
    # Setup
    s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    key_name = "key"
    new_key = "new_key"
    expected_hash = "qz0H8xacy9DtbEtF3iFRn5+TjHLSQSSZiquUnOg7tRs="

    key = s3_resource.Object(bucket_name, key_name)
    key.put(Body=b"some value")

    # Execute
    key2 = s3_resource.Object(bucket_name, new_key)
    key2.copy(
        CopySource={"Bucket": bucket_name, "Key": key_name},
        ExtraArgs={
            "ChecksumAlgorithm": "SHA256",
            "WebsiteRedirectLocation": "http://getmoto.org/",
        },
    )

    # Verify
    resp = client.get_object_attributes(
        Bucket=bucket_name, Key=new_key, ObjectAttributes=["Checksum"]
    )

    assert "Checksum" in resp
    assert "ChecksumSHA256" in resp["Checksum"]
    assert resp["Checksum"]["ChecksumSHA256"] == expected_hash

    obj = client.get_object(Bucket=bucket_name, Key=new_key)
    assert obj["WebsiteRedirectLocation"] == "http://getmoto.org/"

    # Verify in place
    copy_in_place = client.copy_object(
        Bucket=bucket_name,
        CopySource=f"{bucket_name}/{new_key}",
        Key=new_key,
        ChecksumAlgorithm="SHA256",
        MetadataDirective="REPLACE",
    )

    assert "ChecksumSHA256" in copy_in_place["CopyObjectResult"]
    assert copy_in_place["CopyObjectResult"]["ChecksumSHA256"] == expected_hash


@pytest.mark.aws_verified
@s3_aws_verified
def test_copy_key_with_args__using_multipart(bucket_name=None):
    # Setup
    s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    key_name = "key"
    new_key = "new_key"
    expected_hash = "DnKotDi4EtYGwNMDKmnR6SqH3bWVOlo2BC+tsz9rHqw="

    key = s3_resource.Object(bucket_name, key_name)
    key.put(Body=b"some value")

    # Execute
    key2 = s3_resource.Object(bucket_name, new_key)
    key2.copy(
        CopySource={"Bucket": bucket_name, "Key": key_name},
        ExtraArgs={
            "ChecksumAlgorithm": "SHA256",
            "WebsiteRedirectLocation": "http://getmoto.org/",
        },
        Config=boto3.s3.transfer.TransferConfig(multipart_threshold=1),
    )

    # Verify
    resp = client.get_object_attributes(
        Bucket=bucket_name, Key=new_key, ObjectAttributes=["Checksum"]
    )

    assert "Checksum" in resp
    assert "ChecksumSHA256" in resp["Checksum"]
    assert resp["Checksum"]["ChecksumSHA256"] == expected_hash

    obj = client.get_object(Bucket=bucket_name, Key=new_key)
    assert obj["WebsiteRedirectLocation"] == "http://getmoto.org/"


@mock_aws
def test_copy_key_with_version():
    s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    s3_resource.create_bucket(Bucket="foobar")
    client.put_bucket_versioning(
        Bucket="foobar", VersioningConfiguration={"Status": "Enabled"}
    )

    key = s3_resource.Object("foobar", "the-key")
    key.put(Body=b"some value")
    key.put(Body=b"another value")

    all_versions = client.list_object_versions(Bucket="foobar", Prefix="the-key")[
        "Versions"
    ]
    old_version = [v for v in all_versions if not v["IsLatest"]][0]

    key2 = s3_resource.Object("foobar", "new-key")
    key2.copy_from(CopySource=f"foobar/the-key?versionId={old_version['VersionId']}")

    resp = client.get_object(Bucket="foobar", Key="the-key")
    assert resp["Body"].read() == b"another value"
    resp = client.get_object(Bucket="foobar", Key="new-key")
    assert resp["Body"].read() == b"some value"


@mock_aws
def test_copy_object_with_bucketkeyenabled_returns_the_value():
    s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    bucket_name = "test-copy-object-with-bucketkeyenabled"
    s3_resource.create_bucket(Bucket=bucket_name)

    key = s3_resource.Object(bucket_name, "the-key")
    key.put(Body=b"some value")

    key2 = s3_resource.Object(bucket_name, "new-key")
    key2.copy_from(
        CopySource=f"{bucket_name}/the-key",
        BucketKeyEnabled=True,
        ServerSideEncryption="aws:kms",
    )

    resp = client.get_object(Bucket=bucket_name, Key="the-key")
    src_headers = resp["ResponseMetadata"]["HTTPHeaders"]
    assert "x-amz-server-side-encryption" not in src_headers
    assert "x-amz-server-side-encryption-aws-kms-key-id" not in src_headers
    assert "x-amz-server-side-encryption-bucket-key-enabled" not in src_headers

    resp = client.get_object(Bucket=bucket_name, Key="new-key")
    target_headers = resp["ResponseMetadata"]["HTTPHeaders"]
    assert "x-amz-server-side-encryption" in target_headers
    # AWS will also return the KMS default key id - not yet implemented
    # assert "x-amz-server-side-encryption-aws-kms-key-id" in target_headers
    # This field is only returned if encryption is set to 'aws:kms'
    assert "x-amz-server-side-encryption-bucket-key-enabled" in target_headers
    assert (
        str(target_headers["x-amz-server-side-encryption-bucket-key-enabled"]).lower()
        == "true"
    )


@mock_aws
def test_copy_key_with_metadata():
    s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    s3_resource.create_bucket(Bucket="foobar")

    key = s3_resource.Object("foobar", "the-key")
    metadata = {"md": "Metadatastring"}
    content_type = "application/json"
    initial = key.put(Body=b"{}", Metadata=metadata, ContentType=content_type)

    client.copy_object(Bucket="foobar", CopySource="foobar/the-key", Key="new-key")

    resp = client.get_object(Bucket="foobar", Key="new-key")
    assert resp["Metadata"] == metadata
    assert resp["ContentType"] == content_type
    assert resp["ETag"] == initial["ETag"]


@mock_aws
def test_copy_key_replace_metadata():
    s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    s3_resource.create_bucket(Bucket="foobar")

    key = s3_resource.Object("foobar", "the-key")
    initial = key.put(Body=b"some value", Metadata={"md": "Metadatastring"})

    client.copy_object(
        Bucket="foobar",
        CopySource="foobar/the-key",
        Key="new-key",
        Metadata={"momd": "Mometadatastring"},
        MetadataDirective="REPLACE",
    )

    resp = client.get_object(Bucket="foobar", Key="new-key")
    assert resp["Metadata"] == {"momd": "Mometadatastring"}
    assert resp["ETag"] == initial["ETag"]


@s3_aws_verified
@pytest.mark.aws_verified
def test_copy_key_without_changes_should_error(bucket_name=None):
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
    key_name = "my_key"
    key = s3_resource.Object(bucket_name, key_name)

    key.put(Body=b"some value")

    with pytest.raises(ClientError) as exc:
        client.copy_object(
            Bucket=bucket_name,
            CopySource=f"{bucket_name}/{key_name}",
            Key=key_name,
        )
        assert exc.value.response["Error"]["Message"] == (
            "This copy request is illegal because it is trying to copy an "
            "object to itself without changing the object's metadata, storage "
            "class, website redirect location or encryption attributes."
        )


@s3_aws_verified
@pytest.mark.aws_verified
def test_copy_key_without_changes_should_not_error(bucket_name=None):
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
    key_name = "my_key"
    key = s3_resource.Object(bucket_name, key_name)

    key.put(Body=b"some value")

    client.copy_object(
        Bucket=bucket_name,
        CopySource=f"{bucket_name}/{key_name}",
        Key=key_name,
        Metadata={"some-key": "some-value"},
        MetadataDirective="REPLACE",
    )

    new_object = client.get_object(Bucket=bucket_name, Key=key_name)

    assert new_object["Metadata"] == {"some-key": "some-value"}


@mock_aws
def test_copy_key_reduced_redundancy():
    s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    bucket = s3_resource.Bucket("test_bucket")
    bucket.create()

    bucket.put_object(Key="the-key", Body=b"somedata")

    client.copy_object(
        Bucket="test_bucket",
        CopySource="test_bucket/the-key",
        Key="new-key",
        StorageClass="REDUCED_REDUNDANCY",
    )

    keys = {k.key: k for k in bucket.objects.all()}
    assert keys["new-key"].storage_class == "REDUCED_REDUNDANCY"
    assert keys["the-key"].storage_class == "STANDARD"


@s3_aws_verified
@pytest.mark.aws_verified
def test_copy_non_existing_file(bucket_name=None):
    s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
    target = str(uuid4())
    s3_resource.create_bucket(Bucket=target)

    try:
        s3_client = boto3.client("s3", "us-east-1")
        with pytest.raises(ClientError) as exc:
            s3_client.copy_object(
                Bucket=target,
                CopySource={"Bucket": bucket_name, "Key": "foofoofoo"},
                Key="newkey",
            )
        err = exc.value.response["Error"]
        assert err["Code"] == "NoSuchKey"
        assert err["Message"] == "The specified key does not exist."
        assert err["Key"] == "foofoofoo"
    finally:
        s3_client.delete_bucket(Bucket=target)


@s3_aws_verified
@pytest.mark.aws_verified
def test_copy_object_with_versioning(bucket_name=None):
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)

    enable_versioning(bucket_name, client)

    client.put_object(Bucket=bucket_name, Key="test1", Body=b"test1")
    client.put_object(Bucket=bucket_name, Key="test2", Body=b"test2")

    _ = client.get_object(Bucket=bucket_name, Key="test1")["VersionId"]
    obj2_version = client.get_object(Bucket=bucket_name, Key="test2")["VersionId"]

    client.copy_object(
        CopySource={"Bucket": bucket_name, "Key": "test1"},
        Bucket=bucket_name,
        Key="test2",
    )
    obj2_version_new = client.get_object(Bucket=bucket_name, Key="test2")["VersionId"]

    # Version should be different to previous version
    assert obj2_version_new != obj2_version

    client.copy_object(
        CopySource={"Bucket": bucket_name, "Key": "test2", "VersionId": obj2_version},
        Bucket=bucket_name,
        Key="test3",
    )
    obj3_version_new = client.get_object(Bucket=bucket_name, Key="test3")["VersionId"]
    assert obj3_version_new != obj2_version_new

    # Copy file that doesn't exist
    with pytest.raises(ClientError) as exc:
        client.copy_object(
            CopySource={
                "Bucket": bucket_name,
                "Key": "test4",
                "VersionId": obj2_version,
            },
            Bucket=bucket_name,
            Key="test5",
        )
    assert exc.value.response["Error"]["Code"] == "NoSuchVersion"

    response = client.create_multipart_upload(Bucket=bucket_name, Key="test4")
    upload_id = response["UploadId"]
    response = client.upload_part_copy(
        Bucket=bucket_name,
        Key="test4",
        CopySource={
            "Bucket": bucket_name,
            "Key": "test3",
            "VersionId": obj3_version_new,
        },
        UploadId=upload_id,
        PartNumber=1,
    )
    etag = response["CopyPartResult"]["ETag"]
    client.complete_multipart_upload(
        Bucket=bucket_name,
        Key="test4",
        UploadId=upload_id,
        MultipartUpload={"Parts": [{"ETag": etag, "PartNumber": 1}]},
    )

    response = client.get_object(Bucket=bucket_name, Key="test4")
    data = response["Body"].read()
    assert data == b"test2"


@mock_aws
def test_copy_object_from_unversioned_to_versioned_bucket():
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)

    client.create_bucket(Bucket="src")
    client.create_bucket(Bucket="dest")
    client.put_bucket_versioning(
        Bucket="dest", VersioningConfiguration={"Status": "Enabled"}
    )

    client.put_object(Bucket="src", Key="test", Body=b"content")

    obj2_version_new = client.copy_object(
        CopySource={"Bucket": "src", "Key": "test"}, Bucket="dest", Key="test"
    ).get("VersionId")

    # VersionId should be present in the response
    assert obj2_version_new is not None


@mock_aws
def test_copy_object_with_replacement_tagging():
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    client.create_bucket(Bucket="mybucket")
    client.put_object(
        Bucket="mybucket", Key="original", Body=b"test", Tagging="tag=old"
    )

    # using system tags will fail
    with pytest.raises(ClientError) as err:
        client.copy_object(
            CopySource={"Bucket": "mybucket", "Key": "original"},
            Bucket="mybucket",
            Key="copy1",
            TaggingDirective="REPLACE",
            Tagging="aws:tag=invalid_key",
        )

    exc = err.value
    assert exc.response["Error"]["Code"] == "InvalidTag"

    client.copy_object(
        CopySource={"Bucket": "mybucket", "Key": "original"},
        Bucket="mybucket",
        Key="copy1",
        TaggingDirective="REPLACE",
        Tagging="tag=new",
    )
    client.copy_object(
        CopySource={"Bucket": "mybucket", "Key": "original"},
        Bucket="mybucket",
        Key="copy2",
        TaggingDirective="COPY",
    )

    tags1 = client.get_object_tagging(Bucket="mybucket", Key="copy1")["TagSet"]
    assert tags1 == [{"Key": "tag", "Value": "new"}]
    tags2 = client.get_object_tagging(Bucket="mybucket", Key="copy2")["TagSet"]
    assert tags2 == [{"Key": "tag", "Value": "old"}]


@mock_aws
def test_copy_object_with_kms_encryption():
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    kms_client = boto3.client("kms", region_name=DEFAULT_REGION_NAME)
    kms_key = kms_client.create_key()["KeyMetadata"]["KeyId"]

    client.create_bucket(Bucket="blah")

    client.put_object(Bucket="blah", Key="test1", Body=b"test1")

    client.copy_object(
        CopySource={"Bucket": "blah", "Key": "test1"},
        Bucket="blah",
        Key="test2",
        SSEKMSKeyId=kms_key,
        ServerSideEncryption="aws:kms",
    )
    result = client.head_object(Bucket="blah", Key="test2")
    assert result["SSEKMSKeyId"] == kms_key
    assert result["ServerSideEncryption"] == "aws:kms"


@mock_aws
def test_copy_object_in_place_with_encryption():
    kms_client = boto3.client("kms", region_name=DEFAULT_REGION_NAME)
    s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    kms_key = kms_client.create_key()["KeyMetadata"]["KeyId"]
    bucket = s3_resource.Bucket("test_bucket")
    bucket.create()
    key = "source-key"
    resp = client.put_object(
        Bucket="test_bucket",
        Key=key,
        Body=b"somedata",
        ServerSideEncryption="aws:kms",
        BucketKeyEnabled=True,
        SSEKMSKeyId=kms_key,
    )
    assert resp["BucketKeyEnabled"] is True

    # assert that you can copy in place with the same Encryption settings
    client.copy_object(
        Bucket="test_bucket",
        CopySource=f"test_bucket/{key}",
        Key=key,
        ServerSideEncryption="aws:kms",
        BucketKeyEnabled=True,
        SSEKMSKeyId=kms_key,
    )

    # assert that the BucketKeyEnabled setting is not kept in the destination key
    resp = client.copy_object(
        Bucket="test_bucket",
        CopySource=f"test_bucket/{key}",
        Key=key,
        ServerSideEncryption="aws:kms",
        SSEKMSKeyId=kms_key,
    )
    assert "BucketKeyEnabled" not in resp

    # This is an edge case, if the source object SSE was not AES256,
    # AWS allows you to not specify any fields as it will use AES256 by
    # default and is different from the source key.
    resp = client.copy_object(
        Bucket="test_bucket",
        CopySource=f"test_bucket/{key}",
        Key=key,
    )
    assert resp["ServerSideEncryption"] == "AES256"

    # Check that it allows copying in the place with the same
    # ServerSideEncryption setting as the source.
    resp = client.copy_object(
        Bucket="test_bucket",
        CopySource=f"test_bucket/{key}",
        Key=key,
        ServerSideEncryption="AES256",
    )
    assert resp["ServerSideEncryption"] == "AES256"


@mock_aws
def test_copy_object_in_place_with_storage_class():
    """Validate setting StorageClass allows a copy in place.

    This should be true even if destination object is the same as source.
    """
    s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    bucket_name = "test-bucket"
    bucket = s3_resource.Bucket(bucket_name)
    bucket.create()
    key = "source-key"
    bucket.put_object(Key=key, Body=b"somedata", StorageClass="STANDARD")
    client.copy_object(
        Bucket=bucket_name,
        CopySource=f"{bucket_name}/{key}",
        Key=key,
        StorageClass="STANDARD",
    )
    # verify that the copy worked
    resp = client.get_object_attributes(
        Bucket=bucket_name, Key=key, ObjectAttributes=["StorageClass"]
    )
    assert resp["StorageClass"] == "STANDARD"


@mock_aws
def test_copy_object_does_not_copy_storage_class():
    s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    bucket = s3_resource.Bucket("test_bucket")
    bucket.create()
    source_key = "source-key"
    dest_key = "dest-key"
    bucket.put_object(Key=source_key, Body=b"somedata", StorageClass="STANDARD_IA")
    client.copy_object(
        Bucket="test_bucket",
        CopySource=f"test_bucket/{source_key}",
        Key=dest_key,
    )

    # Verify that the destination key does not have STANDARD_IA as StorageClass
    keys = {k.key: k for k in bucket.objects.all()}
    assert keys[source_key].storage_class == "STANDARD_IA"
    assert keys[dest_key].storage_class == "STANDARD"


@mock_aws
def test_copy_object_does_not_copy_acl():
    s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    bucket_name = "testbucket"
    bucket = s3_resource.Bucket(bucket_name)
    bucket.create()
    source_key = "source-key"
    dest_key = "dest-key"
    control_key = "control-key"
    # do not set ACL for the control key to get default ACL
    bucket.put_object(Key=control_key, Body=b"somedata")
    # set ACL for the source key to check if it will get copied
    bucket.put_object(Key=source_key, Body=b"somedata", ACL="public-read")
    # copy object without specifying ACL, so it should get default ACL
    client.copy_object(
        Bucket=bucket_name,
        CopySource=f"{bucket_name}/{source_key}",
        Key=dest_key,
    )

    # Get the ACL from the all the keys
    source_acl = client.get_object_acl(Bucket=bucket_name, Key=source_key)
    dest_acl = client.get_object_acl(Bucket=bucket_name, Key=dest_key)
    default_acl = client.get_object_acl(Bucket=bucket_name, Key=control_key)
    # assert that the source key ACL are different from the destination key ACL
    assert source_acl["Grants"] != dest_acl["Grants"]
    # assert that the copied key got the default ACL like the control key
    assert default_acl["Grants"] == dest_acl["Grants"]


@s3_aws_verified
@pytest.mark.aws_verified
def test_copy_object_in_place_with_metadata(bucket_name=None):
    s3_resource = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    key_name = "source-key"
    s3_resource.Object(bucket_name, key_name).put(Body=b"somedata")

    # test that giving metadata is not enough and should provide
    # MetadataDirective=REPLACE on top.
    with pytest.raises(ClientError) as exc:
        client.copy_object(
            Bucket=bucket_name,
            CopySource=f"{bucket_name}/{key_name}",
            Key=key_name,
            Metadata={"key": "value"},
        )
        assert exc.value.response["Error"]["Message"] == (
            "This copy request is illegal because it is trying to copy an "
            "object to itself without changing the object's metadata, "
            "storage class, website redirect location or encryption attributes."
        )

    # you can only provide MetadataDirective=REPLACE and it will copy without any metadata
    client.copy_object(
        Bucket=bucket_name,
        CopySource=f"{bucket_name}/{key_name}",
        Key=key_name,
        MetadataDirective="REPLACE",
    )

    result = client.head_object(Bucket=bucket_name, Key=key_name)
    assert result["Metadata"] == {}


@mock_aws
def test_copy_objet_legal_hold():
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    bucket_name = "testbucket"
    source_key = "source-key"
    dest_key = "dest-key"
    client.create_bucket(Bucket=bucket_name, ObjectLockEnabledForBucket=True)
    client.put_object(
        Bucket=bucket_name,
        Key=source_key,
        Body=b"somedata",
        ObjectLockLegalHoldStatus="ON",
        ContentMD5=generate_content_md5(b"somedata"),
    )

    head_object = client.head_object(Bucket=bucket_name, Key=source_key)
    assert head_object["ObjectLockLegalHoldStatus"] == "ON"
    assert "VersionId" in head_object
    version_id = head_object["VersionId"]

    resp = client.copy_object(
        Bucket=bucket_name,
        CopySource=f"{bucket_name}/{source_key}",
        Key=dest_key,
    )
    assert resp["CopySourceVersionId"] == version_id
    assert resp["VersionId"] != version_id

    # the destination key did not keep the legal hold from the source key
    head_object = client.head_object(Bucket=bucket_name, Key=dest_key)
    assert "ObjectLockLegalHoldStatus" not in head_object


@mock_aws
def test_s3_copy_object_lock():
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    bucket_name = "testbucket"
    source_key = "source-key"
    dest_key = "dest-key"
    client.create_bucket(Bucket=bucket_name, ObjectLockEnabledForBucket=True)
    # manipulate a bit the datetime object for an easier comparison
    retain_until = datetime.datetime.now(tz=datetime.timezone.utc) + datetime.timedelta(
        minutes=1
    )
    retain_until = retain_until.replace(microsecond=0)

    client.put_object(
        Bucket=bucket_name,
        Key=source_key,
        Body=b"test",
        ObjectLockMode="GOVERNANCE",
        ObjectLockRetainUntilDate=retain_until,
        ContentMD5=generate_content_md5(b"test"),
    )

    head_object = client.head_object(Bucket=bucket_name, Key=source_key)

    assert head_object["ObjectLockMode"] == "GOVERNANCE"
    assert head_object["ObjectLockRetainUntilDate"] == retain_until
    assert "VersionId" in head_object
    version_id = head_object["VersionId"]

    resp = client.copy_object(
        Bucket=bucket_name,
        CopySource=f"{bucket_name}/{source_key}",
        Key=dest_key,
    )
    assert resp["CopySourceVersionId"] == version_id
    assert resp["VersionId"] != version_id

    # the destination key did not keep the lock mode nor the lock until from the source key
    head_object = client.head_object(Bucket=bucket_name, Key=dest_key)
    assert "ObjectLockMode" not in head_object
    assert "ObjectLockRetainUntilDate" not in head_object


@mock_aws
def test_copy_object_in_place_website_redirect_location():
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    bucket_name = "testbucket"
    key = "source-key"
    client.create_bucket(Bucket=bucket_name)
    # This test will validate that setting WebsiteRedirectLocation
    # (even the same as source) allows a copy in place.

    client.put_object(
        Bucket=bucket_name,
        Key=key,
        Body="test",
        WebsiteRedirectLocation="/test/direct",
    )

    head_object = client.head_object(Bucket=bucket_name, Key=key)
    assert head_object["WebsiteRedirectLocation"] == "/test/direct"

    # copy the object with the same WebsiteRedirectLocation as the source object
    client.copy_object(
        Bucket=bucket_name,
        CopySource=f"{bucket_name}/{key}",
        Key=key,
        WebsiteRedirectLocation="/test/direct",
    )

    head_object = client.head_object(Bucket=bucket_name, Key=key)
    assert head_object["WebsiteRedirectLocation"] == "/test/direct"


@mock_aws
def test_copy_object_in_place_with_bucket_encryption():
    # If a bucket has encryption configured, it will allow copy in place per default
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    bucket_name = "test-bucket"
    client.create_bucket(Bucket=bucket_name)
    key = "source-key"

    response = client.put_bucket_encryption(
        Bucket=bucket_name,
        ServerSideEncryptionConfiguration={
            "Rules": [
                {
                    "ApplyServerSideEncryptionByDefault": {"SSEAlgorithm": "AES256"},
                    "BucketKeyEnabled": False,
                },
            ]
        },
    )
    assert response["ResponseMetadata"]["HTTPStatusCode"] == 200

    response = client.put_object(
        Body=b"",
        Bucket=bucket_name,
        Key=key,
    )
    assert response["ServerSideEncryption"] == "AES256"

    response = client.copy_object(
        Bucket=bucket_name,
        CopySource={"Bucket": bucket_name, "Key": key},
        Key=key,
    )
    assert response["ServerSideEncryption"] == "AES256"


@s3_aws_verified
@pytest.mark.aws_verified
def test_copy_object_in_place_with_versioning(bucket_name=None):
    # If a bucket has versioning enabled, it will allow copy in place
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    key = "source-key"

    client.put_object(Body=b"", Bucket=bucket_name, Key=key)

    enable_versioning(bucket_name, client)

    response = client.put_object(Body=b"", Bucket=bucket_name, Key=key)
    version_id = response["ResponseMetadata"]["HTTPHeaders"]["x-amz-version-id"]
    assert version_id and version_id != "null"

    response = client.copy_object(
        Bucket=bucket_name,
        CopySource={"Bucket": bucket_name, "Key": key, "VersionId": version_id},
        Key=key,
    )
    assert response["ResponseMetadata"]["HTTPStatusCode"] == 200

    response = client.copy_object(
        Bucket=bucket_name,
        CopySource={"Bucket": bucket_name, "Key": key, "VersionId": "null"},
        Key=key,
    )
    assert response["ResponseMetadata"]["HTTPStatusCode"] == 200

    response = client.list_object_versions(
        Bucket=bucket_name,
        Prefix=key,
    )
    assert len(response["Versions"]) == 4

    # Copy-In-Place does not work if no other parameters are set
    with pytest.raises(ClientError) as exc:
        client.copy_object(
            Bucket=bucket_name,
            CopySource={"Bucket": bucket_name, "Key": key},
            Key=key,
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "InvalidRequest"
    assert (
        err["Message"]
        == "This copy request is illegal because it is trying to copy an object to itself without changing the object's metadata, storage class, website redirect location or encryption attributes."
    )

    # It does work when any other property is set
    client.copy_object(
        Bucket=bucket_name,
        CopySource={"Bucket": bucket_name, "Key": key},
        Key=key,
        StorageClass="STANDARD",
    )


@mock_aws
@pytest.mark.parametrize(
    "algorithm",
    ["CRC32", "SHA1", "SHA256"],
)
def test_copy_key_with_both_sha256_checksum(algorithm):
    """Validate that moto S3 checksum calculations are correct.

    We first create an object with a Checksum calculated by boto, by
    specifying ChecksumAlgorithm="SHA256".

    We then retrieve the right checksum from this request.

    We copy the object while requesting moto to recalculate the checksum
    for that key.

    We verify that both checksums are equal.
    """
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    source_key = "source-key"
    dest_key = "dest-key"
    bucket = "foobar"
    body = b"checksum-test"
    client.create_bucket(Bucket=bucket)

    checksum_key = f"Checksum{algorithm}"

    resp = client.put_object(
        Bucket=bucket,
        Key=source_key,
        Body=body,
        ChecksumAlgorithm=algorithm,
    )
    assert checksum_key in resp
    checksum_by_boto = resp[checksum_key]

    resp = client.copy_object(
        Bucket=bucket,
        CopySource=f"{bucket}/{source_key}",
        Key=dest_key,
        ChecksumAlgorithm=algorithm,
    )

    assert checksum_key in resp["CopyObjectResult"]
    assert resp["CopyObjectResult"][checksum_key] == checksum_by_boto


@mock_aws
@pytest.mark.parametrize(
    "algorithm, checksum",
    [
        ("CRC32", "lVk/nw=="),
        ("SHA1", "jbXkHAsXUrubtL3dqDQ4w+7WXc0="),
        ("SHA256", "1YQo81vx2VFUl0q5ccWISq8AkSBQQ0WO80S82TmfdIQ="),
    ],
)
def test_copy_object_calculates_checksum(algorithm, checksum):
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    source_key = "source-key"
    dest_key = "dest-key"
    bucket = "foobar"
    body = b"test-checksum"
    client.create_bucket(Bucket=bucket)

    checksum_key = f"Checksum{algorithm}"

    client.put_object(
        Bucket=bucket,
        Key=source_key,
        Body=body,
    )

    resp = client.copy_object(
        Bucket=bucket,
        CopySource=f"{bucket}/{source_key}",
        Key=dest_key,
        ChecksumAlgorithm=algorithm,
    )

    assert checksum_key in resp["CopyObjectResult"]
    assert resp["CopyObjectResult"][checksum_key] == checksum


@mock_aws
def test_copy_object_keeps_checksum():
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    source_key = "source-key"
    dest_key = "dest-key"
    bucket = "foobar"
    body = b"test-checksum"
    expected_checksum = "1YQo81vx2VFUl0q5ccWISq8AkSBQQ0WO80S82TmfdIQ="
    client.create_bucket(Bucket=bucket)

    # put an object with a checksum
    resp = client.put_object(
        Bucket=bucket,
        Key=source_key,
        Body=body,
        ChecksumAlgorithm="SHA256",
    )
    assert "ChecksumSHA256" in resp
    assert resp["ChecksumSHA256"] == expected_checksum

    # do not specify the checksum
    resp = client.copy_object(
        Bucket=bucket,
        CopySource=f"{bucket}/{source_key}",
        Key=dest_key,
    )

    # assert that it kept the checksum from the source key
    assert "ChecksumSHA256" in resp["CopyObjectResult"]
    assert resp["CopyObjectResult"]["ChecksumSHA256"] == expected_checksum


@s3_aws_verified
@pytest.mark.aws_verified
def test_copy_source_if_none_match(bucket_name=None):
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    s3 = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)

    enable_versioning(bucket_name, client)

    obj = s3.Object(bucket_name, "orig")

    etag = obj.put(Body=b"n/a")["ETag"]

    # Exact match
    copy_from_kwargs = {
        "CopySource": {"Bucket": bucket_name, "Key": "orig"},
        "CopySourceIfNoneMatch": etag,
        "StorageClass": "STANDARD",
    }

    with pytest.raises(ClientError) as exc:
        obj.copy_from(**copy_from_kwargs)
    err = exc.value.response["Error"]
    assert err["Code"] == "PreconditionFailed"
    assert (
        err["Message"]
        == "At least one of the pre-conditions you specified did not hold"
    )
    assert err["Condition"] == "x-amz-copy-source-If-None-Match"

    r = client.list_object_versions(Bucket=bucket_name)["Versions"]
    assert len(r) == 1
    assert r[0]["ETag"] == etag

    # Match without quotes
    copy_from_kwargs = {
        "CopySource": {"Bucket": bucket_name, "Key": "orig"},
        "CopySourceIfNoneMatch": etag[1:-1],
        "StorageClass": "STANDARD",
    }

    with pytest.raises(ClientError) as exc:
        obj.copy_from(**copy_from_kwargs)
    err = exc.value.response["Error"]
    assert err["Code"] == "PreconditionFailed"
    assert (
        err["Message"]
        == "At least one of the pre-conditions you specified did not hold"
    )
    assert err["Condition"] == "x-amz-copy-source-If-None-Match"

    r = client.list_object_versions(Bucket=bucket_name)["Versions"]
    assert len(r) == 1
    assert r[0]["ETag"] == etag

    # No match - completely different etag
    copy_from_kwargs = {
        "CopySource": {"Bucket": bucket_name, "Key": "orig"},
        "CopySourceIfNoneMatch": "unknown etag",
        "StorageClass": "STANDARD",
    }

    obj.copy_from(**copy_from_kwargs)

    r = client.list_object_versions(Bucket=bucket_name)["Versions"]
    assert len(r) == 2
    assert r[0]["ETag"] == r[1]["ETag"] == etag
    assert r[0]["VersionId"] != r[1]["VersionId"]