def test_create_crypto_key_version(self): # Setup Expected Response name = "name3373707" import_job = "importJob2125587491" import_failure_reason = "importFailureReason-494073229" expected_response = { "name": name, "import_job": import_job, "import_failure_reason": import_failure_reason, } expected_response = resources_pb2.CryptoKeyVersion(**expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = kms_v1.KeyManagementServiceClient() # Setup Request parent = client.crypto_key_path("[PROJECT]", "[LOCATION]", "[KEY_RING]", "[CRYPTO_KEY]") crypto_key_version = {} response = client.create_crypto_key_version(parent, crypto_key_version) assert expected_response == response assert len(channel.requests) == 1 expected_request = service_pb2.CreateCryptoKeyVersionRequest( parent=parent, crypto_key_version=crypto_key_version) actual_request = channel.requests[0][1] assert expected_request == actual_request
def test_asymmetric_decrypt(self): # Setup Expected Response plaintext = b'-9' expected_response = {'plaintext': plaintext} expected_response = service_pb2.AsymmetricDecryptResponse( **expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) client = kms_v1.KeyManagementServiceClient(channel=channel) # Setup Request name = client.crypto_key_version_path('[PROJECT]', '[LOCATION]', '[KEY_RING]', '[CRYPTO_KEY]', '[CRYPTO_KEY_VERSION]') ciphertext = b'-72' response = client.asymmetric_decrypt(name, ciphertext) assert expected_response == response assert len(channel.requests) == 1 expected_request = service_pb2.AsymmetricDecryptRequest( name=name, ciphertext=ciphertext) actual_request = channel.requests[0][1] assert expected_request == actual_request
def decode_key(project_id: str, location: str, key_ring: str, cipher_text: str, key_name: str, client=None) -> bytes: """暗号化されたkeyを復号する Cloud Key Management Serviceを用いて暗号化されている :param str project_id: Google Cloud Platform のプロジェクトID :param str location: 場所 :param str key_ring: KEY RING :param str cipher_text: 暗号化した文字列 :param str key_name: 復号に必要なKey :return: 復号されたバイト文字列 :rtype: bytes """ if client is None: client = kms_v1.KeyManagementServiceClient() name = client.crypto_key_path(project_id, location, key_ring, key_name) response = client.decrypt(name, base64.b64decode(cipher_text)) return response.plaintext
def __init__(self, key_uri: Text, credentials_path: Text): """Creates a new GcpKmsClient that is bound to the key specified in 'key_uri'. Uses the specifed credentials when communicating with the KMS. Either of arguments can be empty. If 'key_uri' is empty, then the client is not bound to any particular key. If 'credential_path' is empty, then default credentials will be used. Args: key_uri: Text, URI of the key the client should be bound to. credentials_path: Text, Path to the file with the access credentials. Raises: FileNotFoundError: If the path to the credentials is invalid. """ if not key_uri: self.key_uri = GCP_KEYURI_PREFIX elif key_uri.startswith(GCP_KEYURI_PREFIX): self.key_uri = key_uri else: # TODO(kste): Change to tink_error when its moved to pybind11 raise ValueError if not credentials_path: # Use GCP KMS client with default credentials credentials = default() else: credentials = service_account.Credentials.from_service_account_file( filename=credentials_path) self.client = kms_v1.KeyManagementServiceClient( credentials=credentials)
def test_create_crypto_key(self): # Setup Expected Response name = 'name3373707' expected_response = {'name': name} expected_response = resources_pb2.CryptoKey(**expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) client = kms_v1.KeyManagementServiceClient(channel=channel) # Setup Request parent = client.key_ring_path('[PROJECT]', '[LOCATION]', '[KEY_RING]') crypto_key_id = 'my-app-key' purpose = enums.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT seconds = 2147483647 next_rotation_time = {'seconds': seconds} seconds_2 = 604800 rotation_period = {'seconds': seconds_2} crypto_key = { 'purpose': purpose, 'next_rotation_time': next_rotation_time, 'rotation_period': rotation_period } response = client.create_crypto_key(parent, crypto_key_id, crypto_key) assert expected_response == response assert len(channel.requests) == 1 expected_request = service_pb2.CreateCryptoKeyRequest( parent=parent, crypto_key_id=crypto_key_id, crypto_key=crypto_key) actual_request = channel.requests[0][1] assert expected_request == actual_request
def test_key_change_version_state(self): client = kms_v1.KeyManagementServiceClient() name = client.crypto_key_version_path(self.project_id, self.location, self.keyring_id, self.sym_id, self.version) state_enum = enums.CryptoKeyVersion.CryptoKeyVersionState # test disable snippets.disable_crypto_key_version(self.project_id, self.location, self.keyring_id, self.sym_id, self.version) response = client.get_crypto_key_version(name) assert response.state == state_enum.DISABLED # test destroy snippets.destroy_crypto_key_version(self.project_id, self.location, self.keyring_id, self.sym_id, self.version) response = client.get_crypto_key_version(name) assert response.state == state_enum.DESTROY_SCHEDULED # test restore snippets.restore_crypto_key_version(self.project_id, self.location, self.keyring_id, self.sym_id, self.version) response = client.get_crypto_key_version(name) assert response.state == state_enum.DISABLED # test re-enable snippets.enable_crypto_key_version(self.project_id, self.location, self.keyring_id, self.sym_id, self.version) response = client.get_crypto_key_version(name) assert response.state == state_enum.ENABLED
def verify_signature_ec(signature, message, key_name): """ Verify the validity of an 'EC_SIGN_P256_SHA256' signature for the specified message Example key_name: "projects/PROJECT_ID/locations/global/keyRings/RING_ID/cryptoKeys\ /KEY_ID/cryptoKeyVersions/1" Requires: cryptography.exceptions.InvalidSignature cryptography.hazmat.primitives.asymmetric.ec cryptography.hazmat.primitives.asymmetric.utils cryptography.hazmat.primitives.hashes hashlib """ # get the public key client = kms_v1.KeyManagementServiceClient() response = client.get_public_key(key_name) key_txt = response.pem.encode('ascii') public_key = serialization.load_pem_public_key(key_txt, default_backend()) # get the digest of the message digest_bytes = hashlib.sha256(message).digest() try: # Attempt verification public_key.verify(signature, digest_bytes, ec.ECDSA(utils.Prehashed(hashes.SHA256()))) # No errors were thrown. Verification was successful return True except InvalidSignature: return False
def test_update_crypto_key_version(self): # Setup Expected Response name = "name3373707" expected_response = {"name": name} expected_response = resources_pb2.CryptoKeyVersion(**expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = kms_v1.KeyManagementServiceClient() # Setup Request crypto_key_version = {} update_mask = {} response = client.update_crypto_key_version(crypto_key_version, update_mask) assert expected_response == response assert len(channel.requests) == 1 expected_request = service_pb2.UpdateCryptoKeyVersionRequest( crypto_key_version=crypto_key_version, update_mask=update_mask) actual_request = channel.requests[0][1] assert expected_request == actual_request
def test_decrypt(self): # Setup Expected Response plaintext = b"-9" expected_response = {"plaintext": plaintext} expected_response = service_pb2.DecryptResponse(**expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = kms_v1.KeyManagementServiceClient() # Setup Request name = client.crypto_key_path("[PROJECT]", "[LOCATION]", "[KEY_RING]", "[CRYPTO_KEY]") ciphertext = b"-72" response = client.decrypt(name, ciphertext) assert expected_response == response assert len(channel.requests) == 1 expected_request = service_pb2.DecryptRequest(name=name, ciphertext=ciphertext) actual_request = channel.requests[0][1] assert expected_request == actual_request
def test_create_key_ring(self): # Setup Expected Response name = "name3373707" expected_response = {"name": name} expected_response = resources_pb2.KeyRing(**expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = kms_v1.KeyManagementServiceClient() # Setup Request parent = client.location_path("[PROJECT]", "[LOCATION]") key_ring_id = "keyRingId-2056646742" key_ring = {} response = client.create_key_ring(parent, key_ring_id, key_ring) assert expected_response == response assert len(channel.requests) == 1 expected_request = service_pb2.CreateKeyRingRequest( parent=parent, key_ring_id=key_ring_id, key_ring=key_ring) actual_request = channel.requests[0][1] assert expected_request == actual_request
def test_create_crypto_key(self): # Setup Expected Response name = "name3373707" expected_response = {"name": name} expected_response = resources_pb2.CryptoKey(**expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = kms_v1.KeyManagementServiceClient() # Setup Request parent = client.key_ring_path("[PROJECT]", "[LOCATION]", "[KEY_RING]") crypto_key_id = "my-app-key" purpose = enums.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT seconds = 2147483647 next_rotation_time = {"seconds": seconds} seconds_2 = 604800 rotation_period = {"seconds": seconds_2} crypto_key = { "purpose": purpose, "next_rotation_time": next_rotation_time, "rotation_period": rotation_period, } response = client.create_crypto_key(parent, crypto_key_id, crypto_key) assert expected_response == response assert len(channel.requests) == 1 expected_request = service_pb2.CreateCryptoKeyRequest( parent=parent, crypto_key_id=crypto_key_id, crypto_key=crypto_key) actual_request = channel.requests[0][1] assert expected_request == actual_request
def test_test_iam_permissions(self): # Setup Expected Response expected_response = {} expected_response = iam_policy_pb2.TestIamPermissionsResponse( **expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = kms_v1.KeyManagementServiceClient() # Setup Request resource = client.key_ring_path("[PROJECT]", "[LOCATION]", "[KEY_RING]") permissions = [] response = client.test_iam_permissions(resource, permissions) assert expected_response == response assert len(channel.requests) == 1 expected_request = iam_policy_pb2.TestIamPermissionsRequest( resource=resource, permissions=permissions) actual_request = channel.requests[0][1] assert expected_request == actual_request
def remove_member_from_key_ring_policy(project_id, location_id, key_ring_id, member, role): """Removes a member with a given role from the Identity and Access Management (IAM) policy for a given KeyRing.""" from google.cloud import kms_v1 # Creates an API client for the KMS API. client = kms_v1.KeyManagementServiceClient() # The resource name of the KeyRing. resource = client.key_ring_path(project_id, location_id, key_ring_id) # Get the current IAM policy. policy = client.get_iam_policy(resource) # Remove member for b in list(policy.bindings): if b.role == role and member in b.members: b.members.remove(member) # Update the IAM Policy. client.set_iam_policy(resource, policy) # Print results print('Member {} removed from role {} for KeyRing {}'.format( member, role, key_ring_id))
def test_import_crypto_key_version(self): # Setup Expected Response name = "name3373707" import_job_2 = "importJob2-1714851050" import_failure_reason = "importFailureReason-494073229" expected_response = { "name": name, "import_job": import_job_2, "import_failure_reason": import_failure_reason, } expected_response = resources_pb2.CryptoKeyVersion(**expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = kms_v1.KeyManagementServiceClient() # Setup Request parent = client.crypto_key_path("[PROJECT]", "[LOCATION]", "[KEY_RING]", "[CRYPTO_KEY]") algorithm = (enums.CryptoKeyVersion.CryptoKeyVersionAlgorithm. CRYPTO_KEY_VERSION_ALGORITHM_UNSPECIFIED) import_job = "importJob2125587491" response = client.import_crypto_key_version(parent, algorithm, import_job) assert expected_response == response assert len(channel.requests) == 1 expected_request = service_pb2.ImportCryptoKeyVersionRequest( parent=parent, algorithm=algorithm, import_job=import_job) actual_request = channel.requests[0][1] assert expected_request == actual_request
def add_member_to_crypto_key_policy(project_id, location_id, key_ring_id, crypto_key_id, member, role): """Adds a member with a given role to the Identity and Access Management (IAM) policy for a given CryptoKey associated with a KeyRing.""" from google.cloud import kms_v1 # Creates an API client for the KMS API. client = kms_v1.KeyManagementServiceClient() # The resource name of the CryptoKey. resource = client.crypto_key_path_path(project_id, location_id, key_ring_id, crypto_key_id) # Get the current IAM policy. policy = client.get_iam_policy(resource) # Add member policy.bindings.add(role=role, members=[member]) # Update the IAM Policy. client.set_iam_policy(resource, policy) # Print results print("Member {} added with role {} to policy for CryptoKey {} \ in KeyRing {}".format(member, role, crypto_key_id, key_ring_id))
def test_list_key_rings(self): # Setup Expected Response next_page_token = "" total_size = 705419236 key_rings_element = {} key_rings = [key_rings_element] expected_response = { "next_page_token": next_page_token, "total_size": total_size, "key_rings": key_rings, } expected_response = service_pb2.ListKeyRingsResponse( **expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = kms_v1.KeyManagementServiceClient() # Setup Request parent = client.location_path("[PROJECT]", "[LOCATION]") paged_list_response = client.list_key_rings(parent) resources = list(paged_list_response) assert len(resources) == 1 assert expected_response.key_rings[0] == resources[0] assert len(channel.requests) == 1 expected_request = service_pb2.ListKeyRingsRequest(parent=parent) actual_request = channel.requests[0][1] assert expected_request == actual_request
def list_keys(): # Imports the Google APIs client library from google.cloud import kms_v1 # Your Google Cloud Platform project ID project_id = GCP_PROJECT # Lists keys in the "global" location. location = 'global' # Creates an API client for the KMS API. client = kms_v1.KeyManagementServiceClient() # The resource name of the location associated with the key rings. parent = client.location_path(project_id, location) # Lists key rings response = client.list_key_rings(parent) response_list = list(response) if len(response_list) > 0: print('Key rings:') for key_ring in response_list: print(key_ring.name) else: print('No key rings found.')
def test_restore_crypto_key_version(self): # Setup Expected Response name_2 = "name2-1052831874" expected_response = {"name": name_2} expected_response = resources_pb2.CryptoKeyVersion(**expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = kms_v1.KeyManagementServiceClient() # Setup Request name = client.crypto_key_version_path( "[PROJECT]", "[LOCATION]", "[KEY_RING]", "[CRYPTO_KEY]", "[CRYPTO_KEY_VERSION]", ) response = client.restore_crypto_key_version(name) assert expected_response == response assert len(channel.requests) == 1 expected_request = service_pb2.RestoreCryptoKeyVersionRequest( name=name) actual_request = channel.requests[0][1] assert expected_request == actual_request
def test_create_key_ring(self): ring_id = self.keyring_id + '-test-create-{}'.format(uuid.uuid4().hex) snippets.create_key_ring(self.project_id, self.location, ring_id) client = kms_v1.KeyManagementServiceClient() result = client.get_key_ring( client.key_ring_path(self.project_id, self.location, ring_id)) assert ring_id in result.name
def test_get_public_key(self): # Setup Expected Response pem = "pem110872" expected_response = {"pem": pem} expected_response = resources_pb2.PublicKey(**expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = kms_v1.KeyManagementServiceClient() # Setup Request name = client.crypto_key_version_path( "[PROJECT]", "[LOCATION]", "[KEY_RING]", "[CRYPTO_KEY]", "[CRYPTO_KEY_VERSION]", ) response = client.get_public_key(name) assert expected_response == response assert len(channel.requests) == 1 expected_request = service_pb2.GetPublicKeyRequest(name=name) actual_request = channel.requests[0][1] assert expected_request == actual_request
def create_asymmetric_key(project_id, location_id, key_ring_id, crypto_key_id): """Creates an RSA encrypt/decrypt key pair within a specified KeyRing.""" # Creates an API client for the KMS API. client = kms_v1.KeyManagementServiceClient() # The resource name of the KeyRing associated with the CryptoKey. parent = client.key_ring_path(project_id, location_id, key_ring_id) # Create the CryptoKey object template purpose = enums.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT algorithm = enums.CryptoKeyVersion.CryptoKeyVersionAlgorithm.\ RSA_DECRYPT_OAEP_2048_SHA256 crypto_key = { 'purpose': purpose, 'version_template': { 'algorithm': algorithm } } # Create a CryptoKey for the given KeyRing. response = client.create_crypto_key(parent, crypto_key_id, crypto_key) print('Created CryptoKey {}.'.format(response.name)) return response
def test_asymmetric_sign(self): # Setup Expected Response signature = b"-100" expected_response = {"signature": signature} expected_response = service_pb2.AsymmetricSignResponse( **expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = kms_v1.KeyManagementServiceClient() # Setup Request name = client.crypto_key_version_path( "[PROJECT]", "[LOCATION]", "[KEY_RING]", "[CRYPTO_KEY]", "[CRYPTO_KEY_VERSION]", ) digest = {} response = client.asymmetric_sign(name, digest) assert expected_response == response assert len(channel.requests) == 1 expected_request = service_pb2.AsymmetricSignRequest(name=name, digest=digest) actual_request = channel.requests[0][1] assert expected_request == actual_request
def test_list_crypto_key_versions(self): # Setup Expected Response next_page_token = '' total_size = 705419236 crypto_key_versions_element = {} crypto_key_versions = [crypto_key_versions_element] expected_response = { 'next_page_token': next_page_token, 'total_size': total_size, 'crypto_key_versions': crypto_key_versions } expected_response = service_pb2.ListCryptoKeyVersionsResponse( **expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) client = kms_v1.KeyManagementServiceClient(channel=channel) # Setup Request parent = client.crypto_key_path('[PROJECT]', '[LOCATION]', '[KEY_RING]', '[CRYPTO_KEY]') paged_list_response = client.list_crypto_key_versions(parent) resources = list(paged_list_response) assert len(resources) == 1 assert expected_response.crypto_key_versions[0] == resources[0] assert len(channel.requests) == 1 expected_request = service_pb2.ListCryptoKeyVersionsRequest( parent=parent) actual_request = channel.requests[0][1] assert expected_request == actual_request
def test_set_iam_policy(self): # Setup Expected Response version = 351608024 etag = b"21" expected_response = {"version": version, "etag": etag} expected_response = policy_pb2.Policy(**expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = kms_v1.KeyManagementServiceClient() # Setup Request resource = client.key_ring_path("[PROJECT]", "[LOCATION]", "[KEY_RING]") policy = {} response = client.set_iam_policy(resource, policy) assert expected_response == response assert len(channel.requests) == 1 expected_request = iam_policy_pb2.SetIamPolicyRequest( resource=resource, policy=policy) actual_request = channel.requests[0][1] assert expected_request == actual_request
def test_list_key_rings(self): # Setup Expected Response next_page_token = '' total_size = 705419236 key_rings_element = {} key_rings = [key_rings_element] expected_response = { 'next_page_token': next_page_token, 'total_size': total_size, 'key_rings': key_rings } expected_response = service_pb2.ListKeyRingsResponse( **expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) client = kms_v1.KeyManagementServiceClient(channel=channel) # Setup Request parent = client.location_path('[PROJECT]', '[LOCATION]') paged_list_response = client.list_key_rings(parent) resources = list(paged_list_response) assert len(resources) == 1 assert expected_response.key_rings[0] == resources[0] assert len(channel.requests) == 1 expected_request = service_pb2.ListKeyRingsRequest(parent=parent) actual_request = channel.requests[0][1] assert expected_request == actual_request
def google_kms_decrypt(a, *args, **kwargs): kms_project = kwargs.get("kms_project", KMS_PROJECT) kms_location = kwargs.get("kms_location", KMS_LOCATION) kms_keyring = kwargs.get("kms_keyring", KMS_KEYRING) kms_keyname = kwargs.get("kms_key", KMS_KEYNAME) if kms_project is None: raise ValueError("Missing value for KMS Project") if kms_location is None: raise ValueError("Missing value for KMS Location") if kms_keyring is None: raise ValueError("Missing value for KMS keyring") if kms_keyname is None: raise ValueError("Missing value for KMS keyname") kms = kms_v1.KeyManagementServiceClient() keyname = kms.crypto_key_path_path(kms_project, kms_location, kms_keyring, kms_keyname) return str( kms.decrypt(keyname, base64.b64decode(a)).plaintext.decode("ascii").strip())
def test_asymmetric_sign(self): # Setup Expected Response signature = b'-100' expected_response = {'signature': signature} expected_response = service_pb2.AsymmetricSignResponse( **expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) client = kms_v1.KeyManagementServiceClient(channel=channel) # Setup Request name = client.crypto_key_version_path('[PROJECT]', '[LOCATION]', '[KEY_RING]', '[CRYPTO_KEY]', '[CRYPTO_KEY_VERSION]') digest = {} response = client.asymmetric_sign(name, digest) assert expected_response == response assert len(channel.requests) == 1 expected_request = service_pb2.AsymmetricSignRequest(name=name, digest=digest) actual_request = channel.requests[0][1] assert expected_request == actual_request
def main(): args = get_args() # Log in to Box LOG.info("Authenticating with Box and impersonating user {}.".format( args.login)) kms = kms_v1.KeyManagementServiceClient() config_ciphertext = open(args.config, 'rb').read() config_plaintext = kms.decrypt(args.keyname, config_ciphertext).plaintext box = impersonate_mirror_user(get_box_client(config_plaintext), args.login) # Log in to GCS and get bucket bucket_name = args.bucket.replace("gs://", "") LOG.info( "Authenticating with GCS and fetching bucket {}.".format(bucket_name)) bucket = GCSClient().get_bucket(bucket_name) # Walk Box, schedule async copies to GCS, and get a list of new blobs. # We will also opportunistically form a cache of the Box items. LOG.info("Walking Box directories and copying to GCS as needed.") box_cache = {'/': box.root_folder()} copy_jobs = sync_box_to_gcs(box, bucket, cache=box_cache) # Check for and log exceptions. Doing this here also institutes a "pause" between the two sync phases. for exc in get_exceptions(copy_jobs): LOG.exception(exc) # Walk GCS, checking against the cache of Box items, and as needed, schedule async uploads to Box LOG.info("Listing GCS blobs and looking for blobs to upload or delete.") copy_jobs = sync_gcs_to_box(bucket, box, cache=box_cache) # Check for and log exceptions for exc in get_exceptions(copy_jobs): LOG.exception(exc) LOG.info("Synchronization complete.")
def test_list_global_key_rings(self): project_id = os.environ["PROJECT_ID"] client = kms_v1.KeyManagementServiceClient() location = "global" parent = client.location_path(project_id, location) client.list_key_rings(parent)
def test_create_import_job(self): # Setup Expected Response name = "name3373707" expected_response = {"name": name} expected_response = resources_pb2.ImportJob(**expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = kms_v1.KeyManagementServiceClient() # Setup Request parent = client.key_ring_path("[PROJECT]", "[LOCATION]", "[KEY_RING]") import_job_id = "my-import-job" import_method = enums.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 protection_level = enums.ProtectionLevel.HSM import_job = { "import_method": import_method, "protection_level": protection_level, } response = client.create_import_job(parent, import_job_id, import_job) assert expected_response == response assert len(channel.requests) == 1 expected_request = service_pb2.CreateImportJobRequest( parent=parent, import_job_id=import_job_id, import_job=import_job) actual_request = channel.requests[0][1] assert expected_request == actual_request