File: test_server.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 (472 lines) | stat: -rw-r--r-- 17,300 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
import io
from unittest.mock import patch
from urllib.parse import parse_qs, urlparse

import pytest
import requests
import xmltodict
from flask.testing import FlaskClient

import moto.server as server
from moto.moto_server.threaded_moto_server import ThreadedMotoServer


class AuthenticatedClient(FlaskClient):
    def open(self, *args, **kwargs):
        kwargs["headers"] = kwargs.get("headers", {})
        kwargs["headers"]["Authorization"] = "Any authorization header"
        kwargs["content_length"] = 0  # Fixes content-length complaints.
        return super().open(*args, **kwargs)


def authenticated_client():
    backend = server.create_backend_app("s3")
    backend.test_client_class = AuthenticatedClient
    return backend.test_client()


def test_s3_server_get():
    test_client = authenticated_client()
    res = test_client.get("/")

    assert b"ListAllMyBucketsResult" in res.data


@pytest.mark.parametrize("key_name", ["bar_baz", "bar+baz", "baz bar"])
def test_s3_server_bucket_create(key_name):
    test_client = authenticated_client()

    res = test_client.put("/", "http://foobaz.localhost:5000/")
    assert res.status_code == 200

    res = test_client.get("/")
    assert b"<Name>foobaz</Name>" in res.data

    res = test_client.get("/", "http://foobaz.localhost:5000/")
    assert res.status_code == 200
    assert b"ListBucketResult" in res.data

    res = test_client.put(
        f"/{key_name}", "http://foobaz.localhost:5000/", data="test value"
    )
    assert res.status_code == 200
    assert "ETag" in dict(res.headers)

    # ListObjects
    res = test_client.get(
        "/", "http://foobaz.localhost:5000/", query_string={"prefix": key_name}
    )
    assert res.status_code == 200
    content = xmltodict.parse(res.data)["ListBucketResult"]["Contents"]
    # If we receive a dict, we only received one result
    # If content is of type list, our call returned multiple results - which is not correct
    assert isinstance(content, dict)
    assert content["Key"] == key_name

    # ListObjects V2
    res = test_client.get(
        "/",
        "http://foobaz.localhost:5000/",
        query_string={"prefix": key_name, "list-type": "2"},
    )
    assert res.status_code == 200
    content = xmltodict.parse(res.data)["ListBucketResult"]["Contents"]
    assert isinstance(content, dict)
    assert content["Key"] == key_name

    # ListObjectsVersions
    res = test_client.get(
        "/",
        "http://foobaz.localhost:5000/",
        query_string={"prefix": key_name, "versions": ""},
    )
    assert res.status_code == 200
    assert xmltodict.parse(res.data)["ListVersionsResult"]["Prefix"] == key_name
    content = xmltodict.parse(res.data)["ListVersionsResult"]["Version"]
    assert isinstance(content, dict)
    assert content["Key"] == key_name

    # GetBucket
    res = test_client.head("http://foobaz.localhost:5000")
    assert res.status_code == 200
    assert res.headers.get("x-amz-bucket-region") == "us-east-1"

    # HeadObject
    res = test_client.head(f"/{key_name}", "http://foobaz.localhost:5000/")
    assert res.status_code == 200
    assert res.headers.get("Accept-Ranges") == "bytes"

    # GetObject
    res = test_client.get(f"/{key_name}", "http://foobaz.localhost:5000/")
    assert res.status_code == 200
    assert res.data == b"test value"
    assert res.headers.get("Accept-Ranges") == "bytes"


def test_s3_server_ignore_subdomain_for_bucketnames():
    with patch("moto.settings.S3_IGNORE_SUBDOMAIN_BUCKETNAME", True):
        test_client = authenticated_client()

        res = test_client.put("/mybucket", "http://foobaz.localhost:5000/")
        assert res.status_code == 200
        assert b"mybucket" in res.data


def test_s3_server_bucket_versioning():
    test_client = authenticated_client()

    res = test_client.put("/", "http://foobaz.localhost:5000/")
    assert res.status_code == 200

    # Just enough XML to enable versioning
    body = "<Status>Enabled</Status>"
    res = test_client.put("/?versioning", "http://foobaz.localhost:5000", data=body)
    assert res.status_code == 200


def test_s3_server_post_to_bucket():
    test_client = authenticated_client()

    res = test_client.put("/", "http://tester.localhost:5000/")
    assert res.status_code == 200

    test_client.post(
        "/",
        "https://tester.localhost:5000/",
        data={"key": "the-key", "file": "nothing"},
    )

    res = test_client.get("/the-key", "http://tester.localhost:5000/")
    assert res.status_code == 200
    assert res.data == b"nothing"


def test_s3_server_post_to_bucket_redirect():
    test_client = authenticated_client()

    res = test_client.put("/", "http://tester.localhost:5000/")
    assert res.status_code == 200

    redirect_base = "https://redirect.com/success/"
    filecontent = "nothing"
    filename = "test_filename.txt"
    res = test_client.post(
        "/",
        "https://tester.localhost:5000/",
        data={
            "key": "asdf/the-key/${filename}",
            "file": (io.BytesIO(filecontent.encode("utf8")), filename),
            "success_action_redirect": redirect_base,
        },
    )
    real_key = f"asdf/the-key/{filename}"
    assert res.status_code == 303
    redirect = res.headers["location"]
    assert redirect.startswith(redirect_base)

    parts = urlparse(redirect)
    args = parse_qs(parts.query)
    assert args["key"][0] == real_key
    assert args["bucket"][0] == "tester"

    res = test_client.get(f"/{real_key}", "http://tester.localhost:5000/")
    assert res.status_code == 200
    assert res.data == filecontent.encode("utf8")


def test_s3_server_post_without_content_length():
    test_client = authenticated_client()

    # You can create a bucket without specifying Content-Length
    res = test_client.put(
        "/", "http://tester.localhost:5000/", environ_overrides={"CONTENT_LENGTH": ""}
    )
    assert res.status_code == 200

    # You can specify a bucket in another region without specifying Content-Length
    # (The body is just ignored..)
    res = test_client.put(
        "/",
        "http://tester.localhost:5000/",
        environ_overrides={"CONTENT_LENGTH": ""},
        data=(
            "<CreateBucketConfiguration>"
            "<LocationConstraint>us-west-2</LocationConstraint>"
            "</CreateBucketConfiguration>"
        ),
    )
    assert res.status_code == 200

    # You cannot make any other bucket-related requests without specifying Content-Length
    for path in ["/?versioning", "/?policy"]:
        res = test_client.put(
            path, "http://t.localhost:5000", environ_overrides={"CONTENT_LENGTH": ""}
        )
        assert res.status_code == 411

    # You cannot make any POST-request
    res = test_client.post(
        "/", "https://tester.localhost:5000/", environ_overrides={"CONTENT_LENGTH": ""}
    )
    assert res.status_code == 411


def test_s3_server_post_unicode_bucket_key():
    """Verify non-ascii characters in request URLs (e.g., S3 object names)."""
    dispatcher = server.DomainDispatcherApplication(server.create_backend_app)
    backend_app = dispatcher.get_application(
        {
            "HTTP_HOST": "s3.amazonaws.com",
            "PATH_INFO": "/test-bucket/test-object-てすと",
        }
    )
    assert backend_app
    backend_app = dispatcher.get_application(
        {
            "HTTP_HOST": "s3.amazonaws.com",
            "PATH_INFO": "/test-bucket/test-object-てすと".encode(),
        }
    )
    assert backend_app


def test_s3_server_post_cors():
    """Test default CORS headers set by flask-cors plugin"""
    test_client = authenticated_client()
    # Create the bucket
    test_client.put("/", "http://tester.localhost:5000/")

    preflight_headers = {
        "Access-Control-Request-Method": "POST",
        "Access-Control-Request-Headers": "origin, x-requested-with",
        "Origin": "https://localhost:9000",
    }

    res = test_client.options(
        "/", "http://tester.localhost:5000/", headers=preflight_headers
    )
    assert res.status_code in [200, 204]

    expected_methods = {"DELETE", "PATCH", "PUT", "GET", "HEAD", "POST", "OPTIONS"}
    assert (
        set(res.headers["Access-Control-Allow-Methods"].split(", ")) == expected_methods
    )

    assert res.headers["Access-Control-Allow-Origin"] == "https://localhost:9000"
    assert res.headers["Access-Control-Allow-Headers"] == "origin, x-requested-with"


def test_s3_no_default_cors():
    """Test default CORS headers are not set if MOTO_DISABLE_GLOBAL_CORS is true"""
    for disable_cors in [True, False]:
        with patch("moto.moto_server.werkzeug_app.DISABLE_GLOBAL_CORS", disable_cors):
            test_client = authenticated_client()

            # Create a bucket and a file
            test_client.put("/", "http://nodefaultcors.localhost:5000/")
            test_client.put("/test", "http://nodefaultcors.localhost:5000/")
            test_client.put("/", "http://tester.localhost:5000/")

            resp = test_client.get(
                "/test",
                "http://nodefaultcors.localhost:5000/",
                headers={"Origin": "example.com"},
            )
            assert ("Access-Control-Allow-Origin" not in resp.headers) == disable_cors


def test_s3_server_post_cors_exposed_header():
    """Test overriding default CORS headers with custom bucket rules"""
    # github.com/getmoto/moto/issues/4220

    cors_config_payload = """<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
  <CORSRule>
    <AllowedOrigin>https://example.org</AllowedOrigin>
    <AllowedMethod>HEAD</AllowedMethod>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
    <ExposeHeader>ETag</ExposeHeader>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
  </CORSRule>
</CORSConfiguration>
    """

    test_client = authenticated_client()
    valid_origin = "https://example.org"
    preflight_headers = {
        "Access-Control-Request-Method": "POST",
        "Access-Control-Request-Headers": "origin, x-requested-with",
        "Origin": valid_origin,
    }
    # Returns 403 on non existing bucket
    preflight_response = test_client.options(
        "/", "http://testcors.localhost:5000/", headers=preflight_headers
    )
    assert preflight_response.status_code == 403

    # Create the bucket & file
    test_client.put("/", "http://testcors.localhost:5000/")
    test_client.put("/test", "http://testcors.localhost:5000/")
    res = test_client.put(
        "/?cors", "http://testcors.localhost:5000", data=cors_config_payload
    )
    assert res.status_code == 200

    cors_res = test_client.get("/?cors", "http://testcors.localhost:5000")
    assert b"<ExposeHeader>ETag</ExposeHeader>" in cors_res.data

    # Test OPTIONS bucket response and key response
    for key_name in ("/", "/test"):
        preflight_response = test_client.options(
            key_name, "http://testcors.localhost:5000/", headers=preflight_headers
        )
        assert preflight_response.status_code == 200
        expected_cors_headers = {
            "Access-Control-Allow-Methods": "HEAD, GET, PUT, POST, DELETE",
            "Access-Control-Allow-Origin": "https://example.org",
            "Access-Control-Allow-Headers": "*",
            "Access-Control-Expose-Headers": "ETag",
            "Access-Control-Max-Age": "3000",
        }
        for header_name, header_value in expected_cors_headers.items():
            assert header_name in preflight_response.headers
            assert preflight_response.headers[header_name] == header_value

    # Test GET key response
    # A regular GET should not receive any CORS headers
    resp = test_client.get("/test", "http://testcors.localhost:5000/")
    assert "Access-Control-Allow-Methods" not in resp.headers
    assert "Access-Control-Expose-Headers" not in resp.headers

    # A GET with mismatched Origin-header should not receive any CORS headers
    resp = test_client.get(
        "/test", "http://testcors.localhost:5000/", headers={"Origin": "something.com"}
    )
    assert "Access-Control-Allow-Methods" not in resp.headers
    assert "Access-Control-Expose-Headers" not in resp.headers

    # Only a GET with matching Origin-header should receive CORS headers
    resp = test_client.get(
        "/test", "http://testcors.localhost:5000/", headers={"Origin": valid_origin}
    )
    assert (
        resp.headers["Access-Control-Allow-Methods"] == "HEAD, GET, PUT, POST, DELETE"
    )
    assert resp.headers["Access-Control-Expose-Headers"] == "ETag"

    # Test PUT key response
    # A regular PUT should not receive any CORS headers
    resp = test_client.put("/test", "http://testcors.localhost:5000/")
    assert "Access-Control-Allow-Methods" not in resp.headers
    assert "Access-Control-Expose-Headers" not in resp.headers

    # A PUT with mismatched Origin-header should not receive any CORS headers
    resp = test_client.put(
        "/test", "http://testcors.localhost:5000/", headers={"Origin": "something.com"}
    )
    assert "Access-Control-Allow-Methods" not in resp.headers
    assert "Access-Control-Expose-Headers" not in resp.headers

    # Only a PUT with matching Origin-header should receive CORS headers
    resp = test_client.put(
        "/test", "http://testcors.localhost:5000/", headers={"Origin": valid_origin}
    )
    assert (
        resp.headers["Access-Control-Allow-Methods"] == "HEAD, GET, PUT, POST, DELETE"
    )
    assert resp.headers["Access-Control-Expose-Headers"] == "ETag"


def test_s3_server_post_cors_multiple_origins():
    """Test that Moto only responds with the Origin that we that hosts the server"""
    # github.com/getmoto/moto/issues/6003

    cors_config_payload = """<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
  <CORSRule>
    <AllowedOrigin>https://example.org</AllowedOrigin>
    <AllowedOrigin>https://localhost:6789</AllowedOrigin>
    <AllowedMethod>POST</AllowedMethod>
  </CORSRule>
</CORSConfiguration>
    """

    thread = ThreadedMotoServer(port="6789", verbose=False)
    thread.start()

    # Create the bucket
    requests.put("http://testcors.localhost:6789/")
    requests.put("http://testcors.localhost:6789/?cors", data=cors_config_payload)

    # Test only our requested origin is returned
    preflight_response = requests.options(
        "http://testcors.localhost:6789/test2",
        headers={
            "Access-Control-Request-Method": "POST",
            "Origin": "https://localhost:6789",
        },
    )
    assert preflight_response.status_code == 200
    assert (
        preflight_response.headers["Access-Control-Allow-Origin"]
        == "https://localhost:6789"
    )
    assert preflight_response.content == b""

    # Verify a request with unknown origin fails
    preflight_response = requests.options(
        "http://testcors.localhost:6789/test2",
        headers={
            "Access-Control-Request-Method": "POST",
            "Origin": "https://unknown.host",
        },
    )
    assert preflight_response.status_code == 403
    assert b"<Code>AccessForbidden</Code>" in preflight_response.content

    # Verify we can use a wildcard anywhere in the origin
    cors_config_payload = (
        '<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><CORSRule>'
        "<AllowedOrigin>https://*.google.com</AllowedOrigin>"
        "<AllowedMethod>POST</AllowedMethod>"
        "</CORSRule></CORSConfiguration>"
    )
    requests.put("http://testcors.localhost:6789/?cors", data=cors_config_payload)
    for origin in ["https://sth.google.com", "https://a.google.com"]:
        preflight_response = requests.options(
            "http://testcors.localhost:6789/test2",
            headers={"Access-Control-Request-Method": "POST", "Origin": origin},
        )
        assert preflight_response.status_code == 200
        assert preflight_response.headers["Access-Control-Allow-Origin"] == origin

    # Non-matching requests throw an error though - it does not act as a full wildcard
    preflight_response = requests.options(
        "http://testcors.localhost:6789/test2",
        headers={
            "Access-Control-Request-Method": "POST",
            "Origin": "sth.microsoft.com",
        },
    )
    assert preflight_response.status_code == 403
    assert b"<Code>AccessForbidden</Code>" in preflight_response.content

    # Verify we can use a wildcard as the origin
    cors_config_payload = (
        '<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><CORSRule>'
        "<AllowedOrigin>*</AllowedOrigin>"
        "<AllowedMethod>POST</AllowedMethod>"
        "</CORSRule></CORSConfiguration>"
    )
    requests.put("http://testcors.localhost:6789/?cors", data=cors_config_payload)
    for origin in ["https://a.google.com", "http://b.microsoft.com", "any"]:
        preflight_response = requests.options(
            "http://testcors.localhost:6789/test2",
            headers={"Access-Control-Request-Method": "POST", "Origin": origin},
        )
        assert preflight_response.status_code == 200
        assert preflight_response.headers["Access-Control-Allow-Origin"] == origin

    thread.stop()