Python falcon.HTTPForbidden() Examples

The following are 28 code examples of falcon.HTTPForbidden(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module falcon , or try the search function .
Example #1
Source File: __init__.py    From oncall with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def check_user_auth(user, req):
    """
    Check to see if current user is user or admin of team where user is in
    """
    if 'app' in req.context:
        return
    challenger = req.context['user']
    if user == challenger:
        return
    connection = db.connect()
    cursor = connection.cursor()
    get_allowed_query = '''SELECT DISTINCT(`user`.`name`)
        FROM `team_admin`
        JOIN `team_user` ON `team_admin`.`team_id` = `team_user`.`team_id`
        JOIN `user` ON `user`.`id` = `team_user`.`user_id`
        JOIN `user` AS `admin` ON `admin`.`id` = `team_admin`.`user_id`
        WHERE `admin`.`name` = %s'''
    cursor.execute(get_allowed_query, challenger)
    allowed = (user,) in cursor
    cursor.close()
    connection.close()
    if allowed or is_god(challenger):
        return
    raise HTTPForbidden('Unauthorized', 'Action not allowed for "%s"' % challenger) 
Example #2
Source File: ical_key_user.py    From oncall with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def on_delete(req, resp, user_name):
    """Delete the secret key that grants public access to user_name's
    oncall calendar for the logged-in user.

    Current policy only allows the logged-in user to get its own key,
    so user_name parameter must be the same as the logged-in user.

    """
    challenger = req.context['user']
    if challenger != user_name:
        raise HTTPForbidden(
            'Unauthorized',
            'Action not allowed: "%s" is not allowed to delete ical_key of "%s"' % (challenger, user_name)
        )

    delete_ical_key(challenger, user_name, 'user') 
Example #3
Source File: ical_key_user.py    From oncall with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def on_post(req, resp, user_name):
    """Update or create the secret key that grants public access to
    user_name's oncall calendar for the logged-in user.  Updating the
    secret key will automatically invalidate existing secret keys.  A
    subsequent GET will get the secret key.

    Current policy only allows the logged-in user to get its own key,
    so user_name parameter must be the same as the logged-in user.

    """
    challenger = req.context['user']
    if challenger != user_name:
        raise HTTPForbidden(
            'Unauthorized',
            'Action not allowed: "%s" is not allowed to update ical_key of "%s"' % (challenger, user_name)
        )

    key = generate_ical_key()
    update_ical_key(challenger, user_name, 'user', key)

    resp.status = HTTP_201
    resp.body = key
    resp.set_header('Content-Type', 'text/plain') 
Example #4
Source File: bootaction.py    From drydock with Apache License 2.0 6 votes vote down vote up
def check_auth(ba_ctx, req):
        """Check request authentication based on boot action context.

        Raise proper Falcon exception if authentication fails, otherwise
        silently return

        :param ba_ctx: Boot Action context from database
        :param req: The falcon request object of the API call
        """
        identity_key = req.get_header('X-Bootaction-Key', default='')

        if identity_key == '':
            raise falcon.HTTPUnauthorized(
                title='Unauthorized',
                description='No X-Bootaction-Key',
                challenges=['Bootaction-Key'])

        if ba_ctx['identity_key'] != bytes.fromhex(identity_key):
            logger.warn(
                "Forbidding boot action access - node: %s, identity_key: %s, req header: %s"
                % (ba_ctx['node_name'], str(ba_ctx['identity_key']),
                   str(bytes.fromhex(identity_key))))
            raise falcon.HTTPForbidden(
                title='Unauthorized', description='Invalid X-Bootaction-Key') 
Example #5
Source File: db.py    From iris with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def guarded_session():
    '''
    Context manager that will automatically close session on exceptions
    '''
    try:
        session = Session()
        yield session
    except IrisValidationException as e:
        session.close()
        raise HTTPBadRequest('Validation error', str(e))
    except (HTTPForbidden, HTTPUnauthorized, HTTPNotFound, HTTPBadRequest):
        session.close()
        raise
    except Exception:
        session.close()
        logger.exception('SERVER ERROR')
        raise 
Example #6
Source File: errors_handling.py    From inference-model-manager with Apache License 2.0 6 votes vote down vote up
def default_exception_handler(ex, req, resp, params):
    if hasattr(ex, 'title') and "Failed data validation" in ex.title:
        JsonSchemaException(ex)
    message = "Unexpected error occurred: {}".format(ex)
    logger.error(message + "\nRequest: {}  Params: {}".format(req, params))

    if isinstance(ex, falcon.HTTPUnauthorized):
        raise ex

    if isinstance(ex, falcon.HTTPForbidden):
        raise ex

    stacktrace = traceback.format_exc()
    logger.error(stacktrace)

    raise falcon.HTTPInternalServerError(message) 
Example #7
Source File: __init__.py    From oncall with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def check_team_auth(team, req):
    """
    Check to see if the current user is admin of the team
    """
    if 'app' in req.context:
        return
    challenger = req.context['user']
    connection = db.connect()
    cursor = connection.cursor()
    get_allowed_query = '''SELECT `team`.`name`
                           FROM `team_admin`
                           JOIN `team` ON `team_admin`.`team_id` = `team`.`id`
                           JOIN `user` ON `team_admin`.`user_id` = `user`.`id`
                           WHERE `user`.`name` = %s'''
    cursor.execute(get_allowed_query, challenger)
    allowed = (team,) in cursor
    cursor.close()
    connection.close()
    if allowed or is_god(challenger):
        return
    raise HTTPForbidden(
        'Unauthorized',
        'Action not allowed: "%s" is not an admin for "%s"' % (challenger, team)) 
Example #8
Source File: app.py    From iris-relay with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def on_get(self, req, resp):
        token = req.get_param('token', True)
        data = {}
        for key in self.data_keys:
            data[key] = req.get_param(key, True)

        if not self.validate_token(token, data):
            raise falcon.HTTPForbidden('Invalid token for these given values', '')

        endpoint = self.config['iris']['hook']['gmail_one_click']

        try:
            result = self.iclient.post(endpoint, data)
        except MaxRetryError:
            logger.exception('Hitting iris-api failed for gmail oneclick')
        else:
            if result.status == 204:
                resp.status = falcon.HTTP_204
                return
            else:
                logger.error('Unexpected status code from api %s for gmail oneclick', result.status)

        raise falcon.HTTPInternalServerError('Internal Server Error', 'Invalid response from API') 
Example #9
Source File: token.py    From certidude with MIT License 6 votes vote down vote up
def on_put(self, req, resp):
        try:
            username, mail, created, expires, profile = self.manager.consume(req.get_param("token", required=True))
        except RelationalMixin.DoesNotExist:
            raise falcon.HTTPForbidden("Forbidden", "No such token or token expired")
        body = req.stream.read(req.content_length)
        header, _, der_bytes = pem.unarmor(body)
        csr = CertificationRequest.load(der_bytes)
        common_name = csr["certification_request_info"]["subject"].native["common_name"]
        if not common_name.startswith(username + "@"):
            raise falcon.HTTPBadRequest("Bad requst", "Invalid common name %s" % common_name)
        try:
            _, resp.body = self.authority._sign(csr, body, profile=config.PROFILES.get(profile),
                overwrite=config.TOKEN_OVERWRITE_PERMITTED)
            resp.set_header("Content-Type", "application/x-pem-file")
            logger.info("Autosigned %s as proven by token ownership", common_name)
        except FileExistsError:
            logger.info("Won't autosign duplicate %s", common_name)
            raise falcon.HTTPConflict(
                "Certificate with such common name (CN) already exists",
                "Will not overwrite existing certificate signing request, explicitly delete existing one and try again") 
Example #10
Source File: firewall.py    From certidude with MIT License 6 votes vote down vote up
def authorize_server(func):
    """
    Make sure the request originator has a certificate with server flags
    """
    from asn1crypto import pem, x509
    def wrapped(resource, req, resp, *args, **kwargs):
        buf = req.get_header("X-SSL-CERT")
        if not buf:
            logger.info("No TLS certificate presented to access administrative API call from %s" % req.context.get("remote_addr"))
            raise falcon.HTTPForbidden("Forbidden", "Machine not authorized to perform the operation")

        header, _, der_bytes = pem.unarmor(buf.replace("\t", "").encode("ascii"))
        cert = x509.Certificate.load(der_bytes) # TODO: validate serial
        for extension in cert["tbs_certificate"]["extensions"]:
            if extension["extn_id"].native == "extended_key_usage":
                if "server_auth" in extension["extn_value"].native:
                    req.context["machine"] = cert.subject.native["common_name"]
                    return func(resource, req, resp, *args, **kwargs)
        logger.info("TLS authenticated machine '%s' not authorized to access administrative API", cert.subject.native["common_name"])
        raise falcon.HTTPForbidden("Forbidden", "Machine not authorized to perform the operation")
    return wrapped 
Example #11
Source File: __init__.py    From oncall with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def check_calendar_auth_by_id(team_id, req):
    if 'app' in req.context:
        return
    challenger = req.context['user']
    query = '''SELECT `user`.`name`
               FROM `team_user`
               JOIN `user` ON `team_user`.`user_id` = `user`.`id`
               WHERE `team_user`.`team_id` = %s
               AND `user`.`name` = %s'''
    connection = db.connect()
    cursor = connection.cursor()
    cursor.execute(query, (team_id, challenger))
    user_in_team = cursor.rowcount
    cursor.close()
    connection.close()
    if user_in_team != 0 or is_god(challenger):
        return
    raise HTTPForbidden('Unauthorized', 'Action not allowed: "%s" is not a team member' % (challenger)) 
Example #12
Source File: firewall.py    From certidude with MIT License 6 votes vote down vote up
def whitelist_subnets(subnets):
    """
    Validate source IP address of API call against subnet list
    """
    def wrapper(func):
        def wrapped(self, req, resp, *args, **kwargs):
            # Check for administration subnet whitelist
            for subnet in subnets:
                if req.context.get("remote_addr") in subnet:
                    break
            else:
                logger.info("Rejected access to administrative call %s by %s from %s, source address not whitelisted",
                    req.env["PATH_INFO"],
                    req.context.get("user", "unauthenticated user"),
                    req.context.get("remote_addr"))
                raise falcon.HTTPForbidden("Forbidden", "Remote address %s not whitelisted" % req.context.get("remote_addr"))

            return func(self, req, resp, *args, **kwargs)
        return wrapped
    return wrapper 
Example #13
Source File: bootaction.py    From drydock with Apache License 2.0 6 votes vote down vote up
def check_auth(ba_ctx, req):
        """Check request authentication based on boot action context.

        Raise proper Falcon exception if authentication fails, otherwise
        silently return

        :param ba_ctx: Boot Action context from database
        :param req: The falcon request object of the API call
        """
        identity_key = req.get_header('X-Bootaction-Key', default='')

        if identity_key == '':
            raise falcon.HTTPUnauthorized(
                title='Unauthorized',
                description='No X-Bootaction-Key',
                challenges=['Bootaction-Key'])

        if ba_ctx['identity_key'] != bytes.fromhex(identity_key):
            logger.warn(
                "Forbidding boot action access - node: %s, identity_key: %s, req header: %s"
                % (ba_ctx['node_name'], str(ba_ctx['identity_key']),
                   str(bytes.fromhex(identity_key))))
            raise falcon.HTTPForbidden(
                title='Unauthorized', description='Invalid X-Bootaction-Key') 
Example #14
Source File: validation.py    From monasca-log-api with Apache License 2.0 5 votes vote down vote up
def validate_cross_tenant(tenant_id, cross_tenant_id, roles):

    if not validate_is_delegate(roles):
        if cross_tenant_id:
            raise falcon.HTTPForbidden(
                'Permission denied',
                'Projects %s cannot POST cross tenant logs' % tenant_id
            ) 
Example #15
Source File: __init__.py    From oncall with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def debug_only(function):
    def wrapper(*args, **kwargs):
        raise HTTPForbidden('', 'Admin only action')
    return wrapper 
Example #16
Source File: ical_key_requester.py    From oncall with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def on_delete(req, resp, requester):
    challenger = req.context['user']
    if not (challenger == requester or check_ical_key_admin(challenger)):
        raise HTTPForbidden(
            'Unauthorized',
            'Action not allowed: "%s" is not allowed to delete ical_keys of "%s"' % (challenger, ),
        )

    invalidate_ical_key_by_requester(requester) 
Example #17
Source File: validation.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def validate_cross_tenant(tenant_id, cross_tenant_id, roles):

    if not validate_is_delegate(roles):
        if cross_tenant_id:
            raise falcon.HTTPForbidden(
                'Permission denied',
                'Projects %s cannot POST cross tenant logs' % tenant_id
            ) 
Example #18
Source File: ical_key_requester.py    From oncall with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def on_get(req, resp, requester):
    challenger = req.context['user']
    if not (challenger == requester or check_ical_key_admin(challenger)):
        raise HTTPForbidden(
            'Unauthorized',
            'Action not allowed: "%s" is not allowed to view ical_keys of "%s"' % (challenger, requester),
        )

    results = get_ical_key_detail_by_requester(requester)
    if not results:
        raise HTTPNotFound()

    resp.body = json_dumps(results)
    resp.set_header('Content-Type', 'application/json') 
Example #19
Source File: ical_key_detail.py    From oncall with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def on_get(req, resp, key):
    challenger = req.context['user']
    if not (check_ical_key_requester(key, challenger) or check_ical_key_admin(challenger)):
        raise HTTPForbidden(
            'Unauthorized',
            'Action not allowed: "%s" is not an admin of ical_key' % (challenger, ),
        )

    results = get_ical_key_detail(key)
    if not results:
        raise HTTPNotFound()

    resp.body = json_dumps(results)
    resp.set_header('Content-Type', 'application/json') 
Example #20
Source File: ical_key_user.py    From oncall with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def on_get(req, resp, user_name):
    """Get the secret key that grants public access to user_name's oncall
    calendar for the logged-in user.

    Current policy only allows the logged-in user to get its own key,
    so user_name parameter must be the same as the logged-in user.

    **Example request:**

    .. sourcecode:: http

        GET /api/v0/ical_key/user/jdoe HTTP/1.1
        Content-Type: text/plain

        ef895425-5f49-11ea-8eee-10e7c6352aff

    """
    challenger = req.context['user']
    if challenger != user_name:
        raise HTTPForbidden(
            'Unauthorized',
            'Action not allowed: "%s" is not allowed to view ical_key of "%s"' % (challenger, user_name)
        )

    key = get_ical_key(challenger, user_name, 'user')
    if key is None:
        raise HTTPNotFound()

    resp.body = key
    resp.set_header('Content-Type', 'text/plain') 
Example #21
Source File: schedule.py    From oncall with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def verify_auth(req, schedule_id, connection, cursor):
    team_query = ('SELECT `team`.`name` FROM `schedule` JOIN `team` '
                  'ON `schedule`.`team_id` = `team`.`id` WHERE `schedule`.`id` = %s')
    cursor.execute(team_query, schedule_id)
    if cursor.rowcount == 0:
        cursor.close()
        connection.close()
        raise HTTPNotFound()
    try:
        check_team_auth(cursor.fetchone()[0], req)
    except HTTPForbidden:
        cursor.close()
        connection.close()
        raise 
Example #22
Source File: authenticate.py    From inference-model-manager with Apache License 2.0 5 votes vote down vote up
def process_request(self, req, resp):

        path = urlparse(req.url)[2]
        if path in self.no_auth_endpoints:
            return

        token = req.get_header('Authorization')

        if token is None:
            raise falcon.HTTPUnauthorized('Auth token required', 'Missing auth token')

        decoded = self.tokenDecoder.decode(token)
        if not decoded:
            logger.info("Failed to decode token")
            raise falcon.HTTPUnauthorized('Authentication required', "Token not valid.")

        if self._token_expired(decoded):
            raise falcon.HTTPUnauthorized('Authentication required', 'Token expired')

        if path in self.admin_endpoints:
            if not self._token_has_admin_priv(decoded):
                raise falcon.HTTPForbidden('Forbidden', "Insufficient permissions")

        if USE_SERVICE_ACCOUNT:
            req.params['Authorization'] = self.sa_token
            logger.info("Using service account token")
        else:
            req.params['Authorization'] = token
        logger.info("Decoded token : {}".format(decoded))
        logger.info("Request path: {}, method {}".format(req.path, req.method)) 
Example #23
Source File: errors_handling.py    From inference-model-manager with Apache License 2.0 5 votes vote down vote up
def form_response(self, message):
        if self.k8s_api_exception.status == 403:
            raise falcon.HTTPForbidden(message)
        elif 400 <= self.k8s_api_exception.status < 500:
            raise falcon.HTTPBadRequest(message)
        else:
            raise falcon.HTTPInternalServerError(message) 
Example #24
Source File: exceptions.py    From freezer-api with Apache License 2.0 5 votes vote down vote up
def handle(ex, req, resp, params):
        raise falcon.HTTPForbidden(
            title=_("Access Forbidden"),
            description="You are not allowed to access this resource") 
Example #25
Source File: test_exceptions.py    From freezer-api with Apache License 2.0 5 votes vote down vote up
def test_AccessForbidden(self):
        e = exceptions.AccessForbidden(message='testing')
        self.assertRaises(falcon.HTTPForbidden,
                          e.handle, self.ex, self.mock_req, self.mock_req,
                          None) 
Example #26
Source File: firewall.py    From certidude with MIT License 5 votes vote down vote up
def authorize_admin(func):
    @whitelist_subnets(config.ADMIN_SUBNETS)
    def wrapped(resource, req, resp, *args, **kwargs):
        if req.context.get("user").is_admin():
            return func(resource, req, resp, *args, **kwargs)
        logger.info("User '%s' not authorized to access administrative API", req.context.get("user").name)
        raise falcon.HTTPForbidden("Forbidden", "User not authorized to perform administrative operations")
    return wrapped 
Example #27
Source File: firewall.py    From certidude with MIT License 5 votes vote down vote up
def whitelist_subject(func):
    def wrapped(self, req, resp, cn, *args, **kwargs):
        from ipaddress import ip_address
        from certidude import authority
        from xattr import getxattr
        try:
            path, buf, cert, signed, expires = authority.get_signed(cn)
        except IOError:
            raise falcon.HTTPNotFound()
        else:
            # First attempt to authenticate client with certificate
            buf = req.get_header("X-SSL-CERT")
            if buf:
                header, _, der_bytes = pem.unarmor(buf.replace("\t", "").encode("ascii"))
                origin_cert = x509.Certificate.load(der_bytes)
                if origin_cert.native == cert.native:
                    logger.debug("Subject authenticated using certificates")
                    return func(self, req, resp, cn, *args, **kwargs)

            # For backwards compatibility check source IP address
            # TODO: make it disableable
            try:
                inner_address = getxattr(path, "user.lease.inner_address").decode("ascii")
            except IOError:
                raise falcon.HTTPForbidden("Forbidden", "Remote address %s not whitelisted" % req.context.get("remote_addr"))
            else:
                if req.context.get("remote_addr") != ip_address(inner_address):
                    raise falcon.HTTPForbidden("Forbidden", "Remote address %s mismatch" % req.context.get("remote_addr"))
                else:
                    return func(self, req, resp, cn, *args, **kwargs)
    return wrapped 
Example #28
Source File: decorators.py    From certidude with MIT License 5 votes vote down vote up
def csrf_protection(func):
    """
    Protect resource from common CSRF attacks by checking user agent and referrer
    """
    import falcon
    def wrapped(self, req, resp, *args, **kwargs):
        # Assume curl and python-requests are used intentionally
        if req.user_agent.startswith("curl/") or req.user_agent.startswith("python-requests/"):
            return func(self, req, resp, *args, **kwargs)

        # For everything else assert referrer
        referrer = req.headers.get("REFERER")


        if referrer:
            scheme, netloc, path, params, query, fragment = urlparse(referrer)
            if ":" in netloc:
                host, port = netloc.split(":", 1)
            else:
                host, port = netloc, None
            if host == req.host:
                return func(self, req, resp, *args, **kwargs)

        # Kaboom!
        logger.warning("Prevented clickbait from '%s' with user agent '%s'",
            referrer or "-", req.user_agent)
        raise falcon.HTTPForbidden("Forbidden",
            "No suitable UA or referrer provided, cross-site scripting disabled")
    return wrapped