本文整理汇总了Python中swift.common.utils.get_remote_client函数的典型用法代码示例。如果您正苦于以下问题:Python get_remote_client函数的具体用法?Python get_remote_client怎么用?Python get_remote_client使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_remote_client函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: authorize
def authorize(self, req):
env = req.environ
env_identity = env.get('keystone.identity', {})
tenant = env_identity.get('tenant')
try:
version, account, container, obj = split_path(req.path, 1, 4, True)
except ValueError:
return HTTPNotFound(request=req)
if account != '%s_%s' % (self.reseller_prefix, tenant[0]):
self.logger.debug('tenant mismatch')
return self.denied_response(req)
# If user is in the swift operator group then make the owner of it.
user_groups = env_identity.get('roles', [])
for _group in self.keystone_swift_operator_roles.split(','):
_group = _group.strip()
if _group in user_groups:
self.logger.debug(
"User is in group: %s allow him to do whatever it wants" % (_group))
req.environ['swift_owner'] = True
return None
# If user is of the same name of the tenant then make owner of it.
user = env_identity.get('user', '')
if self.keystone_tenant_user_admin and user == tenant[1]:
self.logger.debug("user: %s == %s tenant and option "\
"keystone_tenant_user_admin is set" % \
(user, tenant))
req.environ['swift_owner'] = True
return None
# Allow container sync
if (req.environ.get('swift_sync_key') and
req.environ['swift_sync_key'] ==
req.headers.get('x-container-sync-key', None) and
'x-timestamp' in req.headers and
(req.remote_addr in self.allowed_sync_hosts or
get_remote_client(req) in self.allowed_sync_hosts)):
self.logger.debug('allowing container-sync')
return None
# Check if Referrer allow it
referrers, groups = parse_acl(getattr(req, 'acl', None))
if referrer_allowed(req.referer, referrers):
if obj or '.rlistings' in groups:
self.logger.debug('authorizing via ACL')
return None
return self.denied_response(req)
# Check if we have the group in the usergroups and allow it
for user_group in user_groups:
if user_group in groups:
self.logger.debug('user in group which is allowed in" \
" ACL: %s authorizing' % (user_group))
return None
# last but not least retun deny
return self.denied_response(req)
示例2: handle_request
def handle_request(self, req):
try:
self.logger.set_statsd_prefix('proxy-server')
if req.content_length and req.content_length < 0:
return jresponse('-1','Invalid Content-Length',req,400)
try:
if not check_utf8(req.path_info):
return jresponse('-1','Invalid UTF8',req,412)
except UnicodeError:
return jresponse('-1','Invalid UTF8',req,412)
try:
controller, path_parts = self.get_controller(req)
p = req.path_info
if isinstance(p, unicode):
p = p.encode('utf-8')
except ValueError:
return jresponse('-1','not found',req,404)
if not controller:
return jresponse('-1','Bad URL',req,412)
if self.deny_host_headers and \
req.host.split(':')[0] in self.deny_host_headers:
return HTTPForbidden(request=req, body='Invalid host header')
if not check_path_parts(path_parts):
return HTTPForbidden(request=req, body='Invalid path_parts header')
self.logger.set_statsd_prefix('proxy-server.' +
controller.server_type.lower())
controller = controller(self, **path_parts)
if 'swift.trans_id' not in req.environ:
# if this wasn't set by an earlier middleware, set it now
trans_id = 'tx' + uuid.uuid4().hex
req.environ['swift.trans_id'] = trans_id
self.logger.txn_id = trans_id
req.headers['x-trans-id'] = req.environ['swift.trans_id']
controller.trans_id = req.environ['swift.trans_id']
self.logger.client_ip = get_remote_client(req)
try:
if req.GET.get('op'):
req.method = req.GET.get('op')
handler = getattr(controller, req.method)
getattr(handler, 'publicly_accessible')
except AttributeError:
return HTTPMethodNotAllowed(request=req)
if path_parts['version']:
req.path_info_pop()
req.environ['swift.orig_req_method'] = req.method
return handler(req)
except (Exception, Timeout):
self.logger.exception(_('ERROR Unhandled exception in request'))
return jresponse('-1','ServerERROR',req,500)
示例3: _authorize_unconfirmed_identity
def _authorize_unconfirmed_identity(self, req, obj, referrers, roles):
""""
Perform authorization for access that does not require a
confirmed identity.
:returns: A boolean if authorization is granted or denied. None if
a determination could not be made.
"""
# Allow container sync.
if (req.environ.get('swift_sync_key')
and req.environ['swift_sync_key'] ==
req.headers.get('x-container-sync-key', None)
and 'x-timestamp' in req.headers
and (req.remote_addr in self.allowed_sync_hosts
or swift_utils.get_remote_client(req)
in self.allowed_sync_hosts)):
log_msg = 'allowing proxy %s for container-sync' % req.remote_addr
self.logger.debug(log_msg)
return True
# Check if referrer is allowed.
if swift_acl.referrer_allowed(req.referer, referrers):
if obj or '.rlistings' in roles:
log_msg = 'authorizing %s via referer ACL' % req.referrer
self.logger.debug(log_msg)
return True
return False
示例4: log_request
def log_request(self, req, status_int, bytes_received, bytes_sent,
request_time):
"""
Log a request.
:param req: swob.Request object for the request
:param status_int: integer code for the response status
:param bytes_received: bytes successfully read from the request body
:param bytes_sent: bytes yielded to the WSGI server
:param request_time: time taken to satisfy the request, in seconds
"""
if self.req_already_logged(req):
return
req_path = get_valid_utf8_str(req.path)
the_request = quote(unquote(req_path), QUOTE_SAFE)
if req.query_string:
the_request = the_request + '?' + req.query_string
logged_headers = None
if self.log_hdrs:
logged_headers = '\n'.join('%s: %s' % (k, v)
for k, v in req.headers.items())
method = self.method_from_req(req)
self.access_logger.info(' '.join(
quote(str(x) if x else '-', QUOTE_SAFE)
for x in (
get_remote_client(req),
req.remote_addr,
time.strftime('%d/%b/%Y/%H/%M/%S', time.gmtime()),
method,
the_request,
req.environ.get('SERVER_PROTOCOL'),
status_int,
req.referer,
req.user_agent,
self.obscure_sensitive(req.headers.get('x-auth-token')),
bytes_received,
bytes_sent,
req.headers.get('etag', None),
req.environ.get('swift.trans_id'),
logged_headers,
'%.4f' % request_time,
req.environ.get('swift.source'),
','.join(req.environ.get('swift.log_info') or ''),
)))
self.mark_req_logged(req)
# Log timing and bytes-transfered data to StatsD
metric_name = self.statsd_metric_name(req, status_int, method)
# Only log data for valid controllers (or SOS) to keep the metric count
# down (egregious errors will get logged by the proxy server itself).
if metric_name:
self.access_logger.timing(metric_name + '.timing',
request_time * 1000)
self.access_logger.update_stats(metric_name + '.xfer',
bytes_received + bytes_sent)
示例5: __call__
def __call__(self, env, start_response):
req = Request(env)
if req.method in self.verb_acl:
remote = get_remote_client(req)
for block in self.verb_acl[req.method]:
if remote.startswith(block):
break
else:
raise HTTPForbidden(request=req,
body='Forbidden method for %s' % remote)
return self.app(env, start_response)
示例6: authorize
def authorize(self, req):
env = req.environ
identity = env.get("cloudstack.identity", {})
try:
version, _account, container, obj = split_path(req.path, minsegs=1, maxsegs=4, rest_with_last=True)
except ValueError:
return HTTPNotFound(request=req)
if not _account or not _account.startswith(self.reseller_prefix):
return self.denied_response(req)
# Remove the reseller_prefix from the account.
if self.reseller_prefix != "":
account = _account[len(self.reseller_prefix) + 1 :]
else:
account = _account
user_roles = identity.get("roles", [])
# If this user is part of this account or is the global admin, give access.
if account == identity.get("account") or self.cs_roles[1] in user_roles:
req.environ["swift_owner"] = True
return None
# Allow container sync
if (
req.environ.get("swift_sync_key")
and req.environ["swift_sync_key"] == req.headers.get("x-container-sync-key", None)
and "x-timestamp" in req.headers
and (req.remote_addr in self.allowed_sync_hosts or get_remote_client(req) in self.allowed_sync_hosts)
):
self.logger.debug("Allowing container-sync")
return None
# Check if Referrer allow it
referrers, groups = parse_acl(getattr(req, "acl", None))
if referrer_allowed(req.referer, referrers):
if obj or ".rlistings" in groups:
self.logger.debug("Authorizing via ACL")
return None
return self.denied_response(req)
# Check if we have the group in the user_roles and allow if we do
for role in user_roles:
if role in groups:
self.logger.debug("User has role %s, allowing via ACL" % (role))
return None
# This user is not authorized, deny request.
return self.denied_response(req)
示例7: authorize
def authorize(self, req):
"""
Returns None if the request is authorized to continue or a standard
WSGI response callable if not.
"""
try:
version, account, container, obj = split_path(req.path, 1, 4, True)
except ValueError:
self.logger.increment('errors')
return HTTPNotFound(request=req)
if not account or not account.startswith(self.reseller_prefix):
return self.denied_response(req)
user_groups = (req.remote_user or '').split(',')
if '.reseller_admin' in user_groups and \
account != self.reseller_prefix and \
account[len(self.reseller_prefix)] != '.':
req.environ['swift_owner'] = True
return None
if account in user_groups and \
(req.method not in ('DELETE', 'PUT') or container):
# If the user is admin for the account and is not trying to do an
# account DELETE or PUT...
req.environ['swift_owner'] = True
return None
if (req.environ.get('swift_sync_key') and
req.environ['swift_sync_key'] ==
req.headers.get('x-container-sync-key', None) and
'x-timestamp' in req.headers and
(req.remote_addr in self.allowed_sync_hosts or
get_remote_client(req) in self.allowed_sync_hosts)):
return None
if req.method == 'OPTIONS':
#allow OPTIONS requests to proceed as normal
return None
referrers, groups = parse_acl(getattr(req, 'acl', None))
if referrer_allowed(req.referer, referrers):
if obj or '.rlistings' in groups:
return None
return self.denied_response(req)
if not req.remote_user:
return self.denied_response(req)
for user_group in user_groups:
if user_group in groups:
return None
return self.denied_response(req)
示例8: authorize
def authorize(self, req):
env = req.environ
env_identity = env.get('keystone.identity', {})
tenant = env_identity.get('tenant')
try:
version, account, container, obj = split_path(req.path, 1, 4, True)
except ValueError:
return HTTPNotFound(request=req)
if account != '%s_%s' % (self.reseller_prefix, tenant):
self.logger.debug('tenant mismatch: %s != %s_%s' % \
(account, self.reseller_prefix, tenant))
return self.denied_response(req)
user_groups = env_identity.get('roles', [])
#TODO: setting?
if self.keystone_admin_group in user_groups:
req.environ['swift_owner'] = True
return None
if (req.environ.get('swift_sync_key') and
req.environ['swift_sync_key'] ==
req.headers.get('x-container-sync-key', None) and
'x-timestamp' in req.headers and
(req.remote_addr in self.allowed_sync_hosts or
get_remote_client(req) in self.allowed_sync_hosts)):
self.logger.debug('allowing container-sync')
return None
# Check if Referrer allow it #TODO: check if it works
referrers, groups = parse_acl(getattr(req, 'acl', None))
if referrer_allowed(req.referer, referrers):
if obj or '.rlistings' in groups:
self.logger.debug('authorizing via ACL')
return None
return self.denied_response(req)
# Check if we have the group in the group user and allow it
for user_group in user_groups:
if user_group in groups:
self.logger.debug('user in group: %s authorizing' % \
(user_group))
return None
return self.denied_response(req)
示例9: log_request
def log_request(self, env, status_int, bytes_received, bytes_sent, request_time, client_disconnect):
"""
Log a request.
:param env: WSGI environment
:param status_int: integer code for the response status
:param bytes_received: bytes successfully read from the request body
:param bytes_sent: bytes yielded to the WSGI server
:param request_time: time taken to satisfy the request, in seconds
"""
req = Request(env)
if client_disconnect: # log disconnected clients as '499' status code
status_int = 499
req_path = get_valid_utf8_str(req.path)
the_request = quote(unquote(req_path))
if req.query_string:
the_request = the_request + "?" + req.query_string
logged_headers = None
if self.log_hdrs:
logged_headers = "\n".join("%s: %s" % (k, v) for k, v in req.headers.items())
self.access_logger.info(
" ".join(
quote(str(x) if x else "-")
for x in (
get_remote_client(req),
req.remote_addr,
time.strftime("%d/%b/%Y/%H/%M/%S", time.gmtime()),
req.method,
the_request,
req.environ.get("SERVER_PROTOCOL"),
status_int,
req.referer,
req.user_agent,
req.headers.get("x-auth-token"),
bytes_received,
bytes_sent,
req.headers.get("etag", None),
req.environ.get("swift.trans_id"),
logged_headers,
"%.4f" % request_time,
req.environ.get("swift.source"),
)
)
)
self.access_logger.txn_id = None
示例10: log_request
def log_request(self, env, status_int, bytes_received, bytes_sent,
request_time, client_disconnect):
"""
Log a request.
:param env: WSGI environment
:param status_int: integer code for the response status
:param bytes_received: bytes successfully read from the request body
:param bytes_sent: bytes yielded to the WSGI server
:param request_time: time taken to satisfy the request, in seconds
"""
req = Request(env)
if client_disconnect: # log disconnected clients as '499' status code
status_int = 499
the_request = quote(unquote(req.path))
if req.query_string:
the_request = the_request + '?' + req.query_string
logged_headers = None
if self.log_hdrs:
logged_headers = '\n'.join('%s: %s' % (k, v)
for k, v in req.headers.items())
self.access_logger.info(' '.join(quote(str(x) if x else '-')
for x in (
get_remote_client(req),
req.remote_addr,
time.strftime('%d/%b/%Y/%H/%M/%S', time.gmtime()),
req.method,
the_request,
req.environ.get('SERVER_PROTOCOL'),
status_int,
req.referer,
req.user_agent,
req.headers.get('x-auth-token'),
bytes_received,
bytes_sent,
req.headers.get('etag', None),
req.environ.get('swift.trans_id'),
logged_headers,
'%.4f' % request_time,
req.environ.get('swift.source'),
)))
self.access_logger.txn_id = None
示例11: handle_request
def handle_request(self, req):
"""
Entry point for proxy server.
Should return a WSGI-style callable (such as swob.Response).
:param req: swob.Request object
"""
try:
self.logger.set_statsd_prefix("proxy-server")
if req.content_length and req.content_length < 0:
self.logger.increment("errors")
return HTTPBadRequest(request=req, body="Invalid Content-Length")
try:
if not check_utf8(req.path_info):
self.logger.increment("errors")
return HTTPPreconditionFailed(request=req, body="Invalid UTF8 or contains NULL")
except UnicodeError:
self.logger.increment("errors")
return HTTPPreconditionFailed(request=req, body="Invalid UTF8 or contains NULL")
try:
controller, path_parts = self.get_controller(req)
p = req.path_info
if isinstance(p, six.text_type):
p = p.encode("utf-8")
except APIVersionError:
self.logger.increment("errors")
return HTTPBadRequest(request=req)
except ValueError:
self.logger.increment("errors")
return HTTPNotFound(request=req)
if not controller:
self.logger.increment("errors")
return HTTPPreconditionFailed(request=req, body="Bad URL")
if self.deny_host_headers and req.host.split(":")[0] in self.deny_host_headers:
return HTTPForbidden(request=req, body="Invalid host header")
self.logger.set_statsd_prefix("proxy-server." + controller.server_type.lower())
controller = controller(self, **path_parts)
if "swift.trans_id" not in req.environ:
# if this wasn't set by an earlier middleware, set it now
trans_id_suffix = self.trans_id_suffix
trans_id_extra = req.headers.get("x-trans-id-extra")
if trans_id_extra:
trans_id_suffix += "-" + trans_id_extra[:32]
trans_id = generate_trans_id(trans_id_suffix)
req.environ["swift.trans_id"] = trans_id
self.logger.txn_id = trans_id
req.headers["x-trans-id"] = req.environ["swift.trans_id"]
controller.trans_id = req.environ["swift.trans_id"]
self.logger.client_ip = get_remote_client(req)
try:
handler = getattr(controller, req.method)
getattr(handler, "publicly_accessible")
except AttributeError:
allowed_methods = getattr(controller, "allowed_methods", set())
return HTTPMethodNotAllowed(request=req, headers={"Allow": ", ".join(allowed_methods)})
old_authorize = None
if "swift.authorize" in req.environ:
# We call authorize before the handler, always. If authorized,
# we remove the swift.authorize hook so isn't ever called
# again. If not authorized, we return the denial unless the
# controller's method indicates it'd like to gather more
# information and try again later.
resp = req.environ["swift.authorize"](req)
if (
not resp
and not req.headers.get("X-Copy-From-Account")
and not req.headers.get("Destination-Account")
):
# No resp means authorized, no delayed recheck required.
old_authorize = req.environ["swift.authorize"]
else:
# Response indicates denial, but we might delay the denial
# and recheck later. If not delayed, return the error now.
if not getattr(handler, "delay_denial", None):
return resp
# Save off original request method (GET, POST, etc.) in case it
# gets mutated during handling. This way logging can display the
# method the client actually sent.
req.environ["swift.orig_req_method"] = req.method
try:
if old_authorize:
req.environ.pop("swift.authorize", None)
return handler(req)
finally:
if old_authorize:
req.environ["swift.authorize"] = old_authorize
except HTTPException as error_response:
return error_response
except (Exception, Timeout):
self.logger.exception(_("ERROR Unhandled exception in request"))
return HTTPServerError(request=req)
示例12: handle_request
def handle_request(self, req):
"""
Entry point for proxy server.
Should return a WSGI-style callable (such as swob.Response).
:param req: swob.Request object
"""
try:
#设置日志的前缀为proxy-server
self.logger.set_statsd_prefix('proxy-server')
#如果请求长度为负数,报错
if req.content_length and req.content_length < 0:
self.logger.increment('errors')
return HTTPBadRequest(request=req,
body='Invalid Content-Length')
try:
#如果路径信息不是有效的utf-8编码,报错
if not check_utf8(req.path_info):
self.logger.increment('errors')
return HTTPPreconditionFailed(
request=req, body='Invalid UTF8 or contains NULL')
except UnicodeError:
#解码utf-8失败,报错
self.logger.increment('errors')
return HTTPPreconditionFailed(
request=req, body='Invalid UTF8 or contains NULL')
try:
#1、根据请求的路径信息,获取对应的控制器对象,并返回路径字典
controller, path_parts = self.get_controller(req)
p = req.path_info
if isinstance(p, six.text_type):
p = p.encode('utf-8')
except APIVersionError:
self.logger.increment('errors')
return HTTPBadRequest(request=req)
except ValueError:
self.logger.increment('errors')
return HTTPNotFound(request=req)
if not controller:
self.logger.increment('errors')
return HTTPPreconditionFailed(request=req, body='Bad URL')
if self.deny_host_headers and \
req.host.split(':')[0] in self.deny_host_headers:
return HTTPForbidden(request=req, body='Invalid host header')
self.logger.set_statsd_prefix('proxy-server.' +
controller.server_type.lower())
#2、生成控制器对象
controller = controller(self, **path_parts)
#如果没有在请求的env中设置swift.trans_id,那么现在设置
if 'swift.trans_id' not in req.environ:
# if this wasn't set by an earlier middleware, set it now
trans_id_suffix = self.trans_id_suffix
trans_id_extra = req.headers.get('x-trans-id-extra')
if trans_id_extra:
trans_id_suffix += '-' + trans_id_extra[:32]
trans_id = generate_trans_id(trans_id_suffix)
req.environ['swift.trans_id'] = trans_id
self.logger.txn_id = trans_id
req.headers['x-trans-id'] = req.environ['swift.trans_id']
controller.trans_id = req.environ['swift.trans_id']
self.logger.client_ip = get_remote_client(req)
try:
#3、根据请求方法,获取对应的函数指针handler
handler = getattr(controller, req.method)
getattr(handler, 'publicly_accessible')
except AttributeError:
allowed_methods = getattr(controller, 'allowed_methods', set())
return HTTPMethodNotAllowed(
request=req, headers={'Allow': ', '.join(allowed_methods)})
old_authorize = None
#4、如果请求的env中有鉴权方法,调用该鉴权方法,进行鉴权
if 'swift.authorize' in req.environ:
# We call authorize before the handler, always. If authorized,
# we remove the swift.authorize hook so isn't ever called
# again. If not authorized, we return the denial unless the
# controller's method indicates it'd like to gather more
# information and try again later.
resp = req.environ['swift.authorize'](req)
if not resp and not req.headers.get('X-Copy-From-Account') \
and not req.headers.get('Destination-Account'):
# No resp means authorized, no delayed recheck required.
old_authorize = req.environ['swift.authorize']
else:
# 返回resp代表鉴权失败,但是我们可能延迟后重新检查,如果没有设置延迟检查,则返回失败
# Response indicates denial, but we might delay the denial
# and recheck later. If not delayed, return the error now.
if not getattr(handler, 'delay_denial', None):
return resp
# Save off original request method (GET, POST, etc.) in case it
# gets mutated during handling. This way logging can display the
# method the client actually sent.
req.environ['swift.orig_req_method'] = req.method
try:
#将鉴权方法从请求的env中取出,以免后续再次调用
if old_authorize:
req.environ.pop('swift.authorize', None)
#5、调用处理请求的方法,处理请求
#.........这里部分代码省略.........
示例13: handle_request
def handle_request(self, req):
"""
Entry point for proxy server.
Should return a WSGI-style callable (such as webob.Response).
:param req: webob.Request object
"""
try:
self.logger.set_statsd_prefix('proxy-server')
if req.content_length and req.content_length < 0:
self.logger.increment('errors')
return HTTPBadRequest(request=req,
body='Invalid Content-Length')
try:
if not check_utf8(req.path_info):
self.logger.increment('errors')
return HTTPPreconditionFailed(request=req,
body='Invalid UTF8')
except UnicodeError:
self.logger.increment('errors')
return HTTPPreconditionFailed(request=req, body='Invalid UTF8')
try:
controller, path_parts = self.get_controller(req.path)
p = req.path_info
if isinstance(p, unicode):
p = p.encode('utf-8')
except ValueError:
self.logger.increment('errors')
return HTTPNotFound(request=req)
if not controller:
self.logger.increment('errors')
return HTTPPreconditionFailed(request=req, body='Bad URL')
if self.deny_host_headers and \
req.host.split(':')[0] in self.deny_host_headers:
return HTTPForbidden(request=req, body='Invalid host header')
self.logger.set_statsd_prefix('proxy-server.' +
controller.server_type)
controller = controller(self, **path_parts)
if 'swift.trans_id' not in req.environ:
# if this wasn't set by an earlier middleware, set it now
trans_id = 'tx' + uuid.uuid4().hex
req.environ['swift.trans_id'] = trans_id
self.logger.txn_id = trans_id
req.headers['x-trans-id'] = req.environ['swift.trans_id']
controller.trans_id = req.environ['swift.trans_id']
self.logger.client_ip = get_remote_client(req)
try:
handler = getattr(controller, req.method)
getattr(handler, 'publicly_accessible')
except AttributeError:
self.logger.increment('method_not_allowed')
return HTTPMethodNotAllowed(request=req)
if path_parts['version']:
req.path_info_pop()
if 'swift.authorize' in req.environ:
# We call authorize before the handler, always. If authorized,
# we remove the swift.authorize hook so isn't ever called
# again. If not authorized, we return the denial unless the
# controller's method indicates it'd like to gather more
# information and try again later.
resp = req.environ['swift.authorize'](req)
if not resp:
# No resp means authorized, no delayed recheck required.
del req.environ['swift.authorize']
else:
# Response indicates denial, but we might delay the denial
# and recheck later. If not delayed, return the error now.
if not getattr(handler, 'delay_denial', None):
self.logger.increment('auth_short_circuits')
return resp
return handler(req)
except (Exception, Timeout):
self.logger.exception(_('ERROR Unhandled exception in request'))
return HTTPServerError(request=req)
示例14: authorize
def authorize(self, req):
env = req.environ
identity = env.get('cloudstack.identity', {})
try:
version, _account, container, obj = split_path(req.path, minsegs=1, maxsegs=4, rest_with_last=True)
except ValueError:
return HTTPNotFound(request=req)
if not _account or not _account.startswith(self.reseller_prefix):
return self.denied_response(req)
# Remove the reseller_prefix from the account.
if self.reseller_prefix != '':
account = _account[len(self.reseller_prefix)+1:]
else:
account = _account
user_roles = identity.get('roles', [])
# If this user is part of this account or is the global admin, give access.
if account == identity.get('account') or self.cs_roles[1] in user_roles:
req.environ['swift_owner'] = True
self.logger.debug("User %s is global admin or owner, authorizing" % identity.get('username'))
return None
# Allow container sync
if (req.environ.get('swift_sync_key') and req.environ['swift_sync_key'] == req.headers.get('x-container-sync-key', None) and
'x-timestamp' in req.headers and (req.remote_addr in self.allowed_sync_hosts or get_remote_client(req) in self.allowed_sync_hosts)):
self.logger.debug('Allowing container-sync')
return None
if req.method == 'OPTIONS':
#allow OPTIONS requests to proceed as normal
self.logger.debug("Allow OPTIONS request.")
return None
# Check if Referrer allow it
referrers, groups = parse_acl(getattr(req, 'acl', None))
if referrer_allowed(req.referer, referrers):
if obj or '.rlistings' in groups:
self.logger.debug('Authorizing via ACL')
return None
return self.denied_response(req)
# Check if we have the group in the user_roles and allow if we do
for role in user_roles:
if role in groups:
self.logger.debug('User has role %s, allowing via ACL' % (role))
return None
# This user is not authorized, deny request.
return self.denied_response(req)
示例15: log_request
def log_request(self, env, status_int, bytes_received, bytes_sent, request_time, client_disconnect):
"""
Log a request.
:param env: WSGI environment
:param status_int: integer code for the response status
:param bytes_received: bytes successfully read from the request body
:param bytes_sent: bytes yielded to the WSGI server
:param request_time: time taken to satisfy the request, in seconds
"""
if env.get("swift.proxy_access_log_made"):
return
req = Request(env)
if client_disconnect: # log disconnected clients as '499' status code
status_int = 499
req_path = get_valid_utf8_str(req.path)
the_request = quote(unquote(req_path))
if req.query_string:
the_request = the_request + "?" + req.query_string
logged_headers = None
if self.log_hdrs:
logged_headers = "\n".join("%s: %s" % (k, v) for k, v in req.headers.items())
method = req.environ.get("swift.orig_req_method", req.method)
self.access_logger.info(
" ".join(
quote(str(x) if x else "-")
for x in (
get_remote_client(req),
req.remote_addr,
time.strftime("%d/%b/%Y/%H/%M/%S", time.gmtime()),
method,
the_request,
req.environ.get("SERVER_PROTOCOL"),
status_int,
req.referer,
req.user_agent,
req.headers.get("x-auth-token"),
bytes_received,
bytes_sent,
req.headers.get("etag", None),
req.environ.get("swift.trans_id"),
logged_headers,
"%.4f" % request_time,
req.environ.get("swift.source"),
)
)
)
env["swift.proxy_access_log_made"] = True
# Log timing and bytes-transfered data to StatsD
if req.path.startswith("/v1/"):
try:
stat_type = [None, "account", "container", "object"][req.path.strip("/").count("/")]
except IndexError:
stat_type = "object"
else:
stat_type = env.get("swift.source")
# Only log data for valid controllers (or SOS) to keep the metric count
# down (egregious errors will get logged by the proxy server itself).
if stat_type:
stat_method = method if method in self.valid_methods else "BAD_METHOD"
metric_name = ".".join((stat_type, stat_method, str(status_int)))
self.access_logger.timing(metric_name + ".timing", request_time * 1000)
self.access_logger.update_stats(metric_name + ".xfer", bytes_received + bytes_sent)