Example #1
0
 def _type_check_datetime(self, value):
     try:
         parse_to_aware_datetime(value)
         return True
     except (TypeError, ValueError, AttributeError):
         # Yes, dateutil can sometimes raise an AttributeError
         # when parsing timestamps.
         return False
Example #2
0
 def _type_check_datetime(self, value):
     try:
         parse_to_aware_datetime(value)
         return True
     except (TypeError, ValueError, AttributeError):
         # Yes, dateutil can sometimes raise an AttributeError
         # when parsing timestamps.
         return False
Example #3
0
 def _convert_header_value(self, shape, value):
     if shape.type_name == 'timestamp':
         datetime_obj = parse_to_aware_datetime(value)
         timestamp = calendar.timegm(datetime_obj.utctimetuple())
         return self._timestamp_rfc822(timestamp)
     else:
         return value
Example #4
0
 def _convert_header_value(self, shape, value):
     if shape.type_name == 'timestamp':
         datetime_obj = parse_to_aware_datetime(value)
         timestamp = calendar.timegm(datetime_obj.utctimetuple())
         return self._timestamp_rfc822(timestamp)
     else:
         return value
 def _convert_timestamp_to_str(self, value, timestamp_format=None):
     if timestamp_format is None:
         timestamp_format = self.TIMESTAMP_FORMAT
     timestamp_format = timestamp_format.lower()
     datetime_obj = parse_to_aware_datetime(value)
     converter = getattr(self, '_timestamp_%s' % timestamp_format)
     final_value = converter(datetime_obj)
     return final_value
Example #6
0
 def _run_main(self, args, parsed_globals):
     signer = CloudFrontSigner(
         args.key_pair_id, RSASigner(args.private_key).sign)
     date_less_than = parse_to_aware_datetime(args.date_less_than)
     date_greater_than = args.date_greater_than
     if date_greater_than is not None:
         date_greater_than = parse_to_aware_datetime(date_greater_than)
     if date_greater_than is not None or args.ip_address is not None:
         policy = signer.build_policy(
             args.url, date_less_than, date_greater_than=date_greater_than,
             ip_address=args.ip_address)
         sys.stdout.write(signer.generate_presigned_url(
             args.url, policy=policy))
     else:
         sys.stdout.write(signer.generate_presigned_url(
             args.url, date_less_than=date_less_than))
     return 0
Example #7
0
 def _convert_timestamp_to_str(self, value, timestamp_format=None):
     if timestamp_format is None:
         timestamp_format = self.TIMESTAMP_FORMAT
     timestamp_format = timestamp_format.lower()
     datetime_obj = parse_to_aware_datetime(value)
     converter = getattr(
         self, '_timestamp_%s' % timestamp_format)
     final_value = converter(datetime_obj)
     return final_value
Example #8
0
 def _convert_timestamp_to_str(self,
                               value: Union[int, str, datetime],
                               timestamp_format=None) -> str:
     if timestamp_format is None:
         timestamp_format = self.TIMESTAMP_FORMAT
     timestamp_format = timestamp_format.lower()
     datetime_obj = parse_to_aware_datetime(value)
     converter = getattr(self, "_timestamp_%s" % timestamp_format)
     final_value = converter(datetime_obj)
     return final_value
Example #9
0
 def _convert_header_value(self, shape, value):
     if shape.type_name == 'timestamp':
         datetime_obj = parse_to_aware_datetime(value)
         timestamp = calendar.timegm(datetime_obj.utctimetuple())
         return self._timestamp_rfc822(timestamp)
     elif is_json_value_header(shape):
         # Serialize with no spaces after separators to save space in
         # the header.
         return self._get_base64(json.dumps(value, separators=(',', ':')))
     else:
         return value
Example #10
0
 def _convert_header_value(self, shape, value):
     if shape.type_name == 'timestamp':
         datetime_obj = parse_to_aware_datetime(value)
         timestamp = calendar.timegm(datetime_obj.utctimetuple())
         return self._timestamp_rfc822(timestamp)
     elif is_json_value_header(shape):
         # Serialize with no spaces after separators to save space in
         # the header.
         return self._get_base64(json.dumps(value, separators=(',', ':')))
     else:
         return value
Example #11
0
 def _convert_header_value(self, shape, value):
     if shape.type_name == 'timestamp':
         datetime_obj = parse_to_aware_datetime(value)
         timestamp = calendar.timegm(datetime_obj.utctimetuple())
         timestamp_format = shape.serialization.get(
             'timestampFormat', self.HEADER_TIMESTAMP_FORMAT)
         return self._convert_timestamp_to_str(timestamp, timestamp_format)
     elif is_json_value_header(shape):
         # Serialize with no spaces after separators to save space in
         # the header.
         return self._get_base64(json.dumps(value, separators=(',', ':')))
     else:
         return value
 def _convert_header_value(self, shape, value):
     if shape.type_name == 'timestamp':
         datetime_obj = parse_to_aware_datetime(value)
         timestamp = calendar.timegm(datetime_obj.utctimetuple())
         timestamp_format = shape.serialization.get(
             'timestampFormat', self.HEADER_TIMESTAMP_FORMAT)
         return self._convert_timestamp_to_str(timestamp, timestamp_format)
     elif is_json_value_header(shape):
         # Serialize with no spaces after separators to save space in
         # the header.
         return self._get_base64(json.dumps(value, separators=(',', ':')))
     else:
         return value
Example #13
0
 def test_handles_full_iso_8601(self):
     expected = datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=tzutc())
     self.assertEqual(
         parse_to_aware_datetime('1970-01-01T00:00:00Z'),
         expected)
Example #14
0
 def test_handles_int_epoch(self):
     expected = datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=tzutc())
     self.assertEqual(parse_to_aware_datetime(0), expected)
Example #15
0
 def test_handles_naive_datetime(self):
     original = datetime.datetime(1970, 1, 1, 0, 0, 0)
     expected = datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=tzutc())
     self.assertEqual(parse_to_aware_datetime(original), expected)
Example #16
0
 def test_handles_other_timezone(self):
     tzinfo = tzoffset("BRST", -10800)
     original = datetime.datetime(2014, 1, 1, 0, 0, 0, tzinfo=tzinfo)
     self.assertEqual(parse_to_aware_datetime(original), original)
Example #17
0
 def test_handles_utc_time(self):
     original = datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=tzutc())
     self.assertEqual(parse_to_aware_datetime(original), original)
Example #18
0
 def test_handles_full_iso_8601(self):
     expected = datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=tzutc())
     self.assertEqual(parse_to_aware_datetime('1970-01-01T00:00:00Z'),
                      expected)
Example #19
0
 def _type_check_datetime(self, value):
     try:
         parse_to_aware_datetime(value)
         return True
     except (TypeError, ValueError):
         return False
Example #20
0
 def _type_check_datetime(self, value):
     try:
         parse_to_aware_datetime(value)
         return True
     except (TypeError, ValueError):
         return False
Example #21
0
 def _convert_timestamp_to_str(self, value):
     datetime_obj = parse_to_aware_datetime(value)
     converter = getattr(
         self, '_timestamp_%s' % self.TIMESTAMP_FORMAT.lower())
     final_value = converter(datetime_obj)
     return final_value
Example #22
0
 def test_handles_other_timezone(self):
     tzinfo = tzoffset("BRST", -10800)
     original = datetime.datetime(2014, 1, 1, 0, 0, 0, tzinfo=tzinfo)
     self.assertEqual(parse_to_aware_datetime(original), original)
Example #23
0
 def _to_timestamp(self, datetime_obj):
     obj = utils.parse_to_aware_datetime(datetime_obj)
     return obj.strftime('%Y-%m-%dT%H:%M:%SZ')
Example #24
0
 def test_handles_naive_datetime(self):
     original = datetime.datetime(1970, 1, 1, 0, 0, 0)
     expected = datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=tzutc())
     self.assertEqual(parse_to_aware_datetime(original), expected)
Example #25
0
 def test_year_only_iso_8601(self):
     expected = datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=tzutc())
     self.assertEqual(parse_to_aware_datetime('1970-01-01'), expected)
Example #26
0
 def test_year_only_iso_8601(self):
     expected = datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=tzutc())
     self.assertEqual(parse_to_aware_datetime('1970-01-01'), expected)
Example #27
0
 def _to_timestamp(self, datetime_obj):
     obj = utils.parse_to_aware_datetime(datetime_obj)
     return obj.strftime('%Y-%m-%dT%H:%M:%SZ')
Example #28
0
 def _convert_timestamp_to_str(self, value):
     datetime_obj = parse_to_aware_datetime(value)
     converter = getattr(self,
                         '_timestamp_%s' % self.TIMESTAMP_FORMAT.lower())
     final_value = converter(datetime_obj)
     return final_value
Example #29
0
 def test_handles_utc_time(self):
     original = datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=tzutc())
     self.assertEqual(parse_to_aware_datetime(original), original)
Example #30
0
def _aws_temp_credentials():
    """Construct temporary MONGODB-AWS credentials."""
    global _cached_credentials
    # Store the variable locally for safe threaded access.
    creds = _cached_credentials

    access_key = os.environ.get('AWS_ACCESS_KEY_ID')
    secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY')
    if access_key and secret_key:
        return AwsCredential(access_key, secret_key,
                             os.environ.get('AWS_SESSION_TOKEN'))

    # Check to see if we have valid credentials.
    if creds and creds.expiration is not None:
        now_utc = datetime.now(utc)
        exp_utc = parse_to_aware_datetime(creds.expiration)
        if (exp_utc - now_utc).total_seconds() >= _credential_buffer_seconds:
            return creds

    # Check if environment variables exposed by IAM Roles for Service Accounts (IRSA) are present.
    # See https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html for details.
    irsa_web_id_file = os.getenv('AWS_WEB_IDENTITY_TOKEN_FILE')
    irsa_role_arn = os.getenv('AWS_ROLE_ARN')
    if irsa_web_id_file and irsa_role_arn:
        try:
            with open(irsa_web_id_file) as f:
                irsa_web_id_token = f.read()
            role_session_name = os.getenv('AWS_ROLE_SESSION_NAME',
                                          'pymongo-auth-aws')
            creds = _irsa_assume_role(irsa_role_arn, irsa_web_id_token,
                                      role_session_name)
            _cached_credentials = creds
            return creds
        except Exception as exc:
            raise PyMongoAuthAwsError(
                'temporary MONGODB-AWS credentials could not be obtained, '
                'error: %s' % (exc, ))

    # If the environment variable
    # AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is set then drivers MUST
    # assume that it was set by an AWS ECS agent and use the URI
    # http://169.254.170.2/$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI to
    # obtain temporary credentials.
    relative_uri = os.environ.get('AWS_CONTAINER_CREDENTIALS_RELATIVE_URI')
    if relative_uri is not None:
        try:
            res = requests.get(_AWS_REL_URI + relative_uri,
                               timeout=_AWS_HTTP_TIMEOUT)
            res_json = res.json()
        except (ValueError, requests.exceptions.RequestException) as exc:
            raise PyMongoAuthAwsError(
                'temporary MONGODB-AWS credentials could not be obtained, '
                'error: %s' % (exc, ))
    else:
        # If the environment variable AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is
        # not set drivers MUST assume we are on an EC2 instance and use the
        # endpoint
        # http://169.254.169.254/latest/meta-data/iam/security-credentials
        # /<role-name>
        # whereas role-name can be obtained from querying the URI
        # http://169.254.169.254/latest/meta-data/iam/security-credentials/.
        try:
            # Get token
            headers = {'X-aws-ec2-metadata-token-ttl-seconds': "30"}
            res = requests.put(_AWS_EC2_URI + 'latest/api/token',
                               headers=headers,
                               timeout=_AWS_HTTP_TIMEOUT)
            token = res.content
            # Get role name
            headers = {'X-aws-ec2-metadata-token': token}
            res = requests.get(_AWS_EC2_URI + _AWS_EC2_PATH,
                               headers=headers,
                               timeout=_AWS_HTTP_TIMEOUT)
            role = res.text
            # Get temp creds
            res = requests.get(_AWS_EC2_URI + _AWS_EC2_PATH + role,
                               headers=headers,
                               timeout=_AWS_HTTP_TIMEOUT)
            res_json = res.json()
        except (ValueError, requests.exceptions.RequestException) as exc:
            raise PyMongoAuthAwsError(
                'temporary MONGODB-AWS credentials could not be obtained, '
                'error: %s' % (exc, ))

    # See https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role.html#examples for expected result format.
    try:
        temp_user = res_json['AccessKeyId']
        temp_password = res_json['SecretAccessKey']
        session_token = res_json['Token']
        expiration = res_json['Expiration']
    except KeyError:
        # If temporary credentials cannot be obtained then drivers MUST
        # fail authentication and raise an error.
        raise PyMongoAuthAwsError(
            'temporary MONGODB-AWS credentials could not be obtained')

    creds = AwsCredential(temp_user, temp_password, session_token, expiration)
    _cached_credentials = creds
    return creds
Example #31
0
 def test_handles_int_epoch(self):
     expected = datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=tzutc())
     self.assertEqual(parse_to_aware_datetime(0), expected)