Search in sources :

Example 11 with Policy

use of com.google.api.services.healthcare.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. 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 workspaceId ID of the workspace to enable pet SA in
 * @param userToEnableEmail The user whose proxy group will be granted permission.
 * @param token Token for calling SAM.
 * @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 workspaceId, String userToEnableEmail, String token, @Nullable String eTag) {
    String petSaEmail = SamRethrow.onInterrupted(() -> samService.getOrCreatePetSaEmail(gcpCloudContextService.getRequiredGcpProject(workspaceId), token), "enablePet");
    String proxyGroupEmail = SamRethrow.onInterrupted(() -> samService.getProxyGroupEmail(userToEnableEmail, token), "enablePet");
    String projectId = gcpCloudContextService.getRequiredGcpProject(workspaceId);
    ServiceAccountName petSaName = ServiceAccountName.builder().email(petSaEmail).projectId(projectId).build();
    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, workspaceId);
            return Optional.empty();
        }
        Binding saUserBinding = new Binding().setRole(SERVICE_ACCOUNT_USER_ROLE).setMembers(ImmutableList.of("group:" + proxyGroupEmail));
        // If no bindings exist, getBindings() returns null instead of an empty list.
        List<Binding> bindingList = Optional.ofNullable(saPolicy.getBindings()).orElse(new ArrayList<>());
        // GCP automatically de-duplicates bindings, so this will have no effect if the user already
        // has permission to use their pet service account.
        bindingList.add(saUserBinding);
        saPolicy.setBindings(bindingList);
        SetIamPolicyRequest request = new SetIamPolicyRequest().setPolicy(saPolicy);
        return Optional.of(crlService.getIamCow().projects().serviceAccounts().setIamPolicy(petSaName, request).execute());
    } catch (IOException e) {
        throw new InternalServerErrorException("Error enabling user's proxy group to impersonate pet SA", e);
    }
}
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) InternalServerErrorException(bio.terra.common.exception.InternalServerErrorException) ServiceAccountName(bio.terra.cloudres.google.iam.ServiceAccountName) IOException(java.io.IOException)

Example 12 with Policy

use of com.google.api.services.healthcare.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 workspaceId 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 workspaceId, String userToDisableEmail, AuthenticatedUserRequest userRequest, @Nullable String eTag) {
    String proxyGroupEmail = SamRethrow.onInterrupted(() -> samService.getProxyGroupEmail(userToDisableEmail, userRequest.getRequiredToken()), "disablePet");
    String projectId = gcpCloudContextService.getRequiredGcpProject(workspaceId);
    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, workspaceId);
            return Optional.empty();
        }
        Binding bindingToRemove = new Binding().setRole(SERVICE_ACCOUNT_USER_ROLE).setMembers(ImmutableList.of("group:" + proxyGroupEmail));
        // If no bindings exist, getBindings() returns null instead of an empty list. If there are
        // no policies, there is nothing to revoke, so this method is finished.
        List<Binding> oldBindingList = saPolicy.getBindings();
        if (oldBindingList == null) {
            return Optional.empty();
        }
        List<Binding> newBindingsList = removeBinding(oldBindingList, bindingToRemove);
        saPolicy.setBindings(newBindingsList);
        SetIamPolicyRequest request = new SetIamPolicyRequest().setPolicy(saPolicy);
        return Optional.of(crlService.getIamCow().projects().serviceAccounts().setIamPolicy(userToDisablePetSA.get(), request).execute());
    } catch (IOException e) {
        throw new InternalServerErrorException("Error disabling user's proxy group to impersonate pet SA", e);
    }
}
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) InternalServerErrorException(bio.terra.common.exception.InternalServerErrorException) ServiceAccountName(bio.terra.cloudres.google.iam.ServiceAccountName) IOException(java.io.IOException)

Example 13 with Policy

use of com.google.api.services.healthcare.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 = petSaService.enablePetServiceAccountImpersonation(workspaceId, userEmail, userRequest.getRequiredToken());
    // 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) FlightMap(bio.terra.stairway.FlightMap)

Example 14 with Policy

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

use of com.google.api.services.healthcare.v1.model.Policy in project terra-cloud-resource-lib by DataBiosphere.

the class IamCowTest method getAndSetAndTestIamOnServiceAccount.

@Test
public void getAndSetAndTestIamOnServiceAccount() throws Exception {
    IamCow.Projects.ServiceAccounts serviceAccounts = defaultIam().projects().serviceAccounts();
    String projectName = "projects/" + reusableProject.getProjectId();
    ServiceAccount serviceAccount = serviceAccounts.create(projectName, new CreateServiceAccountRequest().setAccountId(randomServiceAccountId())).execute();
    ServiceAccountName serviceAccountName = ServiceAccountName.builder().projectId(serviceAccount.getProjectId()).email(serviceAccount.getEmail()).build();
    Policy policy = serviceAccounts.getIamPolicy(serviceAccountName).execute();
    assertNotNull(policy);
    List<Binding> bindingList = new ArrayList<>();
    String member = String.format("serviceAccount:%s", IntegrationCredentials.getUserGoogleCredentialsOrDie().getClientEmail());
    Binding newBinding = new Binding().setRole("roles/iam.serviceAccountUser").setMembers(Collections.singletonList(member));
    bindingList.add(newBinding);
    policy.setBindings(bindingList);
    Policy updatedPolicy = serviceAccounts.setIamPolicy(serviceAccountName, new SetIamPolicyRequest().setPolicy(policy)).execute();
    assertThat(updatedPolicy.getBindings(), hasItem(newBinding));
    assertEquals(updatedPolicy, serviceAccounts.getIamPolicy(serviceAccountName).execute());
    // Test the permissions of the user for which the IAM policy was set.
    IamCow.Projects.ServiceAccounts userIamServiceAccounts = IamCow.create(IntegrationUtils.DEFAULT_CLIENT_CONFIG, IntegrationCredentials.getUserGoogleCredentialsOrDie()).projects().serviceAccounts();
    // The "actAs" permission associated with "roles/iam.serviceAccountUser".
    String actAsPermission = "iam.serviceAccounts.actAs";
    TestIamPermissionsResponse iamResponse = userIamServiceAccounts.testIamPermissions(serviceAccountName, new TestIamPermissionsRequest().setPermissions(ImmutableList.of(actAsPermission))).execute();
    assertThat(iamResponse.getPermissions(), Matchers.contains(actAsPermission));
}
Also used : Policy(com.google.api.services.iam.v1.model.Policy) Binding(com.google.api.services.iam.v1.model.Binding) ServiceAccount(com.google.api.services.iam.v1.model.ServiceAccount) SetIamPolicyRequest(com.google.api.services.iam.v1.model.SetIamPolicyRequest) TestIamPermissionsRequest(com.google.api.services.iam.v1.model.TestIamPermissionsRequest) ArrayList(java.util.ArrayList) CreateServiceAccountRequest(com.google.api.services.iam.v1.model.CreateServiceAccountRequest) TestIamPermissionsResponse(com.google.api.services.iam.v1.model.TestIamPermissionsResponse) Test(org.junit.jupiter.api.Test)

Aggregations

Policy (com.google.api.services.cloudresourcemanager.v3.model.Policy)15 IOException (java.io.IOException)13 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 CloudKMS (com.google.api.services.cloudkms.v1.CloudKMS)6 Policy (com.google.api.services.cloudkms.v1.model.Policy)6 Policy (com.google.api.services.iam.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 InternalServerErrorException (bio.terra.common.exception.InternalServerErrorException)3 Binding (com.google.api.services.cloudkms.v1.model.Binding)3 SetIamPolicyRequest (com.google.api.services.cloudkms.v1.model.SetIamPolicyRequest)3 CloudResourceManager (com.google.api.services.cloudresourcemanager.v3.CloudResourceManager)3 Binding (com.google.api.services.iam.v1.model.Binding)3 SetIamPolicyRequest (com.google.api.services.iam.v1.model.SetIamPolicyRequest)3