Search in sources :

Example 6 with Policy

use of com.google.api.services.notebooks.v1.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 7 with Policy

use of com.google.api.services.notebooks.v1.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 8 with Policy

use of com.google.api.services.notebooks.v1.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)

Example 9 with Policy

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

the class PetSaService method enablePetServiceAccountImpersonationWithEtag.

/**
 * Grant a user's proxy group permission to impersonate their pet service account in a given
 * workspace. Unlike other operations, this does not run as a flight because it only requires one
 * write operation. If the user's pet SA does not exist, this will create it. This operation is
 * idempotent.
 *
 * <p>The provided workspace must have a GCP context.
 *
 * <p>This method does not authenticate that the user should have access to impersonate their pet
 * SA, callers should validate this first.
 *
 * <p>userToEnableEmail is separate from token because of RevokePetUsagePermissionStep.undoStep().
 * If User A removes B from workspace, userToEnableEmail is B and token is from A's userRequest.
 *
 * @param workspaceUuid ID of the workspace to enable pet SA in
 * @param userToEnableEmail The user whose proxy group will be granted permission.
 * @param userReq Auth info for calling SAM. Do not use userReq.getEmail() here; it will return
 *     the caller's email, but there's no guarantee whether that will be an end-user email or a
 *     pet SA email.
 * @param eTag GCP eTag which must match the pet SA's current policy. If null, this is ignored.
 * @return The new IAM policy on the user's pet service account, or empty if the eTag value
 *     provided is non-null and does not match current IAM policy on the pet SA.
 */
public Optional<Policy> enablePetServiceAccountImpersonationWithEtag(UUID workspaceUuid, String userToEnableEmail, AuthenticatedUserRequest userReq, @Nullable String eTag) {
    String projectId = gcpCloudContextService.getRequiredGcpProject(workspaceUuid);
    Optional<ServiceAccountName> maybePetSaName = getUserPetSa(projectId, userToEnableEmail, userReq);
    // If the pet SA does not exist and no eTag is specified, create the pet SA and continue.
    if (maybePetSaName.isEmpty()) {
        if (eTag == null) {
            String saEmail = SamRethrow.onInterrupted(() -> samService.getOrCreatePetSaEmail(gcpCloudContextService.getRequiredGcpProject(workspaceUuid), userReq.getRequiredToken()), "enablePet");
            maybePetSaName = Optional.of(ServiceAccountName.builder().projectId(projectId).email(saEmail).build());
        } else {
            // so return empty optional.
            return Optional.empty();
        }
    }
    // Pet name is populated above, so it's always safe to unwrap here.
    ServiceAccountName petSaName = maybePetSaName.get();
    String proxyGroupEmail = SamRethrow.onInterrupted(() -> samService.getProxyGroupEmail(userToEnableEmail, userReq.getRequiredToken()), "enablePet");
    String targetMember = "group:" + proxyGroupEmail;
    try {
        Policy saPolicy = crlService.getIamCow().projects().serviceAccounts().getIamPolicy(petSaName).execute();
        // clobbering other changes.
        if (eTag != null && !saPolicy.getEtag().equals(eTag)) {
            logger.warn("GCP IAM policy eTag did not match expected value when granting pet SA access for user {} in workspace {}. This is normal for Step retries.", userToEnableEmail, workspaceUuid);
            return Optional.empty();
        }
        // See if the user is already on the policy. If so, return the policy. This avoids
        // calls to set the IAM policy that have a rate limit.
        Optional<Binding> serviceAccountUserBinding = findServiceAccountUserBinding(saPolicy);
        if (serviceAccountUserBinding.isPresent() && serviceAccountUserBinding.get().getMembers().contains(targetMember)) {
            logger.info("user {} is already enabled on petSA {}", userToEnableEmail, petSaName.email());
            return Optional.of(saPolicy);
        } else if (serviceAccountUserBinding.isPresent()) {
            // If a binding exists for the ServiceAccountUser role but the proxy group is not a member,
            // add it.
            serviceAccountUserBinding.get().getMembers().add(targetMember);
        } else {
            // Otherwise, create the ServiceAccountUser role binding.
            Binding newBinding = new Binding().setRole(SERVICE_ACCOUNT_USER_ROLE).setMembers(ImmutableList.of(targetMember));
            // If no bindings exist, getBindings() returns null instead of an empty list.
            if (saPolicy.getBindings() != null) {
                saPolicy.getBindings().add(newBinding);
            } else {
                List<Binding> bindingList = new ArrayList<>();
                bindingList.add(newBinding);
                saPolicy.setBindings(bindingList);
            }
        }
        SetIamPolicyRequest request = new SetIamPolicyRequest().setPolicy(saPolicy);
        return Optional.of(crlService.getIamCow().projects().serviceAccounts().setIamPolicy(petSaName, request).execute());
    } catch (IOException e) {
        return handleProxyUpdateError(e, "enabling");
    }
}
Also used : Policy(com.google.api.services.iam.v1.model.Policy) Binding(com.google.api.services.iam.v1.model.Binding) SetIamPolicyRequest(com.google.api.services.iam.v1.model.SetIamPolicyRequest) ServiceAccountName(bio.terra.cloudres.google.iam.ServiceAccountName) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) IOException(java.io.IOException)

Example 10 with Policy

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

the class PetSaService method disablePetServiceAccountImpersonationWithEtag.

/**
 * Revoke the permission to impersonate a pet service account granted by {@code
 * enablePetServiceAccountImpersonation}. Unlike other operations, this does not run in a flight
 * because it only requires one write operation. This operation is idempotent.
 *
 * <p>This method requires a user's pet service account email as input. As a transitive
 * dependency, this also means the provided workspace must have a GCP context.
 *
 * <p>This method does not authenticate that the user should have access to impersonate their pet
 * SA, callers should validate this first.
 *
 * @param workspaceUuid ID of the workspace to disable pet SA in
 * @param userToDisableEmail The user losing access to pet SA
 * @param userRequest This request's token will be used to authenticate SAM requests
 * @param eTag GCP eTag which must match the pet SA's current policy. If null, this is ignored.
 */
public Optional<Policy> disablePetServiceAccountImpersonationWithEtag(UUID workspaceUuid, String userToDisableEmail, AuthenticatedUserRequest userRequest, @Nullable String eTag) {
    String proxyGroupEmail = SamRethrow.onInterrupted(() -> samService.getProxyGroupEmail(userToDisableEmail, userRequest.getRequiredToken()), "disablePet");
    String targetMember = "group:" + proxyGroupEmail;
    String projectId = gcpCloudContextService.getRequiredGcpProject(workspaceUuid);
    try {
        Optional<ServiceAccountName> userToDisablePetSA = getUserPetSa(projectId, userToDisableEmail, userRequest);
        if (userToDisablePetSA.isEmpty()) {
            return Optional.empty();
        }
        Policy saPolicy = crlService.getIamCow().projects().serviceAccounts().getIamPolicy(userToDisablePetSA.get()).execute();
        // clobbering other changes.
        if (eTag != null && !saPolicy.getEtag().equals(eTag)) {
            logger.warn("GCP IAM policy eTag did not match expected value when revoking pet SA access for user {} in workspace {}. This is normal for Step retries.", userToDisableEmail, workspaceUuid);
            return Optional.empty();
        }
        // If the member is already not on the policy, we are done
        // This handles the case where there are no bindings at all, so we don't
        // need to worry about null binding later in the logic.
        Optional<Binding> bindingToModify = findServiceAccountUserBinding(saPolicy);
        if (bindingToModify.isEmpty() || !bindingToModify.get().getMembers().contains(targetMember)) {
            return Optional.empty();
        }
        bindingToModify.get().getMembers().remove(targetMember);
        SetIamPolicyRequest request = new SetIamPolicyRequest().setPolicy(saPolicy);
        return Optional.of(crlService.getIamCow().projects().serviceAccounts().setIamPolicy(userToDisablePetSA.get(), request).execute());
    } catch (IOException e) {
        return handleProxyUpdateError(e, "disabling");
    }
}
Also used : Policy(com.google.api.services.iam.v1.model.Policy) Binding(com.google.api.services.iam.v1.model.Binding) SetIamPolicyRequest(com.google.api.services.iam.v1.model.SetIamPolicyRequest) ServiceAccountName(bio.terra.cloudres.google.iam.ServiceAccountName) IOException(java.io.IOException)

Aggregations

Policy (com.google.api.services.cloudresourcemanager.v3.model.Policy)15 IOException (java.io.IOException)14 Binding (com.google.api.services.cloudresourcemanager.v3.model.Binding)11 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 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 Test (org.junit.jupiter.api.Test)6 FlightMap (bio.terra.stairway.FlightMap)5 SetIamPolicyRequest (com.google.api.services.cloudresourcemanager.v3.model.SetIamPolicyRequest)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 ArrayList (java.util.ArrayList)4 ServiceAccountName (bio.terra.cloudres.google.iam.ServiceAccountName)3 StepResult (bio.terra.stairway.StepResult)3 Binding (com.google.api.services.cloudkms.v1.model.Binding)3