Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(cognito): implement managed login branding (#2869)

Brian Taylor1e4e8b9ee80d
diff --git a/docs/services/cognito.md b/docs/services/cognito.md
index 54cc64c608..772e1afd51 100644
--- a/docs/services/cognito.md
+++ b/docs/services/cognito.md
@@ -145,6 +145,46 @@ further divergences, both deliberate:
| AdminRemoveUserFromGroup | Removes a user from a group. |
| AdminListGroupsForUser | Lists the groups assigned to a user. |
+### Managed Login Branding
+
+| Action | Description |
+|--------|-------------|
+| CreateManagedLoginBranding | Creates the branding for an app client. |
+| DescribeManagedLoginBranding | Returns a branding by its id. |
+| DescribeManagedLoginBrandingByClient | Returns the branding attached to an app client. |
+| UpdateManagedLoginBranding | Updates a branding's settings, assets or provided-values flag. |
+| DeleteManagedLoginBranding | Deletes a branding from its app client. |
+
+`CreateManagedLoginBranding` must name either `UseCognitoProvidedValues` or `Settings`; a
+request with neither is rejected. One branding per app client: a second
+`CreateManagedLoginBranding` for the same client is rejected with
+`ManagedLoginBrandingExistsException`. `ManagedLoginBrandingId` must be a
+version 4 UUID, and a malformed one is rejected before the lookup, as AWS does.
+`Assets` holds at most 40 entries on create and on update.
+`Settings` is omitted from the response when the caller supplied none, while `Assets` is
+always returned. Members an update omits are left unchanged.
+
+The asset-count and branding-id checks run before the pool, client or branding is looked
+up, so an oversized request naming something that does not exist reports the request
+problem rather than `ResourceNotFoundException`, and an update violating both reports them
+in one message with the asset list first.
+
+Branding is presentation for the hosted UI, which Floci does not serve, so it is stored
+and returned rather than rendered. Two divergences follow from that:
+
+- **`Settings` is stored opaquely.** AWS validates it against a deep schema, rejecting
+ unknown properties with `Invalid settings provided. Validation errors: [{property:
+ $.components...., errorType: UnknownProperty}]`. That schema is not published, so Floci
+ accepts any object.
+- **A wrongly typed `Settings` returns a client error.** AWS answers that particular input
+ with `InternalErrorException` and a 500; Floci returns
+ `SerializationException: Unexpected field type`, which is what AWS returns for a wrongly
+ typed `Assets`. Reproducing someone else's 500 seemed worse than being consistent.
+- **`ReturnMergedResources` is not honoured.** Against AWS it merges Cognito's own default
+ settings and assets into the response: on a pool with 8 configured assets it returns 38.
+ Reproducing that needs Cognito's default corpus, so Floci returns the stored branding
+ either way.
+
## Well-Known And OAuth Endpoints
| Endpoint | Description |
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java
index b7431f7791..bdca6f26bb 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java
@@ -15,12 +15,14 @@ import io.github.hectorvent.floci.services.cognito.model.UserPool;
import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
import io.github.hectorvent.floci.services.cognito.model.UserPoolClientSecret;
import io.github.hectorvent.floci.services.cognito.model.UserPoolDomain;
+import io.github.hectorvent.floci.services.cognito.model.ManagedLoginBranding;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.HashMap;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -75,6 +77,11 @@ public class CognitoJsonHandler {
case "AdminEnableUser" -> handleAdminEnableUser(request);
case "AdminDisableUser" -> handleAdminDisableUser(request);
case "AdminLinkProviderForUser" -> handleAdminLinkProviderForUser(request);
+ case "CreateManagedLoginBranding" -> handleCreateManagedLoginBranding(request);
+ case "DescribeManagedLoginBranding" -> handleDescribeManagedLoginBranding(request);
+ case "DescribeManagedLoginBrandingByClient" -> handleDescribeManagedLoginBrandingByClient(request);
+ case "UpdateManagedLoginBranding" -> handleUpdateManagedLoginBranding(request);
+ case "DeleteManagedLoginBranding" -> handleDeleteManagedLoginBranding(request);
case "ListUsers" -> handleListUsers(request);
case "InitiateAuth" -> handleInitiateAuth(request);
case "AdminInitiateAuth" -> handleAdminInitiateAuth(request);
@@ -555,6 +562,139 @@ public class CognitoJsonHandler {
return Response.ok(objectMapper.createObjectNode()).build();
}
+ /**
+ * AWS coerces a JSON string in this member instead of rejecting it, and rejects every
+ * other non-boolean type. Measured against Cognito in ap-southeast-1:
+ *
+ * <pre>
+ * absent accepted, stored false
+ * true / false accepted as given
+ * "true", "yes" accepted, stored true
+ * "false" accepted, stored false
+ * 1, null, {}, [] SerializationException
+ * </pre>
+ *
+ * <p>Jackson would map all of those last four to false through {@code asBoolean()},
+ * which is how a malformed flag used to be accepted alongside valid settings and
+ * persisted as unintended branding state.
+ */
+ private static Boolean readUseCognitoProvidedValues(JsonNode request) {
+ if (!request.has("UseCognitoProvidedValues")) {
+ return null;
+ }
+ JsonNode node = request.path("UseCognitoProvidedValues");
+ if (node.isBoolean()) {
+ return node.booleanValue();
+ }
+ if (node.isTextual()) {
+ return !"false".equalsIgnoreCase(node.asText());
+ }
+ throw new AwsException("SerializationException", null, 400);
+ }
+
+ private Response handleCreateManagedLoginBranding(JsonNode request) {
+ ManagedLoginBranding branding = service.createManagedLoginBranding(
+ request.path("UserPoolId").asText(),
+ request.path("ClientId").asText(),
+ readUseCognitoProvidedValues(request),
+ readObjectMap(request, "Settings"),
+ readMapList(request, "Assets")
+ );
+ return brandingResponse(branding);
+ }
+
+ private Response handleDescribeManagedLoginBranding(JsonNode request) {
+ return brandingResponse(service.describeManagedLoginBranding(
+ request.path("UserPoolId").asText(),
+ request.path("ManagedLoginBrandingId").asText(null)));
+ }
+
+ private Response handleDescribeManagedLoginBrandingByClient(JsonNode request) {
+ return brandingResponse(service.describeManagedLoginBrandingByClient(
+ request.path("UserPoolId").asText(),
+ request.path("ClientId").asText()));
+ }
+
+ private Response handleUpdateManagedLoginBranding(JsonNode request) {
+ return brandingResponse(service.updateManagedLoginBranding(
+ request.path("UserPoolId").asText(),
+ request.path("ManagedLoginBrandingId").asText(null),
+ readUseCognitoProvidedValues(request),
+ readObjectMap(request, "Settings"),
+ readMapList(request, "Assets")));
+ }
+
+ private Response handleDeleteManagedLoginBranding(JsonNode request) {
+ service.deleteManagedLoginBranding(
+ request.path("UserPoolId").asText(),
+ request.path("ManagedLoginBrandingId").asText(null));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ private Response brandingResponse(ManagedLoginBranding branding) {
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("ManagedLoginBranding", managedLoginBrandingToNode(branding));
+ return Response.ok(response).build();
+ }
+
+ /** AWS omits Settings entirely when none was supplied, but always returns Assets. */
+ private ObjectNode managedLoginBrandingToNode(ManagedLoginBranding branding) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("ManagedLoginBrandingId", branding.getManagedLoginBrandingId());
+ node.put("UserPoolId", branding.getUserPoolId());
+ node.put("UseCognitoProvidedValues", branding.isUseCognitoProvidedValues());
+ if (branding.getSettings() != null) {
+ node.set("Settings", objectMapper.valueToTree(branding.getSettings()));
+ }
+ ArrayNode assets = node.putArray("Assets");
+ branding.getAssets().forEach(asset -> assets.add(objectMapper.valueToTree(asset)));
+ node.put("CreationDate", branding.getCreationDate());
+ node.put("LastModifiedDate", branding.getLastModifiedDate());
+ return node;
+ }
+
+ /** Absent or null yields null; a value of the wrong JSON type is a deserialization failure. */
+ private Map<String, Object> readObjectMap(JsonNode request, String member) {
+ JsonNode node = request.get(member);
+ if (node == null || node.isNull()) {
+ return null;
+ }
+ if (!node.isObject()) {
+ throw new AwsException("SerializationException", "Unexpected field type", 400);
+ }
+ return objectMapper.convertValue(node, new TypeReference<LinkedHashMap<String, Object>>() {});
+ }
+
+ /**
+ * Elements are checked before conversion so a scalar cannot escape as an IllegalArgumentException.
+ * AWS separates the two failures: a null element is a validation error, a non-object element a
+ * deserialization one. Note this differs from LogConfigurations, where a null element is dropped.
+ */
+ private List<Map<String, Object>> readMapList(JsonNode request, String member) {
+ JsonNode node = request.get(member);
+ if (node == null || node.isNull()) {
+ return null;
+ }
+ if (!node.isArray()) {
+ throw new AwsException("SerializationException", "Unexpected field type", 400);
+ }
+ List<Map<String, Object>> values = new ArrayList<>();
+ for (JsonNode element : node) {
+ if (element.isNull()) {
+ throw new AwsException("InvalidParameterException",
+ "1 validation error detected: Value '" + node + "' at '"
+ + Character.toLowerCase(member.charAt(0)) + member.substring(1)
+ + "' failed to satisfy constraint: Member must satisfy constraint: "
+ + "[Member must not be null]", 400);
+ }
+ if (!element.isObject()) {
+ throw new AwsException("SerializationException", "Unexpected value type in payload", 400);
+ }
+ values.add(objectMapper.convertValue(element, new TypeReference<Map<String, Object>>() {}));
+ }
+ return values;
+ }
+
private Response handleAdminLinkProviderForUser(JsonNode request) {
JsonNode sourceUser = request.path("SourceUser");
service.adminLinkProviderForUser(
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java
index fedc5faa1c..4fd8f9d272 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java
@@ -25,6 +25,7 @@ import io.github.hectorvent.floci.services.cognito.model.UserPool;
import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
import io.github.hectorvent.floci.services.cognito.model.UserPoolClientSecret;
import io.github.hectorvent.floci.services.cognito.model.UserPoolDomain;
+import io.github.hectorvent.floci.services.cognito.model.ManagedLoginBranding;
import io.github.hectorvent.floci.services.cognito.verification.CognitoMessageDispatcher;
import io.github.hectorvent.floci.services.cognito.verification.VerificationCode;
import io.github.hectorvent.floci.services.cognito.verification.VerificationCodeException;
@@ -68,6 +69,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
+import java.util.regex.Pattern;
import static io.github.hectorvent.floci.core.common.ReservedTags.rejectUnknownReservedTags;
@@ -1499,6 +1501,188 @@ public class CognitoService implements ResourceProvider {
};
}
+ // ──────────────────────────── Managed Login Branding ────────────────────────────
+
+ private static final Pattern BRANDING_ID_PATTERN = Pattern.compile(
+ "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[4][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$");
+ private static final int MAX_BRANDING_ASSETS = 40;
+
+ public ManagedLoginBranding createManagedLoginBranding(String userPoolId, String clientId,
+ Boolean useCognitoProvidedValues,
+ Map<String, Object> settings,
+ List<Map<String, Object>> assets) {
+ List<String> errors = new ArrayList<>();
+ collectAssetsLengthError(errors, assets);
+ throwBrandingValidationErrors(errors);
+
+ UserPoolClient client = describeUserPoolClient(userPoolId, clientId);
+ validateBrandingSource(useCognitoProvidedValues, settings);
+ if (client.getManagedLoginBranding() != null) {
+ throw new AwsException("ManagedLoginBrandingExistsException",
+ "A ManagedLoginBranding already exists for client " + clientId, 400);
+ }
+
+ ManagedLoginBranding branding = new ManagedLoginBranding();
+ branding.setManagedLoginBrandingId(UUID.randomUUID().toString());
+ branding.setUserPoolId(userPoolId);
+ branding.setUseCognitoProvidedValues(Boolean.TRUE.equals(useCognitoProvidedValues));
+ branding.setSettings(settings);
+ branding.setAssets(assets);
+ client.setManagedLoginBranding(branding);
+ clientStore.put(clientId, client);
+ return branding;
+ }
+
+ public ManagedLoginBranding describeManagedLoginBranding(String userPoolId, String brandingId) {
+ List<String> errors = new ArrayList<>();
+ collectBrandingIdError(errors, brandingId);
+ throwBrandingValidationErrors(errors);
+
+ describeUserPool(userPoolId);
+ return findBrandingClient(userPoolId, brandingId).getManagedLoginBranding();
+ }
+
+ public ManagedLoginBranding describeManagedLoginBrandingByClient(String userPoolId, String clientId) {
+ UserPoolClient client = describeUserPoolClient(userPoolId, clientId);
+ ManagedLoginBranding branding = client.getManagedLoginBranding();
+ if (branding == null) {
+ throw new AwsException("ResourceNotFoundException",
+ "ManagedLoginBranding for client " + clientId + " does not exist.", 400);
+ }
+ return branding;
+ }
+
+ /**
+ * Members the request omits are left as they were, matching the identity provider update
+ * semantics; an explicitly empty list or map is what clears them.
+ */
+ public ManagedLoginBranding updateManagedLoginBranding(String userPoolId, String brandingId,
+ Boolean useCognitoProvidedValues,
+ Map<String, Object> settings,
+ List<Map<String, Object>> assets) {
+ List<String> errors = new ArrayList<>();
+ collectAssetsLengthError(errors, assets);
+ collectBrandingIdError(errors, brandingId);
+ throwBrandingValidationErrors(errors);
+
+ describeManagedLoginBranding(userPoolId, brandingId);
+ validateBrandingSource(useCognitoProvidedValues, settings);
+ UserPoolClient client = findBrandingClient(userPoolId, brandingId);
+ ManagedLoginBranding branding = client.getManagedLoginBranding();
+
+ if (useCognitoProvidedValues != null) {
+ branding.setUseCognitoProvidedValues(useCognitoProvidedValues);
+ }
+ if (settings != null) {
+ branding.setSettings(settings);
+ }
+ if (assets != null) {
+ branding.setAssets(assets);
+ }
+ branding.setLastModifiedDate(System.currentTimeMillis() / 1000L);
+ clientStore.put(client.getClientId(), client);
+ return branding;
+ }
+
+ /**
+ * A branding request must select exactly one source of branding, and the same rule
+ * applies to create and to update. Measured against Cognito in ap-southeast-1:
+ *
+ * <pre>
+ * useCognitoProvidedValues settings result
+ * absent absent InvalidParameterException
+ * true absent accepted
+ * false absent InvalidParameterException
+ * absent present accepted
+ * true present InvalidParameterException
+ * false present accepted
+ * </pre>
+ *
+ * <p>So the member being present is not what counts: {@code false} selects no source,
+ * which is why it is rejected unless settings supply one.
+ */
+ private void validateBrandingSource(Boolean useCognitoProvidedValues, Map<String, Object> settings) {
+ if (Boolean.TRUE.equals(useCognitoProvidedValues) == (settings != null)) {
+ throw new AwsException("InvalidParameterException",
+ "useCognitoProvidedValues or settings should be specified (but not both)", 400);
+ }
+ }
+
+ /**
+ * The shape checks AWS runs before it looks anything up, so an oversized asset list against a
+ * client or a branding id that does not exist reports the request problem rather than the
+ * missing resource. Measured against Cognito in ap-southeast-1: 41 assets with an unknown
+ * client reports the asset list, and 41 assets with a malformed branding id reports both, the
+ * asset list first.
+ */
+ private void collectAssetsLengthError(List<String> errors, List<Map<String, Object>> assets) {
+ if (assets != null && assets.size() > MAX_BRANDING_ASSETS) {
+ errors.add("Value '" + renderAssets(assets) + "' at 'assets' failed to satisfy constraint: "
+ + "Member must have length less than or equal to " + MAX_BRANDING_ASSETS);
+ }
+ }
+
+ private void collectBrandingIdError(List<String> errors, String brandingId) {
+ if (brandingId == null || !BRANDING_ID_PATTERN.matcher(brandingId).matches()) {
+ errors.add("Value '" + brandingId + "' at 'managedLoginBrandingId' failed to satisfy "
+ + "constraint: Member must satisfy regular expression pattern: "
+ + BRANDING_ID_PATTERN.pattern());
+ }
+ }
+
+ private void throwBrandingValidationErrors(List<String> errors) {
+ if (errors.isEmpty()) {
+ return;
+ }
+ String header = errors.size() == 1
+ ? "1 validation error detected: "
+ : errors.size() + " validation errors detected: ";
+ throw new AwsException("InvalidParameterException", header + String.join("; ", errors), 400);
+ }
+
+ /** Mirrors the request model's {@code toString}, which AWS embeds in the length-constraint message. */
+ private String renderAssets(List<Map<String, Object>> assets) {
+ List<String> rendered = new ArrayList<>();
+ for (Map<String, Object> asset : assets) {
+ rendered.add("AssetType(category=" + asset.get("Category")
+ + ", colorMode=" + asset.get("ColorMode")
+ + ", extension=" + asset.get("Extension")
+ + ", bytes=" + renderAssetBytes(asset.get("Bytes"))
+ + ", resourceId=" + asset.get("ResourceId") + ")");
+ }
+ return "[" + String.join(", ", rendered) + "]";
+ }
+
+ /**
+ * AWS renders the blob as the buffer it decoded, so the reported length is the decoded byte
+ * count rather than the base64 string's. The lenient decoder is deliberate: this runs while
+ * building a rejection, and must not raise a second failure of its own.
+ */
+ private String renderAssetBytes(Object bytes) {
+ if (bytes == null) {
+ return "null";
+ }
+ int length = Base64.getMimeDecoder().decode(String.valueOf(bytes)).length;
+ return "java.nio.HeapByteBuffer[pos=0 lim=" + length + " cap=" + length + "]";
+ }
+
+ public void deleteManagedLoginBranding(String userPoolId, String brandingId) {
+ describeManagedLoginBranding(userPoolId, brandingId);
+ UserPoolClient client = findBrandingClient(userPoolId, brandingId);
+ client.setManagedLoginBranding(null);
+ clientStore.put(client.getClientId(), client);
+ }
+
+ private UserPoolClient findBrandingClient(String userPoolId, String brandingId) {
+ return clientStore.scan(k -> true).stream()
+ .filter(c -> userPoolId.equals(c.getUserPoolId())
+ && c.getManagedLoginBranding() != null
+ && brandingId.equals(c.getManagedLoginBranding().getManagedLoginBrandingId()))
+ .findFirst()
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException",
+ "ManagedLoginBranding does not exist.", 400));
+ }
+
// ──────────────────────────── Groups ────────────────────────────
public CognitoGroup createGroup(String userPoolId, String groupName, String description,
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/ManagedLoginBranding.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/ManagedLoginBranding.java
new file mode 100644
index 0000000000..f52525ac0c
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/ManagedLoginBranding.java
@@ -0,0 +1,57 @@
+package io.github.hectorvent.floci.services.cognito.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class ManagedLoginBranding {
+ private String managedLoginBrandingId;
+ private String userPoolId;
+ private boolean useCognitoProvidedValues;
+ /** Null when the caller supplied none; AWS omits Settings from the response in that case. */
+ private Map<String, Object> settings;
+ private List<Map<String, Object>> assets = new ArrayList<>();
+ private long creationDate;
+ private long lastModifiedDate;
+
+ public ManagedLoginBranding() {
+ long now = System.currentTimeMillis() / 1000L;
+ this.creationDate = now;
+ this.lastModifiedDate = now;
+ }
+
+ public String getManagedLoginBrandingId() { return managedLoginBrandingId; }
+ public void setManagedLoginBrandingId(String managedLoginBrandingId) {
+ this.managedLoginBrandingId = managedLoginBrandingId;
+ }
+
+ public String getUserPoolId() { return userPoolId; }
+ public void setUserPoolId(String userPoolId) { this.userPoolId = userPoolId; }
+
+ public boolean isUseCognitoProvidedValues() { return useCognitoProvidedValues; }
+ public void setUseCognitoProvidedValues(boolean useCognitoProvidedValues) {
+ this.useCognitoProvidedValues = useCognitoProvidedValues;
+ }
+
+ public Map<String, Object> getSettings() { return settings; }
+ public void setSettings(Map<String, Object> settings) {
+ this.settings = settings == null ? null : new LinkedHashMap<>(settings);
+ }
+
+ public List<Map<String, Object>> getAssets() { return assets; }
+ public void setAssets(List<Map<String, Object>> assets) {
+ this.assets = assets == null ? new ArrayList<>() : new ArrayList<>(assets);
+ }
+
+ public long getCreationDate() { return creationDate; }
+ public void setCreationDate(long creationDate) { this.creationDate = creationDate; }
+
+ public long getLastModifiedDate() { return lastModifiedDate; }
+ public void setLastModifiedDate(long lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPoolClient.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPoolClient.java
index 6554cf8f0e..b3ec49f90a 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPoolClient.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPoolClient.java
@@ -37,6 +37,9 @@ public class UserPoolClient {
private long creationDate;
private long lastModifiedDate;
+ /** One managed login branding per client, or null when none has been created. */
+ private ManagedLoginBranding managedLoginBranding;
+
public UserPoolClient() {
long now = System.currentTimeMillis() / 1000L;
this.creationDate = now;
@@ -136,4 +139,9 @@ public class UserPoolClient {
public long getLastModifiedDate() { return lastModifiedDate; }
public void setLastModifiedDate(long lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; }
+
+ public ManagedLoginBranding getManagedLoginBranding() { return managedLoginBranding; }
+ public void setManagedLoginBranding(ManagedLoginBranding managedLoginBranding) {
+ this.managedLoginBranding = managedLoginBranding;
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginBrandingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginBrandingIntegrationTest.java
new file mode 100644
index 0000000000..ed3ae4a6b7
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginBrandingIntegrationTest.java
@@ -0,0 +1,661 @@
+package io.github.hectorvent.floci.services.cognito;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+
+import java.util.UUID;
+
+import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;
+import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Covers CreateManagedLoginBranding, DescribeManagedLoginBranding,
+ * DescribeManagedLoginBrandingByClient, UpdateManagedLoginBranding and
+ * DeleteManagedLoginBranding.
+ *
+ * <p>Response shapes and error messages were measured against the live Cognito API. In
+ * particular {@code Settings} is omitted entirely when the caller supplied none, while
+ * {@code Assets} is always returned.
+ */
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class CognitoManagedLoginBrandingIntegrationTest {
+
+ private static String poolId;
+ private static String clientId;
+ private static String brandingId;
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ @Order(1)
+ void createPoolAndClient() throws Exception {
+ poolId = cognitoJson("CreateUserPool", """
+ {
+ "PoolName": "BrandingTestPool"
+ }
+ """).path("UserPool").path("Id").asText();
+
+ clientId = cognitoJson("CreateUserPoolClient", """
+ {
+ "UserPoolId": "%s",
+ "ClientName": "branding-client"
+ }
+ """.formatted(poolId)).path("UserPoolClient").path("ClientId").asText();
+ }
+
+ @Test
+ @Order(2)
+ void describeByClientBeforeAnyBrandingExists() {
+ cognitoAction("DescribeManagedLoginBrandingByClient", """
+ {
+ "UserPoolId": "%s",
+ "ClientId": "%s"
+ }
+ """.formatted(poolId, clientId))
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("ResourceNotFoundException"))
+ .body("message", equalTo(
+ "ManagedLoginBranding for client " + clientId + " does not exist."));
+ }
+
+ @Test
+ @Order(3)
+ void createWithCognitoProvidedValuesOmitsSettings() throws Exception {
+ JsonNode branding = cognitoJson("CreateManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ClientId": "%s",
+ "UseCognitoProvidedValues": true
+ }
+ """.formatted(poolId, clientId)).path("ManagedLoginBranding");
+
+ brandingId = branding.path("ManagedLoginBrandingId").asText();
+ assertTrue(branding.path("Settings").isMissingNode(),
+ "AWS omits Settings when the caller supplied none");
+ assertTrue(branding.path("Assets").isArray(), "Assets is always returned");
+ assertEquals(0, branding.path("Assets").size());
+ assertTrue(branding.path("UseCognitoProvidedValues").asBoolean());
+ assertEquals(poolId, branding.path("UserPoolId").asText());
+ }
+
+ @Test
+ @Order(4)
+ void createRejectsASecondBrandingForTheSameClient() {
+ cognitoAction("CreateManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ClientId": "%s",
+ "UseCognitoProvidedValues": true
+ }
+ """.formatted(poolId, clientId))
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("ManagedLoginBrandingExistsException"))
+ .body("message", equalTo(
+ "A ManagedLoginBranding already exists for client " + clientId));
+ }
+
+ @Test
+ @Order(5)
+ void describeByIdReturnsTheSameBranding() throws Exception {
+ JsonNode branding = cognitoJson("DescribeManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ManagedLoginBrandingId": "%s"
+ }
+ """.formatted(poolId, brandingId)).path("ManagedLoginBranding");
+
+ assertEquals(brandingId, branding.path("ManagedLoginBrandingId").asText());
+ assertTrue(branding.path("Settings").isMissingNode());
+ }
+
+ @Test
+ @Order(6)
+ void describeRejectsAnIdThatIsNotAVersion4Uuid() {
+ cognitoAction("DescribeManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ManagedLoginBrandingId": "00000000-0000-0000-0000-000000000000"
+ }
+ """.formatted(poolId))
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("InvalidParameterException"));
+ }
+
+ @Test
+ @Order(7)
+ void describeReportsAWellFormedButUnknownId() {
+ cognitoAction("DescribeManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ManagedLoginBrandingId": "%s"
+ }
+ """.formatted(poolId, UUID.randomUUID()))
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("ResourceNotFoundException"))
+ .body("message", equalTo("ManagedLoginBranding does not exist."));
+ }
+
+ @Test
+ @Order(8)
+ void updateSetsSettingsAndAssets() throws Exception {
+ JsonNode branding = cognitoJson("UpdateManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ManagedLoginBrandingId": "%s",
+ "UseCognitoProvidedValues": false,
+ "Settings": {"components": {}},
+ "Assets": [
+ {"Category": "FAVICON_SVG", "ColorMode": "DARK", "Extension": "SVG", "Bytes": "PHN2Zy8+"}
+ ]
+ }
+ """.formatted(poolId, brandingId)).path("ManagedLoginBranding");
+
+ assertTrue(branding.path("Settings").isObject());
+ assertEquals(1, branding.path("Assets").size());
+ assertEquals("FAVICON_SVG", branding.path("Assets").get(0).path("Category").asText());
+
+ JsonNode readBack = cognitoJson("DescribeManagedLoginBrandingByClient", """
+ {
+ "UserPoolId": "%s",
+ "ClientId": "%s"
+ }
+ """.formatted(poolId, clientId)).path("ManagedLoginBranding");
+ assertEquals(1, readBack.path("Assets").size());
+ }
+
+ @Test
+ @Order(9)
+ void updateLeavesOmittedMembersAlone() throws Exception {
+ // Settings alone is the legal way to touch one member: AWS rejects an update whose
+ // only branding member is UseCognitoProvidedValues=false, because false selects no
+ // source. See validateBrandingSource for the measured matrix.
+ cognitoJson("UpdateManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ManagedLoginBrandingId": "%s",
+ "Settings": {"components": {}}
+ }
+ """.formatted(poolId, brandingId));
+
+ JsonNode branding = cognitoJson("DescribeManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ManagedLoginBrandingId": "%s"
+ }
+ """.formatted(poolId, brandingId)).path("ManagedLoginBranding");
+
+ assertEquals(1, branding.path("Assets").size(), "omitting Assets must not clear them");
+ assertTrue(branding.path("Settings").isObject(), "omitting Settings must not clear it");
+ }
+
+ @Test
+ @Order(10)
+ void createRejectsAnUnknownClient() {
+ cognitoAction("CreateManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ClientId": "nosuchclientid",
+ "UseCognitoProvidedValues": true
+ }
+ """.formatted(poolId))
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("ResourceNotFoundException"));
+ }
+
+ /**
+ * Measured against AWS: a create naming neither member is rejected, a wrongly typed Assets
+ * is a deserialization failure, and a non-boolean UseCognitoProvidedValues is accepted
+ * rather than rejected.
+ */
+ @Test
+ @Order(11)
+ void malformedCreateMembersMatchAwsHandling() throws Exception {
+ String otherClient = cognitoJson("CreateUserPoolClient", """
+ {
+ "UserPoolId": "%s",
+ "ClientName": "branding-client-2"
+ }
+ """.formatted(poolId)).path("UserPoolClient").path("ClientId").asText();
+
+ cognitoAction("CreateManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ClientId": "%s"
+ }
+ """.formatted(poolId, otherClient))
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("InvalidParameterException"))
+ .body("message", equalTo(
+ "useCognitoProvidedValues or settings should be specified (but not both)"));
+
+ cognitoAction("CreateManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ClientId": "%s",
+ "UseCognitoProvidedValues": true,
+ "Assets": "nope"
+ }
+ """.formatted(poolId, otherClient))
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("SerializationException"));
+
+ cognitoAction("CreateManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ClientId": "%s",
+ "UseCognitoProvidedValues": true,
+ "Assets": [1, 2]
+ }
+ """.formatted(poolId, otherClient))
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("SerializationException"))
+ .body("message", equalTo("Unexpected value type in payload"));
+
+ cognitoAction("CreateManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ClientId": "%s",
+ "UseCognitoProvidedValues": true,
+ "Assets": [null]
+ }
+ """.formatted(poolId, otherClient))
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("InvalidParameterException"))
+ .body("message", equalTo(
+ "1 validation error detected: Value '[null]' at 'assets' failed to satisfy "
+ + "constraint: Member must satisfy constraint: [Member must not be null]"));
+
+ JsonNode coerced = cognitoJson("CreateManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ClientId": "%s",
+ "UseCognitoProvidedValues": "yes"
+ }
+ """.formatted(poolId, otherClient)).path("ManagedLoginBranding");
+ assertTrue(coerced.path("ManagedLoginBrandingId").isTextual(),
+ "AWS accepts a non-boolean UseCognitoProvidedValues rather than rejecting it");
+
+ cognitoAction("DeleteManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ManagedLoginBrandingId": "%s"
+ }
+ """.formatted(poolId, coerced.path("ManagedLoginBrandingId").asText()))
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ @Order(12)
+ void deleteRemovesTheBranding() {
+ cognitoAction("DeleteManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ManagedLoginBrandingId": "%s"
+ }
+ """.formatted(poolId, brandingId))
+ .then()
+ .statusCode(200);
+
+ cognitoAction("DescribeManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ManagedLoginBrandingId": "%s"
+ }
+ """.formatted(poolId, brandingId))
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("ResourceNotFoundException"));
+ }
+
+ /**
+ * A branding request must select exactly one source. Measured against Cognito in
+ * ap-southeast-1: naming both, naming neither, and naming only
+ * {@code UseCognitoProvidedValues=false} are all rejected with the same message,
+ * on create and on update alike.
+ */
+ @Test
+ @Order(13)
+ void brandingSourceMustBeExactlyOne() throws Exception {
+ String message = "useCognitoProvidedValues or settings should be specified (but not both)";
+
+ String freshClient = cognitoJson("CreateUserPoolClient", """
+ {
+ "UserPoolId": "%s",
+ "ClientName": "branding-source-client"
+ }
+ """.formatted(poolId)).path("UserPoolClient").path("ClientId").asText();
+
+ // Own the branding this test updates: the shared brandingId is deleted earlier.
+ String ownBrandingId = cognitoJson("CreateManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ClientId": "%s",
+ "UseCognitoProvidedValues": true
+ }
+ """.formatted(poolId, freshClient))
+ .path("ManagedLoginBranding").path("ManagedLoginBrandingId").asText();
+
+ String bareClient = cognitoJson("CreateUserPoolClient", """
+ {
+ "UserPoolId": "%s",
+ "ClientName": "branding-source-bare"
+ }
+ """.formatted(poolId)).path("UserPoolClient").path("ClientId").asText();
+
+ cognitoAction("CreateManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ClientId": "%s",
+ "UseCognitoProvidedValues": true,
+ "Settings": {"components": {}}
+ }
+ """.formatted(poolId, bareClient))
+ .then().statusCode(400).body("message", equalTo(message));
+
+ cognitoAction("CreateManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ClientId": "%s",
+ "UseCognitoProvidedValues": false
+ }
+ """.formatted(poolId, bareClient))
+ .then().statusCode(400).body("message", equalTo(message));
+
+ cognitoAction("UpdateManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ManagedLoginBrandingId": "%s",
+ "UseCognitoProvidedValues": true,
+ "Settings": {"components": {}}
+ }
+ """.formatted(poolId, ownBrandingId))
+ .then().statusCode(400).body("message", equalTo(message));
+
+ cognitoAction("UpdateManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ManagedLoginBrandingId": "%s"
+ }
+ """.formatted(poolId, ownBrandingId))
+ .then().statusCode(400).body("message", equalTo(message));
+
+ cognitoAction("UpdateManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ManagedLoginBrandingId": "%s",
+ "Assets": []
+ }
+ """.formatted(poolId, ownBrandingId))
+ .then().statusCode(400).body("message", equalTo(message));
+
+ // false plus settings selects settings, so it is accepted.
+ cognitoAction("UpdateManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ManagedLoginBrandingId": "%s",
+ "UseCognitoProvidedValues": false,
+ "Settings": {"components": {}}
+ }
+ """.formatted(poolId, ownBrandingId))
+ .then().statusCode(200);
+ }
+
+ /**
+ * Every non-boolean, non-string type in this member is a SerializationException at
+ * the service, including alongside otherwise valid Settings. Measured in
+ * ap-southeast-1: 1, JSON null, {} and [] are all rejected, while omitting the
+ * member entirely is accepted and stores false.
+ */
+ @Test
+ @Order(14)
+ void malformedUseCognitoProvidedValuesTypesAreRejected() throws Exception {
+ for (String malformed : new String[] {"1", "null", "{}", "[]"}) {
+ String client = cognitoJson("CreateUserPoolClient", """
+ {
+ "UserPoolId": "%s",
+ "ClientName": "malformed-flag-%s"
+ }
+ """.formatted(poolId, Integer.toHexString(malformed.hashCode())))
+ .path("UserPoolClient").path("ClientId").asText();
+
+ cognitoAction("CreateManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ClientId": "%s",
+ "UseCognitoProvidedValues": %s,
+ "Settings": {"components": {}}
+ }
+ """.formatted(poolId, client, malformed))
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("SerializationException"));
+ }
+
+ // Omitting the member is not malformed: settings alone select the source.
+ String ok = cognitoJson("CreateUserPoolClient", """
+ {
+ "UserPoolId": "%s",
+ "ClientName": "malformed-flag-control"
+ }
+ """.formatted(poolId)).path("UserPoolClient").path("ClientId").asText();
+ cognitoAction("CreateManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ClientId": "%s",
+ "Settings": {"components": {}}
+ }
+ """.formatted(poolId, ok))
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ @Order(15)
+ void createRejectsMoreThanFortyAssets() {
+ cognitoAction("CreateManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ClientId": "%s",
+ "Settings": {"components": {}},
+ "Assets": %s
+ }
+ """.formatted(poolId, clientId, assetArray(41)))
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("InvalidParameterException"))
+ .body("message", equalTo(
+ "1 validation error detected: Value '" + renderedAssets(41)
+ + "' at 'assets' failed to satisfy constraint: "
+ + "Member must have length less than or equal to 40"));
+ }
+
+ @Test
+ @Order(16)
+ void fortyAssetsAreAccepted() throws Exception {
+ String extraClient = cognitoJson("CreateUserPoolClient", """
+ {
+ "UserPoolId": "%s",
+ "ClientName": "forty-asset-client"
+ }
+ """.formatted(poolId)).path("UserPoolClient").path("ClientId").asText();
+
+ cognitoAction("CreateManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ClientId": "%s",
+ "Settings": {"components": {}},
+ "Assets": %s
+ }
+ """.formatted(poolId, extraClient, assetArray(40)))
+ .then()
+ .statusCode(200)
+ .body("ManagedLoginBranding.Assets.size()", equalTo(40));
+ }
+
+ @Test
+ @Order(17)
+ void updateRejectsMoreThanFortyAssets() {
+ cognitoAction("UpdateManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ManagedLoginBrandingId": "%s",
+ "Settings": {"components": {}},
+ "Assets": %s
+ }
+ """.formatted(poolId, brandingId, assetArray(41)))
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("InvalidParameterException"))
+ .body("message", equalTo(
+ "1 validation error detected: Value '" + renderedAssets(41)
+ + "' at 'assets' failed to satisfy constraint: "
+ + "Member must have length less than or equal to 40"));
+ }
+
+ @Test
+ @Order(18)
+ void theAssetViolationIsReportedAheadOfTheBrandingIdViolation() {
+ cognitoAction("UpdateManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ManagedLoginBrandingId": "not-a-uuid",
+ "Settings": {"components": {}},
+ "Assets": %s
+ }
+ """.formatted(poolId, assetArray(41)))
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("InvalidParameterException"))
+ .body("message", equalTo(
+ "2 validation errors detected: Value '" + renderedAssets(41)
+ + "' at 'assets' failed to satisfy constraint: "
+ + "Member must have length less than or equal to 40; "
+ + "Value 'not-a-uuid' at 'managedLoginBrandingId' failed to satisfy "
+ + "constraint: Member must satisfy regular expression pattern: "
+ + BRANDING_ID_PATTERN));
+ }
+
+ @Test
+ @Order(19)
+ void shapeViolationsAreReportedBeforeTheMissingPool() {
+ cognitoAction("DescribeManagedLoginBranding", """
+ {
+ "UserPoolId": "us-east-1_nosuchpool",
+ "ManagedLoginBrandingId": "not-a-uuid"
+ }
+ """)
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("InvalidParameterException"))
+ .body("message", equalTo(
+ "1 validation error detected: Value 'not-a-uuid' at 'managedLoginBrandingId' "
+ + "failed to satisfy constraint: Member must satisfy regular expression "
+ + "pattern: " + BRANDING_ID_PATTERN));
+ }
+
+ @Test
+ @Order(20)
+ void aRejectedUpdateLeavesTheAssetsAlone() throws Exception {
+ String client = cognitoJson("CreateUserPoolClient", """
+ {
+ "UserPoolId": "%s",
+ "ClientName": "rejected-update-client"
+ }
+ """.formatted(poolId)).path("UserPoolClient").path("ClientId").asText();
+ String branding = cognitoJson("CreateManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ClientId": "%s",
+ "Settings": {"components": {}},
+ "Assets": %s
+ }
+ """.formatted(poolId, client, assetArray(1)))
+ .path("ManagedLoginBranding").path("ManagedLoginBrandingId").asText();
+
+ cognitoAction("UpdateManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ManagedLoginBrandingId": "%s",
+ "Settings": {"components": {}},
+ "Assets": %s
+ }
+ """.formatted(poolId, branding, assetArray(41)))
+ .then()
+ .statusCode(400);
+
+ JsonNode readBack = cognitoJson("DescribeManagedLoginBranding", """
+ {
+ "UserPoolId": "%s",
+ "ManagedLoginBrandingId": "%s"
+ }
+ """.formatted(poolId, branding)).path("ManagedLoginBranding");
+ assertEquals(1, readBack.path("Assets").size(), "a rejected update must not replace the assets");
+ }
+
+ @Test
+ @Order(21)
+ void deletePool() {
+ cognitoAction("DeleteUserPool", """
+ {
+ "UserPoolId": "%s"
+ }
+ """.formatted(poolId))
+ .then()
+ .statusCode(200);
+ }
+
+ private static final String BRANDING_ID_PATTERN =
+ "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[4][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$";
+
+ /** A one-byte payload, so the rendered buffer length stays easy to read. */
+ private static final String ASSET_BYTES = "AA==";
+
+ private static String assetArray(int count) {
+ StringBuilder json = new StringBuilder("[");
+ for (int i = 0; i < count; i++) {
+ if (i > 0) {
+ json.append(", ");
+ }
+ json.append("{\"Category\": \"PAGE_HEADER_LOGO\", \"ColorMode\": \"LIGHT\", ")
+ .append("\"Extension\": \"PNG\", \"Bytes\": \"").append(ASSET_BYTES)
+ .append("\", \"ResourceId\": \"asset-").append(i).append("\"}");
+ }
+ return json.append("]").toString();
+ }
+
+ private static String renderedAssets(int count) {
+ StringBuilder rendered = new StringBuilder("[");
+ for (int i = 0; i < count; i++) {
+ if (i > 0) {
+ rendered.append(", ");
+ }
+ rendered.append("AssetType(category=PAGE_HEADER_LOGO, colorMode=LIGHT, extension=PNG, ")
+ .append("bytes=java.nio.HeapByteBuffer[pos=0 lim=1 cap=1], resourceId=asset-")
+ .append(i).append(")");
+ }
+ return rendered.append("]").toString();
+ }
+}