Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for AgentPermissions in CloudFormation (Schema + CreateHandler) #10

Merged
merged 6 commits into from
May 26, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion aws-codeguruprofiler-profilinggroup/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ pre-commit run --all-files && AWS_REGION=us-east-1 mvn clean verify package

5. Create a sample CloudFormation stack that defines a profiling group:
```
aws cloudformation create-stack --region us-east-1 --template-body "file://sample-template.json" --stack-name "sample-profiling-group-resource-creation"
aws cloudformation create-stack --region us-east-1 --template-body "file://sample-template.json" --stack-name "sample-profiling-group-resource-creation" --capabilities CAPABILITY_IAM
```

6. Validate the creation of the profiling group!
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@
"Arn": {
"type": "string",
"pattern": "^arn:aws(-(cn|gov))?:[a-z-]+:(([a-z]+-)+[0-9]+):([0-9]{12}):[^.]+$"
},
"ArnIam": {
"type": "string",
"pattern": "^arn:aws(-(cn|gov))?:iam::([0-9]{12}):[^.]+$"

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking into it in #19

}
},
"properties": {
Expand All @@ -16,6 +20,33 @@
"maxLength": 255,
"pattern": "^[\\w-]+$"
},
"Permissions": {
"description": "The permissions attached for this profiling group.",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"description": "The permissions attached for this profiling group.",
"description": "The permissions attached to this profiling group.",

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I will update.

"type": "object",
"additionalProperties": false,
"required": [
"AgentPermissions"
],
"properties": {
"AgentPermissions": {
"type": "object",
"description": "The permissions for the agent.",
"additionalProperties": false,
"required": [
"Principals"
],
"properties": {
"Principals": {
"description": "The principals for the agent permissions.",
"type": "array",
"items": {
"$ref": "#/definitions/ArnIam"
}
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This structure seems quite deep:

{
  "Type": "AWS::CodeGuruProfiler::ProfilingGroup",
  "Properties": {
    "ProfilingGroupName": "some-profiling-group",
    "Permissions": {
      "AgentPermissions": {
        "Principals": ["...list of principals... "]
      }
    }
  }
}

What do you think of making it a little more flatter by going with

{
  "Type": "AWS::CodeGuruProfiler::ProfilingGroup",
  "Properties": {
    "ProfilingGroupName": "some-profiling-group",
    "Permissions": [
      {
        "ActionGroup": "agentPermissions",
        "Principals": ["...list of principals..."]
      }
    ]
  }
}

or

{
  "Type": "AWS::CodeGuruProfiler::ProfilingGroup",
  "Properties": {
    "ProfilingGroupName": "some-profiling-group",
    "AgentPermissions": {
      "Principals": ["...list of principals... "]
    }
  }
}

?

Cloudformation is already quite verbose, so the more lightweight we can make it, the better :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point, I will update the code with having AgentPermissions as first-level property, thanks.

}
},
"Arn": {
"description": "The Amazon Resource Name (ARN) of the specified profiling group.",
"$ref": "#/definitions/Arn",
Expand All @@ -26,7 +57,8 @@
},
"additionalProperties": false,
"required": [
"ProfilingGroupName"
"ProfilingGroupName",
"Permissions"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems potentially problematic -- what happens to existing customers that have cloudformation written without specifying permissions?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It makes sense, I will update then the code for Permissions to not be required, thanks.

],
"primaryIdentifier": [
"/properties/ProfilingGroupName"
Expand All @@ -40,7 +72,8 @@
"handlers": {
"create": {
"permissions": [
"codeguru-profiler:CreateProfilingGroup"
"codeguru-profiler:CreateProfilingGroup",
"codeguru-profiler:PutPermission"
]
},
"read": {
Expand Down
14 changes: 12 additions & 2 deletions aws-codeguruprofiler-profilinggroup/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
<dependency>
<groupId>software.amazon.cloudformation</groupId>
<artifactId>aws-cloudformation-rpdk-java-plugin</artifactId>
<version>1.0.2</version>
<version>1.0.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
Expand Down Expand Up @@ -74,9 +74,19 @@
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>codeguruprofiler</artifactId>
<version>2.10.63</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bom</artifactId>
<version>2.13.16</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be nice to see this change in a separate commit and with an explanation of what it does, so that it would be clear and we could refer to it in the future.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was later extracted by @gimki as part of PR #11.


<build>
<plugins>
Expand Down
1 change: 1 addition & 0 deletions aws-codeguruprofiler-profilinggroup/resource-role.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ Resources:
- "codeguru-profiler:DeleteProfilingGroup"
- "codeguru-profiler:DescribeProfilingGroup"
- "codeguru-profiler:ListProfilingGroups"
- "codeguru-profiler:PutPermission"
Resource: "*"
Outputs:
ExecutionRoleArn:
Expand Down
35 changes: 34 additions & 1 deletion aws-codeguruprofiler-profilinggroup/sample-template.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,43 @@
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "Sample template for the AWS::CodeGuruProfiler::ProfilingGroup resource.",
"Resources": {
"MyRole": {
gimki marked this conversation as resolved.
Show resolved Hide resolved
"Type": "AWS::IAM::Role",
"Properties": {
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": [
"ec2.amazonaws.com"
]
},
"Action": [
"sts:AssumeRole"
]
}
]
}
}
},
"MyProfilingGroup": {
"Type": "AWS::CodeGuruProfiler::ProfilingGroup",
"Properties": {
"ProfilingGroupName": "MySampleProfilingGroup"
"ProfilingGroupName": "MySampleProfilingGroup",
gimki marked this conversation as resolved.
Show resolved Hide resolved
"Permissions": {
"AgentPermissions": {
"Principals": [
{
"Fn::GetAtt": [
"MyRole",
"Arn"
]
}
]
}
}
}
}
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package software.amazon.codeguruprofiler.profilinggroup;

import software.amazon.awssdk.services.codeguruprofiler.CodeGuruProfilerClient;
import software.amazon.awssdk.services.codeguruprofiler.model.ActionGroup;
import software.amazon.awssdk.services.codeguruprofiler.model.ConflictException;
import software.amazon.awssdk.services.codeguruprofiler.model.CreateProfilingGroupRequest;
import software.amazon.awssdk.services.codeguruprofiler.model.InternalServerException;
import software.amazon.awssdk.services.codeguruprofiler.model.PutPermissionRequest;
import software.amazon.awssdk.services.codeguruprofiler.model.ServiceQuotaExceededException;
import software.amazon.awssdk.services.codeguruprofiler.model.ThrottlingException;
import software.amazon.awssdk.services.codeguruprofiler.model.ValidationException;
Expand All @@ -17,6 +19,10 @@
import software.amazon.cloudformation.proxy.ProgressEvent;
import software.amazon.cloudformation.proxy.ResourceHandlerRequest;

import java.util.List;

import static java.util.Collections.emptyList;

public class CreateHandler extends BaseHandler<CallbackContext> {

private final CodeGuruProfilerClient profilerClient = CodeGuruProfilerClientBuilder.create();
Expand All @@ -40,6 +46,14 @@ public ProgressEvent<ResourceModel, CallbackContext> handleRequest(

proxy.injectCredentialsAndInvokeV2(createProfilingGroupRequest, profilerClient::createProfilingGroup);

PutPermissionRequest putPermissionRequest = PutPermissionRequest.builder()
gimki marked this conversation as resolved.
Show resolved Hide resolved
.profilingGroupName(model.getProfilingGroupName())
.actionGroup(ActionGroup.AGENT_PERMISSIONS)
.principals(extractPrincipalsForAgentPermissions(model))
.build();

proxy.injectCredentialsAndInvokeV2(putPermissionRequest, profilerClient::putPermission);

logger.log(String.format("%s [%s] for accountId [%s] has been successfully created!", ResourceModel.TYPE_NAME, model.getProfilingGroupName(), awsAccountId));

return ProgressEvent.defaultSuccessHandler(model);
Expand All @@ -55,4 +69,14 @@ public ProgressEvent<ResourceModel, CallbackContext> handleRequest(
throw new CfnInvalidRequestException(ResourceModel.TYPE_NAME + e.getMessage(), e);
}
}

private static List<String> extractPrincipalsForAgentPermissions(final ResourceModel model) {
if (model.getPermissions() == null) {
return emptyList();
}
if (model.getPermissions().getAgentPermissions() == null) {
gimki marked this conversation as resolved.
Show resolved Hide resolved
return emptyList();
}
return model.getPermissions().getAgentPermissions().getPrincipals();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
import software.amazon.awssdk.services.codeguruprofiler.model.CreateProfilingGroupResponse;
import software.amazon.awssdk.services.codeguruprofiler.model.InternalServerException;
import software.amazon.awssdk.services.codeguruprofiler.model.ProfilingGroupDescription;
import software.amazon.awssdk.services.codeguruprofiler.model.PutPermissionRequest;
import software.amazon.awssdk.services.codeguruprofiler.model.PutPermissionResponse;
import software.amazon.awssdk.services.codeguruprofiler.model.ServiceQuotaExceededException;
import software.amazon.awssdk.services.codeguruprofiler.model.ThrottlingException;
import software.amazon.awssdk.services.codeguruprofiler.model.ValidationException;
Expand All @@ -25,13 +27,17 @@
import software.amazon.cloudformation.proxy.ProgressEvent;
import software.amazon.cloudformation.proxy.ResourceHandlerRequest;

import java.util.Arrays;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static software.amazon.codeguruprofiler.profilinggroup.RequestBuilder.makeInvalidRequest;
import static software.amazon.codeguruprofiler.profilinggroup.RequestBuilder.makeRequest;
import static software.amazon.codeguruprofiler.profilinggroup.RequestBuilder.makeValidRequest;

@ExtendWith(MockitoExtension.class)
Expand All @@ -54,16 +60,25 @@ public void setup() {
}

@Test
public void testSuccessState() {
doReturn(CreateProfilingGroupResponse.builder()
public void testSuccessStateNoPermissions() {
gimki marked this conversation as resolved.
Show resolved Hide resolved
String pgName = "IronMan-Suit-34";
String clientToken = "clientTokenXXX";

// Use Mockito's lenient feature to allow stubbed method to be invoked with different arguments.
lenient().doReturn(CreateProfilingGroupResponse.builder()
.profilingGroup(ProfilingGroupDescription.builder()
.name("IronMan-Suit-34")
.name(pgName)
.build())
.build())
.when(proxy).injectCredentialsAndInvokeV2(
ArgumentMatchers.eq(CreateProfilingGroupRequest
.builder()
.profilingGroupName("IronMan-Suit-34").clientToken("clientTokenXXX")
ArgumentMatchers.eq(CreateProfilingGroupRequest.builder()
gimki marked this conversation as resolved.
Show resolved Hide resolved
.profilingGroupName(pgName).clientToken(clientToken)
.build()), any());

lenient().doReturn(PutPermissionResponse.builder()
.build())
.when(proxy).injectCredentialsAndInvokeV2(
ArgumentMatchers.eq(PutPermissionRequest.builder()
.build()), any());

final ProgressEvent<ResourceModel, CallbackContext> response
Expand All @@ -78,6 +93,38 @@ public void testSuccessState() {
assertThat(response.getErrorCode()).isNull();
}

@Test
public void testSuccessStatePermissions() {
// Use Mockito's lenient feature to allow stubbed method to be invoked with different arguments.
lenient().doReturn(CreateProfilingGroupResponse.builder().build())
.when(proxy).injectCredentialsAndInvokeV2(
ArgumentMatchers.eq(CreateProfilingGroupRequest.builder().build()), any());

lenient().doReturn(PutPermissionResponse.builder().build())
.when(proxy).injectCredentialsAndInvokeV2(
ArgumentMatchers.eq(PutPermissionRequest.builder().build()), any());

CreateHandler handler = new CreateHandler();

assertThat(handler.handleRequest(proxy, newRequestWithPermissions(null), null, logger)).isNotNull();

Permissions noAgentPermissions = Permissions.builder().agentPermissions(null).build();
assertThat(handler.handleRequest(proxy, newRequestWithPermissions(noAgentPermissions), null, logger)).isNotNull();

Permissions agentPermissions = Permissions.builder().agentPermissions(
AgentPermissions.builder().principals(Arrays.asList("a", "bc")).build())
.build();
assertThat(handler.handleRequest(proxy, newRequestWithPermissions(agentPermissions), null, logger)).isNotNull();
}

private static ResourceHandlerRequest<ResourceModel> newRequestWithPermissions(final Permissions permissions) {
return makeRequest(newResourceModel(permissions));
}

private static ResourceModel newResourceModel(final Permissions permissions) {
return ResourceModel.builder().permissions(permissions).build();
}

@Test
public void testConflictException() {
doThrow(ConflictException.builder().build())
Expand Down