use of com.google.api.services.cloudresourcemanager.v3.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);
}
use of com.google.api.services.cloudresourcemanager.v3.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());
}
use of com.google.api.services.cloudresourcemanager.v3.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();
}
Aggregations