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
|
# Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import datetime
import pytest
from dateutil.tz import tzutc
import botocore.session
from botocore.auth import S3ExpressAuth
from botocore.awsrequest import AWSRequest
from botocore.credentials import Credentials, RefreshableCredentials
from botocore.utils import S3ExpressIdentityCache
from tests import ClientHTTPStubber, mock
ACCESS_KEY = "AKIDEXAMPLE"
SECRET_KEY = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"
TOKEN = "TOKEN"
EXPRESS_ACCESS_KEY = "EXPRESS_AKIDEXAMPLE"
EXPRESS_SECRET_KEY = "EXPRESS_53cr37"
EXPRESS_TOKEN = "EXPRESS_TOKEN"
CREDENTIALS = Credentials(ACCESS_KEY, SECRET_KEY, TOKEN)
ENDPOINT = "https://s3.us-west-2.amazonaws.com"
S3EXPRESS_BUCKET = "mytestbucket--usw2-az5--x-s3"
DATE = datetime.datetime(2023, 11, 26, 0, 0, 0, tzinfo=tzutc())
CREATE_SESSION_RESPONSE = (
b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
b"<CreateSessionResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">"
b"<Credentials><SessionToken>EXPRESS_TOKEN</SessionToken>"
b"<SecretAccessKey>EXPRESS_53cr37</SecretAccessKey>"
b"<AccessKeyId>EXPRESS_AKIDEXAMPLE</AccessKeyId>"
b"<Expiration>2023-11-28T01:46:39Z</Expiration>"
b"</Credentials></CreateSessionResult>"
)
@pytest.fixture
def default_s3_client():
session = botocore.session.Session()
return session.create_client(
's3',
'us-west-2',
aws_access_key_id=ACCESS_KEY,
aws_secret_access_key=SECRET_KEY,
aws_session_token=TOKEN,
)
@pytest.fixture
def mock_datetime():
with mock.patch('datetime.datetime', spec=True) as mock_datetime:
yield mock_datetime
def _assert_expected_create_session_call(request, bucket):
assert bucket in request.url
assert request.url.endswith('?session')
assert request.method == "GET"
class TestS3ExpressAuth:
def _assert_has_expected_headers(self, request, header_list=None):
if header_list is None:
header_list = ["Authorization", "X-Amz-S3Session-Token"]
for header in header_list:
assert header in request.headers
def test_s3express_auth_requires_instance_cache(self):
assert hasattr(S3ExpressAuth, "REQUIRES_IDENTITY_CACHE")
assert S3ExpressAuth.REQUIRES_IDENTITY_CACHE is True
def test_s3_express_auth_headers(self):
request = AWSRequest(
method='GET',
url=ENDPOINT,
)
auth_instance = S3ExpressAuth(
CREDENTIALS, "s3", "us-west-2", identity_cache={}
)
# Confirm there is no existing auth info on request
assert 'Authorization' not in request.headers
auth_instance.add_auth(request)
self._assert_has_expected_headers(request)
# Confirm we're not including the unsupported X-Amz-Security-Token
# header for S3Express.
assert 'X-Amz-Security-Token' not in request.headers
class TestS3ExpressIdentityCache:
def test_default_s3_express_cache(self, default_s3_client, mock_datetime):
mock_datetime.now.return_value = DATE
identity_cache = S3ExpressIdentityCache(
default_s3_client,
RefreshableCredentials,
)
with ClientHTTPStubber(default_s3_client) as stubber:
stubber.add_response(body=CREATE_SESSION_RESPONSE)
credentials = identity_cache.get_credentials('my_bucket')
assert credentials.access_key == EXPRESS_ACCESS_KEY
assert credentials.secret_key == EXPRESS_SECRET_KEY
assert credentials.token == EXPRESS_TOKEN
def test_s3_express_cache_one_network_call(
self, default_s3_client, mock_datetime
):
mock_datetime.now.return_value = DATE
bucket = 'my_bucket'
identity_cache = S3ExpressIdentityCache(
default_s3_client,
RefreshableCredentials,
)
with ClientHTTPStubber(default_s3_client) as stubber:
# Only set one response
stubber.add_response(body=CREATE_SESSION_RESPONSE)
first_creds = identity_cache.get_credentials(bucket)
second_creds = identity_cache.get_credentials(bucket)
# Confirm we got back the same credentials
assert first_creds == second_creds
# Confirm we didn't hit the API twice
assert len(stubber.requests) == 1
_assert_expected_create_session_call(stubber.requests[0], bucket)
def test_s3_express_cache_multiple_buckets(
self, default_s3_client, mock_datetime
):
mock_datetime.now.return_value = DATE
bucket = 'my_bucket'
other_bucket = 'other_bucket'
identity_cache = S3ExpressIdentityCache(
default_s3_client,
RefreshableCredentials,
)
with ClientHTTPStubber(default_s3_client) as stubber:
stubber.add_response(body=CREATE_SESSION_RESPONSE)
stubber.add_response(body=CREATE_SESSION_RESPONSE)
identity_cache.get_credentials(bucket)
identity_cache.get_credentials(other_bucket)
# Confirm we hit the API for each bucket
assert len(stubber.requests) == 2
_assert_expected_create_session_call(stubber.requests[0], bucket)
_assert_expected_create_session_call(
stubber.requests[1], other_bucket
)
class TestS3ExpressRequests:
def _assert_standard_sigv4_signature(self, headers):
sigv4_auth_preamble = (
b'AWS4-HMAC-SHA256 Credential='
b'AKIDEXAMPLE/20231126/us-west-2/s3express/aws4_request'
)
assert 'Authorization' in headers
assert headers['Authorization'].startswith(sigv4_auth_preamble)
def _assert_s3express_credentials(self, headers):
s3express_auth_preamble = (
b'AWS4-HMAC-SHA256 Credential='
b'EXPRESS_AKIDEXAMPLE/20231126/us-west-2/s3express/aws4_request'
)
assert 'Authorization' in headers
assert 'x-amz-s3session-token' in headers
assert headers['Authorization'].startswith(s3express_auth_preamble)
assert headers['x-amz-s3session-token'] == b'EXPRESS_TOKEN'
def _assert_checksum_algorithm_added(self, algorithm, headers):
algorithm_header_name = f"x-amz-checksum-{algorithm}"
assert algorithm_header_name in headers
def _call_get_object(self, client):
return client.get_object(
Bucket=S3EXPRESS_BUCKET,
Key='my-test-object',
)
def test_create_bucket(self, default_s3_client, mock_datetime):
mock_datetime.now.return_value = DATE
with ClientHTTPStubber(default_s3_client) as stubber:
stubber.add_response()
default_s3_client.create_bucket(
Bucket=S3EXPRESS_BUCKET,
CreateBucketConfiguration={
'Location': {
'Name': 'usw2-az5',
'Type': 'AvailabilityZone',
},
'Bucket': {
"DataRedundancy": "SingleAvailabilityZone",
"Type": "Directory",
},
},
)
# Confirm we don't call CreateSession for create_bucket
assert len(stubber.requests) == 1
self._assert_standard_sigv4_signature(stubber.requests[0].headers)
def test_get_object(self, default_s3_client, mock_datetime):
mock_datetime.now.return_value = DATE
with ClientHTTPStubber(default_s3_client) as stubber:
stubber.add_response(body=CREATE_SESSION_RESPONSE)
stubber.add_response()
self._call_get_object(default_s3_client)
# Confirm we called CreateSession for create_bucket
assert len(stubber.requests) == 2
_assert_expected_create_session_call(
stubber.requests[0], S3EXPRESS_BUCKET
)
self._assert_standard_sigv4_signature(stubber.requests[0].headers)
# Confirm actual PutObject request was signed with Session credentials
self._assert_s3express_credentials(stubber.requests[1].headers)
def test_cache_with_multiple_requests(
self, default_s3_client, mock_datetime
):
mock_datetime.now.return_value = DATE
with ClientHTTPStubber(default_s3_client) as stubber:
stubber.add_response(body=CREATE_SESSION_RESPONSE)
stubber.add_response()
stubber.add_response()
self._call_get_object(default_s3_client)
self._call_get_object(default_s3_client)
# Confirm we called CreateSession for create_bucket once
assert len(stubber.requests) == 3
_assert_expected_create_session_call(
stubber.requests[0], S3EXPRESS_BUCKET
)
self._assert_standard_sigv4_signature(stubber.requests[0].headers)
# Confirm we signed both called with S3Express credentials
self._assert_s3express_credentials(stubber.requests[1].headers)
self._assert_s3express_credentials(stubber.requests[2].headers)
def test_delete_objects_injects_correct_checksum(
self, default_s3_client, mock_datetime
):
mock_datetime.now.return_value = DATE
with ClientHTTPStubber(default_s3_client) as stubber:
stubber.add_response(body=CREATE_SESSION_RESPONSE)
stubber.add_response()
default_s3_client.delete_objects(
Bucket=S3EXPRESS_BUCKET,
Delete={
"Objects": [
{
"Key": "my-obj",
"VersionId": "1",
}
]
},
)
# Confirm we called CreateSession for create_bucket
assert len(stubber.requests) == 2
_assert_expected_create_session_call(
stubber.requests[0], S3EXPRESS_BUCKET
)
self._assert_standard_sigv4_signature(stubber.requests[0].headers)
# Confirm we signed both called with S3Express credentials
self._assert_s3express_credentials(stubber.requests[1].headers)
self._assert_checksum_algorithm_added(
'crc32', stubber.requests[1].headers
)
|