Light, fluffy, and always free - The AWS Local Emulator alternative
feat(firehose): accept a Redshift destination on create, update and describe (#6004)
Vũ Thế Huy484255871e2a
diff --git a/docs/services/firehose.md b/docs/services/firehose.mdindex 5f66dd3246..ca8a01a8fb 100644--- a/docs/services/firehose.md+++ b/docs/services/firehose.md@@ -123,6 +123,40 @@ Delivered objects are named `<evaluated prefix><streamName>-<versionId>-<yyyy-MMKnown deviations from AWS: timestamps are evaluated at flush time instead of the oldest buffered record's arrival time; expressions AWS would reject at create time (unknown namespaces, `!{partitionKeyFromQuery:...}`/`!{partitionKeyFromLambda:...}` dynamic partitioning keys, invalid patterns) are kept literally in the key; `FileExtension` is accepted on the legacy `S3DestinationConfiguration` shape too, where AWS only defines it on the extended one.+## Redshift destination++`CreateDeliveryStream` accepts `RedshiftDestinationConfiguration` and `UpdateDestination` accepts+`RedshiftDestinationUpdate`. A stream has either an S3 destination or a Redshift destination, never both.+`DescribeDeliveryStream` returns `RedshiftDestinationDescription`, which never includes `Password`.++Supported members: `RoleARN`, `ClusterJDBCURL`, `Username`, `Password`, `CopyCommand`+(`DataTableName`, `CopyOptions`, `DataTableColumns`), `S3Configuration` (the intermediate S3 location),+`RetryOptions`, `S3BackupMode` with `S3BackupConfiguration`, `SecretsManagerConfiguration`,+`ProcessingConfiguration` and `CloudWatchLoggingOptions`. Members are validated against the Firehose API+model: required members, length and pattern limits, and the rule that `SNAPPY` and `ZIP` are refused on the+intermediate S3 location. `S3BackupMode` can be switched on after creation but not off again.++`DataTableName` and `DataTableColumns` must be identifiers Redshift would read as such: a table name with an optional+schema, and a comma-separated list of column names. `CopyOptions` must not carry a second statement, so outside a+quoted value a `;`, a `$` (dollar quoting is never needed) and the comment markers `--` and `/*` are refused, as is an+unterminated quote. One closing `;` at the very end is the exception (the API reference's own example,+`delimiter '\t' lzop;`, is accepted). Create and update reject anything else.++This release accepts and stores the destination and stages each batch in the intermediate S3 location, like an+S3 destination. It does not run the `COPY` into the cluster yet, and `S3BackupMode` has no effect on what is written.++### Known deviations from AWS++- `ClusterJDBCURL` must match the AWS pattern, so it needs a host such as+ `mycluster.abc123.us-east-1.redshift.amazonaws.com`. Floci treats the URL as a logical address: the first+ host label is the cluster identifier, and the host suffix and port are ignored. The database name is ignored+ too, because the emulated database is always `dev`. The cluster is not looked up when the stream is created, so a stream+ can be created before its cluster.+- `ProcessingConfiguration` on a Redshift destination is accepted and returned but not executed.+- The intermediate `Prefix` must not contain whitespace or quotes, because the `COPY` emulation cannot read such+ object keys. `DataFormatConversionConfiguration` is ignored on the Redshift `S3Configuration`, which AWS does not+ define.+## Configuration| Variable | Default | Description |diff --git a/src/main/java/io/github/hectorvent/floci/services/firehose/FirehoseJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/firehose/FirehoseJsonHandler.javaindex 801bfa1cd3..619723bd74 100644--- a/src/main/java/io/github/hectorvent/floci/services/firehose/FirehoseJsonHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/firehose/FirehoseJsonHandler.java@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescriptimport 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}diff --git a/src/main/java/io/github/hectorvent/floci/services/firehose/FirehoseService.java b/src/main/java/io/github/hectorvent/floci/services/firehose/FirehoseService.javaindex aa5b744fdc..6959acdf75 100644--- a/src/main/java/io/github/hectorvent/floci/services/firehose/FirehoseService.java+++ b/src/main/java/io/github/hectorvent/floci/services/firehose/FirehoseService.java@@ -15,6 +15,7 @@ import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescriptimport 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.diff --git a/src/main/java/io/github/hectorvent/floci/services/firehose/RedshiftCopySql.java b/src/main/java/io/github/hectorvent/floci/services/firehose/RedshiftCopySql.javanew file mode 100644index 0000000000..94ba37864e--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/firehose/RedshiftCopySql.java@@ -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;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/firehose/RedshiftDestinationValidator.java b/src/main/java/io/github/hectorvent/floci/services/firehose/RedshiftDestinationValidator.javanew file mode 100644index 0000000000..f508736ece--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/firehose/RedshiftDestinationValidator.java@@ -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);+ }+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/firehose/RedshiftJdbcUrl.java b/src/main/java/io/github/hectorvent/floci/services/firehose/RedshiftJdbcUrl.javanew file mode 100644index 0000000000..599ba11272--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/firehose/RedshiftJdbcUrl.java@@ -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));+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/firehose/model/DeliveryStreamDescription.java b/src/main/java/io/github/hectorvent/floci/services/firehose/model/DeliveryStreamDescription.javaindex 8208913b08..9b71a9c4b4 100644--- a/src/main/java/io/github/hectorvent/floci/services/firehose/model/DeliveryStreamDescription.java+++ b/src/main/java/io/github/hectorvent/floci/services/firehose/model/DeliveryStreamDescription.java@@ -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; }diff --git a/src/main/java/io/github/hectorvent/floci/services/firehose/model/RedshiftDestination.java b/src/main/java/io/github/hectorvent/floci/services/firehose/model/RedshiftDestination.javanew file mode 100644index 0000000000..69abc2e281--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/firehose/model/RedshiftDestination.java@@ -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; }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/firehose/FirehoseRedshiftDestinationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/firehose/FirehoseRedshiftDestinationIntegrationTest.javanew file mode 100644index 0000000000..31f732df47--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/firehose/FirehoseRedshiftDestinationIntegrationTest.java@@ -0,0 +1,361 @@+package io.github.hectorvent.floci.services.firehose;++import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.response.ValidatableResponse;+import jakarta.inject.Inject;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import java.nio.charset.StandardCharsets;+import java.util.Base64;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.nullValue;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;++/** Wire-level coverage of the Redshift destination shape on CreateDeliveryStream and UpdateDestination. */+@QuarkusTest+class FirehoseRedshiftDestinationIntegrationTest {++ private static final String CONTENT_TYPE = "application/x-amz-json-1.1";+ private static final String TARGET_PREFIX = "Firehose_20150804.";+ private static final String JDBC_URL = "jdbc:redshift://c1.abc.us-east-1.redshift.amazonaws.com:5439/dev";+ private static final String DESTINATION_ID = "destinationId-000000000001";++ private static final String RS_CONFIG = """+ {+ "DeliveryStreamName": "%s",+ "RedshiftDestinationConfiguration": {+ "RoleARN": "arn:aws:iam::000000000000:role/firehose",+ "ClusterJDBCURL": "%s",+ "Username": "admin", "Password": "Secret123",+ "CopyCommand": {"DataTableName": "events", "CopyOptions": "json 'auto'"},+ "S3Configuration": {"RoleARN": "arn:aws:iam::000000000000:role/firehose", "BucketARN": "arn:aws:s3:::%s"}+ }+ }+ """;++ @Inject+ FirehoseService firehoseService;++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ private static ValidatableResponse post(String action, String body) {+ return given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", TARGET_PREFIX + action)+ .body(body)+ .when()+ .post("/")+ .then();+ }++ private static String createBody(String name, String bucket) {+ return RS_CONFIG.formatted(name, JDBC_URL, bucket);+ }++ private static void assertStreamAbsent(String name) {+ post("DescribeDeliveryStream", "{\"DeliveryStreamName\": \"" + name + "\"}")+ .statusCode(400).body("__type", equalTo("ResourceNotFoundException"));+ }++ /** A rejected update must leave the stored destination and its version exactly as they were. */+ private static void assertUnchanged(String name, String version, String table) {+ post("DescribeDeliveryStream", "{\"DeliveryStreamName\": \"" + name + "\"}")+ .statusCode(200)+ .body("DeliveryStreamDescription.VersionId", equalTo(version))+ .body("DeliveryStreamDescription.Destinations[0].RedshiftDestinationDescription"+ + ".CopyCommand.DataTableName", equalTo(table))+ .body("DeliveryStreamDescription.Destinations[0].RedshiftDestinationDescription"+ + ".S3BackupMode", nullValue());+ }++ @Test+ void createAndDescribeNeverReturnsThePassword() {+ post("CreateDeliveryStream", createBody("rs-describe", "rs-describe-stage")).statusCode(200);++ post("DescribeDeliveryStream", "{\"DeliveryStreamName\": \"rs-describe\"}")+ .statusCode(200)+ .body("DeliveryStreamDescription.Destinations[0].RedshiftDestinationDescription.ClusterJDBCURL",+ equalTo(JDBC_URL))+ .body("DeliveryStreamDescription.Destinations[0].RedshiftDestinationDescription.Username",+ equalTo("admin"))+ .body("DeliveryStreamDescription.Destinations[0].RedshiftDestinationDescription.Password",+ nullValue())+ .body("DeliveryStreamDescription.Destinations[0].RedshiftDestinationDescription"+ + ".S3DestinationDescription.BucketARN", equalTo("arn:aws:s3:::rs-describe-stage"))+ .body("DeliveryStreamDescription.Destinations[0].ExtendedS3DestinationDescription", nullValue());+ }++ @Test+ void describeDoesNotStripThePasswordFromTheStoredStream() {+ post("CreateDeliveryStream", createBody("rs-keeps-password", "rs-keeps-password-stage")).statusCode(200);++ post("DescribeDeliveryStream", "{\"DeliveryStreamName\": \"rs-keeps-password\"}").statusCode(200);++ String stored = firehoseService.describeDeliveryStream("rs-keeps-password")+ .getDestinations().get(0).getRedshiftDestinationDescription().getPassword();+ assertEquals("Secret123", stored);+ }++ @Test+ void createRejectsTwoDestinationConfigurations() {+ String body = createBody("rs-two", "rs-two-stage")+ .replace("\"RedshiftDestinationConfiguration\"",+ "\"ExtendedS3DestinationConfiguration\": {\"RoleARN\": \"arn:aws:iam::000000000000:role/r\","+ + " \"BucketARN\": \"arn:aws:s3:::b\"}, \"RedshiftDestinationConfiguration\"");++ post("CreateDeliveryStream", body).statusCode(400).body("__type", equalTo("InvalidArgumentException"));+ assertStreamAbsent("rs-two");+ }++ @Test+ void createRejectsAJdbcUrlThatDoesNotMatchTheAwsPattern() {+ String body = RS_CONFIG.formatted("rs-bad-url", "jdbc:postgresql://localhost:5432/dev", "rs-bad-url-stage");++ post("CreateDeliveryStream", body).statusCode(400)+ .body("message", containsString("clusterJDBCURL"));+ assertStreamAbsent("rs-bad-url");+ }++ @Test+ void createRejectsAnIntermediateConfigurationWithoutABucketOrRole() {+ String body = createBody("rs-no-bucket", "unused")+ .replace("\"S3Configuration\": {\"RoleARN\": \"arn:aws:iam::000000000000:role/firehose\","+ + " \"BucketARN\": \"arn:aws:s3:::unused\"}", "\"S3Configuration\": {}");++ post("CreateDeliveryStream", body).statusCode(400)+ .body("message", containsString("s3Configuration.bucketARN"))+ .body("message", containsString("s3Configuration.roleARN"));+ assertStreamAbsent("rs-no-bucket");+ }++ @Test+ void createRejectsABackupConfigurationWithoutABucket() {+ String body = createBody("rs-backup-no-bucket", "rs-backup-no-bucket-stage")+ .replace("\"Username\": \"admin\"", "\"S3BackupMode\": \"Enabled\","+ + " \"S3BackupConfiguration\": {\"RoleARN\": \"arn:aws:iam::000000000000:role/firehose\"},"+ + " \"Username\": \"admin\"");++ post("CreateDeliveryStream", body).statusCode(400)+ .body("message", containsString("s3BackupConfiguration.bucketARN"));+ assertStreamAbsent("rs-backup-no-bucket");+ }++ @Test+ void createRejectsOnlyHalfOfTheBackupBufferingHints() {+ String body = createBody("rs-backup-hints", "rs-backup-hints-stage")+ .replace("\"Username\": \"admin\"", "\"S3BackupMode\": \"Enabled\","+ + " \"S3BackupConfiguration\": {\"RoleARN\": \"arn:aws:iam::000000000000:role/firehose\","+ + " \"BucketARN\": \"arn:aws:s3:::rs-backup-hints-copy\","+ + " \"BufferingHints\": {\"SizeInMBs\": 5}}, \"Username\": \"admin\"");++ post("CreateDeliveryStream", body).statusCode(400).body("__type", equalTo("InvalidArgumentException"));+ assertStreamAbsent("rs-backup-hints");+ }++ @Test+ void createRejectsAMalformedSecretsManagerRole() {+ String body = createBody("rs-secret-role", "rs-secret-role-stage")+ .replace("\"Username\": \"admin\"", "\"SecretsManagerConfiguration\": {\"Enabled\": false,"+ + " \"RoleARN\": \"not-an-arn\"}, \"Username\": \"admin\"");++ post("CreateDeliveryStream", body).statusCode(400)+ .body("message", containsString("secretsManagerConfiguration.roleARN"));+ assertStreamAbsent("rs-secret-role");+ }++ @Test+ void updateAfterDeleteDoesNotBringTheStreamBack() {+ post("CreateDeliveryStream", createBody("rs-deleted", "rs-deleted-stage")).statusCode(200);+ post("DeleteDeliveryStream", "{\"DeliveryStreamName\": \"rs-deleted\"}").statusCode(200);++ post("UpdateDestination", """+ {"DeliveryStreamName": "rs-deleted", "CurrentDeliveryStreamVersionId": "1",+ "DestinationId": "%s",+ "RedshiftDestinationUpdate": {"CopyCommand": {"DataTableName": "events2"}}}+ """.formatted(DESTINATION_ID)).statusCode(400).body("__type", equalTo("ResourceNotFoundException"));+ assertStreamAbsent("rs-deleted");+ }++ @Test+ void updateDestinationChangesTheCopyCommandAndBumpsTheVersion() {+ post("CreateDeliveryStream", createBody("rs-update", "rs-update-stage")).statusCode(200);++ post("UpdateDestination", """+ {"DeliveryStreamName": "rs-update", "CurrentDeliveryStreamVersionId": "1",+ "DestinationId": "%s",+ "RedshiftDestinationUpdate": {"CopyCommand": {"DataTableName": "events2"}}}+ """.formatted(DESTINATION_ID)).statusCode(200);++ post("DescribeDeliveryStream", "{\"DeliveryStreamName\": \"rs-update\"}")+ .body("DeliveryStreamDescription.VersionId", equalTo("2"))+ .body("DeliveryStreamDescription.Destinations[0].RedshiftDestinationDescription"+ + ".CopyCommand.DataTableName", equalTo("events2"));+ }++ @Test+ void s3UpdateOnARedshiftStreamIsRejected() {+ post("CreateDeliveryStream", createBody("rs-wrong-update", "rs-wrong-update-stage")).statusCode(200);++ post("UpdateDestination", """+ {"DeliveryStreamName": "rs-wrong-update", "CurrentDeliveryStreamVersionId": "1",+ "DestinationId": "%s",+ "ExtendedS3DestinationUpdate": {"BucketARN": "arn:aws:s3:::other"}}+ """.formatted(DESTINATION_ID)).statusCode(400).body("__type", equalTo("InvalidArgumentException"));+ assertUnchanged("rs-wrong-update", "1", "events");+ }++ @Test+ void backupCanBeEnabledButNotDisabledAgain() {+ post("CreateDeliveryStream", createBody("rs-backup", "rs-backup-stage")).statusCode(200);++ post("UpdateDestination", """+ {"DeliveryStreamName": "rs-backup", "CurrentDeliveryStreamVersionId": "1",+ "DestinationId": "%s",+ "RedshiftDestinationUpdate": {"S3BackupMode": "Enabled",+ "S3BackupUpdate": {"RoleARN": "arn:aws:iam::000000000000:role/firehose",+ "BucketARN": "arn:aws:s3:::rs-backup-copy"}}}+ """.formatted(DESTINATION_ID)).statusCode(200);++ post("UpdateDestination", """+ {"DeliveryStreamName": "rs-backup", "CurrentDeliveryStreamVersionId": "2",+ "DestinationId": "%s",+ "RedshiftDestinationUpdate": {"S3BackupMode": "Disabled"}}+ """.formatted(DESTINATION_ID)).statusCode(400);+ }++ @Test+ void flushStagesTheBatchInTheIntermediateBucket() {+ post("CreateDeliveryStream", createBody("rs-flush", "rs-flush-stage")).statusCode(200);+ String data = Base64.getEncoder().encodeToString("{\"id\":1}".getBytes(StandardCharsets.UTF_8));+ post("PutRecord", "{\"DeliveryStreamName\": \"rs-flush\", \"Record\": {\"Data\": \"" + data + "\"}}")+ .statusCode(200);++ firehoseService.flush("rs-flush");++ String listing = given().when().get("/rs-flush-stage").then().statusCode(200).extract().asString();+ assertTrue(listing.contains("<Key>"),+ "expected a staged object in rs-flush-stage, got: " + listing);+ }++ @Test+ void partialBackupUpdateKeepsTheBackupBucket() {+ post("CreateDeliveryStream", createBody("rs-backup-merge", "rs-backup-merge-stage")).statusCode(200);+ post("UpdateDestination", """+ {"DeliveryStreamName": "rs-backup-merge", "CurrentDeliveryStreamVersionId": "1",+ "DestinationId": "%s",+ "RedshiftDestinationUpdate": {"S3BackupMode": "Enabled",+ "S3BackupUpdate": {"RoleARN": "arn:aws:iam::000000000000:role/firehose",+ "BucketARN": "arn:aws:s3:::rs-backup-merge-copy"}}}+ """.formatted(DESTINATION_ID)).statusCode(200);++ post("UpdateDestination", """+ {"DeliveryStreamName": "rs-backup-merge", "CurrentDeliveryStreamVersionId": "2",+ "DestinationId": "%s",+ "RedshiftDestinationUpdate": {"S3BackupUpdate": {"Prefix": "bk/"}}}+ """.formatted(DESTINATION_ID)).statusCode(200);++ post("DescribeDeliveryStream", "{\"DeliveryStreamName\": \"rs-backup-merge\"}")+ .body("DeliveryStreamDescription.Destinations[0].RedshiftDestinationDescription"+ + ".S3BackupDescription.BucketARN", equalTo("arn:aws:s3:::rs-backup-merge-copy"))+ .body("DeliveryStreamDescription.Destinations[0].RedshiftDestinationDescription"+ + ".S3BackupDescription.Prefix", equalTo("bk/"));+ }++ @Test+ void updateCopyCommandWithoutATableNameIsRejected() {+ post("CreateDeliveryStream", createBody("rs-copy-no-table", "rs-copy-no-table-stage")).statusCode(200);++ post("UpdateDestination", """+ {"DeliveryStreamName": "rs-copy-no-table", "CurrentDeliveryStreamVersionId": "1",+ "DestinationId": "%s",+ "RedshiftDestinationUpdate": {"CopyCommand": {"CopyOptions": "CSV"}}}+ """.formatted(DESTINATION_ID)).statusCode(400);+ assertUnchanged("rs-copy-no-table", "1", "events");+ }++ @Test+ void updateRejectsANewBackupWithoutABucketAndKeepsTheStream() {+ post("CreateDeliveryStream", createBody("rs-new-backup", "rs-new-backup-stage")).statusCode(200);++ post("UpdateDestination", """+ {"DeliveryStreamName": "rs-new-backup", "CurrentDeliveryStreamVersionId": "1",+ "DestinationId": "%s",+ "RedshiftDestinationUpdate": {"S3BackupMode": "Enabled",+ "S3BackupUpdate": {"Prefix": "bk/"}}}+ """.formatted(DESTINATION_ID)).statusCode(400)+ .body("message", containsString("s3BackupUpdate.bucketARN"));+ assertUnchanged("rs-new-backup", "1", "events");+ }++ @Test+ void updateRejectsOnlyHalfOfTheBackupBufferingHints() {+ post("CreateDeliveryStream", createBody("rs-upd-hints", "rs-upd-hints-stage")).statusCode(200);++ post("UpdateDestination", """+ {"DeliveryStreamName": "rs-upd-hints", "CurrentDeliveryStreamVersionId": "1",+ "DestinationId": "%s",+ "RedshiftDestinationUpdate": {"S3BackupMode": "Enabled",+ "S3BackupUpdate": {"RoleARN": "arn:aws:iam::000000000000:role/firehose",+ "BucketARN": "arn:aws:s3:::rs-upd-hints-copy",+ "BufferingHints": {"IntervalInSeconds": 60}}}}+ """.formatted(DESTINATION_ID)).statusCode(400).body("__type", equalTo("InvalidArgumentException"));+ assertUnchanged("rs-upd-hints", "1", "events");+ }++ @Test+ void explicitNullRedshiftConfigurationIsTreatedAsAbsent() {+ post("CreateDeliveryStream", """+ {"DeliveryStreamName": "rs-null-config", "RedshiftDestinationConfiguration": null}+ """).statusCode(200);+ }++ @Test+ void dataFormatConversionInTheIntermediateS3ConfigurationIsIgnored() {+ String body = createBody("rs-conversion", "rs-conversion-stage")+ .replace("\"BucketARN\": \"arn:aws:s3:::rs-conversion-stage\"",+ "\"BucketARN\": \"arn:aws:s3:::rs-conversion-stage\","+ + " \"DataFormatConversionConfiguration\": {\"Enabled\": true}");+ post("CreateDeliveryStream", body).statusCode(200);++ post("DescribeDeliveryStream", "{\"DeliveryStreamName\": \"rs-conversion\"}")+ .body("DeliveryStreamDescription.Destinations[0].RedshiftDestinationDescription"+ + ".S3DestinationDescription.DataFormatConversionConfiguration", nullValue());+ }++ @Test+ void createRejectsBackupEnabledWithoutABackupConfiguration() {+ String body = createBody("rs-backup-missing", "rs-backup-missing-stage")+ .replace("\"Username\": \"admin\"", "\"S3BackupMode\": \"Enabled\", \"Username\": \"admin\"");++ post("CreateDeliveryStream", body).statusCode(400);+ }++ @Test+ void updateRejectsBackupEnabledWithoutABackupConfiguration() {+ post("CreateDeliveryStream", createBody("rs-backup-missing-upd", "rs-backup-missing-upd-stage")).statusCode(200);++ post("UpdateDestination", """+ {"DeliveryStreamName": "rs-backup-missing-upd", "CurrentDeliveryStreamVersionId": "1",+ "DestinationId": "%s",+ "RedshiftDestinationUpdate": {"S3BackupMode": "Enabled"}}+ """.formatted(DESTINATION_ID)).statusCode(400);+ }++ @Test+ void createRejectsAnIntermediatePrefixTheCopyEmulationCannotRead() {+ String body = createBody("rs-bad-prefix", "rs-bad-prefix-stage")+ .replace("\"BucketARN\": \"arn:aws:s3:::rs-bad-prefix-stage\"",+ "\"BucketARN\": \"arn:aws:s3:::rs-bad-prefix-stage\", \"Prefix\": \"my prefix/\"");++ post("CreateDeliveryStream", body).statusCode(400);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/firehose/RedshiftCopySqlTest.java b/src/test/java/io/github/hectorvent/floci/services/firehose/RedshiftCopySqlTest.javanew file mode 100644index 0000000000..8f0a7e960c--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/firehose/RedshiftCopySqlTest.java@@ -0,0 +1,127 @@+package io.github.hectorvent.floci.services.firehose;++import org.junit.jupiter.api.Test;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;++class RedshiftCopySqlTest {++ @Test+ void qualifiedAndQuotedTableNamesAreAccepted() {+ for (String table : new String[] {"events", "Public.MyEvents", "\"my schema\".\"t\""}) {+ assertTrue(RedshiftCopySql.isValidTableName(table), table);+ }+ }++ @Test+ void tableNameThatIsNotAnIdentifierIsRejected() {+ for (String table : new String[] {"t; DROP TABLE x", "a.b.c", "ev\"il", "t (id)", "", null}) {+ assertFalse(RedshiftCopySql.isValidTableName(table), String.valueOf(table));+ }+ }++ @Test+ void columnThatIsNotAnIdentifierIsRejected() {+ assertFalse(RedshiftCopySql.isValidColumnList("id, name); DROP TABLE t; --"));+ assertTrue(RedshiftCopySql.isValidColumnList("Id, \"Full Name\""));+ assertTrue(RedshiftCopySql.isValidColumnList(null));+ }++ @Test+ void statementSeparatorOutsideQuotesIsDetected() {+ assertTrue(RedshiftCopySql.hasStatementSeparator("gzip; DROP TABLE t"));+ }++ @Test+ void semicolonInsideAQuotedCopyOptionValueIsAllowed() {+ assertFalse(RedshiftCopySql.hasStatementSeparator("DELIMITER ';' CSV"));+ }++ @Test+ void apiReferenceCopyOptionsExampleIsAccepted() {+ assertFalse(RedshiftCopySql.hasStatementSeparator("delimiter '\\t' lzop;"));+ }++ @Test+ void oneClosingTerminatorIsAcceptedWithWhitespaceAroundIt() {+ assertFalse(RedshiftCopySql.hasStatementSeparator("gzip ;"));+ assertFalse(RedshiftCopySql.hasStatementSeparator("gzip; \n"));+ }++ @Test+ void terminatorFollowedByAnythingIsRefused() {+ assertTrue(RedshiftCopySql.hasStatementSeparator("gzip;;"));+ assertTrue(RedshiftCopySql.hasStatementSeparator("gzip; DROP TABLE t;"));+ assertTrue(RedshiftCopySql.hasStatementSeparator("gzip; -- x"));+ }++ @Test+ void terminatorInsideAnUnclosedLiteralIsRefused() {+ assertTrue(RedshiftCopySql.hasStatementSeparator("NULL AS 'a;"));+ }++ @Test+ void withoutTrailingTerminatorDropsOnlyTheClosingSemicolon() {+ assertEquals("gzip", RedshiftCopySql.withoutTrailingTerminator("gzip ; "));+ assertEquals("DELIMITER ';'", RedshiftCopySql.withoutTrailingTerminator("DELIMITER ';'"));+ assertEquals("gzip", RedshiftCopySql.withoutTrailingTerminator("gzip"));+ }++ @Test+ void separatorScanHandlesEscapedQuotes() {+ assertFalse(RedshiftCopySql.hasStatementSeparator("NULL AS 'it''s;ok'"));+ assertTrue(RedshiftCopySql.hasStatementSeparator("NULL AS 'it''s' ; DROP"));+ }++ @Test+ void doubleQuotedValueMayContainASemicolon() {+ assertFalse(RedshiftCopySql.hasStatementSeparator("DELIMITER \";\" CSV"));+ }++ @Test+ void escapeStringCannotHideASecondStatement() {+ assertTrue(RedshiftCopySql.hasStatementSeparator("NULL AS E'\\'';DROP TABLE t;--'"));+ }++ @Test+ void quoteInsideADoubleQuotedIdentifierCannotHideASecondStatement() {+ assertTrue(RedshiftCopySql.hasStatementSeparator("\"a'b\"; DROP TABLE t; --'"));+ }++ @Test+ void escapeStringKeepsAnEscapedQuoteInsideTheLiteral() {+ assertFalse(RedshiftCopySql.hasStatementSeparator("NULL AS E'it\\'s;ok'"));+ }++ @Test+ void dollarQuoteTagsWithDigitsOrNonAsciiLettersCannotHideASecondStatement() {+ assertTrue(RedshiftCopySql.hasStatementSeparator("NULL AS $a1$'$a1$; drop table t; --'"));+ assertTrue(RedshiftCopySql.hasStatementSeparator("NULL AS $é$'$é$;x;--'"));+ assertTrue(RedshiftCopySql.hasStatementSeparator("NULL AS $_tag9$ x $_tag9$"));+ }++ @Test+ void dollarQuoteTagOutsideTheBasicPlaneCannotHideASecondStatement() {+ assertTrue(RedshiftCopySql.hasStatementSeparator("NULL AS $😀$'$😀$; drop table t; --'"));+ }++ @Test+ void dollarSignInsideAQuotedLiteralIsAllowed() {+ assertFalse(RedshiftCopySql.hasStatementSeparator("NULL AS 'a$b$' CSV"));+ assertFalse(RedshiftCopySql.hasStatementSeparator("DELIMITER \"$\" CSV"));+ }++ @Test+ void anyDollarSignOutsideAQuotedLiteralIsRefused() {+ assertTrue(RedshiftCopySql.hasStatementSeparator("NULL AS $x"));+ }++ @Test+ void dollarQuotingAndCommentsAreRefused() {+ assertTrue(RedshiftCopySql.hasStatementSeparator("NULL AS $$'$$ gzip"));+ assertTrue(RedshiftCopySql.hasStatementSeparator("gzip -- trailing"));+ assertTrue(RedshiftCopySql.hasStatementSeparator("gzip /* x */"));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/firehose/RedshiftDestinationModelTest.java b/src/test/java/io/github/hectorvent/floci/services/firehose/RedshiftDestinationModelTest.javanew file mode 100644index 0000000000..58f7b30945--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/firehose/RedshiftDestinationModelTest.java@@ -0,0 +1,93 @@+package io.github.hectorvent.floci.services.firehose;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription;+import io.github.hectorvent.floci.services.firehose.model.RedshiftDestination;+import org.junit.jupiter.api.Test;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertNull;++class RedshiftDestinationModelTest {++ private static final String CONFIG = """+ {+ "RoleARN": "arn:aws:iam::000000000000:role/firehose",+ "ClusterJDBCURL": "jdbc:redshift://c1.abc.us-east-1.redshift.amazonaws.com:5439/dev",+ "Username": "admin",+ "Password": "Secret123",+ "CopyCommand": {"DataTableName": "events", "CopyOptions": "json 'auto'", "DataTableColumns": "id,name"},+ "RetryOptions": {"DurationInSeconds": 120},+ "S3BackupMode": "Disabled",+ "S3Configuration": {"RoleARN": "arn:aws:iam::000000000000:role/firehose", "BucketARN": "arn:aws:s3:::stage"},+ "S3BackupConfiguration": {"RoleARN": "arn:aws:iam::000000000000:role/firehose", "BucketARN": "arn:aws:s3:::backup"}+ }+ """;++ private final ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();++ @Test+ void configurationShapeMapsToDescriptionKeys() throws Exception {+ RedshiftDestination dest = mapper.readValue(CONFIG, RedshiftDestination.class);++ assertEquals("events", dest.getCopyCommand().getDataTableName());+ assertEquals(120, dest.getRetryOptions().getDurationInSeconds());+ assertEquals("stage", dest.getS3().bucketName());+ assertEquals("backup", dest.getS3Backup().bucketName());++ JsonNode out = mapper.readTree(mapper.writeValueAsString(dest));+ assertEquals("arn:aws:s3:::stage", out.get("S3DestinationDescription").get("BucketARN").asText());+ assertNotNull(out.get("S3BackupDescription"));+ assertFalse(out.has("S3Configuration"));+ }++ @Test+ void updateShapeAliasesAreAccepted() throws Exception {+ RedshiftDestination dest = mapper.readValue(+ "{\"S3Update\": {\"BucketARN\": \"arn:aws:s3:::next\"}, \"S3BackupUpdate\": {\"BucketARN\": \"arn:aws:s3:::nextbk\"}}",+ RedshiftDestination.class);++ assertEquals("next", dest.getS3().bucketName());+ assertEquals("nextbk", dest.getS3Backup().bucketName());+ }++ @Test+ void copyWithoutPasswordDropsOnlyThePassword() throws Exception {+ RedshiftDestination dest = mapper.readValue(CONFIG, RedshiftDestination.class);++ RedshiftDestination redacted = dest.copyWithoutPassword();++ assertNull(redacted.getPassword());+ assertEquals("admin", redacted.getUsername());+ assertEquals("Secret123", dest.getPassword());+ }++ @Test+ void streamWithRedshiftDestinationExposesIntermediateS3AndSurvivesReload() throws Exception {+ RedshiftDestination dest = mapper.readValue(CONFIG, RedshiftDestination.class);++ DeliveryStreamDescription stream = new DeliveryStreamDescription("s",+ "arn:aws:firehose:us-east-1:000000000000:deliverystream/s", null, dest, null);++ assertEquals("stage", stream.s3Destination().bucketName());+ assertNotNull(stream.s3Destination().getBufferingHints());++ DeliveryStreamDescription reloaded =+ mapper.readValue(mapper.writeValueAsString(stream), DeliveryStreamDescription.class);+ assertEquals("Secret123", reloaded.getDestinations().get(0).getRedshiftDestinationDescription().getPassword());+ assertEquals("stage", reloaded.s3Destination().bucketName());+ }++ @Test+ void redshiftStreamWithoutBucketHasNoBucketName() throws Exception {+ RedshiftDestination dest = mapper.readValue(+ "{\"S3Configuration\": {\"RoleARN\": \"arn:aws:iam::000000000000:role/r\"}}", RedshiftDestination.class);++ DeliveryStreamDescription stream = new DeliveryStreamDescription("s", "arn", null, dest, null);++ assertNull(stream.s3Destination().bucketName());+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/firehose/RedshiftDestinationValidatorTest.java b/src/test/java/io/github/hectorvent/floci/services/firehose/RedshiftDestinationValidatorTest.javanew file mode 100644index 0000000000..e594b3d99c--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/firehose/RedshiftDestinationValidatorTest.java@@ -0,0 +1,218 @@+package io.github.hectorvent.floci.services.firehose;++import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination;+import io.github.hectorvent.floci.services.firehose.model.RedshiftDestination;+import org.junit.jupiter.api.Test;++import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++class RedshiftDestinationValidatorTest {++ private static final String SHAPE = "redshiftDestinationConfiguration";+ private final ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();++ private RedshiftDestination valid() throws Exception {+ return mapper.readValue("""+ {+ "RoleARN": "arn:aws:iam::000000000000:role/firehose",+ "ClusterJDBCURL": "jdbc:redshift://c1.abc.us-east-1.redshift.amazonaws.com:5439/dev",+ "Username": "admin", "Password": "Secret123",+ "CopyCommand": {"DataTableName": "events"},+ "S3Configuration": {"RoleARN": "arn:aws:iam::000000000000:role/firehose", "BucketARN": "arn:aws:s3:::stage"}+ }+ """, RedshiftDestination.class);+ }++ private static String messageOf(RedshiftDestination dest) {+ AwsException e = assertThrows(AwsException.class,+ () -> RedshiftDestinationValidator.validateConfiguration(dest, SHAPE));+ return e.getMessage();+ }++ @Test+ void validConfigurationPasses() throws Exception {+ RedshiftDestination dest = valid();++ assertDoesNotThrow(() -> RedshiftDestinationValidator.validateConfiguration(dest, SHAPE));+ }++ @Test+ void missingRequiredMembersAreReported() throws Exception {+ RedshiftDestination dest = valid();+ dest.setRoleArn(null);+ dest.setClusterJdbcUrl(null);+ dest.setCopyCommand(null);+ dest.setS3(null);++ String message = messageOf(dest);++ assertTrue(message.contains("redshiftDestinationConfiguration.roleARN"), message);+ assertTrue(message.contains("redshiftDestinationConfiguration.clusterJDBCURL"), message);+ assertTrue(message.contains("redshiftDestinationConfiguration.copyCommand"), message);+ assertTrue(message.contains("redshiftDestinationConfiguration.s3Configuration"), message);+ }++ @Test+ void intermediateConfigurationWithoutBucketOrRoleIsRejected() throws Exception {+ RedshiftDestination dest = valid();+ dest.getS3().setBucketArn(null);+ dest.getS3().setRoleArn(null);++ String message = messageOf(dest);++ assertTrue(message.contains("redshiftDestinationConfiguration.s3Configuration.bucketARN"), message);+ assertTrue(message.contains("redshiftDestinationConfiguration.s3Configuration.roleARN"), message);+ }++ @Test+ void backupConfigurationWithoutABucketIsRejected() throws Exception {+ RedshiftDestination dest = valid();+ dest.setS3BackupMode("Enabled");+ S3Destination backup = new S3Destination();+ backup.setRoleArn("arn:aws:iam::000000000000:role/firehose");+ dest.setS3Backup(backup);++ assertTrue(messageOf(dest).contains("s3BackupConfiguration.bucketARN"));+ }++ @Test+ void secretsManagerRoleMustBeAnIamRoleArn() throws Exception {+ RedshiftDestination dest = valid();+ RedshiftDestination.SecretsManagerConfiguration secrets = new RedshiftDestination.SecretsManagerConfiguration();+ secrets.setEnabled(false);+ secrets.setRoleArn("not-an-arn");+ dest.setSecretsManagerConfiguration(secrets);++ assertTrue(messageOf(dest).contains("secretsManagerConfiguration.roleARN"));+ }++ @Test+ void jdbcUrlNotMatchingAwsPatternIsRejected() throws Exception {+ RedshiftDestination dest = valid();+ dest.setClusterJdbcUrl("jdbc:postgresql://localhost:5432/dev");++ assertTrue(messageOf(dest).contains("clusterJDBCURL"));+ }++ @Test+ void serverlessAndPostgresqlSchemeUrlsAreAccepted() throws Exception {+ RedshiftDestination dest = valid();+ dest.setClusterJdbcUrl("jdbc:postgresql://wg.123456789012.us-east-1.redshift-serverless.amazonaws.com:5439/dev");++ assertDoesNotThrow(() -> RedshiftDestinationValidator.validateConfiguration(dest, SHAPE));+ }++ @Test+ void passwordShorterThanSixIsRejected() throws Exception {+ RedshiftDestination dest = valid();+ dest.setPassword("short");++ assertTrue(messageOf(dest).contains("password"));+ }++ @Test+ void snappyAndZipAreRejectedOnTheIntermediateLocation() throws Exception {+ for (String format : new String[] {"ZIP", "Snappy"}) {+ RedshiftDestination dest = valid();+ dest.getS3().setCompressionFormat(format);++ assertTrue(messageOf(dest).contains("s3Configuration.compressionFormat"), format);+ }+ }++ @Test+ void retryDurationOutOfRangeIsRejected() throws Exception {+ RedshiftDestination dest = valid();+ RedshiftDestination.RetryOptions retry = new RedshiftDestination.RetryOptions();+ retry.setDurationInSeconds(7201);+ dest.setRetryOptions(retry);++ assertTrue(messageOf(dest).contains("retryOptions.durationInSeconds"));+ }++ @Test+ void secretsManagerEnabledRequiresSecretArn() throws Exception {+ RedshiftDestination dest = valid();+ RedshiftDestination.SecretsManagerConfiguration secrets = new RedshiftDestination.SecretsManagerConfiguration();+ secrets.setEnabled(true);+ dest.setSecretsManagerConfiguration(secrets);++ assertTrue(messageOf(dest).contains("secretsManagerConfiguration.secretARN"));+ }++ @Test+ void invalidBackupModeAndDisablingBackupAreRejected() throws Exception {+ RedshiftDestination dest = valid();+ dest.setS3BackupMode("Maybe");+ assertTrue(messageOf(dest).contains("s3BackupMode"));++ assertThrows(AwsException.class, () -> RedshiftDestinationValidator.validateBackupTransition("Enabled", "Disabled"));+ assertDoesNotThrow(() -> RedshiftDestinationValidator.validateBackupTransition("Disabled", "Enabled"));+ assertDoesNotThrow(() -> RedshiftDestinationValidator.validateBackupTransition(null, "Disabled"));+ }++ @Test+ void updateChecksOnlyPresentMembers() {+ RedshiftDestination update = new RedshiftDestination();+ update.setUsername("other");++ assertDoesNotThrow(() -> RedshiftDestinationValidator.validateUpdate(update, "redshiftDestinationUpdate"));+ }++ @Test+ void tableNameAndColumnsMustBeIdentifiersTheProxyUnderstands() throws Exception {+ RedshiftDestination dest = valid();+ dest.getCopyCommand().setDataTableName("a.b.c");+ assertTrue(messageOf(dest).contains("copyCommand.dataTableName"));++ RedshiftDestination columns = valid();+ columns.getCopyCommand().setDataTableColumns("id, name); DROP TABLE t");+ assertTrue(messageOf(columns).contains("copyCommand.dataTableColumns"));+ }++ @Test+ void copyOptionsSeparatorIsRejectedOnlyOutsideQuotes() throws Exception {+ RedshiftDestination bad = valid();+ bad.getCopyCommand().setCopyOptions("gzip; DROP TABLE events");+ assertTrue(messageOf(bad).contains("copyCommand.copyOptions"));++ RedshiftDestination fine = valid();+ fine.getCopyCommand().setCopyOptions("DELIMITER ';' CSV");+ assertDoesNotThrow(() -> RedshiftDestinationValidator.validateConfiguration(fine, SHAPE));+ }++ @Test+ void updateCopyCommandStillNeedsATableName() {+ RedshiftDestination update = new RedshiftDestination();+ RedshiftDestination.CopyCommand command = new RedshiftDestination.CopyCommand();+ command.setCopyOptions("CSV");+ update.setCopyCommand(command);++ AwsException e = assertThrows(AwsException.class,+ () -> RedshiftDestinationValidator.validateUpdate(update, "redshiftDestinationUpdate"));++ assertTrue(e.getMessage().contains("copyCommand.dataTableName"), e.getMessage());+ }++ @Test+ void backupEnabledWithoutABackupConfigurationIsRejected() throws Exception {+ RedshiftDestination dest = valid();+ dest.setS3BackupMode("Enabled");++ assertTrue(messageOf(dest).contains("s3BackupConfiguration"));+ }++ @Test+ void intermediatePrefixWithWhitespaceOrQuotesIsRejected() throws Exception {+ for (String prefix : new String[] {"my prefix/", "it's/", "say\"/"}) {+ RedshiftDestination dest = valid();+ dest.getS3().setPrefix(prefix);++ assertTrue(messageOf(dest).contains("s3Configuration.prefix"), prefix);+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/firehose/RedshiftJdbcUrlTest.java b/src/test/java/io/github/hectorvent/floci/services/firehose/RedshiftJdbcUrlTest.javanew file mode 100644index 0000000000..d96dfea2c3--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/firehose/RedshiftJdbcUrlTest.java@@ -0,0 +1,42 @@+package io.github.hectorvent.floci.services.firehose;++import org.junit.jupiter.api.Test;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++class RedshiftJdbcUrlTest {++ @Test+ void provisionedUrlYieldsClusterIdentifierAndDatabase() {+ RedshiftJdbcUrl url = RedshiftJdbcUrl.parse(+ "jdbc:redshift://my-cluster.abc123.us-east-1.redshift.amazonaws.com:5439/analytics");++ assertEquals("my-cluster", url.clusterIdentifier());+ assertEquals("analytics", url.database());+ assertFalse(url.serverless());+ }++ @Test+ void serverlessUrlIsFlagged() {+ RedshiftJdbcUrl url = RedshiftJdbcUrl.parse(+ "jdbc:postgresql://wg.123456789012.us-east-1.redshift-serverless.amazonaws.com:5439/dev");++ assertEquals("wg", url.clusterIdentifier());+ assertTrue(url.serverless());+ }++ @Test+ void hostWithoutRegionSegmentStillYieldsFirstLabel() {+ RedshiftJdbcUrl url = RedshiftJdbcUrl.parse("jdbc:redshift://c1.redshift.localhost:5439/dev");++ assertEquals("c1", url.clusterIdentifier());+ }++ @Test+ void garbageIsRejected() {+ assertThrows(IllegalArgumentException.class, () -> RedshiftJdbcUrl.parse("not a url"));+ }+}