use of com.google.api.services.iam.v1.model.SetIamPolicyRequest in project java-docs-samples by GoogleCloudPlatform.
the class Snippets method addMemberToKeyRingPolicy.
// [END kms_add_member_to_cryptokey_policy]
// [START kms_add_member_to_keyring_policy]
/**
* Adds the given member to the given keyring, with the given role.
*
* @param projectId The id of the project.
* @param locationId The location id of the key.
* @param keyRingId The id of the keyring.
* @param member The member to add. Must be in the proper format, eg:
*
* allUsers user:$userEmail serviceAccount:$serviceAccountEmail
*
* See https://g.co/cloud/kms/docs/reference/rest/v1/Policy#binding for more details.
* @param role Must be in one of the following formats: roles/[role]
* organizations/[organizationId]/roles/[role] projects/[projectId]/roles/[role]
*
* See https://g.co/cloud/iam/docs/understanding-roles for available values for [role].
*/
public static Policy addMemberToKeyRingPolicy(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 keyring version
String keyring = String.format("projects/%s/locations/%s/keyRings/%s", projectId, locationId, keyRingId);
// Get the current IAM policy
Policy iamPolicy = getKeyRingPolicy(projectId, locationId, keyRingId);
// Add the new account to it.
Binding newBinding = new Binding().setRole(role).setMembers(Collections.singletonList(member));
List<Binding> bindings = iamPolicy.getBindings();
if (null == bindings) {
bindings = Collections.singletonList(newBinding);
} else {
bindings.add(newBinding);
}
iamPolicy.setBindings(bindings);
// Set the new IAM Policy.
Policy newIamPolicy = kms.projects().locations().keyRings().setIamPolicy(keyring, new SetIamPolicyRequest().setPolicy(iamPolicy)).execute();
System.out.println("Response: " + newIamPolicy);
return newIamPolicy;
}
use of com.google.api.services.iam.v1.model.SetIamPolicyRequest 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;
}
use of com.google.api.services.iam.v1.model.SetIamPolicyRequest in project platinum by hartwigmedical.
the class PipelineIamPolicyTest method addsServiceAccountRolesToExistingPolicy.
@Test
public void addsServiceAccountRolesToExistingPolicy() throws Exception {
CloudResourceManager resourceManager = mock(CloudResourceManager.class);
CloudResourceManager.Projects projects = mock(CloudResourceManager.Projects.class);
CloudResourceManager.Projects.GetIamPolicy getIamPolicy = mock(CloudResourceManager.Projects.GetIamPolicy.class);
CloudResourceManager.Projects.SetIamPolicy setIamPolicy = mock(CloudResourceManager.Projects.SetIamPolicy.class);
Policy policy = new Policy().setBindings(new ArrayList<>());
when(resourceManager.projects()).thenReturn(projects);
when(projects.getIamPolicy("projects/test", new GetIamPolicyRequest())).thenReturn(getIamPolicy);
when(getIamPolicy.execute()).thenReturn(policy);
ArgumentCaptor<String> projectArgumentCaptor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<SetIamPolicyRequest> policyArgumentCaptor = ArgumentCaptor.forClass(SetIamPolicyRequest.class);
when(projects.setIamPolicy(projectArgumentCaptor.capture(), policyArgumentCaptor.capture())).thenReturn(setIamPolicy);
PipelineIamPolicy victim = new PipelineIamPolicy(resourceManager);
victim.apply(new ServiceAccount().setEmail(EMAIL).setProjectId(PROJECT_ID));
assertThat(projectArgumentCaptor.getValue()).isEqualTo(PROJECT_ID);
assertThat(policyArgumentCaptor.getValue().getPolicy().getBindings()).contains(new Binding().setMembers(List.of(IDENTITY)).setRole(PipelineIamPolicy.COMPUTE_ADMIN), new Binding().setMembers(List.of(IDENTITY)).setRole(PipelineIamPolicy.STORAGE_ADMIN));
}
use of com.google.api.services.iam.v1.model.SetIamPolicyRequest 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();
}
use of com.google.api.services.iam.v1.model.SetIamPolicyRequest 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");
}
}
Aggregations