mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(cognito): implement log delivery configuration (#2867)
* feat(cognito): implement log delivery configuration SetLogDeliveryConfiguration and GetLogDeliveryConfiguration were unsupported, so a config declaring `aws_cognito_log_delivery_configuration` could not be applied against Floci. The configuration is stored on the user pool and validated the way the live API validates it: - LogLevel accepts ERROR or INFO, EventSource accepts userNotification or userAuthEvents, both reported with AWS's 1-based member path - every entry must name a CloudWatch, Firehose or S3 destination - Set replaces the list rather than merging, so an empty list clears it - Get always returns LogConfigurations, as [] when nothing is configured Floci stores the configuration and delivers nothing: the destination is neither written to nor required to exist, and the pricing-tier gate AWS applies to userAuthEvents is not reproduced. Closes #2855 * fix(cognito): reject a null LogConfigurations instead of clearing the configuration SetLogDeliveryConfiguration treated an omitted, null or wrongly typed LogConfigurations as an empty replacement, so a malformed request returned 200 and erased the pool's stored configuration. AWS rejects all three. An omitted or null member fails validation, and a value of the wrong JSON type fails deserialization: omitted / null -> InvalidParameterException: 1 validation error detected: Value null at 'logConfigurations' failed to satisfy constraint: Member must not be null wrong type -> SerializationException: Expected list or null Also drops two em-dashes from the docs, per AGENTS.md. * fix(cognito): translate malformed LogConfigurations elements the way AWS does A scalar inside the array reached Jackson's convertValue directly, so an IllegalArgumentException escaped as a 500 InternalFailure instead of a client error, and a null element would have failed on the validation loop. AWS answers both without a 500: [1, 2] / ["a string"] -> SerializationException: Expected null [null] -> 200, the null element is dropped Elements are now checked before conversion: nulls are skipped and non-objects raise SerializationException. * fix(cognito): bound LogConfigurations and reject a repeated event source SetLogDeliveryConfiguration validated each element but never checked the list itself, so a request with three or more well-formed configurations, or two naming the same event source, was accepted and stored where AWS rejects it. Measured against Cognito in ap-southeast-1: 3 well-formed configs InvalidParameterException, length constraint on 'logConfigurations', max 2 2 duplicate sources InvalidParameterException, "appear more then once" 3 configs, one bad enum 2 validation errors, the length one reported first unknown pool, bad enum the validation error, not ResourceNotFoundException 0 configs 200 OK The shape checks now run before the pool lookup, matching that last row, and collect every violation into one message instead of throwing on the first. The duplicate and missing-destination complaints share one message with the missing-destination clause first, and each event source is named once however many configurations carry it, as measured. "more then once" is the service's own spelling, kept so the message matches. The length message embeds the request model's toString, which the emulator now reproduces for all three destination shapes and for an absent destination.
This commit is contained in:
1 parent
7d693de663
commit
b8f1e22c74
6 files changed
+816
No files matched your search
@@ -19,6 +19,7 @@ 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.List;
|
||||
import java.util.Map;
|
||||
@@ -61,6 +62,8 @@ public class CognitoJsonHandler {
|
||||
case "CreateUserPoolDomain" -> handleCreateUserPoolDomain(request);
|
||||
case "DescribeUserPoolDomain" -> handleDescribeUserPoolDomain(request);
|
||||
case "DeleteUserPoolDomain" -> handleDeleteUserPoolDomain(request);
|
||||
case "SetLogDeliveryConfiguration" -> handleSetLogDeliveryConfiguration(request);
|
||||
case "GetLogDeliveryConfiguration" -> handleGetLogDeliveryConfiguration(request);
|
||||
case "AdminResetUserPassword" -> handleAdminResetUserPassword(request);
|
||||
case "AdminCreateUser" -> handleAdminCreateUser(request);
|
||||
case "AdminGetUser" -> handleAdminGetUser(request);
|
||||
@@ -373,6 +376,57 @@ public class CognitoJsonHandler {
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleSetLogDeliveryConfiguration(JsonNode request) {
|
||||
UserPool pool = service.setLogDeliveryConfiguration(
|
||||
request.path("UserPoolId").asText(),
|
||||
readObjectList(request, "LogConfigurations")
|
||||
);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("LogDeliveryConfiguration", logDeliveryConfigurationToNode(pool));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleGetLogDeliveryConfiguration(JsonNode request) {
|
||||
UserPool pool = service.getLogDeliveryConfiguration(request.path("UserPoolId").asText());
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("LogDeliveryConfiguration", logDeliveryConfigurationToNode(pool));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private ObjectNode logDeliveryConfigurationToNode(UserPool pool) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("UserPoolId", pool.getId());
|
||||
ArrayNode configurations = node.putArray("LogConfigurations");
|
||||
pool.getLogConfigurations().forEach(config -> configurations.add(objectMapper.valueToTree(config)));
|
||||
return node;
|
||||
}
|
||||
|
||||
/**
|
||||
* Absent or null yields null so the service can reject it. A value of the wrong JSON type is
|
||||
* a deserialization failure, which AWS reports as SerializationException, and a null element
|
||||
* inside the array is dropped, which is what AWS does with it.
|
||||
*/
|
||||
private List<Map<String, Object>> readObjectList(JsonNode request, String member) {
|
||||
JsonNode node = request.get(member);
|
||||
if (node == null || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!node.isArray()) {
|
||||
throw new AwsException("SerializationException", "Expected list or null", 400);
|
||||
}
|
||||
List<Map<String, Object>> values = new ArrayList<>();
|
||||
for (JsonNode element : node) {
|
||||
if (element.isNull()) {
|
||||
continue;
|
||||
}
|
||||
if (!element.isObject()) {
|
||||
throw new AwsException("SerializationException", "Expected null", 400);
|
||||
}
|
||||
values.add(objectMapper.convertValue(element, new TypeReference<Map<String, Object>>() {}));
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
private Response handleDeleteUserPoolDomain(JsonNode request) {
|
||||
service.deleteUserPoolDomain(
|
||||
request.path("Domain").asText(),
|
||||
|
||||
@@ -946,6 +946,140 @@ public class CognitoService implements ResourceProvider {
|
||||
.format(java.time.Instant.now());
|
||||
}
|
||||
|
||||
// ──────────────────────────── Log Delivery ────────────────────────────
|
||||
|
||||
private static final Set<String> LOG_LEVELS = Set.of("ERROR", "INFO");
|
||||
private static final Set<String> LOG_EVENT_SOURCES = Set.of("userAuthEvents", "userNotification");
|
||||
private static final int MAX_LOG_CONFIGURATIONS = 2;
|
||||
|
||||
/**
|
||||
* Replaces the pool's log configuration wholesale: AWS has no merge semantics here, and an
|
||||
* empty list is what clears it.
|
||||
*/
|
||||
public UserPool setLogDeliveryConfiguration(String userPoolId, List<Map<String, Object>> logConfigurations) {
|
||||
validateLogConfigurations(logConfigurations);
|
||||
rejectUnusableEventSources(logConfigurations);
|
||||
|
||||
UserPool pool = describeUserPool(userPoolId);
|
||||
pool.setLogConfigurations(new ArrayList<>(logConfigurations));
|
||||
poolStore.put(userPoolId, pool);
|
||||
return pool;
|
||||
}
|
||||
|
||||
public UserPool getLogDeliveryConfiguration(String userPoolId) {
|
||||
return describeUserPool(userPoolId);
|
||||
}
|
||||
|
||||
/**
|
||||
* The shape checks AWS runs before it looks the pool up, so an oversized or malformed request
|
||||
* against a pool that does not exist reports the request problem rather than the missing pool.
|
||||
* Every violation is collected into one message, the list-length one ahead of the per-element
|
||||
* ones, the way the service reports them.
|
||||
*/
|
||||
private void validateLogConfigurations(List<Map<String, Object>> configs) {
|
||||
if (configs == null) {
|
||||
throw validationErrors(List.of(
|
||||
"Value null at 'logConfigurations' failed to satisfy constraint: Member must not be null"));
|
||||
}
|
||||
|
||||
List<String> errors = new ArrayList<>();
|
||||
if (configs.size() > MAX_LOG_CONFIGURATIONS) {
|
||||
errors.add("Value '" + renderLogConfigurations(configs) + "' at 'logConfigurations' failed to "
|
||||
+ "satisfy constraint: Member must have length less than or equal to " + MAX_LOG_CONFIGURATIONS);
|
||||
}
|
||||
for (int i = 0; i < configs.size(); i++) {
|
||||
Map<String, Object> config = configs.get(i);
|
||||
collectLogMemberError(errors, config.get("LogLevel"), LOG_LEVELS, i, "logLevel", "[ERROR, INFO]");
|
||||
collectLogMemberError(errors, config.get("EventSource"), LOG_EVENT_SOURCES, i, "eventSource",
|
||||
"[userAuthEvents, userNotification]");
|
||||
}
|
||||
if (!errors.isEmpty()) {
|
||||
throw validationErrors(errors);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Both complaints share one message, the missing-destination clause first, and each event
|
||||
* source is named once however many configurations carry it.
|
||||
*
|
||||
* <p>"more then once" is the service's own spelling, kept so the message matches byte for byte.
|
||||
*/
|
||||
private void rejectUnusableEventSources(List<Map<String, Object>> configs) {
|
||||
Set<String> withoutDestination = new LinkedHashSet<>();
|
||||
Set<String> seen = new LinkedHashSet<>();
|
||||
Set<String> duplicated = new LinkedHashSet<>();
|
||||
for (Map<String, Object> config : configs) {
|
||||
String eventSource = String.valueOf(config.get("EventSource"));
|
||||
if (!hasLogDestination(config)) {
|
||||
withoutDestination.add(eventSource);
|
||||
}
|
||||
if (!seen.add(eventSource)) {
|
||||
duplicated.add(eventSource);
|
||||
}
|
||||
}
|
||||
|
||||
StringBuilder message = new StringBuilder();
|
||||
if (!withoutDestination.isEmpty()) {
|
||||
message.append(" Following event sources in request have no destination: ")
|
||||
.append(new ArrayList<>(withoutDestination)).append(".");
|
||||
}
|
||||
if (!duplicated.isEmpty()) {
|
||||
message.append(" Following event sources appear more then once in a request: ")
|
||||
.append(new ArrayList<>(duplicated)).append(".");
|
||||
}
|
||||
if (!message.isEmpty()) {
|
||||
throw new AwsException("InvalidParameterException", "Request validation Failed." + message, 400);
|
||||
}
|
||||
}
|
||||
|
||||
private AwsException validationErrors(List<String> errors) {
|
||||
String header = errors.size() == 1
|
||||
? "1 validation error detected: "
|
||||
: errors.size() + " validation errors detected: ";
|
||||
return 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 renderLogConfigurations(List<Map<String, Object>> configs) {
|
||||
List<String> rendered = new ArrayList<>();
|
||||
for (Map<String, Object> config : configs) {
|
||||
rendered.add("LogConfigurationType(logLevel=" + config.get("LogLevel")
|
||||
+ ", eventSource=" + config.get("EventSource")
|
||||
+ ", cloudWatchLogsConfiguration=" + renderLogDestination(
|
||||
config.get("CloudWatchLogsConfiguration"), "CloudWatchLogsConfigurationType",
|
||||
"LogGroupArn", "logGroupArn")
|
||||
+ ", s3Configuration=" + renderLogDestination(
|
||||
config.get("S3Configuration"), "S3ConfigurationType", "BucketArn", "bucketArn")
|
||||
+ ", firehoseConfiguration=" + renderLogDestination(
|
||||
config.get("FirehoseConfiguration"), "FirehoseConfigurationType",
|
||||
"StreamArn", "streamArn")
|
||||
+ ")");
|
||||
}
|
||||
return "[" + String.join(", ", rendered) + "]";
|
||||
}
|
||||
|
||||
private String renderLogDestination(Object value, String typeName, String requestMember, String modelMember) {
|
||||
if (!(value instanceof Map<?, ?> destination)) {
|
||||
return "null";
|
||||
}
|
||||
return typeName + "(" + modelMember + "=" + destination.get(requestMember) + ")";
|
||||
}
|
||||
|
||||
private boolean hasLogDestination(Map<String, Object> config) {
|
||||
return config.get("CloudWatchLogsConfiguration") != null
|
||||
|| config.get("FirehoseConfiguration") != null
|
||||
|| config.get("S3Configuration") != null;
|
||||
}
|
||||
|
||||
/** AWS reports the offending member with a 1-based index, e.g. {@code logConfigurations.1.member.logLevel}. */
|
||||
private void collectLogMemberError(List<String> errors, Object value, Set<String> allowed, int index,
|
||||
String member, String enumSet) {
|
||||
if (value == null || !allowed.contains(String.valueOf(value))) {
|
||||
errors.add("Value '" + value + "' at 'logConfigurations." + (index + 1) + ".member." + member
|
||||
+ "' failed to satisfy constraint: Member must satisfy enum value set: " + enumSet);
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── Users ────────────────────────────
|
||||
|
||||
public CognitoUser adminCreateUser(String userPoolId, String username, Map<String, String> attributes,
|
||||
|
||||
@@ -49,6 +49,9 @@ public class UserPool {
|
||||
private String clientIdOverride = null;
|
||||
private String clientSecretOverride = null;
|
||||
|
||||
/** Empty until SetLogDeliveryConfiguration sets it; GetLogDeliveryConfiguration always returns it. */
|
||||
private List<Map<String, Object>> logConfigurations = new ArrayList<>();
|
||||
|
||||
public UserPool() {
|
||||
long now = System.currentTimeMillis() / 1000L;
|
||||
this.creationDate = now;
|
||||
@@ -159,4 +162,9 @@ public class UserPool {
|
||||
|
||||
public String getClientSecretOverride() { return clientSecretOverride; }
|
||||
public void setClientSecretOverride(String clientSecretOverride) { this.clientSecretOverride = clientSecretOverride; }
|
||||
|
||||
public List<Map<String, Object>> getLogConfigurations() { return logConfigurations; }
|
||||
public void setLogConfigurations(List<Map<String, Object>> logConfigurations) {
|
||||
this.logConfigurations = logConfigurations;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user