def test_acl_provider(self, get_header_mock, path_mock, method_mock): method_mock.return_value = 'GET' path_mock.return_value = '/todos' with TemporaryDirectory() as tmpdir: rsa_key = generate_rsa_keypair() priv_key = serialize_private_pem(rsa_key) pub_key = serialize_public_pem(rsa_key) with open(path_join(tmpdir, 'system'), 'wb') as keyfile: keyfile.write(priv_key) with open(path_join(tmpdir, 'system.pub'), 'wb') as keyfile: keyfile.write(pub_key) key_store = KeyStore(dir_path=tmpdir) header_token = get_jwt( key_store, { 'userId': 'test-user', 'username': '******', 'scopes': 'api:read', 'roles': 'user', 'organizations': 'test-organization', 'namespaces': 'test-namespace', }, ) get_header_mock.return_value = 'Bearer %s' % header_token jwt_provider = JWTProvider(key_store=key_store) local_context = local() # Thread-Local underlying local context context = SecurityContext(local_context=local_context) req_object = local() request = Request(req_object) response = Response() jwt_provider(context, request, response) acl_provider = ACLProvider(CONFIG_ACL) # Check SecurityException is not thrown acl_provider(context, request, response) assert context.has_auth() auth = context.get_auth() assert auth is not None assert auth.user_id == 'test-user' assert auth.username == 'ana' assert auth.scopes == ['api:read'] assert auth.roles == ['user'] assert auth.organizations == ['test-organization'] assert auth.namespaces == ['test-namespace']
def test_saml_sp(host_mock, form_mock, args_mock, register_sp_mock): """ Test SAML SP middleware """ register_sp_mock.return_value = 'OK' args_mock.return_value = ['arg1'] form_mock.return_value = {'RelayState': 'dsd67atdas6dad67ad67a'} host_mock = 'localhost:5000' with TemporaryDirectory() as tmpdir: rsa_key = generate_RSA_keypair() priv_key = serialize_private_pem(rsa_key) pub_key = serialize_public_pem(rsa_key) with open(path_join(tmpdir, 'service.key'), 'wb') as keyfile: keyfile.write(priv_key) with open(path_join(tmpdir, 'service.cert'), 'wb') as keyfile: keyfile.write(pub_key) key_store = KeyStore(dir_path=tmpdir) local_context = local() # Thread-Local underlying local context context = SecurityContext(local_context=local_context) req_object = local() request = Request(req_object) response = Response() sp = SAMLServiceProvider(key_store, configSAML) sp(context, request, response) assert response.redirect_url.startswith( 'http://*****:*****@example.com'], 'urn:oid:1.3.6.1.4.1.5923.1.1.1.1': ['user'] } } sp = SAMLServiceProvider(key_store, configSAML, saml_session=saml_session) sp(context, request, response) auth = context.get_auth() assert context.has_auth() assert auth.user_id == 'test-user' assert auth.roles == ['user'] assert auth.username == '*****@*****.**'
def test_jwt_pass(get_header_mock): """Test the JWT provider in a successful vanila scenario. """ with TemporaryDirectory() as tmpdir: rsa_key = generate_RSA_keypair() priv_key = serialize_private_pem(rsa_key) pub_key = serialize_public_pem(rsa_key) with open(path_join(tmpdir, 'system'), 'wb') as keyfile: keyfile.write(priv_key) with open(path_join(tmpdir, 'system.pub'), 'wb') as keyfile: keyfile.write(pub_key) key_store = KeyStore(dir_path=tmpdir) header_token = get_jwt( key_store, { 'userId': 'test-user', 'username': '******', 'scopes': 'api:read', 'roles': 'user,test', 'organizations': 'org1,org2', 'namespaces': 'microkubes,special1' }) get_header_mock.return_value = 'Bearer %s' % header_token jwt_provider = JWTProvider(key_store=key_store) local_context = local() # Thread-Local underlying local context context = SecurityContext(local_context=local_context) req_object = local() request = Request(req_object) response = Response() jwt_provider(context, request, response) assert context.has_auth() auth = context.get_auth() assert auth is not None assert auth.user_id == 'test-user' assert auth.username == '*****@*****.**' assert auth.scopes == ['api:read'] assert auth.roles == ['user', 'test'] assert auth.organizations == ['org1', 'org2'] assert auth.namespaces == ['microkubes', 'special1']
def test_is_authenticated_provider_pass(has_auth_mock): """Test is_authenticated provider - authenticated scenario. """ has_auth_mock.return_value = True sc = SecurityContext(None) req = Request(None) resp = Response() is_authenticated_provider(sc, req, resp) assert has_auth_mock.call_count == 1
def test_public_routes_provider(): """Test public routes provider. """ def expect(exc, fn, *args): """Expect fn to throw an exception of the provided type. """ try: fn(*args) except Exception as e: if not isinstance(e, exc): raise Exception('Expected error of type %s but got "%s" of type: %s' % (exc, e, type(e))) return raise Exception("Expected error of type %s but none was raised." % e) _R = namedtuple('_Request', ['path']) def request(path): """Create new request with this path. """ return Request(_R(path)) sc = SecurityContext(None) resp = Response() # test exact matches provider = public_routes_provider('/path', '/longer/path') expect(BreakChain, provider, sc, request('/path'), resp) expect(BreakChain, provider, sc, request('/longer/path'), resp) provider(sc, request('/not/matched'), resp) provider(sc, request('/longer/path/invalid'), resp) # test pattern provider = public_routes_provider('/path/.*', r'.*\.js') expect(BreakChain, provider, sc, request('/path/a'), resp) expect(BreakChain, provider, sc, request('/path/longer'), resp) expect(BreakChain, provider, sc, request('/resources/file.js'), resp) expect(BreakChain, provider, sc, request('file.js'), resp) provider(sc, request('/path'), resp) provider(sc, request('/api/v1/service'), resp) provider(sc, request('/api.js/v1'), resp)
def test_is_authenticated_provider_block(has_auth_mock): """Test is_authenticated provider - not authenticated scenario. """ has_auth_mock.return_value = False sc = SecurityContext(None) req = Request(None) resp = Response() err = None try: is_authenticated_provider(sc, req, resp) except SecurityException as sec: err = sec assert has_auth_mock.call_count == 1 assert err is not None assert err.status_code == 401 assert str(err) == 'authentication required'
def test_security_context(): """Test SecurityContext with thread-local based context. """ local_context = local() sc = SecurityContext(local_context) assert sc.has_auth() is False auth = Auth(user_id="test", username="******") sc.set_auth(auth) assert local_context.microkubes_auth is not None assert sc.has_auth() is True result = sc.get_auth() assert result is not None assert result == auth sc.clear_auth() assert local_context.microkubes_auth is None assert sc.has_auth() is False assert sc.get_auth() is None