Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_s3api_with_s3_token_no_pass_token_to_auth_token(self):
self.swift = FakeSwift()
self.keystone_auth = KeystoneAuth(
self.swift, {'operator_roles': 'swift-user'})
self.auth_token = AuthProtocol(
self.keystone_auth, {'delay_auth_decision': 'True'})
self.s3_token = S3Token(
self.auth_token, {'auth_uri': 'https://fakehost/identity'})
self.s3api = S3Middleware(self.s3_token, CONF)
req = Request.blank(
'/bucket',
environ={'REQUEST_METHOD': 'PUT'},
headers={'Authorization': 'AWS access:signature',
'Date': self.get_date_header()})
self.swift.register('PUT', '/v1/AUTH_TENANT_ID/bucket',
swob.HTTPCreated, {}, None)
self.swift.register('HEAD', '/v1/AUTH_TENANT_ID',
swob.HTTPOk, {}, None)
with patch.object(self.s3_token, '_json_request') as mock_req:
with patch.object(self.auth_token,
'_do_fetch_token') as mock_fetch:
def test_s3api_with_s3_token_and_auth_token(self):
self.swift = FakeSwift()
self.keystone_auth = KeystoneAuth(
self.swift, {'operator_roles': 'swift-user'})
self.auth_token = AuthProtocol(
self.keystone_auth, {'delay_auth_decision': 'True'})
self.s3_token = S3Token(
self.auth_token, {'auth_uri': 'https://fakehost/identity'})
self.s3api = S3Middleware(self.s3_token, CONF)
req = Request.blank(
'/bucket',
environ={'REQUEST_METHOD': 'PUT'},
headers={'Authorization': 'AWS access:signature',
'Date': self.get_date_header()})
self.swift.register('PUT', '/v1/AUTH_TENANT_ID/bucket',
swob.HTTPCreated, {}, None)
self.swift.register('HEAD', '/v1/AUTH_TENANT_ID',
swob.HTTPOk, {}, None)
with patch.object(self.s3_token, '_json_request') as mock_req:
with patch.object(self.auth_token,
'_do_fetch_token') as mock_fetch:
def setup(*args, **kwargs):
"""Set a KeystoneAuthBackend as the auth backend.
Loads keystone settings from hil.cfg.
"""
if not cfg.has_section(__name__):
logger.error('No section for [%s] in hil.cfg; authentication will '
'not work without this. Please add this section and try '
'again.', __name__)
sys.exit(1)
keystone_cfg = {}
for key in cfg.options(__name__):
keystone_cfg[key] = cfg.get(__name__, key)
# Great job with the API design Openstack!
factory = filter_factory(keystone_cfg)
app.wsgi_app = factory(app.wsgi_app)
auth.set_auth_backend(KeystoneAuthBackend())
def setup(*args, **kwargs):
"""Set a KeystoneAuthBackend as the auth backend.
Loads keystone settings from hil.cfg.
"""
if not cfg.has_section(__name__):
logger.error('No section for [%s] in hil.cfg; authentication will '
'not work without this. Please add this section and try '
'again.', __name__)
sys.exit(1)
keystone_cfg = {}
for key in cfg.options(__name__):
keystone_cfg[key] = cfg.get(__name__, key)
# Great job with the API design Openstack!
factory = filter_factory(keystone_cfg)
app.wsgi_app = factory(app.wsgi_app)
auth.set_auth_backend(KeystoneAuthBackend())
level=level,
max_depth=max_depth)
if isinstance(value, dict):
return dict((k, recursive(v)) for k, v in six.iteritems(value))
elif isinstance(value, (list, tuple)):
return [recursive(lv) for lv in value]
# It's not clear why xmlrpclib created their own DateTime type, but
# for our purposes, make it a datetime type which is explicitly
# handled
if isinstance(value, xmlrpclib.DateTime):
value = datetime.datetime(*tuple(value.timetuple())[:6])
if convert_datetime and isinstance(value, datetime.datetime):
return timeutils.strtime(value)
elif isinstance(value, gettextutils.Message):
return value.data
elif hasattr(value, 'iteritems'):
return recursive(dict(value.iteritems()), level=level + 1)
elif hasattr(value, '__iter__'):
return recursive(list(value))
elif convert_instances and hasattr(value, '__dict__'):
# Likely an instance of something. Watch for cycles.
# Ignore class member vars.
return recursive(value.__dict__, level=level + 1)
elif netaddr and isinstance(value, netaddr.IPAddress):
return six.text_type(value)
else:
if any(test(value) for test in _nasty_type_tests):
return six.text_type(value)
return value
except TypeError:
for d_o in o.deprecated_opts:
opt_types[d_o.name] = type_dest
opts = {}
for k, v in six.iteritems(conf):
dest = k
try:
if v is not None:
type_, dest = opt_types[k]
v = type_(v)
except KeyError:
# This option is not known to auth_token.
pass
except ValueError as e:
raise ksm_exceptions.ConfigurationError(
_('Unable to convert the value of %(key)s option into correct '
'type: %(ex)s') % {'key': k, 'ex': e})
opts[dest] = v
return opts
def __call__(self, req):
# NOTE(alevine): We need to calculate the hash here because
# subsequent access to request modifies the req.body so the hash
# calculation will yield invalid results.
body_hash = hashlib.sha256(req.body).hexdigest()
signature = self._get_signature(req)
if not signature:
msg = _("Signature not provided")
return self._ec2_error_response("AuthFailure", msg)
access = self._get_access(req)
if not access:
msg = _("Access key not provided")
return self._ec2_error_response("AuthFailure", msg)
if 'X-Amz-Signature' in req.params or 'Authorization' in req.headers:
auth_params = {}
else:
# Make a copy of args for authentication and signature verification
auth_params = dict(req.params)
# Not part of authentication args
auth_params.pop('Signature', None)
headers = req.headers
if six.PY3:
"""
# cache backends return None when no data is found. We don't mind
# that this particular special value is unsigned.
if signed_data is None:
return None
# First we calculate the signature
provided_mac = signed_data[:DIGEST_LENGTH_B64]
calculated_mac = sign_data(
keys['MAC'],
signed_data[DIGEST_LENGTH_B64:])
# Then verify that it matches the provided value
if not secretutils.constant_time_compare(provided_mac, calculated_mac):
raise InvalidMacError(_('Invalid MAC; data appears to be corrupted.'))
data = base64.b64decode(signed_data[DIGEST_LENGTH_B64:])
# then if necessary decrypt the data
if keys['strategy'] == b'ENCRYPT':
data = decrypt_data(keys['ENCRYPTION'], data)
return data
def _invalid_user_token(self, msg=False):
# NOTE(jamielennox): use False as the default so that None is valid
if msg is False:
msg = _('Token authorization failed')
raise ksm_exceptions.InvalidToken(msg)
def _verify_signing_dir(self):
if os.path.isdir(self._directory_name):
if not os.access(self._directory_name, os.W_OK):
raise exc.ConfigurationError(
_('unable to access signing_dir %s') %
self._directory_name)
uid = os.getuid()
if os.stat(self._directory_name).st_uid != uid:
self._log.warning('signing_dir is not owned by %s', uid)
current_mode = stat.S_IMODE(os.stat(self._directory_name).st_mode)
if current_mode != stat.S_IRWXU:
self._log.warning(
'signing_dir mode is %(mode)s instead of %(need)s',
{'mode': oct(current_mode), 'need': oct(stat.S_IRWXU)})
else:
os.makedirs(self._directory_name, stat.S_IRWXU)