Search in sources :

Example 1 with GetIamPolicyRequest

use of com.google.api.services.cloudresourcemanager.v3.model.GetIamPolicyRequest in project java-docs-samples by GoogleCloudPlatform.

the class DeviceRegistryExample method getIamPermissions.

// [END iot_set_device_config]
// [START iot_get_iam_policy]
/**
 * Retrieves IAM permissions for the given registry.
 */
protected static void getIamPermissions(String projectId, String cloudRegion, String registryName) throws GeneralSecurityException, IOException {
    GoogleCredentials credential = GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
    final CloudIot service = new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init).setApplicationName(APP_NAME).build();
    final String registryPath = String.format("projects/%s/locations/%s/registries/%s", projectId, cloudRegion, registryName);
    com.google.api.services.cloudiot.v1.model.Policy policy = service.projects().locations().registries().getIamPolicy(registryPath, new GetIamPolicyRequest()).execute();
    System.out.println("Policy ETAG: " + policy.getEtag());
    if (policy.getBindings() != null) {
        for (com.google.api.services.cloudiot.v1.model.Binding binding : policy.getBindings()) {
            System.out.println(String.format("Role: %s", binding.getRole()));
            System.out.println("Binding members: ");
            for (String member : binding.getMembers()) {
                System.out.println(String.format("\t%s", member));
            }
        }
    } else {
        System.out.println(String.format("No policy bindings for %s", registryName));
    }
}
Also used : CloudIot(com.google.api.services.cloudiot.v1.CloudIot) HttpCredentialsAdapter(com.google.auth.http.HttpCredentialsAdapter) JsonFactory(com.google.api.client.json.JsonFactory) GetIamPolicyRequest(com.google.api.services.cloudiot.v1.model.GetIamPolicyRequest) GoogleCredentials(com.google.auth.oauth2.GoogleCredentials) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer)

Example 2 with GetIamPolicyRequest

use of com.google.api.services.cloudresourcemanager.v3.model.GetIamPolicyRequest in project java-docs-samples by GoogleCloudPlatform.

the class DeviceRegistryExample method setIamPermissions.

// [END iot_get_iam_policy]
// [START iot_set_iam_policy]
/**
 * Sets IAM permissions for the given registry.
 */
protected static void setIamPermissions(String projectId, String cloudRegion, String registryName, String member, String role) throws GeneralSecurityException, IOException {
    GoogleCredentials credential = GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
    final CloudIot service = new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init).setApplicationName(APP_NAME).build();
    final String registryPath = String.format("projects/%s/locations/%s/registries/%s", projectId, cloudRegion, registryName);
    com.google.api.services.cloudiot.v1.model.Policy policy = service.projects().locations().registries().getIamPolicy(registryPath, new GetIamPolicyRequest()).execute();
    List<com.google.api.services.cloudiot.v1.model.Binding> bindings = policy.getBindings();
    boolean addNewRole = true;
    if (bindings != null) {
        for (com.google.api.services.cloudiot.v1.model.Binding binding : bindings) {
            if (binding.getRole().equals(role)) {
                List<String> members = binding.getMembers();
                members.add(member);
                binding.setMembers(members);
                addNewRole = false;
            }
        }
    } else {
        bindings = new ArrayList<>();
    }
    if (addNewRole) {
        com.google.api.services.cloudiot.v1.model.Binding bind = new com.google.api.services.cloudiot.v1.model.Binding();
        bind.setRole(role);
        List<String> members = new ArrayList<>();
        members.add(member);
        bind.setMembers(members);
        bindings.add(bind);
    }
    policy.setBindings(bindings);
    SetIamPolicyRequest req = new SetIamPolicyRequest().setPolicy(policy);
    policy = service.projects().locations().registries().setIamPolicy(registryPath, req).execute();
    System.out.println("Policy ETAG: " + policy.getEtag());
    for (com.google.api.services.cloudiot.v1.model.Binding binding : policy.getBindings()) {
        System.out.println(String.format("Role: %s", binding.getRole()));
        System.out.println("Binding members: ");
        for (String mem : binding.getMembers()) {
            System.out.println(String.format("\t%s", mem));
        }
    }
}
Also used : Binding(com.google.iam.v1.Binding) CloudIot(com.google.api.services.cloudiot.v1.CloudIot) HttpCredentialsAdapter(com.google.auth.http.HttpCredentialsAdapter) SetIamPolicyRequest(com.google.api.services.cloudiot.v1.model.SetIamPolicyRequest) JsonFactory(com.google.api.client.json.JsonFactory) ArrayList(java.util.ArrayList) GetIamPolicyRequest(com.google.api.services.cloudiot.v1.model.GetIamPolicyRequest) GoogleCredentials(com.google.auth.oauth2.GoogleCredentials) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer)

Example 3 with GetIamPolicyRequest

use of com.google.api.services.cloudresourcemanager.v3.model.GetIamPolicyRequest in project java-docs-samples by GoogleCloudPlatform.

the class AddMember method addMember.

// Adds a member to a preexisting role.
public static void addMember(Policy policy) {
    // policy = service.Projects.GetIAmPolicy(new GetIamPolicyRequest(), your-project-id).Execute();
    String role = "roles/existing-role";
    String member = "user:member-to-add@example.com";
    List<Binding> bindings = policy.getBindings();
    for (Binding b : bindings) {
        if (b.getRole().equals(role)) {
            b.getMembers().add(member);
            System.out.println("Member " + member + " added to role " + role);
            return;
        }
    }
    System.out.println("Role not found in policy; member not added");
}
Also used : Binding(com.google.api.services.cloudresourcemanager.v3.model.Binding)

Example 4 with GetIamPolicyRequest

use of com.google.api.services.cloudresourcemanager.v3.model.GetIamPolicyRequest in project terra-workspace-manager by DataBiosphere.

the class CreateGcpContextFlightV2Test method assertPolicyGroupsSynced.

/**
 * Asserts that Sam groups are granted their appropriate IAM roles on a GCP project.
 */
private void assertPolicyGroupsSynced(UUID workspaceId, Project project) throws Exception {
    Map<WsmIamRole, String> roleToSamGroup = Arrays.stream(WsmIamRole.values()).collect(Collectors.toMap(Function.identity(), role -> "group:" + SamRethrow.onInterrupted(() -> mockSamService.syncWorkspacePolicy(workspaceId, role, userAccessUtils.defaultUserAuthRequest()), "syncWorkspacePolicy")));
    Policy currentPolicy = crl.getCloudResourceManagerCow().projects().getIamPolicy(project.getProjectId(), new GetIamPolicyRequest()).execute();
    for (WsmIamRole role : WsmIamRole.values()) {
        // Don't check MANAGER role, which isn't synced to GCP.
        if (role.equals(WsmIamRole.MANAGER)) {
            continue;
        }
        assertRoleBindingInPolicy(role, roleToSamGroup.get(role), currentPolicy, project.getProjectId());
    }
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) WsmIamRole(bio.terra.workspace.service.iam.model.WsmIamRole) SamService(bio.terra.workspace.service.iam.SamService) Autowired(org.springframework.beans.factory.annotation.Autowired) AuthenticatedUserRequest(bio.terra.workspace.service.iam.AuthenticatedUserRequest) GcpCloudContext(bio.terra.workspace.service.workspace.model.GcpCloudContext) CloudSyncRoleMapping(bio.terra.workspace.service.workspace.CloudSyncRoleMapping) Role(com.google.api.services.iam.v1.model.Role) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) GetIamPolicyRequest(com.google.api.services.cloudresourcemanager.v3.model.GetIamPolicyRequest) FlightState(bio.terra.stairway.FlightState) Duration(java.time.Duration) Map(java.util.Map) SpendUnauthorizedException(bio.terra.workspace.service.spendprofile.exceptions.SpendUnauthorizedException) CustomGcpIamRoleMapping(bio.terra.workspace.service.resource.controlled.cloud.gcp.CustomGcpIamRoleMapping) JobService(bio.terra.workspace.service.job.JobService) MockBean(org.springframework.boot.test.mock.mockito.MockBean) UserAccessUtils(bio.terra.workspace.connected.UserAccessUtils) NoBillingAccountException(bio.terra.workspace.service.workspace.exceptions.NoBillingAccountException) StairwayTestUtils(bio.terra.workspace.common.StairwayTestUtils) Binding(com.google.api.services.cloudresourcemanager.v3.model.Binding) UUID(java.util.UUID) SpendProfileId(bio.terra.workspace.service.spendprofile.SpendProfileId) Collectors(java.util.stream.Collectors) WorkspaceConnectedTestUtils(bio.terra.workspace.connected.WorkspaceConnectedTestUtils) CustomGcpIamRole(bio.terra.workspace.service.resource.controlled.cloud.gcp.CustomGcpIamRole) Test(org.junit.jupiter.api.Test) List(java.util.List) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Optional(java.util.Optional) StepStatus(bio.terra.stairway.StepStatus) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) JobMapKeys(bio.terra.workspace.service.job.JobMapKeys) WorkspaceService(bio.terra.workspace.service.workspace.WorkspaceService) Policy(com.google.api.services.cloudresourcemanager.v3.model.Policy) Project(com.google.api.services.cloudresourcemanager.v3.model.Project) HashMap(java.util.HashMap) Function(java.util.function.Function) SamResource(bio.terra.workspace.service.iam.model.SamConstants.SamResource) SamRethrow(bio.terra.workspace.service.iam.SamRethrow) DisabledIfEnvironmentVariable(org.junit.jupiter.api.condition.DisabledIfEnvironmentVariable) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) FlightDebugInfo(bio.terra.stairway.FlightDebugInfo) CrlService(bio.terra.workspace.service.crl.CrlService) Nullable(javax.annotation.Nullable) SamSpendProfileAction(bio.terra.workspace.service.iam.model.SamConstants.SamSpendProfileAction) MissingSpendProfileException(bio.terra.workspace.service.workspace.exceptions.MissingSpendProfileException) FlightMap(bio.terra.stairway.FlightMap) Workspace(bio.terra.workspace.service.workspace.model.Workspace) IOException(java.io.IOException) BaseConnectedTest(bio.terra.workspace.common.BaseConnectedTest) SpendConnectedTestUtils(bio.terra.workspace.service.spendprofile.SpendConnectedTestUtils) WorkspaceStage(bio.terra.workspace.service.workspace.model.WorkspaceStage) Mockito(org.mockito.Mockito) FlightStatus(bio.terra.stairway.FlightStatus) Collections(java.util.Collections) Policy(com.google.api.services.cloudresourcemanager.v3.model.Policy) GetIamPolicyRequest(com.google.api.services.cloudresourcemanager.v3.model.GetIamPolicyRequest) WsmIamRole(bio.terra.workspace.service.iam.model.WsmIamRole)

Example 5 with GetIamPolicyRequest

use of com.google.api.services.cloudresourcemanager.v3.model.GetIamPolicyRequest in project terra-resource-buffer by DataBiosphere.

the class CreateGkeDefaultSAStep method doStep.

@Override
public StepResult doStep(FlightContext flightContext) throws RetryException {
    if (!createGkeDefaultSa(gcpProjectConfig)) {
        return StepResult.getStepResultSuccess();
    }
    String projectId = flightContext.getWorkingMap().get(GOOGLE_PROJECT_ID, String.class);
    CreateServiceAccountRequest createRequest = new CreateServiceAccountRequest().setAccountId(GKE_SA_NAME).setServiceAccount(new ServiceAccount().setDescription("Default service account can be used on GKE node. "));
    try {
        iamCow.projects().serviceAccounts().create("projects/" + projectId, createRequest).execute();
    } catch (GoogleJsonResponseException e) {
        // Otherwise throw a retry exception.
        if (e.getStatusCode() != HttpStatus.CONFLICT.value()) {
            throw new RetryException(e);
        }
        logger.warn("Service account {} already created for notebook instance.", GKE_SA_NAME);
    } catch (IOException e) {
        throw new RetryException(e);
    }
    // Grants permission that a GKE node runner needs
    String serviceAccountEmail = ServiceAccountName.emailFromAccountId(GKE_SA_NAME, projectId);
    try {
        Policy policy = rmCow.projects().getIamPolicy(projectId, new GetIamPolicyRequest()).execute();
        GKE_SA_ROLES.forEach(r -> policy.getBindings().add(new Binding().setRole(r).setMembers(Collections.singletonList("serviceAccount:" + serviceAccountEmail))));
        // Duplicating bindings is harmless (e.g. on retry). GCP de-duplicates.
        rmCow.projects().setIamPolicy(projectId, new SetIamPolicyRequest().setPolicy(policy)).execute();
    } catch (IOException e) {
        logger.info("Error when setting IAM policy for GKE default node SA", e);
        return new StepResult(StepStatus.STEP_RESULT_FAILURE_RETRY, e);
    }
    return StepResult.getStepResultSuccess();
}
Also used : Policy(com.google.api.services.cloudresourcemanager.v3.model.Policy) Binding(com.google.api.services.cloudresourcemanager.v3.model.Binding) ServiceAccount(com.google.api.services.iam.v1.model.ServiceAccount) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) SetIamPolicyRequest(com.google.api.services.cloudresourcemanager.v3.model.SetIamPolicyRequest) IOException(java.io.IOException) RetryException(bio.terra.stairway.exception.RetryException) GetIamPolicyRequest(com.google.api.services.cloudresourcemanager.v3.model.GetIamPolicyRequest) StepResult(bio.terra.stairway.StepResult) CreateServiceAccountRequest(com.google.api.services.iam.v1.model.CreateServiceAccountRequest)

Aggregations

IOException (java.io.IOException)10 Binding (com.google.api.services.cloudresourcemanager.v3.model.Binding)9 Policy (com.google.api.services.cloudresourcemanager.v3.model.Policy)9 GetIamPolicyRequest (com.google.api.services.cloudresourcemanager.v3.model.GetIamPolicyRequest)8 SetIamPolicyRequest (com.google.api.services.cloudresourcemanager.v3.model.SetIamPolicyRequest)4 FlightMap (bio.terra.stairway.FlightMap)3 StepStatus (bio.terra.stairway.StepStatus)3 WsmIamRole (bio.terra.workspace.service.iam.model.WsmIamRole)3 CloudResourceManagerCow (bio.terra.cloudres.google.cloudresourcemanager.CloudResourceManagerCow)2 FlightDebugInfo (bio.terra.stairway.FlightDebugInfo)2 FlightState (bio.terra.stairway.FlightState)2 FlightStatus (bio.terra.stairway.FlightStatus)2 StepResult (bio.terra.stairway.StepResult)2 RetryException (bio.terra.stairway.exception.RetryException)2 BaseConnectedTest (bio.terra.workspace.common.BaseConnectedTest)2 StairwayTestUtils (bio.terra.workspace.common.StairwayTestUtils)2 UserAccessUtils (bio.terra.workspace.connected.UserAccessUtils)2 WorkspaceConnectedTestUtils (bio.terra.workspace.connected.WorkspaceConnectedTestUtils)2 CrlService (bio.terra.workspace.service.crl.CrlService)2 AuthenticatedUserRequest (bio.terra.workspace.service.iam.AuthenticatedUserRequest)2