| 1 |
""" |
| 2 |
AWS client-side authentication: standard credentials providers and signing. |
| 3 |
""" |
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
import _awscrt |
| 9 |
from awscrt import NativeResource |
| 10 |
import awscrt.exceptions |
| 11 |
from awscrt.http import HttpRequest, HttpProxyOptions |
| 12 |
from awscrt.io import ClientBootstrap, ClientTlsContext |
| 13 |
from concurrent.futures import Future |
| 14 |
import datetime |
| 15 |
from enum import IntEnum |
| 16 |
from typing import Optional, Sequence, Tuple |
| 17 |
|
| 18 |
|
| 19 |
class AwsCredentials(NativeResource): |
| 20 |
""" |
| 21 |
AwsCredentials are the public/private data needed to sign an authenticated AWS request. |
| 22 |
|
| 23 |
AwsCredentials are immutable. |
| 24 |
|
| 25 |
Args: |
| 26 |
access_key_id (str): Access key ID |
| 27 |
secret_access_key (str): Secret access key |
| 28 |
session_token (Optional[str]): Optional security token associated with |
| 29 |
the credentials. |
| 30 |
expiration (Optional[datetime.datetime]): Optional expiration datetime, |
| 31 |
that the credentials will no longer be valid past. |
| 32 |
Converted to UTC timezone and rounded down to nearest second. |
| 33 |
If not set, then credentials do not expire. |
| 34 |
|
| 35 |
Attributes: |
| 36 |
access_key_id (str): Access key ID |
| 37 |
secret_access_key (str): Secret access key |
| 38 |
session_token (Optional[str]): Security token associated with |
| 39 |
the credentials. None if not set. |
| 40 |
expiration (Optional[datetime.datetime]): Expiration datetime, |
| 41 |
that the credentials will no longer be valid past. |
| 42 |
None if credentials do not expire. |
| 43 |
Timezone is always UTC. |
| 44 |
""" |
| 45 |
__slots__ = () |
| 46 |
|
| 47 |
|
| 48 |
_NONEXPIRING_TIMESTAMP = 0xFFFFFFFFFFFFFFFF |
| 49 |
|
| 50 |
def __init__(self, access_key_id, secret_access_key, session_token=None, expiration=None): |
| 51 |
assert isinstance(access_key_id, str) |
| 52 |
assert isinstance(secret_access_key, str) |
| 53 |
assert isinstance(session_token, str) or session_token is None |
| 54 |
|
| 55 |
|
| 56 |
if expiration is None: |
| 57 |
expiration_timestamp = self._NONEXPIRING_TIMESTAMP |
| 58 |
else: |
| 59 |
expiration_timestamp = int(expiration.timestamp()) |
| 60 |
if expiration_timestamp < 0 or expiration_timestamp >= self._NONEXPIRING_TIMESTAMP: |
| 61 |
raise OverflowError("expiration datetime out of range") |
| 62 |
|
| 63 |
super().__init__() |
| 64 |
self._binding = _awscrt.credentials_new( |
| 65 |
access_key_id, |
| 66 |
secret_access_key, |
| 67 |
session_token, |
| 68 |
expiration_timestamp) |
| 69 |
|
| 70 |
@classmethod |
| 71 |
def _from_binding(cls, binding): |
| 72 |
"""Construct from a pre-existing native object""" |
| 73 |
credentials = cls.__new__(cls) |
| 74 |
super(cls, credentials).__init__() |
| 75 |
credentials._binding = binding |
| 76 |
return credentials |
| 77 |
|
| 78 |
@property |
| 79 |
def access_key_id(self): |
| 80 |
return _awscrt.credentials_access_key_id(self._binding) |
| 81 |
|
| 82 |
@property |
| 83 |
def secret_access_key(self): |
| 84 |
return _awscrt.credentials_secret_access_key(self._binding) |
| 85 |
|
| 86 |
@property |
| 87 |
def session_token(self): |
| 88 |
return _awscrt.credentials_session_token(self._binding) |
| 89 |
|
| 90 |
@property |
| 91 |
def expiration(self): |
| 92 |
timestamp = _awscrt.credentials_expiration_timestamp_seconds(self._binding) |
| 93 |
|
| 94 |
if timestamp == self._NONEXPIRING_TIMESTAMP: |
| 95 |
return None |
| 96 |
else: |
| 97 |
return datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc) |
| 98 |
|
| 99 |
def __deepcopy__(self, memo): |
| 100 |
|
| 101 |
return self |
| 102 |
|
| 103 |
|
| 104 |
class AwsCredentialsProviderBase(NativeResource): |
| 105 |
|
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
|
| 111 |
|
| 112 |
pass |
| 113 |
|
| 114 |
|
| 115 |
class AwsCredentialsProvider(AwsCredentialsProviderBase): |
| 116 |
""" |
| 117 |
Credentials providers source the AwsCredentials needed to sign an authenticated AWS request. |
| 118 |
|
| 119 |
This class provides `new_X()` functions for several built-in provider types. |
| 120 |
To define a custom provider, use the :meth:`new_delegate()` function. |
| 121 |
""" |
| 122 |
__slots__ = () |
| 123 |
|
| 124 |
def __init__(self, binding): |
| 125 |
super().__init__() |
| 126 |
self._binding = binding |
| 127 |
|
| 128 |
@classmethod |
| 129 |
def new_default_chain(cls, client_bootstrap=None): |
| 130 |
""" |
| 131 |
Create the default provider chain used by most AWS SDKs. |
| 132 |
|
| 133 |
Generally: |
| 134 |
|
| 135 |
1. Environment |
| 136 |
2. Profile |
| 137 |
3. (conditional, off by default) ECS |
| 138 |
4. (conditional, on by default) EC2 Instance Metadata |
| 139 |
|
| 140 |
Args: |
| 141 |
client_bootstrap (Optional[ClientBootstrap]): Client bootstrap to use when initiating socket connection. |
| 142 |
If not set, uses the default static ClientBootstrap instead. |
| 143 |
|
| 144 |
Returns: |
| 145 |
AwsCredentialsProvider: |
| 146 |
""" |
| 147 |
assert isinstance(client_bootstrap, ClientBootstrap) or client_bootstrap is None |
| 148 |
|
| 149 |
if client_bootstrap is None: |
| 150 |
client_bootstrap = ClientBootstrap.get_or_create_static_default() |
| 151 |
|
| 152 |
binding = _awscrt.credentials_provider_new_chain_default(client_bootstrap) |
| 153 |
return cls(binding) |
| 154 |
|
| 155 |
@classmethod |
| 156 |
def new_static(cls, access_key_id, secret_access_key, session_token=None): |
| 157 |
""" |
| 158 |
Create a simple provider that just returns a fixed set of credentials. |
| 159 |
|
| 160 |
Args: |
| 161 |
access_key_id (str): Access key ID |
| 162 |
secret_access_key (str): Secret access key |
| 163 |
session_token (Optional[str]): Optional session token |
| 164 |
|
| 165 |
Returns: |
| 166 |
AwsCredentialsProvider: |
| 167 |
""" |
| 168 |
assert isinstance(access_key_id, str) |
| 169 |
assert isinstance(secret_access_key, str) |
| 170 |
assert isinstance(session_token, str) or session_token is None |
| 171 |
|
| 172 |
binding = _awscrt.credentials_provider_new_static(access_key_id, secret_access_key, session_token) |
| 173 |
return cls(binding) |
| 174 |
|
| 175 |
@classmethod |
| 176 |
def new_profile( |
| 177 |
cls, |
| 178 |
client_bootstrap=None, |
| 179 |
profile_name=None, |
| 180 |
config_filepath=None, |
| 181 |
credentials_filepath=None): |
| 182 |
""" |
| 183 |
Creates a provider that sources credentials from key-value profiles |
| 184 |
loaded from the aws credentials file. |
| 185 |
|
| 186 |
Args: |
| 187 |
client_bootstrap (Optional[ClientBootstrap]): Client bootstrap to use when initiating socket connection. |
| 188 |
If not set, uses the static default ClientBootstrap instead. |
| 189 |
|
| 190 |
profile_name (Optional[str]): Name of profile to use. |
| 191 |
If not set, uses value from AWS_PROFILE environment variable. |
| 192 |
If that is not set, uses value of "default" |
| 193 |
|
| 194 |
config_filepath (Optional[str]): Path to profile config file. |
| 195 |
If not set, uses value from AWS_CONFIG_FILE environment variable. |
| 196 |
If that is not set, uses value of "~/.aws/config" |
| 197 |
|
| 198 |
credentials_filepath (Optional[str]): Path to profile credentials file. |
| 199 |
If not set, uses value from AWS_SHARED_CREDENTIALS_FILE environment variable. |
| 200 |
If that is not set, uses value of "~/.aws/credentials" |
| 201 |
|
| 202 |
Returns: |
| 203 |
AwsCredentialsProvider: |
| 204 |
""" |
| 205 |
assert isinstance(client_bootstrap, ClientBootstrap) or client_bootstrap is None |
| 206 |
assert isinstance(profile_name, str) or profile_name is None |
| 207 |
assert isinstance(config_filepath, str) or config_filepath is None |
| 208 |
assert isinstance(credentials_filepath, str) or credentials_filepath is None |
| 209 |
|
| 210 |
if client_bootstrap is None: |
| 211 |
client_bootstrap = ClientBootstrap.get_or_create_static_default() |
| 212 |
|
| 213 |
binding = _awscrt.credentials_provider_new_profile( |
| 214 |
client_bootstrap, profile_name, config_filepath, credentials_filepath) |
| 215 |
return cls(binding) |
| 216 |
|
| 217 |
@classmethod |
| 218 |
def new_process(cls, profile_to_use=None): |
| 219 |
""" |
| 220 |
Creates a provider that sources credentials from running an external command or process. |
| 221 |
|
| 222 |
The command to run is sourced from a profile in the AWS config file, using the standard |
| 223 |
profile selection rules. The profile key the command is read from is "credential_process." |
| 224 |
Example:: |
| 225 |
|
| 226 |
[default] |
| 227 |
credential_process=/opt/amazon/bin/my-credential-fetcher --argsA=abc |
| 228 |
|
| 229 |
On successfully running the command, the output should be a json data with the following |
| 230 |
format:: |
| 231 |
|
| 232 |
{ |
| 233 |
"Version": 1, |
| 234 |
"AccessKeyId": "accesskey", |
| 235 |
"SecretAccessKey": "secretAccessKey" |
| 236 |
"SessionToken": "....", |
| 237 |
"Expiration": "2019-05-29T00:21:43Z" |
| 238 |
} |
| 239 |
|
| 240 |
Version here identifies the command output format version. |
| 241 |
This provider is not part of the default provider chain. |
| 242 |
|
| 243 |
Args: |
| 244 |
profile_to_use (Optional[str]): Name of profile in which to look for credential_process. |
| 245 |
If not set, uses value from AWS_PROFILE environment variable. |
| 246 |
If that is not set, uses value of "default" |
| 247 |
|
| 248 |
Returns: |
| 249 |
AwsCredentialsProvider: |
| 250 |
""" |
| 251 |
|
| 252 |
binding = _awscrt.credentials_provider_new_process(profile_to_use) |
| 253 |
return cls(binding) |
| 254 |
|
| 255 |
@classmethod |
| 256 |
def new_environment(cls): |
| 257 |
""" |
| 258 |
Creates a provider that returns credentials sourced from environment variables. |
| 259 |
|
| 260 |
* AWS_ACCESS_KEY_ID |
| 261 |
* AWS_SECRET_ACCESS_KEY |
| 262 |
* AWS_SESSION_TOKEN |
| 263 |
|
| 264 |
Returns: |
| 265 |
AwsCredentialsProvider: |
| 266 |
""" |
| 267 |
|
| 268 |
binding = _awscrt.credentials_provider_new_environment() |
| 269 |
return cls(binding) |
| 270 |
|
| 271 |
@classmethod |
| 272 |
def new_chain(cls, providers): |
| 273 |
""" |
| 274 |
Creates a provider that sources credentials from an ordered sequence of providers. |
| 275 |
|
| 276 |
This provider uses the first set of credentials successfully queried. |
| 277 |
Providers are queried one at a time; a provider is not queried until the |
| 278 |
preceding provider has failed to source credentials. |
| 279 |
|
| 280 |
Args: |
| 281 |
providers (List[AwsCredentialsProvider]): List of credentials providers. |
| 282 |
|
| 283 |
Returns: |
| 284 |
AwsCredentialsProvider: |
| 285 |
""" |
| 286 |
|
| 287 |
binding = _awscrt.credentials_provider_new_chain(providers) |
| 288 |
return cls(binding) |
| 289 |
|
| 290 |
@classmethod |
| 291 |
def new_delegate(cls, get_credentials): |
| 292 |
""" |
| 293 |
Creates a provider that sources credentials from a custom |
| 294 |
synchronous callback. |
| 295 |
|
| 296 |
Args: |
| 297 |
get_credentials: Callable which takes no arguments and returns |
| 298 |
:class:`AwsCredentials`. |
| 299 |
|
| 300 |
Returns: |
| 301 |
AwsCredentialsProvider: |
| 302 |
""" |
| 303 |
|
| 304 |
|
| 305 |
assert callable(get_credentials) |
| 306 |
|
| 307 |
binding = _awscrt.credentials_provider_new_delegate(get_credentials) |
| 308 |
return cls(binding) |
| 309 |
|
| 310 |
@classmethod |
| 311 |
def new_cognito( |
| 312 |
cls, |
| 313 |
*, |
| 314 |
endpoint: str, |
| 315 |
identity: str, |
| 316 |
tls_ctx: awscrt.io.ClientTlsContext, |
| 317 |
logins: Optional[Sequence[Tuple[str, str]]] = None, |
| 318 |
custom_role_arn: Optional[str] = None, |
| 319 |
client_bootstrap: Optional[ClientBootstrap] = None, |
| 320 |
http_proxy_options: Optional[HttpProxyOptions] = None): |
| 321 |
""" |
| 322 |
Creates a provider that sources credentials from the AWS Cognito Identity service. |
| 323 |
|
| 324 |
Args: |
| 325 |
endpoint (str): Cognito Identity service regional endpoint to source credentials from. |
| 326 |
|
| 327 |
identity (str): Cognito identity to fetch credentials relative to. |
| 328 |
|
| 329 |
tls_ctx (ClientTlsContext): Client TLS context to use when querying cognito credentials by HTTP. |
| 330 |
|
| 331 |
logins (Optional[Sequence[tuple[str, str]]]): Sequence of tuples specifying pairs of identity provider name |
| 332 |
and token values, representing established login contexts for identity authentication purposes. |
| 333 |
|
| 334 |
custom_role_arn (Optional[str]): ARN of the role to be assumed when multiple roles were received in the |
| 335 |
token from the identity provider. |
| 336 |
|
| 337 |
client_bootstrap (Optional[ClientBootstrap]): Client bootstrap to use when initiating a socket connection. |
| 338 |
If not set, uses the static default ClientBootstrap instead. |
| 339 |
|
| 340 |
http_proxy_options (Optional[HttpProxyOptions]): Optional HTTP proxy options. |
| 341 |
If None is provided then an HTTP proxy is not used. |
| 342 |
|
| 343 |
Returns: |
| 344 |
AwsCredentialsProvider: |
| 345 |
""" |
| 346 |
|
| 347 |
assert isinstance(endpoint, str) |
| 348 |
assert isinstance(identity, str) |
| 349 |
assert isinstance(tls_ctx, ClientTlsContext) |
| 350 |
assert isinstance(custom_role_arn, str) or custom_role_arn is None |
| 351 |
assert isinstance(http_proxy_options, HttpProxyOptions) or http_proxy_options is None |
| 352 |
|
| 353 |
if client_bootstrap is None: |
| 354 |
client_bootstrap = ClientBootstrap.get_or_create_static_default() |
| 355 |
assert isinstance(client_bootstrap, ClientBootstrap) |
| 356 |
|
| 357 |
binding = _awscrt.credentials_provider_new_cognito( |
| 358 |
endpoint, |
| 359 |
identity, |
| 360 |
tls_ctx, |
| 361 |
client_bootstrap, |
| 362 |
logins, |
| 363 |
custom_role_arn, |
| 364 |
http_proxy_options) |
| 365 |
return cls(binding) |
| 366 |
|
| 367 |
@classmethod |
| 368 |
def new_x509( |
| 369 |
cls, |
| 370 |
*, |
| 371 |
endpoint: str, |
| 372 |
thing_name: str, |
| 373 |
role_alias: str, |
| 374 |
tls_ctx: awscrt.io.ClientTlsContext, |
| 375 |
client_bootstrap: Optional[ClientBootstrap] = None, |
| 376 |
http_proxy_options: Optional[HttpProxyOptions] = None): |
| 377 |
""" |
| 378 |
Creates a provider that sources credentials from IoT's X509 credentials service. |
| 379 |
|
| 380 |
Args: |
| 381 |
endpoint (str): X509 service regional endpoint to source credentials from. |
| 382 |
This is a per-account value that can be determined via the CLI: |
| 383 |
`aws iot describe-endpoint --endpoint-type iot:CredentialProvider` |
| 384 |
|
| 385 |
thing_name (str): The name of the IoT thing to use to fetch credentials. |
| 386 |
|
| 387 |
role_alias (str): The name of the role alias to fetch credentials through. |
| 388 |
|
| 389 |
tls_ctx (ClientTlsContext): The client TLS context to use when establishing the http connection to IoT's X509 credentials service. |
| 390 |
|
| 391 |
client_bootstrap (Optional[ClientBootstrap]): Client bootstrap to use when initiating a socket connection. |
| 392 |
If not set, uses the static default ClientBootstrap instead. |
| 393 |
|
| 394 |
http_proxy_options (Optional[HttpProxyOptions]): Optional HTTP proxy options. |
| 395 |
If None is provided then an HTTP proxy is not used. |
| 396 |
|
| 397 |
Returns: |
| 398 |
AwsCredentialsProvider: |
| 399 |
""" |
| 400 |
|
| 401 |
assert isinstance(endpoint, str) |
| 402 |
assert isinstance(thing_name, str) |
| 403 |
assert isinstance(role_alias, str) |
| 404 |
assert isinstance(tls_ctx, ClientTlsContext) |
| 405 |
assert isinstance(http_proxy_options, HttpProxyOptions) or http_proxy_options is None |
| 406 |
if client_bootstrap is None: |
| 407 |
client_bootstrap = ClientBootstrap.get_or_create_static_default() |
| 408 |
assert isinstance(client_bootstrap, ClientBootstrap) |
| 409 |
|
| 410 |
binding = _awscrt.credentials_provider_new_x509( |
| 411 |
endpoint, |
| 412 |
thing_name, |
| 413 |
role_alias, |
| 414 |
tls_ctx, |
| 415 |
client_bootstrap, |
| 416 |
http_proxy_options) |
| 417 |
return cls(binding) |
| 418 |
|
| 419 |
def get_credentials(self): |
| 420 |
""" |
| 421 |
Asynchronously fetch AwsCredentials. |
| 422 |
|
| 423 |
Returns: |
| 424 |
concurrent.futures.Future: A Future which will contain |
| 425 |
:class:`AwsCredentials` (or an exception) when the operation completes. |
| 426 |
The operation may complete on a different thread. |
| 427 |
""" |
| 428 |
future = Future() |
| 429 |
|
| 430 |
def _on_complete(error_code, binding): |
| 431 |
try: |
| 432 |
if error_code: |
| 433 |
future.set_exception(awscrt.exceptions.from_code(error_code)) |
| 434 |
else: |
| 435 |
credentials = AwsCredentials._from_binding(binding) |
| 436 |
future.set_result(credentials) |
| 437 |
|
| 438 |
except Exception as e: |
| 439 |
future.set_exception(e) |
| 440 |
|
| 441 |
try: |
| 442 |
_awscrt.credentials_provider_get_credentials(self._binding, _on_complete) |
| 443 |
except Exception as e: |
| 444 |
future.set_exception(e) |
| 445 |
|
| 446 |
return future |
| 447 |
|
| 448 |
|
| 449 |
class AwsSigningAlgorithm(IntEnum): |
| 450 |
"""AWS signing algorithm enumeration.""" |
| 451 |
|
| 452 |
V4 = 0 |
| 453 |
"""Signature Version 4""" |
| 454 |
|
| 455 |
V4_ASYMMETRIC = 1 |
| 456 |
"""Signature Version 4 - Asymmetric""" |
| 457 |
|
| 458 |
V4_S3EXPRESS = 2 |
| 459 |
"""Signature Version 4 - S3 Express""" |
| 460 |
|
| 461 |
|
| 462 |
class AwsSignatureType(IntEnum): |
| 463 |
"""Which sort of signature should be computed from the signable.""" |
| 464 |
|
| 465 |
HTTP_REQUEST_HEADERS = 0 |
| 466 |
""" |
| 467 |
A signature for a full HTTP request should be computed, |
| 468 |
with header updates applied to the signing result. |
| 469 |
""" |
| 470 |
|
| 471 |
HTTP_REQUEST_QUERY_PARAMS = 1 |
| 472 |
""" |
| 473 |
A signature for a full HTTP request should be computed, |
| 474 |
with query param updates applied to the signing result. |
| 475 |
""" |
| 476 |
|
| 477 |
|
| 478 |
class AwsSignedBodyValue: |
| 479 |
""" |
| 480 |
Values for use with :attr:`AwsSigningConfig.signed_body_value`. |
| 481 |
|
| 482 |
Some services use special values (e.g. "UNSIGNED-PAYLOAD") when the body |
| 483 |
is not being signed in the usual way. |
| 484 |
""" |
| 485 |
|
| 486 |
EMPTY_SHA256 = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' |
| 487 |
"""The SHA-256 of the empty string.""" |
| 488 |
|
| 489 |
UNSIGNED_PAYLOAD = 'UNSIGNED-PAYLOAD' |
| 490 |
"""Unsigned payload option (not accepted by all services)""" |
| 491 |
|
| 492 |
STREAMING_AWS4_HMAC_SHA256_PAYLOAD = 'STREAMING-AWS4-HMAC-SHA256-PAYLOAD' |
| 493 |
"""Each payload chunk will be signed (not accepted by all services)""" |
| 494 |
|
| 495 |
STREAMING_AWS4_HMAC_SHA256_EVENTS = 'STREAMING-AWS4-HMAC-SHA256-EVENTS' |
| 496 |
"""Each event will be signed (not accepted by all services)""" |
| 497 |
|
| 498 |
|
| 499 |
class AwsSignedBodyHeaderType(IntEnum): |
| 500 |
""" |
| 501 |
Controls if signing adds a header containing the canonical request's signed body value. |
| 502 |
|
| 503 |
See :attr:`AwsSigningConfig.signed_body_value`. |
| 504 |
""" |
| 505 |
|
| 506 |
NONE = 0 |
| 507 |
"""Do not add a header.""" |
| 508 |
|
| 509 |
X_AMZ_CONTENT_SHA_256 = 1 |
| 510 |
"""Add the "x-amz-content-sha256" header with the canonical request's signed body value""" |
| 511 |
|
| 512 |
|
| 513 |
class AwsSigningConfig(NativeResource): |
| 514 |
""" |
| 515 |
Configuration for use in AWS-related signing. |
| 516 |
|
| 517 |
AwsSigningConfig is immutable. |
| 518 |
|
| 519 |
It is good practice to use a new config for each signature, or the date might get too old. |
| 520 |
|
| 521 |
Args: |
| 522 |
algorithm (AwsSigningAlgorithm): Which signing algorithm to use. |
| 523 |
|
| 524 |
signature_type (AwsSignatureType): Which sort of signature should be |
| 525 |
computed from the signable. |
| 526 |
|
| 527 |
credentials_provider (AwsCredentialsProvider): Credentials provider |
| 528 |
to fetch signing credentials with. If the algorithm is |
| 529 |
:attr:`AwsSigningAlgorithm.V4_ASYMMETRIC`, ECC-based credentials will be derived from the |
| 530 |
fetched credentials. |
| 531 |
|
| 532 |
region (str): If the algorithm is :attr:`AwsSigningAlgorithm.V4`, the region to sign against. |
| 533 |
If the algorithm is :attr:`AwsSigningAlgorithm.V4_ASYMMETRIC`, the value of the |
| 534 |
"X-amzn-region-set" header (added in signing). |
| 535 |
|
| 536 |
service (str): Name of service to sign a request for. |
| 537 |
|
| 538 |
date (Optional[datetime.datetime]): Date and time to use during the |
| 539 |
signing process. If None is provided then |
| 540 |
`datetime.datetime.now(datetime.timezone.utc)` is used. |
| 541 |
Naive dates (lacking timezone info) are assumed to be in local time. |
| 542 |
|
| 543 |
should_sign_header (Optional[Callable[[str], bool]]): |
| 544 |
Optional function to control which headers are |
| 545 |
a part of the canonical request. |
| 546 |
|
| 547 |
Skipping auth-required headers will result in an unusable signature. |
| 548 |
Headers injected by the signing process are not skippable. |
| 549 |
This function does not override the internal check function |
| 550 |
(x-amzn-trace-id, user-agent), but rather supplements it. |
| 551 |
In particular, a header will get signed if and only if it returns |
| 552 |
true to both the internal check (skips x-amzn-trace-id, user-agent) |
| 553 |
and this function (if defined). |
| 554 |
|
| 555 |
use_double_uri_encode (bool): Whether to double-encode the resource path |
| 556 |
when constructing the canonical request (assuming the path is already |
| 557 |
encoded). Default is True. All services except S3 use double encoding. |
| 558 |
|
| 559 |
should_normalize_uri_path (bool): Whether the resource paths are |
| 560 |
normalized when building the canonical request. Default is True. |
| 561 |
|
| 562 |
signed_body_value (Optional[str]): If set, this value is used as the |
| 563 |
canonical request's body value. Typically, this is the SHA-256 |
| 564 |
of the payload, written as lowercase hex. If this has been |
| 565 |
precalculated, it can be set here. Special values used by certain |
| 566 |
services can also be set (see :class:`AwsSignedBodyValue`). If `None` |
| 567 |
is passed (the default), the typical value will be calculated from |
| 568 |
the payload during signing. |
| 569 |
|
| 570 |
signed_body_header_type (AwsSignedBodyHeaderType): Controls if signing |
| 571 |
adds a header containing the canonical request's signed body value. |
| 572 |
Default is to not add a header. |
| 573 |
|
| 574 |
expiration_in_seconds (Optional[int]): If set, and signature_type is |
| 575 |
:attr:`AwsSignatureType.HTTP_REQUEST_QUERY_PARAMS`, then signing will add "X-Amz-Expires" |
| 576 |
to the query string, equal to the value specified here. |
| 577 |
|
| 578 |
omit_session_token (bool): If set True, the "X-Amz-Security-Token" |
| 579 |
query param is omitted from the canonical request. |
| 580 |
The default False should be used for most services. |
| 581 |
""" |
| 582 |
__slots__ = ('_priv_should_sign_cb') |
| 583 |
|
| 584 |
_attributes = ( |
| 585 |
'algorithm', |
| 586 |
'signature_type', |
| 587 |
'credentials_provider', |
| 588 |
'region', |
| 589 |
'service', |
| 590 |
'date', |
| 591 |
'should_sign_header', |
| 592 |
'use_double_uri_encode', |
| 593 |
'should_normalize_uri_path', |
| 594 |
'signed_body_value', |
| 595 |
'signed_body_header_type', |
| 596 |
'expiration_in_seconds', |
| 597 |
'omit_session_token', |
| 598 |
) |
| 599 |
|
| 600 |
def __init__(self, |
| 601 |
algorithm=AwsSigningAlgorithm.V4, |
| 602 |
signature_type=AwsSignatureType.HTTP_REQUEST_HEADERS, |
| 603 |
credentials_provider=None, |
| 604 |
region="", |
| 605 |
service="", |
| 606 |
date=None, |
| 607 |
should_sign_header=None, |
| 608 |
use_double_uri_encode=True, |
| 609 |
should_normalize_uri_path=True, |
| 610 |
signed_body_value=None, |
| 611 |
signed_body_header_type=AwsSignedBodyHeaderType.NONE, |
| 612 |
expiration_in_seconds=None, |
| 613 |
omit_session_token=False, |
| 614 |
): |
| 615 |
|
| 616 |
assert isinstance(algorithm, AwsSigningAlgorithm) |
| 617 |
assert isinstance(signature_type, AwsSignatureType) |
| 618 |
assert isinstance(credentials_provider, AwsCredentialsProvider) or credentials_provider is None |
| 619 |
assert isinstance(region, str) |
| 620 |
assert isinstance(service, str) |
| 621 |
assert callable(should_sign_header) or should_sign_header is None |
| 622 |
assert signed_body_value is None or (isinstance(signed_body_value, str) and len(signed_body_value) > 0) |
| 623 |
assert isinstance(signed_body_header_type, AwsSignedBodyHeaderType) |
| 624 |
assert expiration_in_seconds is None or expiration_in_seconds > 0 |
| 625 |
|
| 626 |
super().__init__() |
| 627 |
|
| 628 |
if date is None: |
| 629 |
date = datetime.datetime.now(datetime.timezone.utc) |
| 630 |
|
| 631 |
timestamp = date.timestamp() |
| 632 |
|
| 633 |
self._priv_should_sign_cb = should_sign_header |
| 634 |
|
| 635 |
if should_sign_header is not None: |
| 636 |
def should_sign_header_wrapper(name): |
| 637 |
return should_sign_header(name=name) |
| 638 |
else: |
| 639 |
should_sign_header_wrapper = None |
| 640 |
|
| 641 |
if expiration_in_seconds is None: |
| 642 |
|
| 643 |
expiration_in_seconds = 0 |
| 644 |
|
| 645 |
self._binding = _awscrt.signing_config_new( |
| 646 |
algorithm, |
| 647 |
signature_type, |
| 648 |
credentials_provider, |
| 649 |
region, |
| 650 |
service, |
| 651 |
date, |
| 652 |
timestamp, |
| 653 |
should_sign_header_wrapper, |
| 654 |
use_double_uri_encode, |
| 655 |
should_normalize_uri_path, |
| 656 |
signed_body_value, |
| 657 |
signed_body_header_type, |
| 658 |
expiration_in_seconds, |
| 659 |
omit_session_token) |
| 660 |
|
| 661 |
def replace(self, **kwargs): |
| 662 |
""" |
| 663 |
Return an AwsSigningConfig with the same attributes, except for those |
| 664 |
attributes given new values by whichever keyword arguments are specified. |
| 665 |
""" |
| 666 |
args = {x: kwargs.get(x, getattr(self, x)) for x in AwsSigningConfig._attributes} |
| 667 |
return AwsSigningConfig(**args) |
| 668 |
|
| 669 |
@property |
| 670 |
def algorithm(self): |
| 671 |
"""AwsSigningAlgorithm: Which signing algorithm to use""" |
| 672 |
return AwsSigningAlgorithm(_awscrt.signing_config_get_algorithm(self._binding)) |
| 673 |
|
| 674 |
@property |
| 675 |
def signature_type(self): |
| 676 |
"""AwsSignatureType: Which sort of signature should be computed from the signable.""" |
| 677 |
return AwsSignatureType(_awscrt.signing_config_get_signature_type(self._binding)) |
| 678 |
|
| 679 |
@property |
| 680 |
def credentials_provider(self): |
| 681 |
""" |
| 682 |
AwsCredentialsProvider: Credentials provider to fetch signing credentials with. |
| 683 |
If the algorithm is :attr:`AwsSigningAlgorithm.V4_ASYMMETRIC`, ECC-based credentials will be derived |
| 684 |
from the fetched credentials. |
| 685 |
""" |
| 686 |
return _awscrt.signing_config_get_credentials_provider(self._binding) |
| 687 |
|
| 688 |
@property |
| 689 |
def region(self): |
| 690 |
""" |
| 691 |
str: If signing algorithm is :attr:`AwsSigningAlgorithm.V4`, the region to sign against. |
| 692 |
If the algorithm is :attr:`AwsSigningAlgorithm.V4_ASYMMETRIC`, the value of the |
| 693 |
"X-amzn-region-set header" (added in signing). |
| 694 |
""" |
| 695 |
return _awscrt.signing_config_get_region(self._binding) |
| 696 |
|
| 697 |
@property |
| 698 |
def service(self): |
| 699 |
"""str: Name of service to sign a request for""" |
| 700 |
return _awscrt.signing_config_get_service(self._binding) |
| 701 |
|
| 702 |
@property |
| 703 |
def date(self): |
| 704 |
""" |
| 705 |
datetime.datetime: Date and time to use during the signing process. |
| 706 |
|
| 707 |
If None is provided, then `datetime.datetime.now(datetime.timezone.utc)` |
| 708 |
at time of object construction is used. |
| 709 |
|
| 710 |
It is good practice to use a new config for each signature, or the date might get too old. |
| 711 |
""" |
| 712 |
return _awscrt.signing_config_get_date(self._binding) |
| 713 |
|
| 714 |
@property |
| 715 |
def should_sign_header(self): |
| 716 |
""" |
| 717 |
Optional[Callable[[str], bool]]: Optional function to control which |
| 718 |
headers are a part of the canonical request. |
| 719 |
|
| 720 |
Skipping auth-required headers will result in an unusable signature. |
| 721 |
Headers injected by the signing process are not skippable. |
| 722 |
This function does not override the internal check function |
| 723 |
(x-amzn-trace-id, user-agent), but rather supplements it. In particular, |
| 724 |
a header will get signed if and only if it returns true to both |
| 725 |
the internal check (skips x-amzn-trace-id, user-agent) and this function (if defined). |
| 726 |
""" |
| 727 |
return self._priv_should_sign_cb |
| 728 |
|
| 729 |
@property |
| 730 |
def use_double_uri_encode(self): |
| 731 |
""" |
| 732 |
bool: Whether to double-encode the resource path when constructing |
| 733 |
the canonical request (assuming the path is already encoded). |
| 734 |
|
| 735 |
By default, all services except S3 use double encoding. |
| 736 |
""" |
| 737 |
return _awscrt.signing_config_get_use_double_uri_encode(self._binding) |
| 738 |
|
| 739 |
@property |
| 740 |
def should_normalize_uri_path(self): |
| 741 |
""" |
| 742 |
bool: Whether the resource paths are normalized when building the |
| 743 |
canonical request. |
| 744 |
""" |
| 745 |
return _awscrt.signing_config_get_should_normalize_uri_path(self._binding) |
| 746 |
|
| 747 |
@property |
| 748 |
def signed_body_value(self): |
| 749 |
""" |
| 750 |
Optional[str]: What to use as the canonical request's body value. |
| 751 |
If `None` is set (the default), a value will be calculated from |
| 752 |
the payload during signing. Typically, this is the SHA-256 of the |
| 753 |
payload, written as lowercase hex. If this has been precalculated, |
| 754 |
it can be set here. Special values used by certain services can also |
| 755 |
be set (see :class:`AwsSignedBodyValue`). |
| 756 |
""" |
| 757 |
return _awscrt.signing_config_get_signed_body_value(self._binding) |
| 758 |
|
| 759 |
@property |
| 760 |
def signed_body_header_type(self): |
| 761 |
""" |
| 762 |
AwsSignedBodyHeaderType: Controls if signing adds a header containing |
| 763 |
the canonical request's signed body value. |
| 764 |
""" |
| 765 |
return AwsSignedBodyHeaderType(_awscrt.signing_config_get_signed_body_header_type(self._binding)) |
| 766 |
|
| 767 |
@property |
| 768 |
def expiration_in_seconds(self): |
| 769 |
""" |
| 770 |
Optional[int]: If set, and signature_type is :attr:`AwsSignatureType.HTTP_REQUEST_QUERY_PARAMS`, |
| 771 |
then signing will add "X-Amz-Expires" to the query string, equal to the |
| 772 |
value specified here. Otherwise, this is None has no effect. |
| 773 |
""" |
| 774 |
expiration = _awscrt.signing_config_get_expiration_in_seconds(self._binding) |
| 775 |
|
| 776 |
return None if expiration == 0 else expiration |
| 777 |
|
| 778 |
@property |
| 779 |
def omit_session_token(self): |
| 780 |
""" |
| 781 |
bool: Whether the "X-Amz-Security-Token" query param is omitted |
| 782 |
from the canonical request. This should be False for most services. |
| 783 |
""" |
| 784 |
return _awscrt.signing_config_get_omit_session_token(self._binding) |
| 785 |
|
| 786 |
|
| 787 |
def aws_sign_request(http_request, signing_config): |
| 788 |
""" |
| 789 |
Perform AWS HTTP request signing. |
| 790 |
|
| 791 |
The :class:`awscrt.http.HttpRequest` is transformed asynchronously, |
| 792 |
according to the :class:`AwsSigningConfig`. |
| 793 |
|
| 794 |
When signing: |
| 795 |
|
| 796 |
1. It is good practice to use a new config for each signature, |
| 797 |
or the date might get too old. |
| 798 |
|
| 799 |
2. Do not add the following headers to requests before signing, they may be added by the signer: |
| 800 |
x-amz-content-sha256, |
| 801 |
X-Amz-Date, |
| 802 |
Authorization |
| 803 |
|
| 804 |
3. Do not add the following query params to requests before signing, they may be added by the signer: |
| 805 |
X-Amz-Signature, |
| 806 |
X-Amz-Date, |
| 807 |
X-Amz-Credential, |
| 808 |
X-Amz-Algorithm, |
| 809 |
X-Amz-SignedHeaders |
| 810 |
|
| 811 |
Args: |
| 812 |
http_request (awscrt.http.HttpRequest): The HTTP request to sign. |
| 813 |
signing_config (AwsSigningConfig): Configuration for signing. |
| 814 |
|
| 815 |
Returns: |
| 816 |
concurrent.futures.Future: A Future whose result will be the signed |
| 817 |
:class:`awscrt.http.HttpRequest`. The future will contain an exception |
| 818 |
if the signing process fails. |
| 819 |
""" |
| 820 |
|
| 821 |
assert isinstance(http_request, HttpRequest) |
| 822 |
assert isinstance(signing_config, AwsSigningConfig) |
| 823 |
|
| 824 |
future = Future() |
| 825 |
|
| 826 |
def _on_complete(error_code): |
| 827 |
try: |
| 828 |
if error_code: |
| 829 |
future.set_exception(awscrt.exceptions.from_code(error_code)) |
| 830 |
else: |
| 831 |
future.set_result(http_request) |
| 832 |
except Exception as e: |
| 833 |
future.set_exception(e) |
| 834 |
|
| 835 |
_awscrt.sign_request_aws(http_request, signing_config, _on_complete) |
| 836 |
return future |