Search in sources :

Example 1 with Binding

use of com.google.api.services.iam.v1.model.Binding in project google-cloud-intellij by GoogleCloudPlatform.

the class CloudApiManager method addRolesToServiceAccount.

/**
 * Adds a set of {@link Role roles} to a {@link ServiceAccount}.
 *
 * <p>This is done by fetching the cloud project's existing IAM Policy, adding the new roles to
 * the given service account, and then writing the updated policy back to the cloud project.
 *
 * @param user the current {@link CredentialedUser}
 * @param serviceAccount the {@link ServiceAccount} to which to add roles
 * @param roles the set of {@link Role} to be added to the service account
 * @param cloudProject the current {@link CloudProject}
 * @throws IOException if the API call fails to update the IAM policy
 */
private static void addRolesToServiceAccount(CredentialedUser user, ServiceAccount serviceAccount, Set<Role> roles, CloudProject cloudProject) throws IOException {
    CloudResourceManager resourceManager = GoogleApiClientFactory.getInstance().getCloudResourceManagerClient(user.getCredential());
    Policy existingPolicy = resourceManager.projects().getIamPolicy(cloudProject.projectId(), new GetIamPolicyRequest()).execute();
    List<Binding> bindings = Lists.newArrayList(existingPolicy.getBindings());
    List<Binding> additionalBindings = roles.stream().map(role -> {
        Binding binding = new Binding();
        binding.setRole(role.getName());
        binding.setMembers(createServiceAccountMemberBindings(serviceAccount));
        return binding;
    }).collect(Collectors.toList());
    bindings.addAll(additionalBindings);
    SetIamPolicyRequest policyRequest = new SetIamPolicyRequest();
    Policy newPolicy = new Policy();
    newPolicy.setBindings(bindings);
    policyRequest.setPolicy(newPolicy);
    resourceManager.projects().setIamPolicy(cloudProject.projectId(), policyRequest).execute();
}
Also used : Policy(com.google.api.services.cloudresourcemanager.model.Policy) Binding(com.google.api.services.cloudresourcemanager.model.Binding) ServiceAccountKey(com.google.api.services.iam.v1.model.ServiceAccountKey) ZonedDateTime(java.time.ZonedDateTime) Binding(com.google.api.services.cloudresourcemanager.model.Binding) Role(com.google.api.services.iam.v1.model.Role) CloudProject(com.google.cloud.tools.intellij.project.CloudProject) Logger(com.intellij.openapi.diagnostic.Logger) Path(java.nio.file.Path) ProgressManager(com.intellij.openapi.progress.ProgressManager) CloudLibrary(com.google.cloud.tools.libraries.json.CloudLibrary) Set(java.util.Set) EnableServiceRequest(com.google.api.services.servicemanagement.model.EnableServiceRequest) GoogleApiClientFactory(com.google.cloud.tools.intellij.resources.GoogleApiClientFactory) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) NotificationType(com.intellij.notification.NotificationType) Notification(com.intellij.notification.Notification) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) List(java.util.List) ServiceManager(com.intellij.openapi.components.ServiceManager) Services(com.google.cloud.tools.intellij.login.Services) ApplicationManager(com.intellij.openapi.application.ApplicationManager) Optional(java.util.Optional) ServiceManagement(com.google.api.services.servicemanagement.ServiceManagement) Pattern(java.util.regex.Pattern) SetIamPolicyRequest(com.google.api.services.cloudresourcemanager.model.SetIamPolicyRequest) NotificationDisplayType(com.intellij.notification.NotificationDisplayType) ServiceAccount(com.google.api.services.iam.v1.model.ServiceAccount) ArrayList(java.util.ArrayList) GetIamPolicyRequest(com.google.api.services.cloudresourcemanager.model.GetIamPolicyRequest) CloudResourceManager(com.google.api.services.cloudresourcemanager.CloudResourceManager) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) PropertiesFileFlagReader(com.google.cloud.tools.intellij.flags.PropertiesFileFlagReader) NotificationGroup(com.intellij.notification.NotificationGroup) CredentialedUser(com.google.cloud.tools.intellij.login.CredentialedUser) CreateServiceAccountKeyRequest(com.google.api.services.iam.v1.model.CreateServiceAccountKeyRequest) Project(com.intellij.openapi.project.Project) GctBundle(com.google.cloud.tools.intellij.util.GctBundle) DialogManager(git4idea.DialogManager) Policy(com.google.api.services.cloudresourcemanager.model.Policy) Base64(com.google.api.client.util.Base64) Files(java.nio.file.Files) GctTracking(com.google.cloud.tools.intellij.analytics.GctTracking) IOException(java.io.IOException) UsageTrackerProvider(com.google.cloud.tools.intellij.analytics.UsageTrackerProvider) Paths(java.nio.file.Paths) CreateServiceAccountRequest(com.google.api.services.iam.v1.model.CreateServiceAccountRequest) DateTimeFormatter(java.time.format.DateTimeFormatter) Iam(com.google.api.services.iam.v1.Iam) GoogleCloudCoreIcons(com.google.cloud.tools.intellij.GoogleCloudCoreIcons) CloudResourceManager(com.google.api.services.cloudresourcemanager.CloudResourceManager) SetIamPolicyRequest(com.google.api.services.cloudresourcemanager.model.SetIamPolicyRequest) GetIamPolicyRequest(com.google.api.services.cloudresourcemanager.model.GetIamPolicyRequest)

Example 2 with Binding

use of com.google.api.services.iam.v1.model.Binding in project java-docs-samples by GoogleCloudPlatform.

the class Snippets method addMemberToCryptoKeyPolicy.

// [END kms_get_keyring_policy]
// [START kms_add_member_to_cryptokey_policy]
/**
 * Adds the given member to the given key, with the given role.
 *
 * @param projectId The id of the project.
 * @param locationId The location id of the key.
 * @param keyRingId The id of the keyring.
 * @param cryptoKeyId The id of the crypto key.
 * @param member The member to add. Must be in the proper format, eg:
 *
 * allUsers user:$userEmail serviceAccount:$serviceAccountEmail
 *
 * See https://g.co/cloud/kms/docs/reference/rest/v1/Policy#binding for more details.
 * @param role Must be in one of the following formats: roles/[role]
 * organizations/[organizationId]/roles/[role] projects/[projectId]/roles/[role]
 *
 * See https://g.co/cloud/iam/docs/understanding-roles for available values for [role].
 */
public static Policy addMemberToCryptoKeyPolicy(String projectId, String locationId, String keyRingId, String cryptoKeyId, String member, String role) throws IOException {
    // Create the Cloud KMS client.
    CloudKMS kms = createAuthorizedClient();
    // The resource name of the cryptoKey version
    String cryptoKey = String.format("projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s", projectId, locationId, keyRingId, cryptoKeyId);
    // Get the current IAM policy
    Policy iamPolicy = getCryptoKeyPolicy(projectId, locationId, keyRingId, cryptoKeyId);
    // Add the new account to it.
    Binding newBinding = new Binding().setRole(role).setMembers(Collections.singletonList(member));
    List<Binding> bindings = iamPolicy.getBindings();
    if (null == bindings) {
        bindings = Collections.singletonList(newBinding);
    } else {
        bindings.add(newBinding);
    }
    iamPolicy.setBindings(bindings);
    // Set the new IAM Policy.
    Policy newIamPolicy = kms.projects().locations().keyRings().cryptoKeys().setIamPolicy(cryptoKey, new SetIamPolicyRequest().setPolicy(iamPolicy)).execute();
    System.out.println("Response: " + newIamPolicy);
    return newIamPolicy;
}
Also used : Policy(com.google.api.services.cloudkms.v1.model.Policy) Binding(com.google.api.services.cloudkms.v1.model.Binding) CloudKMS(com.google.api.services.cloudkms.v1.CloudKMS) SetIamPolicyRequest(com.google.api.services.cloudkms.v1.model.SetIamPolicyRequest)

Example 3 with Binding

use of com.google.api.services.iam.v1.model.Binding in project java-docs-samples by GoogleCloudPlatform.

the class Snippets method addMemberToKeyRingPolicy.

// [END kms_add_member_to_cryptokey_policy]
// [START kms_add_member_to_keyring_policy]
/**
 * Adds the given member to the given keyring, with the given role.
 *
 * @param projectId The id of the project.
 * @param locationId The location id of the key.
 * @param keyRingId The id of the keyring.
 * @param member The member to add. Must be in the proper format, eg:
 *
 * allUsers user:$userEmail serviceAccount:$serviceAccountEmail
 *
 * See https://g.co/cloud/kms/docs/reference/rest/v1/Policy#binding for more details.
 * @param role Must be in one of the following formats: roles/[role]
 * organizations/[organizationId]/roles/[role] projects/[projectId]/roles/[role]
 *
 * See https://g.co/cloud/iam/docs/understanding-roles for available values for [role].
 */
public static Policy addMemberToKeyRingPolicy(String projectId, String locationId, String keyRingId, String member, String role) throws IOException {
    // Create the Cloud KMS client.
    CloudKMS kms = createAuthorizedClient();
    // The resource name of the keyring version
    String keyring = String.format("projects/%s/locations/%s/keyRings/%s", projectId, locationId, keyRingId);
    // Get the current IAM policy
    Policy iamPolicy = getKeyRingPolicy(projectId, locationId, keyRingId);
    // Add the new account to it.
    Binding newBinding = new Binding().setRole(role).setMembers(Collections.singletonList(member));
    List<Binding> bindings = iamPolicy.getBindings();
    if (null == bindings) {
        bindings = Collections.singletonList(newBinding);
    } else {
        bindings.add(newBinding);
    }
    iamPolicy.setBindings(bindings);
    // Set the new IAM Policy.
    Policy newIamPolicy = kms.projects().locations().keyRings().setIamPolicy(keyring, new SetIamPolicyRequest().setPolicy(iamPolicy)).execute();
    System.out.println("Response: " + newIamPolicy);
    return newIamPolicy;
}
Also used : Policy(com.google.api.services.cloudkms.v1.model.Policy) Binding(com.google.api.services.cloudkms.v1.model.Binding) CloudKMS(com.google.api.services.cloudkms.v1.CloudKMS) SetIamPolicyRequest(com.google.api.services.cloudkms.v1.model.SetIamPolicyRequest)

Example 4 with Binding

use of com.google.api.services.iam.v1.model.Binding in project java-docs-samples by GoogleCloudPlatform.

the class Snippets method removeMemberFromKeyRingPolicy.

// [END kms_remove_member_from_cryptokey_policy]
// [START kms_remove_member_from_keyring_policy]
/**
 * Removes the given member from the given policy.
 */
public static Policy removeMemberFromKeyRingPolicy(String projectId, String locationId, String keyRingId, String member, String role) throws IOException {
    // Create the Cloud KMS client.
    CloudKMS kms = createAuthorizedClient();
    // The resource name of the cryptoKey
    String cryptoKey = String.format("projects/%s/locations/%s/keyRings/%s", projectId, locationId, keyRingId);
    // Get the current IAM policy and add the new account to it.
    Policy iamPolicy = getKeyRingPolicy(projectId, locationId, keyRingId);
    // Filter out the given member
    for (Binding b : iamPolicy.getBindings()) {
        if (role.equals(b.getRole()) && b.getMembers().contains(member)) {
            b.getMembers().remove(member);
            break;
        }
    }
    // Set the new IAM Policy.
    Policy newIamPolicy = kms.projects().locations().keyRings().setIamPolicy(cryptoKey, new SetIamPolicyRequest().setPolicy(iamPolicy)).execute();
    System.out.println("Response: " + newIamPolicy);
    return newIamPolicy;
}
Also used : Policy(com.google.api.services.cloudkms.v1.model.Policy) Binding(com.google.api.services.cloudkms.v1.model.Binding) CloudKMS(com.google.api.services.cloudkms.v1.CloudKMS) SetIamPolicyRequest(com.google.api.services.cloudkms.v1.model.SetIamPolicyRequest)

Example 5 with Binding

use of com.google.api.services.iam.v1.model.Binding in project java-docs-samples by GoogleCloudPlatform.

the class QuickstartTests method testQuickstart.

@Test
public void testQuickstart() throws Exception {
    String member = "serviceAccount:" + serviceAccount.getEmail();
    String role = "roles/logging.logWriter";
    // Tests initializeService()
    CloudResourceManager crmService = Quickstart.initializeService();
    // Tests addBinding()
    Quickstart.addBinding(crmService, "projects/" + PROJECT_ID, member, role);
    // Get the project's polcy and confirm that the member is in the policy
    Policy policy = Quickstart.getPolicy(crmService, "projects/" + PROJECT_ID);
    Binding binding = null;
    List<Binding> bindings = policy.getBindings();
    for (Binding b : bindings) {
        if (b.getRole().equals(role)) {
            binding = b;
            break;
        }
    }
    assertThat(binding.getMembers(), hasItem(member));
    // Tests removeMember()
    Quickstart.removeMember(crmService, "projects/" + PROJECT_ID, member, role);
    // Confirm that the member has been removed
    policy = Quickstart.getPolicy(crmService, "projects/" + PROJECT_ID);
    binding = null;
    bindings = policy.getBindings();
    for (Binding b : bindings) {
        if (b.getRole().equals(role)) {
            binding = b;
            break;
        }
    }
    if (binding != null) {
        assertThat(binding.getMembers(), not(hasItem(member)));
    }
}
Also used : Policy(com.google.api.services.cloudresourcemanager.v3.model.Policy) Binding(com.google.api.services.cloudresourcemanager.v3.model.Binding) CloudResourceManager(com.google.api.services.cloudresourcemanager.v3.CloudResourceManager) Test(org.junit.Test)

Aggregations

Binding (com.google.api.services.cloudresourcemanager.v3.model.Binding)12 Policy (com.google.api.services.cloudresourcemanager.v3.model.Policy)9 IOException (java.io.IOException)9 Binding (com.google.api.services.iam.v1.model.Binding)5 ArrayList (java.util.ArrayList)5 CloudKMS (com.google.api.services.cloudkms.v1.CloudKMS)4 Binding (com.google.api.services.cloudkms.v1.model.Binding)4 Policy (com.google.api.services.cloudkms.v1.model.Policy)4 SetIamPolicyRequest (com.google.api.services.cloudkms.v1.model.SetIamPolicyRequest)4 GetIamPolicyRequest (com.google.api.services.cloudresourcemanager.v3.model.GetIamPolicyRequest)4 SetIamPolicyRequest (com.google.api.services.cloudresourcemanager.v3.model.SetIamPolicyRequest)4 CloudHealthcare (com.google.api.services.healthcare.v1.CloudHealthcare)4 Binding (com.google.api.services.healthcare.v1.model.Binding)4 Policy (com.google.api.services.healthcare.v1.model.Policy)4 SetIamPolicyRequest (com.google.api.services.healthcare.v1.model.SetIamPolicyRequest)4 CreateServiceAccountRequest (com.google.api.services.iam.v1.model.CreateServiceAccountRequest)4 Policy (com.google.api.services.iam.v1.model.Policy)4 ServiceAccount (com.google.api.services.iam.v1.model.ServiceAccount)4 SetIamPolicyRequest (com.google.api.services.iam.v1.model.SetIamPolicyRequest)4 InternalServerErrorException (bio.terra.common.exception.InternalServerErrorException)3