本文整理汇总了Python中swift.common.utils.get_remote_client函数的典型用法代码示例。如果您正苦于以下问题:Python get_remote_client函数的具体用法?Python get_remote_client怎么用?Python get_remote_client使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_remote_client函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:mdegerne,项目名称:swift-keystone2,代码行数:60,代码来源:middleware.py
示例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)
开发者ID:sun3shines,项目名称:swift-1.7.4,代码行数:60,代码来源:server.py
示例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
开发者ID:a3linux,项目名称:swift,代码行数:27,代码来源:keystoneauth.py
示例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)
开发者ID:morucci,项目名称:swift,代码行数:54,代码来源:proxy_logging.py
示例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)
开发者ID:jfsmig,项目名称:oio-swift,代码行数:12,代码来源:verb_acl.py
示例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)
开发者ID:cloudops,项目名称:cs_auth,代码行数:51,代码来源:middleware.py
示例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)
开发者ID:mohitsethi,项目名称:swift,代码行数:46,代码来源:tempauth.py
示例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)
开发者ID:chmouel,项目名称:swift-keystone2,代码行数:46,代码来源:middleware.py
示例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
开发者ID:ngtuna,项目名称:swift,代码行数:45,代码来源:proxy_logging.py
示例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
开发者ID:bhuvan,项目名称:swift,代码行数:42,代码来源:proxy_logging.py
示例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)
开发者ID:harrisonfeng,项目名称:swift,代码行数:94,代码来源:server.py
示例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、调用处理请求的方法,处理请求
#.........这里部分代码省略.........
开发者ID:revoer,项目名称:keystone-8.0.0,代码行数:101,代码来源:server.py
示例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)
开发者ID:andrewgaul,项目名称:swift,代码行数:77,代码来源:server.py
示例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)
开发者ID:cldmnky,项目名称:cs_auth,代码行数:53,代码来源:middleware.py
示例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)
开发者ID:WIZARD-CXY,项目名称:swift,代码行数:63,代码来源:proxy_logging.py
示例16: authorize
def authorize(self, req):
env = req.environ
env_identity = env.get('keystone.identity', {})
tenant = env_identity.get('tenant')
try:
part = swift_utils.split_path(req.path, 1, 4, True)
version, account, container, obj = part
except ValueError:
return webob.exc.HTTPNotFound(request=req)
user_roles = env_identity.get('roles', [])
# Give unconditional access to a user with the reseller_admin
# role.
if self.reseller_admin_role in user_roles:
msg = 'User %s has reseller admin authorizing'
self.logger.debug(msg % tenant[0])
req.environ['swift_owner'] = True
return
# Check if a user tries to access an account that does not match their
# token
if not self._reseller_check(account, tenant[0]):
log_msg = 'tenant mismatch: %s != %s' % (account, tenant[0])
self.logger.debug(log_msg)
return self.denied_response(req)
# Check the roles the user is belonging to. If the user is
# part of the role defined in the config variable
# operator_roles (like admin) then it will be
# promoted as an admin of the account/tenant.
for role in self.operator_roles.split(','):
role = role.strip()
if role in user_roles:
log_msg = 'allow user with role %s as account admin' % (role)
self.logger.debug(log_msg)
req.environ['swift_owner'] = True
return
# If user is of the same name of the tenant then make owner of it.
user = env_identity.get('user', '')
if self.is_admin and user == tenant[1]:
req.environ['swift_owner'] = True
return
# 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
# Check if referrer is allowed.
referrers, roles = swift_acl.parse_acl(getattr(req, 'acl', None))
if swift_acl.referrer_allowed(req.referer, referrers):
#TODO(chmou): convert .rlistings to Keystone type role.
if obj or '.rlistings' in roles:
log_msg = 'authorizing %s via referer ACL' % req.referrer
self.logger.debug(log_msg)
return
return self.denied_response(req)
# Allow ACL at individual user level (tenant:user fo
|
请发表评论