Beispiel #1
0
    def test_create_can_be_retrieved_later(self):

        payload = {
            "name": "test can be retrieved",
            "setup": "pass",
            "snippets": ("pass", "pass")
        }

        start_response = StartResponseMock()
        result = self.app(
            create_environ(
                path='/entries',
                method='POST',
                body=json.dumps(payload),
            ),
            start_response,
        )[0].decode()
        result = json.loads(result)

        start_response2 = StartResponseMock()
        result2 = self.app(
            create_environ(path='/entries/{0}'.format(result['id']), ),
            start_response2,
        )[0].decode()
        result2 = json.loads(result2)

        self.assertTrue(start_response2.status != '404 Not Found')
        self.assertTrue(result2['id'] == result['id'])
        self.assertTrue(result2['name'] == payload['name'])
        self.assertTrue(result2['setup'] == payload['setup'])

        for snip1, snip2 in zip(payload['snippets'], result2['snippets']):
            self.assertTrue(snip1 == snip2)
Beispiel #2
0
    def test_create_can_be_retrieved_later(self):

        payload = {
            "name": "test can be retrieved",
            "setup": "pass",
            "snippets": ("pass", "pass")
        }

        start_response = StartResponseMock()
        result = self.app(
            create_environ(
                path='/entries',
                method='POST',
                body=json.dumps(payload),
            ),
            start_response,
        )[0].decode()
        result = json.loads(result)

        start_response2 = StartResponseMock()
        result2 = self.app(
            create_environ(
                path='/entries/{0}'.format(result['id']),
            ),
            start_response2,
        )[0].decode()
        result2 = json.loads(result2)

        self.assertTrue(start_response2.status != '404 Not Found')
        self.assertTrue(result2['id'] == result['id'])
        self.assertTrue(result2['name'] == payload['name'])
        self.assertTrue(result2['setup'] == payload['setup'])

        for snip1, snip2 in zip(payload['snippets'], result2['snippets']):
            self.assertTrue(snip1 == snip2)
Beispiel #3
0
    def test_results_can_be_retrieved(self):

        payload = {
            "name": "test has results",
            "setup": "pass",
            "snippets": ("pass", "pass")
        }

        start_response = StartResponseMock()
        result = self.app(
            create_environ(
                path='/entries',
                method='POST',
                body=json.dumps(payload),
            ),
            start_response,
        )[0].decode()
        result = json.loads(result)

        start_response2 = StartResponseMock()
        result2 = self.app(
            create_environ(path='/entries/{0}/results'.format(result['id']), ),
            start_response2,
        )[0].decode()
        result2 = json.loads(result2)

        self.assertTrue(start_response2.status != '404 Not Found')
        self.assertTrue(start_response2.status != '500 Internal Server Error')

        for snippet in result2['snippets']:

            self.assertTrue(snippet['runtime'] is None)
            self.assertTrue(snippet['memory']['max'] is None)
            self.assertTrue(snippet['memory']['avg'] is None)
            self.assertTrue(snippet['memory']['min'] is None)
Beispiel #4
0
    def simulate_request(self, path, decode=None, **kwargs):
        """ Simulates a request.

        Simulates a request to the API for testing purposes.

        Args:
            path: Request path for the desired resource
            decode: If set to a character encoding, such as 'utf-8',
                the method will assume the response is a single
                byte string and will decode it and return a single
                wide string instead of the raw WSGI response iterable.
            kwargs: Same as falcon.testing.create_environ()

        """

        if not path:
            path = '/'

        result = self.api(create_environ(path=path, **kwargs),
                          self.srmock)

        if decode is not None:
            if not result:
                return ''

            return result[0].decode(decode)

        return result
Beispiel #5
0
 def test_sl_client(self):
     # Jumpgate request has an sl_client property.
     env = helpers.create_environ()
     r = api.Request(env)
     self.assertIsNone(r.sl_client)
     r.sl_client = 'fake_client'
     self.assertEqual('fake_client', r.sl_client)
Beispiel #6
0
def _set_up_req_resp_body(**kwargs):
    env = helpers.create_environ(**kwargs)
    req = falcon.Request(env)
    resp = falcon.Response()
    client = mock.MagicMock()
    env['sl_client'] = client
    return client, env, req, resp
Beispiel #7
0
 def fake_request(self, path, **kwargs):
     kwargs.setdefault('headers', {})
     content_type = kwargs.pop('content_type', None)
     if content_type:
         kwargs['headers']['Content-Type'] = content_type
     if self._before:
         self._before(kwargs)
     parsed = urlparse(path)
     path = parsed.path
     if parsed.query:
         kwargs['query_string'] = parsed.query
     if isinstance(kwargs.get('query_string', None), dict):
         kwargs['query_string'] = urlencode(kwargs['query_string'])
     self.encode_body(kwargs)
     resp = StartResponseMock()
     body = self.app(create_environ(path, **kwargs), resp)
     resp.headers = resp.headers_dict
     resp.status_code = int(resp.status.split(' ')[0])
     resp.body = b''.join(list(body)) if body else b''
     try:
         # …to be smart and provide the response as str if it let iself
         # decode.
         resp.body = resp.body.decode()
     except UnicodeDecodeError:
         # But do not insist.
         pass
     if 'application/json' in resp.headers.get('Content-Type', ''):
         resp.json = json.loads(resp.body) if resp.body else {}
     if self._after:
         self._after(resp)
     return resp
    def test_authenticate_with_invalid_user(self):
        """
        Verify authenticate denies with a proper JSON in Etcd, Authorization header, and no matching user.
        """
        with mock.patch('cherrypy.engine.publish') as _publish:
            # Mock the return of the Etcd get result
            return_value = mock.MagicMock(etcd.EtcdResult)
            with open(self.user_config, 'r') as users_file:
                return_value.value = users_file.read()

            manager = mock.MagicMock(StoreHandlerManager)
            _publish.return_value = [manager]

            manager.get.return_value = return_value

            # Reload with the data from the mock'd Etcd
            http_basic_auth = httpbasicauth.HTTPBasicAuth()

            # Test the call
            req = falcon.Request(
                create_environ(headers={'Authorization': 'basic Yjpi'}))
            resp = falcon.Response()
            self.assertRaises(
                falcon.HTTPForbidden,
                http_basic_auth.authenticate,
                req, resp)
Beispiel #9
0
 def fake_request(self, path, **kwargs):
     kwargs.setdefault("headers", {})
     content_type = kwargs.pop("content_type", None)
     if content_type:
         kwargs["headers"]["Content-Type"] = content_type
     if self._before:
         self._before(kwargs)
     parsed = urlparse(path)
     path = parsed.path
     if parsed.query:
         kwargs["query_string"] = parsed.query
     if isinstance(kwargs.get("query_string", None), dict):
         kwargs["query_string"] = urlencode(kwargs["query_string"])
     self.encode_body(kwargs)
     resp = StartResponseMock()
     environ = create_environ(path, **kwargs)
     resp.environ = environ
     body = self.app(environ, resp)
     resp.headers = resp.headers_dict
     resp.status_code = int(resp.status.split(" ")[0])
     resp.body = b"".join(list(body)) if body else b""
     try:
         # …to be smart and provide the response as str if it let iself
         # decode.
         resp.body = resp.body.decode()
     except UnicodeDecodeError:
         # But do not insist.
         pass
     if "application/json" in resp.headers.get("Content-Type", ""):
         resp.json = json.loads(resp.body) if resp.body else {}
     if self._after:
         self._after(resp)
     return resp
Beispiel #10
0
 def test_decode_basic_auth_with_no_header(self):
     """
     Verify returns no user with no authorization header.
     """
     req = falcon.Request(create_environ(headers={}))
     self.assertEquals((None, None),
                       self.http_basic_auth._decode_basic_auth(req))
Beispiel #11
0
    def simulate_request(self, path, decode=None, **kwargs):
        """Simulates a request to `self.api`.

        Args:
            path (str): The path to request.
            decode (str, optional): If this is set to a character encoding,
                such as 'utf-8', `simulate_request` will assume the
                response is a single byte string, and will decode it as the
                result of the request, rather than simply returning the
                standard WSGI iterable.
            kwargs (optional): Same as those defined for
                `falcon.testing.create_environ`.

        """

        if not path:
            path = "/"

        result = self.api(create_environ(path=path, **kwargs), self.srmock)

        if decode is not None:
            if not result:
                return ""

            return result[0].decode(decode)

        return result
Beispiel #12
0
    def simulate_request(self, path, decode=None, **kwargs):
        """Simulates a request to `self.api`.

        Args:
            path (str): The path to request.
            decode (str, optional): If this is set to a character encoding,
                such as 'utf-8', `simulate_request` will assume the
                response is a single byte string, and will decode it as the
                result of the request, rather than simply returning the
                standard WSGI iterable.
            kwargs (optional): Same as those defined for
                `falcon.testing.create_environ`.

        """

        if not path:
            path = '/'

        result = self.api(create_environ(path=path, **kwargs),
                          self.srmock)

        if decode is not None:
            if not result:
                return ''

            return result[0].decode(decode)

        return result
Beispiel #13
0
def test_request_json_body_prop():
    body = '''{
        "key": null
    }'''
    env = create_environ(body=body)
    req = Request(env)
    assert req.json_body == {"key": None}
Beispiel #14
0
def test_oauth_middleware_request_auth_invalid(headers):
    auth_middleware = JwtMiddleware()
    auth_middleware._verification_key = RSA_2048_PUB_KEY

    with pytest.raises(falcon.HTTPUnauthorized):
        auth_middleware.process_resource(
            Request(create_environ(headers=headers)), None, None, None)
 def test_authenticator_process_request(self):
     """
     Verify Authenticator's process_request calls authenticate.
     """
     self.assertRaises(falcon.HTTPForbidden,
                       self.authenticator.process_request,
                       falcon.Request(create_environ()), falcon.Response())
Beispiel #16
0
    def test_valid_auth(self, identity):
        client = MagicMock()
        env = helpers.create_environ(headers={'X-AUTH-TOKEN': 'AUTHTOK',
                                              'X-AUTH-PROJECT-ID': 'public'})

        req = jumpgate.api.Request(env, sl_client=client)
        req.method = 'GET'
        req.path = '/v2/servers'
        resp = MagicMock()

        token = {
            'username': '******',
            'auth_type': 'api_key',
            'user_id': '1234567',
            'tenant_id': '123456',
            'expires': 1234567891.123456,
            'api_key': '123456789123456789123456789123456789123456789123456789'
        }

        def mock_validate(tok, tenant_id=None):
            self.assertEqual('AUTHTOK', tok)
            self.assertEqual('public', tenant_id)

        class MockIdDriver(object):
            def token_from_id(self, tok):
                return token

        identity.validate_token_id = mock_validate
        identity.token_id_driver.return_value = MockIdDriver()
        validate_token(req, resp, {'X-AUTH-PROJECT-ID': 'public'})
        self.assertEqual(req.env.get('auth'), token)
        self.assertEqual('1234567', req.user_id)
Beispiel #17
0
 def fake_request(self, path, **kwargs):
     kwargs.setdefault('headers', {})
     content_type = kwargs.pop('content_type', None)
     if content_type:
         kwargs['headers']['Content-Type'] = content_type
     if self._before:
         self._before(kwargs)
     parsed = urlparse(path)
     path = parsed.path
     if parsed.query:
         kwargs['query_string'] = parsed.query
     if isinstance(kwargs.get('query_string', None), dict):
         kwargs['query_string'] = urlencode(kwargs['query_string'])
     self.encode_body(kwargs)
     resp = StartResponseMock()
     body = self.app(create_environ(path, **kwargs), resp)
     resp.headers = resp.headers_dict
     resp.status_code = int(resp.status.split(' ')[0])
     resp.body = b''.join(list(body)) if body else b''
     try:
         # …to be smart and provide the response as str if it let iself
         # decode.
         resp.body = resp.body.decode()
     except UnicodeDecodeError:
         # But do not insist.
         pass
     if 'application/json' in resp.headers.get('Content-Type', ''):
         resp.json = json.loads(resp.body) if resp.body else {}
     if self._after:
         self._after(resp)
     return resp
Beispiel #18
0
    def simulate_request(self, method='GET', path='/', query_string=None,
                         headers=None, body=None, file_wrapper=None):
        """Simulates a request to a WSGI application.

        Performs a WSGI request directly against ``self.api``.

        Keyword Args:
            method (str): The HTTP method to use in the request
                (default: 'GET')
            path (str): The URL path to request (default: '/')
            query_string (str): A raw query string to include in the
                request (default: ``None``)
            headers (dict): Additional headers to include in the request
                (default: ``None``)
            body (str): A string to send as the body of the request.
                Accepts both byte strings and Unicode strings
                (default: ``None``). If a Unicode string is provided,
                it will be encoded as UTF-8 in the request.
            file_wrapper (callable): Callable that returns an iterable,
                to be used as the value for *wsgi.file_wrapper* in the
                environ (default: ``None``).

        Returns:
            :py:class:`~.Result`: The result of the request
        """

        if not path.startswith('/'):
            raise ValueError("path must start with '/'")

        if query_string and query_string.startswith('?'):
            raise ValueError("query_string should not start with '?'")

        if '?' in path:
            # NOTE(kgriffs): We could allow this, but then we'd need
            #   to define semantics regarding whether the path takes
            #   precedence over the query_string. Also, it would make
            #   tests less consistent, since there would be "more than
            #   one...way to do it."
            raise ValueError(
                'path may not contain a query string. Please use the '
                'query_string parameter instead.'
            )

        env = create_environ(
            method=method,
            path=path,
            query_string=(query_string or ''),
            headers=headers,
            body=body,
            file_wrapper=file_wrapper,
        )

        srmock = StartResponseMock()
        validator = wsgiref.validate.validator(self.api)
        iterable = validator(env, srmock)

        result = Result(iterable, srmock.status, srmock.headers)

        return result
Beispiel #19
0
    def simulate_request(self, method='GET', path='/', query_string=None,
                         headers=None, body=None, file_wrapper=None):
        """Simulates a request to a WSGI application.

        Performs a WSGI request directly against ``self.api``.

        Keyword Args:
            method (str): The HTTP method to use in the request
                (default: 'GET')
            path (str): The URL path to request (default: '/')
            query_string (str): A raw query string to include in the
                request (default: ``None``)
            headers (dict): Additional headers to include in the request
                (default: ``None``)
            body (str): A string to send as the body of the request.
                Accepts both byte strings and Unicode strings
                (default: ``None``). If a Unicode string is provided,
                it will be encoded as UTF-8 in the request.
            file_wrapper (callable): Callable that returns an iterable,
                to be used as the value for *wsgi.file_wrapper* in the
                environ (default: ``None``).

        Returns:
            :py:class:`~.Result`: The result of the request
        """

        if not path.startswith('/'):
            raise ValueError("path must start with '/'")

        if query_string and query_string.startswith('?'):
            raise ValueError("query_string should not start with '?'")

        if '?' in path:
            # NOTE(kgriffs): We could allow this, but then we'd need
            #   to define semantics regarding whether the path takes
            #   precedence over the query_string. Also, it would make
            #   tests less consistent, since there would be "more than
            #   one...way to do it."
            raise ValueError(
                'path may not contain a query string. Please use the '
                'query_string parameter instead.'
            )

        env = create_environ(
            method=method,
            path=path,
            query_string=(query_string or ''),
            headers=headers,
            body=body,
            file_wrapper=file_wrapper,
        )

        srmock = StartResponseMock()
        validator = wsgiref.validate.validator(self.api)
        iterable = validator(env, srmock)

        result = Result(iterable, srmock.status, srmock.headers)

        return result
Beispiel #20
0
 def test_decode_basic_auth_with_bad_data_in_header(self):
     """
     Verify decoding returns no user with bad base64 data in the header.
     """
     req = falcon.Request(
         create_environ(headers={'Authorization': 'basic BADDATA'}))
     self.assertEquals((None, None),
                       self.http_basic_auth._decode_basic_auth(req))
 def test_decode_basic_auth_with_no_header(self):
     """
     Verify returns no user with no authorization header.
     """
     req = falcon.Request(create_environ(headers={}))
     self.assertEquals(
         (None, None),
         self.http_basic_auth._decode_basic_auth(req))
Beispiel #22
0
def test_request_body_prop():
    body = """
        A	B	C	D	E	F	G	H
        8	♖	♘	♗	♕	♔	♗	♘	♖
        ​...
    """
    env = create_environ(body=body)
    req = Request(env)
    assert req.body == body.encode()
    def test_valid_certs(self):
        """
        Verify authenticate succeeds when cn matches, fails when it doesn't
        """
        self.expect_forbidden(data=self.cert, cn="other-cn")

        auth = httpauthclientcert.HTTPClientCertAuth(cn="system:master-proxy")
        req = falcon.Request(create_environ())
        req.env[SSL_CLIENT_VERIFY] = self.cert
        resp = falcon.Response()
        self.assertEqual(None, auth.authenticate(req, resp))

        # With no cn any is valid
        auth = httpauthclientcert.HTTPClientCertAuth()
        req = falcon.Request(create_environ())
        req.env[SSL_CLIENT_VERIFY] = self.cert
        resp = falcon.Response()
        self.assertEqual(None, auth.authenticate(req, resp))
Beispiel #24
0
 def _request_generator(method, path, query_string=None, headers=None, body=None):
     env = create_environ(
         method=method,
         path=path,
         query_string=(query_string or ''),
         headers=headers,
         body=body,
     )
     return Request(env)
Beispiel #25
0
def test_oauth_middleware_request_auth_valid():
    auth_middleware = JwtMiddleware()
    auth_middleware._verification_key = RSA_2048_PUB_KEY
    test_req = Request(create_environ(headers={"Authorization": TEST_AUTH_HEADER}))
    test_resp = Response()

    auth_middleware.process_resource(test_req, test_resp, None, None)
    auth_middleware.process_request(test_req, test_resp)
    auth_middleware.process_response(test_req, test_resp, None)
 def test_authenticator_process_request(self):
     """
     Verify Authenticator's process_request calls authenticate.
     """
     self.assertRaises(
         falcon.HTTPForbidden,
         self.authenticator.process_request,
         falcon.Request(create_environ()),
         falcon.Response())
Beispiel #27
0
 def _request_generator(method, path, query_string=None, headers=None, body=None):
     env = create_environ(
         method=method,
         path=path,
         query_string=(query_string or ''),
         headers=headers,
         body=body,
     )
     return Request(env)
 def test_decode_basic_auth_with_bad_data_in_header(self):
     """
     Verify decoding returns no user with bad base64 data in the header.
     """
     req = falcon.Request(
         create_environ(headers={'Authorization': 'basic BADDATA'}))
     self.assertEquals(
         (None, None),
         self.http_basic_auth._decode_basic_auth(req))
    def test_valid_certs(self):
        """
        Verify authenticate succeeds when cn matches, fails when it doesn't
        """
        self.expect_forbidden(data=self.cert, cn="other-cn")

        auth = httpauthclientcert.HTTPClientCertAuth(cn="system:master-proxy")
        req = falcon.Request(create_environ())
        req.env[SSL_CLIENT_VERIFY] = self.cert
        resp = falcon.Response()
        self.assertEqual(None, auth.authenticate(req, resp))

        # With no cn any is valid
        auth = httpauthclientcert.HTTPClientCertAuth()
        req = falcon.Request(create_environ())
        req.env[SSL_CLIENT_VERIFY] = self.cert
        resp = falcon.Response()
        self.assertEqual(None, auth.authenticate(req, resp))
Beispiel #30
0
def test_oauth_middleware_request_auth_valid():
    auth_middleware = JwtMiddleware()
    auth_middleware._verification_key = RSA_2048_PUB_KEY
    test_req = Request(
        create_environ(headers={'Authorization': TEST_AUTH_HEADER}))
    test_resp = Response()

    auth_middleware.process_resource(test_req, test_resp, None, None)
    auth_middleware.process_request(test_req, test_resp)
    auth_middleware.process_response(test_req, test_resp, None)
Beispiel #31
0
 def test_authenticate_with_header(self):
     """
     Verify authenticate uses the submitted token and forbids without the header.
     """
     self._container_mgr.__getitem__()._get = mock.MagicMock(
         return_value=mock.MagicMock(status_code=409))
     req = falcon.Request(create_environ(headers={}))
     resp = falcon.Response()
     self.assertRaises(falcon.errors.HTTPForbidden,
                       self.kubernetes_auth.authenticate, req, resp)
Beispiel #32
0
def test_request_entity_prop_malformed_header_raises_401():
    headers = {'Authorization': '11532145'}
    env = create_environ(headers=headers)
    req = Request(env)
    try:
        req.entity
    except HTTPUnauthorized:
        pass
    else:
        assert False, "Expected an error to be raised"
Beispiel #33
0
def test_request_entity_prop_invalid_entity_type_raises_401():
    headers = {'Authorization': 'invalid_user_type:1234'}
    env = create_environ(headers=headers)
    req = Request(env)
    try:
        req.entity
    except HTTPUnauthorized:
        pass
    else:
        assert False, "Expected an error to be raised"
Beispiel #34
0
def test_request_entity_prop():
    headers = {}
    sentinel = object()
    env = create_environ(headers=headers)
    req = Request(env)
    with mock.patch(
            'http_agent.request.authenticate_entity') as mock_entity_factory:
        mock_entity_factory.return_value = sentinel
        assert req.entity is sentinel
        mock_entity_factory.assert_called_once_with()
Beispiel #35
0
 def test_authenticate_with_invalid_user(self):
     """
     Verify authenticate denies with a proper JSON file, Authorization header, and no matching user.
     """
     self.http_basic_auth_by_file = httpauth.HTTPBasicAuthByFile(
         './conf/users.json')
     req = falcon.Request(
         create_environ(headers={'Authorization': 'basic Yjpi'}))
     resp = falcon.Response()
     self.assertRaises(falcon.HTTPForbidden,
                       self.http_basic_auth_by_file.authenticate, req, resp)
Beispiel #36
0
 def test_authenticate_with_header(self):
     """
     Verify authenticate uses the submitted token and succeeds with the header.
     """
     self._container_mgr.__getitem__()._get = mock.MagicMock(
         return_value=mock.MagicMock(status_code=200))
     req = falcon.Request(
         create_environ(headers={'Authorization': 'Bearer 123'}))
     resp = falcon.Response()
     self.kubernetes_auth.authenticate(req, resp)
     self.assertEquals('200 OK', resp.status)
Beispiel #37
0
 def test_authenticate_with_invalid_password(self):
     """
     Verify authenticate denies with a proper JSON file, Authorization header, and the wrong password.
     """
     self.http_basic_auth_by_file = httpauth.HTTPBasicAuthByFile(
         self.user_config)
     req = falcon.Request(
         create_environ(headers={'Authorization': 'basic YTpiCg=='}))
     resp = falcon.Response()
     self.assertRaises(falcon.HTTPForbidden,
                       self.http_basic_auth_by_file.authenticate, req, resp)
 def test_authenticate_with_valid_user(self):
     """
     Verify authenticate works with a proper JSON file, Authorization header, and a matching user.
     """
     self.http_basic_auth = httpbasicauth.HTTPBasicAuth(self.user_config)
     req = falcon.Request(
         create_environ(headers={'Authorization': 'basic YTph'}))
     resp = falcon.Response()
     self.assertEquals(
         None,
         self.http_basic_auth.authenticate(req, resp))
Beispiel #39
0
 def test_authenticate_with_valid_user(self):
     """
     Verify authenticate works with a proper JSON file, Authorization header, and a matching user.
     """
     self.http_basic_auth_by_file = httpauth.HTTPBasicAuthByFile(
         './conf/users.json')
     req = falcon.Request(
         create_environ(headers={'Authorization': 'basic YTph'}))
     resp = falcon.Response()
     self.assertEquals(None,
                       self.http_basic_auth_by_file.authenticate(req, resp))
    def expect_forbidden(self, data=None, cn=None):
        auth = httpauthclientcert.HTTPClientCertAuth(cn=cn)
        req = falcon.Request(create_environ())
        if data is not None:
            req.env[SSL_CLIENT_VERIFY] = data

        resp = falcon.Response()
        self.assertRaises(
            falcon.HTTPForbidden,
            auth.authenticate,
            req, resp)
Beispiel #41
0
def test_request_json_body_prop_invalid_raises_400():
    body = ""
    env = create_environ(body=body)
    req = Request(env)

    try:
        req.json_body
    except HTTPBadRequest:
        pass
    else:
        assert False, "Expected an error to be raised"
Beispiel #42
0
def test_request_entity_prop_from_header():
    headers = {'Authorization': 'admin:1234'}
    sentinel = object()
    env = create_environ(headers=headers)
    req = Request(env)
    with mock.patch(
            'http_agent.request.authenticate_entity') as mock_entity_factory:
        mock_entity_factory.return_value = sentinel
        assert req.entity is sentinel
        mock_entity_factory.assert_called_once_with(
            entity_type=EntityType['admin'], entity_id='1234')
    def expect_forbidden(self, data=None, cn=None):
        auth = httpauthclientcert.HTTPClientCertAuth(cn=cn)
        req = falcon.Request(create_environ())
        if data is not None:
            req.env[SSL_CLIENT_VERIFY] = data

        resp = falcon.Response()
        self.assertRaises(
            falcon.HTTPForbidden,
            auth.authenticate,
            req, resp)
 def test_authenticate_with_invalid_password(self):
     """
     Verify authenticate denies with a proper JSON file, Authorization header, and the wrong password.
     """
     self.http_basic_auth= httpbasicauth.HTTPBasicAuth(self.user_config)
     req = falcon.Request(
         create_environ(headers={'Authorization': 'basic YTpiCg=='}))
     resp = falcon.Response()
     self.assertRaises(
         falcon.HTTPForbidden,
         self.http_basic_auth.authenticate,
         req, resp)
Beispiel #45
0
 def test_decode_basic_auth_with_header(self):
     """
     Verify decoding returns a filled tuple given the proper header no matter the case of basic.
     """
     basic = list('basic')
     for x in range(0, 5):
         headers = {'Authorization': '{0} YTph'.format(''.join(basic))}
         req = falcon.Request(create_environ(headers=headers))
         self.assertEquals(('a', 'a'),
                           self.http_basic_auth._decode_basic_auth(req))
         # Update the next letter to be capitalized
         basic[x] = basic[x].capitalize()
 def test_authenticate_with_invalid_user(self):
     """
     Verify authenticate denies with a proper JSON file, Authorization header, and no matching user.
     """
     self.http_basic_auth_by_file = httpauth.HTTPBasicAuthByFile(
         './conf/users.json')
     req = falcon.Request(
         create_environ(headers={'Authorization': 'basic Yjpi'}))
     resp = falcon.Response()
     self.assertRaises(
         falcon.HTTPForbidden,
         self.http_basic_auth_by_file.authenticate,
         req, resp)
Beispiel #47
0
    def test_create_errors_when_json_invalid(self):

        start_response = StartResponseMock()

        self.app(
            create_environ(
                path='/entries',
                method='POST',
                body='{{[[[}}]',
            ),
            start_response,
        )[0].decode()

        self.assertTrue(start_response.status == '400 Bad Request')
Beispiel #48
0
    def test_create_errors_when_payload_invalid(self):

        start_response = StartResponseMock()

        self.app(
            create_environ(
                path='/entries',
                method='POST',
                body='{"name": "test"}',  # Missing values
            ),
            start_response,
        )[0].decode()

        self.assertTrue(start_response.status == '400 Bad Request')
 def test_decode_basic_auth_with_header(self):
     """
     Verify decoding returns a filled tuple given the proper header no matter the case of basic.
     """
     basic = list('basic')
     for x in range(0, 5):
         headers = {'Authorization': '{0} YTph'.format(''.join(basic))}
         req = falcon.Request(
             create_environ(headers=headers))
         self.assertEquals(
             ('a', 'a'),
             self.http_basic_auth._decode_basic_auth(req))
         # Update the next letter to be capitalized
         basic[x] = basic[x].capitalize()
Beispiel #50
0
    def test_results_can_be_retrieved(self):

        payload = {
            "name": "test has results",
            "setup": "pass",
            "snippets": ("pass", "pass")
        }

        start_response = StartResponseMock()
        result = self.app(
            create_environ(
                path='/entries',
                method='POST',
                body=json.dumps(payload),
            ),
            start_response,
        )[0].decode()
        result = json.loads(result)

        start_response2 = StartResponseMock()
        result2 = self.app(
            create_environ(
                path='/entries/{0}/results'.format(result['id']),
            ),
            start_response2,
        )[0].decode()
        result2 = json.loads(result2)

        self.assertTrue(start_response2.status != '404 Not Found')
        self.assertTrue(start_response2.status != '500 Internal Server Error')

        for snippet in result2['snippets']:

            self.assertTrue(snippet['runtime'] is None)
            self.assertTrue(snippet['memory']['max'] is None)
            self.assertTrue(snippet['memory']['avg'] is None)
            self.assertTrue(snippet['memory']['min'] is None)
Beispiel #51
0
def jwt_request(app, **kwargs):

	path = kwargs.pop('path')
	env = create_environ(path=path, **kwargs)
	env[OPTIO_SECRET_KEY] = 'some secret used to sign tokens'
	env[OPTIO_LOGIN_PATH] = '/login'
	resp = StartResponseMock()

	body = app(env, resp)

	data = json.loads(body[0].decode('utf-8'))

	identity = env['user_identity']

	return body, env, resp, identity, data
Beispiel #52
0
    def simulate_request(self, path, **kwargs):
        """ Simulates a request.

        Simulates a request to the API for testing purposes.

        Args:
            path: Request path for the desired resource
            kwargs: Same as falcon.testing.create_environ()

        """

        if not path:
            path = '/'

        return self.api(create_environ(path=path, **kwargs),
                        self.srmock)
    def test_authenticate_with_invalid_password(self):
        """
        Verify authenticate denies with a proper JSON file, Authorization header, and the wrong password.
        """
        with mock.patch('cherrypy.engine.publish') as _publish:
            return_value = mock.MagicMock(etcd.EtcdResult)
            with open(self.user_config, 'r') as users_file:
                return_value.value = users_file.read()
            _publish.return_value = [[return_value, None]]

            # Reload with the data from the mock'd Etcd
            http_basic_auth_by_etcd = httpauthbyetcd.HTTPBasicAuthByEtcd()

            req = falcon.Request(
                create_environ(headers={'Authorization': 'basic YTpiCg=='}))
            resp = falcon.Response()
            self.assertRaises(
                falcon.HTTPForbidden,
                http_basic_auth_by_etcd.authenticate,
                req, resp)
Beispiel #54
0
    def test_can_list_all_entries(self):

        results = self.app(
            create_environ(
                path='/entries',
            ),
            StartResponseMock(),
        )[0].decode()

        results = json.loads(results)

        try:

            for r in results:

                pass

        except TypeError:

            raise AssertionError('API results are not iterable.')
    def test_authenticate_with_valid_user(self):
        """
        Verify authenticate works with a proper JSON in Etcd, Authorization header, and a matching user.
        """
        # Mock the return of the Etcd get result
        return_value = mock.MagicMock(etcd.EtcdResult)
        with open('conf/users.json', 'r') as users_file:
            return_value.value = users_file.read()
        self.ds.get.return_value = return_value

        # Reload with the data from the mock'd Etcd
        self.http_basic_auth_by_etcd.load()

        # Test the call
        req = falcon.Request(
            create_environ(headers={'Authorization': 'basic YTph'}))
        resp = falcon.Response()
        self.assertEquals(
            None,
            self.http_basic_auth_by_etcd.authenticate(req, resp))
        self.assertEquals(1, self.ds.get.call_count)
    def test_authenticate_with_invalid_password(self):
        """
        Verify authenticate denies with a proper JSON file, Authorization header, and the wrong password.
        """
        # Mock the return of the Etcd get result
        return_value = mock.MagicMock(etcd.EtcdResult)
        with open(self.user_config, 'r') as users_file:
            return_value.value = users_file.read()
        self.ds.get.return_value = return_value

        # Reload with the data from the mock'd Etcd
        self.http_basic_auth_by_etcd.load()

        req = falcon.Request(
            create_environ(headers={'Authorization': 'basic YTpiCg=='}))
        resp = falcon.Response()
        self.assertRaises(
            falcon.HTTPForbidden,
            self.http_basic_auth_by_etcd.authenticate,
            req, resp)
        self.assertEquals(1, self.ds.get.call_count)
    def test_authenticate_with_valid_user(self):
        """
        Verify authenticate works with a proper JSON in Etcd, Authorization header, and a matching user.
        """
        with mock.patch('cherrypy.engine.publish') as _publish:
            # Mock the return of the Etcd get result
            return_value = mock.MagicMock(etcd.EtcdResult)
            with open(self.user_config, 'r') as users_file:
                return_value.value = users_file.read()

            _publish.return_value = [[return_value, None]]

            # Reload with the data from the mock'd Etcd
            http_basic_auth_by_etcd = httpauthbyetcd.HTTPBasicAuthByEtcd()

            # Test the call
            req = falcon.Request(
                create_environ(headers={'Authorization': 'basic YTph'}))
            resp = falcon.Response()
            self.assertEquals(
                None,
                http_basic_auth_by_etcd.authenticate(req, resp))
Beispiel #58
0
    def test_create_succeeds_when_payload_correct(self):

        start_response = StartResponseMock()

        result = self.app(
            create_environ(
                path='/entries',
                method='POST',
                body=json.dumps(
                    {
                        "name": "test correct payload",
                        "setup": "pass",
                        "snippets": ("pass", "pass")
                    }
                ),
            ),
            start_response,
        )[0].decode()
        result = json.loads(result)

        self.assertTrue(start_response.status == '201 Created')
        self.assertTrue(result['id'] == 'test_correct_payload')
    def test_authenticate_with_invalid_user(self):
        """
        Verify authenticate denies with a proper JSON in Etcd, Authorization header, and no matching user.
        """
        with mock.patch('cherrypy.engine.publish') as _publish:
            # Mock the return of the Etcd get result
            return_value = mock.MagicMock(etcd.EtcdResult)
            with open(self.user_config, 'r') as users_file:
                return_value.value = users_file.read()
            _publish.return_value = [[return_value, None]]

            # Reload with the data from the mock'd Etcd
            http_basic_auth = httpbasicauth.HTTPBasicAuth()

            # Test the call
            req = falcon.Request(
                create_environ(headers={'Authorization': 'basic Yjpi'}))
            resp = falcon.Response()
            self.assertRaises(
                falcon.HTTPForbidden,
                http_basic_auth.authenticate,
                req, resp)