Exemplo n.º 1
0
    def _check_auth(self, req, tenant=None):
        auth = req.headers.get('Authorization', None)
        if auth is None:
            raise exc.HTTPUnauthorized(explanation='Bad credentials')

        auth_info = auth.split(' ')[1]
        auth_decoded = base64.b64decode(auth_info)
        user = auth_decoded.split(':')[0]
        password = auth_decoded.split(':')[1]
        if tenant:
            keystone = keystone_auth.authenticate(user, password, tenant)
        else:
            keystone = keystone_auth.authenticate(user, password)
        return (user, password, keystone)
Exemplo n.º 2
0
    def process_request(self, req):
        """Get keystone token for external request

        This middleware is used for external requests. It get credentials from
        request and try to get keystone token for further authorization.

        :param req: wsgi request object that will be given the context object
        """
        try:
            credentials = base64.b64decode(
                req.headers['Authorization'].split(' ')[1])
            user, password = credentials.decode('utf-8').split(':', 2)
            req.headers['X-Auth-Token'] = self.get_keystone_token(
                user, password)
            req.endpoints = self.get_endpoints()
        except KeyError:
            msg = _("Authorization required")
            LOG.warning(msg)
            raise exc.HTTPUnauthorized(explanation=msg)
        except exceptions.Unauthorized:
            msg = _("Your credentials are wrong. Please try again")
            LOG.warning(msg)
            raise exc.HTTPUnauthorized(explanation=msg)
Exemplo n.º 3
0
    def __inner(self, request, environment_id, *args, **kwargs):
        unit = db_session.get_session()
        environment = unit.query(models.Environment).get(environment_id)
        if environment is None:
            LOG.info(_("Environment with id '{0}'"
                       " not found").format(environment_id))
            raise exc.HTTPNotFound()

        if hasattr(request, 'context'):
            if environment.tenant_id != request.context.tenant:
                LOG.info(_('User is not authorized to access'
                           ' this tenant resources'))
                raise exc.HTTPUnauthorized()

        return func(self, request, environment_id, *args, **kwargs)
Exemplo n.º 4
0
    def _check_environment(self, request, environment_id):
        unit = db_session.get_session()
        environment = unit.query(models.Environment).get(environment_id)

        if environment is None:
            msg = _('Environment <EnvId {0}>'
                    ' is not found').format(environment_id)
            LOG.error(msg)
            raise exc.HTTPNotFound(explanation=msg)

        if environment.tenant_id != request.context.tenant:
            msg = _('User is not authorized to access '
                    'this tenant resources.')
            LOG.error(msg)
            raise exc.HTTPUnauthorized(explanation=msg)
def login(ctx, request:FanteWeb.Request):
    print(request)
    print(request.json)
    payload = request.json

    # 用户email验证
    email = payload.get('email')
    user = session.query(User).filter(User.email == email).first()
    if user and bcrypt.checkpw(payload['password'].encode(), user.password.encode()):
        return jsonify(user={
            'id':user.id,
            'name':user.name
        }, token=gen_token(user.id))
    else:
        raise exc.HTTPUnauthorized()
Exemplo n.º 6
0
    def add_member(self, req, image_id, member, body=None):
        """
        Adds a membership to the image, or updates an existing one.
        If a body is present, it is a dict with the following format::

            {"member": {
                "can_share": [True|False]
            }}

        If "can_share" is provided, the member's ability to share is
        set accordingly.  If it is not provided, existing memberships
        remain unchanged and new memberships default to False.
        """
        if req.context.read_only:
            raise exc.HTTPForbidden()
        elif req.context.owner is None:
            raise exc.HTTPUnauthorized(_("No authenticated user"))

        # Make sure the image exists
        try:
            image = db_api.image_get(req.context, image_id)
        except exception.NotFound:
            raise exc.HTTPNotFound()
        except exception.NotAuthorized:
            # If it's private and doesn't belong to them, don't let on
            # that it exists
            msg = _("Access by %(user)s to image %(id)s "
                    "denied") % ({
                        'user': req.context.user,
                        'id': image_id
                    })
            logger.info(msg)
            raise exc.HTTPNotFound()

        # Can they manipulate the membership?
        if not req.context.is_image_sharable(image):
            raise exc.HTTPForbidden(_("No permission to share that image"))

        # Determine the applicable can_share value
        can_share = None
        if body:
            try:
                can_share = bool(body['member']['can_share'])
            except Exception, e:
                # Malformed entity...
                msg = _("Invalid membership association: %s") % e
                raise exc.HTTPBadRequest(explanation=msg)
Exemplo n.º 7
0
    def _exchange(rej, res):
        if req.params.has_key('error'):
            # if request has 'error' param, reject with Unauthorized error (401)
            # note I'm not sure about using this response
            #
            comment = req.params.get('error_description',
                                     req.params.get('error', ''))
            rej(exc.HTTPUnauthorized(comment=comment))

        else:
            # otherwise, resolve to credentials of OAuth exchange (step 2 of dance)
            #
            try:
                flow = webserver_flow(params, req, {})
                res(flow.step2_exchange(req.params))
            except Exception as e:
                rej(err.wrap(e))
Exemplo n.º 8
0
 def _authenticate(self):
     bearer_token_prefix = 'Bearer '
     auth = request.headers.get('Authorization')
     if auth and auth.startswith(bearer_token_prefix):
         access_token = auth[len(bearer_token_prefix):]
     else:
         access_token = request.params.get('access_token')
     if access_token:
         # handle bearer tokens
         # skip https check if auth invoked from tests
         testing = request.environ.get('paste.testing', False)
         debug = asbool(config.get('debug', False))
         if not any((testing,
                     request.scheme == 'https',
                     request.environ.get('HTTP_X_FORWARDED_SSL') == 'on',
                     request.environ.get('HTTP_X_FORWARDED_PROTO') == 'https',
                     debug)):
             request.environ['tg.status_code_redirect'] = True
             raise exc.HTTPUnauthorized('HTTPS is required to use bearer tokens %s' % request.environ)
         access_token = M.OAuthAccessToken.query.get(api_key=access_token)
         if not (access_token and access_token.is_bearer):
             request.environ['tg.status_code_redirect'] = True
             raise exc.HTTPUnauthorized
         return access_token
     req = oauth.Request.from_request(
         request.method,
         request.url.split('?')[0],
         headers=request.headers,
         parameters=dict(request.params),
         query_string=request.query_string
     )
     consumer_token = M.OAuthConsumerToken.query.get(api_key=req['oauth_consumer_key'])
     access_token = M.OAuthAccessToken.query.get(api_key=req['oauth_token'])
     if consumer_token is None:
         log.error('Invalid consumer token')
         return None
     if access_token is None:
         log.error('Invalid access token')
         raise exc.HTTPUnauthorized
     consumer = consumer_token.consumer
     try:
         self.server.verify_request(req, consumer, access_token.as_token())
     except oauth.Error as e:
         log.error('Invalid signature %s %s', type(e), e)
         raise exc.HTTPUnauthorized
     return access_token
Exemplo n.º 9
0
    def __inner(self, request, env_template_id, *args, **kwargs):
        unit = db_session.get_session()
        template = unit.query(models.EnvironmentTemplate).get(env_template_id)
        if template is None:
            LOG.error(
                _LE("Environment Template with id '{id}' not found").format(
                    id=env_template_id))
            raise exc.HTTPNotFound()

        if hasattr(request, 'context'):
            if template.tenant_id != request.context.tenant:
                LOG.error(
                    _LE('User is not authorized to access '
                        'this tenant resources'))
                raise exc.HTTPUnauthorized()

        return func(self, request, env_template_id, *args, **kwargs)
Exemplo n.º 10
0
    def delete_member(self, req, image_id, member):
        """
        Removes a membership from the image.
        """
        if req.context.read_only:
            raise exc.HTTPForbidden()
        elif req.context.owner is None:
            raise exc.HTTPUnauthorized(_("No authenticated user"))

        # Make sure the image exists
        try:
            image = db_api.image_get(req.context, image_id)
        except exception.NotFound:
            raise exc.HTTPNotFound()
        except exception.NotAuthorized:
            # If it's private and doesn't belong to them, don't let on
            # that it exists
            msg = _("Access by %(user)s to image %(id)s "
                    "denied") % ({
                        'user': req.context.user,
                        'id': image_id
                    })
            logger.info(msg)
            raise exc.HTTPNotFound()

        # Can they manipulate the membership?
        if not req.context.is_image_sharable(image):
            raise exc.HTTPForbidden(_("No permission to share that image"))

        # Look up an existing membership
        try:
            session = db_api.get_session()
            member_ref = db_api.image_member_find(req.context,
                                                  image_id,
                                                  member,
                                                  session=session)
            db_api.image_member_delete(req.context,
                                       member_ref,
                                       session=session)
        except exception.NotFound:
            pass

        # Make an appropriate result
        return exc.HTTPNoContent()
Exemplo n.º 11
0
    def replace_members(self, req, image_id, body):
        """
        Replaces the members of the image with those specified in the
        body.  The body is a dict with the following format::

            {"memberships": [
                {"member_id": <MEMBER_ID>,
                 ["can_share": [True|False]]}, ...
            ]}
        """
        if req.context.read_only:
            raise exc.HTTPForbidden()
        elif req.context.owner is None:
            raise exc.HTTPUnauthorized(_("No authenticated user"))

        # Make sure the image exists
        session = db_api.get_session()
        try:
            image = db_api.image_get(req.context, image_id, session=session)
        except exception.NotFound:
            raise exc.HTTPNotFound()
        except exception.NotAuthorized:
            # If it's private and doesn't belong to them, don't let on
            # that it exists
            msg = _("Access by %(user)s to image %(id)s "
                    "denied") % ({
                        'user': req.context.user,
                        'id': image_id
                    })
            logger.info(msg)
            raise exc.HTTPNotFound()

        # Can they manipulate the membership?
        if not req.context.is_image_sharable(image):
            raise exc.HTTPForbidden(_("No permission to share that image"))

        # Get the membership list
        try:
            memb_list = body['memberships']
        except Exception, e:
            # Malformed entity...
            msg = _("Invalid membership association: %s") % e
            raise exc.HTTPBadRequest(explanation=msg)
Exemplo n.º 12
0
def require(predicate, message=None):
    '''
    Example: require(has_access(c.app, 'read'))

    :param callable predicate: truth function to call
    :param str message: message to show upon failure
    :raises: HTTPForbidden or HTTPUnauthorized
    '''

    from allura import model as M
    if predicate(): return
    if not message:
        message = """You don't have permission to do that.
                     You must ask a project administrator for rights to perform this task.
                     Please click the back button to return to the previous page."""
    if c.user != M.User.anonymous():
        request.environ['error_message'] = message
        raise exc.HTTPForbidden(detail=message)
    else:
        raise exc.HTTPUnauthorized()
Exemplo n.º 13
0
    def show(self, request, environment_id, session_id):
        LOG.debug('Session:Show <SessionId: {0}>'.format(session_id))

        unit = db_session.get_session()
        session = unit.query(models.Session).get(session_id)

        self._check_session(environment_id, session, session_id)

        user_id = request.context.user
        msg = _('User <UserId {0}> is not authorized to access session'
                '<SessionId {1}>.').format(user_id, session_id)
        if session.user_id != user_id:
            LOG.error(msg)
            raise exc.HTTPUnauthorized(explanation=msg)

        if not sessions.SessionServices.validate(session):
            msg = _('Session <SessionId {0}> is invalid').format(session_id)
            LOG.error(msg)
            raise exc.HTTPForbidden(explanation=msg)

        return session.to_dict()
Exemplo n.º 14
0
    def _resize(self, req, instance_id, flavor_id, **kwargs):
        """Begin the resize process with given instance/flavor."""
        context = req.environ["nova.context"]
        instance = self._get_server(context, req, instance_id)

        try:
            self.compute_api.resize(context, instance, flavor_id, **kwargs)
        except exception.QuotaError as error:
            raise exc.HTTPForbidden(explanation=error.format_message(),
                                    headers={'Retry-After': 0})
        except exception.FlavorNotFound:
            msg = _("Unable to locate requested flavor.")
            raise exc.HTTPBadRequest(explanation=msg)
        except exception.CannotResizeToSameFlavor:
            msg = _("Resize requires a flavor change.")
            raise exc.HTTPBadRequest(explanation=msg)
        except (exception.CannotResizeDisk,
                exception.AutoDiskConfigDisabledByImage) as e:
            raise exc.HTTPBadRequest(explanation=e.format_message())
        except exception.InstanceIsLocked as e:
            raise exc.HTTPConflict(explanation=e.format_message())
        except exception.InstanceInvalidState as state_error:
            common.raise_http_conflict_for_instance_invalid_state(
                state_error, 'resize', instance_id)
        except exception.ImageNotAuthorized:
            msg = _("You are not authorized to access the image "
                    "the instance was started with.")
            raise exc.HTTPUnauthorized(explanation=msg)
        except exception.ImageNotFound:
            msg = _("Image that the instance was started "
                    "with could not be found.")
            raise exc.HTTPBadRequest(explanation=msg)
        except (exception.NoValidHost,
                exception.AutoDiskConfigDisabledByImage) as e:
            raise exc.HTTPBadRequest(explanation=e.format_message())
        except exception.Invalid:
            msg = _("Invalid instance image.")
            raise exc.HTTPBadRequest(explanation=msg)

        return webob.Response(status_int=202)
    def _deleteFixedIPs(self, req, id, body):
        context = req.environ['nova.context']
        if not authorize(context):
            msg = _('Authorization failed.')
            LOG.error(msg)
            raise exc.HTTPUnauthorized()

        self._check_body(body, 'deleteFixedIPs')

        try:
            net = objects.Network.get_by_uuid(context, id)
            net.delete_fixed_ips(context)
        except exception.NotFound:
            msg = _('Network {net} not found'.format(net=id))
            LOG.error(msg)
            raise exc.HTTPNotFound()
        except exception.FixedIpAlreadyInUse as e:
            msg = _('Cannot delete, fixed ip in use: {e}'.format(e=e))
            LOG.error(msg)
            raise exc.HTTPServerError(detail=msg)

        return Response(status_int=202)
Exemplo n.º 16
0
    def __call__(self, req):
        """Ensures that the requested and token tenants match

        Handle incoming requests by checking tenant info from the
        headers and url ({tenant_id} url attribute), if using v1 or v1.1
        APIs. If using the v2 API, this function will check the token
        tenant and the requested tenent in the headers.

        Pass request downstream on success.
        Reject request if tenant_id from headers is not equal to the
        tenant_id from url or v2 project header.
        """
        path = req.environ['PATH_INFO']
        if path != '/':
            token_tenant = req.environ.get("HTTP_X_TENANT_ID")
            if not token_tenant:
                LOG.warning(_LW("Can't get tenant_id from env"))
                raise ex.HTTPServiceUnavailable()

            try:
                if path.startswith('/v2'):
                    version, rest = strutils.split_path(path, 2, 2, True)
                    requested_tenant = req.headers.get('OpenStack-Project-ID')
                else:

                    version, requested_tenant, rest = strutils.split_path(
                        path, 3, 3, True)
            except ValueError:
                LOG.warning(_LW("Incorrect path: {path}").format(path=path))
                raise ex.HTTPNotFound(_("Incorrect path"))

            if token_tenant != requested_tenant:
                LOG.debug("Unauthorized: token tenant != requested tenant")
                raise ex.HTTPUnauthorized(
                    _('Token tenant != requested tenant'))
        return self.application
Exemplo n.º 17
0
    def _resize(self, req, instance_id, flavor_id, **kwargs):
        """Begin the resize process with given instance/flavor."""
        context = req.environ["nova.context"]
        context.can(server_policies.SERVERS % 'resize')
        instance = self._get_server(context, req, instance_id)

        try:
            self.compute_api.resize(context, instance, flavor_id, **kwargs)
        except exception.InstanceUnknownCell as e:
            raise exc.HTTPNotFound(explanation=e.format_message())
        except exception.QuotaError as error:
            raise exc.HTTPForbidden(
                explanation=error.format_message())
        except exception.InstanceIsLocked as e:
            raise exc.HTTPConflict(explanation=e.format_message())
        except exception.InstanceInvalidState as state_error:
            common.raise_http_conflict_for_instance_invalid_state(state_error,
                    'resize', instance_id)
        except exception.ImageNotAuthorized:
            msg = _("You are not authorized to access the image "
                    "the instance was started with.")
            raise exc.HTTPUnauthorized(explanation=msg)
        except exception.ImageNotFound:
            msg = _("Image that the instance was started "
                    "with could not be found.")
            raise exc.HTTPBadRequest(explanation=msg)
        except (exception.AutoDiskConfigDisabledByImage,
                exception.CannotResizeDisk,
                exception.CannotResizeToSameFlavor,
                exception.FlavorNotFound,
                exception.NoValidHost,
                exception.PciRequestAliasNotDefined) as e:
            raise exc.HTTPBadRequest(explanation=e.format_message())
        except exception.Invalid:
            msg = _("Invalid instance image.")
            raise exc.HTTPBadRequest(explanation=msg)
Exemplo n.º 18
0
def abort_unauthorized(msg=None):
    raise exc.HTTPUnauthorized('Unauthorized - %s' %
                               msg if msg else 'Unauthorized')
Exemplo n.º 19
0
def secure_application(environ, start_response):
    if 'REMOTE_USER' not in environ:
        return exc.HTTPUnauthorized('vomis')(environ, start_response)
    return application(environ, start_response)
Exemplo n.º 20
0
    def _http_request(self,
                      method,
                      url,
                      headers,
                      body,
                      ignore_result_body=False):
        """Perform an HTTP request against the server.

        method: the HTTP method to use
        url: the URL to request (not including server portion)
        headers: headers for the request
        body: body to send with the request
        ignore_result_body: the body of the result will be ignored

        Returns: a http_client response object
        """
        if self.auth_token:
            headers.setdefault('x-auth-token', self.auth_token)

        LOG.debug(
            'Request: %(method)s http://%(server)s:%(port)s'
            '%(url)s with headers %(headers)s', {
                'method': method,
                'server': self.conn.host,
                'port': self.conn.port,
                'url': url,
                'headers': repr(headers)
            })
        self.conn.request(method, url, body, headers)

        response = self.conn.getresponse()
        headers = self._header_list_to_dict(response.getheaders())
        code = response.status
        code_description = http_client.responses[code]
        LOG.debug('Response: %(code)s %(status)s %(headers)s', {
            'code': code,
            'status': code_description,
            'headers': repr(headers)
        })

        if code == 400:
            raise exc.HTTPBadRequest(explanation=response.read())

        if code == 500:
            raise exc.HTTPInternalServerError(explanation=response.read())

        if code == 401:
            raise exc.HTTPUnauthorized(explanation=response.read())

        if code == 403:
            raise exc.HTTPForbidden(explanation=response.read())

        if code == 409:
            raise exc.HTTPConflict(explanation=response.read())

        if ignore_result_body:
            # NOTE: because we are pipelining requests through a single HTTP
            # connection, http_client requires that we read the response body
            # before we can make another request. If the caller knows they
            # don't care about the body, they can ask us to do that for them.
            response.read()
        return response
Exemplo n.º 21
0
 def _reject_request(self, env, start_response, auth_url):
     """Redirect client to auth server."""
     headers = [('WWW-Authenticate', 'Keystone uri=\'%s\'' % auth_url)]
     resp = exc.HTTPUnauthorized('Authentication required', headers)
     return resp(env, start_response)
Exemplo n.º 22
0
        collection_name = match_object.group("collection_name")
        self._log.debug("request {0}: _list_versions".format(user_request_id))

        try:
            collection_row = \
                self._authenticator.authenticate(collection_name,
                                                 list_access,
                                                 req)
        except AccessForbidden, instance:
            self._log.error("request {0}: forbidden {1}".format(
                user_request_id, instance))
            raise exc.HTTPForbidden()
        except AccessUnauthorized, instance:
            self._log.error("request {0}: unauthorized {1}".format(
                user_request_id, instance))
            raise exc.HTTPUnauthorized()
        except Exception:
            self._log.exception("request {0}".format(user_request_id))
            raise exc.HTTPBadRequest()

        variable_names = [
            "prefix",
            "max_keys",
            "delimiter",
            "key_marker",
            "version_id_marker",
        ]

        # pass on any variable names we recognize as keyword args
        kwargs = dict()
        for variable_name in variable_names:
Exemplo n.º 23
0
    def __call__(self, environ, start_response):

        req = Request(environ)
        step = req.path_info.strip('/')

        try:

            if step in [i[0] for i in self.steps]:
                # determine which step we are on
                index = [i[0] for i in self.steps].index(step)
            else:
                # delegate to Trac

                environ['trac.env_parent_dir'] = self.directory
                environ['trac.env_index_template'] = self.index

                # data for index template
                if req.remote_user and self.remote_user_name:
                    # XXX fails if unicode
                    req.remote_user = str(
                        self.remote_user_name(req.remote_user))
                data = {
                    'remote_user': req.remote_user or '',
                    'auth': self.auth and 'yes' or ''
                }
                environ['trac.template_vars'] = ','.join(
                    ["%s=%s" % (key, value) for key, value in data.items()])
                return dispatch_request(environ, start_response)

            # if self.auth, enforce remote_user to be set
            if self.auth and not req.remote_user:
                return exc.HTTPUnauthorized()(environ, start_response)

            # if POST-ing, validate the request and store needed information
            errors = []
            name, step = self.steps[index]
            base_url = req.url.rsplit(step.name, 1)[0]
            project = req.params.get('project')
            if req.method == 'POST':

                # check for project existence
                if not project and index:
                    res = exc.HTTPSeeOther("No session found",
                                           location="create-project")
                    return res(environ, start_response)
                if index:
                    if project not in self.projects:
                        errors.append('Project not found')

                project_data = self.projects.get(project)
                errors = step.errors(project_data, req.POST)
                if not index:
                    project_data = self.projects[project] = {}

                # set *after* error check so that `create-project` doesn't find itself
                project_data['base_url'] = base_url

                if not errors:  # success
                    step.transition(project_data, req.POST)

                    # find the next step and redirect to it
                    while True:
                        index += 1

                        if index == len(self.steps):
                            destination = self.done % self.projects[project][
                                'vars']
                            time.sleep(1)  # XXX needed?
                            self.projects.pop(
                                project)  # successful project creation
                            break
                        else:
                            name, step = self.steps[index]
                            if step.display(project_data):
                                destination = '%s?project=%s' % (
                                    self.steps[index][0], project)
                                break
                            else:
                                step.transition(project_data, {})
                    res = exc.HTTPSeeOther(destination, location=destination)
                    return res(environ, start_response)

            else:  # GET
                project_data = self.projects.get(project, {})
                project_data['base_url'] = base_url
                if index and project not in self.projects:
                    res = exc.HTTPSeeOther("No session found",
                                           location="create-project")
                    return res(environ, start_response)

            # render the template and return the response
            data = step.data(project_data)
            data['req'] = req
            data['errors'] = errors
            template = self.loader.load(step.template)
            html = template.generate(**data).render('html', doctype='html')
            res = Response(content_type='text/html', body=html)
            return res(environ, start_response)

        except:
            # error handling
            exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
            buffer = StringIO()
            traceback.print_exception(exceptionType,
                                      exceptionValue,
                                      exceptionTraceback,
                                      limit=20,
                                      file=buffer)
            res = exc.HTTPServerError(buffer.getvalue())
            return res(environ, start_response)
Exemplo n.º 24
0
 def before(self, state):
     headers = state.request.headers
     if not policy.check_is_admin(headers.get('X-Roles', "").split(",")):
         raise exc.HTTPUnauthorized()
Exemplo n.º 25
0
 def _login(self):
     user = self.by_username(self.request.params['username'])
     if not self._validate_password(user, self.request.params['password']):
         raise exc.HTTPUnauthorized()
     return user
Exemplo n.º 26
0
 def _check_access(self, req, environ, start_response):
     if req.app.private_token:
         sent_private_token = req.GET.get("private_token", None)
         if not (req.app.private_token == sent_private_token):
             return exc.HTTPUnauthorized()(environ, start_response)
Exemplo n.º 27
0
def abort_unauthorized(msg=None):
    raise exc.HTTPUnauthorized("Unauthorized - %s" % msg if msg else "Unauthorized")
 def _auth(self, request):
     if not self.requires_secret:
         return
     provided = request.headers.get('X-Secret')
     if provided != self.secret:
         raise exc.HTTPUnauthorized()
Exemplo n.º 29
0
 def _requestAuth(self, detail=None):
     raise exc.HTTPUnauthorized(
         detail=detail,
         headers=[('WWW-Authenticate', 'Basic realm="Conary Repository"')],
     )