/** * Check that the given IAM principal has permissions to access the KMS key. * * This is important because when an IAM principal is deleted and recreated with the same name, then the recreated * principal cannot access the KMS key until the key policy is regenerated -- updating the policy permissions to * allow the ARN of the recreated principal instead of the ID of the deleted principal. * * @param policyJson - The KMS key policy as a String */ protected boolean consumerPrincipalIsAnArnAndNotAnId(String policyJson) { try { Policy policy = policyReader.createPolicyFromJsonString(policyJson); return policy.getStatements() .stream() .anyMatch(statement -> StringUtils.equals(statement.getId(), CERBERUS_CONSUMER_SID) && statement.getPrincipals() .stream() .anyMatch(principal -> awsIamRoleArnParser.isArnThatCanGoInKeyPolicy(principal.getId()))); } catch (Exception e) { // if we can't deserialize we will assume policy has been corrupted manually and regenerate it logger.error("Failed to validate policy, did someone manually edit the kms policy?", e); } return false; }
/** * Validate that the IAM principal for the CMS has permissions to schedule and cancel deletion of the KMS key. * @param policyJson - The KMS key policy as a String */ protected boolean cmsHasKeyDeletePermissions(String policyJson) { try { Policy policy = policyReader.createPolicyFromJsonString(policyJson); return policy.getStatements() .stream() .anyMatch(statement -> StringUtils.equals(statement.getId(), CERBERUS_MANAGEMENT_SERVICE_SID) && statementAppliesToPrincipal(statement, cmsRoleArn) && statement.getEffect() == Statement.Effect.Allow && statementIncludesAction(statement, KMSActions.ScheduleKeyDeletion) && statementIncludesAction(statement, KMSActions.CancelKeyDeletion)); } catch (Exception e) { logger.error("Failed to validate that CMS can delete KMS key, there may be something wrong with the policy", e); } return false; }
public String subscribeQueueToTopic(String snsTopicArn, String sqsQueueUrl){ Map<String, String> queueAttributes = sqsClient.getQueueAttributes(new GetQueueAttributesRequest(sqsQueueUrl) .withAttributeNames(QueueAttributeName.QueueArn.toString())).getAttributes(); String sqsQueueArn = queueAttributes.get(QueueAttributeName.QueueArn.toString()); Policy policy = new Policy().withStatements( new Statement(Effect.Allow) .withId("topic-subscription-" + snsTopicArn) .withPrincipals(Principal.AllUsers) .withActions(SQSActions.SendMessage) .withResources(new Resource(sqsQueueArn)) .withConditions(ConditionFactory.newSourceArnCondition(snsTopicArn))); logger.debug("Policy: " + policy.toJson()); queueAttributes = new HashMap<String, String>(); queueAttributes.put(QueueAttributeName.Policy.toString(), policy.toJson()); sqsClient.setQueueAttributes(new SetQueueAttributesRequest(sqsQueueUrl, queueAttributes)); SubscribeResult subscribeResult = snsClient.subscribe(new SubscribeRequest() .withEndpoint(sqsQueueArn) .withProtocol("sqs") .withTopicArn(snsTopicArn)); return subscribeResult.getSubscriptionArn(); }
boolean policyChanged(String localPolicyJSON, com.amazonaws.services.identitymanagement.model.InstanceProfile remoteInstanceProfile) { String instanceProfileName = remoteInstanceProfile.getInstanceProfileName(); List<Role> roles = remoteInstanceProfile.getRoles(); Asserts.isFalse(roles.isEmpty(), "instance profile does not not have role, please check whether the role failed to add to instance profile, instanceProfileName={}", instanceProfileName); Asserts.equals(roles.size(), 1, "instance profile should only have one role, check whether it's modified not by cmn, instanceProfileName={}, roles={}", instanceProfileName, roles); Role role = roles.get(0); Optional<Policy> remotePolicy = AWS.iam.findRolePolicy(role.getRoleName(), role.getRoleName()); if (!remotePolicy.isPresent()) { logger.warn("role policy doesn't exist, it could be due to failure of last sync, it will try to create this time, instanceProfileName={}", instanceProfileName); return true; } Policy localPolicy = Policy.fromJson(localPolicyJSON); return policyChanged(localPolicy, remotePolicy.get()); }
@Test public void shouldSetQueueAttributes_withPolicy() { // Given final Policy mockPolicy = mock(Policy.class); final String mockPolicyJson = randomString(); when(mockPolicy.toJson()).thenReturn(mockPolicyJson); // When sqsQueueResource.setPolicy(mockPolicy); // Then final ArgumentCaptor<SetQueueAttributesRequest> captor = ArgumentCaptor .forClass(SetQueueAttributesRequest.class); verify(amazonSqsClient).setQueueAttributes(captor.capture()); final SetQueueAttributesRequest setQueueAttributesRequest = captor.getValue(); assertEquals(queueUrl, setQueueAttributesRequest.getQueueUrl()); assertEquals(mockPolicyJson, setQueueAttributesRequest.getAttributes() .get(QueueAttributeName.Policy.toString())); }
@Test public void shouldSetPolicy_withPolicy() { // Given final Policy mockPolicy = mock(Policy.class); final String mockPolicyJson = randomString(); when(mockPolicy.toJson()).thenReturn(mockPolicyJson); // When snsTopicResource.setPolicy(mockPolicy); // Then final ArgumentCaptor<SetTopicAttributesRequest> captor = ArgumentCaptor .forClass(SetTopicAttributesRequest.class); verify(mockAmazonSnsClient).setTopicAttributes(captor.capture()); final SetTopicAttributesRequest setTopicAttributesRequest = captor.getValue(); assertEquals(topicArn, setTopicAttributesRequest.getTopicArn()); assertEquals("Policy", setTopicAttributesRequest.getAttributeName()); assertEquals(mockPolicyJson, setTopicAttributesRequest.getAttributeValue()); }
@Test public void shouldThrowException_onAmazonClientExceptionFromSetPolicy() { // Given final Policy mockPolicy = mock(Policy.class); final String mockPolicyJson = randomString(); when(mockPolicy.toJson()).thenReturn(mockPolicyJson); doThrow(AmazonClientException.class).when(mockAmazonSnsClient) .setTopicAttributes(any(SetTopicAttributesRequest.class)); // When AmazonClientException thrownException = null; try { snsTopicResource.setPolicy(mockPolicy); } catch (final AmazonClientException e) { thrownException = e; } // Then assertNotNull(thrownException); }
/** * Converts the specified JSON string to an AWS policy object. * * For more information see, @see * http://docs.aws.amazon.com/AWSSdkDocsJava/latest * /DeveloperGuide/java-dg-access-control.html * * @param jsonString * the specified JSON string representation of this AWS access * control policy. * * @return An AWS policy object. * * @throws IllegalArgumentException * If the specified JSON string is null or invalid and cannot be * converted to an AWS policy object. */ public Policy createPolicyFromJsonString(String jsonString) { if (jsonString == null) { throw new IllegalArgumentException("JSON string cannot be null"); } JsonNode policyNode; JsonNode idNode; JsonNode statementNodes; Policy policy = new Policy(); List<Statement> statements = new LinkedList<Statement>(); try { policyNode = Jackson.jsonNodeOf(jsonString); idNode = policyNode.get(JsonDocumentFields.POLICY_ID); if (isNotNull(idNode)) { policy.setId(idNode.asText()); } statementNodes = policyNode.get(JsonDocumentFields.STATEMENT); if (isNotNull(statementNodes)) { for (JsonNode node : statementNodes) { statements.add(statementOf(node)); } } } catch (Exception e) { String message = "Unable to generate policy object fron JSON string " + e.getMessage(); throw new IllegalArgumentException(message, e); } policy.setStatements(statements); return policy; }
static Policy getForUser(String bucket, String userName) { Statement creatingObjectsStatement = getObjectCreatingStatement(bucket, userName); Statement multipartUploadStatement = getMultipartUploadStatement(bucket, userName); Statement listBucketStatement = getListBucketStatement(bucket, userName); return new Policy("PerUserFileUploadingPolicy", Arrays.asList(multipartUploadStatement, creatingObjectsStatement, listBucketStatement)); }
public FederatedUserCredentials getFederatedTokenFor(String username) { Policy policy = DefaultS3FolderPolicy.getForUser(bucket, username); GetFederationTokenRequest getFederationTokenRequest = new GetFederationTokenRequest() .withName(username) .withDurationSeconds(TEMPORARY_CREDENTIALS_VALIDITY) .withPolicy(policy.toJson()); GetFederationTokenResult federationTokenResult = tokenService.getFederationToken(getFederationTokenRequest); return new FederatedUserCredentials(region, bucket, username, federationTokenResult.getCredentials()); }
private String getPolicy(List<String> accountIds) { Policy policy = new Policy("AuthorizedWorkerAccessPolicy"); Statement stmt = new Statement(Effect.Allow); Action action = SQSActions.SendMessage; stmt.getActions().add(action); stmt.setResources(new LinkedList<>()); for(String accountId : accountIds) { Principal principal = new Principal(accountId); stmt.getPrincipals().add(principal); } stmt.getResources().add(new Resource(getQueueARN())); policy.getStatements().add(stmt); return policy.toJson(); }
/** * Overwrite the policy statement for CMS with the standard statement. Add the standard statement for CMS * to the policy if it did not already exist. * * @param policyJson - The KMS key policy in JSON format * @return - The updated JSON KMS policy containing a regenerated statement for CMS */ protected String overwriteCMSPolicy(String policyJson) { Policy policy = policyReader.createPolicyFromJsonString(policyJson); removeStatementFromPolicy(policy, CERBERUS_MANAGEMENT_SERVICE_SID); Collection<Statement> statements = policy.getStatements(); statements.add(generateStandardCMSPolicyStatement()); return policy.toJson(); }
protected void removeStatementFromPolicy(Policy policy, String statementId) { Collection<Statement> existingStatements = policy.getStatements(); List<Statement> policyStatementsExcludingConsumer = existingStatements.stream() .filter(statement -> ! StringUtils.equals(statement.getId(), statementId)) .collect(Collectors.toList()); policyStatementsExcludingConsumer.add(generateStandardCMSPolicyStatement()); policy.setStatements(policyStatementsExcludingConsumer); }
public String generateStandardKmsPolicy(String iamRoleArn) { Policy kmsPolicy = new Policy(); Statement rootUserStatement = new Statement(Statement.Effect.Allow); rootUserStatement.withId("Root User Has All Actions"); rootUserStatement.withPrincipals(new Principal(AWS_PROVIDER, rootUserArn, false)); rootUserStatement.withActions(KMSActions.AllKMSActions); rootUserStatement.withResources(new Resource("*")); Statement keyAdministratorStatement = new Statement(Statement.Effect.Allow); keyAdministratorStatement.withId("Admin Role Has All Actions"); keyAdministratorStatement.withPrincipals(new Principal(AWS_PROVIDER, adminRoleArn, false)); keyAdministratorStatement.withActions(KMSActions.AllKMSActions); keyAdministratorStatement.withResources(new Resource("*")); Statement instanceUsageStatement = generateStandardCMSPolicyStatement(); Statement iamRoleUsageStatement = new Statement(Statement.Effect.Allow); iamRoleUsageStatement.withId(CERBERUS_CONSUMER_SID); iamRoleUsageStatement.withPrincipals( new Principal(AWS_PROVIDER, iamRoleArn, false)); iamRoleUsageStatement.withActions(KMSActions.Decrypt); iamRoleUsageStatement.withResources(new Resource("*")); kmsPolicy.withStatements(rootUserStatement, keyAdministratorStatement, instanceUsageStatement, iamRoleUsageStatement); return kmsPolicy.toJson(); }
@Test public void test_that_generateStandardCMSPolicyStatement_returns_a_valid_statement() { Statement result = kmsPolicyService.generateStandardCMSPolicyStatement(); assertEquals(KmsPolicyService.CERBERUS_MANAGEMENT_SERVICE_SID, result.getId()); assertEquals(Statement.Effect.Allow, result.getEffect()); assertTrue(kmsPolicyService.cmsHasKeyDeletePermissions(new Policy().withStatements(result).toJson())); }
@Test public void test_that_removePolicyFromStatement_removes_the_given_statement() { String removeId = "remove id"; String keepId = "keep id"; Statement statementToRemove = new Statement(Statement.Effect.Allow).withId(removeId).withActions(KMSActions.AllKMSActions); Statement statementToKeep = new Statement(Statement.Effect.Deny).withId(keepId).withActions(KMSActions.AllKMSActions); Policy policy = new Policy("policy", Lists.newArrayList(statementToKeep, statementToRemove)); kmsPolicyService.removeStatementFromPolicy(policy, removeId); assertTrue(policy.getStatements().contains(statementToKeep)); assertFalse(policy.getStatements().contains(statementToRemove)); }
public static String getPublicReadPolicy(String bucket_name) { Policy bucket_policy = new Policy().withStatements( new Statement(Statement.Effect.Allow) .withPrincipals(Principal.AllUsers) .withActions(S3Actions.GetObject) .withResources(new Resource( "arn:aws:s3:::" + bucket_name + "/*"))); return bucket_policy.toJson(); }
private String provisionKmsCmkForBackupRegion(String region) { Policy kmsPolicy = new Policy(); final List<Statement> statements = new LinkedList<>(); // allow the configured admin iam principals all permissions configStore.getBackupAdminIamPrincipals().forEach( principal -> { log.debug("Adding principal: {} to the CMK Policy for region {}", principal, region); statements.add(new Statement(Statement.Effect.Allow) .withId("Principal " + principal + " Has All Actions") .withPrincipals(new Principal(AWS_PROVIDER, principal, false)) .withActions(KMSActions.AllKMSActions) .withResources(new Resource("*"))); }); kmsPolicy.setStatements(statements); String policyString = kmsPolicy.toJson(); log.debug("Creating key for region {} with policy {}", region, policyString); AWSKMS kms = AWSKMSClient.builder().withCredentials(getAWSCredentialsProviderChain()).withRegion(region).build(); CreateKeyResult createKeyResult = kms.createKey( new CreateKeyRequest() .withPolicy(policyString) .withBypassPolicyLockoutSafetyCheck(true) .withDescription(String.format("Cerberus Backup Encryption key for env: %S region: %s", environmentMetadata.getName(), region)) .withTags( new Tag().withTagKey("env").withTagValue(environmentMetadata.getName()), new Tag().withTagKey("region").withTagValue(region), new Tag().withTagKey("cerberus-backup-key").withTagValue("true") ) ); String keyId = createKeyResult.getKeyMetadata().getKeyId(); log.info("Created new backup KMS CMK with id: {} for region: {}", keyId, region); return keyId; }
/** * Returns a set of temporary security credentials (consisting of an access key ID, a secret access key, and a security token) that can be used to access * the specified AWS resource. * * @param sessionName the session name that will be associated with the temporary credentials. The session name must be the same for an initial set of * credentials and an extended set of credentials if credentials are to be refreshed. The session name also is used to identify the user in AWS logs so it * should be something unique and useful to identify the caller/use. * @param awsRoleArn the AWS ARN for the role required to provide access to the specified AWS resource * @param awsRoleDurationSeconds the duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) to 3600 seconds (1 hour). * @param policy the temporary policy to apply to this request * * @return the assumed session credentials */ @Override public Credentials getTemporarySecurityCredentials(AwsParamsDto awsParamsDto, String sessionName, String awsRoleArn, int awsRoleDurationSeconds, Policy policy) { // Construct a new AWS security token service client using the specified client configuration to access Amazon S3. // A credentials provider chain will be used that searches for credentials in this order: // - Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_KEY // - Java System Properties - aws.accessKeyId and aws.secretKey // - Instance Profile Credentials - delivered through the Amazon EC2 metadata service ClientConfiguration clientConfiguration = new ClientConfiguration().withRetryPolicy(retryPolicyFactory.getRetryPolicy()); // Only set the proxy hostname and/or port if they're configured. if (StringUtils.isNotBlank(awsParamsDto.getHttpProxyHost())) { clientConfiguration.setProxyHost(awsParamsDto.getHttpProxyHost()); } if (awsParamsDto.getHttpProxyPort() != null) { clientConfiguration.setProxyPort(awsParamsDto.getHttpProxyPort()); } AWSSecurityTokenServiceClient awsSecurityTokenServiceClient = new AWSSecurityTokenServiceClient(clientConfiguration); // Create the request. AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest(); assumeRoleRequest.setRoleSessionName(sessionName); assumeRoleRequest.setRoleArn(awsRoleArn); assumeRoleRequest.setDurationSeconds(awsRoleDurationSeconds); if (policy != null) { assumeRoleRequest.setPolicy(policy.toJson()); } // Get the temporary security credentials. AssumeRoleResult assumeRoleResult = stsOperations.assumeRole(awsSecurityTokenServiceClient, assumeRoleRequest); return assumeRoleResult.getCredentials(); }
void validatePolicyDocument(String policyJSON) { Policy policy = Policy.fromJson(policyJSON); Asserts.isFalse(policy.getStatements().isEmpty(), "statement is required"); for (Statement statement : policy.getStatements()) { Asserts.isFalse(statement.getActions().isEmpty(), "action is required"); } }
boolean policyChanged(Policy policy1, Policy policy2) { Collection<Statement> statements1 = policy1.getStatements(); Collection<Statement> statements2 = policy2.getStatements(); if (statements1.size() != statements2.size()) return true; for (Statement statement1 : statements1) { if (!containStatement(statements2, statement1)) return true; } return false; }
public Optional<Policy> findRolePolicy(String roleName, String policyName) { logger.info("find role policy, roleName={}, policyName={}", roleName, policyName); try { GetRolePolicyResult result = iam.getRolePolicy(new GetRolePolicyRequest() .withRoleName(roleName) .withPolicyName(policyName)); String policyJSON = Encodings.decodeURL(result.getPolicyDocument()); return Optional.of(Policy.fromJson(policyJSON)); } catch (NoSuchEntityException e) { return Optional.empty(); } }
@Test void policyChangedWithSamePolicy() { Policy policy1 = Policy.fromJson(ClasspathResources.text("iam-test/policy1.json")); Policy policy2 = Policy.fromJson(ClasspathResources.text("iam-test/policy1.json")); boolean changed = instanceProfileHelper.policyChanged(policy1, policy2); assertFalse(changed); }
@Test void policyChangedWithDifferentPolicies() { Policy policy1 = Policy.fromJson(ClasspathResources.text("iam-test/policy1.json")); Policy policy2 = Policy.fromJson(ClasspathResources.text("iam-test/policy2.json")); boolean changed = instanceProfileHelper.policyChanged(policy1, policy2); assertTrue(changed); }
/** * Converts the given <code>Policy</code> into a JSON String. * * @param policy * the policy to be converted. * @return a JSON String of the specified policy object. */ private String jsonStringOf(Policy policy) throws JsonGenerationException, IOException { generator.writeStartObject(); writeJsonKeyValue(JsonDocumentFields.VERSION, policy.getVersion()); if (isNotNull(policy.getId())) writeJsonKeyValue(JsonDocumentFields.POLICY_ID, policy.getId()); writeJsonArrayStart(JsonDocumentFields.STATEMENT); for (Statement statement : policy.getStatements()) { generator.writeStartObject(); if (isNotNull(statement.getId())) { writeJsonKeyValue(JsonDocumentFields.STATEMENT_ID, statement.getId()); } writeJsonKeyValue(JsonDocumentFields.STATEMENT_EFFECT, statement .getEffect().toString()); List<Principal> principals = statement.getPrincipals(); if (isNotNull(principals) && !principals.isEmpty()) writePrincipals(principals); List<Action> actions = statement.getActions(); if (isNotNull(actions) && !actions.isEmpty()) writeActions(actions); List<Resource> resources = statement.getResources(); if (isNotNull(resources) && !resources.isEmpty()) writeResources(resources); List<Condition> conditions = statement.getConditions(); if (isNotNull(conditions) && !conditions.isEmpty()) writeConditions(conditions); generator.writeEndObject(); } writeJsonArrayEnd(); generator.writeEndObject(); generator.flush(); return writer.toString(); }
@Override public void run(SetBackupAdminPrincipalsCommand command) { GetCallerIdentityResult identityResult = sts.getCallerIdentity(new GetCallerIdentityRequest()); String accountId = identityResult.getAccount(); String rootArn = String.format("arn:aws:iam::%s:root", accountId); String adminRoleArn = configStore.getAccountAdminArn().get(); Set<String> principals = new HashSet<>(); principals.add(rootArn); principals.add(adminRoleArn); principals.addAll(command.getAdditionalPrincipals()); configStore.storeBackupAdminIamPrincipals(principals); if (! configStore.getRegionBackupBucketMap().isEmpty()) { configStore.getRegionBackupBucketMap().forEach((region, backupRegionInfo) -> { final List<Statement> statements = new LinkedList<>(); principals.forEach( principal -> { log.debug("Adding principal: {} to the CMK Policy for region {}", principal, region); statements.add(new Statement(Statement.Effect.Allow) .withId("Principal " + principal + " Has All Actions") .withPrincipals(new Principal(AWS_PROVIDER, principal, false)) .withActions(KMSActions.AllKMSActions) .withResources(new Resource("*"))); }); Policy kmsPolicy = new Policy(); kmsPolicy.setStatements(statements); String policyString = kmsPolicy.toJson(); log.debug("Updating key {} for region {} with policy {}", backupRegionInfo.getKmsCmkId(), region, policyString); AWSKMS kms = AWSKMSClient.builder().withCredentials(getAWSCredentialsProviderChain()).withRegion(region).build(); PutKeyPolicyRequest request = new PutKeyPolicyRequest() .withKeyId(backupRegionInfo.getKmsCmkId()) .withPolicyName("default") .withBypassPolicyLockoutSafetyCheck(true) .withPolicy(policyString); kms.putKeyPolicy(request); log.info("Successfully updated key {} in region {} to allow the following principals access {}", backupRegionInfo.getKmsCmkId(), region, String.join(", ", principals)); }); } }
public AwsPolicyBuilder() { policy = new Policy(null, new ArrayList<>()); }
@SuppressWarnings("PMD.CloseResource") // These are not SQL statements so they don't need to be closed. private Policy createUploaderPolicyNoKmsKey(String s3BucketName, String s3Key) { return new AwsPolicyBuilder().withS3(s3BucketName, s3Key, S3Actions.PutObject).build(); }
public Credentials getTemporarySecurityCredentials(AwsParamsDto awsParamsDto, String sessionName, String awsRoleArn, int awsRoleDurationSeconds, Policy policy);
@Test public void testGetTemporarySecurityCredentials() { // Create an AWS parameters DTO with proxy settings. AwsParamsDto awsParamsDto = new AwsParamsDto(); awsParamsDto.setHttpProxyHost(HTTP_PROXY_HOST); awsParamsDto.setHttpProxyPort(HTTP_PROXY_PORT); // Specify the duration, in seconds, of the role session. int awsRoleDurationSeconds = INTEGER_VALUE; // Create an IAM policy. Policy policy = new Policy(STRING_VALUE); // Create a retry policy. RetryPolicy retryPolicy = new RetryPolicy(PredefinedRetryPolicies.DEFAULT_RETRY_CONDITION, PredefinedRetryPolicies.DEFAULT_BACKOFF_STRATEGY, INTEGER_VALUE, true); // Create the expected assume role request. AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest().withRoleArn(AWS_ROLE_ARN).withRoleSessionName(SESSION_NAME).withPolicy(policy.toJson()) .withDurationSeconds(awsRoleDurationSeconds); // Create AWS credentials for API authentication. Credentials credentials = new Credentials(); credentials.setAccessKeyId(AWS_ASSUMED_ROLE_ACCESS_KEY); credentials.setSecretAccessKey(AWS_ASSUMED_ROLE_SECRET_KEY); credentials.setSessionToken(AWS_ASSUMED_ROLE_SESSION_TOKEN); // Create an assume role result. AssumeRoleResult assumeRoleResult = new AssumeRoleResult(); assumeRoleResult.setCredentials(credentials); // Mock the external calls. when(retryPolicyFactory.getRetryPolicy()).thenReturn(retryPolicy); when(stsOperations.assumeRole(any(AWSSecurityTokenServiceClient.class), eq(assumeRoleRequest))).thenReturn(assumeRoleResult); // Call the method under test. Credentials result = stsDaoImpl.getTemporarySecurityCredentials(awsParamsDto, SESSION_NAME, AWS_ROLE_ARN, awsRoleDurationSeconds, policy); // Verify the external calls. verify(retryPolicyFactory).getRetryPolicy(); verify(stsOperations).assumeRole(any(AWSSecurityTokenServiceClient.class), eq(assumeRoleRequest)); verifyNoMoreInteractionsHelper(); // Validate the returned object. assertEquals(credentials, result); }
/** * Sets the {@link Policy} of the AWS SQS queue * @param policy {@link Policy} to set */ public void setPolicy(final Policy policy) throws AmazonClientException { final Map<String, String> queueAttributes = Collections.singletonMap(AWS_POLICY_ATTRIBUTE, policy.toJson()); amazonSqsClient.setQueueAttributes(new SetQueueAttributesRequest(queueUrl, queueAttributes)); }
private static void allowSQSQueueToReceiveMessagesFromSNSTopic( AmazonSQS amazonSQS, String queueURL, String queueARN, String topicARN ) { GetQueueAttributesResult queueAttributesResult = amazonSQS.getQueueAttributes( new GetQueueAttributesRequest().withQueueUrl(queueURL).withAttributeNames( QueueAttributeName.Policy ) ); String policyJson = queueAttributesResult.getAttributes().get(QueueAttributeName.Policy.name()); final List<Statement> statements; if (policyJson != null) { statements = new ArrayList<>(Policy.fromJson(policyJson).getStatements()); } else { // no policies yet exist statements = new ArrayList<>(); } statements.add( new Statement(Statement.Effect.Allow) .withPrincipals(Principal.AllUsers) .withResources(new Resource(queueARN)) .withActions(SQSActions.SendMessage) .withConditions(ConditionFactory.newSourceArnCondition(topicARN)) ); Policy policy = new Policy(); policy.setStatements(statements); Map<String, String> queueAttributes = new HashMap<>(); queueAttributes.put(QueueAttributeName.Policy.name(), policy.toJson()); // Note that if the queue already has this policy, this will do nothing. amazonSQS.setQueueAttributes( new SetQueueAttributesRequest() .withQueueUrl(queueURL) .withAttributes(queueAttributes) ); }
/** * Creates a restricted policy JSON string which only allows PutObject to the given bucket name and object key, and allows GenerateDataKey and Decrypt for * the given key ID. The Decrypt is required for multipart upload with KMS encryption. * * @param s3BucketName - The S3 bucket name to restrict uploads to * @param s3Key - The S3 object key to restrict the uploads to * @param awsKmsKeyId - The KMS key ID to allow access * * @return the policy JSON string */ @SuppressWarnings("PMD.CloseResource") // These are not SQL statements so they don't need to be closed. private Policy createUploaderPolicy(String s3BucketName, String s3Key, String awsKmsKeyId) { return new AwsPolicyBuilder().withS3(s3BucketName, s3Key, S3Actions.PutObject).withKms(awsKmsKeyId, KmsActions.GENERATE_DATA_KEY, KmsActions.DECRYPT) .build(); }
/** * Removes the 'Allow' statement for the consumer IAM principal. * * This is important when updating the KMS policy * because if the IAM principal has been deleted then the KMS policy will contain the principal 'ID' instead of the * ARN, which renders the policy invalid when calling {@link com.amazonaws.services.kms.AWSKMSClient#putKeyPolicy(PutKeyPolicyRequest)}. * * @param policyJson - Key policy JSON from which to remove consumer principal * @return - The updated key policy JSON */ protected String removeConsumerPrincipalFromPolicy(String policyJson) { Policy policy = policyReader.createPolicyFromJsonString(policyJson); removeStatementFromPolicy(policy, CERBERUS_CONSUMER_SID); return policy.toJson(); }
/** * Returns the policy object. * * @return The policy */ public Policy build() { return policy; }
/** * Creates a restricted policy JSON string which only allows GetObject to the given bucket name and object key, and allows Decrypt for the given key ID. * * @param s3BucketName - The S3 bucket name to restrict uploads to * @param s3Key - The S3 object key to restrict the uploads to * @param awsKmsKeyId - The KMS key ID to allow access * * @return the policy JSON string */ @SuppressWarnings("PMD.CloseResource") // These are not SQL statements so they don't need to be closed. private Policy createDownloaderPolicy(String s3BucketName, String s3Key, String awsKmsKeyId) { return new AwsPolicyBuilder().withS3(s3BucketName, s3Key, S3Actions.GetObject).withKms(awsKmsKeyId, KmsActions.DECRYPT).build(); }
/** * Creates a restricted policy JSON string which only allows GetObject to the given bucket name and object key, and allows Decrypt for the given key ID. * * @param s3BucketName - The S3 bucket name to restrict uploads to * @param s3Key - The S3 object key to restrict the uploads to * * @return the policy JSON string */ @SuppressWarnings("PMD.CloseResource") // These are not SQL statements so they don't need to be closed. private Policy createDownloaderPolicy(String s3BucketName, String s3Key) { return new AwsPolicyBuilder().withS3(s3BucketName, s3Key, S3Actions.GetObject).build(); }
/** * Sets the {@link Policy} of the AWS SNS topic * @param policy {@link Policy} to set * @throws AmazonClientException */ public void setPolicy(final Policy policy) throws AmazonClientException { amazonSnsClient .setTopicAttributes(new SetTopicAttributesRequest(topicArn, TOPIC_POLICY_ATTRIBUTE, policy.toJson())); }