def add(self, name, value): """ Add a name-value pair. """ assert isinstance_str(name) assert isinstance_str(value) _awscrt.http_headers_add(self._binding, name, value)
def set(self, name, value): """ Set a name-value pair, any existing values for the name are removed. """ assert isinstance_str(name) assert isinstance_str(value) _awscrt.http_headers_set(self._binding, name, value)
def __init__(self, access_key_id, secret_access_key, session_token=None): assert isinstance_str(access_key_id) assert isinstance_str(secret_access_key) assert isinstance_str(session_token) or session_token is None super(AwsCredentials, self).__init__() self._binding = _awscrt.credentials_new(access_key_id, secret_access_key, session_token)
def remove_value(self, name, value): """ Remove a specific value for this name. Raises a ValueError if value not found. """ assert isinstance_str(name) assert isinstance_str(value) _awscrt.http_headers_remove_value(self._binding, name, value)
def __init__(self, algorithm, # type: AwsSigningAlgorithm credentials_provider, # type: AwsCredentialsProviderBase region, # type: str service, # type: str date=None, # type: Optional[datetime.datetime] should_sign_param=None, # type: Optional[Callable[[str], bool]] use_double_uri_encode=False, # type: bool should_normalize_uri_path=True, # type: bool body_signing_type=AwsBodySigningConfigType.BodySigningOn # type: AwsBodySigningConfigType ): # type: (...) -> None assert isinstance(algorithm, AwsSigningAlgorithm) assert isinstance(credentials_provider, AwsCredentialsProviderBase) assert isinstance_str(region) assert isinstance_str(service) assert isinstance(date, datetime.datetime) or date is None assert callable(should_sign_param) or should_sign_param is None assert isinstance(body_signing_type, AwsBodySigningConfigType) super(AwsSigningConfig, self).__init__() if date is None: date = datetime.datetime.now(_utc) try: timestamp = date.timestamp() except AttributeError: # Python 2 doesn't have datetime.timestamp() function. # If it did we could just call it from binding code instead of calculating it here. if date.tzinfo is None: timestamp = time.mktime(date.timetuple()) else: epoch = datetime.datetime(1970, 1, 1, tzinfo=_utc) timestamp = (date - epoch).total_seconds() self._priv_should_sign_cb = should_sign_param if should_sign_param is not None: def should_sign_param_wrapper(name): return should_sign_param(name=name) else: should_sign_param_wrapper = None self._binding = _awscrt.signing_config_new( algorithm, credentials_provider, region, service, date, timestamp, should_sign_param_wrapper, use_double_uri_encode, should_normalize_uri_path, body_signing_type)
def new_static(cls, access_key_id, secret_access_key, session_token=None): """ Create a simple provider that just returns a fixed set of credentials """ assert isinstance_str(access_key_id) assert isinstance_str(secret_access_key) assert isinstance_str(session_token) or session_token is None binding = _awscrt.credentials_provider_new_static( access_key_id, secret_access_key, session_token) return cls(binding)
def remove(self, name): """ Remove all values for this name. Raises a KeyError if name not found. """ assert isinstance_str(name) _awscrt.http_headers_remove(self._binding, name)
def get(self, name, default=None): """ Get the first value for this name, ignoring any additional values. Returns `default` if no values exist. """ assert isinstance_str(name) return _awscrt.http_headers_get(self._binding, name, default)
def _alpn_list_to_str(alpn_list): """ Transform ['h2', 'http/1.1'] -> "h2;http/1.1" None is returned if list is None or empty """ if alpn_list: assert not isinstance_str(alpn_list) return ';'.join(alpn_list) return None
def get_values(self, name): """ Return an iterator over the values for this name. """ assert isinstance_str(name) name = name.lower() for i in range(_awscrt.http_headers_count(self._binding)): name_i, value_i = _awscrt.http_headers_get_index(self._binding, i) if name_i.lower() == name: yield value_i
def override_default_trust_store_from_path(self, ca_dirpath=None, ca_filepath=None): """Override default trust store. Args: ca_dirpath (Optional[str]): Path to directory containing trusted certificates, which will overrides the default trust store. Only supported on Unix. ca_filepath(Optional[str]): Path to file containing PEM armored chain of trusted CA certificates. """ assert isinstance_str(ca_dirpath) or ca_dirpath is None assert isinstance_str(ca_filepath) or ca_filepath is None if ca_filepath: ca_buffer = _read_binary_file(ca_filepath) self.override_default_trust_store(ca_buffer) self.ca_dirpath = ca_dirpath
def create_server_pkcs12(pkcs12_filepath, pkcs12_password): """ Create options configured for use in server mode. NOTE: This configuration only works on Apple devices. Args: pkcs12_filepath (str): Path to PKCS #12 file. pkcs12_password (str): Password to PKCS #12 file. Returns: TlsContextOptions: """ assert isinstance_str(pkcs12_filepath) assert isinstance_str(pkcs12_password) opt = TlsContextOptions() opt.pkcs12_filepath = pkcs12_filepath opt.pkcs12_password = pkcs12_password opt.verify_peer = False return opt
def create_server_from_path(cert_filepath, pk_filepath): """ Create options configured for use in server mode. Both files are treated as PKCS #7 PEM armored. They are loaded from disk and stored in buffers internally. Args: cert_filepath (str): Path to certificate file. pk_filepath (str): Path to private key file. Returns: TlsContextOptions: """ assert isinstance_str(cert_filepath) assert isinstance_str(pk_filepath) cert_buffer = _read_binary_file(cert_filepath) key_buffer = _read_binary_file(pk_filepath) return TlsContextOptions.create_server(cert_buffer, key_buffer)
def create_client_with_mtls_pkcs12(pkcs12_filepath, pkcs12_password): """ Create options configured for use with mutual TLS in client mode. NOTE: This configuration only works on Apple devices. Args: pkcs12_filepath (str): Path to PKCS #12 file. The file is loaded from disk and stored internally. pkcs12_password (str): Password to PKCS #12 file. Returns: TlsContextOptions: """ assert isinstance_str(pkcs12_filepath) assert isinstance_str(pkcs12_password) opt = TlsContextOptions() opt.pkcs12_filepath = pkcs12_filepath opt.pkcs12_password = pkcs12_password opt.verify_peer = True return opt
def get(self, name, default=None): """ Get the first value for this name, ignoring any additional values. Returns `default` if no values exist. Args: name (str): Name. default (Optional[str]): If `name` not found, this value is returned. Defaults to None. Returns: str: """ assert isinstance_str(name) return _awscrt.http_headers_get(self._binding, name, default)
def new(cls, host_name, port, bootstrap, socket_options=None, tls_connection_options=None, proxy_options=None): """ Asynchronously establish a new HttpClientConnection. Args: host_name (str): Connect to host. port (int): Connect to port. bootstrap (ClientBootstrap): Client bootstrap to use when initiating socket connection. socket_options (Optional[SocketOptions]): Optional socket options. If None is provided, then default options are used. tls_connection_options (Optional[TlsConnectionOptions]): Optional TLS connection options. If None is provided, then the connection will be attempted over plain-text. proxy_options (Optional[HttpProxyOptions]): Optional proxy options. If None is provided then a proxy is not used. Returns: concurrent.futures.Future: A Future which completes when connection succeeds or fails. If successful, the Future will contain a new :class:`HttpClientConnection`. Otherwise, it will contain an exception. """ assert isinstance(bootstrap, ClientBootstrap) or bootstrap is None assert isinstance_str(host_name) assert isinstance(port, int) assert isinstance( tls_connection_options, TlsConnectionOptions) or tls_connection_options is None assert isinstance(socket_options, SocketOptions) or socket_options is None assert isinstance(proxy_options, HttpProxyOptions) or proxy_options is None future = Future() try: if not socket_options: socket_options = SocketOptions() if not bootstrap: event_loop_group = EventLoopGroup(1) host_resolver = DefaultHostResolver(event_loop_group) bootstrap = ClientBootstrap(event_loop_group, host_resolver) connection = cls() connection._host_name = host_name connection._port = port def on_connection_setup(binding, error_code, http_version): if error_code == 0: connection._binding = binding connection._version = HttpVersion(http_version) future.set_result(connection) else: future.set_exception( awscrt.exceptions.from_code(error_code)) # on_shutdown MUST NOT reference the connection itself, just the shutdown_future within it. # Otherwise we create a circular reference that prevents the connection from getting GC'd. shutdown_future = connection.shutdown_future def on_shutdown(error_code): if error_code: shutdown_future.set_exception( awscrt.exceptions.from_code(error_code)) else: shutdown_future.set_result(None) _awscrt.http_client_connection_new(bootstrap, on_connection_setup, on_shutdown, host_name, port, socket_options, tls_connection_options, proxy_options) except Exception as e: future.set_exception(e) return future
def new(cls, host_name, port, bootstrap, socket_options=None, tls_connection_options=None, proxy_options=None): """ Initiates a new connection to host_name and port using socket_options and tls_connection_options if supplied. if tls_connection_options is None, then the connection will be attempted over plain-text. Returns a future where the result is a new instance to HttpClientConnection, once the connection has completed and is ready for use. """ assert isinstance(bootstrap, ClientBootstrap) or bootstrap is None assert isinstance_str(host_name) assert isinstance(port, int) assert isinstance( tls_connection_options, TlsConnectionOptions) or tls_connection_options is None assert isinstance(socket_options, SocketOptions) or socket_options is None assert isinstance(proxy_options, HttpProxyOptions) or proxy_options is None future = Future() try: if not socket_options: socket_options = SocketOptions() if not bootstrap: event_loop_group = EventLoopGroup(1) host_resolver = DefaultHostResolver(event_loop_group) bootstrap = ClientBootstrap(event_loop_group, host_resolver) connection = cls() connection._host_name = host_name connection._port = port def on_connection_setup(binding, error_code): if error_code == 0: connection._binding = binding future.set_result(connection) else: future.set_exception( awscrt.exceptions.from_code(error_code)) # on_shutdown MUST NOT reference the connection itself, just the shutdown_future within it. # Otherwise we create a circular reference that prevents the connection from getting GC'd. shutdown_future = connection.shutdown_future def on_shutdown(error_code): if error_code: shutdown_future.set_exception( awscrt.exceptions.from_code(error_code)) else: shutdown_future.set_result(None) _awscrt.http_client_connection_new(bootstrap, on_connection_setup, on_shutdown, host_name, port, socket_options, tls_connection_options, proxy_options) except Exception as e: future.set_exception(e) return future
def __init__( self, algorithm, signature_type, credentials_provider, region, service, date=None, should_sign_header=None, use_double_uri_encode=True, should_normalize_uri_path=True, signed_body_value_type=AwsSignedBodyValueType.PAYLOAD, signed_body_header_type=AwsSignedBodyHeaderType.NONE, expiration_in_seconds=None, omit_session_token=False, ): assert isinstance(algorithm, AwsSigningAlgorithm) assert isinstance(signature_type, AwsSignatureType) assert isinstance(credentials_provider, AwsCredentialsProviderBase) assert isinstance_str(region) assert isinstance_str(service) assert callable(should_sign_header) or should_sign_header is None assert isinstance(signed_body_value_type, AwsSignedBodyValueType) assert isinstance(signed_body_header_type, AwsSignedBodyHeaderType) assert expiration_in_seconds is None or expiration_in_seconds > 0 super(AwsSigningConfig, self).__init__() if date is None: date = datetime.datetime.now(_utc) try: timestamp = date.timestamp() except AttributeError: # Python 2 doesn't have datetime.timestamp() function. # If it did we could just call it from binding code instead of calculating it here. if date.tzinfo is None: timestamp = time.mktime(date.timetuple()) else: epoch = datetime.datetime(1970, 1, 1, tzinfo=_utc) timestamp = (date - epoch).total_seconds() self._priv_should_sign_cb = should_sign_header if should_sign_header is not None: def should_sign_header_wrapper(name): return should_sign_header(name=name) else: should_sign_header_wrapper = None if expiration_in_seconds is None: # C layer uses 0 to indicate None expiration_in_seconds = 0 self._binding = _awscrt.signing_config_new( algorithm, signature_type, credentials_provider, region, service, date, timestamp, should_sign_header_wrapper, use_double_uri_encode, should_normalize_uri_path, signed_body_value_type, signed_body_header_type, expiration_in_seconds, omit_session_token)