mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(cognito): add cognito overrides for client-id and secret. some b… (#1486)
* feat(cognito): add cognito overrides for client-id and secret. some boy-scouting * feat(cognito): update docs, clarify reserved tags and possible values. Throws exception when unknown reserved tags are used. * feat(cognito): reverted pom changes, align errorCode, use cleaned tag value * feat(cognito): fix region resolver initialization
This commit is contained in:
17 files changed
+371
-209
No files matched your search
@@ -53,6 +53,7 @@ import org.jboss.logging.Logger;
|
||||
@Path("/")
|
||||
public class AwsJson11Controller {
|
||||
|
||||
public static final String CONTENT_TYPE_AWS_JSON_1_1 = "application/x-amz-json-1.1";
|
||||
private static final Logger LOG = Logger.getLogger(AwsJson11Controller.class);
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
@@ -160,8 +161,8 @@ public class AwsJson11Controller {
|
||||
}
|
||||
|
||||
@POST
|
||||
@Consumes("application/x-amz-json-1.1")
|
||||
@Produces("application/x-amz-json-1.1")
|
||||
@Consumes(CONTENT_TYPE_AWS_JSON_1_1)
|
||||
@Produces(CONTENT_TYPE_AWS_JSON_1_1)
|
||||
public Response handle(
|
||||
@HeaderParam("X-Amz-Target") String target,
|
||||
@Context HttpHeaders httpHeaders,
|
||||
|
||||
@@ -27,6 +27,7 @@ import org.jboss.logging.Logger;
|
||||
@Path("/")
|
||||
public class AwsJsonController {
|
||||
|
||||
public static final String CONTENT_TYPE_AWS_JSON_1_0 = "application/x-amz-json-1.0";
|
||||
private static final Logger LOG = Logger.getLogger(AwsJsonController.class);
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
@@ -59,8 +60,8 @@ public class AwsJsonController {
|
||||
}
|
||||
|
||||
@POST
|
||||
@Consumes("application/x-amz-json-1.0")
|
||||
@Produces("application/x-amz-json-1.0")
|
||||
@Consumes(CONTENT_TYPE_AWS_JSON_1_0)
|
||||
@Produces(CONTENT_TYPE_AWS_JSON_1_0)
|
||||
public Response handleJsonRequest(
|
||||
@HeaderParam("X-Amz-Target") String target,
|
||||
@Context HttpHeaders httpHeaders,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import org.apache.commons.lang3.function.TriFunction;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
@@ -10,15 +11,30 @@ public final class ReservedTags {
|
||||
|
||||
public static final String RESERVED_PREFIX = "floci:";
|
||||
public static final String OVERRIDE_ID_KEY = RESERVED_PREFIX + "override-id";
|
||||
public static final String OVERRIDE_COGNITO_CLIENT_ID_KEY = RESERVED_PREFIX + "override-cognito-client-id";
|
||||
public static final String OVERRIDE_COGNITO_CLIENT_SECRET_KEY = RESERVED_PREFIX + "override-cognito-client-secret";
|
||||
private static final String INVALID_PARAMETER_EXCEPTION = "InvalidParameterException";
|
||||
private static final String VALIDATION_EXCEPTION = "ValidationException";
|
||||
private static final String TAG_EXCEPTION = "TagException";
|
||||
private static final String CONTROL_CHARACTER_ERROR_MESSAGE = "Override %s must not contain control characters.";
|
||||
|
||||
private ReservedTags() {
|
||||
}
|
||||
|
||||
public static String extractOverrideId(Map<String, String> tags) {
|
||||
if (tags == null) {
|
||||
return null;
|
||||
}
|
||||
return tags.get(OVERRIDE_ID_KEY);
|
||||
public static String extractOverrideKeyId(Map<String, String> tags) {
|
||||
return getOverride(tags, OVERRIDE_ID_KEY, ReservedTags::validateOverrideId, "Resource ID", TAG_EXCEPTION);
|
||||
}
|
||||
|
||||
public static String extractOverrideUserPoolId(Map<String, String> tags) {
|
||||
return getOverride(tags, OVERRIDE_ID_KEY, ReservedTags::validateOverrideId, "Resource ID", INVALID_PARAMETER_EXCEPTION);
|
||||
}
|
||||
|
||||
public static String extractOverrideCognitoClientId(Map<String, String> tags) {
|
||||
return getOverride(tags, OVERRIDE_COGNITO_CLIENT_ID_KEY, ReservedTags::validateOverrideId, "Cognito Client ID", INVALID_PARAMETER_EXCEPTION);
|
||||
}
|
||||
|
||||
public static String extractOverrideCognitoClientSecret(Map<String, String> tags) {
|
||||
return getOverride(tags, OVERRIDE_COGNITO_CLIENT_SECRET_KEY, ReservedTags::validateClientSecret, "Cognito Client Secret", INVALID_PARAMETER_EXCEPTION);
|
||||
}
|
||||
|
||||
public static Map<String, String> stripReservedTags(Map<String, String> tags) {
|
||||
@@ -41,7 +57,7 @@ public final class ReservedTags {
|
||||
for (String key : tags.keySet()) {
|
||||
if (isReserved(key)) {
|
||||
throw new AwsException(
|
||||
"ValidationException",
|
||||
VALIDATION_EXCEPTION,
|
||||
"Reserved tag keys with prefix " + RESERVED_PREFIX + " can only be supplied during resource creation.",
|
||||
400
|
||||
);
|
||||
@@ -49,6 +65,63 @@ public final class ReservedTags {
|
||||
}
|
||||
}
|
||||
|
||||
public static void rejectUnknownReservedTags(Map<String, String> tags, String errorCode) {
|
||||
if (tags == null) {
|
||||
return;
|
||||
}
|
||||
for (String key : tags.keySet()) {
|
||||
if (isReserved(key) && !key.equals(OVERRIDE_ID_KEY) && !key.equals(OVERRIDE_COGNITO_CLIENT_ID_KEY) && !key.equals(OVERRIDE_COGNITO_CLIENT_SECRET_KEY)) {
|
||||
throw new AwsException(
|
||||
errorCode,
|
||||
"%s is an unknown Reserved Tag.".formatted(key),
|
||||
400
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String getOverride(Map<String, String> tags, String override, TriFunction<String, String, String, String> validator, String name, String errorCode) {
|
||||
if (tags == null) {
|
||||
return null;
|
||||
}
|
||||
if (tags.containsKey(override)) {
|
||||
String ov = tags.get(override);
|
||||
return validator.apply(ov, name, errorCode);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String validateOverrideId(String overrideId, String name, String errorCode) {
|
||||
String normalized = checkNullAndWhitespace(overrideId, name, errorCode);
|
||||
if (normalized.indexOf('/') >= 0 || normalized.indexOf('?') >= 0 || normalized.indexOf('#') >= 0) {
|
||||
throw new AwsException(errorCode, "Override %s contains unsupported characters.".formatted(name), 400);
|
||||
}
|
||||
if (normalized.chars().anyMatch(Character::isISOControl)) {
|
||||
throw new AwsException(errorCode, CONTROL_CHARACTER_ERROR_MESSAGE.formatted(name), 400);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private static String validateClientSecret(String overrideSecret, String name, String errorCode) {
|
||||
String normalized = checkNullAndWhitespace(overrideSecret, name, errorCode);
|
||||
if (normalized.chars().anyMatch(Character::isISOControl)) {
|
||||
throw new AwsException(errorCode, CONTROL_CHARACTER_ERROR_MESSAGE.formatted(name), 400);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private static String checkNullAndWhitespace(String overrideSecret, String name, String errorCode) {
|
||||
if (overrideSecret == null || overrideSecret.trim().isEmpty()) {
|
||||
throw new AwsException(errorCode, "Override %s must not be blank.".formatted(name), 400);
|
||||
}
|
||||
String normalized = overrideSecret.trim();
|
||||
if (normalized.chars().anyMatch(Character::isWhitespace)) {
|
||||
throw new AwsException(errorCode, "Override %s must not contain whitespace.".formatted(name), 400);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
|
||||
private static boolean isReserved(String key) {
|
||||
return key != null && key.startsWith(RESERVED_PREFIX);
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ import io.github.hectorvent.floci.services.sns.SnsService;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.*;
|
||||
@@ -30,6 +31,8 @@ import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.*;
|
||||
|
||||
import static io.github.hectorvent.floci.core.common.ReservedTags.rejectUnknownReservedTags;
|
||||
|
||||
@ApplicationScoped
|
||||
public class CognitoService {
|
||||
private static final int DEFAULT_REFRESH_TOKEN_VALIDITY_DAYS = 30;
|
||||
@@ -39,7 +42,7 @@ public class CognitoService {
|
||||
|
||||
/**
|
||||
* Claim overrides returned by a PreTokenGeneration Lambda trigger.
|
||||
*
|
||||
* <p>
|
||||
* Supports both V1 (single claims map applied to both id and access tokens)
|
||||
* and V2 (per-token-type claim overrides + scope changes for the access
|
||||
* token). For V1 lambdas the parser populates the id/access slots with the
|
||||
@@ -138,6 +141,7 @@ public class CognitoService {
|
||||
public UserPool createUserPool(Map<String, Object> request, String region) {
|
||||
String name = (String) request.get("PoolName");
|
||||
Map<String, String> userPoolTags = (Map<String, String>) request.get("UserPoolTags");
|
||||
rejectUnknownReservedTags(userPoolTags,"UserPoolTaggingException");
|
||||
String id = resolveUserPoolId(region, userPoolTags);
|
||||
if (poolStore.get(id).isPresent()) {
|
||||
throw new AwsException("ResourceConflictException", "User pool already exists", 400);
|
||||
@@ -146,7 +150,8 @@ public class CognitoService {
|
||||
pool.setId(id);
|
||||
pool.setName(name);
|
||||
pool.setArn(regionResolver.buildArn("cognito-idp", region, "userpool/" + id));
|
||||
|
||||
pool.setClientIdOverride(getClientIdOverride(userPoolTags));
|
||||
pool.setClientSecretOverride(ReservedTags.extractOverrideCognitoClientSecret(userPoolTags));
|
||||
populateUserPool(pool, request);
|
||||
|
||||
ensureJwtSigningKeys(pool);
|
||||
@@ -155,6 +160,15 @@ public class CognitoService {
|
||||
return pool;
|
||||
}
|
||||
|
||||
private @Nullable String getClientIdOverride(Map<String, String> userPoolTags) {
|
||||
String overrideMode = ReservedTags.extractOverrideCognitoClientId(userPoolTags);
|
||||
if (overrideMode != null &&
|
||||
(!overrideMode.equals("use-name") && !overrideMode.startsWith("append-to-name:") && !overrideMode.startsWith("prepend-to-name:"))) {
|
||||
throw new AwsException("InvalidParameterException", "Invalid override mode for Cognito client ID. Only use-name, append-to-name: and prepend-to-name: are allowed", 400);
|
||||
}
|
||||
return overrideMode;
|
||||
}
|
||||
|
||||
public UserPool updateUserPool(Map<String, Object> request, String region) {
|
||||
String id = (String) request.get("UserPoolId");
|
||||
UserPool pool = describeUserPool(id);
|
||||
@@ -331,16 +345,17 @@ public class CognitoService {
|
||||
}
|
||||
|
||||
public UserPoolClient createUserPoolClient(String userPoolId, String clientName,
|
||||
boolean generateSecret, boolean allowedOAuthFlowsUserPoolClient,
|
||||
List<String> allowedOAuthFlows, List<String> allowedOAuthScopes,
|
||||
Map<String, Object> analyticsConfiguration, List<String> callbackURLs,
|
||||
String defaultRedirectURI, List<String> explicitAuthFlows, Integer accessTokenValidity,
|
||||
Integer idTokenValidity, List<String> logoutURLs, String preventUserExistenceErrors,
|
||||
List<String> readAttributes, Integer refreshTokenValidity,
|
||||
List<String> supportedIdentityProviders, Map<String, String> tokenValidityUnits,
|
||||
List<String> writeAttributes, Map<String, Object> refreshTokenRotation,
|
||||
Boolean enableTokenRevocation) {
|
||||
describeUserPool(userPoolId);
|
||||
boolean generateSecret, boolean allowedOAuthFlowsUserPoolClient,
|
||||
List<String> allowedOAuthFlows, List<String> allowedOAuthScopes,
|
||||
Map<String, Object> analyticsConfiguration, List<String> callbackURLs,
|
||||
String defaultRedirectURI, List<String> explicitAuthFlows, Integer accessTokenValidity,
|
||||
Integer idTokenValidity, List<String> logoutURLs, String preventUserExistenceErrors,
|
||||
List<String> readAttributes, Integer refreshTokenValidity,
|
||||
List<String> supportedIdentityProviders, Map<String, String> tokenValidityUnits,
|
||||
List<String> writeAttributes, Map<String, Object> refreshTokenRotation,
|
||||
Boolean enableTokenRevocation) {
|
||||
|
||||
UserPool userPool = describeUserPool(userPoolId);
|
||||
String clientId = UUID.randomUUID().toString().replace("-", "").substring(0, 26);
|
||||
List<String> normalizedAllowedOAuthFlows = normalizeStringList(allowedOAuthFlows);
|
||||
List<String> normalizedAllowedOAuthScopes = normalizeStringList(allowedOAuthScopes);
|
||||
@@ -368,6 +383,15 @@ public class CognitoService {
|
||||
);
|
||||
|
||||
UserPoolClient client = new UserPoolClient();
|
||||
if (userPool.getClientIdOverride() != null) {
|
||||
if (userPool.getClientIdOverride().equalsIgnoreCase("use-name")) {
|
||||
clientId = clientName;
|
||||
} else if (userPool.getClientIdOverride().startsWith("append-to-name:")) {
|
||||
clientId = clientName + userPool.getClientIdOverride().substring(15);
|
||||
} else if (userPool.getClientIdOverride().startsWith("prepend-to-name:")) {
|
||||
clientId = userPool.getClientIdOverride().substring(16) + clientName;
|
||||
}
|
||||
}
|
||||
client.setClientId(clientId);
|
||||
client.setUserPoolId(userPoolId);
|
||||
client.setClientName(clientName);
|
||||
@@ -394,6 +418,12 @@ public class CognitoService {
|
||||
client.setEnableTokenRevocation(enableTokenRevocation != null ? enableTokenRevocation : Boolean.TRUE);
|
||||
if (generateSecret) {
|
||||
String clientSecret = generateSecretValue();
|
||||
if (userPool.getClientSecretOverride() != null) {
|
||||
clientSecret = userPool.getClientSecretOverride();
|
||||
if (clientSecret.isEmpty()) {
|
||||
throw new AwsException("InvalidParameterException", "Client secret override cannot be empty", 400);
|
||||
}
|
||||
}
|
||||
client.setClientSecret(clientSecret);
|
||||
|
||||
long epochMillis = System.currentTimeMillis();
|
||||
@@ -1367,29 +1397,11 @@ public class CognitoService {
|
||||
}
|
||||
|
||||
private String resolveUserPoolId(String region, Map<String, String> tags) {
|
||||
String overrideId = ReservedTags.extractOverrideId(tags);
|
||||
String overrideId = ReservedTags.extractOverrideUserPoolId(tags);
|
||||
if (overrideId == null) {
|
||||
return region + "_" + UUID.randomUUID().toString().replace("-", "").substring(0, 9);
|
||||
}
|
||||
validateOverridePoolId(overrideId);
|
||||
return overrideId.trim();
|
||||
}
|
||||
|
||||
private void validateOverridePoolId(String overrideId) {
|
||||
if (overrideId == null || overrideId.trim().isEmpty()) {
|
||||
throw new AwsException("ValidationException", "Override resource ID must not be blank.", 400);
|
||||
}
|
||||
|
||||
String normalized = overrideId.trim();
|
||||
if (normalized.chars().anyMatch(Character::isWhitespace)) {
|
||||
throw new AwsException("ValidationException", "Override resource ID must not contain whitespace.", 400);
|
||||
}
|
||||
if (normalized.indexOf('/') >= 0 || normalized.indexOf('?') >= 0 || normalized.indexOf('#') >= 0) {
|
||||
throw new AwsException("ValidationException", "Override resource ID contains unsupported characters.", 400);
|
||||
}
|
||||
if (normalized.chars().anyMatch(Character::isISOControl)) {
|
||||
throw new AwsException("ValidationException", "Override resource ID must not contain control characters.", 400);
|
||||
}
|
||||
return overrideId;
|
||||
}
|
||||
|
||||
public String getJwksUri(String poolId) {
|
||||
|
||||
@@ -46,6 +46,9 @@ public class UserPool {
|
||||
private Map<String, Object> accountRecoverySetting = new HashMap<>();
|
||||
private String userPoolTier = "ESSENTIALS";
|
||||
|
||||
private String clientIdOverride = null;
|
||||
private String clientSecretOverride = null;
|
||||
|
||||
public UserPool() {
|
||||
long now = System.currentTimeMillis() / 1000L;
|
||||
this.creationDate = now;
|
||||
@@ -151,4 +154,10 @@ public class UserPool {
|
||||
|
||||
public String getUserPoolTier() { return userPoolTier; }
|
||||
public void setUserPoolTier(String userPoolTier) { this.userPoolTier = userPoolTier; }
|
||||
|
||||
public String getClientIdOverride() { return clientIdOverride; }
|
||||
public void setClientIdOverride(String clientIdOverride) { this.clientIdOverride = clientIdOverride;}
|
||||
|
||||
public String getClientSecretOverride() { return clientSecretOverride; }
|
||||
public void setClientSecretOverride(String clientSecretOverride) { this.clientSecretOverride = clientSecretOverride; }
|
||||
}
|
||||
@@ -20,6 +20,8 @@ import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import static io.github.hectorvent.floci.core.common.ReservedTags.rejectUnknownReservedTags;
|
||||
|
||||
@ApplicationScoped
|
||||
public class KmsJsonHandler {
|
||||
|
||||
@@ -87,7 +89,7 @@ public class KmsJsonHandler {
|
||||
String policy = request.path("Policy").isMissingNode() ? null : request.path("Policy").asText(null);
|
||||
Map<String, String> tags = new HashMap<>();
|
||||
request.path("Tags").forEach(t -> tags.put(t.path("TagKey").asText(), t.path("TagValue").asText()));
|
||||
|
||||
rejectUnknownReservedTags(tags,"TagException");
|
||||
KmsKey key = service.createKey(description, keyUsage, keySpec, policy, tags, region);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("KeyMetadata", addKeyMetadata(key));
|
||||
|
||||
@@ -156,17 +156,17 @@ public class KmsService {
|
||||
}
|
||||
|
||||
private String resolveKeyId(Map<String, String> tags) {
|
||||
String overrideId = ReservedTags.extractOverrideId(tags);
|
||||
String overrideId = ReservedTags.extractOverrideKeyId(tags);
|
||||
if (overrideId == null) {
|
||||
return UUID.randomUUID().toString();
|
||||
}
|
||||
|
||||
String normalized = overrideId.trim();
|
||||
if (normalized.isEmpty()) {
|
||||
throw new AwsException("ValidationException", "Override resource ID must not be blank.", 400);
|
||||
throw new AwsException("TagException", "Override resource ID must not be blank.", 400);
|
||||
}
|
||||
if (normalized.length() > 256) {
|
||||
throw new AwsException("ValidationException", "Override resource ID must be 256 characters or fewer.", 400);
|
||||
throw new AwsException("TagException", "Override resource ID must be 256 characters or fewer.", 400);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user