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

* feat(cognito): implement managed login branding

CreateManagedLoginBranding, DescribeManagedLoginBranding,
DescribeManagedLoginBrandingByClient, UpdateManagedLoginBranding and
DeleteManagedLoginBranding were unsupported, so a config declaring
`aws_cognito_managed_login_branding` could not be applied against Floci.

A branding belongs to one app client and is stored on it. Behaviour matches what
the live API does:

- a second branding for the same client raises ManagedLoginBrandingExistsException
- ManagedLoginBrandingId must be a version 4 UUID, checked before the lookup
- Settings is omitted from the response when the caller supplied none, while
  Assets is always returned
- members an update omits are left unchanged

Settings is stored opaquely rather than validated against AWS's unpublished
schema, and ReturnMergedResources does not merge Cognito's default corpus.

Closes #2856

* fix(cognito): reject malformed CreateManagedLoginBranding members

Create coerced an absent UseCognitoProvidedValues to false and silently ignored a
wrongly typed Settings or Assets, so a malformed request produced persisted state.

Measured against AWS:

  neither UseCognitoProvidedValues nor Settings -> InvalidParameterException:
      useCognitoProvidedValues or settings should be specified (but not both)
  Assets of the wrong type   -> SerializationException: Unexpected field type
  UseCognitoProvidedValues of the wrong type -> accepted, not rejected

Create now enforces the first rule and type-checks Settings and Assets. A
non-boolean UseCognitoProvidedValues is still accepted, because AWS accepts it.

AWS answers a wrongly typed Settings with a 500 InternalErrorException; Floci
returns the same client error it returns for Assets rather than reproducing that,
and the divergence is documented.

* fix(cognito): check Assets elements before converting them

The Assets reader validated only the outer array, so a scalar element reached
Jackson's convertValue and escaped as a 500 InternalFailure. This is the same
class of bug as the LogConfigurations one, which I fixed in that reader without
applying it here.

AWS separates the two failures, and they differ from the LogConfigurations rules:

  [1, 2] / ["str"] -> SerializationException: Unexpected value type in payload
  [null]           -> InvalidParameterException: 1 validation error detected:
                      Value '[null]' at 'assets' failed to satisfy constraint:
                      Member must satisfy constraint: [Member must not be null]

A null element is rejected here, where LogConfigurations drops it.

* fix(cognito): match AWS branding source validation

A managed login branding request must select exactly one source of branding,
and the same rule governs create and update. Measured against Cognito in
ap-southeast-1:

  useCognitoProvidedValues  settings   result
  absent                    absent     InvalidParameterException
  true                      absent     accepted
  false                     absent     InvalidParameterException
  absent                    present    accepted
  true                      present    InvalidParameterException
  false                     present    accepted

Create rejected only the neither case, update validated nothing at all, so
naming both members and updating with no source both succeeded where the
service rejects them. Presence of the member is not the test: false selects no
source, which is why it needs settings alongside it.

Reading the flag had to move with it. AWS coerces a JSON string rather than
rejecting it, storing true for "true" and for "yes" and false for "false",
while Jackson maps every string except "true" to false. That turned "yes" into
a request selecting no source, so the coercion now follows the service.

* fix(cognito): reject malformed UseCognitoProvidedValues types

Jackson's asBoolean() maps a number, a JSON null, an object and an array all to
false, so a malformed flag alongside valid Settings passed source validation and
persisted as branding state that was never requested.

Measured against Cognito in ap-southeast-1: 1, null, {} and [] are each a
SerializationException, with or without Settings, while omitting the member is
accepted and stores false. Only booleans and strings are read now, strings still
coerced the way the service coerces them, and everything else raises
SerializationException the way SesController already does.

* fix(cognito): bound managed login branding assets at 40

Neither create nor update checked the documented 40-item maximum on Assets, so
an oversized request was accepted and stored where AWS rejects it.

Measured against Cognito in ap-southeast-1:

  create 40 assets            passes the bound, reaches the source rule
  create 41 assets            InvalidParameterException, length constraint
  create 41 + unknown client  the length error, not the missing client
  update 41 + malformed id    2 validation errors, the length one first
  update malformed id alone   1 validation error, before the pool lookup

The asset and branding-id checks now run before anything is looked up and
share one message, matching those last three rows. DescribeManagedLoginBranding
ran its pool lookup ahead of the branding-id check, which the fourth row shows
is the wrong way round, so it moved with them.

The length message embeds the request model's toString. The blob renders as the
decoded buffer, confirmed at three payload sizes; the decoder used here is the
lenient one so that building a rejection cannot itself fail.
This commit is contained in:
Brian Taylor authored and GitHub committed 2026-09-02 11:50:47 -04:00
1 parent b8f1e22c74
commit 1e4e8b9ee8
6 files changed
+1090

No files matched your search

@@ -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(
@@ -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,
@@ -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; }
}
@@ -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;
}
}