Light, fluffy, and always free - The AWS Local Emulator alternative
fix(Cognito): implement CloudFormation provisioning for UserPool and UserPoolClient (#1007)
Arthur Tristram6434fc91f722
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.javaindex b5f97152c8..23cf5f89df 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java@@ -28,6 +28,9 @@ import io.github.hectorvent.floci.services.ssm.SsmService;import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;import io.github.hectorvent.floci.services.apigatewayv2.model.*;+import io.github.hectorvent.floci.services.cognito.CognitoService;+import io.github.hectorvent.floci.services.cognito.model.UserPool;+import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;import io.github.hectorvent.floci.core.common.AwsException;import com.fasterxml.jackson.databind.JsonNode;import jakarta.enterprise.context.ApplicationScoped;@@ -73,6 +76,7 @@ public class CloudFormationResourceProvisioner {private final ApiGatewayV2Service apiGatewayV2Service;private final EcrService ecrService;private final PipesService pipesService;+ private final CognitoService cognitoService;@Injectpublic CloudFormationResourceProvisioner(S3Service s3Service, SqsService sqsService,@@ -84,7 +88,8 @@ public class CloudFormationResourceProvisioner {ApiGatewayService apiGatewayService,ApiGatewayV2Service apiGatewayV2Service,EcrService ecrService,- PipesService pipesService) {+ PipesService pipesService,+ CognitoService cognitoService) {this.s3Service = s3Service;this.sqsService = sqsService;this.snsService = snsService;@@ -99,6 +104,7 @@ public class CloudFormationResourceProvisioner {this.apiGatewayV2Service = apiGatewayV2Service;this.ecrService = ecrService;this.pipesService = pipesService;+ this.cognitoService = cognitoService;}/**@@ -169,6 +175,10 @@ public class CloudFormationResourceProvisioner {case "AWS::Pipes::Pipe" -> provisionPipe(resource, properties, engine, region, stackName);case "AWS::Lambda::EventSourceMapping" ->provisionLambdaEventSourceMapping(resource, properties, engine, region);+ case "AWS::Cognito::UserPool" ->+ provisionCognitoUserPool(resource, properties, engine, region, accountId, stackName);+ case "AWS::Cognito::UserPoolClient" ->+ provisionCognitoUserPoolClient(resource, properties, engine, region, accountId, stackName);default -> {LOG.debugv("Stubbing unsupported resource type: {0} ({1})", resourceType, logicalId);resource.setPhysicalId(logicalId + "-" + UUID.randomUUID().toString().substring(0, 8));@@ -209,6 +219,8 @@ public class CloudFormationResourceProvisioner {ecrService.deleteRepository(physicalId, null, true, region);case "AWS::Pipes::Pipe" -> pipesService.deletePipe(physicalId, region);case "AWS::Lambda::EventSourceMapping" -> lambdaService.deleteEventSourceMapping(physicalId);+ case "AWS::Cognito::UserPool" -> cognitoService.deleteUserPool(physicalId);+ case "AWS::Cognito::UserPoolClient" -> cognitoService.deleteUserPoolClient(physicalId);default -> LOG.debugv("Skipping delete of unsupported resource type: {0}", resourceType);}} catch (Exception e) {@@ -1583,6 +1595,71 @@ public class CloudFormationResourceProvisioner {r.setPhysicalId(deployment.getDeploymentId());}+ // ── Cognito ──────────────────────────────────────────────────────────────++ private void provisionCognitoUserPool(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,+ String region, String accountId, String stackName) {+ String poolName = resolveOptional(props, "UserPoolName", engine);+ if (poolName == null || poolName.isBlank()) {+ poolName = generatePhysicalName(stackName, r.getLogicalId(), 128, false);+ }++ Map<String, Object> req = new HashMap<>();+ if (props != null) {+ req.putAll(jsonObjectToMap(engine.resolveNode(props)));+ }+ req.put("PoolName", poolName);++ // Handle Tags+ Map<String, String> tags = parseCfnTags(props != null ? props.get("UserPoolTags") : null, engine);+ if (!tags.isEmpty()) {+ req.put("UserPoolTags", tags);+ }++ UserPool pool;+ if (r.getPhysicalId() == null) {+ pool = cognitoService.createUserPool(req, region);+ } else {+ req.put("UserPoolId", r.getPhysicalId());+ pool = cognitoService.updateUserPool(req, region);+ }++ r.setPhysicalId(pool.getId());+ r.getAttributes().put("Arn", pool.getArn());+ r.getAttributes().put("UserPoolId", pool.getId());+ r.getAttributes().put("ProviderName", pool.getName());+ r.getAttributes().put("ProviderURL", cognitoService.getIssuer(pool.getId()));+ }++ private void provisionCognitoUserPoolClient(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,+ String region, String accountId, String stackName) {+ String userPoolId = resolveOptional(props, "UserPoolId", engine);+ String clientName = resolveOptional(props, "ClientName", engine);+ if (clientName == null || clientName.isBlank()) {+ clientName = generatePhysicalName(stackName, r.getLogicalId(), 128, false);+ }+ boolean generateSecret = Boolean.parseBoolean(resolveOrDefault(props, "GenerateSecret", engine, "false"));+ boolean allowedOAuthFlowsUserPoolClient = Boolean.parseBoolean(resolveOrDefault(props, "AllowedOAuthFlowsUserPoolClient", engine, "false"));+ List<String> allowedOAuthFlows = resolveStringListOrEmpty(props, "AllowedOAuthFlows", engine);+ List<String> allowedOAuthScopes = resolveStringListOrEmpty(props, "AllowedOAuthScopes", engine);++ UserPoolClient client;+ if (r.getPhysicalId() == null) {+ client = cognitoService.createUserPoolClient(userPoolId, clientName, generateSecret,+ allowedOAuthFlowsUserPoolClient, allowedOAuthFlows, allowedOAuthScopes);+ } else {+ client = cognitoService.updateUserPoolClient(userPoolId, r.getPhysicalId(), clientName,+ allowedOAuthFlowsUserPoolClient, allowedOAuthFlows, allowedOAuthScopes);+ }++ r.setPhysicalId(client.getClientId());+ r.getAttributes().put("ClientId", client.getClientId());+ r.getAttributes().put("ClientName", client.getClientName());+ if (client.getClientSecret() != null) {+ r.getAttributes().put("ClientSecret", client.getClientSecret());+ }+ }+private String resolveOptional(JsonNode props, String name, CloudFormationTemplateEngine engine) {if (props == null || !props.has(name) || props.get(name).isNull()) {return null;diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.javaindex 8100709dcf..e232d180e4 100644--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java@@ -278,6 +278,11 @@ public class CognitoService {return clientStore.scan(k -> clientStore.get(k).map(c -> c.getUserPoolId().equals(userPoolId)).orElse(false));}+ public void deleteUserPoolClient(String clientId) {+ clientStore.get(clientId).orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool client not found", 404));+ clientStore.delete(clientId);+ }+public void deleteUserPoolClient(String userPoolId, String clientId) {describeUserPoolClient(userPoolId, clientId);clientStore.delete(clientId);diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.javaindex acca519725..59be5c7f6a 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java@@ -30,6 +30,7 @@ class CloudFormationIntegrationTest {private static final String DYNAMODB_CONTENT_TYPE = "application/x-amz-json-1.0";private static final String SSM_CONTENT_TYPE = "application/x-amz-json-1.1";private static final String SM_CONTENT_TYPE = "application/x-amz-json-1.1";+ private static final String COGNITO_CONTENT_TYPE = "application/x-amz-json-1.1";private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();@BeforeAll@@ -4303,4 +4304,126 @@ class CloudFormationIntegrationTest {.body(containsString("cfn-sub-policies-dlq"));}+ @Test+ void createStack_withCognitoUserPoolAndClient() {+ String template = """+ {+ "Resources": {+ "UserPool": {+ "Type": "AWS::Cognito::UserPool",+ "Properties": {+ "UserPoolName": "cfn-test-pool",+ "UserPoolTags": [+ { "Key": "env", "Value": "test" },+ { "Key": "team", "Value": "auth" }+ ]+ }+ },+ "UserPoolClient": {+ "Type": "AWS::Cognito::UserPoolClient",+ "Properties": {+ "ClientName": "cfn-test-client",+ "UserPoolId": { "Ref": "UserPool" },+ "GenerateSecret": true+ }+ }+ },+ "Outputs": {+ "PoolId": { "Value": { "Ref": "UserPool" } },+ "PoolArn": { "Value": { "Fn::GetAtt": ["UserPool", "Arn"] } },+ "ClientId": { "Value": { "Ref": "UserPoolClient" } }+ }+ }+ """;++ String stackName = "cognito-test-stack";++ // 1. Create Stack+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateStack")+ .formParam("StackName", stackName)+ .formParam("TemplateBody", template)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<StackId>"));++ // 2. Describe Stacks and capture outputs+ String describeXml = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))+ .extract().asString();++ String poolId = describeXml.split("<OutputKey>PoolId</OutputKey>")[1].split("<OutputValue>")[1].split("</OutputValue>")[0];+ String poolArn = describeXml.split("<OutputKey>PoolArn</OutputKey>")[1].split("<OutputValue>")[1].split("</OutputValue>")[0];+ String clientId = describeXml.split("<OutputKey>ClientId</OutputKey>")[1].split("<OutputValue>")[1].split("</OutputValue>")[0];++ assertThat(poolId, startsWith("us-east-1_"));+ assertThat(poolArn, startsWith("arn:aws:cognito-idp:"));+ assertThat(clientId, notNullValue());++ // 3. Verify UserPool via Cognito API+ given()+ .header("X-Amz-Target", "AWSCognitoIdentityProviderService.DescribeUserPool")+ .contentType(COGNITO_CONTENT_TYPE)+ .body("{\"UserPoolId\": \"" + poolId + "\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("UserPool.Name", equalTo("cfn-test-pool"))+ .body("UserPool.UserPoolTags.env", equalTo("test"))+ .body("UserPool.UserPoolTags.team", equalTo("auth"));++ // 4. Verify UserPoolClient via Cognito API+ given()+ .header("X-Amz-Target", "AWSCognitoIdentityProviderService.DescribeUserPoolClient")+ .contentType(COGNITO_CONTENT_TYPE)+ .body("{\"UserPoolId\": \"" + poolId + "\", \"ClientId\": \"" + clientId + "\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("UserPoolClient.ClientName", equalTo("cfn-test-client"))+ .body("UserPoolClient.UserPoolId", equalTo(poolId))+ .body("UserPoolClient.ClientSecret", notNullValue());++ // 5. Delete Stack+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DeleteStack")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200);++ // 6. Verify resources are deleted+ given()+ .header("X-Amz-Target", "AWSCognitoIdentityProviderService.DescribeUserPool")+ .contentType(COGNITO_CONTENT_TYPE)+ .body("{\"UserPoolId\": \"" + poolId + "\"}")+ .when()+ .post("/")+ .then()+ .statusCode(404);++ given()+ .header("X-Amz-Target", "AWSCognitoIdentityProviderService.DescribeUserPoolClient")+ .contentType(COGNITO_CONTENT_TYPE)+ .body("{\"UserPoolId\": \"" + poolId + "\", \"ClientId\": \"" + clientId + "\"}")+ .when()+ .post("/")+ .then()+ .statusCode(404);+ }+}