feat(firehose): accept a Redshift destination on create, update and describe (#6004)

* feat(firehose): accept a Redshift destination on create, update and describe

Adds RedshiftDestinationConfiguration to CreateDeliveryStream and RedshiftDestinationUpdate to UpdateDestination, validated against the Firehose API model. DescribeDeliveryStream returns RedshiftDestinationDescription without Password. A batch is staged in the intermediate S3 location like an S3 destination; the COPY delivery follows in a separate change.

* fix(firehose): close review gaps in the Redshift destination API

Require BucketARN and RoleARN on the intermediate and backup S3 configurations, validate the Secrets Manager RoleARN, apply the paired buffering-hints rule to the backup location, recognise dollar-quote tags with digits or non-ASCII letters in CopyOptions, and take the update lock in DeleteDeliveryStream so a concurrent update cannot revive a deleted stream. Rejected requests are now asserted to leave the stream unchanged.

* fix(firehose): refuse any dollar sign outside a quoted CopyOptions literal

A dollar-quote tag can hold any non-ASCII character, including code points outside the basic plane that a Java character-class range does not cover, so a tag pattern could hide a second statement. CopyOptions never need dollar quoting, so the separator check now refuses a dollar sign outside a quoted literal instead of parsing the tag.

* docs(firehose): list every refused CopyOptions token in the docs and validation message
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-20 13:05:31 -04:00
1 parent 645c97c803
commit 484255871e
13 files changed
+1584 -9

No files matched your search

@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescript
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.KinesisStreamSource;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination;
import io.github.hectorvent.floci.services.firehose.model.Record;
import io.github.hectorvent.floci.services.firehose.model.RedshiftDestination;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
@@ -53,6 +54,18 @@ public class FirehoseJsonHandler {
s3 = mapper.treeToValue(request.get("ExtendedS3DestinationConfiguration"), S3Destination.class);
S3DestinationValidator.validateWireShape(s3, "extendedS3DestinationConfiguration");
}
RedshiftDestination redshift = null;
if (request.hasNonNull("RedshiftDestinationConfiguration")) {
if (s3 != null) {
throw new AwsException("InvalidArgumentException",
"Only one destination configuration may be specified.", 400);
}
redshift = mapper.treeToValue(request.get("RedshiftDestinationConfiguration"),
RedshiftDestination.class);
dropExtendedOnlyMembersFromLegacyShape(redshift.getS3());
dropExtendedOnlyMembersFromLegacyShape(redshift.getS3Backup());
RedshiftDestinationValidator.validateConfiguration(redshift, "redshiftDestinationConfiguration");
}
List<io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.Tag> tags = new ArrayList<>();
if (request.has("Tags")) {
requireListSize(request.get("Tags"), "Tags", 1, 50);
@@ -70,7 +83,7 @@ public class FirehoseJsonHandler {
? mapper.treeToValue(request.get("KinesisStreamSourceConfiguration"), KinesisStreamSource.class)
: null;
String arn = firehoseService.createDeliveryStream(
region, name, s3, tags, deliveryStreamType, source);
region, name, s3, redshift, tags, deliveryStreamType, source);
yield Response.ok(Map.of("DeliveryStreamARN", arn)).build();
}
case "UpdateDestination" -> {
@@ -86,7 +99,20 @@ public class FirehoseJsonHandler {
dropExtendedOnlyMembersFromLegacyShape(update);
S3DestinationValidator.validateWireShape(update, "s3DestinationUpdate");
}
firehoseService.updateDestination(name, currentVersionId, destinationId, update);
if (request.hasNonNull("RedshiftDestinationUpdate")) {
if (update != null) {
throw new AwsException("InvalidArgumentException",
"Only one destination update may be specified.", 400);
}
RedshiftDestination redshiftUpdate = mapper.treeToValue(request.get("RedshiftDestinationUpdate"),
RedshiftDestination.class);
dropExtendedOnlyMembersFromLegacyShape(redshiftUpdate.getS3());
dropExtendedOnlyMembersFromLegacyShape(redshiftUpdate.getS3Backup());
RedshiftDestinationValidator.validateUpdate(redshiftUpdate, "redshiftDestinationUpdate");
firehoseService.updateRedshiftDestination(name, currentVersionId, destinationId, redshiftUpdate);
} else {
firehoseService.updateDestination(name, currentVersionId, destinationId, update);
}
yield Response.ok(Map.of()).build();
}
case "StartDeliveryStreamEncryption" -> {
@@ -117,7 +143,7 @@ public class FirehoseJsonHandler {
case "DescribeDeliveryStream" -> {
String name = getDeliveryStreamName(request);
DeliveryStreamDescription desc = firehoseService.describeDeliveryStream(name);
yield Response.ok(Map.of("DeliveryStreamDescription", desc)).build();
yield Response.ok(Map.of("DeliveryStreamDescription", withoutSecrets(desc))).build();
}
case "ListDeliveryStreams" -> {
yield Response.ok(Map.of(
@@ -198,6 +224,26 @@ public class FirehoseJsonHandler {
};
}
/**
* Returns the description with every Redshift password removed. The stored object is never
* touched: in memory mode it is the live instance the delivery path reads the password from.
*/
private DeliveryStreamDescription withoutSecrets(DeliveryStreamDescription desc) {
boolean hasRedshift = desc.getDestinations() != null && desc.getDestinations().stream()
.anyMatch(d -> d.getRedshiftDestinationDescription() != null);
if (!hasRedshift) {
return desc;
}
DeliveryStreamDescription copy = mapper.convertValue(desc, DeliveryStreamDescription.class);
for (DeliveryStreamDescription.Destination destination : copy.getDestinations()) {
if (destination.getRedshiftDestinationDescription() != null) {
destination.setRedshiftDestinationDescription(
destination.getRedshiftDestinationDescription().copyWithoutPassword());
}
}
return copy;
}
/**
* Clears {@code DataFormatConversionConfiguration} and
* {@code ProcessingConfiguration} from a legacy {@code S3DestinationConfiguration}
@@ -15,6 +15,7 @@ import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescript
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.KinesisStreamSource;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination;
import io.github.hectorvent.floci.services.firehose.model.Record;
import io.github.hectorvent.floci.services.firehose.model.RedshiftDestination;
import io.github.hectorvent.floci.services.kinesis.KinesisService;
import io.github.hectorvent.floci.services.kinesis.model.KinesisRecord;
import io.github.hectorvent.floci.services.kinesis.model.KinesisShard;
@@ -111,6 +112,8 @@ public class FirehoseService implements ResourceProvider {
private final Map<String, Map<String, String>> pendingSourceIterators = new ConcurrentHashMap<>();
private final FirehoseParquetConverter parquetConverter;
private final FirehoseLambdaTransformer lambdaTransformer;
// Serialises the read, version check, merge and write of a Redshift UpdateDestination per stream.
private final Map<String, Object> redshiftUpdateLocks = new ConcurrentHashMap<>();
private final Clock clock;
private final long tickIntervalSeconds;
private final int flushRecordCount;
@@ -314,6 +317,19 @@ public class FirehoseService implements ResourceProvider {
public String createDeliveryStream(String region, String accountId, String name, S3Destination s3Config,
List<DeliveryStreamDescription.Tag> tags, String deliveryStreamType,
KinesisStreamSource source) {
return createDeliveryStream(region, accountId, name, s3Config, null, tags, deliveryStreamType, source);
}
public String createDeliveryStream(String region, String name, S3Destination s3Config,
RedshiftDestination redshift, List<DeliveryStreamDescription.Tag> tags,
String deliveryStreamType, KinesisStreamSource source) {
return createDeliveryStream(region, regionResolver.getAccountId(), name, s3Config, redshift, tags,
deliveryStreamType, source);
}
public String createDeliveryStream(String region, String accountId, String name, S3Destination s3Config,
RedshiftDestination redshift, List<DeliveryStreamDescription.Tag> tags,
String deliveryStreamType, KinesisStreamSource source) {
String streamKey = scopedKey(accountId, region, name);
if (name == null || name.isEmpty() || name.length() > 64 || !name.matches("[a-zA-Z0-9_.-]+")) {
throw new AwsException("InvalidArgumentException",
@@ -326,6 +342,10 @@ public class FirehoseService implements ResourceProvider {
}
validateBufferingHints(s3Config);
if (redshift != null) {
validateBufferingHints(redshift.getS3());
validateBufferingHints(redshift.getS3Backup());
}
DataFormatConversionValidator.validateEffective(s3Config);
ProcessingConfigurationValidator.validateEffective(s3Config);
if (s3Config != null) {
@@ -342,7 +362,7 @@ public class FirehoseService implements ResourceProvider {
if (source != null && source.getDeliveryStartTimestamp() == null) {
source.setDeliveryStartTimestamp(Instant.now());
}
DeliveryStreamDescription description = new DeliveryStreamDescription(name, arn, s3Config, source);
DeliveryStreamDescription description = new DeliveryStreamDescription(name, arn, s3Config, redshift, source);
description.setAccountId(accountId);
description.setTags(tags);
if (deliveryStreamType != null && !deliveryStreamType.isBlank()) {
@@ -363,7 +383,15 @@ public class FirehoseService implements ResourceProvider {
updateDestination(scopedKey(accountId, region, name), name, currentVersionId, destinationId, update);
}
private void updateDestination(String streamKey, String name, String currentVersionId, String destinationId, S3Destination update) {
/** The stream an UpdateDestination call targets, with the destination it addresses. */
private record UpdateTarget(DeliveryStreamDescription stream, DeliveryStreamDescription.Destination destination) {}
/**
* The checks every UpdateDestination variant starts with, in the order AWS applies them: the stream exists, the
* caller holds its current version, and the destination id is the stream's destination.
*/
private UpdateTarget resolveUpdateTarget(String streamKey, String name, String currentVersionId,
String destinationId) {
DeliveryStreamDescription stream = streamGet(streamKey)
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Delivery stream not found: " + name, 400));
if (!stream.getVersionId().equals(currentVersionId)) {
@@ -378,10 +406,21 @@ public class FirehoseService implements ResourceProvider {
throw new AwsException("InvalidArgumentException",
"Destination Id " + destinationId + " not found", 400);
}
return new UpdateTarget(stream, destination);
}
private void updateDestination(String streamKey, String name, String currentVersionId, String destinationId, S3Destination update) {
UpdateTarget target = resolveUpdateTarget(streamKey, name, currentVersionId, destinationId);
DeliveryStreamDescription stream = target.stream();
DeliveryStreamDescription.Destination destination = target.destination();
if (update == null) {
throw new AwsException("InvalidArgumentException",
"A destination update is required for UpdateDestination.", 400);
}
if (destination.getRedshiftDestinationDescription() != null) {
throw new AwsException("InvalidArgumentException",
"The delivery stream " + name + " has a Redshift destination; use RedshiftDestinationUpdate.", 400);
}
validateBufferingHints(update);
S3Destination current = destination.getExtendedS3DestinationDescription();
if (current == null) {
@@ -411,6 +450,87 @@ public class FirehoseService implements ResourceProvider {
LOG.infov("Updated destination {0} of Firehose delivery stream {1}", destinationId, name);
}
public void updateRedshiftDestination(String name, String currentVersionId, String destinationId,
RedshiftDestination update) {
String streamKey = scopedKey(name);
synchronized (redshiftUpdateLocks.computeIfAbsent(streamKey, k -> new Object())) {
UpdateTarget target = resolveUpdateTarget(streamKey, name, currentVersionId, destinationId);
DeliveryStreamDescription stream = target.stream();
RedshiftDestination current = target.destination().getRedshiftDestinationDescription();
if (current == null) {
throw new AwsException("InvalidArgumentException",
"The delivery stream " + name + " does not have a Redshift destination.", 400);
}
RedshiftDestinationValidator.validateBackupTransition(current.getS3BackupMode(), update.getS3BackupMode());
String effectiveBackupMode = update.getS3BackupMode() != null
? update.getS3BackupMode() : current.getS3BackupMode();
if ("Enabled".equals(effectiveBackupMode) && update.getS3Backup() == null && current.getS3Backup() == null) {
throw new AwsException("InvalidArgumentException",
"S3BackupMode is Enabled but no S3 backup configuration is set.", 400);
}
validateBufferingHints(update.getS3());
validateBufferingHints(update.getS3Backup());
if (update.getS3Backup() != null && current.getS3Backup() == null) {
RedshiftDestinationValidator.validateNewBackup(update.getS3Backup(), "redshiftDestinationUpdate");
}
mergeRedshiftDestination(current, update);
stream.setVersionId(String.valueOf(parseVersionId(stream.getVersionId()) + 1));
stream.setLastUpdateTimestamp(Instant.now());
streamPut(streamKey, stream);
LOG.infov("Updated Redshift destination {0} of Firehose delivery stream {1}", destinationId, name);
}
}
/** Members present in the update replace the stored ones; absent members are kept. */
private static void mergeRedshiftDestination(RedshiftDestination current, RedshiftDestination update) {
if (update.getRoleArn() != null) {
current.setRoleArn(update.getRoleArn());
}
if (update.getClusterJdbcUrl() != null) {
current.setClusterJdbcUrl(update.getClusterJdbcUrl());
}
if (update.getUsername() != null) {
current.setUsername(update.getUsername());
}
if (update.getPassword() != null) {
current.setPassword(update.getPassword());
}
if (update.getCopyCommand() != null) {
current.setCopyCommand(update.getCopyCommand());
}
if (update.getRetryOptions() != null) {
current.setRetryOptions(update.getRetryOptions());
}
if (update.getS3BackupMode() != null) {
current.setS3BackupMode(update.getS3BackupMode());
}
if (update.getSecretsManagerConfiguration() != null) {
current.setSecretsManagerConfiguration(update.getSecretsManagerConfiguration());
}
if (update.getProcessingConfiguration() != null) {
current.setProcessingConfiguration(update.getProcessingConfiguration());
}
if (update.getCloudWatchLoggingOptions() != null) {
current.setCloudWatchLoggingOptions(update.getCloudWatchLoggingOptions());
}
if (update.getS3() != null) {
if (current.getS3() == null) {
update.getS3().applyDefaults();
current.setS3(update.getS3());
} else {
mergeDestination(current.getS3(), update.getS3());
}
}
if (update.getS3Backup() != null) {
if (current.getS3Backup() == null) {
update.getS3Backup().applyDefaults();
current.setS3Backup(update.getS3Backup());
} else {
mergeDestination(current.getS3Backup(), update.getS3Backup());
}
}
}
public void startDeliveryStreamEncryption(String name, String keyType, String keyArn) {
DeliveryStreamDescription stream = describeDeliveryStream(name);
String effectiveKeyType = keyType == null ? "AWS_OWNED_CMK" : keyType;
@@ -654,8 +774,13 @@ public class FirehoseService implements ResourceProvider {
public void deleteDeliveryStream(String accountId, String region, String name) {
String streamKey = scopedKey(accountId, region, name);
describeDeliveryStream(streamKey, name);
streamDelete(streamKey);
// Under the lock a Redshift update holds across its read and write: an update that read the stream just before
// this delete would otherwise write it back afterwards. The lock entry is kept, because removing it while an
// update waits on it would let a later caller take a second lock for the same stream.
synchronized (redshiftUpdateLocks.computeIfAbsent(streamKey, k -> new Object())) {
describeDeliveryStream(streamKey, name);
streamDelete(streamKey);
}
// Pending records are discarded, not flushed: verified against real AWS
// (2026-07-13, eu-west-1) — 3 records buffered under a 300s/5MB hint never
// reached the bucket after DeleteDeliveryStream completed.
@@ -0,0 +1,113 @@
package io.github.hectorvent.floci.services.firehose;
import java.util.regex.Pattern;
/**
* Rules for the {@code DataTableName}, {@code DataTableColumns} and {@code CopyOptions} members of a Redshift
* destination's {@code CopyCommand}. AWS pastes these members into the {@code COPY} statement as given, so Floci
* does the same and lets Redshift's own identifier folding apply: an unquoted name is lowercased, a quoted one is
* kept. Instead of quoting, it refuses names that are not identifiers and any {@code ;}, {@code $} or comment marker
* outside a quoted literal, which is what keeps the text from carrying a second statement. The separator scan follows PostgreSQL's own
* quoting rules rather than a simplified one, because the statement is later run in simple query mode, where
* PostgreSQL executes every {@code ;}-separated statement it receives.
*/
final class RedshiftCopySql {
private static final String NAME = "(?:[A-Za-z_][A-Za-z0-9_$]*|\"[^\"]+\")";
private static final Pattern QUALIFIED_NAME = Pattern.compile(NAME + "(?:\\." + NAME + ")?");
private static final Pattern SIMPLE_NAME = Pattern.compile(NAME);
private RedshiftCopySql() {}
static boolean isValidTableName(String table) {
return table != null && QUALIFIED_NAME.matcher(table).matches();
}
/** An absent or blank list is valid: the proxy then discovers the table columns itself. */
static boolean isValidColumnList(String columns) {
if (columns == null || columns.isBlank()) {
return true;
}
for (String column : columns.split(",", -1)) {
if (!SIMPLE_NAME.matcher(column.trim()).matches()) {
return false;
}
}
return true;
}
/**
* The text without one closing {@code ;} and the whitespace around it. A terminator at the very end carries no
* second statement, and the Firehose API reference's own CopyOptions example ends with one:
* {@code delimiter '\t' lzop;}.
*/
static String withoutTrailingTerminator(String text) {
String trimmed = text.stripTrailing();
return trimmed.endsWith(";") ? trimmed.substring(0, trimmed.length() - 1).stripTrailing() : text;
}
/**
* True when the text could carry a second statement: a {@code ;} outside a quoted literal other than a single
* closing one, an unterminated literal, any {@code $} or a comment. A {@code $} outside a literal is refused
* outright rather than parsed as a dollar-quote tag: CopyOptions never need dollar quoting, and a tag can hold any
* non-ASCII character, so a tag pattern here could always fall behind PostgreSQL's lexer. Single-quoted strings honour
* backslash escapes only in the {@code E'...'} form, double-quoted identifiers are skipped as a whole, and a
* doubled quote stays inside its literal.
*/
static boolean hasStatementSeparator(String text) {
String body = withoutTrailingTerminator(text);
int length = body.length();
int i = 0;
while (i < length) {
char c = body.charAt(i);
if (c == '\'') {
boolean escapeString = i > 0 && (body.charAt(i - 1) == 'e' || body.charAt(i - 1) == 'E')
&& (i == 1 || !isIdentifierChar(body.charAt(i - 2)));
i = endOfQuoted(body, i + 1, '\'', escapeString);
} else if (c == '"') {
i = endOfQuoted(body, i + 1, '"', false);
} else if (c == ';' || c == '$' || startsComment(body, i)) {
return true;
} else {
i++;
}
if (i < 0) {
return true;
}
}
return false;
}
private static boolean startsComment(String text, int i) {
if (i + 1 >= text.length()) {
return false;
}
char c = text.charAt(i);
char next = text.charAt(i + 1);
return (c == '-' && next == '-') || (c == '/' && next == '*');
}
private static boolean isIdentifierChar(char c) {
return Character.isLetterOrDigit(c) || c == '_' || c == '$';
}
/** Index just past the closing quote, or -1 when the literal is never closed. */
private static int endOfQuoted(String text, int from, char quote, boolean backslashEscapes) {
int j = from;
while (j < text.length()) {
char ch = text.charAt(j);
if (backslashEscapes && ch == '\\') {
j += 2;
} else if (ch == quote) {
if (j + 1 < text.length() && text.charAt(j + 1) == quote) {
j += 2;
} else {
return j + 1;
}
} else {
j++;
}
}
return -1;
}
}
@@ -0,0 +1,213 @@
package io.github.hectorvent.floci.services.firehose;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination;
import io.github.hectorvent.floci.services.firehose.model.RedshiftDestination;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Pattern;
/**
* Validates the members of a Redshift destination against the Firehose API model: required
* members on create, length and pattern limits, the SNAPPY/ZIP restriction on the intermediate
* S3 location, and the one-way S3 backup switch.
*/
final class RedshiftDestinationValidator {
private static final String JDBC_URL_REGEX =
"jdbc:(redshift|postgresql)://((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+(redshift(-serverless)?)\\.([a-zA-Z0-9\\.\\-]+):\\d{1,5}/[a-zA-Z0-9_$-]+";
private static final Pattern JDBC_URL = Pattern.compile(JDBC_URL_REGEX);
private static final String ROLE_ARN_REGEX = "arn:.*:iam::\\d{12}:role/[a-zA-Z_0-9+=,.@\\-_/]+";
private static final Pattern ROLE_ARN = Pattern.compile(ROLE_ARN_REGEX);
private static final String SECRET_ARN_REGEX =
"arn:.*:secretsmanager:[a-zA-Z0-9\\-]+:\\d{12}:secret:[a-zA-Z0-9\\-/_+=.@]+";
private static final Pattern SECRET_ARN = Pattern.compile(SECRET_ARN_REGEX);
private static final Pattern UNREADABLE_KEY_CHARS = Pattern.compile("[\\s'\"]");
private static final Set<String> BACKUP_MODES = Set.of("Disabled", "Enabled");
private static final Set<String> UNSUPPORTED_COMPRESSION = Set.of("zip", "snappy");
private RedshiftDestinationValidator() {}
static void validateConfiguration(RedshiftDestination config, String shapeName) {
List<String> violations = new ArrayList<>();
require(config.getRoleArn(), shapeName, "roleARN", violations);
require(config.getClusterJdbcUrl(), shapeName, "clusterJDBCURL", violations);
if (config.getCopyCommand() == null) {
violations.add(violation(shapeName, "copyCommand", "Member must not be null"));
}
if (config.getS3() == null) {
violations.add(violation(shapeName, "s3Configuration", "Member must not be null"));
} else {
requireS3Locators(config.getS3(), shapeName, "s3Configuration", violations);
}
if (config.getS3Backup() != null) {
requireS3Locators(config.getS3Backup(), shapeName, "s3BackupConfiguration", violations);
}
if ("Enabled".equals(config.getS3BackupMode()) && config.getS3Backup() == null) {
violations.add(violation(shapeName, "s3BackupConfiguration",
"Member must not be null when S3BackupMode is Enabled"));
}
collectMemberViolations(config, shapeName, violations);
throwIfAny(violations);
S3DestinationValidator.validateWireShape(config.getS3(), shapeName + ".s3Configuration");
if (config.getS3Backup() != null) {
S3DestinationValidator.validateWireShape(config.getS3Backup(), shapeName + ".s3BackupConfiguration");
}
}
static void validateUpdate(RedshiftDestination update, String shapeName) {
List<String> violations = new ArrayList<>();
collectMemberViolations(update, shapeName, violations);
throwIfAny(violations);
if (update.getS3() != null) {
S3DestinationValidator.validateWireShape(update.getS3(), shapeName + ".s3Update");
}
if (update.getS3Backup() != null) {
S3DestinationValidator.validateWireShape(update.getS3Backup(), shapeName + ".s3BackupUpdate");
}
}
/**
* A backup location an update supplies when none is stored yet is a whole new S3 configuration, so its required
* members must be present: the merge has nothing to take them from.
*/
static void validateNewBackup(S3Destination backup, String shapeName) {
List<String> violations = new ArrayList<>();
requireS3Locators(backup, shapeName, "s3BackupUpdate", violations);
throwIfAny(violations);
}
/** Backup can be switched on after creation but never off again. */
static void validateBackupTransition(String storedMode, String requestedMode) {
if ("Enabled".equals(storedMode) && "Disabled".equals(requestedMode)) {
throw new AwsException("InvalidArgumentException",
"S3 backup cannot be disabled once it is enabled.", 400);
}
}
private static void collectMemberViolations(RedshiftDestination dest, String shape, List<String> violations) {
String roleArn = dest.getRoleArn();
if (roleArn != null) {
checkLength(roleArn, 1, 512, shape, "roleARN", violations);
checkPattern(roleArn, ROLE_ARN, ROLE_ARN_REGEX, shape, "roleARN", violations);
}
String url = dest.getClusterJdbcUrl();
if (url != null) {
checkLength(url, 1, 512, shape, "clusterJDBCURL", violations);
checkPattern(url, JDBC_URL, JDBC_URL_REGEX, shape, "clusterJDBCURL", violations);
}
if (dest.getUsername() != null) {
checkLength(dest.getUsername(), 1, 512, shape, "username", violations);
}
if (dest.getPassword() != null) {
checkLength(dest.getPassword(), 6, 512, shape, "password", violations);
}
RedshiftDestination.CopyCommand copy = dest.getCopyCommand();
if (copy != null) {
// DataTableName is required inside CopyCommand on update too: the merge replaces the whole structure.
require(copy.getDataTableName(), shape, "copyCommand.dataTableName", violations);
if (copy.getDataTableName() != null) {
checkLength(copy.getDataTableName(), 1, 512, shape, "copyCommand.dataTableName", violations);
if (!RedshiftCopySql.isValidTableName(copy.getDataTableName())) {
violations.add(violation(shape, "copyCommand.dataTableName",
"Member must be a table name, optionally schema-qualified"));
}
}
if (copy.getCopyOptions() != null) {
checkLength(copy.getCopyOptions(), 0, 10240, shape, "copyCommand.copyOptions", violations);
if (RedshiftCopySql.hasStatementSeparator(copy.getCopyOptions())) {
violations.add(violation(shape, "copyCommand.copyOptions",
"Member must not contain ';', '$', '--' or '/*' outside a quoted value"));
}
}
if (copy.getDataTableColumns() != null) {
checkLength(copy.getDataTableColumns(), 0, 10240, shape, "copyCommand.dataTableColumns", violations);
if (!RedshiftCopySql.isValidColumnList(copy.getDataTableColumns())) {
violations.add(violation(shape, "copyCommand.dataTableColumns",
"Member must be a comma-separated list of column names"));
}
}
}
RedshiftDestination.RetryOptions retry = dest.getRetryOptions();
if (retry != null && retry.getDurationInSeconds() != null
&& (retry.getDurationInSeconds() < 0 || retry.getDurationInSeconds() > 7200)) {
violations.add(violation(shape, "retryOptions.durationInSeconds",
"Member must have value between 0 and 7200"));
}
if (dest.getS3BackupMode() != null && !BACKUP_MODES.contains(dest.getS3BackupMode())) {
violations.add(violation(shape, "s3BackupMode", "Member must satisfy enum value set: [Disabled, Enabled]"));
}
RedshiftDestination.SecretsManagerConfiguration secrets = dest.getSecretsManagerConfiguration();
if (secrets != null) {
if (secrets.getEnabled() == null) {
violations.add(violation(shape, "secretsManagerConfiguration.enabled", "Member must not be null"));
}
if (Boolean.TRUE.equals(secrets.getEnabled()) && secrets.getSecretArn() == null) {
violations.add(violation(shape, "secretsManagerConfiguration.secretARN",
"Member must not be null when Enabled is true"));
}
if (secrets.getRoleArn() != null) {
checkLength(secrets.getRoleArn(), 1, 512, shape, "secretsManagerConfiguration.roleARN", violations);
checkPattern(secrets.getRoleArn(), ROLE_ARN, ROLE_ARN_REGEX, shape,
"secretsManagerConfiguration.roleARN", violations);
}
if (secrets.getSecretArn() != null) {
checkLength(secrets.getSecretArn(), 1, 2048, shape, "secretsManagerConfiguration.secretARN", violations);
checkPattern(secrets.getSecretArn(), SECRET_ARN, SECRET_ARN_REGEX, shape,
"secretsManagerConfiguration.secretARN", violations);
}
}
S3Destination s3 = dest.getS3();
if (s3 != null && s3.getPrefix() != null && UNREADABLE_KEY_CHARS.matcher(s3.getPrefix()).find()) {
violations.add(violation(shape, "s3Configuration.prefix",
"Member must not contain whitespace or quotes: the Redshift COPY emulation cannot read such object keys"));
}
if (s3 != null && s3.getCompressionFormat() != null
&& UNSUPPORTED_COMPRESSION.contains(s3.getCompressionFormat().toLowerCase(Locale.ROOT))) {
violations.add(violation(shape, "s3Configuration.compressionFormat",
"Member must not be SNAPPY or ZIP: the Amazon Redshift COPY command cannot read these formats"));
}
}
/** The bucket and role an S3 configuration cannot do without: with no bucket, staging falls back to a shared one. */
private static void requireS3Locators(S3Destination s3, String shape, String member, List<String> violations) {
require(s3.getBucketArn(), shape, member + ".bucketARN", violations);
require(s3.getRoleArn(), shape, member + ".roleARN", violations);
}
private static void require(String value, String shape, String member, List<String> violations) {
if (value == null) {
violations.add(violation(shape, member, "Member must not be null"));
}
}
private static void checkLength(String value, int min, int max, String shape, String member,
List<String> violations) {
if (value.length() < min) {
violations.add(violation(shape, member, "Member must have length greater than or equal to " + min));
} else if (value.length() > max) {
violations.add(violation(shape, member, "Member must have length less than or equal to " + max));
}
}
private static void checkPattern(String value, Pattern pattern, String regex, String shape, String member,
List<String> violations) {
if (!pattern.matcher(value).matches()) {
violations.add(violation(shape, member, "Member must satisfy regular expression pattern: " + regex));
}
}
private static String violation(String shape, String member, String constraint) {
return "Value at '" + shape + "." + member + "' failed to satisfy constraint: " + constraint;
}
private static void throwIfAny(List<String> violations) {
if (!violations.isEmpty()) {
throw SmithyValidationErrors.validationException(violations);
}
}
}
@@ -0,0 +1,29 @@
package io.github.hectorvent.floci.services.firehose;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The logical address in a Firehose {@code ClusterJDBCURL}. Floci routes by the first host label
* (the cluster identifier or workgroup name) and ignores the host suffix and port, because a
* Floci cluster is reachable on a Docker host and a dynamic port, not on the AWS-shaped name the
* API requires.
*/
record RedshiftJdbcUrl(String clusterIdentifier, boolean serverless, String database) {
private static final Pattern URL = Pattern.compile(
"jdbc:(?:redshift|postgresql)://([A-Za-z0-9-]{1,63})\\.([A-Za-z0-9.\\-]+):\\d{1,5}/([a-zA-Z0-9_$-]+)");
private static final Pattern SERVICE_LABEL = Pattern.compile("(?:^|\\.)redshift(-serverless)?\\.");
static RedshiftJdbcUrl parse(String url) {
Matcher matcher = URL.matcher(url == null ? "" : url);
if (!matcher.matches()) {
throw new IllegalArgumentException("Unsupported ClusterJDBCURL: " + url);
}
Matcher service = SERVICE_LABEL.matcher(matcher.group(2));
if (!service.find()) {
throw new IllegalArgumentException("ClusterJDBCURL host is not a Redshift host: " + url);
}
return new RedshiftJdbcUrl(matcher.group(1), service.group(1) != null, matcher.group(3));
}
}
@@ -57,6 +57,11 @@ public class DeliveryStreamDescription {
}
public DeliveryStreamDescription(String name, String arn, S3Destination s3, KinesisStreamSource kinesisStreamSource) {
this(name, arn, s3, null, kinesisStreamSource);
}
public DeliveryStreamDescription(String name, String arn, S3Destination s3, RedshiftDestination redshift,
KinesisStreamSource kinesisStreamSource) {
this.deliveryStreamName = name;
this.deliveryStreamARN = arn;
this.deliveryStreamStatus = DeliveryStreamStatus.ACTIVE;
@@ -64,7 +69,10 @@ public class DeliveryStreamDescription {
if (s3 != null) {
s3.applyDefaults();
}
this.destinations = List.of(new Destination(s3));
if (redshift != null && redshift.getS3() != null) {
redshift.getS3().applyDefaults();
}
this.destinations = List.of(redshift != null ? new Destination(redshift) : new Destination(s3));
this.deliveryStreamEncryptionConfiguration = DeliveryStreamEncryptionConfiguration.disabled();
if (kinesisStreamSource != null) {
this.source = new Source(kinesisStreamSource);
@@ -155,7 +163,11 @@ public class DeliveryStreamDescription {
*/
public S3Destination s3Destination() {
if (destinations == null || destinations.isEmpty()) return null;
return destinations.get(0).getExtendedS3DestinationDescription();
Destination first = destinations.get(0);
if (first.getRedshiftDestinationDescription() != null) {
return first.getRedshiftDestinationDescription().getS3();
}
return first.getExtendedS3DestinationDescription();
}
@RegisterForReflection
@@ -171,8 +183,16 @@ public class DeliveryStreamDescription {
// extended-only fields like S3BackupMode aren't part of the plain shape.
private S3Destination s3;
private RedshiftDestination redshift;
public Destination() {}
public Destination(S3Destination s3) { this.s3 = s3; }
public Destination(RedshiftDestination redshift) { this.redshift = redshift; }
@JsonProperty("RedshiftDestinationDescription")
public RedshiftDestination getRedshiftDestinationDescription() { return redshift; }
@JsonProperty("RedshiftDestinationDescription")
public void setRedshiftDestinationDescription(RedshiftDestination redshift) { this.redshift = redshift; }
public String getDestinationId() { return destinationId; }
public void setDestinationId(String destinationId) { this.destinationId = destinationId; }
@@ -0,0 +1,154 @@
package io.github.hectorvent.floci.services.firehose.model;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.ProcessingConfiguration;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* One class for the Configuration, Update and Description shapes of a Redshift destination,
* the way {@link S3Destination} serves all of its shapes. The intermediate S3 location is read
* from {@code S3Configuration} or {@code S3Update} and written as {@code S3DestinationDescription}.
* The password is kept because delivery needs it; the describe handler strips it.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class RedshiftDestination {
@JsonProperty("RoleARN")
private String roleArn;
@JsonProperty("ClusterJDBCURL")
private String clusterJdbcUrl;
@JsonProperty("Username")
private String username;
@JsonProperty("Password")
private String password;
@JsonProperty("CopyCommand")
private CopyCommand copyCommand;
@JsonProperty("RetryOptions")
private RetryOptions retryOptions;
@JsonProperty("S3BackupMode")
private String s3BackupMode;
@JsonProperty("S3DestinationDescription")
@JsonAlias({"S3Configuration", "S3Update"})
private S3Destination s3;
@JsonProperty("S3BackupDescription")
@JsonAlias({"S3BackupConfiguration", "S3BackupUpdate"})
private S3Destination s3Backup;
@JsonProperty("SecretsManagerConfiguration")
private SecretsManagerConfiguration secretsManagerConfiguration;
@JsonProperty("ProcessingConfiguration")
private ProcessingConfiguration processingConfiguration;
@JsonProperty("CloudWatchLoggingOptions")
private JsonNode cloudWatchLoggingOptions;
public RedshiftDestination() {}
public String getRoleArn() { return roleArn; }
public void setRoleArn(String roleArn) { this.roleArn = roleArn; }
public String getClusterJdbcUrl() { return clusterJdbcUrl; }
public void setClusterJdbcUrl(String clusterJdbcUrl) { this.clusterJdbcUrl = clusterJdbcUrl; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
public CopyCommand getCopyCommand() { return copyCommand; }
public void setCopyCommand(CopyCommand copyCommand) { this.copyCommand = copyCommand; }
public RetryOptions getRetryOptions() { return retryOptions; }
public void setRetryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; }
public String getS3BackupMode() { return s3BackupMode; }
public void setS3BackupMode(String s3BackupMode) { this.s3BackupMode = s3BackupMode; }
public S3Destination getS3() { return s3; }
public void setS3(S3Destination s3) { this.s3 = s3; }
public S3Destination getS3Backup() { return s3Backup; }
public void setS3Backup(S3Destination s3Backup) { this.s3Backup = s3Backup; }
public SecretsManagerConfiguration getSecretsManagerConfiguration() { return secretsManagerConfiguration; }
public void setSecretsManagerConfiguration(SecretsManagerConfiguration configuration) {
this.secretsManagerConfiguration = configuration;
}
public ProcessingConfiguration getProcessingConfiguration() { return processingConfiguration; }
public void setProcessingConfiguration(ProcessingConfiguration processingConfiguration) {
this.processingConfiguration = processingConfiguration;
}
public JsonNode getCloudWatchLoggingOptions() { return cloudWatchLoggingOptions; }
public void setCloudWatchLoggingOptions(JsonNode cloudWatchLoggingOptions) {
this.cloudWatchLoggingOptions = cloudWatchLoggingOptions;
}
/** Shallow copy without the password, for responses. Nested objects are shared and must not be mutated. */
public RedshiftDestination copyWithoutPassword() {
RedshiftDestination copy = new RedshiftDestination();
copy.roleArn = roleArn;
copy.clusterJdbcUrl = clusterJdbcUrl;
copy.username = username;
copy.copyCommand = copyCommand;
copy.retryOptions = retryOptions;
copy.s3BackupMode = s3BackupMode;
copy.s3 = s3;
copy.s3Backup = s3Backup;
copy.secretsManagerConfiguration = secretsManagerConfiguration;
copy.processingConfiguration = processingConfiguration;
copy.cloudWatchLoggingOptions = cloudWatchLoggingOptions;
return copy;
}
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class CopyCommand {
@JsonProperty("DataTableName")
private String dataTableName;
@JsonProperty("CopyOptions")
private String copyOptions;
@JsonProperty("DataTableColumns")
private String dataTableColumns;
public CopyCommand() {}
public String getDataTableName() { return dataTableName; }
public void setDataTableName(String dataTableName) { this.dataTableName = dataTableName; }
public String getCopyOptions() { return copyOptions; }
public void setCopyOptions(String copyOptions) { this.copyOptions = copyOptions; }
public String getDataTableColumns() { return dataTableColumns; }
public void setDataTableColumns(String dataTableColumns) { this.dataTableColumns = dataTableColumns; }
}
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class RetryOptions {
@JsonProperty("DurationInSeconds")
private Integer durationInSeconds;
public RetryOptions() {}
public Integer getDurationInSeconds() { return durationInSeconds; }
public void setDurationInSeconds(Integer durationInSeconds) { this.durationInSeconds = durationInSeconds; }
}
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class SecretsManagerConfiguration {
@JsonProperty("Enabled")
private Boolean enabled;
@JsonProperty("SecretARN")
private String secretArn;
@JsonProperty("RoleARN")
private String roleArn;
public SecretsManagerConfiguration() {}
public Boolean getEnabled() { return enabled; }
public void setEnabled(Boolean enabled) { this.enabled = enabled; }
public String getSecretArn() { return secretArn; }
public void setSecretArn(String secretArn) { this.secretArn = secretArn; }
public String getRoleArn() { return roleArn; }
public void setRoleArn(String roleArn) { this.roleArn = roleArn; }
}
}