mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(cloudformation): provision Cognito user pool identity providers (#7350)
This commit is contained in:
1 parent
121dc22563
commit
d0747f26d1
15 files changed
+1617
-345
No files matched your search
+244
@@ -0,0 +1,244 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Output;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Parameter;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.model.IdentityProviderType;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.model.ProviderDescription;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.model.ResourceNotFoundException;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
/**
|
||||
* Exercises identity providers through both CloudFormation and Cognito SDK clients. Pools live
|
||||
* outside the stack so replacement and rollback cleanup remain observable after stack deletion.
|
||||
*/
|
||||
@DisplayName("CloudFormation AWS::Cognito::UserPoolIdentityProvider")
|
||||
class CloudFormationCognitoIdentityProviderTest {
|
||||
|
||||
private static final String TEMPLATE = """
|
||||
{
|
||||
"Parameters": {
|
||||
"UserPoolId": {"Type": "String"},
|
||||
"ProviderName": {"Type": "String"},
|
||||
"ClientId": {"Type": "String"},
|
||||
"Fail": {"Type": "String", "Default": "false"}
|
||||
},
|
||||
"Conditions": {
|
||||
"Fail": {"Fn::Equals": [{"Ref": "Fail"}, "true"]}
|
||||
},
|
||||
"Resources": {
|
||||
"Idp": {
|
||||
"Type": "AWS::Cognito::UserPoolIdentityProvider",
|
||||
"Properties": {
|
||||
"UserPoolId": {"Ref": "UserPoolId"},
|
||||
"ProviderName": {"Ref": "ProviderName"},
|
||||
"ProviderType": "OIDC",
|
||||
"ProviderDetails": {
|
||||
"client_id": {"Ref": "ClientId"},
|
||||
"client_secret": "example-secret",
|
||||
"oidc_issuer": "https://issuer.example.com",
|
||||
"authorize_scopes": "openid email",
|
||||
"attributes_request_method": "GET"
|
||||
},
|
||||
"AttributeMapping": {"email": "email"}
|
||||
}
|
||||
},
|
||||
"Duplicate": {
|
||||
"Type": "AWS::Cognito::UserPoolIdentityProvider",
|
||||
"Condition": "Fail",
|
||||
"DependsOn": "Idp",
|
||||
"Properties": {
|
||||
"UserPoolId": {"Ref": "UserPoolId"},
|
||||
"ProviderName": {"Ref": "Idp"},
|
||||
"ProviderType": "OIDC",
|
||||
"ProviderDetails": {
|
||||
"client_id": "duplicate",
|
||||
"oidc_issuer": "https://issuer.example.com",
|
||||
"authorize_scopes": "openid"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"ProviderRef": {"Value": {"Ref": "Idp"}}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
private static CloudFormationClient cfn;
|
||||
private static CognitoIdentityProviderClient cognito;
|
||||
|
||||
private String stackName;
|
||||
private String stackId;
|
||||
private String p1;
|
||||
private String p2;
|
||||
|
||||
@BeforeAll
|
||||
static void clients() {
|
||||
cfn = TestFixtures.cloudFormationClient();
|
||||
cognito = TestFixtures.cognitoClient();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
stackName = TestFixtures.uniqueName("compat-cfn-cidp");
|
||||
p1 = cognito.createUserPool(r -> r.poolName(stackName + "-p1")).userPool().id();
|
||||
p2 = cognito.createUserPool(r -> r.poolName(stackName + "-p2")).userPool().id();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanup() throws InterruptedException {
|
||||
try {
|
||||
deleteStack();
|
||||
} finally {
|
||||
for (String pool : new String[] {p1, p2}) {
|
||||
if (pool == null) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
cognito.deleteUserPool(r -> r.userPoolId(pool));
|
||||
} catch (ResourceNotFoundException expected) {
|
||||
// The pool never finished creating or was already removed.
|
||||
}
|
||||
}
|
||||
p1 = null;
|
||||
p2 = null;
|
||||
}
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void closeClients() {
|
||||
cfn.close();
|
||||
cognito.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Ref is ProviderName, and ProviderDetails update in place before stack deletion")
|
||||
void providerDetailsUpdateInPlaceAndStackDeletionRemovesTheProvider() throws InterruptedException {
|
||||
createStack(parameters(p1, "ExampleOIDC", "original-client", false));
|
||||
assertIdentity("ExampleOIDC");
|
||||
assertProvider(p1, "ExampleOIDC", "original-client");
|
||||
|
||||
updateStack(parameters(p1, "ExampleOIDC", "updated-client", false), "UPDATE_COMPLETE");
|
||||
assertIdentity("ExampleOIDC");
|
||||
assertProvider(p1, "ExampleOIDC", "updated-client");
|
||||
assertThat(providerNames(p1)).containsExactly("ExampleOIDC");
|
||||
|
||||
deleteStack();
|
||||
assertProviderNotFound(p1, "ExampleOIDC");
|
||||
assertThat(providerNames(p1)).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Changing ProviderName replaces the provider and deletes the old one")
|
||||
void renamingReplacesTheProvider() throws InterruptedException {
|
||||
createStack(parameters(p1, "ExampleOIDC", "client", false));
|
||||
|
||||
updateStack(parameters(p1, "RenamedOIDC", "client", false), "UPDATE_COMPLETE");
|
||||
|
||||
assertIdentity("RenamedOIDC");
|
||||
assertProvider(p1, "RenamedOIDC", "client");
|
||||
assertThat(providerNames(p1)).containsExactly("RenamedOIDC");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Changing UserPoolId replaces the provider while Ref stays the ProviderName")
|
||||
void movingPoolsReplacesTheProvider() throws InterruptedException {
|
||||
createStack(parameters(p1, "ExampleOIDC", "client", false));
|
||||
|
||||
updateStack(parameters(p2, "ExampleOIDC", "moved-client", false), "UPDATE_COMPLETE");
|
||||
|
||||
assertIdentity("ExampleOIDC");
|
||||
assertProvider(p2, "ExampleOIDC", "moved-client");
|
||||
assertThat(providerNames(p1)).isEmpty();
|
||||
deleteStack();
|
||||
assertThat(providerNames(p2)).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("A failed dependent resource rolls the in-place ProviderDetails update back")
|
||||
void aFailedDependentResourceRestoresTheProviderDetails() throws InterruptedException {
|
||||
createStack(parameters(p1, "ExampleOIDC", "original-client", false));
|
||||
|
||||
updateStack(parameters(p1, "ExampleOIDC", "attempted-client", true), "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
assertThat(cfn.describeStackEvents(r -> r.stackName(stackId)).stackEvents())
|
||||
.anySatisfy(event -> {
|
||||
assertThat(event.logicalResourceId()).isEqualTo("Duplicate");
|
||||
assertThat(event.resourceStatusAsString()).isIn("CREATE_FAILED", "UPDATE_FAILED");
|
||||
assertThat(event.resourceStatusReason()).contains("already exists");
|
||||
});
|
||||
assertIdentity("ExampleOIDC");
|
||||
assertProvider(p1, "ExampleOIDC", "original-client");
|
||||
assertThat(providerNames(p1)).containsExactly("ExampleOIDC");
|
||||
}
|
||||
|
||||
private static List<Parameter> parameters(String pool, String providerName, String clientId, boolean fail) {
|
||||
return List.of(
|
||||
Parameter.builder().parameterKey("UserPoolId").parameterValue(pool).build(),
|
||||
Parameter.builder().parameterKey("ProviderName").parameterValue(providerName).build(),
|
||||
Parameter.builder().parameterKey("ClientId").parameterValue(clientId).build(),
|
||||
Parameter.builder().parameterKey("Fail").parameterValue(Boolean.toString(fail)).build());
|
||||
}
|
||||
|
||||
private void createStack(List<Parameter> parameters) throws InterruptedException {
|
||||
stackId = cfn.createStack(r -> r.stackName(stackName).templateBody(TEMPLATE).parameters(parameters)).stackId();
|
||||
awaitStatus("CREATE_COMPLETE");
|
||||
}
|
||||
|
||||
private void updateStack(List<Parameter> parameters, String expected) throws InterruptedException {
|
||||
cfn.updateStack(r -> r.stackName(stackName).templateBody(TEMPLATE).parameters(parameters));
|
||||
awaitStatus(expected);
|
||||
}
|
||||
|
||||
private void assertIdentity(String providerName) {
|
||||
assertThat(cfn.describeStacks(r -> r.stackName(stackId)).stacks().get(0).outputs())
|
||||
.filteredOn(o -> "ProviderRef".equals(o.outputKey())).extracting(Output::outputValue)
|
||||
.as("Ref is the bare ProviderName").containsExactly(providerName);
|
||||
assertThat(cfn.describeStackResource(r -> r.stackName(stackId).logicalResourceId("Idp"))
|
||||
.stackResourceDetail().physicalResourceId())
|
||||
.as("the physical id is the bare ProviderName").isEqualTo(providerName);
|
||||
}
|
||||
|
||||
private IdentityProviderType provider(String pool, String providerName) {
|
||||
return cognito.describeIdentityProvider(r -> r.userPoolId(pool).providerName(providerName)).identityProvider();
|
||||
}
|
||||
|
||||
private void assertProvider(String pool, String providerName, String clientId) {
|
||||
IdentityProviderType provider = provider(pool, providerName);
|
||||
assertThat(provider.userPoolId()).isEqualTo(pool);
|
||||
assertThat(provider.providerName()).isEqualTo(providerName);
|
||||
assertThat(provider.providerTypeAsString()).isEqualTo("OIDC");
|
||||
assertThat(provider.providerDetails()).containsEntry("client_id", clientId);
|
||||
assertThat(provider.attributeMapping()).containsEntry("email", "email");
|
||||
}
|
||||
|
||||
private void assertProviderNotFound(String pool, String providerName) {
|
||||
assertThatThrownBy(() -> provider(pool, providerName)).isInstanceOf(ResourceNotFoundException.class);
|
||||
}
|
||||
|
||||
private List<String> providerNames(String pool) {
|
||||
return cognito.listIdentityProvidersPaginator(r -> r.userPoolId(pool)).providers().stream()
|
||||
.map(ProviderDescription::providerName).sorted().toList();
|
||||
}
|
||||
|
||||
private void awaitStatus(String expected) throws InterruptedException {
|
||||
CloudFormationStackTestHelper.awaitStatus(cfn, stackId, stackName, expected);
|
||||
}
|
||||
|
||||
private void deleteStack() throws InterruptedException {
|
||||
CloudFormationStackTestHelper.deleteStack(cfn, stackId, stackName);
|
||||
stackId = null;
|
||||
}
|
||||
}
|
||||
+2
-49
@@ -15,14 +15,12 @@ import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
|
||||
import software.amazon.awssdk.services.cloudformation.model.CloudFormationException;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Output;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Parameter;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Stack;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.model.ResourceNotFoundException;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.model.ResourceServerScopeType;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.model.ResourceServerType;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
@@ -35,8 +33,6 @@ import static org.assertj.core.api.Assertions.tuple;
|
||||
@DisplayName("CloudFormation AWS::Cognito::UserPoolResourceServer")
|
||||
class CloudFormationCognitoResourceServerTest {
|
||||
|
||||
private static final long TIMEOUT_NANOS = 300_000_000_000L;
|
||||
|
||||
private static final String TEMPLATE = """
|
||||
{
|
||||
"Parameters": {
|
||||
@@ -435,54 +431,11 @@ class CloudFormationCognitoResourceServerTest {
|
||||
}
|
||||
|
||||
private void awaitStatus(String expected) throws InterruptedException {
|
||||
TestFixtures.await(() -> {
|
||||
Stack stack = cfn.describeStacks(r -> r.stackName(stackId)).stacks().get(0);
|
||||
String status = stack.stackStatusAsString();
|
||||
if (expected.equals(status)) {
|
||||
return true;
|
||||
}
|
||||
if (!status.endsWith("_IN_PROGRESS") && (status.contains("FAILED") || status.contains("ROLLBACK"))) {
|
||||
throw new AssertionError(stackName + " reached " + status + " instead of " + expected + ": "
|
||||
+ stack.stackStatusReason() + failedEvents());
|
||||
}
|
||||
return false;
|
||||
}, stackName, expected, TIMEOUT_NANOS, TestFixtures.isRealAws() ? 2_000 : 100);
|
||||
}
|
||||
|
||||
private String failedEvents() {
|
||||
return cfn.describeStackEvents(r -> r.stackName(stackId)).stackEvents().stream()
|
||||
.filter(event -> event.resourceStatusAsString().endsWith("_FAILED"))
|
||||
.map(event -> event.logicalResourceId() + " " + event.resourceStatusAsString() + ": "
|
||||
+ event.resourceStatusReason())
|
||||
.collect(Collectors.joining("; ", " [", "]"));
|
||||
CloudFormationStackTestHelper.awaitStatus(cfn, stackId, stackName, expected);
|
||||
}
|
||||
|
||||
private void deleteStack() throws InterruptedException {
|
||||
if (stackId == null) {
|
||||
return;
|
||||
}
|
||||
cfn.deleteStack(r -> r.stackName(stackId));
|
||||
TestFixtures.await(() -> {
|
||||
try {
|
||||
List<Stack> stacks = cfn.describeStacks(r -> r.stackName(stackId)).stacks();
|
||||
if (stacks.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
Stack stack = stacks.get(0);
|
||||
if ("DELETE_FAILED".equals(stack.stackStatusAsString())) {
|
||||
throw new AssertionError(stackName + " deletion failed: " + stack.stackStatusReason());
|
||||
}
|
||||
return "DELETE_COMPLETE".equals(stack.stackStatusAsString());
|
||||
} catch (CloudFormationException e) {
|
||||
if ("ValidationError".equals(e.awsErrorDetails().errorCode())
|
||||
&& e.getMessage().contains("does not exist")) {
|
||||
return true;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}, stackName, "stack deletion", TIMEOUT_NANOS, TestFixtures.isRealAws() ? 2_000 : 100);
|
||||
CloudFormationStackTestHelper.deleteStack(cfn, stackId, stackName);
|
||||
stackId = null;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package com.floci.test;
|
||||
|
||||
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
|
||||
import software.amazon.awssdk.services.cloudformation.model.CloudFormationException;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Stack;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/** Stack waits shared by the CloudFormation tests that drive one stack through create, update and delete. */
|
||||
final class CloudFormationStackTestHelper {
|
||||
|
||||
private static final long TIMEOUT_NANOS = 300_000_000_000L;
|
||||
|
||||
private CloudFormationStackTestHelper() {
|
||||
}
|
||||
|
||||
/** Waits for {@code expected}, failing fast with the failed events when the stack settles anywhere else. */
|
||||
static void awaitStatus(CloudFormationClient cfn, String stackId, String stackName, String expected)
|
||||
throws InterruptedException {
|
||||
TestFixtures.await(() -> {
|
||||
Stack stack = cfn.describeStacks(r -> r.stackName(stackId)).stacks().get(0);
|
||||
String status = stack.stackStatusAsString();
|
||||
if (expected.equals(status)) {
|
||||
return true;
|
||||
}
|
||||
if (!status.endsWith("_IN_PROGRESS") && (status.contains("FAILED") || status.contains("ROLLBACK"))) {
|
||||
throw new AssertionError(stackName + " reached " + status + " instead of " + expected + ": "
|
||||
+ stack.stackStatusReason() + failedEvents(cfn, stackId));
|
||||
}
|
||||
return false;
|
||||
}, stackName, expected, TIMEOUT_NANOS, pollMillis());
|
||||
}
|
||||
|
||||
/** Deletes the stack and waits until it is gone; a null {@code stackId} means none was created. */
|
||||
static void deleteStack(CloudFormationClient cfn, String stackId, String stackName) throws InterruptedException {
|
||||
if (stackId == null) {
|
||||
return;
|
||||
}
|
||||
cfn.deleteStack(r -> r.stackName(stackId));
|
||||
TestFixtures.await(() -> {
|
||||
try {
|
||||
List<Stack> stacks = cfn.describeStacks(r -> r.stackName(stackId)).stacks();
|
||||
if (stacks.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
Stack stack = stacks.get(0);
|
||||
if ("DELETE_FAILED".equals(stack.stackStatusAsString())) {
|
||||
throw new AssertionError(stackName + " deletion failed: " + stack.stackStatusReason());
|
||||
}
|
||||
return "DELETE_COMPLETE".equals(stack.stackStatusAsString());
|
||||
} catch (CloudFormationException e) {
|
||||
if ("ValidationError".equals(e.awsErrorDetails().errorCode())
|
||||
&& e.getMessage().contains("does not exist")) {
|
||||
return true;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}, stackName, "stack deletion", TIMEOUT_NANOS, pollMillis());
|
||||
}
|
||||
|
||||
private static String failedEvents(CloudFormationClient cfn, String stackId) {
|
||||
return cfn.describeStackEvents(r -> r.stackName(stackId)).stackEvents().stream()
|
||||
.filter(event -> event.resourceStatusAsString().endsWith("_FAILED"))
|
||||
.map(event -> event.logicalResourceId() + " " + event.resourceStatusAsString() + ": "
|
||||
+ event.resourceStatusReason())
|
||||
.collect(Collectors.joining("; ", " [", "]"));
|
||||
}
|
||||
|
||||
private static long pollMillis() {
|
||||
return TestFixtures.isRealAws() ? 2_000 : 100;
|
||||
}
|
||||
}
|
||||
@@ -203,7 +203,7 @@ cross-resource references.
|
||||
| CodePipeline | `Pipeline`, `CustomActionType`, `Webhook` |
|
||||
| CodeBuild | `Project` |
|
||||
| Batch | `ComputeEnvironment`, `JobQueue`, `JobDefinition` |
|
||||
| Cognito | `UserPool` (`ProviderURL` is the local issuer of the tokens Floci mints, `<base-url>/<pool id>`; `EnabledMfas` is applied with `SetUserPoolMfaConfig`, as on AWS, and once `SMS_MFA` is on only `MfaConfiguration: OFF` turns it off), `UserPoolClient`, `UserPoolDomain`, `UserPoolGroup`, `UserPoolResourceServer`, `UserPoolUser`, `UserPoolUserToGroupAttachment` |
|
||||
| Cognito | `UserPool` (`ProviderURL` is the local issuer of the tokens Floci mints, `<base-url>/<pool id>`; `EnabledMfas` is applied with `SetUserPoolMfaConfig`, as on AWS, and once `SMS_MFA` is on only `MfaConfiguration: OFF` turns it off), `UserPoolClient`, `UserPoolDomain`, `UserPoolGroup`, `UserPoolIdentityProvider` (Ref returns the ProviderName; changing only `ProviderType` is refused, as on AWS, because the name is always the template's and the replacement would need the same address), `UserPoolResourceServer`, `UserPoolUser`, `UserPoolUserToGroupAttachment` |
|
||||
| ACM | `Certificate` |
|
||||
| EventBridge | `Rule`, `EventBus`, `EventBusPolicy`, `ApiDestination`, `Archive` (`KmsKeyIdentifier` is ignored) |
|
||||
| EventBridge Scheduler | `Schedule`, `ScheduleGroup` |
|
||||
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoPoolScopedLifecycle.Identity;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoPoolScopedLifecycle.Prior;
|
||||
import io.github.hectorvent.floci.services.cognito.CognitoService;
|
||||
import io.github.hectorvent.floci.services.cognito.model.IdentityProvider;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Provisions {@code AWS::Cognito::UserPoolIdentityProvider}. {@code Ref} is the bare
|
||||
* {@code ProviderName}, while the provider is addressed by its pool and name, so the stack
|
||||
* lifecycle is {@link CognitoPoolScopedLifecycle}'s. {@code ProviderDetails}, {@code AttributeMapping}
|
||||
* and {@code IdpIdentifiers} update in place and roll back from a snapshot. A change to
|
||||
* {@code UserPoolId} or {@code ProviderName} replaces the provider. {@code ProviderType} is
|
||||
* create-only too, but the name is always the template's, so changing only the type would need a
|
||||
* replacement at the same address, which, as on AWS, is refused before anything is changed.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class CognitoIdentityProviderCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
private static final String TYPE = "AWS::Cognito::UserPoolIdentityProvider";
|
||||
|
||||
private final CognitoService cognitoService;
|
||||
private final CognitoPoolScopedLifecycle lifecycle;
|
||||
|
||||
@Inject
|
||||
public CognitoIdentityProviderCfnProvisioner(CognitoService cognitoService) {
|
||||
this.cognitoService = cognitoService;
|
||||
this.lifecycle = new CognitoPoolScopedLifecycle("identity provider", "__FlociIdentityProviderPoolId",
|
||||
"__FlociIdentityProviderUpdate", "providerName",
|
||||
identity -> cognitoService.deleteIdentityProvider(identity.poolId(), identity.name()),
|
||||
this::restore);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> resourceTypes() {
|
||||
return Set.of(TYPE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void provision(StackResource resource, JsonNode properties, ProvisionContext ctx) {
|
||||
String poolId = required(ctx.resolveOptional(properties, "UserPoolId"), "UserPoolId");
|
||||
String providerName = required(ctx.resolveOptional(properties, "ProviderName"), "ProviderName");
|
||||
String providerType = required(ctx.resolveOptional(properties, "ProviderType"), "ProviderType");
|
||||
validateString(poolId, "UserPoolId", 55, "[\\w-]+_[0-9a-zA-Z]+");
|
||||
validateString(providerName, "ProviderName", 32,
|
||||
"[^_\\p{Z}][\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}][^_\\p{Z}]+");
|
||||
if (!CognitoService.PROVIDER_TYPES.contains(providerType)) {
|
||||
throw new AwsException("ValidationError", TYPE + " has invalid ProviderType", 400);
|
||||
}
|
||||
Map<String, String> providerDetails = stringMap(properties, "ProviderDetails", ctx);
|
||||
if (providerDetails == null) {
|
||||
throw new AwsException("ValidationError", TYPE + " requires ProviderDetails", 400);
|
||||
}
|
||||
Map<String, String> attributeMapping = stringMap(properties, "AttributeMapping", ctx);
|
||||
List<String> idpIdentifiers = idpIdentifiers(properties, ctx);
|
||||
|
||||
lifecycle.beginUpdate(resource, ctx);
|
||||
Prior prior = lifecycle.prior(resource, ctx);
|
||||
Identity current = prior.identity();
|
||||
boolean replacement = current != null
|
||||
&& (!current.poolId().equals(poolId) || !current.name().equals(providerName));
|
||||
Identity target = current;
|
||||
if (current == null || replacement) {
|
||||
cognitoService.createIdentityProvider(poolId, providerName, providerType, providerDetails,
|
||||
attributeMapping, idpIdentifiers);
|
||||
target = new Identity(poolId, providerName);
|
||||
} else {
|
||||
IdentityProvider existing = cognitoService.describeIdentityProvider(current.poolId(), current.name());
|
||||
if (!providerType.equals(existing.getProviderType())) {
|
||||
throw new AwsException("ValidationError",
|
||||
"CloudFormation cannot update a stack when a custom-named resource requires "
|
||||
+ "replacing. Rename " + providerName + " and update the stack again.", 400);
|
||||
}
|
||||
ObjectNode snapshot = lifecycle.snapshot(current);
|
||||
snapshot.set("providerDetails", CognitoPoolScopedLifecycle.MAPPER.valueToTree(existing.getProviderDetails()));
|
||||
snapshot.set("attributeMapping",
|
||||
CognitoPoolScopedLifecycle.MAPPER.valueToTree(existing.getAttributeMapping()));
|
||||
snapshot.set("idpIdentifiers", CognitoPoolScopedLifecycle.MAPPER.valueToTree(existing.getIdpIdentifiers()));
|
||||
lifecycle.saveSnapshot(resource, snapshot);
|
||||
cognitoService.updateIdentityProvider(poolId, providerName, providerDetails, attributeMapping,
|
||||
idpIdentifiers);
|
||||
}
|
||||
lifecycle.commit(resource, ctx, prior, target);
|
||||
}
|
||||
|
||||
/** Puts every in-place member back explicitly, so a value the update cleared returns too. */
|
||||
private void restore(Identity identity, ObjectNode snapshot) {
|
||||
cognitoService.updateIdentityProvider(identity.poolId(), identity.name(),
|
||||
snapshotMap(snapshot.path("providerDetails")), snapshotMap(snapshot.path("attributeMapping")),
|
||||
snapshotList(snapshot.path("idpIdentifiers")));
|
||||
}
|
||||
|
||||
private static String required(String value, String property) {
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new AwsException("ValidationError", TYPE + " requires " + property, 400);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static void validateString(String value, String property, int maximum, String pattern) {
|
||||
if (value.length() > maximum || !value.matches(pattern)) {
|
||||
throw new AwsException("ValidationError", TYPE + " has invalid " + property, 400);
|
||||
}
|
||||
}
|
||||
|
||||
/** A map-of-strings property, or null when it is absent or resolves to {@code AWS::NoValue}. */
|
||||
private static Map<String, String> stringMap(JsonNode properties, String property, ProvisionContext ctx) {
|
||||
if (properties == null || !properties.has(property) || properties.get(property).isNull()) {
|
||||
return null;
|
||||
}
|
||||
JsonNode resolved = ctx.engine().resolveNodeOmittingNoValue(properties.get(property));
|
||||
if (resolved != null && resolved.isMissingNode()) {
|
||||
return null;
|
||||
}
|
||||
if (resolved == null || !resolved.isObject()) {
|
||||
throw new AwsException("ValidationError", TYPE + " " + property + " must be a map of strings", 400);
|
||||
}
|
||||
Map<String, String> values = new LinkedHashMap<>();
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = resolved.fields();
|
||||
while (fields.hasNext()) {
|
||||
Map.Entry<String, JsonNode> field = fields.next();
|
||||
if (!field.getValue().isValueNode() || field.getValue().isNull()) {
|
||||
throw new AwsException("ValidationError", TYPE + " " + property + " must be a map of strings", 400);
|
||||
}
|
||||
values.put(field.getKey(), field.getValue().asText());
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
/** The template's identifiers, or null when it declares none, so an update keeps the stored ones. */
|
||||
private static List<String> idpIdentifiers(JsonNode properties, ProvisionContext ctx) {
|
||||
if (properties == null || !properties.has("IdpIdentifiers") || properties.get("IdpIdentifiers").isNull()) {
|
||||
return null;
|
||||
}
|
||||
List<String> identifiers = ctx.resolveStringList(properties, "IdpIdentifiers");
|
||||
if (identifiers.size() > 50) {
|
||||
throw new AwsException("ValidationError", TYPE + " allows at most 50 IdpIdentifiers", 400);
|
||||
}
|
||||
return identifiers;
|
||||
}
|
||||
|
||||
private static Map<String, String> snapshotMap(JsonNode node) {
|
||||
Map<String, String> values = new LinkedHashMap<>();
|
||||
node.fields().forEachRemaining(field -> values.put(field.getKey(), field.getValue().asText()));
|
||||
return values;
|
||||
}
|
||||
|
||||
private static List<String> snapshotList(JsonNode node) {
|
||||
List<String> values = new ArrayList<>();
|
||||
node.forEach(value -> values.add(value.asText()));
|
||||
return values;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(StackResource resource, String region) {
|
||||
lifecycle.delete(resource, region);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean rollbackUpdate(StackResource resource) {
|
||||
return lifecycle.rollbackUpdate(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasReplacementUpdate(StackResource resource) {
|
||||
return lifecycle.hasReplacementUpdate(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean retainsFailedUpdateState(StackResource resource) {
|
||||
return lifecycle.retainsFailedUpdateState(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String updateCleanupPhysicalId(StackResource resource) {
|
||||
return lifecycle.updateCleanupPhysicalId(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateCleanupResult completeUpdate(StackResource resource) {
|
||||
return lifecycle.completeUpdate(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateCleanupResult completeDeleteCleanup(StackResource resource) {
|
||||
return lifecycle.completeDeleteCleanup(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearDeleteCleanup(StackResource resource) {
|
||||
lifecycle.clearDeleteCleanup(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearUpdate(StackResource resource) {
|
||||
lifecycle.clearUpdate(resource);
|
||||
}
|
||||
}
|
||||
+370
@@ -0,0 +1,370 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* Stack lifecycle shared by the Cognito types whose {@code Ref} is a bare name within a user pool,
|
||||
* while Cognito addresses them by pool and name: {@code AWS::Cognito::UserPoolResourceServer} and
|
||||
* {@code AWS::Cognito::UserPoolIdentityProvider}.
|
||||
*
|
||||
* <p>The pool lives in an attribute next to the bare physical id. Every lifecycle record works on a
|
||||
* detached projection whose physical id is the encoded {@code [poolId, name]} pair, so
|
||||
* {@link ReplacementCleanup} can delete a displaced entity from its own pool; no encoded id is ever
|
||||
* assigned to the stack resource or passed to the template engine. An in-place update keeps a
|
||||
* snapshot, written by the provisioner and put back by its {@link SnapshotRestorer}, so a failed
|
||||
* update rolls back.
|
||||
*/
|
||||
final class CognitoPoolScopedLifecycle {
|
||||
|
||||
static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
/** A pool-scoped entity's address. */
|
||||
record Identity(String poolId, String name) {
|
||||
}
|
||||
|
||||
/** What an update found on the resource before provisioning it. */
|
||||
record Prior(String physicalId, boolean stub, Identity identity) {
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
interface EntityDeleter {
|
||||
void delete(Identity identity);
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
interface SnapshotRestorer {
|
||||
void restore(Identity identity, ObjectNode snapshot);
|
||||
}
|
||||
|
||||
private final String label;
|
||||
private final String poolAttr;
|
||||
private final String updateAttr;
|
||||
private final String snapshotNameKey;
|
||||
private final EntityDeleter deleter;
|
||||
private final SnapshotRestorer restorer;
|
||||
|
||||
/**
|
||||
* @param label the entity's name in messages, lower case (for example {@code "resource server"})
|
||||
* @param poolAttr the attribute holding the owning pool id
|
||||
* @param updateAttr the attribute holding an in-place update's snapshot
|
||||
* @param snapshotNameKey the snapshot field naming the entity next to {@code poolId}
|
||||
*/
|
||||
CognitoPoolScopedLifecycle(String label, String poolAttr, String updateAttr, String snapshotNameKey,
|
||||
EntityDeleter deleter, SnapshotRestorer restorer) {
|
||||
this.label = label;
|
||||
this.poolAttr = poolAttr;
|
||||
this.updateAttr = updateAttr;
|
||||
this.snapshotNameKey = snapshotNameKey;
|
||||
this.deleter = deleter;
|
||||
this.restorer = restorer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens an update: ends the previous rollback's retry window and finishes a rollback the last
|
||||
* attempt left pending, so its snapshot or cleanup identity is not overwritten.
|
||||
*/
|
||||
void beginUpdate(StackResource resource, ProvisionContext ctx) {
|
||||
if (!ctx.isUpdate()) {
|
||||
return;
|
||||
}
|
||||
// Rolling this update back undoes it alone; only ContinueUpdateRollback retries the
|
||||
// delete the last rollback could not make.
|
||||
ReplacementCleanup.endRollbackRetry(resource);
|
||||
if (retainsFailedUpdateState(resource)) {
|
||||
try {
|
||||
rollbackUpdate(resource);
|
||||
resource.getAttributes().remove(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR);
|
||||
resource.getAttributes().remove(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR);
|
||||
} catch (RuntimeException failure) {
|
||||
resource.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, failure.getMessage());
|
||||
throw new IllegalStateException("Could not finish the previous " + label + " update rollback",
|
||||
failure);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The resource's address before this provision: none on a create or a dispatcher stub. */
|
||||
Prior prior(StackResource resource, ProvisionContext ctx) {
|
||||
String priorPhysicalId = ctx.isUpdate() ? resource.getPhysicalId() : null;
|
||||
boolean priorIsStub = ctx.isUpdate()
|
||||
&& CfnResourceDispatcher.isStub(priorPhysicalId, resource.getAttributes());
|
||||
Identity identity = ctx.isUpdate() && !priorIsStub ? identity(resource, priorPhysicalId) : null;
|
||||
return new Prior(priorPhysicalId, priorIsStub, identity);
|
||||
}
|
||||
|
||||
/** A snapshot holding the address, for the provisioner to add its in-place configuration to. */
|
||||
ObjectNode snapshot(Identity identity) {
|
||||
return MAPPER.createObjectNode().put("poolId", identity.poolId()).put(snapshotNameKey, identity.name());
|
||||
}
|
||||
|
||||
void saveSnapshot(StackResource resource, ObjectNode snapshot) {
|
||||
resource.getAttributes().put(updateAttr, snapshot.toString());
|
||||
}
|
||||
|
||||
/** Assigns {@code target} to the resource and records what an update displaced or must roll back. */
|
||||
void commit(StackResource resource, ProvisionContext ctx, Prior prior, Identity target) {
|
||||
Map<String, String> attributesBefore = new HashMap<>(resource.getAttributes());
|
||||
setIdentity(resource, target);
|
||||
if (prior.stub()) {
|
||||
resource.getAttributes().remove("Arn");
|
||||
}
|
||||
String cleanupPrior = prior.stub() ? prior.physicalId()
|
||||
: prior.identity() == null ? null : encode(prior.identity());
|
||||
ProvisionContext cleanupContext = new ProvisionContext(ctx.engine(), ctx.region(), ctx.accountId(),
|
||||
ctx.stackName(), cleanupPrior, ctx.progress(), ctx.priorProperties());
|
||||
withProjection(resource, projected -> {
|
||||
ReplacementCleanup.record(projected, cleanupContext, attributesBefore);
|
||||
return null;
|
||||
});
|
||||
resource.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
|
||||
}
|
||||
|
||||
private Identity identity(StackResource resource, String name) {
|
||||
String poolId = resource.getAttributes().get(poolAttr);
|
||||
if (poolId == null || poolId.isBlank() || name == null || name.isBlank()) {
|
||||
throw new IllegalStateException("Missing Cognito " + label + " identity for " + resource.getLogicalId());
|
||||
}
|
||||
return new Identity(poolId, name);
|
||||
}
|
||||
|
||||
private void setIdentity(StackResource resource, Identity identity) {
|
||||
resource.setPhysicalId(identity.name());
|
||||
resource.getAttributes().put(poolAttr, identity.poolId());
|
||||
}
|
||||
|
||||
private static String encode(Identity identity) {
|
||||
return MAPPER.createArrayNode().add(identity.poolId()).add(identity.name()).toString();
|
||||
}
|
||||
|
||||
private Identity decode(String physicalId) {
|
||||
try {
|
||||
JsonNode address = MAPPER.readTree(physicalId);
|
||||
if (address != null && address.isArray() && address.size() == 2
|
||||
&& address.get(0).isTextual() && !address.get(0).asText().isBlank()
|
||||
&& address.get(1).isTextual() && !address.get(1).asText().isBlank()) {
|
||||
return new Identity(address.get(0).asText(), address.get(1).asText());
|
||||
}
|
||||
} catch (JsonProcessingException invalid) {
|
||||
throw new IllegalStateException("Invalid Cognito " + label + " cleanup address", invalid);
|
||||
}
|
||||
throw new IllegalStateException("Invalid Cognito " + label + " cleanup address");
|
||||
}
|
||||
|
||||
/*
|
||||
* Ref is only the name, whereas the entity's delete address also includes its pool.
|
||||
* Only this detached view gives ReplacementCleanup the full address.
|
||||
*/
|
||||
private StackResource project(StackResource resource) {
|
||||
StackResource projected = new StackResource();
|
||||
projected.setLogicalId(resource.getLogicalId());
|
||||
projected.setResourceType(resource.getResourceType());
|
||||
projected.setStatus(resource.getStatus());
|
||||
projected.setDeletionPolicy(resource.getDeletionPolicy());
|
||||
projected.setUpdateReplacePolicy(resource.getUpdateReplacePolicy());
|
||||
projected.setAttributes(new HashMap<>(resource.getAttributes()));
|
||||
if (resource.getPhysicalId() != null) {
|
||||
projected.setPhysicalId(CfnResourceDispatcher.isStub(resource.getPhysicalId(), resource.getAttributes())
|
||||
? resource.getPhysicalId() : encode(identity(resource, resource.getPhysicalId())));
|
||||
}
|
||||
validateCleanup(projected);
|
||||
return projected;
|
||||
}
|
||||
|
||||
private <T> T withProjection(StackResource resource, Function<StackResource, T> operation) {
|
||||
StackResource projected = project(resource);
|
||||
try {
|
||||
return operation.apply(projected);
|
||||
} finally {
|
||||
// Rollback restores the prior identity before deleting the replacement, even if that delete fails.
|
||||
boolean restoredStub = CfnResourceDispatcher.isStub(projected.getPhysicalId(), projected.getAttributes());
|
||||
Identity restored = projected.getPhysicalId() == null || restoredStub
|
||||
? null : decode(projected.getPhysicalId());
|
||||
resource.getAttributes().clear();
|
||||
resource.getAttributes().putAll(projected.getAttributes());
|
||||
if (restoredStub) {
|
||||
resource.setPhysicalId(projected.getPhysicalId());
|
||||
resource.getAttributes().remove(poolAttr);
|
||||
} else if (restored != null) {
|
||||
setIdentity(resource, restored);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void requireIdentity(Identity identity) {
|
||||
if (identity.poolId().isBlank() || identity.name().isBlank()) {
|
||||
throw new IllegalStateException("Invalid Cognito " + label + " lifecycle identity");
|
||||
}
|
||||
}
|
||||
|
||||
private void validateCleanup(StackResource projected) {
|
||||
ObjectNode cleanup = read(projected, CfnRollback.REPLACEMENT_CLEANUP_ATTR);
|
||||
if (cleanup == null) {
|
||||
return;
|
||||
}
|
||||
if (cleanup.has("displaced") && !cleanup.path("displaced").isArray()) {
|
||||
throw new IllegalStateException("Invalid Cognito " + label + " cleanup entries");
|
||||
}
|
||||
for (JsonNode entry : cleanup.path("displaced")) {
|
||||
if (!entry.isObject() || !entry.path("physicalId").isTextual()
|
||||
|| entry.path("cleanupAttempts").asInt(0) < 0) {
|
||||
throw new IllegalStateException("Invalid Cognito " + label + " cleanup entry");
|
||||
}
|
||||
decode(entry.path("physicalId").asText());
|
||||
}
|
||||
if (cleanup.hasNonNull("priorPhysicalId")) {
|
||||
if (!cleanup.path("priorAttributes").isObject()) {
|
||||
throw new IllegalStateException("Invalid Cognito " + label + " rollback attributes");
|
||||
}
|
||||
Map<String, String> priorAttributes = new HashMap<>();
|
||||
cleanup.path("priorAttributes").fields()
|
||||
.forEachRemaining(entry -> priorAttributes.put(entry.getKey(), entry.getValue().asText()));
|
||||
String priorPhysicalId = cleanup.path("priorPhysicalId").asText();
|
||||
if (!CfnResourceDispatcher.isStub(priorPhysicalId, priorAttributes)) {
|
||||
decode(priorPhysicalId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteAddress(String resourceType, String physicalId, String region) {
|
||||
Identity identity = decode(physicalId);
|
||||
CfnDeletes.safeDelete("Cognito " + label, identity.name(), () -> deleter.delete(identity),
|
||||
"ResourceNotFoundException");
|
||||
}
|
||||
|
||||
void delete(StackResource resource, String region) {
|
||||
withProjection(resource, projected -> {
|
||||
if (projected.getPhysicalId() != null
|
||||
&& !CfnResourceDispatcher.isStub(projected.getPhysicalId(), projected.getAttributes())) {
|
||||
deleteAddress(projected.getResourceType(), projected.getPhysicalId(), region);
|
||||
}
|
||||
projected.getAttributes().remove(updateAttr);
|
||||
projected.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR);
|
||||
ReplacementCleanup.clear(projected);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
boolean rollbackUpdate(StackResource resource) {
|
||||
return withProjection(resource, projected -> {
|
||||
if (ReplacementCleanup.rollback(projected, this::deleteAddress)) {
|
||||
return true;
|
||||
}
|
||||
ObjectNode snapshot = read(projected, updateAttr);
|
||||
if (snapshot == null) {
|
||||
return false;
|
||||
}
|
||||
Identity prior = new Identity(snapshot.path("poolId").asText(), snapshot.path(snapshotNameKey).asText());
|
||||
requireIdentity(prior);
|
||||
restorer.restore(prior, snapshot);
|
||||
projected.setPhysicalId(encode(prior));
|
||||
projected.getAttributes().remove(updateAttr);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
boolean hasReplacementUpdate(StackResource resource) {
|
||||
return withProjection(resource, ReplacementCleanup::hasReplacement);
|
||||
}
|
||||
|
||||
private boolean hasPendingRollback(StackResource projected) {
|
||||
ObjectNode cleanup = read(projected, CfnRollback.REPLACEMENT_CLEANUP_ATTR);
|
||||
return projected.getAttributes().containsKey(updateAttr)
|
||||
|| (cleanup != null && cleanup.hasNonNull("priorPhysicalId"));
|
||||
}
|
||||
|
||||
boolean retainsFailedUpdateState(StackResource resource) {
|
||||
return withProjection(resource, this::hasPendingRollback);
|
||||
}
|
||||
|
||||
String updateCleanupPhysicalId(StackResource resource) {
|
||||
return withProjection(resource, projected -> {
|
||||
String physicalId = ReplacementCleanup.cleanupPhysicalId(projected);
|
||||
return physicalId == null ? null : decode(physicalId).name();
|
||||
});
|
||||
}
|
||||
|
||||
private UpdateCleanupResult publicResult(UpdateCleanupResult result) {
|
||||
String physicalId = result.previousPhysicalId();
|
||||
return new UpdateCleanupResult(result.applicable(), result.complete(),
|
||||
physicalId == null ? null : decode(physicalId).name(),
|
||||
result.attempts(), result.failureReason());
|
||||
}
|
||||
|
||||
UpdateCleanupResult completeUpdate(StackResource resource) {
|
||||
return withProjection(resource, projected -> {
|
||||
if ("UPDATE_FAILED".equals(projected.getStatus()) && hasPendingRollback(projected)) {
|
||||
throw new IllegalStateException(Character.toUpperCase(label.charAt(0)) + label.substring(1)
|
||||
+ " rollback is still pending; its original configuration cannot be discarded by "
|
||||
+ "another resource's update cleanup");
|
||||
}
|
||||
boolean updated = projected.getAttributes().remove(updateAttr) != null;
|
||||
ObjectNode committed = read(projected, CfnRollback.REPLACEMENT_CLEANUP_ATTR);
|
||||
if (committed != null) {
|
||||
// Committing the update spends its rollback identity, independently of delete retry debt.
|
||||
committed.remove("priorPhysicalId");
|
||||
committed.remove("priorAttributes");
|
||||
projected.getAttributes().put(CfnRollback.REPLACEMENT_CLEANUP_ATTR, committed.toString());
|
||||
}
|
||||
UpdateCleanupResult cleanup = ReplacementCleanup.complete(projected, this::deleteAddress);
|
||||
return !cleanup.applicable() && updated
|
||||
? new UpdateCleanupResult(true, true, null, 0, null) : publicResult(cleanup);
|
||||
});
|
||||
}
|
||||
|
||||
UpdateCleanupResult completeDeleteCleanup(StackResource resource) {
|
||||
return withProjection(resource, projected -> publicResult(ReplacementCleanup.complete(projected,
|
||||
this::deleteAddress)));
|
||||
}
|
||||
|
||||
void clearDeleteCleanup(StackResource resource) {
|
||||
withProjection(resource, projected -> {
|
||||
ObjectNode cleanup = read(projected, CfnRollback.REPLACEMENT_CLEANUP_ATTR);
|
||||
JsonNode prior = cleanup == null ? null : cleanup.get("priorPhysicalId");
|
||||
JsonNode attributes = cleanup == null ? null : cleanup.get("priorAttributes");
|
||||
ReplacementCleanup.clear(projected);
|
||||
if (prior != null) {
|
||||
ObjectNode remaining = read(projected, CfnRollback.REPLACEMENT_CLEANUP_ATTR);
|
||||
if (remaining == null) {
|
||||
remaining = MAPPER.createObjectNode();
|
||||
remaining.putArray("displaced");
|
||||
}
|
||||
remaining.set("priorPhysicalId", prior);
|
||||
remaining.set("priorAttributes", attributes);
|
||||
projected.getAttributes().put(CfnRollback.REPLACEMENT_CLEANUP_ATTR, remaining.toString());
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
void clearUpdate(StackResource resource) {
|
||||
withProjection(resource, projected -> {
|
||||
projected.getAttributes().remove(updateAttr);
|
||||
ReplacementCleanup.clear(projected);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private ObjectNode read(StackResource resource, String attribute) {
|
||||
String raw = resource.getAttributes().get(attribute);
|
||||
if (raw == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
JsonNode node = MAPPER.readTree(raw);
|
||||
if (node instanceof ObjectNode object) {
|
||||
return object;
|
||||
}
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException("Invalid Cognito " + label + " lifecycle record", e);
|
||||
}
|
||||
throw new IllegalStateException("Invalid Cognito " + label + " lifecycle record");
|
||||
}
|
||||
}
|
||||
+45
-294
@@ -1,11 +1,11 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoPoolScopedLifecycle.Identity;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoPoolScopedLifecycle.Prior;
|
||||
import io.github.hectorvent.floci.services.cognito.CognitoService;
|
||||
import io.github.hectorvent.floci.services.cognito.model.ResourceServer;
|
||||
import io.github.hectorvent.floci.services.cognito.model.ResourceServerScope;
|
||||
@@ -13,25 +13,24 @@ import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
|
||||
@ApplicationScoped
|
||||
public class CognitoResourceServerCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
private static final String TYPE = "AWS::Cognito::UserPoolResourceServer";
|
||||
private static final String POOL_ATTR = "__FlociResourceServerPoolId";
|
||||
private static final String UPDATE_ATTR = "__FlociResourceServerUpdate";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private final CognitoService cognitoService;
|
||||
private final CognitoPoolScopedLifecycle lifecycle;
|
||||
|
||||
@Inject
|
||||
public CognitoResourceServerCfnProvisioner(CognitoService cognitoService) {
|
||||
this.cognitoService = cognitoService;
|
||||
this.lifecycle = new CognitoPoolScopedLifecycle("resource server", "__FlociResourceServerPoolId",
|
||||
"__FlociResourceServerUpdate", "identifier",
|
||||
identity -> cognitoService.deleteResourceServer(identity.poolId(), identity.name()),
|
||||
this::restore);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -49,49 +48,29 @@ public class CognitoResourceServerCfnProvisioner implements CfnResourceProvision
|
||||
validateString(name, "Name", 256, "[\\w\\s+=,.@-]+");
|
||||
List<ResourceServerScope> scopes = scopes(properties, ctx);
|
||||
|
||||
if (ctx.isUpdate()) {
|
||||
// Rolling this update back undoes it alone; only ContinueUpdateRollback retries the
|
||||
// delete the last rollback could not make.
|
||||
ReplacementCleanup.endRollbackRetry(resource);
|
||||
}
|
||||
if (ctx.isUpdate() && retainsFailedUpdateState(resource)) {
|
||||
try {
|
||||
rollbackUpdate(resource);
|
||||
resource.getAttributes().remove(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR);
|
||||
resource.getAttributes().remove(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR);
|
||||
} catch (RuntimeException failure) {
|
||||
resource.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, failure.getMessage());
|
||||
throw new IllegalStateException("Could not finish the previous resource server update rollback", failure);
|
||||
}
|
||||
}
|
||||
String priorPhysicalId = ctx.isUpdate() ? resource.getPhysicalId() : null;
|
||||
boolean priorIsStub = ctx.isUpdate()
|
||||
&& CfnResourceDispatcher.isStub(priorPhysicalId, resource.getAttributes());
|
||||
Identity prior = ctx.isUpdate() && !priorIsStub ? identity(resource, priorPhysicalId) : null;
|
||||
boolean replacement = prior != null
|
||||
&& (!prior.poolId().equals(poolId) || !prior.identifier().equals(identifier));
|
||||
Identity target = prior;
|
||||
if (prior == null || replacement) {
|
||||
lifecycle.beginUpdate(resource, ctx);
|
||||
Prior prior = lifecycle.prior(resource, ctx);
|
||||
Identity current = prior.identity();
|
||||
boolean replacement = current != null
|
||||
&& (!current.poolId().equals(poolId) || !current.name().equals(identifier));
|
||||
Identity target = current;
|
||||
if (current == null || replacement) {
|
||||
cognitoService.createResourceServer(poolId, identifier, name, scopes);
|
||||
target = new Identity(poolId, identifier);
|
||||
} else {
|
||||
ResourceServer existing = cognitoService.describeResourceServer(prior.poolId(), prior.identifier());
|
||||
resource.getAttributes().put(UPDATE_ATTR, snapshot(prior, existing).toString());
|
||||
ResourceServer existing = cognitoService.describeResourceServer(current.poolId(), current.name());
|
||||
ObjectNode snapshot = lifecycle.snapshot(current);
|
||||
snapshot.put("name", existing.getName());
|
||||
snapshot.set("scopes", CognitoPoolScopedLifecycle.MAPPER.valueToTree(existing.getScopes()));
|
||||
lifecycle.saveSnapshot(resource, snapshot);
|
||||
cognitoService.updateResourceServer(poolId, identifier, name, scopes);
|
||||
}
|
||||
Map<String, String> attributesBefore = new HashMap<>(resource.getAttributes());
|
||||
setIdentity(resource, target);
|
||||
if (priorIsStub) {
|
||||
resource.getAttributes().remove("Arn");
|
||||
}
|
||||
ProvisionContext cleanupContext = new ProvisionContext(ctx.engine(), ctx.region(), ctx.accountId(),
|
||||
ctx.stackName(), priorIsStub ? priorPhysicalId : prior == null ? null : encode(prior),
|
||||
ctx.progress(), ctx.priorProperties());
|
||||
withProjection(resource, projected -> {
|
||||
ReplacementCleanup.record(projected, cleanupContext, attributesBefore);
|
||||
return null;
|
||||
});
|
||||
resource.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
|
||||
lifecycle.commit(resource, ctx, prior, target);
|
||||
}
|
||||
|
||||
private void restore(Identity identity, ObjectNode snapshot) {
|
||||
cognitoService.updateResourceServer(identity.poolId(), identity.name(), snapshot.path("name").asText(),
|
||||
scopes(snapshot.path("scopes")));
|
||||
}
|
||||
|
||||
private static String required(String value, String property) {
|
||||
@@ -131,6 +110,17 @@ public class CognitoResourceServerCfnProvisioner implements CfnResourceProvision
|
||||
return scopes;
|
||||
}
|
||||
|
||||
private static List<ResourceServerScope> scopes(JsonNode nodes) {
|
||||
List<ResourceServerScope> scopes = new ArrayList<>();
|
||||
for (JsonNode node : nodes) {
|
||||
ResourceServerScope scope = new ResourceServerScope();
|
||||
scope.setScopeName(node.path("scopeName").asText());
|
||||
scope.setScopeDescription(node.path("scopeDescription").asText(null));
|
||||
scopes.add(scope);
|
||||
}
|
||||
return scopes;
|
||||
}
|
||||
|
||||
private static void validateString(String value, String property, int maximum, String pattern) {
|
||||
if (value.length() > maximum || !value.matches(pattern)) {
|
||||
throw new AwsException("ValidationError", TYPE + " has invalid " + property, 400);
|
||||
@@ -145,287 +135,48 @@ public class CognitoResourceServerCfnProvisioner implements CfnResourceProvision
|
||||
return !value.isEmpty() && value.length() <= 256;
|
||||
}
|
||||
|
||||
private record Identity(String poolId, String identifier) {
|
||||
}
|
||||
|
||||
private static Identity identity(StackResource resource, String identifier) {
|
||||
String poolId = resource.getAttributes().get(POOL_ATTR);
|
||||
if (poolId == null || poolId.isBlank() || identifier == null || identifier.isBlank()) {
|
||||
throw new IllegalStateException("Missing Cognito resource server identity for " + resource.getLogicalId());
|
||||
}
|
||||
return new Identity(poolId, identifier);
|
||||
}
|
||||
|
||||
private static Identity identity(JsonNode node) {
|
||||
return new Identity(node.path("poolId").asText(), node.path("identifier").asText());
|
||||
}
|
||||
|
||||
private static void setIdentity(StackResource resource, Identity identity) {
|
||||
resource.setPhysicalId(identity.identifier());
|
||||
resource.getAttributes().put(POOL_ATTR, identity.poolId());
|
||||
}
|
||||
|
||||
private static ObjectNode address(Identity identity) {
|
||||
return MAPPER.createObjectNode().put("poolId", identity.poolId()).put("identifier", identity.identifier());
|
||||
}
|
||||
|
||||
private static ObjectNode snapshot(Identity identity, ResourceServer server) {
|
||||
ObjectNode snapshot = address(identity);
|
||||
snapshot.put("name", server.getName());
|
||||
snapshot.set("scopes", MAPPER.valueToTree(server.getScopes()));
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
private static String encode(Identity identity) {
|
||||
return MAPPER.createArrayNode().add(identity.poolId()).add(identity.identifier()).toString();
|
||||
}
|
||||
|
||||
private static Identity decode(String physicalId) {
|
||||
try {
|
||||
JsonNode address = MAPPER.readTree(physicalId);
|
||||
if (address != null && address.isArray() && address.size() == 2
|
||||
&& address.get(0).isTextual() && !address.get(0).asText().isBlank()
|
||||
&& address.get(1).isTextual() && !address.get(1).asText().isBlank()) {
|
||||
return new Identity(address.get(0).asText(), address.get(1).asText());
|
||||
}
|
||||
} catch (JsonProcessingException invalid) {
|
||||
throw new IllegalStateException("Invalid Cognito resource server cleanup address", invalid);
|
||||
}
|
||||
throw new IllegalStateException("Invalid Cognito resource server cleanup address");
|
||||
}
|
||||
|
||||
/*
|
||||
* Ref is only Identifier, whereas a resource server's delete address also includes its pool.
|
||||
* Only this detached view gives ReplacementCleanup the full address; no encoded id is assigned
|
||||
* to the stack resource or passed to the template engine.
|
||||
*/
|
||||
private static StackResource project(StackResource resource) {
|
||||
StackResource projected = new StackResource();
|
||||
projected.setLogicalId(resource.getLogicalId());
|
||||
projected.setResourceType(resource.getResourceType());
|
||||
projected.setStatus(resource.getStatus());
|
||||
projected.setDeletionPolicy(resource.getDeletionPolicy());
|
||||
projected.setUpdateReplacePolicy(resource.getUpdateReplacePolicy());
|
||||
projected.setAttributes(new HashMap<>(resource.getAttributes()));
|
||||
if (resource.getPhysicalId() != null) {
|
||||
projected.setPhysicalId(CfnResourceDispatcher.isStub(resource.getPhysicalId(), resource.getAttributes())
|
||||
? resource.getPhysicalId() : encode(identity(resource, resource.getPhysicalId())));
|
||||
}
|
||||
validateCleanup(projected);
|
||||
return projected;
|
||||
}
|
||||
|
||||
private static <T> T withProjection(StackResource resource, Function<StackResource, T> operation) {
|
||||
StackResource projected = project(resource);
|
||||
try {
|
||||
return operation.apply(projected);
|
||||
} finally {
|
||||
// Rollback restores the prior identity before deleting the replacement, even if that delete fails.
|
||||
boolean restoredStub = CfnResourceDispatcher.isStub(projected.getPhysicalId(), projected.getAttributes());
|
||||
Identity restored = projected.getPhysicalId() == null || restoredStub
|
||||
? null : decode(projected.getPhysicalId());
|
||||
resource.getAttributes().clear();
|
||||
resource.getAttributes().putAll(projected.getAttributes());
|
||||
if (restoredStub) {
|
||||
resource.setPhysicalId(projected.getPhysicalId());
|
||||
resource.getAttributes().remove(POOL_ATTR);
|
||||
} else if (restored != null) {
|
||||
setIdentity(resource, restored);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireIdentity(Identity identity) {
|
||||
if (identity.poolId().isBlank() || identity.identifier().isBlank()) {
|
||||
throw new IllegalStateException("Invalid Cognito resource server lifecycle identity");
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateCleanup(StackResource projected) {
|
||||
ObjectNode cleanup = read(projected, CfnRollback.REPLACEMENT_CLEANUP_ATTR);
|
||||
if (cleanup == null) {
|
||||
return;
|
||||
}
|
||||
if (cleanup.has("displaced") && !cleanup.path("displaced").isArray()) {
|
||||
throw new IllegalStateException("Invalid Cognito resource server cleanup entries");
|
||||
}
|
||||
for (JsonNode entry : cleanup.path("displaced")) {
|
||||
if (!entry.isObject() || !entry.path("physicalId").isTextual()
|
||||
|| entry.path("cleanupAttempts").asInt(0) < 0) {
|
||||
throw new IllegalStateException("Invalid Cognito resource server cleanup entry");
|
||||
}
|
||||
decode(entry.path("physicalId").asText());
|
||||
}
|
||||
if (cleanup.hasNonNull("priorPhysicalId")) {
|
||||
if (!cleanup.path("priorAttributes").isObject()) {
|
||||
throw new IllegalStateException("Invalid Cognito resource server rollback attributes");
|
||||
}
|
||||
Map<String, String> priorAttributes = new HashMap<>();
|
||||
cleanup.path("priorAttributes").fields()
|
||||
.forEachRemaining(entry -> priorAttributes.put(entry.getKey(), entry.getValue().asText()));
|
||||
String priorPhysicalId = cleanup.path("priorPhysicalId").asText();
|
||||
if (!CfnResourceDispatcher.isStub(priorPhysicalId, priorAttributes)) {
|
||||
decode(priorPhysicalId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteAddress(String resourceType, String physicalId, String region) {
|
||||
delete(decode(physicalId));
|
||||
}
|
||||
|
||||
private void delete(Identity identity) {
|
||||
CfnDeletes.safeDelete("Cognito resource server", identity.identifier(),
|
||||
() -> cognitoService.deleteResourceServer(identity.poolId(), identity.identifier()),
|
||||
"ResourceNotFoundException");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(StackResource resource, String region) {
|
||||
withProjection(resource, projected -> {
|
||||
if (projected.getPhysicalId() != null
|
||||
&& !CfnResourceDispatcher.isStub(projected.getPhysicalId(), projected.getAttributes())) {
|
||||
deleteAddress(projected.getResourceType(), projected.getPhysicalId(), region);
|
||||
}
|
||||
projected.getAttributes().remove(UPDATE_ATTR);
|
||||
projected.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR);
|
||||
ReplacementCleanup.clear(projected);
|
||||
return null;
|
||||
});
|
||||
lifecycle.delete(resource, region);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean rollbackUpdate(StackResource resource) {
|
||||
return withProjection(resource, projected -> {
|
||||
if (ReplacementCleanup.rollback(projected, this::deleteAddress)) {
|
||||
return true;
|
||||
}
|
||||
ObjectNode snapshot = read(projected, UPDATE_ATTR);
|
||||
if (snapshot == null) {
|
||||
return false;
|
||||
}
|
||||
Identity prior = identity(snapshot);
|
||||
requireIdentity(prior);
|
||||
cognitoService.updateResourceServer(prior.poolId(), prior.identifier(), snapshot.path("name").asText(),
|
||||
scopes(snapshot.path("scopes")));
|
||||
projected.setPhysicalId(encode(prior));
|
||||
projected.getAttributes().remove(UPDATE_ATTR);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
private static List<ResourceServerScope> scopes(JsonNode nodes) {
|
||||
List<ResourceServerScope> scopes = new ArrayList<>();
|
||||
for (JsonNode node : nodes) {
|
||||
ResourceServerScope scope = new ResourceServerScope();
|
||||
scope.setScopeName(node.path("scopeName").asText());
|
||||
scope.setScopeDescription(node.path("scopeDescription").asText(null));
|
||||
scopes.add(scope);
|
||||
}
|
||||
return scopes;
|
||||
return lifecycle.rollbackUpdate(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasReplacementUpdate(StackResource resource) {
|
||||
return withProjection(resource, ReplacementCleanup::hasReplacement);
|
||||
}
|
||||
|
||||
private static boolean hasPendingRollback(StackResource projected) {
|
||||
ObjectNode cleanup = read(projected, CfnRollback.REPLACEMENT_CLEANUP_ATTR);
|
||||
return projected.getAttributes().containsKey(UPDATE_ATTR)
|
||||
|| (cleanup != null && cleanup.hasNonNull("priorPhysicalId"));
|
||||
return lifecycle.hasReplacementUpdate(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean retainsFailedUpdateState(StackResource resource) {
|
||||
return withProjection(resource, CognitoResourceServerCfnProvisioner::hasPendingRollback);
|
||||
return lifecycle.retainsFailedUpdateState(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String updateCleanupPhysicalId(StackResource resource) {
|
||||
return withProjection(resource, projected -> {
|
||||
String physicalId = ReplacementCleanup.cleanupPhysicalId(projected);
|
||||
return physicalId == null ? null : decode(physicalId).identifier();
|
||||
});
|
||||
}
|
||||
|
||||
private static UpdateCleanupResult publicResult(UpdateCleanupResult result) {
|
||||
String physicalId = result.previousPhysicalId();
|
||||
return new UpdateCleanupResult(result.applicable(), result.complete(),
|
||||
physicalId == null ? null : decode(physicalId).identifier(),
|
||||
result.attempts(), result.failureReason());
|
||||
return lifecycle.updateCleanupPhysicalId(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateCleanupResult completeUpdate(StackResource resource) {
|
||||
return withProjection(resource, projected -> {
|
||||
if ("UPDATE_FAILED".equals(projected.getStatus()) && hasPendingRollback(projected)) {
|
||||
throw new IllegalStateException("Resource server rollback is still pending; its original configuration "
|
||||
+ "cannot be discarded by another resource's update cleanup");
|
||||
}
|
||||
boolean updated = projected.getAttributes().remove(UPDATE_ATTR) != null;
|
||||
ObjectNode committed = read(projected, CfnRollback.REPLACEMENT_CLEANUP_ATTR);
|
||||
if (committed != null) {
|
||||
// Committing the update spends its rollback identity, independently of delete retry debt.
|
||||
committed.remove("priorPhysicalId");
|
||||
committed.remove("priorAttributes");
|
||||
projected.getAttributes().put(CfnRollback.REPLACEMENT_CLEANUP_ATTR, committed.toString());
|
||||
}
|
||||
UpdateCleanupResult cleanup = ReplacementCleanup.complete(projected, this::deleteAddress);
|
||||
return !cleanup.applicable() && updated
|
||||
? new UpdateCleanupResult(true, true, null, 0, null) : publicResult(cleanup);
|
||||
});
|
||||
return lifecycle.completeUpdate(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateCleanupResult completeDeleteCleanup(StackResource resource) {
|
||||
return withProjection(resource, projected -> publicResult(ReplacementCleanup.complete(projected,
|
||||
this::deleteAddress)));
|
||||
return lifecycle.completeDeleteCleanup(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearDeleteCleanup(StackResource resource) {
|
||||
withProjection(resource, projected -> {
|
||||
ObjectNode cleanup = read(projected, CfnRollback.REPLACEMENT_CLEANUP_ATTR);
|
||||
JsonNode prior = cleanup == null ? null : cleanup.get("priorPhysicalId");
|
||||
JsonNode attributes = cleanup == null ? null : cleanup.get("priorAttributes");
|
||||
ReplacementCleanup.clear(projected);
|
||||
if (prior != null) {
|
||||
ObjectNode remaining = read(projected, CfnRollback.REPLACEMENT_CLEANUP_ATTR);
|
||||
if (remaining == null) {
|
||||
remaining = MAPPER.createObjectNode();
|
||||
remaining.putArray("displaced");
|
||||
}
|
||||
remaining.set("priorPhysicalId", prior);
|
||||
remaining.set("priorAttributes", attributes);
|
||||
projected.getAttributes().put(CfnRollback.REPLACEMENT_CLEANUP_ATTR, remaining.toString());
|
||||
}
|
||||
return null;
|
||||
});
|
||||
lifecycle.clearDeleteCleanup(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearUpdate(StackResource resource) {
|
||||
withProjection(resource, projected -> {
|
||||
projected.getAttributes().remove(UPDATE_ATTR);
|
||||
ReplacementCleanup.clear(projected);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private static ObjectNode read(StackResource resource, String attribute) {
|
||||
String raw = resource.getAttributes().get(attribute);
|
||||
if (raw == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
JsonNode node = MAPPER.readTree(raw);
|
||||
if (node instanceof ObjectNode object) {
|
||||
return object;
|
||||
}
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException("Invalid Cognito resource server lifecycle record", e);
|
||||
}
|
||||
throw new IllegalStateException("Invalid Cognito resource server lifecycle record");
|
||||
lifecycle.clearUpdate(resource);
|
||||
}
|
||||
}
|
||||
@@ -1664,7 +1664,7 @@ public class CognitoService implements ResourceProvider {
|
||||
|
||||
// ──────────────────────────── Identity Providers ────────────────────────────
|
||||
|
||||
private static final Set<String> PROVIDER_TYPES =
|
||||
public static final Set<String> PROVIDER_TYPES =
|
||||
Set.of("Facebook", "SAML", "SignInWithApple", "LoginWithAmazon", "OIDC", "Google");
|
||||
|
||||
public IdentityProvider createIdentityProvider(String userPoolId, String providerName, String providerType,
|
||||
|
||||
@@ -218,6 +218,11 @@
|
||||
"UserPoolId",
|
||||
"GroupName"
|
||||
],
|
||||
"AWS::Cognito::UserPoolIdentityProvider": [
|
||||
"ProviderName",
|
||||
"ProviderType",
|
||||
"UserPoolId"
|
||||
],
|
||||
"AWS::Cognito::UserPoolResourceServer": [
|
||||
"Identifier",
|
||||
"UserPoolId"
|
||||
|
||||
+2
@@ -45,6 +45,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudWatc
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudWatchCompositeAlarmCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudWatchDashboardCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoIdentityProviderCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoResourceServerCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoUserPoolGroupCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoUserPoolUserCfnProvisioner;
|
||||
@@ -355,6 +356,7 @@ final class CfnProvisionerFixture {
|
||||
}
|
||||
if (cognitoService != null) {
|
||||
discovered.add(new CognitoCfnProvisioner(cognitoService));
|
||||
discovered.add(new CognitoIdentityProviderCfnProvisioner(cognitoService));
|
||||
discovered.add(new CognitoResourceServerCfnProvisioner(cognitoService));
|
||||
discovered.add(new CognitoUserPoolGroupCfnProvisioner(cognitoService));
|
||||
discovered.add(new CognitoUserPoolUserCfnProvisioner(cognitoService));
|
||||
|
||||
+287
@@ -0,0 +1,287 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.github.hectorvent.floci.testing.CfnStackWaits;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;
|
||||
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;
|
||||
import static io.github.hectorvent.floci.testing.CfnRequests.cfn;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
|
||||
@QuarkusTest
|
||||
class CognitoIdentityProviderCfnIntegrationTest {
|
||||
|
||||
private static final String CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261101/us-east-1/cloudformation/aws4_request";
|
||||
private static final String SM_CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
private static final String NAME = "ExampleOIDC";
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final List<String> poolIds = new ArrayList<>();
|
||||
private final List<String> secretIds = new ArrayList<>();
|
||||
private final String stack = "cognito-idp-" + Long.toString(System.nanoTime(), 36);
|
||||
private boolean createdStack;
|
||||
|
||||
@BeforeAll
|
||||
static void configureAwsContentTypes() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanup() {
|
||||
if (createdStack) {
|
||||
cloudFormation("DeleteStack", null);
|
||||
CfnStackWaits.awaitStackDeleted(stack);
|
||||
}
|
||||
for (String pool : poolIds) {
|
||||
cognitoAction("DeleteUserPool", "{\"UserPoolId\":\"" + pool + "\"}").then().statusCode(200);
|
||||
}
|
||||
for (String secret : secretIds) {
|
||||
given().header("X-Amz-Target", "secretsmanager.DeleteSecret").contentType(SM_CONTENT_TYPE)
|
||||
.body(mapper.createObjectNode().put("SecretId", secret)
|
||||
.put("ForceDeleteWithoutRecovery", true).toString())
|
||||
.when().post("/").then().statusCode(200);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void stackCreatesUpdatesReplacesAndDeletesTheBackingProvider() throws Exception {
|
||||
String poolA = createPool();
|
||||
String poolB = createPool();
|
||||
createStack(template(poolA, NAME, "OIDC", "original-client"));
|
||||
assertEquals(NAME, output("ProviderRef"));
|
||||
JsonNode created = provider(poolA, NAME);
|
||||
assertEquals("OIDC", created.path("ProviderType").asText());
|
||||
assertEquals("original-client", created.path("ProviderDetails").path("client_id").asText());
|
||||
assertEquals("email", created.path("AttributeMapping").path("email").asText());
|
||||
|
||||
updateStack(template(poolA, NAME, "OIDC", "updated-client"), "UPDATE_COMPLETE");
|
||||
assertEquals(NAME, output("ProviderRef"));
|
||||
assertClientId(poolA, NAME, "updated-client");
|
||||
|
||||
updateStack(template(poolA, "RenamedOIDC", "OIDC", "updated-client"), "UPDATE_COMPLETE");
|
||||
assertEquals("RenamedOIDC", output("ProviderRef"));
|
||||
assertProviderGone(poolA, NAME);
|
||||
assertClientId(poolA, "RenamedOIDC", "updated-client");
|
||||
|
||||
updateStack(template(poolB, "RenamedOIDC", "OIDC", "moved-client"), "UPDATE_COMPLETE");
|
||||
assertEquals("RenamedOIDC", output("ProviderRef"));
|
||||
assertProviderGone(poolA, "RenamedOIDC");
|
||||
assertClientId(poolB, "RenamedOIDC", "moved-client");
|
||||
|
||||
cloudFormation("DeleteStack", null);
|
||||
CfnStackWaits.awaitStackDeleted(stack);
|
||||
createdStack = false;
|
||||
assertProviderGone(poolB, "RenamedOIDC");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aUserPoolClientListsTheProviderThroughItsRef() throws Exception {
|
||||
ObjectNode template = mapper.createObjectNode();
|
||||
ObjectNode resources = template.putObject("Resources");
|
||||
resources.putObject("Pool").put("Type", "AWS::Cognito::UserPool")
|
||||
.putObject("Properties").put("UserPoolName", stack);
|
||||
ObjectNode idp = resources.putObject("Idp");
|
||||
idp.put("Type", "AWS::Cognito::UserPoolIdentityProvider");
|
||||
ObjectNode idpProperties = providerProperties(NAME, "OIDC", "example-client");
|
||||
idpProperties.putObject("UserPoolId").put("Ref", "Pool");
|
||||
idp.set("Properties", idpProperties);
|
||||
ObjectNode client = resources.putObject("Client");
|
||||
client.put("Type", "AWS::Cognito::UserPoolClient");
|
||||
ObjectNode clientProperties = client.putObject("Properties");
|
||||
clientProperties.putObject("UserPoolId").put("Ref", "Pool");
|
||||
clientProperties.put("ClientName", "federated");
|
||||
clientProperties.putArray("SupportedIdentityProviders").addObject().put("Ref", "Idp");
|
||||
ObjectNode outputs = template.putObject("Outputs");
|
||||
outputs.putObject("PoolId").putObject("Value").put("Ref", "Pool");
|
||||
outputs.putObject("ClientId").putObject("Value").put("Ref", "Client");
|
||||
|
||||
createStack(template);
|
||||
|
||||
String pool = output("PoolId");
|
||||
assertClientId(pool, NAME, "example-client");
|
||||
JsonNode described = cognitoJson("DescribeUserPoolClient", mapper.createObjectNode()
|
||||
.put("UserPoolId", pool).put("ClientId", output("ClientId")).toString()).path("UserPoolClient");
|
||||
assertEquals(NAME, described.path("SupportedIdentityProviders").get(0).asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clientSecretResolvesFromASecretsManagerDynamicReference() throws Exception {
|
||||
String pool = createPool();
|
||||
String secret = stack + "-oidc";
|
||||
given().header("X-Amz-Target", "secretsmanager.CreateSecret").contentType(SM_CONTENT_TYPE)
|
||||
.body(mapper.createObjectNode().put("Name", secret)
|
||||
.put("SecretString", "{\"clientSecret\":\"resolved-secret\"}").toString())
|
||||
.when().post("/").then().statusCode(200);
|
||||
secretIds.add(secret);
|
||||
ObjectNode template = template(pool, NAME, "OIDC", "example-client");
|
||||
((ObjectNode) template.path("Resources").path("Idp").path("Properties").path("ProviderDetails"))
|
||||
.put("client_secret", "{{resolve:secretsmanager:" + secret + ":SecretString:clientSecret}}");
|
||||
|
||||
createStack(template);
|
||||
|
||||
assertEquals("resolved-secret",
|
||||
provider(pool, NAME).path("ProviderDetails").path("client_secret").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingOnlyTheProviderTypeRollsTheUpdateBack() throws Exception {
|
||||
String pool = createPool();
|
||||
createStack(template(pool, NAME, "OIDC", "original-client"));
|
||||
|
||||
ObjectNode saml = template(pool, NAME, "SAML", "original-client");
|
||||
((ObjectNode) saml.path("Resources").path("Idp").path("Properties").path("ProviderDetails"))
|
||||
.put("MetadataURL", "https://issuer.example.com/saml/metadata");
|
||||
updateStack(saml, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
JsonNode kept = provider(pool, NAME);
|
||||
assertEquals("OIDC", kept.path("ProviderType").asText());
|
||||
assertEquals("original-client", kept.path("ProviderDetails").path("client_id").asText());
|
||||
assertFalse(kept.path("ProviderDetails").has("MetadataURL"));
|
||||
assertEquals(NAME, output("ProviderRef"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theOriginalProviderUpdatesInPlaceAfterARolledBackTypeAndNameReplacement() throws Exception {
|
||||
String pool = createPool();
|
||||
createStack(template(pool, NAME, "OIDC", "original-client"));
|
||||
ObjectNode saml = template(pool, "ExampleSAML", "SAML", "original-client");
|
||||
((ObjectNode) saml.path("Resources").path("Idp").path("Properties").path("ProviderDetails"))
|
||||
.put("MetadataURL", "https://issuer.example.com/saml/metadata");
|
||||
addFailingDependentResource(saml);
|
||||
updateStack(saml, "UPDATE_ROLLBACK_COMPLETE");
|
||||
assertProviderGone(pool, "ExampleSAML");
|
||||
|
||||
updateStack(template(pool, NAME, "OIDC", "updated-client"), "UPDATE_COMPLETE");
|
||||
|
||||
assertEquals(NAME, output("ProviderRef"));
|
||||
assertClientId(pool, NAME, "updated-client");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedDependentResourceRestoresThePriorInPlaceConfiguration() throws Exception {
|
||||
String pool = createPool();
|
||||
createStack(template(pool, NAME, "OIDC", "original-client"));
|
||||
ObjectNode attempted = template(pool, NAME, "OIDC", "attempted-client");
|
||||
ObjectNode attemptedProperties = (ObjectNode) attempted.path("Resources").path("Idp").path("Properties");
|
||||
attemptedProperties.putObject("AttributeMapping").put("email", "mail");
|
||||
attemptedProperties.putArray("IdpIdentifiers").add("example.com");
|
||||
addFailingDependentResource(attempted);
|
||||
|
||||
updateStack(attempted, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
JsonNode restored = provider(pool, NAME);
|
||||
assertEquals("original-client", restored.path("ProviderDetails").path("client_id").asText());
|
||||
assertEquals("email", restored.path("AttributeMapping").path("email").asText());
|
||||
assertEquals(0, restored.path("IdpIdentifiers").size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedDependentResourceDeletesTheReplacementAndRestoresThePriorPool() throws Exception {
|
||||
String poolA = createPool();
|
||||
String poolB = createPool();
|
||||
createStack(template(poolA, NAME, "OIDC", "original-client"));
|
||||
ObjectNode attempted = template(poolB, NAME, "OIDC", "replacement-client");
|
||||
addFailingDependentResource(attempted);
|
||||
|
||||
updateStack(attempted, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
assertClientId(poolA, NAME, "original-client");
|
||||
assertProviderGone(poolB, NAME);
|
||||
assertEquals(NAME, output("ProviderRef"));
|
||||
}
|
||||
|
||||
private String createPool() throws Exception {
|
||||
String id = cognitoJson("CreateUserPool", "{\"PoolName\":\"" + stack + "\"}")
|
||||
.path("UserPool").path("Id").asText();
|
||||
poolIds.add(id);
|
||||
return id;
|
||||
}
|
||||
|
||||
private void createStack(ObjectNode template) {
|
||||
cloudFormation("CreateStack", template);
|
||||
createdStack = true;
|
||||
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack).status());
|
||||
}
|
||||
|
||||
private void updateStack(ObjectNode template, String expectedStatus) {
|
||||
cloudFormation("UpdateStack", template);
|
||||
assertEquals(expectedStatus, CfnStackWaits.awaitTerminal(stack).status());
|
||||
}
|
||||
|
||||
private void cloudFormation(String action, ObjectNode template) {
|
||||
RequestSpecification request = cfn(action, stack).header("Authorization", CFN_AUTH);
|
||||
if (template != null) {
|
||||
request.formParam("TemplateBody", template.toString());
|
||||
}
|
||||
request.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private String output(String key) {
|
||||
String xml = cfn("DescribeStacks", stack).header("Authorization", CFN_AUTH)
|
||||
.when().post("/").then().statusCode(200).extract().asString();
|
||||
return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
|
||||
}
|
||||
|
||||
private ObjectNode providerProperties(String name, String type, String clientId) {
|
||||
ObjectNode properties = mapper.createObjectNode();
|
||||
properties.put("ProviderName", name);
|
||||
properties.put("ProviderType", type);
|
||||
properties.putObject("ProviderDetails")
|
||||
.put("client_id", clientId)
|
||||
.put("oidc_issuer", "https://issuer.example.com")
|
||||
.put("authorize_scopes", "openid email")
|
||||
.put("attributes_request_method", "GET");
|
||||
properties.putObject("AttributeMapping").put("email", "email");
|
||||
return properties;
|
||||
}
|
||||
|
||||
private ObjectNode template(String pool, String name, String type, String clientId) {
|
||||
ObjectNode template = mapper.createObjectNode();
|
||||
ObjectNode resource = template.putObject("Resources").putObject("Idp");
|
||||
resource.put("Type", "AWS::Cognito::UserPoolIdentityProvider");
|
||||
ObjectNode properties = providerProperties(name, type, clientId);
|
||||
properties.put("UserPoolId", pool);
|
||||
resource.set("Properties", properties);
|
||||
template.putObject("Outputs").putObject("ProviderRef").putObject("Value").put("Ref", "Idp");
|
||||
return template;
|
||||
}
|
||||
|
||||
private static void addFailingDependentResource(ObjectNode template) {
|
||||
ObjectNode broken = ((ObjectNode) template.path("Resources")).putObject("Broken");
|
||||
broken.put("Type", "AWS::Cognito::UserPoolClient");
|
||||
broken.put("DependsOn", "Idp");
|
||||
broken.putObject("Properties").put("UserPoolId", "us-east-1_nonexistent").put("ClientName", "broken");
|
||||
}
|
||||
|
||||
private static JsonNode provider(String pool, String name) throws Exception {
|
||||
return cognitoJson("DescribeIdentityProvider", "{\"UserPoolId\":\"" + pool
|
||||
+ "\",\"ProviderName\":\"" + name + "\"}").path("IdentityProvider");
|
||||
}
|
||||
|
||||
private static void assertClientId(String pool, String name, String clientId) throws Exception {
|
||||
JsonNode provider = provider(pool, name);
|
||||
assertEquals(name, provider.path("ProviderName").asText());
|
||||
assertEquals(clientId, provider.path("ProviderDetails").path("client_id").asText());
|
||||
}
|
||||
|
||||
private static void assertProviderGone(String pool, String name) {
|
||||
cognitoAction("DescribeIdentityProvider", "{\"UserPoolId\":\"" + pool
|
||||
+ "\",\"ProviderName\":\"" + name + "\"}")
|
||||
.then().statusCode(400).body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
}
|
||||
+373
@@ -0,0 +1,373 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.cognito.CognitoService;
|
||||
import io.github.hectorvent.floci.services.cognito.model.IdentityProvider;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class CognitoIdentityProviderCfnProvisionerTest {
|
||||
|
||||
private static final String POOL = "us-east-1_original";
|
||||
private static final String NEW_POOL = "us-east-1_replacement";
|
||||
private static final String NAME = "ExampleOIDC";
|
||||
private static final String POOL_ATTR = "__FlociIdentityProviderPoolId";
|
||||
|
||||
private final CognitoService cognito = mock(CognitoService.class);
|
||||
private final CognitoIdentityProviderCfnProvisioner provisioner = new CognitoIdentityProviderCfnProvisioner(cognito);
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
private ProvisionContext ctx(String priorId) {
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolve(any())).thenAnswer(invocation -> {
|
||||
JsonNode node = invocation.getArgument(0);
|
||||
return node == null || node.isNull() ? null : node.asText();
|
||||
});
|
||||
when(engine.resolveNode(any())).thenAnswer(invocation -> invocation.getArgument(0));
|
||||
when(engine.resolveNodeOmittingNoValue(any())).thenAnswer(invocation -> invocation.getArgument(0));
|
||||
when(engine.resolveStringList(any())).thenAnswer(invocation -> {
|
||||
List<String> values = new ArrayList<>();
|
||||
JsonNode node = invocation.getArgument(0);
|
||||
node.forEach(value -> values.add(value.asText()));
|
||||
return values;
|
||||
});
|
||||
return new ProvisionContext(engine, "us-east-1", "000000000000", "test-stack", priorId);
|
||||
}
|
||||
|
||||
private ProvisionContext intrinsicContext() {
|
||||
CloudFormationTemplateEngine engine = CloudFormationTemplateEngine.standalone(
|
||||
"000000000000", "us-east-1", "test-stack", mapper, null);
|
||||
return new ProvisionContext(engine, "us-east-1", "000000000000", "test-stack");
|
||||
}
|
||||
|
||||
private ObjectNode properties(String poolId, String providerName, String providerType, String clientId) {
|
||||
ObjectNode properties = mapper.createObjectNode();
|
||||
if (poolId != null) {
|
||||
properties.put("UserPoolId", poolId);
|
||||
}
|
||||
if (providerName != null) {
|
||||
properties.put("ProviderName", providerName);
|
||||
}
|
||||
if (providerType != null) {
|
||||
properties.put("ProviderType", providerType);
|
||||
}
|
||||
if (clientId != null) {
|
||||
properties.putObject("ProviderDetails")
|
||||
.put("client_id", clientId)
|
||||
.put("oidc_issuer", "https://issuer.example.com");
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
|
||||
private ObjectNode oidc(String poolId, String providerName, String clientId) {
|
||||
return properties(poolId, providerName, "OIDC", clientId);
|
||||
}
|
||||
|
||||
private static Map<String, String> details(String clientId) {
|
||||
Map<String, String> details = new LinkedHashMap<>();
|
||||
details.put("client_id", clientId);
|
||||
details.put("oidc_issuer", "https://issuer.example.com");
|
||||
return details;
|
||||
}
|
||||
|
||||
private StackResource resource(String providerName, String poolId) {
|
||||
StackResource resource = new StackResource();
|
||||
resource.setLogicalId("Idp");
|
||||
resource.setResourceType("AWS::Cognito::UserPoolIdentityProvider");
|
||||
resource.setPhysicalId(providerName);
|
||||
resource.setAttributes(new HashMap<>());
|
||||
if (poolId != null) {
|
||||
resource.getAttributes().put(POOL_ATTR, poolId);
|
||||
}
|
||||
return resource;
|
||||
}
|
||||
|
||||
private static IdentityProvider provider(String poolId, String providerName, String clientId) {
|
||||
IdentityProvider provider = new IdentityProvider();
|
||||
provider.setUserPoolId(poolId);
|
||||
provider.setProviderName(providerName);
|
||||
provider.setProviderType("OIDC");
|
||||
provider.setProviderDetails(details(clientId));
|
||||
provider.setAttributeMapping(new LinkedHashMap<>(Map.of("email", "email")));
|
||||
provider.setIdpIdentifiers(new ArrayList<>(List.of("old-idp")));
|
||||
return provider;
|
||||
}
|
||||
|
||||
@Test
|
||||
void servesIdentityProviderType() {
|
||||
assertEquals(Set.of("AWS::Cognito::UserPoolIdentityProvider"), provisioner.resourceTypes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createsProviderWithResolvedMembersAndSetsRefAndPoolTracking() {
|
||||
ObjectNode properties = oidc(POOL, NAME, "client");
|
||||
properties.putObject("AttributeMapping").put("email", "email");
|
||||
properties.putArray("IdpIdentifiers").add("example.com");
|
||||
StackResource resource = resource(null, null);
|
||||
|
||||
provisioner.provision(resource, properties, ctx(null));
|
||||
|
||||
verify(cognito).createIdentityProvider(POOL, NAME, "OIDC", details("client"),
|
||||
Map.of("email", "email"), List.of("example.com"));
|
||||
assertEquals(NAME, resource.getPhysicalId());
|
||||
assertEquals(POOL, resource.getAttributes().get(POOL_ATTR));
|
||||
assertFalse(resource.getAttributes().containsKey("ProviderName"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void absentOptionalMembersReachCognitoAsNullSoItsDefaultsApply() {
|
||||
provisioner.provision(resource(null, null), oidc(POOL, NAME, "client"), ctx(null));
|
||||
|
||||
verify(cognito).createIdentityProvider(POOL, NAME, "OIDC", details("client"), null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAttributeMappingOfNoValueIsOmitted() {
|
||||
ObjectNode properties = oidc(POOL, NAME, "client");
|
||||
properties.putObject("AttributeMapping").put("Ref", "AWS::NoValue");
|
||||
|
||||
provisioner.provision(resource(null, null), properties, intrinsicContext());
|
||||
|
||||
verify(cognito).createIdentityProvider(POOL, NAME, "OIDC", details("client"), null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsMissingRequiredPropertiesBeforeCallingCognito() {
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(resource(null, null),
|
||||
oidc(null, NAME, "client"), ctx(null)));
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(resource(null, null),
|
||||
oidc(POOL, null, "client"), ctx(null)));
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(resource(null, null),
|
||||
properties(POOL, NAME, null, "client"), ctx(null)));
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(resource(null, null),
|
||||
oidc(POOL, NAME, null), ctx(null)));
|
||||
verifyNoInteractions(cognito);
|
||||
}
|
||||
|
||||
@Test
|
||||
void validatesSchemaBoundsBeforeCallingCognito() {
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(resource(null, null),
|
||||
properties(POOL, NAME, "Okta", "client"), ctx(null)));
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(resource(null, null),
|
||||
oidc(POOL, "n".repeat(33), "client"), ctx(null)));
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(resource(null, null),
|
||||
oidc("not a pool", NAME, "client"), ctx(null)));
|
||||
ObjectNode nestedDetails = oidc(POOL, NAME, null);
|
||||
nestedDetails.putObject("ProviderDetails").putObject("client_id");
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(resource(null, null), nestedDetails, ctx(null)));
|
||||
ObjectNode tooMany = oidc(POOL, NAME, "client");
|
||||
for (int index = 0; index < 51; index++) {
|
||||
tooMany.withArray("IdpIdentifiers").add("idp" + index);
|
||||
}
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(resource(null, null), tooMany, ctx(null)));
|
||||
verifyNoInteractions(cognito);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unchangedIdentityUpdatesInPlaceAndRollbackRestoresTheSnapshot() {
|
||||
when(cognito.describeIdentityProvider(POOL, NAME)).thenReturn(provider(POOL, NAME, "old-client"));
|
||||
StackResource resource = resource(NAME, POOL);
|
||||
|
||||
provisioner.provision(resource, oidc(POOL, NAME, "new-client"), ctx(NAME));
|
||||
|
||||
verify(cognito).updateIdentityProvider(POOL, NAME, details("new-client"), null, null);
|
||||
verify(cognito, never()).createIdentityProvider(any(), any(), any(), any(), any(), any());
|
||||
assertFalse(provisioner.hasReplacementUpdate(resource));
|
||||
assertTrue(provisioner.retainsFailedUpdateState(resource));
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(resource));
|
||||
|
||||
verify(cognito).updateIdentityProvider(POOL, NAME, details("old-client"),
|
||||
Map.of("email", "email"), List.of("old-idp"));
|
||||
assertEquals(NAME, resource.getPhysicalId());
|
||||
assertEquals(POOL, resource.getAttributes().get(POOL_ATTR));
|
||||
assertFalse(provisioner.retainsFailedUpdateState(resource));
|
||||
}
|
||||
|
||||
@Test
|
||||
void committingAnInPlaceUpdateDropsItsSnapshot() {
|
||||
when(cognito.describeIdentityProvider(POOL, NAME)).thenReturn(provider(POOL, NAME, "old-client"));
|
||||
StackResource resource = resource(NAME, POOL);
|
||||
provisioner.provision(resource, oidc(POOL, NAME, "new-client"), ctx(NAME));
|
||||
|
||||
assertTrue(provisioner.completeUpdate(resource).complete());
|
||||
|
||||
assertFalse(provisioner.retainsFailedUpdateState(resource));
|
||||
assertFalse(provisioner.rollbackUpdate(resource));
|
||||
verify(cognito, never()).deleteIdentityProvider(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingOnlyTheProviderTypeIsRefusedBeforeChangingAnything() {
|
||||
when(cognito.describeIdentityProvider(POOL, NAME)).thenReturn(provider(POOL, NAME, "client"));
|
||||
StackResource resource = resource(NAME, POOL);
|
||||
HashMap<String, String> priorAttributes = new HashMap<>(resource.getAttributes());
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(resource,
|
||||
properties(POOL, NAME, "SAML", "client"), ctx(NAME)));
|
||||
|
||||
assertEquals("ValidationError", failure.getErrorCode());
|
||||
assertTrue(failure.getMessage().contains("custom-named resource requires replacing"));
|
||||
assertEquals(NAME, resource.getPhysicalId());
|
||||
assertEquals(priorAttributes, resource.getAttributes());
|
||||
verify(cognito, never()).createIdentityProvider(any(), any(), any(), any(), any(), any());
|
||||
verify(cognito, never()).updateIdentityProvider(any(), any(), any(), any(), any());
|
||||
verify(cognito, never()).deleteIdentityProvider(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingTheTypeWithANewNameReplacesTheProvider() {
|
||||
StackResource resource = resource(NAME, POOL);
|
||||
|
||||
provisioner.provision(resource, properties(POOL, "ExampleSAML", "SAML", "client"), ctx(NAME));
|
||||
|
||||
verify(cognito).createIdentityProvider(POOL, "ExampleSAML", "SAML", details("client"), null, null);
|
||||
assertTrue(provisioner.completeUpdate(resource).complete());
|
||||
verify(cognito).deleteIdentityProvider(POOL, NAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theOriginalTypeUpdatesInPlaceAfterARolledBackTypeAndNameReplacement() {
|
||||
when(cognito.describeIdentityProvider(POOL, NAME)).thenReturn(provider(POOL, NAME, "client"));
|
||||
StackResource resource = resource(NAME, POOL);
|
||||
resource.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
|
||||
provisioner.provision(resource, properties(POOL, "ExampleSAML", "SAML", "client"), ctx(NAME));
|
||||
assertTrue(provisioner.rollbackUpdate(resource));
|
||||
assertEquals(NAME, resource.getPhysicalId());
|
||||
|
||||
provisioner.provision(resource, oidc(POOL, NAME, "updated-client"), ctx(NAME));
|
||||
|
||||
verify(cognito).deleteIdentityProvider(POOL, "ExampleSAML");
|
||||
verify(cognito).updateIdentityProvider(POOL, NAME, details("updated-client"), null, null);
|
||||
verify(cognito, never()).createIdentityProvider(eq(POOL), eq(NAME), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void renamingReplacesAndCommitDeletesTheOldProvider() {
|
||||
StackResource resource = resource(NAME, POOL);
|
||||
|
||||
provisioner.provision(resource, oidc(POOL, "RenamedOIDC", "client"), ctx(NAME));
|
||||
|
||||
verify(cognito).createIdentityProvider(POOL, "RenamedOIDC", "OIDC", details("client"), null, null);
|
||||
verify(cognito, never()).describeIdentityProvider(any(), any());
|
||||
assertEquals("RenamedOIDC", resource.getPhysicalId());
|
||||
assertTrue(provisioner.hasReplacementUpdate(resource));
|
||||
assertEquals(NAME, provisioner.updateCleanupPhysicalId(resource));
|
||||
assertTrue(provisioner.completeUpdate(resource).complete());
|
||||
verify(cognito).deleteIdentityProvider(POOL, NAME);
|
||||
verify(cognito, never()).deleteIdentityProvider(POOL, "RenamedOIDC");
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingPoolReplacesEvenWhenRefIsUnchanged() {
|
||||
StackResource resource = resource(NAME, POOL);
|
||||
|
||||
provisioner.provision(resource, oidc(NEW_POOL, NAME, "client"), ctx(NAME));
|
||||
|
||||
verify(cognito).createIdentityProvider(NEW_POOL, NAME, "OIDC", details("client"), null, null);
|
||||
assertEquals(NAME, resource.getPhysicalId());
|
||||
assertEquals(NEW_POOL, resource.getAttributes().get(POOL_ATTR));
|
||||
assertTrue(provisioner.hasReplacementUpdate(resource));
|
||||
assertTrue(provisioner.completeUpdate(resource).complete());
|
||||
verify(cognito).deleteIdentityProvider(POOL, NAME);
|
||||
verify(cognito, never()).deleteIdentityProvider(NEW_POOL, NAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacementRollbackRestoresPriorIdentityAndDeletesOnlyTheNewProvider() {
|
||||
StackResource resource = resource(NAME, POOL);
|
||||
resource.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
|
||||
HashMap<String, String> priorAttributes = new HashMap<>(resource.getAttributes());
|
||||
provisioner.provision(resource, oidc(NEW_POOL, NAME, "client"), ctx(NAME));
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(resource));
|
||||
|
||||
assertEquals(NAME, resource.getPhysicalId());
|
||||
assertEquals(priorAttributes, resource.getAttributes());
|
||||
verify(cognito).deleteIdentityProvider(NEW_POOL, NAME);
|
||||
verify(cognito, never()).deleteIdentityProvider(POOL, NAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
void retainingAReplacementDoesNotDeleteThePriorProvider() {
|
||||
StackResource resource = resource(NAME, POOL);
|
||||
resource.setUpdateReplacePolicy("Retain");
|
||||
provisioner.provision(resource, oidc(POOL, "RenamedOIDC", "client"), ctx(NAME));
|
||||
|
||||
assertNull(provisioner.updateCleanupPhysicalId(resource));
|
||||
assertTrue(provisioner.completeUpdate(resource).complete());
|
||||
verify(cognito, never()).deleteIdentityProvider(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedReplacementCreateLeavesThePriorAddressAndMetadataUnchanged() {
|
||||
StackResource resource = resource(NAME, POOL);
|
||||
HashMap<String, String> priorAttributes = new HashMap<>(resource.getAttributes());
|
||||
AwsException failure = new AwsException("DuplicateProviderException", "exists", 400);
|
||||
when(cognito.createIdentityProvider(eq(POOL), eq("RenamedOIDC"), any(), any(), any(), any()))
|
||||
.thenThrow(failure);
|
||||
|
||||
assertEquals(failure, assertThrows(AwsException.class, () -> provisioner.provision(resource,
|
||||
oidc(POOL, "RenamedOIDC", "client"), ctx(NAME))));
|
||||
|
||||
assertEquals(NAME, resource.getPhysicalId());
|
||||
assertEquals(priorAttributes, resource.getAttributes());
|
||||
verify(cognito, never()).deleteIdentityProvider(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void migratesDispatcherStubByCreatingTheProviderWithoutOwingTheFakeIdADelete() {
|
||||
StackResource resource = resource("Idp-1a2b3c4d", null);
|
||||
resource.getAttributes().put("Arn", CfnResourceDispatcher.STUB_ARN_PREFIX + resource.getLogicalId());
|
||||
|
||||
provisioner.provision(resource, oidc(POOL, NAME, "client"), ctx(resource.getPhysicalId()));
|
||||
|
||||
verify(cognito).createIdentityProvider(POOL, NAME, "OIDC", details("client"), null, null);
|
||||
assertEquals(NAME, resource.getPhysicalId());
|
||||
assertFalse(resource.getAttributes().containsKey("Arn"));
|
||||
assertNull(provisioner.updateCleanupPhysicalId(resource));
|
||||
|
||||
provisioner.completeUpdate(resource);
|
||||
|
||||
verify(cognito, never()).deleteIdentityProvider(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteUsesStoredPoolAndOnlyToleratesAlreadyMissingProviders() {
|
||||
StackResource resource = resource(NAME, POOL);
|
||||
doThrow(new AwsException("ResourceNotFoundException", "gone", 400))
|
||||
.when(cognito).deleteIdentityProvider(POOL, NAME);
|
||||
provisioner.delete(resource, "us-east-1");
|
||||
verify(cognito).deleteIdentityProvider(POOL, NAME);
|
||||
|
||||
StackResource failing = resource(NAME, POOL);
|
||||
doThrow(new AwsException("InternalErrorException", "storage unavailable", 500))
|
||||
.when(cognito).deleteIdentityProvider(POOL, NAME);
|
||||
assertThrows(AwsException.class, () -> provisioner.delete(failing, "us-east-1"));
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,7 @@ AWS::Cognito::UserPool Arn,ProviderName,ProviderURL,UserPoolId AccountRecoverySe
|
||||
AWS::Cognito::UserPoolClient ClientId,ClientSecret,Name AccessTokenValidity,AllowedOAuthFlows,AllowedOAuthFlowsUserPoolClient,AllowedOAuthScopes,AnalyticsConfiguration,AuthSessionValidity,CallbackURLs,ClientName,DefaultRedirectURI,EnablePropagateAdditionalUserContextData,EnableTokenRevocation,ExplicitAuthFlows,GenerateSecret,IdTokenValidity,LogoutURLs,PreventUserExistenceErrors,ReadAttributes,RefreshTokenRotation,RefreshTokenValidity,SupportedIdentityProviders,TokenValidityUnits,UserPoolId,WriteAttributes
|
||||
AWS::Cognito::UserPoolDomain CloudFrontDistribution CustomDomainConfig,Domain,ManagedLoginVersion,Routing,UserPoolId
|
||||
AWS::Cognito::UserPoolGroup Description,GroupName,Precedence,RoleArn,UserPoolId
|
||||
AWS::Cognito::UserPoolIdentityProvider AttributeMapping,IdpIdentifiers,ProviderDetails,ProviderName,ProviderType,UserPoolId
|
||||
AWS::Cognito::UserPoolResourceServer Identifier,Name,Scopes,UserPoolId
|
||||
AWS::Cognito::UserPoolUser ClientMetadata,DesiredDeliveryMediums,ForceAliasCreation,MessageAction,UserAttributes,UserPoolId,Username,ValidationData
|
||||
AWS::Cognito::UserPoolUserToGroupAttachment GroupName,UserPoolId,Username
|
||||
|
||||
|
@@ -66,6 +66,7 @@ AWS::Cognito::UserPool CognitoCfnProvisioner
|
||||
AWS::Cognito::UserPoolClient CognitoCfnProvisioner
|
||||
AWS::Cognito::UserPoolDomain CognitoCfnProvisioner
|
||||
AWS::Cognito::UserPoolGroup CognitoUserPoolGroupCfnProvisioner
|
||||
AWS::Cognito::UserPoolIdentityProvider CognitoIdentityProviderCfnProvisioner
|
||||
AWS::Cognito::UserPoolResourceServer CognitoResourceServerCfnProvisioner
|
||||
AWS::Cognito::UserPoolUser CognitoUserPoolUserCfnProvisioner
|
||||
AWS::Cognito::UserPoolUserToGroupAttachment CognitoUserPoolUserToGroupAttachmentCfnProvisioner
|
||||
|
||||
|
@@ -213,6 +213,7 @@ notes:
|
||||
Custom::DynamoDBReplica: applied natively against DynamoDB, not via a provider Lambda
|
||||
AWS::DynamoDB::Table: '`TimeToLiveSpecification` applied on create and update; to rename an enabled TTL attribute, disable TTL in one update and enable the new attribute in a later one'
|
||||
AWS::Cognito::UserPool: '`ProviderURL` is the local issuer of the tokens Floci mints, `<base-url>/<pool id>`; `EnabledMfas` is applied with `SetUserPoolMfaConfig`, as on AWS, and once `SMS_MFA` is on only `MfaConfiguration: OFF` turns it off'
|
||||
AWS::Cognito::UserPoolIdentityProvider: 'Ref returns the ProviderName; changing only `ProviderType` is refused, as on AWS, because the name is always the template''s and the replacement would need the same address'
|
||||
AWS::SES::EmailIdentity: 'BYODKIM is not supported by this resource; Easy DKIM DNS attributes use the shared emulator signing zone `dkim.amazonses.com` rather than AWS''s region- and identity-specific zone assignment'
|
||||
AWS::SES::ReceiptRule: 'stored in an existing SES receipt rule set; Ref and RuleName return the rule name; management plane only, with no inbound mail delivery'
|
||||
AWS::Events::Archive: '`KmsKeyIdentifier` is ignored'
|
||||
|
||||
Reference in new issue
Block a user