Search in sources :

Example 6 with TestIamPermissionsRequest

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

the class NotebookUtils method userHasProxyAccess.

/**
 * Check whether the user has access to the Notebook through the proxy with a service account.
 *
 * <p>We can't directly test that we can go through the proxy to the Jupyter notebook without a
 * real Google user auth flow, so we check the necessary ingredients instead.
 */
public static boolean userHasProxyAccess(CreatedControlledGcpAiNotebookInstanceResult createdNotebook, TestUserSpecification user, String projectId) throws GeneralSecurityException, IOException {
    String instanceName = String.format("projects/%s/locations/%s/instances/%s", createdNotebook.getAiNotebookInstance().getAttributes().getProjectId(), createdNotebook.getAiNotebookInstance().getAttributes().getLocation(), createdNotebook.getAiNotebookInstance().getAttributes().getInstanceId());
    AIPlatformNotebooks userNotebooks = ClientTestUtils.getAIPlatformNotebooksClient(user);
    Instance instance;
    try {
        instance = userNotebooks.projects().locations().instances().get(instanceName).execute();
    } catch (GoogleJsonResponseException googleException) {
        // If we get a 403 or 404 when fetching the instance, the user does not have access.
        if (googleException.getStatusCode() == HttpStatus.SC_FORBIDDEN || googleException.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            return false;
        } else {
            // If a different status code is thrown instead, rethrow here as that's an unexpected error.
            throw googleException;
        }
    }
    // Test that the user has access to the notebook with a service account through proxy mode.
    // git secrets gets a false positive if 'service_account' is double quoted.
    assertThat("Notebook has correct proxy mode access", instance.getMetadata(), Matchers.hasEntry("proxy-mode", "service_" + "account"));
    // The user needs to have the actAs permission on the service account.
    String actAsPermission = "iam.serviceAccounts.actAs";
    String serviceAccountName = String.format("projects/%s/serviceAccounts/%s", projectId, instance.getServiceAccount());
    List<String> maybePermissionsList = ClientTestUtils.getGcpIamClient(user).projects().serviceAccounts().testIamPermissions(serviceAccountName, new TestIamPermissionsRequest().setPermissions(List.of(actAsPermission))).execute().getPermissions();
    // GCP returns null rather than an empty list when a user does not have any permissions
    return Optional.ofNullable(maybePermissionsList).map(list -> list.contains(actAsPermission)).orElse(false);
}
Also used : AccessScope(bio.terra.workspace.model.AccessScope) CloningInstructionsEnum(bio.terra.workspace.model.CloningInstructionsEnum) ControlledGcpResourceApi(bio.terra.workspace.api.ControlledGcpResourceApi) Instance(com.google.api.services.notebooks.v1.model.Instance) JobControl(bio.terra.workspace.model.JobControl) ManagedBy(bio.terra.workspace.model.ManagedBy) CreateControlledGcpAiNotebookInstanceRequestBody(bio.terra.workspace.model.CreateControlledGcpAiNotebookInstanceRequestBody) HttpStatus(org.apache.http.HttpStatus) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) GeneralSecurityException(java.security.GeneralSecurityException) Duration(java.time.Duration) DeleteControlledGcpAiNotebookInstanceResult(bio.terra.workspace.model.DeleteControlledGcpAiNotebookInstanceResult) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) GcpAiNotebookInstanceVmImage(bio.terra.workspace.model.GcpAiNotebookInstanceVmImage) Nullable(javax.annotation.Nullable) DeleteControlledGcpAiNotebookInstanceRequest(bio.terra.workspace.model.DeleteControlledGcpAiNotebookInstanceRequest) AIPlatformNotebooks(com.google.api.services.notebooks.v1.AIPlatformNotebooks) ControlledResourceCommonFields(bio.terra.workspace.model.ControlledResourceCommonFields) ApiException(bio.terra.workspace.client.ApiException) Matchers(org.hamcrest.Matchers) IOException(java.io.IOException) UUID(java.util.UUID) CreatedControlledGcpAiNotebookInstanceResult(bio.terra.workspace.model.CreatedControlledGcpAiNotebookInstanceResult) GcpAiNotebookInstanceCreationParameters(bio.terra.workspace.model.GcpAiNotebookInstanceCreationParameters) List(java.util.List) TestUserSpecification(bio.terra.testrunner.runner.config.TestUserSpecification) Optional(java.util.Optional) RandomStringUtils(org.apache.commons.lang3.RandomStringUtils) TestIamPermissionsRequest(com.google.api.services.iam.v1.model.TestIamPermissionsRequest) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Instance(com.google.api.services.notebooks.v1.model.Instance) TestIamPermissionsRequest(com.google.api.services.iam.v1.model.TestIamPermissionsRequest) AIPlatformNotebooks(com.google.api.services.notebooks.v1.AIPlatformNotebooks)

Example 7 with TestIamPermissionsRequest

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

the class ControlledResourceServiceTest method createAiNotebookInstanceDo.

@Test
@DisabledIfEnvironmentVariable(named = "TEST_ENV", matches = BUFFER_SERVICE_DISABLED_ENVS_REG_EX)
void createAiNotebookInstanceDo() throws Exception {
    UUID workspaceUuid = workspace.getWorkspaceId();
    String workspaceUserFacingId = workspace.getUserFacingId();
    var instanceId = "create-ai-notebook-instance-do";
    var serverName = "verily-autopush";
    cliConfiguration.setServerName(serverName);
    ApiGcpAiNotebookInstanceCreationParameters creationParameters = ControlledResourceFixtures.defaultNotebookCreationParameters().instanceId(instanceId).location(DEFAULT_NOTEBOOK_LOCATION);
    ControlledAiNotebookInstanceResource resource = makeNotebookTestResource(workspaceUuid, "initial-notebook-name", instanceId);
    // Test idempotency of steps by retrying them once.
    Map<String, StepStatus> retrySteps = new HashMap<>();
    retrySteps.put(RetrieveNetworkNameStep.class.getName(), StepStatus.STEP_RESULT_FAILURE_RETRY);
    retrySteps.put(GrantPetUsagePermissionStep.class.getName(), StepStatus.STEP_RESULT_FAILURE_RETRY);
    retrySteps.put(CreateAiNotebookInstanceStep.class.getName(), StepStatus.STEP_RESULT_FAILURE_RETRY);
    retrySteps.put(NotebookCloudSyncStep.class.getName(), StepStatus.STEP_RESULT_FAILURE_RETRY);
    jobService.setFlightDebugInfoForTest(FlightDebugInfo.newBuilder().doStepFailures(retrySteps).build());
    String jobId = controlledResourceService.createAiNotebookInstance(resource, creationParameters, DEFAULT_ROLE, new ApiJobControl().id(UUID.randomUUID().toString()), "fakeResultPath", user.getAuthenticatedRequest());
    jobService.waitForJob(jobId);
    assertEquals(FlightStatus.SUCCESS, stairwayComponent.get().getFlightState(jobId).getFlightStatus());
    assertEquals(resource, controlledResourceService.getControlledResource(workspaceUuid, resource.getResourceId(), user.getAuthenticatedRequest()));
    InstanceName instanceName = resource.toInstanceName(workspaceService.getAuthorizedRequiredGcpProject(workspaceUuid, user.getAuthenticatedRequest()));
    Instance instance = crlService.getAIPlatformNotebooksCow().instances().get(instanceName).execute();
    // Test that the user has permissions from WRITER roles on the notebooks instance. Only notebook
    // instance level permissions can be checked on the notebook instance test IAM permissions
    // endpoint, so no "notebooks.instances.list" permission as that's project level.
    List<String> expectedWriterPermissions = ImmutableList.of("notebooks.instances.get", "notebooks.instances.reset", "notebooks.instances.setAccelerator", "notebooks.instances.setMachineType", "notebooks.instances.start", "notebooks.instances.stop", "notebooks.instances.use");
    assertThat(AIPlatformNotebooksCow.create(crlService.getClientConfig(), user.getGoogleCredentials()).instances().testIamPermissions(instanceName, new com.google.api.services.notebooks.v1.model.TestIamPermissionsRequest().setPermissions(expectedWriterPermissions)).execute().getPermissions(), containsInAnyOrder(expectedWriterPermissions.toArray()));
    // Test that the user has access to the notebook with a service account through proxy mode.
    // git secrets gets a false positive if 'service_account' is double quoted.
    assertThat(instance.getMetadata(), Matchers.hasEntry("proxy-mode", "service_" + "account"));
    assertThat(instance.getMetadata(), Matchers.hasEntry("terra-cli-server", serverName));
    assertThat(instance.getMetadata(), Matchers.hasEntry("terra-workspace-id", workspaceUserFacingId));
    ServiceAccountName serviceAccountName = ServiceAccountName.builder().projectId(instanceName.projectId()).email(instance.getServiceAccount()).build();
    // The user needs to have the actAs permission on the service account.
    String actAsPermission = "iam.serviceAccounts.actAs";
    assertThat(IamCow.create(crlService.getClientConfig(), user.getGoogleCredentials()).projects().serviceAccounts().testIamPermissions(serviceAccountName, new TestIamPermissionsRequest().setPermissions(List.of(actAsPermission))).execute().getPermissions(), Matchers.contains(actAsPermission));
    // Creating a controlled resource with a duplicate underlying notebook instance is not allowed.
    ControlledAiNotebookInstanceResource duplicateResource = makeNotebookTestResource(workspaceUuid, "new-name-same-notebook-instance", instanceId);
    String duplicateResourceJobId = controlledResourceService.createAiNotebookInstance(duplicateResource, creationParameters, DEFAULT_ROLE, new ApiJobControl().id(UUID.randomUUID().toString()), "fakeResultPath", user.getAuthenticatedRequest());
    jobService.waitForJob(duplicateResourceJobId);
    JobService.JobResultOrException<ControlledAiNotebookInstanceResource> duplicateJobResult = jobService.retrieveJobResult(duplicateResourceJobId, ControlledAiNotebookInstanceResource.class, user.getAuthenticatedRequest());
    assertEquals(DuplicateResourceException.class, duplicateJobResult.getException().getClass());
}
Also used : Instance(com.google.api.services.notebooks.v1.model.Instance) JobService(bio.terra.workspace.service.job.JobService) bio.terra.workspace.generated.model(bio.terra.workspace.generated.model) org.junit.jupiter.api(org.junit.jupiter.api) TestIamPermissionsRequest(com.google.api.services.iam.v1.model.TestIamPermissionsRequest) ServiceAccountName(bio.terra.cloudres.google.iam.ServiceAccountName) StepStatus(bio.terra.stairway.StepStatus) InstanceName(bio.terra.cloudres.google.notebooks.InstanceName) BaseConnectedTest(bio.terra.workspace.common.BaseConnectedTest) DisabledIfEnvironmentVariable(org.junit.jupiter.api.condition.DisabledIfEnvironmentVariable)

Example 8 with TestIamPermissionsRequest

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

the class AIPlatformNotebooksCowTest method setGetTestIamPolicyNotebookInstance.

@Test
public void setGetTestIamPolicyNotebookInstance() throws Exception {
    InstanceName instanceName = defaultInstanceName().instanceId("set-get-iam").build();
    createInstance(instanceName);
    String userEmail = IntegrationCredentials.getUserGoogleCredentialsOrDie().getClientEmail();
    Binding binding = new Binding().setRole("roles/notebooks.viewer").setMembers(ImmutableList.of("serviceAccount:" + userEmail));
    Policy policy = notebooks.instances().getIamPolicy(instanceName).execute();
    policy.setBindings(ImmutableList.of(binding));
    Policy updatedPolicy = notebooks.instances().setIamPolicy(instanceName, new SetIamPolicyRequest().setPolicy(policy)).execute();
    assertThat(updatedPolicy.getBindings(), Matchers.hasItem(binding));
    Policy secondRetrieval = notebooks.instances().getIamPolicy(instanceName).execute();
    assertThat(secondRetrieval.getBindings(), Matchers.hasItem(binding));
    // Test the permissions of the user for which the IAM policy was set.
    AIPlatformNotebooksCow userNotebooks = AIPlatformNotebooksCow.create(IntegrationUtils.DEFAULT_CLIENT_CONFIG, IntegrationCredentials.getUserGoogleCredentialsOrDie());
    // Notebook get permission from "roles/notebooks.viewer".
    String getNotebookPermission = "notebooks.instances.get";
    TestIamPermissionsResponse iamResponse = userNotebooks.instances().testIamPermissions(instanceName, new TestIamPermissionsRequest().setPermissions(ImmutableList.of(getNotebookPermission))).execute();
    assertThat(iamResponse.getPermissions(), Matchers.contains(getNotebookPermission));
    notebooks.instances().delete(instanceName).execute();
}
Also used : Binding(com.google.api.services.notebooks.v1.model.Binding) Policy(com.google.api.services.notebooks.v1.model.Policy) SetIamPolicyRequest(com.google.api.services.notebooks.v1.model.SetIamPolicyRequest) TestIamPermissionsResponse(com.google.api.services.notebooks.v1.model.TestIamPermissionsResponse) TestIamPermissionsRequest(com.google.api.services.notebooks.v1.model.TestIamPermissionsRequest) Test(org.junit.jupiter.api.Test)

Aggregations

TestIamPermissionsRequest (com.google.api.services.iam.v1.model.TestIamPermissionsRequest)6 TestIamPermissionsResponse (com.google.api.services.iam.v1.model.TestIamPermissionsResponse)4 Instance (com.google.api.services.notebooks.v1.model.Instance)2 IOException (java.io.IOException)2 GeneralSecurityException (java.security.GeneralSecurityException)2 ServiceAccountName (bio.terra.cloudres.google.iam.ServiceAccountName)1 InstanceName (bio.terra.cloudres.google.notebooks.InstanceName)1 StepStatus (bio.terra.stairway.StepStatus)1 TestUserSpecification (bio.terra.testrunner.runner.config.TestUserSpecification)1 ControlledGcpResourceApi (bio.terra.workspace.api.ControlledGcpResourceApi)1 ApiException (bio.terra.workspace.client.ApiException)1 BaseConnectedTest (bio.terra.workspace.common.BaseConnectedTest)1 bio.terra.workspace.generated.model (bio.terra.workspace.generated.model)1 AccessScope (bio.terra.workspace.model.AccessScope)1 CloningInstructionsEnum (bio.terra.workspace.model.CloningInstructionsEnum)1 ControlledResourceCommonFields (bio.terra.workspace.model.ControlledResourceCommonFields)1 CreateControlledGcpAiNotebookInstanceRequestBody (bio.terra.workspace.model.CreateControlledGcpAiNotebookInstanceRequestBody)1 CreatedControlledGcpAiNotebookInstanceResult (bio.terra.workspace.model.CreatedControlledGcpAiNotebookInstanceResult)1 DeleteControlledGcpAiNotebookInstanceRequest (bio.terra.workspace.model.DeleteControlledGcpAiNotebookInstanceRequest)1 DeleteControlledGcpAiNotebookInstanceResult (bio.terra.workspace.model.DeleteControlledGcpAiNotebookInstanceResult)1