Search in sources :

Example 6 with Policy

use of com.google.api.services.cloudresourcemanager.v3.model.Policy 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 7 with Policy

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

the class GrantPetUsagePermissionStep method doStep.

@Override
public StepResult doStep(FlightContext context) throws InterruptedException, RetryException {
    String userEmail = SamRethrow.onInterrupted(() -> samService.getUserEmailFromSam(userRequest), "enablePet");
    Policy modifiedPolicy;
    try {
        modifiedPolicy = petSaService.enablePetServiceAccountImpersonation(workspaceUuid, userEmail, userRequest);
    } catch (ConflictException e) {
        // There was a conflict enabling the service account. Request retry.
        return new StepResult(StepStatus.STEP_RESULT_FAILURE_RETRY, e);
    }
    // Store the eTag value of the modified policy in case this step needs to be undone.
    FlightMap workingMap = context.getWorkingMap();
    workingMap.put(PetSaKeys.MODIFIED_PET_SA_POLICY_ETAG, modifiedPolicy.getEtag());
    return StepResult.getStepResultSuccess();
}
Also used : Policy(com.google.api.services.iam.v1.model.Policy) ConflictException(bio.terra.common.exception.ConflictException) FlightMap(bio.terra.stairway.FlightMap) StepResult(bio.terra.stairway.StepResult)

Example 8 with Policy

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

the class NotebookCloudSyncStep method doStep.

@Override
public StepResult doStep(FlightContext flightContext) throws InterruptedException, RetryException {
    FlightMap workingMap = flightContext.getWorkingMap();
    FlightUtils.validateRequiredEntries(workingMap, ControlledResourceKeys.GCP_CLOUD_CONTEXT);
    GcpCloudContext cloudContext = workingMap.get(ControlledResourceKeys.GCP_CLOUD_CONTEXT, GcpCloudContext.class);
    List<Binding> newBindings = createBindings(cloudContext, flightContext.getWorkingMap());
    AIPlatformNotebooksCow notebooks = crlService.getAIPlatformNotebooksCow();
    InstanceName instanceName = resource.toInstanceName(cloudContext.getGcpProjectId());
    try {
        Policy policy = notebooks.instances().getIamPolicy(instanceName).execute();
        // Duplicating bindings is harmless (e.g. on retry). GCP de-duplicates.
        Optional.ofNullable(policy.getBindings()).ifPresent(newBindings::addAll);
        policy.setBindings(newBindings);
        notebooks.instances().setIamPolicy(instanceName, new SetIamPolicyRequest().setPolicy(policy)).execute();
    } catch (IOException e) {
        return new StepResult(StepStatus.STEP_RESULT_FAILURE_RETRY, e);
    }
    return StepResult.getStepResultSuccess();
}
Also used : Binding(com.google.api.services.notebooks.v1.model.Binding) InstanceName(bio.terra.cloudres.google.notebooks.InstanceName) Policy(com.google.api.services.notebooks.v1.model.Policy) AIPlatformNotebooksCow(bio.terra.cloudres.google.notebooks.AIPlatformNotebooksCow) SetIamPolicyRequest(com.google.api.services.notebooks.v1.model.SetIamPolicyRequest) FlightMap(bio.terra.stairway.FlightMap) IOException(java.io.IOException) StepResult(bio.terra.stairway.StepResult) GcpCloudContext(bio.terra.workspace.service.workspace.model.GcpCloudContext)

Example 9 with Policy

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

the class CreateGcpContextFlightV2Test method successCreatesProjectAndContext.

@Test
@DisabledIfEnvironmentVariable(named = "TEST_ENV", matches = BUFFER_SERVICE_DISABLED_ENVS_REG_EX)
void successCreatesProjectAndContext() throws Exception {
    UUID workspaceUuid = createWorkspace(spendUtils.defaultSpendId());
    AuthenticatedUserRequest userRequest = userAccessUtils.defaultUserAuthRequest();
    assertTrue(testUtils.getAuthorizedGcpCloudContext(workspaceUuid, userRequest).isEmpty());
    // Retry steps once to validate idempotency.
    Map<String, StepStatus> retrySteps = getStepNameToStepStatusMap();
    FlightDebugInfo debugInfo = FlightDebugInfo.newBuilder().doStepFailures(retrySteps).build();
    FlightState flightState = StairwayTestUtils.blockUntilFlightCompletes(jobService.getStairway(), CreateGcpContextFlightV2.class, createInputParameters(workspaceUuid, userRequest), STAIRWAY_FLIGHT_TIMEOUT, debugInfo);
    assertEquals(FlightStatus.SUCCESS, flightState.getFlightStatus());
    String projectId = flightState.getResultMap().get().get(WorkspaceFlightMapKeys.GCP_PROJECT_ID, String.class);
    assertTrue(testUtils.getAuthorizedGcpCloudContext(workspaceUuid, userRequest).isPresent());
    String contextProjectId = workspaceService.getAuthorizedRequiredGcpProject(workspaceUuid, userRequest);
    assertEquals(projectId, contextProjectId);
    // Verify that the policies were properly stored
    Optional<GcpCloudContext> optionalCloudContext = testUtils.getAuthorizedGcpCloudContext(workspaceUuid, userRequest);
    assertTrue(optionalCloudContext.isPresent(), "has cloud context");
    GcpCloudContext cloudContext = optionalCloudContext.get();
    assertTrue(cloudContext.getSamPolicyOwner().isPresent(), "has owner policy");
    assertTrue(cloudContext.getSamPolicyWriter().isPresent(), "has writer policy");
    assertTrue(cloudContext.getSamPolicyReader().isPresent(), "has reader policy");
    assertTrue(cloudContext.getSamPolicyApplication().isPresent(), "has application policy");
    Project project = crl.getCloudResourceManagerCow().projects().get(projectId).execute();
    assertEquals(projectId, project.getProjectId());
    assertEquals("billingAccounts/" + spendUtils.defaultBillingAccountId(), crl.getCloudBillingClientCow().getProjectBillingInfo("projects/" + projectId).getBillingAccountName());
    assertRolesExist(project);
    assertPolicyGroupsSynced(workspaceUuid, project);
}
Also used : FlightState(bio.terra.stairway.FlightState) Project(com.google.api.services.cloudresourcemanager.v3.model.Project) FlightDebugInfo(bio.terra.stairway.FlightDebugInfo) AuthenticatedUserRequest(bio.terra.workspace.service.iam.AuthenticatedUserRequest) StepStatus(bio.terra.stairway.StepStatus) UUID(java.util.UUID) GcpCloudContext(bio.terra.workspace.service.workspace.model.GcpCloudContext) Test(org.junit.jupiter.api.Test) BaseConnectedTest(bio.terra.workspace.common.BaseConnectedTest) DisabledIfEnvironmentVariable(org.junit.jupiter.api.condition.DisabledIfEnvironmentVariable)

Example 10 with Policy

use of com.google.api.services.cloudresourcemanager.v3.model.Policy 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 workspaceUuid, Project project) throws Exception {
    Map<WsmIamRole, String> roleToSamGroup = Arrays.stream(WsmIamRole.values()).collect(Collectors.toMap(Function.identity(), role -> "group:" + SamRethrow.onInterrupted(() -> mockSamService.syncWorkspacePolicy(workspaceUuid, 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)

Aggregations

IOException (java.io.IOException)16 Policy (com.google.api.services.cloudresourcemanager.v3.model.Policy)15 Binding (com.google.api.services.cloudresourcemanager.v3.model.Binding)14 GetIamPolicyRequest (com.google.api.services.cloudresourcemanager.v3.model.GetIamPolicyRequest)8 CloudHealthcare (com.google.api.services.healthcare.v1.CloudHealthcare)8 Policy (com.google.api.services.healthcare.v1.model.Policy)8 Test (org.junit.jupiter.api.Test)8 Policy (com.google.api.services.iam.v1.model.Policy)7 CloudKMS (com.google.api.services.cloudkms.v1.CloudKMS)6 Policy (com.google.api.services.cloudkms.v1.model.Policy)6 SetIamPolicyRequest (com.google.api.services.cloudresourcemanager.v3.model.SetIamPolicyRequest)6 FlightMap (bio.terra.stairway.FlightMap)5 ArrayList (java.util.ArrayList)5 StepResult (bio.terra.stairway.StepResult)4 StepStatus (bio.terra.stairway.StepStatus)4 Binding (com.google.api.services.healthcare.v1.model.Binding)4 SetIamPolicyRequest (com.google.api.services.healthcare.v1.model.SetIamPolicyRequest)4 Binding (com.google.api.services.iam.v1.model.Binding)4 SetIamPolicyRequest (com.google.api.services.iam.v1.model.SetIamPolicyRequest)4 ServiceAccountName (bio.terra.cloudres.google.iam.ServiceAccountName)3