Commit Graph
37 Commits
Author SHA1 Message Date
Vũ Thế Huy b15bc708fa feat: deliver Redshift audit logs to CloudWatch Logs (#6432)
* feat: deliver Redshift audit logs to CloudWatch Logs

* fix: correct Redshift audit logging and account isolation

* docs: remove Redshift audit logging design document

* fix: reject transaction control in Redshift Data API batches

* fix: track Redshift batch audit changes through savepoints

* fix(redshift-data): guard explicit batch commits against cancellation

* fix(redshift): preserve audit regions and redact ambiguous passwords
2026-10-25 07:42:48 -04:00
Vũ Thế Huy fac6378abd fix(redshift): raise postgres max_connections to 500 (#6421)
* fix(redshift): raise postgres max_connections to 500

The Postgres container behind a Redshift cluster runs with the default max_connections of 100, and each retained session keeps a connection open. Near 100 sessions, Data API calls and JDBC clients on that cluster encounter 'sorry, too many clients already', well before reaching the 500-session limit. Raising max_connections to 500 in RedshiftContainerManager lets the documented 500-session limit apply.

* fix(redshift): raise default proxy max connections to 500

The PostgreSQL backend limit was raised to 500, but the Redshift auth proxy connection semaphore defaulted to 100 via proxy-max-connections. As a result, client connections above 100 were refused by the proxy before reaching PostgreSQL. Raise the default proxy-max-connections to 500 across config, application YAML, and documentation.

* fix(redshift): follow node type for max_connections and raise proxy default to 2000

* fix(redshift): support rg node types, pass serverless from runtime, and update test stubs

- Include rg.* node types for 2,000 max_connections
- Pass 'serverless' node type from RedshiftServerlessRuntime and drop prefix check
- Update start(...) stubs across integration tests with the six-argument signature
2026-10-24 21:09:27 -04:00
Vũ Thế Huy 4c70d6b1a2 feat(cloudformation): support Redshift snapshot restores (#6395)
* feat(cloudformation): support Redshift snapshot restores

* fix(cloudformation): address Redshift snapshot restore review findings

- Reconcile ManageMasterPassword and KMS key on in-place cluster update
- Avoid overriding inherited snapshot passwords on unrelated template changes
- Reconcile tags by deleting removed tags on update
- Mint ARN for parameter group tags to prevent invalid parameter errors
- Scope mutate locking during snapshot restore to prevent stalling writes

* fix(cloudformation): narrow Redshift snapshot restore scope

* fix(cloudformation): use shared rollback for Redshift state
2026-10-24 08:01:26 -04:00
Andre Kurait a96921afad fix(redshift): reclaim anonymous container volumes (#6382)
Reclaim disposable anonymous volumes while preserving adopted containers during failed recovery. Retain pre-reboot dumps and failed cleanup ownership across partial teardown. Preserve the original database when only proxy shutdown fails. Share startup orchestration while retaining the opt-in cleanup policy.

Signed-off-by: Andre Kurait <AndreKurait@gmail.com>
2026-10-23 20:46:24 -04:00
Vũ Thế Huy 1b8548a0af feat(redshift): create final snapshots before deleting clusters (#6346)
* feat(redshift): create final snapshots before deleting clusters

* fix(redshift): clean failed dumps and scope snapshot locking

* fix(redshift): default manual snapshot retention and fix Spectrum cleanup
2026-10-23 14:06:47 -04:00
Vũ Thế Huy 7e51e69c44 feat(redshift): support default IAM roles for COPY and UNLOAD (#6304)
* feat(redshift): support default IAM roles for COPY and UNLOAD

* fix(redshift): distinguish default role keyword from literals

* fix(redshift): accept blank default IAM roles
2026-10-23 08:33:20 -04:00
Priamo Germosen 812c95499d fix(iam): check iam:PassRole for Redshift, Redshift Serverless and AddRoleToInstanceProfile (#6250)
Under IAM enforcement a request that passes a role to a service needs iam:PassRole on that role,
but no Redshift or Redshift Serverless operation was checked for it. A caller allowed to create a
cluster or change its roles could attach any role to it, and Floci's COPY, UNLOAD and Spectrum
statements then run as that role; statements run through the Data API on a Redshift Serverless
workgroup can use its namespace's roles the same way.

Now checked, with iam:PassedToService as the Service Authorization Reference gives it:
- Redshift CreateCluster and RestoreFromClusterSnapshot pass the roles in IamRoles, and
  ModifyClusterIamRoles those in AddIamRoles, to redshift.amazonaws.com. The lists are read through
  the Redshift handler's own member pattern, so IamRoles.IamRoleArn.N, as the SDK sends it,
  IamRoles.member.N and IamRoles.N all count. RestoreFromClusterSnapshot is checked although
  Floci's restore attaches no role yet, as AWS checks it.
- Redshift Serverless CreateNamespace and UpdateNamespace pass the roles in iamRoles and the one
  in defaultIamRoleArn, and CreateScheduledAction and UpdateScheduledAction pass roleArn, to
  redshift-serverless.amazonaws.com.

The Redshift management guide: "To associate an IAM role with a cluster, a user must have
iam:PassRole permission for that IAM role." A role named only as a cluster's default,
DefaultIamRoleArn, is not checked on its own: the default is one of the roles the cluster holds, and
Floci does not act on it. A namespace's defaultIamRoleArn is checked, since Floci keeps it whether
or not iamRoles holds it.

COPY, UNLOAD and Spectrum now take a role only under the ARN IAM holds it under, path included, as
STS AssumeRole does. They looked the role up by its name alone, so a cluster given
role/sandbox/AdminRole, which a PassRole grant on role/sandbox/* allows, ran its statements as the
AdminRole IAM holds under another path.

IAM's AddRoleToInstanceProfile now passes the role it adds to ec2.amazonaws.com. Every instance
running with the profile gets that role's credentials from the instance metadata service, so adding
a role to a profile already attached to a running instance handed it any role. The IAM API
reference: "The caller of this operation must be granted the PassRole permission on the IAM role by
a permissions policy." RoleName names the role without its path, so the check uses the ARN IAM holds
the role under, or, for a role IAM does not hold, the ARN the name gives.

docs/services/iam.md lists the new operations, and docs/services/redshift.md the path rule.
2026-10-22 17:06:02 -05:00
Vũ Thế Huy d2f2625005 feat(redshift): add ResetClusterParameterGroup (#6230)
* feat(redshift): add ResetClusterParameterGroup

* docs(redshift): update supported operation count

* fix(redshift): validate resets and preserve legacy parameter groups

* fix(redshift): accept empty Query parameter lists
2026-10-22 15:59:54 -04:00
Vũ Thế Huy fd37e109f8 feat(firehose): deliver staged Redshift batches with single-attempt COPY (#6006)
* feat(firehose): deliver staged Redshift batches with single-attempt COPY

A flush stages the batch in the intermediate S3 location, then runs COPY against the cluster proxy over JDBC simple-query mode without an IAM role. The load runs on its own thread so that slow COPY queries do not hold the shared flush executor or PutRecord callers, and failures are logged with the staged batch kept in S3.

* fix(firehose): address review comments on Redshift single-attempt COPY delivery

- Drain buffers before shutting down the Redshift delivery executor on Firehose shutdown and log dropped queued tasks.

- Catch RejectedExecutionException in deliverRedshiftBatch to prevent staged records from returning to the buffer.

- Extract DatabaseSecretCredentials helper in core.common to deduplicate Secrets Manager credentials parsing across RDS Data, Redshift Data, and Firehose.

- Extract RedshiftConnections test helper for waitForConnection and use DockerAvailability.isAvailable() in FirehoseRedshiftDeliveryIntegrationTest.

- Update docs and Javadocs to remove outdated references to retries and shared flush threads.

* fix(firehose): wait for queued Redshift COPY delivery before shutdown and log secret parse errors

* refactor(firehose): deduplicate dropAndLogQueuedTasks helper on shutdown
2026-10-21 13:40:53 -04:00
Aniket Shukla 35ddd5c59d fix(redshift): retry snapshot and catalog uploads (#6065)
Rebuild host-resource uploads and catalog tar streams for transient Docker I/O retries. Keep SQL outside the retry boundary and preserve snapshot failure and optional bootstrap behavior.

Refs #5096.
2026-10-20 07:14:28 -04:00
Vũ Thế Huy c33823bd48 feat(redshift): complete Glue external table lifecycle (#5866)
* feat(redshift): complete Glue external table lifecycle

* fix(test): use existing frame helper in Spectrum bridge test

* fix(redshift): safeguard external catalog lifecycle operations

* fix(redshift): shorten spectrum catalog lock waits and reuse test helper
2026-10-17 13:59:29 -04:00
Allen Sanborn 63b48342d6 feat(redshift): add snapshot copy and snapshot schedule operations (#5574)
* feat(redshift): add snapshot copy and snapshot schedule operations

Terraform's aws_redshift_snapshot_copy, aws_redshift_snapshot_schedule and
aws_redshift_snapshot_schedule_association failed with InvalidAction because
the Query handler had no arms for these actions.

- EnableSnapshotCopy / DisableSnapshotCopy / ModifySnapshotCopyRetentionPeriod
  store the copy settings on the cluster, and DescribeClusters reports
  ClusterSnapshotCopyStatus while copy is enabled. RetentionPeriod defaults
  to 7 and ManualSnapshotRetentionPeriod to -1. Faults follow the Redshift
  model: SnapshotCopyAlreadyEnabledFault, SnapshotCopyAlreadyDisabledFault,
  SnapshotCopyDisabledFault (modify), InvalidRetentionPeriodFault and
  SnapshotCopyGrantNotFoundFault.
- Create/Describe/Modify/DeleteSnapshotSchedule and
  ModifyClusterSnapshotSchedule. The association lives on the cluster, so
  DescribeSnapshotSchedules derives AssociatedClusters (state ACTIVE) and
  filters by ClusterIdentifier from it, and a deleted cluster cannot leave a
  stale association. Deleting a schedule in use is refused with
  InvalidClusterSnapshotScheduleState.
- Snapshot schedules take part in CreateTags/DeleteTags/DescribeTags as
  resource type snapshotschedule.

No snapshot is copied to another region or taken on a schedule; the docs
say so.

* fix(redshift): reject malformed snapshot schedules and in-use copy grant deletion

* fix(redshift): validate snapshot copy region and snapshot schedule identifier

EnableSnapshotCopy now refuses a DestinationRegion that is not a published
AWS region with UnknownSnapshotCopyRegionFault (404), as the model lists.

CreateSnapshotSchedule now refuses a ScheduleIdentifier containing anything
but letters, digits and hyphens with InvalidParameterValue (400). The API
reference allows alphanumerics; the management guide's example uses a hyphen.
2026-10-13 13:12:34 -04:00
Vũ Thế Huy 38ce99ba54 feat(redshift): support more COPY and UNLOAD options (#5204)
* feat(redshift): support more COPY and UNLOAD options

COPY now accepts REGION, CREDENTIALS, key-based credentials, EMPTYASNULL,
BLANKSASNULL, REMOVEQUOTES, ACCEPTINVCHARS and TRUNCATECOLUMNS. UNLOAD now
accepts REGION, CREDENTIALS, key-based credentials and EXTENSION. Field
content options run in a new CopyRecordTransformer; TRUNCATECOLUMNS reads
column lengths from the catalog and so needs the Simple Query protocol.
Clauses that cannot be honoured still fail open to PostgreSQL.

* feat(redshift): support UNLOAD ESCAPE, CLEANPATH and server-side encryption options

UNLOAD now accepts ESCAPE (text framing only), CLEANPATH, ENCRYPTED AUTO and
ENCRYPTED with KMS_KEY_ID, which is stored as aws:kms server-side encryption
on the data and manifest objects. CLEANPATH lists and authorizes every delete
up front but removes the objects only when the first output arrives, so a
query that PostgreSQL rejects keeps the previous export. An empty prefix,
ALLOWOVERWRITE and client-side encryption still fail open to PostgreSQL.

* fix(redshift): address review findings on COPY and UNLOAD options

- Reject blank access key, secret, session token and IAM role so an empty
  pair cannot enable unsigned S3 access.
- CLEANPATH lists and authorizes the prefix again when the first output
  arrives, so an object uploaded since preparation does not survive.
- REMOVEQUOTES no longer closes a text-mode field on an escaped quote.
- TRUNCATECOLUMNS counts characters, as PostgreSQL does for varchar(n),
  and cuts decoded text so escape sequences are never split.
- Bound the heap used by field-level COPY options with a per-object size
  limit and a budget shared across connections.

* fix(redshift): delete the CLEANPATH prefix under one bucket lock

S3Service.deleteObjectsWithPrefix lists the prefix, authorizes every key
and deletes them while holding the bucket monitor that PutObject and
DeleteObject already use, so an upload cannot land between the listing
and the deletes and survive next to the new export.

* fix(redshift): measure TRUNCATECOLUMNS in bytes and tighten review follow-ups

Redshift counts CHAR(n) and VARCHAR(n) in bytes, so TRUNCATECOLUMNS now
measures decoded bytes and cuts on a character boundary instead of
counting characters. The UNLOAD docs described bare ENCRYPTED as
client-side; client-side is the MASTER_SYMMETRIC_KEY form. The
concurrent-put lock test now waits for the put thread to be BLOCKED
instead of a fixed 300 ms timeout.

* style(redshift): fix import order in S3CopySimulatorTest
2026-10-08 23:19:40 -04:00
Vũ Thế Huy 950b6fe774 feat(redshift): add relational queries for Redshift Spectrum (#5095)
* feat: add relational queries for Redshift Spectrum

* fix(redshift): harden Spectrum relational query preparation

Catch RuntimeException during preparation so the client gets an ErrorResponse
instead of a dropped connection, skip preparation while the backend discards
until Sync, defer schema binding until the transaction commits, make the
catalog functions SECURITY DEFINER, and track COMMIT and ROLLBACK from the
command tag.

* fix(redshift): address review findings on transaction handling in Spectrum relational queries

- Undo Glue tables created inside a rolled back transaction (Data API batch and wire proxy)
- Keep bindings and Glue tables on ROLLBACK TO SAVEPOINT; only a closed transaction discards them
- Report the real transaction status for locally handled simple queries instead of idle
- Use a switch expression in BackendResponseCoordinator
- Map host.docker.internal into the floci-duck container on Linux

* fix(redshift): undo Glue tables across sessions and on rollback to savepoint

- Scope staged Glue tables by the backend socket so the proxy rollback finds tables created by another session
- Track SAVEPOINT, ROLLBACK TO and RELEASE so a Data API batch undoes only the tables created after the savepoint

* fix(redshift): defer Glue undo on rollback to savepoint until the backend confirms and bundle bootstrap catalog in native image

* fix(redshift): reject CREATE EXTERNAL TABLE inside a transaction like AWS

AWS does not allow CREATE EXTERNAL TABLE inside a transaction block, and a
Data API batch runs as one transaction. Return SQLSTATE 25001 instead of
staging Glue tables and undoing them on rollback, which removes the savepoint
tracking and cross-session undo code. Reuse ExternalTableMaterializer.quote.

* fix(redshift): reject CREATE EXTERNAL TABLE in a transaction for legacy schemas too
2026-10-06 15:30:53 -04:00
Vũ Thế Huy d7d2f73e99 feat(redshift): add external catalog statement parsing and metadata writers (#4679)
* feat(redshift): add external catalog statement parsing and metadata writers

* fix(redshift): harden external statement parsing and reference scanning

- Scanner: recognise dollar-quoted bodies, E'..\'..' strings and nested
  block comments; catch SELECT INTO, CREATE VIEW and CREATE INDEX writes;
  ignore FROM inside EXTRACT, SUBSTRING, TRIM and IS DISTINCT FROM.
- Parser: accept CREATE EXTERNAL SCHEMA IF NOT EXISTS, strip leading
  comments, support quoted names with dots, read TBLPROPERTIES and
  PARTITION values that contain parentheses or escaped quotes, validate
  IAM_ROLE as one quoted literal, and canonicalise Redshift type aliases
  to Hive types.
- Registry: percent-encode key parts so separators in identifiers cannot
  collide.
- Backend session: do not treat socket write failures as source read
  failures during COPY.
- Keep property order stable in statements.

* fix(redshift): address external catalog review findings

* fix(redshift): inherit omitted partition settings

* fix(redshift): preserve explicit empty partition settings

* fix(redshift): canonicalise character and varbyte external column types

* fix(redshift): default unsized character types

* fix(redshift): enforce Spectrum varchar default length

* fix(redshift): null surplus varchar values during Spectrum copy
2026-10-02 13:42:21 -04:00
Mario Toffia 2df052181d fix(dynamodb): route stream consumers through one account-scoped reader (#4394)
* refactor(dynamodb): add a stream reader and key native streams by table ARN

DynamoDbStreamReader is the engine-neutral way to read DynamoDB Streams.
DynamoDbApiStreamReader implements it over the selected DynamoDbOperations using the Streams wire API.
Native streams were keyed by region and table name, so same-named tables in two accounts shared one stream.
They are now keyed by table ARN, and ListStreams returns only the caller's account and region.

Streams of every account are restored from persisted tables at startup.

* refactor(dynamodb): move stream consumers onto the stream reader

The Lambda DynamoDB Streams poller reads through DynamoDbStreamReader: each tick renews iterators from committed progress for every readable shard, and reads a child shard only after its parent was read to its end.
It discards restart checkpoints only for a process-lifetime engine, and pins LATEST per shard via newestSequenceNumbers, replacing DynamoDbStreamService.latestSequenceNumber.
A read fills a batch from as many GetRecords calls as it needs, so a batch is not cut at the 1000 record GetRecords maximum.
EventBridge Pipes reads DynamoDB streams the same way, committing a batch only once it is delivered or sent to the DLQ, delivers the AWS stream record shape with eventSourceARN, and honors LATEST.
The Redshift zero-ETL consumer reads the same way, keeping per-shard progress in the integration (legacy checkpointSequenceNumber is ignored on load) and committing a batch only after it is written to the landing table.
It discards that progress at startup for a process-lifetime engine, and the writer now takes AWS stream records, so Redshift no longer uses DynamoDbStreamService or DynamoDbStreamRecord, whose SHARD_ID is now package-private.
2026-09-26 01:08:45 -05:00
Vũ Thế Huy 6bdf14210e fix(redshift): accept s3table log destination and reject mutual snapshot restore params (#4340)
* fix(redshift): accept s3table log destination and reject mutual snapshot restore params

Closes #4242

* fix(redshift): preserve S3-table logging configuration and report status

Pass S3TableKmsKeyId and S3TableGranularity through EnableLogging, store them on Cluster, and serialize S3Tables in LoggingStatus responses.

* fix(redshift): validate S3-table logging settings

* fix(redshift): complete S3 table logging status
2026-09-25 15:20:20 -04:00
Vũ Thế Huy a450cdc9b0 feat(redshift): support Redshift Spectrum phase one (#4184)
* feat: add Redshift Spectrum metadata catalog

* feat: parse Redshift Spectrum DDL

* feat: read Redshift Spectrum CSV data from S3

* feat: classify and rewrite Redshift Spectrum queries

* feat: materialize Spectrum rows into PostgreSQL

* feat: intercept Redshift Spectrum queries

* test: cover Redshift Spectrum wire integration

* docs: document Redshift Spectrum phase one

* fix: handle Spectrum extended queries

* fix: preserve Spectrum query protocol state

* fix: resolve Spectrum cursor paging and extended query race condition

- Await prior backend queries before streaming local Spectrum Extended Query frames
- Drop synthetic Spectrum Parse/Bind/Describe/Close frames from coordinator pending queue
- Support server-side cursor pagination with PortalSuspended across multiple Execute cycles
- Add cascade cleanup for unexhausted portal cursors when prepared statement is closed

* fix(redshift): register SpectrumMaterializer for GraalVM runtime initialization

* fix(redshift): forward non-Spectrum queries and register storage models for reflection

* docs(redshift): clarify Spectrum temp table lifecycle across protocols

* docs(redshift): note that Simple Query Spectrum creates a temp table per query

---------

Signed-off-by: Vũ Thế Huy <31652864+vuthehuyht@users.noreply.github.com>
2026-09-23 23:34:03 -04:00
yarammanasa2001-maxandyarammanasa2001-max 317e007942 fix(redshift): fix Redshift emulation gaps found against the Terraform AWS provider (#3987)
* fix(redshift): add SnapshotArn and SnapshotCreateTime to snapshot responses

DescribeClusterSnapshots and CreateClusterSnapshot never populated
SnapshotArn or SnapshotCreateTime — the Snapshot model didn't carry
either field. Real AWS returns both, and callers that filter on
recovery-point age or restore by ARN have nothing to key off.

SnapshotArn reuses the existing snapshotArn(clusterIdentifier,
snapshotIdentifier) helper (already used for tagging, just never
attached to the model). SnapshotCreateTime is captured via Instant.now()
at snapshot creation and formatted with the same DateTimeFormatter.ISO_INSTANT
convention already used elsewhere in this file for Expiration/CreateTime.

Both elements are omitted from the XML response when the snapshot predates
this field (an on-disk store surviving an upgrade), matching how the other
optional elements in buildSnapshotXml already degrade.

* feat(redshift): support DescribeLoggingStatus, EnableLogging, DisableLogging

The Upbound Terraform provider's redshift Cluster resource calls
DescribeLoggingStatus on every observe cycle, unconditionally, as part
of its standard drift check across all configurable cluster aspects —
not something a caller opts into. Without it, every cluster's observe
step failed outright with InvalidAction, and the cluster could never
report Synced/Ready even once fully created and available.

Adds the three logging actions as a set, matching how EnableLogging/
DisableLogging/DescribeLoggingStatus share one response shape in the
real API. No log delivery is emulated — only the configuration a caller
set (enabled, bucket, prefix) is tracked and returned, the same
graceful-scope choice already made for snapshot dump handling.

XML wrapper element names (DescribeLoggingStatusResult, EnableLoggingResult,
DisableLoggingResult) were verified against aws-sdk-go-v2's own generated
deserializer, not assumed from the docs.

* fix(redshift): default parameter group and MultiAZ on cluster responses

Terraform provider's resourceClusterRead indexes ClusterParameterGroups[0]
and requires MultiAZ to be exactly "enabled" or "disabled" unconditionally.
Real AWS always attaches a default parameter group and never returns MultiAZ
blank; floci previously omitted both, causing a panic and then a read error
in the provider.

* fix(redshift): resolve RestoreFromClusterSnapshot by SnapshotArn too

Real AWS lets callers restore from either SnapshotIdentifier or
SnapshotArn. Terraform's aws_redshift_cluster resource populates only
snapshot_arn when that's the field configured, so the request carried
no SnapshotIdentifier at all and floci NPE'd looking one up as null.

* fix(redshift): use the real AWS error code for missing subnet groups

RedshiftService threw "ClusterSubnetGroupNotFound", but AWS's actual
code is "ClusterSubnetGroupNotFoundFault" and the Terraform AWS
provider's generated deserializer type-matches on that exact string to
recognize "doesn't exist yet, create it". A bare code fell through to
an unclassified error, so the provider never got past Observe and a
cluster subnet group could never be created through Crossplane.

* fix(redshift): address PR review feedback

Validate SnapshotArn (400 on malformed/missing, account and region check),
honor ClusterParameterGroupName and MultiAZ, seed the default parameter
group, allow CloudWatch EnableLogging, return 400 for missing subnet
groups, sync docs, and add tests.

* test(redshift): fix merge of logging tests with main's IAM role tests

* refactor(redshift): share logging response helper and trim comments

* fix(redshift): restore testDisableLogging's closing brace lost in the main merge

Merging main's snapshot-copy-grant tests (#3628) next to the logging
tests dropped the closing brace of testDisableLogging and the @Test
annotation on describesSnapshotCopyGrants, so the latter body ran
inside the former and the file failed to compile.

* docs(redshift): resync action table order after the main merge

make docs-sync moved ModifyCluster after the snapshot-copy-grant rows
main added, matching the generator's canonical action order.

---------

Co-authored-by: yarammanasa2001-max <271440416+yarammanasa2001-max@users.noreply.github.com>
2026-09-23 16:59:27 -04:00
Allen Sanborn 2af7ed71a7 feat(redshift): implement snapshot copy grant lifecycle (#3628)
* feat(redshift): implement snapshot copy grant lifecycle

Terraform's aws_redshift_snapshot_copy_grant needs the full CRUD, and all
three actions returned InvalidAction. Add CreateSnapshotCopyGrant,
DescribeSnapshotCopyGrants and DeleteSnapshotCopyGrant to the Query handler,
backed by a new storage map on RedshiftService.

The grant name is the key: a duplicate create raises
SnapshotCopyGrantAlreadyExistsFault, and describe-by-name or delete of a
missing grant raises SnapshotCopyGrantNotFoundFault. Describe without a name
returns every grant. KmsKeyId is optional and defaults to the account's
AWS-managed Redshift key alias ARN, mirroring how Ec2EbsEncryptionService
stands in for a default key.

Tags ride along on create, since the CLI sends them inline as
Tags.Tag.N.Key/.Value on this action rather than via CreateTags, and
snapshotcopygrant ARNs now resolve in the tagging operations alongside the
other Redshift resource types.

* test(redshift): cover snapshot copy grants through the real SDK

* fix(redshift): paginate DescribeSnapshotCopyGrants

The action returned every grant in one page and ignored MaxRecords and
Marker, so a client with more grants than fit in a page had no way to walk
them.

Page through the shared Pagination helper, which sorts by the grant name and
encodes the last returned name as an opaque base64 cursor, so ordering is
stable and a marker stays resumable when grants are created or deleted
between pages. Marker is emitted only while further pages remain, which is
what tells a paginating client to stop.

MaxRecords follows the Redshift model: default 100, and a value outside
20 to 100 is rejected with InvalidParameterValue rather than clamped.

The model documents SnapshotCopyGrantName and Marker as mutually exclusive
but declares no error for sending both, so this filters by name and then
paginates instead of rejecting the pair. A name matches at most one grant,
which fits in any page.

* fix(redshift): enforce the SnapshotCopyGrantName contract

AWS validates SnapshotCopyGrantName as 1-63 characters, first a lowercase
letter, then lowercase letters, digits or single hyphens with no trailing
or doubled hyphen. Create accepted anything non-blank, so names Redshift
rejects (1grant, Grant, grant--copy, grant-, 64 characters) persisted
locally and diverged from AWS.

Validate in RedshiftService before persistence, matching the existing
snapshot identifier check, and answer InvalidParameterValue as the rest of
the handler does.

* fix(redshift): return 400 for SnapshotCopyGrantNotFoundFault on Describe and Delete

AWS documents SnapshotCopyGrantNotFoundFault as HTTP 400 in the error tables
for both DescribeSnapshotCopyGrants and DeleteSnapshotCopyGrant; we returned
404. Two existing wire-level assertions in RedshiftOperationsTest pinned the
wrong status, so they move with the code, and the unit tests now assert the
status alongside the error code.

The third throw site, in the tagging helper, deliberately stays 404: the
status belongs to the action rather than the fault code, and that path is
reached only from CreateTags/DeleteTags/DescribeTags, whose documented
missing-resource error is ResourceNotFoundFault at 404. A regression pins
that, and a comment says why the two differ.

Refs:
https://docs.aws.amazon.com/redshift/latest/APIReference/API_DescribeSnapshotCopyGrants.html
https://docs.aws.amazon.com/redshift/latest/APIReference/API_DeleteSnapshotCopyGrant.html
https://docs.aws.amazon.com/redshift/latest/APIReference/API_CreateTags.html

* fix(redshift): serialize grant create/delete, and use ResourceNotFoundFault on the tag path

Two findings from the latest review round.

createSnapshotCopyGrant checked the name was free and then wrote, with nothing
between the two steps, so two concurrent creates of one name could both succeed
and the second would overwrite the first. create and delete are now synchronized,
as createCluster and modifyCluster already are. The new wire-level test holds two
threads on a latch and releases them into the same name: it fails on every run
without the keyword (3/3 locally) and passes with it, so it pins the lock rather
than describing it.

The tagging path threw SnapshotCopyGrantNotFoundFault with HTTP 404. Both halves
of that pairing cannot be right at once: botocore's Redshift model gives that
shape httpStatusCode 400, and an error shape's status is a property of the shape,
not of the calling action. But 404 is the correct status here, because
CreateTags/DeleteTags/DescribeTags do not list that fault at all -- they document
ResourceNotFoundFault, modelled at 404, for any missing resource. So the status
stays and the code changes. That also explains why the three sibling cases in the
same switch are already consistent: ClusterNotFound, ClusterSnapshotNotFound and
ClusterParameterGroupNotFound are each modelled at 404 themselves.

Describe and Delete still return SnapshotCopyGrantNotFoundFault at 400, which is
what those two actions document.

Docs gain a short section on the grant surface: the alias-ARN KmsKeyId default,
the unvalidated tag limits, and why a missing grant reports two different faults
depending on which action you reach it through.

* style(test): name the new snapshot copy grant tests without the testX prefix

AGENTS.md: "Name test methods either as a camelCase sentence or as
method_scenario_expectation. Both are established. testX names are common in
older tests and are not the pattern to copy." The 31 tests this PR adds to
src/test all used testX because the three Redshift files they landed in are
unusually full of it -- 7/7, 30/50 and 69/104 -- but that is the local exception,
not the repo convention, and the rule is explicit about not copying it.

Renames only; no test body changes. The two new tests in
compatibility-tests/sdk-test-java keep testX: that module has the opposite idiom
and AGENTS.md says to follow the module you are in, and all five methods in that
file, three of them pre-existing, are named that way.
2026-09-21 18:31:00 -04:00
Vũ Thế Huy d227ef9195 feat(redshift): add ModifyClusterIamRoles, DescribeClusterVersions and DescribeOrderableClusterOptions (#3990)
ModifyClusterIamRoles adds and removes the IAM roles associated with a
cluster. The change is pushed to the running auth proxy, so COPY and
UNLOAD on new connections authorize against the updated role list.
Cluster IamRoles now report ApplyStatus in-sync.

DescribeClusterVersions and DescribeOrderableClusterOptions return static
data so IaC providers can validate node types before creating a cluster.
2026-09-21 11:32:09 -04:00
Vũ Thế Huy 9379fa1179 feat(redshift): support S3 COPY JSON and manifest, and DynamoDB zero-ETL backfill (#3889)
* feat(redshift): support S3 COPY FORMAT AS JSON 'auto' and MANIFEST

* fix(redshift): resolve column discovery via pg_catalog and guard against empty columns

* feat(redshift): track zero-ETL backfill progress and syncing status

* feat(redshift): backfill existing DynamoDB items into zero-ETL landing table

* test(redshift): prove zero-ETL backfill and syncing-to-active status

* fix(redshift): reject JSON 'auto' COPY without columns over Extended Query clearly

Catalog-based column discovery only runs over the Simple Query protocol, so
a column-less COPY ... FORMAT AS JSON 'auto' sent over Extended Query failed
with an obscure error. Name the cause and remedy in the error, document the
limitation, and run the discovery tests over Simple Query.

* docs(redshift): document zero-ETL DynamoDB backfill and syncing status

* fix(redshift): address review feedback on COPY JSON, manifest and zero-ETL backfill

* fix(redshift): pass user column list as written and clarify syncing status in docs

* fix(redshift): wrap long condition in identifier unquoting

* fix(redshift): keep user columns as written in runCopyFrom and verify backfill account scope

* test(redshift): use assertNotNull for last evaluated key assertion
2026-09-20 00:23:54 -04:00
Vũ Thế Huy 29b601834b feat: add DynamoDB to Redshift zero-ETL replication (#3872)
* feat: add DynamoDB to Redshift zero-ETL replication

* fix(redshift): preserve zero-etl account polling state

* fix(redshift): preserve zero-etl target account
2026-09-18 22:35:10 -04:00
Vũ Thế Huy 023af51627 feat(redshift): manage master password with secrets manager (#3871)
* feat(redshift): manage master password with secrets manager

* fix(redshift): align managed password contract

* fix(redshift): expose managed password secret arn
2026-09-18 13:55:13 -04:00
Vũ Thế Huy 677cdbe053 feat(redshift): authorize COPY and UNLOAD with IAM_ROLE (#3815)
* feat(redshift): parse IAM_ROLE clause on COPY and UNLOAD

* feat(s3): add signed-principal authorization wrappers for role sessions

* feat(redshift): authorize COPY/UNLOAD S3 access through an IAM_ROLE session

* feat(redshift): thread IamService through the Redshift auth proxy chain

* test(redshift): cover IAM_ROLE resolution and signed authorization in prepareCopy

* fix(redshift): complete IAM_ROLE S3 authorization

* test(redshift): cover IAM_ROLE authorization end to end

* docs(redshift): document IAM_ROLE COPY and UNLOAD

* fix(redshift): retain IAM_ROLE session during COPY

* style(test): use Mockito static imports

* fix(native): initialize redshift copy simulator at runtime

* fix(redshift): address IAM role review feedback

* test(redshift): use valid proxy relay keys

* fix(redshift): require IAM roles to be associated

* test(compat): recover CodeArtifact create retries

* fix(redshift): parse IAM role location names

* fix(docs): exclude Redshift IAM role member label

* chore: remove unrelated CodeArtifact test
2026-09-18 10:21:10 -04:00
Vũ Thế Huy d9abefb83f feat(redshift): seed catalog and system views (#3552)
* feat(redshift): seed catalog and system views on cluster startup

Seed Amazon Redshift catalog and system views on container startup into both template1 and dev databases so BI, ORM, and migration tools (Tableau, Looker, DBeaver, Flyway, Liquibase, dbt) can introspect database schema metadata without missing-relation errors.

* feat(redshift): record COPY failures in stl_load_errors and dynamicize query logs

Record failed S3 COPY attempts into pg_catalog.stl_load_errors via LoadErrorRecorder across simple and extended query flows. Convert stl_query and svl_qlog into dynamic views backed by pg_stat_activity, and add stv_wlm_query_state and svv_diskusage catalog views.

* fix(redshift): align catalog views with documented Redshift column schema

* fix(redshift): separate catalog seeding from copy error recording

* test(redshift): preserve container manager coverage
2026-09-16 21:39:50 -04:00
Ovidiu (Ovi) d3bfe2609c feat(redshift): implement zero-ETL integrations (#3559)
* feat(redshift): implement zero-ETL integrations

DescribeIntegrations had no implementation, so an application that
discovers its zero-ETL integration at runtime could not run against the
emulator.

Implementing that action alone would have been worse than leaving it out.
A caller matches its integration by SourceArn and treats "no match" as a
hard error, so an action that always answered with an empty list would turn
a clean "unsupported" into a confusing "no integration whose source is the
X table". CreateIntegration and DeleteIntegration come with it, so an
integration can exist and the empty list means what it says.

Shape captured from a live integration in us-west-2:

  - Status is lower case ("active"), not ACTIVE
  - Errors is present but empty on a healthy integration
  - the record carries IntegrationArn, IntegrationName, SourceArn,
    TargetArn, Status, CreateTime, KMSKeyId, Tags and
    AdditionalEncryptionContext
  - describing with an unknown IntegrationArn is IntegrationNotFoundFault,
    "The requested integration doesn't exist."
  - an account with no integrations answers with an empty list, not an
    error
  - no Marker element is emitted when there is no further page, which is
    what stops a caller's pagination loop

This is metadata only: nothing replicates from the source, and the
integration settles as active immediately rather than passing through
creating, because there is no work for it to do.

* fix(redshift): correct the integration Query contract

Three gaps against the modelled Query API, each confirmed in the bundled
botocore service model rather than taken on trust.

Tags arrive under TagList, not Tags. The shape is a list whose member
carries locationName Tag, so a real client sends TagList.Tag.N.Key and
.Value. Reading Tags.Tag.N meant every tag an SDK sent was silently
dropped, which a hand written form-encoded test did not catch because it
used the wrong name too.

DescribeIntegrations is paginated and filterable. MaxRecords, Marker and
Filters.DescribeIntegrationsFilter.N were all ignored, so the operation
only worked while every record fitted in one response and a caller using
filters got unrelated integrations back. MaxRecords honours the documented
20 to 100 range, the marker is the last ARN already returned rather than an
offset, and no Marker is emitted on the terminal page. The four modelled
filter names are implemented: integration-arn, source-arn, source-types and
status. An unrecognised name is rejected rather than ignored.

CreateIntegration advertises Description and AdditionalEncryptionContext.
Both are now parsed, stored and rendered, with the documented rule that the
encryption context is only valid alongside a KMSKeyId, and Description
capped at the modelled 1000 characters.

* test(redshift): cross a real page boundary in the marker regression

The previous test created three integrations and asked for twenty, so it
only proved the terminal case: no Marker when everything fits. It never
forced a second page, never asserted a non-terminal page carries a Marker,
and never sent one back.

It now creates twenty-one records against the smallest legal page size and
walks every page, asserting that a full page carries exactly MaxRecords
records and a Marker, that no record appears on two pages, that the final
page omits the Marker, and that the traversal returns the same set as a
single large page. Other tests in this class share the store, so the
assertions are about the traversal rather than absolute counts.

* feat(redshift): validate IntegrationName against the modelled pattern

CreateIntegration only checked IntegrationName for non-blank, so a name
real AWS refuses was accepted: the member is modelled min 1, max 63,
pattern ^[a-zA-Z][a-zA-Z0-9]*(-[a-zA-Z0-9]+)*$. A leading digit or
hyphen, an underscore, a doubled hyphen and a trailing hyphen all got
through, as did a name over 63 characters.

Validate both constraints in createIntegration, alongside the existing
Description length and encryption-context rules.

Three regressions cover the rejected shapes, the over-length case and
acceptance at the 63 character boundary.
2026-09-15 13:36:10 -04:00
Niels Kootstra 1987bf0c96 fix(rds): bound RDS/Redshift auth proxy connections and handshakes (#3545)
Cap concurrent proxy connections with a per-proxy semaphore, apply
configurable handshake and backend-connect timeouts to both the
client and backend sockets, and defer backend PostgreSQL connects
until after client auth completes. Close leaked backend sockets
defensively on every exit path, including a RuntimeException thrown
between authenticate() returning a session and the bridge finishing
its own cleanup, and bound backend-side reads during the handshake
so a silent backend that accepts TCP but never answers cannot pin a
handler thread and its connection permit forever.

New EmulatorConfig keys under services.rds and services.redshift:
proxy-handshake-timeout-millis (default 10000),
proxy-backend-connect-timeout-millis (default 5000),
proxy-max-connections (default 100).
2026-09-14 10:48:48 -04:00
Vũ Thế Huy e5bd8be405 feat(redshift): provision AWS::Redshift::Cluster through CloudFormation (#3427)
* feat(cloudformation): provision AWS::Redshift::Cluster (create path)

* feat(cloudformation): AWS::Redshift::Cluster update and replacement

* feat(cloudformation): force replacement on Redshift cluster createOnly property change

* feat(cloudformation): force replacement on Redshift cluster DBName change

* feat(cloudformation): provision Redshift parameter, subnet and security groups

* chore(cloudformation): register Redshift provisioner in inventory and docs

* test(cloudformation): end-to-end AWS::Redshift::Cluster stack

* docs(redshift): document CloudFormation cluster provisioning

* test(cloudformation): assert ClusterSubnetGroupNotFound error code on subnet group deletion

* fix(cloudformation): correct attribute handling for Redshift security group provisioning

* fix(cloudformation): apply Redshift parameter group Parameters and fix docs

ClusterParameterGroup silently dropped Properties.Parameters on both
create and update instead of calling ModifyClusterParameterGroup, and
did not replace the entity when Description or ParameterGroupFamily
changed, even though AWS marks both as replacement properties.

Also remove the Id GetAtt claim from the Cluster docs: neither the
provisioner nor AWS's own schema expose it for AWS::Redshift::Cluster.
2026-09-13 18:45:40 -05:00
Vũ Thế Huy e9454af855 feat(redshift): intercept Extended Query protocol (#3474)
* feat(redshift): decode Extended Query wire messages

* feat(redshift): track Extended Query statements and portals

* feat(redshift): coordinate Extended Query backend responses

* refactor(redshift): share S3 COPY and UNLOAD transfers

* feat(redshift): execute S3 transfers through Extended Query

* fix(redshift): retain next-cycle pipelined portals

* feat(redshift): intercept Extended Query statements

* test(redshift): cover Extended Query JDBC compatibility

* test(redshift): cover Extended Query SDK compatibility

* docs(redshift): document Extended Query interception

* feat(redshift): implement extended query execution handling in BackendResponseCoordinator and update related classes

* feat(redshift): enhance ExtendedS3Exchange with client synchronization handling

* fix(redshift): synchronize extended COPY failures

* fix(redshift): tolerate backend ownership fragmentation

* fix(redshift): forward extended query flush frames

* fix(redshift): abort backend copy on unload failure

* fix(redshift): preserve later extended query mutations

* fix(redshift): return ready state after copy failure

* test(redshift): cover later sync cycle rollback

* fix(redshift): preserve independent mutations when rejecting a pipelined mutation

ExtendedQuerySession.rejectFrom() restored the whole statements/portals
map back to the rejected mutation's "before" snapshot and truncated the
journal to the end, discarding any later, independent mutation that
happened to run first. The coordinator already rejects one pipelined
mutation at a time in journal order, so this only ever needs to undo
that one mutation's own effect.

Each journal entry now also records its own "after" snapshot at
creation time, since reconstructing it later from the next entry's
"before" or from the live maps goes stale once an earlier reject's
cascading portal cleanup has already touched a key this mutation never
itself changed.

* fix(redshift): forward the real ReadyForQuery after a COPY/UNLOAD failure

readClientSync(client) called the two-argument overload without its
Flush-forwarding OutputStream, which did not compile.

Every error branch in the Extended Query COPY/UNLOAD path sent CopyFail
and Sync to the backend but never drained or forwarded the backend's
resulting ReadyForQuery: the client waited on a frame nobody ever read
off the wire. drainReadyForQuery already existed for exactly this but
was never called. Wire it into every COPY and UNLOAD error branch.
2026-09-13 08:54:52 -04:00
Vũ Thế Huy 6b17ef2b1c feat(redshift): emulate GetClusterCredentials and GetClusterCredentialsWithIAM (#3273)
* feat(redshift): add RedshiftCredentialBroker for short-lived Db credentials

* refactor(rds-proxy): widen PasswordValidator to a three-value AuthResult

The wire-level password check the PostgreSQL/MySQL proxy handlers take now
returns REJECT / PASSTHROUGH / MASTER_EQUIVALENT instead of a boolean, so a
caller can tell the proxy to open the backend leg as the cluster master for a
client it has vouched for. RdsAuthProxy keeps its own boolean master-password
callback, renamed MasterPasswordCheck to free the PasswordValidator name, and
adapts it at the handler boundary (non-master stays PASSTHROUGH).

* feat(redshift): auth proxy accepts live GetClusterCredentials credentials

passwordValidatorFor now returns AuthResult and consults RedshiftCredentialBroker:
the master pair and any live minted credential resolve to MASTER_EQUIVALENT, a
known broker user with a stale password is REJECTed, everyone else PASSTHROUGH.

* feat(redshift): add default-credential-duration-seconds config

* feat(redshift): implement GetClusterCredentials action

Mints a short-lived DbUser/DbPassword pair via RedshiftCredentialBroker and
returns it as Query-protocol XML. AutoCreate prefixes IAM: on the DbUser,
DbGroups are echoed, DurationSeconds is validated to 900-3600 (default from
the new config key), and an unknown ClusterIdentifier propagates ClusterNotFound.
The two credential actions are registered in AwsQueryController.REDSHIFT_ACTIONS
and the Query dispatch now forwards the Authorization header to the handler.

* feat(redshift): implement GetClusterCredentialsWithIAM action

Derives the DbUser from the caller's IAM identity resolved via the Authorization
header: an IAM user maps to IAM:<name>, an assumed role to IAMR:<role>, and an
unresolvable caller to the IAMR:floci fallback with a WARN so local and CI flows
are not blocked. Any DbUser request parameter is ignored.

* feat(redshift-data): resolve non-master DbUser via GetClusterCredentials

resolveViaDbUser now accepts a DbUser that has a live credential in
RedshiftCredentialBroker, connecting to the container as the cluster master
(the minted DbUser is nominal). An unknown non-master DbUser still fails with
ValidationException.

* test(redshift): end-to-end GetClusterCredentials + Data API non-master DbUser

Docker-gated: mints a credential for a non-master DbUser via GetClusterCredentials
then runs SELECT 1 through the Data API as that DbUser, asserting the result.

* test(compat): SDK coverage for Redshift GetClusterCredentials

Adds getClusterCredentials and getClusterCredentialsWithIAM assertions to the
AWS SDK Redshift compatibility test.

* docs(redshift): document GetClusterCredentials and GetClusterCredentialsWithIAM

Regenerates the redshift.md action table (excluding the DbGroups member-name
switch label), fills the two new descriptions, updates the wire-auth and
redshift-data.md DbUser notes, and bumps the Service Matrix count to 23.

* fix(redshift): reject a wrong master password instead of passing it through

passwordValidatorFor only treated the master pair as MASTER_EQUIVALENT and let
everything else fall to the broker. A request with the master username but a
wrong password is unknown to the broker, so it classified as PASSTHROUGH; the
wire proxy then opened the backend leg as master (isMaster is username-only) and
the client authenticated with the wrong password. Now the master username is
decided on its own password: match to MASTER_EQUIVALENT, mismatch to REJECT.

* fix(redshift): reject proxy logins when the cluster row is gone; strip IAM user path

passwordValidatorFor fell through to the broker when the cluster was absent from
the account partition, classifying an unknown user as PASSTHROUGH; the wire proxy
reads isMaster from its own start-time config, so that still opened the backend
as master for the master username with any password. Return REJECT when there is
no cluster row to validate against.

RedshiftIamDbUserResolver now strips an IAM path prefix from a user ARN
(user/team/alice -> alice), matching how AWS names the DbUser.

* fix(redshift): keep concurrent credentials, revoke on delete, bound the config default

Addresses PR review (greptile):
- RedshiftCredentialBroker now holds every unexpired credential per DbUser instead
  of one slot, so a reissue no longer invalidates a still-live password (matches
  AWS, which keeps each issued credential valid to its own expiry).
- Add revokeCluster(); RedshiftService calls it on deleteCluster and at the start
  of createCluster, so a cluster recreated with the same identifier does not
  inherit master-equivalent access from a stale credential.
- resolveDurationSeconds now holds the YAML default to the same 900-3600 bounds as
  a request value, falling back to 900 with a WARN instead of minting a credential
  that is already expired or over-range.

* fix(redshift): revoke temp credentials on createCluster rollback too

The greptile review asked for revocation on 'relevant rollback paths'. Both
createCluster failure branches that delete the cluster row now also call
credentialBroker.revokeCluster, so a credential issued by a concurrent
GetClusterCredentials while the row briefly existed cannot outlive it.

* fix(redshift): correct GetClusterCredentials AutoCreate prefix

AWS prefixes the returned DbUser with IAM: when AutoCreate is false and
IAMA: when it is true. The handler returned IAM: when true and no prefix
when false, so a client using the returned name could not authenticate
and the value diverged from GetClusterCredentialsWithIAM, which already
issues prefixed identities.

The broker keys on the returned name, so the proxy and Data API now
expect the prefixed DbUser. Tests and the redshift docs are updated to
match.

* test(redshift): give compat GetClusterCredentials tests distinct @Order

Three methods shared @Order(2), leaving their relative order undefined.
Number the two credential tests 3 and 4 and move testDeleteCluster to 5.
2026-09-10 23:58:33 -04:00
Vũ Thế Huy b9039fef1d feat(redshift-data): emulate the Amazon Redshift Data API (#3186)
* feat(redshift-data): resource resolver, connection factory, statement store, service registration

* feat(redshift-data): field mapper, column metadata, SQL parameter binding

* feat(redshift-data): execute, describe, and paged result retrieval

* feat(redshift-data): batch execution, list statements, cancel

* feat(redshift-data): schema introspection operations

* test(redshift-data): end-to-end Data API over a real cluster plus SDK compatibility test

* docs(redshift-data): document the Redshift Data API surface

* fix(redshift-data): address code review findings

- rejectMultiStatement now reuses the SQL tokenizer so a semicolon inside a
  comment, string literal, or dollar-quoted block no longer rejects a valid
  single statement
- GetStatementResultV2 gains unit coverage for the typed and CSV envelopes
- CSV output is RFC 4180 quoted (embedded comma, quote, CR, LF)
- batch rollback is asserted transactionally in the integration test
- RedshiftDataFieldMapper logs a swallowed blob-read SQLException
- RedshiftPid/RedshiftQueryId use a non-negative hash
- NextToken that decodes to a negative offset is rejected
- CancelStatement leaves a FAILED statement FAILED
- DescribeTable paginates ColumnList and emits NextToken
- DbUser is echoed on the SecretArn path
- the statement store no longer builds its sweeper executor in the test constructor

* fix(redshift-data): address PR #3186 review findings

- SQL scanner handles PostgreSQL escape strings (E'...'): a backslash-escaped
  quote no longer ends the literal and mis-detects a following :name as a bind
  marker; plain '...' literals still treat backslash as an ordinary character
- ListStatements clamps MaxResults to 1..100 so MaxResults=0 no longer emits the
  same NextToken forever
- DescribeTable matches Table / Schema exactly (=) instead of LIKE, so a name
  containing _ or % cannot merge other tables' columns into ColumnList
- register the service in the README category table
- drop a stray em dash from the neighbouring services.yaml comment

* fix(redshift-data): bind string parameters untyped so real PostgreSQL infers the column type

CI ran the integration test against a real Redshift (PostgreSQL 15) cluster and
parameterisedStatement failed: a string bound to an int column via setString
raised "operator does not exist: integer = character varying". H2 in PostgreSQL
mode coerces it, so the unit test missed it.

- RedshiftDataConnectionFactory adds stringtype=unspecified to the JDBC URL, so
  setString sends the value untyped and the server infers the target type,
  matching how AWS binds Redshift Data API parameters
- ListStatements now rejects MaxResults above 100 with ValidationException
  instead of silently clamping (PR #3186 re-review)
- RedshiftDataOperationsTest uses JBoss Logging, not java.util.logging (PR #3186 re-review)

* fix(redshift-data): back the statement store with StorageFactory

The store held a bare ConcurrentHashMap outside the configured storage and
lifecycle model. It now obtains an account-aware backend through StorageFactory
("redshift-data", statements.json), the same as Athena's query store, resolved to
the global storage mode via the catalog descriptor. Default mode stays memory, so
statements are still lost on restart as documented; the 24h TTL sweep now walks
every account partition and deletes per account since the sweep thread has no
request context. StoredStatement is annotated for reflection and field-visible
serialization so persistent modes round-trip it.

* test(redshift-data): cover StoredStatement serialization round-trip and values()

The StorageFactory-backed store serializes StoredStatement in persistent modes.
Adds a round-trip test through the exact mapper PersistentStorage builds,
covering the ArrayNode, enum, Instant, and nested sub-statement fields plus the
field-visibility annotation, and a values() test.

* fix(redshift-data): register the nested Status enum for reflection

PersistedModelReflectionTest walks every type reachable from a StorageFactory
persistence root; StoredStatement.status pointed at an unregistered enum, so
native-image deserialization of a persisted statement would fail on restart.
2026-09-07 20:18:22 -04:00
Vũ Thế Huy 4570bf62c5 feat(redshift): emulate Redshift UNLOAD TO s3 over Simple Query protocol (#3129)
* feat(redshift): parse UNLOAD TO s3 statements

* feat(redshift): add S3Service.authorizeAnonymousPutObject for the UNLOAD writer

* feat(redshift): simulate Redshift UNLOAD TO s3 via CopyOut

* feat(redshift): dispatch UNLOAD via the intercepting bridge

* test(redshift): cover UNLOAD to S3 end to end

* docs(redshift): document UNLOAD to S3 support

* fix(redshift): drain backend on UNLOAD streaming failure and handle final slice error

* refactor(redshift): clean up inline FQCN imports across main and test sources

* fix(redshift): address review feedback on UNLOAD to S3 simulator

* fix(redshift): authorize ListBucket on UNLOAD prefix probe and clean up manifest on backend EOF

* fix(redshift): authorize UNLOAD cleanup deletes and skip them under ALLOWOVERWRITE

* fix(redshift): fail open on UNLOAD MAXFILESIZE above the buffering ceiling

* feat(redshift): repeat the UNLOAD header row at the start of every slice

* test(redshift): cover UNLOAD to S3 over JDBC in the SDK compatibility suite

* docs(redshift): document UNLOAD per-file header, MAXFILESIZE bytes, and over-cap fail-open

* fix(redshift): clean up new UNLOAD slice objects even under ALLOWOVERWRITE

deleteWritten previously bailed entirely when ALLOWOVERWRITE was set, to avoid
destroying a pre-existing object a slice key had overwritten. That also left
genuinely new slice keys behind on a MANIFEST failure, exposing a partial result
with no manifest. Track which slice keys existed before the write and skip only
those on cleanup.

* fix(redshift): never delete UNLOAD output under ALLOWOVERWRITE

The preExistingKeys heuristic could not distinguish an overwrite from a fresh
write atomically: two concurrent UNLOADs to the same prefix could both classify a
key as new, and one operation's cleanup could then delete the other's output.
Drop the heuristic and simply never delete under ALLOWOVERWRITE. Non-overwrite
runs verified the prefix was empty, so their cleanup is still safe. A failed
MANIFEST + ALLOWOVERWRITE UNLOAD may leave data objects without a manifest, which
is now documented.

* fix(redshift): read UNLOAD objects via getObject in the integration test

listObjects returns metadata-only S3Object entries whose getData() is null, so
unloadToS3PrefixWritesRowsAsObjects and unloadGzipWritesCompressedObject threw
NullPointerException in CI. Fetch each body with getObject, as the MANIFEST test
already does.
2026-09-06 15:58:37 -05:00
Vũ Thế Huy 85180a4d88 feat(redshift): emulate Redshift COPY FROM s3 over Simple Query protocol (#3100)
* feat(redshift): parse COPY FROM s3 statements

* feat(redshift): simulate Redshift COPY FROM s3 via CopyIn

* feat(redshift): mediate the intercepting bridge pump with a backend lock

* feat(redshift): dispatch COPY FROM s3 via intercepting bridge

* test(redshift): cover COPY from S3 end to end

* docs(redshift): document COPY from S3 support

* fix(redshift): harden the S3 COPY simulator error and protocol handling

Address code review findings on the Part 4 COPY simulator:

- Guarantee exactly one client response on a mid-copy failure. The abort
  path sent CopyFail, relayed the backend's ErrorResponse/ReadyForQuery,
  then also synthesized its own, desynchronizing the client. It now emits
  one response: the backend's, or a synthesized one only when the backend
  is unreachable.
- Catch RuntimeException (AwsException) while streaming objects. A key that
  vanished between listing and reading previously propagated out of the
  bridge and closed the connection with the backend stuck in CopyIn.
- Reply to the client when the backend closes before CopyInResponse
  instead of returning silently and leaving the client blocked.
- Stop doubling backslashes when quoting DELIMITER / NULL values. Under
  standard_conforming_strings a backslash is literal, so NULL AS '\N' was
  reaching the backend as '\N' and nulls loaded as text.
- Reject COPY statements carrying an option the simulator cannot honour
  (PARQUET, JSON, MAXERROR, credentials, ...) or a trailing statement,
  so they fail open to PostgreSQL rather than loading with wrong framing.
- Scan option keywords with string literals blanked, so NULL AS 'csv' no
  longer flips the format and DELIMITER ';' no longer trips the trailing
  check.
- Report the failed-transaction status ('E') in a synthesized error when
  the client is in a transaction block; track it from the backend's
  ReadyForQuery in the bridge.
- Bound the backend read timeout during an owned exchange (60s) instead of
  blocking forever; back off between idle-wait retries.
- Relay asynchronous backend messages (NoticeResponse, ParameterStatus)
  to the client instead of dropping them; log every tolerated AwsException.
- Honour the BackendExchange return value so a future interceptor can
  decline before touching the backend.

Tests: cover the mid-copy abort (one E + one Z), backend EOF, literal
NULL AS '\N', the unsupported-clause and trailing-statement rejections,
failed-transaction status, plus a GZIP end-to-end case; the missing-object
integration test now seeds its own bucket.

* fix(redshift): address review feedback on COPY option parsing, prefix pagination, and tx state

* fix(redshift): handle backend tx abort sync failure and log socket close

* fix(redshift): verify backend transaction status 'E' after abort query
2026-09-05 23:46:49 -04:00
Vũ Thế Huy 4daba7ed6a feat(redshift): wire the Simple Query DDL interceptor into the proxy (#3029)
* feat(redshift): add PostgresWireDecoder for frontend wire-message framing

* feat(redshift): intercept Simple Query DDL through RedshiftInterceptingBridge

* test(redshift): end-to-end DDL rewrite over the Simple Query protocol

* docs(redshift): document the Simple Query DDL interceptor

* fix(redshift): remove em-dashes and address review feedback on bridge

* fix(redshift): stream opaque non-query frames without size limit

* fix(redshift): stream oversized simple query frames to passthrough

* test(redshift): import stream types in RedshiftInterceptingBridgeTest

* test(rdsdata): fallback to direct H2 driver on classloader mismatch

* test(redshift): remove oversized socket test from RedshiftInterceptingBridgeTest
2026-09-05 10:36:34 -04:00
Vũ Thế Huy 426fbcb284 feat/redshift auth proxy (#2751)
* feat(redshift): add auth proxy port range and endpoint-host config

* feat(redshift): add containerHost/containerPort/proxyPort to Cluster model

* feat(redshift): add RedshiftAuthProxy reusing the RDS PostgreSQL protocol handler

* feat(redshift): add RedshiftProxyManager registry with shutdown hook

* feat(redshift): front new clusters with an auth proxy and advertise it

* feat(redshift): stop/update proxy on delete/modify, start it on snapshot restore

* feat(redshift): keep proxy port stable across reboot and adopt-on-startup

* test(redshift): integration coverage for JDBC through the auth proxy

* test(redshift): reinstate JDBC connectivity check now that the proxy exists

* docs(redshift): document the cluster auth proxy and its config

* fix(redshift): prevent minor port leak when proxy fails to start

* fix(redshift): rollback container on proxy failure and surface teardown errors

* fix(redshift): stop auth proxy on rollback to prevent listener collisions

* fix(redshift): ensure proxy shutdown failure does not abort container and port cleanup

* fix(redshift): add proper logging for intentionally ignored cleanup exceptions

* fix: Wait for Redshift database readiness before proxying

Previously, RedshiftContainerManager just slept for 3 seconds before marking the container as started. On slower CI environments, the PostgreSQL database might take longer to initialize, resulting in Connection Refused when the RedshiftAuthProxy forwards connections.
Now, RedshiftContainerManager polls the database using psql until it's ready, up to 60 seconds.

* fix(redshift): prevent proxy port reallocation on shutdown failure

Addresses a review comment indicating that if a Redshift auth proxy fails to shut down during rollback or deletion, its port must not be released into the available pool. Reassigning a still-bound port would cause subsequent cluster creations to fail with a BindException.
Instead, we now tolerate proxy shutdown errors but intentionally leak the port allocation to prevent collisions.

* fix(redshift): fix failing tests due to proxy changes

1. RedshiftOperationsTest checked for a hardcoded port 5440, but the RedshiftService now allocates dynamic proxy ports. Removed the exact port assertion.
2. RedshiftContainerManager's psql readiness check was connecting via local Unix socket, which succeeded before PostgreSQL was actually ready to accept remote TCP connections from the proxy. Added '-h 127.0.0.1' to enforce TCP readiness.

* test(redshift): use Awaitility to connect to proxy

Use Awaitility to retry the initial connection in RedshiftProxyIntegrationTest to prevent transient 'Connection attempt failed' errors on slower CI environments.

* chore(redshift): use proper imports instead of fully-qualified class names in tests

* fix(redshift): fix compiler errors introduced during import cleanup

* fix(redshift): resolve proxy lifecycle bugs and CI network issues

- Throw RuntimeException from RedshiftProxyManager.stopProxy if proxy is not found. This allows RedshiftService to catch it and intentionally leak the port, preventing port collisions if a proxy fails before registration.
- Force RedshiftProxyIntegrationTest to connect via 127.0.0.1 instead of the endpoint address, which resolves to host.docker.internal in CI environments and causes UnknownHostException.

* fix(redshift): prevent proxy port exhaustion on startup failures

Instead of blindly assuming missing proxies denote a leaked port, RedshiftProxyManager now tracks proxies that failed their socket cleanup during startup. stopProxy throws an exception only if the socket is known to be leaked. This allows RedshiftService to safely release ports after clean proxy startup failures, addressing Greptile's feedback about port exhaustion.

* fix(redshift): retain proxy reference to allow retry on close failure

As identified by Greptile, stopProxy previously removed the proxy from the registry before calling proxy.stop(). If stop() threw an exception, the proxy reference was lost, preventing any subsequent retry from ever finding it and attempting to close it again. stopProxy now only removes the proxy from the registry after stop() returns successfully. Additionally, failedCleanups is now retained instead of cleared, ensuring retries continue to safely leak the port if cleanup remains impossible.

* fix(redshift): abort cluster deletion if proxy fails to stop

As highlighted by Greptile, previously deleteCluster would swallow proxy shutdown failures and delete the cluster metadata anyway. This eliminated the retry path, stranding the unclosed proxy and its port reservation until the process exited. Now, if stopProxyAndReleasePortSafely fails, deleteCluster throws an exception to preserve the cluster metadata so the deletion can be retried.

* test(redshift): lock in proxy lifecycle failure-recovery behaviors

Bổ sung test cho ba hành vi hardening chưa được cover, để refactor sau
không âm thầm phá vỡ:

- stopProxy giữ lại proxy trong registry khi close() ném, cho phép retry
  gọi lại đúng instance và chỉ deregister sau khi stop sạch
- marker leak khi startup cleanup thất bại được retain qua mọi retry và
  chỉ bị xoá bởi một lần start mới thành công
- deleteCluster abort với InternalFailure, giữ nguyên container + metadata
  khi proxy không stop được; retry sau đó hoàn tất khi proxy stop OK

Đồng thời bỏ "-p 7100-7199:7100-7199" trong compatibility.yml: proxy bind
0.0.0.0 trong container floci và sdk-test-java chạy trên compat-net nên
JDBC đi container-to-container qua alias "floci", không cần publish port
ra host. Giữ lại FLOCI_SERVICES_REDSHIFT_ENDPOINT_HOST=floci.

* fix(redshift): keep an unclosable proxy reachable for later retry

Theo phản hồi mới của Greptile: khi start/replace proxy thất bại và
cleanupFailedStart cũng không đóng được listener, code cũ chỉ lưu relayKey
vào một Set rồi vứt object RedshiftAuthProxy. stopProxy sau đó ném vĩnh
viễn mà không còn cách nào chạm tới listener để thử đóng lại, khiến
cluster không xoá được và port bị giữ mãi trong dải hữu hạn.

Thay Set<String> failedCleanups bằng Map<String, RedshiftAuthProxy>
unclosableProxies. cleanupFailedStart giữ lại chính proxy đó; stopProxy và
stopAll thử đóng lại, chỉ gỡ entry khi stop thành công. startProxy không
còn xoá marker khi start mới — chỉ một lần stop thành công mới gỡ, vì
listener cũ có thể vẫn đang bound.

* fix(redshift): retry proxy port bind to absorb reboot rebind race

rebootCluster giữ nguyên proxy port của cluster để endpoint ổn định, nên
listener cũ bị đóng rồi bind lại đúng port đó chỉ vài ms sau. Dưới tải
(CI runner ARM) kernel có thể chưa nhả port và SO_REUSEADDR không giúp
được khi accept loop cũ đang teardown -> BindException -> RebootCluster
trả 500. Đây là nguyên nhân test RedshiftOperationsTest.
testClusterAndSnapshotLifecycle fail chập chờn.

start() giờ retry bind tối đa ~1s, chỉ nuốt BindException; IOException
khác vẫn propagate ngay. Thêm test dựng cảnh port bị chiếm tạm thời rồi
nhả, xác nhận proxy vẫn bind được.

* fix(redshift): tear down proxy and release port when rebootCluster fails

Nếu startProxy/restoreSnapshot ném sau khi proxy đã (re)start trong
rebootCluster, hai nhánh catch chỉ set status "failed" rồi rethrow —
proxy mới vẫn chạy và port vẫn nằm trong usedPorts, không nhánh nào dọn.
Giờ cả hai catch gọi stopProxyAndReleasePortSafely như createCluster và
restoreFromClusterSnapshot đã làm; proxyPort được hoist ra ngoài try với
sentinel -1 để rollback an toàn kể cả khi chưa cấp port.

Thêm test: restoreSnapshot ném -> proxy được stop lại, AwsException nổi lên.

* fix(redshift): serialize createCluster/deleteCluster/restoreFromClusterSnapshot

modifyCluster và rebootCluster đã synchronized nhưng create/delete/restore
thì không, dù cả năm method đều chạy chuỗi container + proxy + port nhiều
bước trên cùng một cluster. deleteCluster(x) chạy song song rebootCluster(x)
có thể để lại metadata mồ côi trỏ tới container/proxy đã dừng. Thêm
synchronized cho ba method còn lại để nhất quán.

* fix(rds,redshift): close backend socket when the auth handshake fails

handleConnection mở kết nối TCP tới container Postgres trước khi gọi
handleAuth. Chỉ nhánh thành công (bridge) và vài nhánh lỗi có kiểm soát
mới đóng backend; nếu handleAuth trả về sớm ở một probe trần (SSLRequest
không kèm startup) hoặc ném IOException (client ngắt giữa handshake), catch
cũ chỉ đóng client -> mỗi health-check TCP làm rò một connection tới
Postgres, ăn dần max_connections.

Chuyển việc đóng socket sang finally, đóng cả client lẫn backend
(idempotent, nhánh thành công đã đóng sẵn). Áp cho cả RdsAuthProxy vì
RedshiftAuthProxy được copy từ đó. Thêm test: client drop giữa handshake
-> backend nhận EOF.

* fix(redshift): stop replacement container and keep dump on failed reboot

Rollback của rebootCluster (b44fd1e3) mới chỉ stop proxy + release port,
để container thay thế chạy tiếp sau một cluster "failed", và finally vẫn
xoá tempDump. Vì container gốc đã stop và không có volume, tempDump là bản
sao duy nhất của data -> mất data không khôi phục được (bug có sẵn, giờ
mới lộ).

rollbackReboot() giờ stop luôn container thay thế (như createCluster/
restoreFromClusterSnapshot). tempDump chỉ bị xoá khi reboot thành công;
khi fail thì giữ lại và log đường dẫn để khôi phục thủ công.

* fix(redshift): make reboot rollback phase-aware to protect the original

Commit trước cho rollbackReboot stop container vô điều kiện. Nếu reboot
fail ngay ở takeSnapshot hoặc stopProxy — lúc container gốc (chứa data,
không volume) VẪN đang chạy — thì rollback lại force-remove chính nó, huỷ
bản sao data hoàn chỉnh duy nhất và chỉ còn dump rỗng/dở.

Thêm hai cờ:
- originalTornDown: đã stop proxy + container gốc -> rollback mới được
  đụng vào proxy/port
- replacementStarted: đã start container thay thế -> rollback mới được
  stop container
Fail trước hai mốc đó: không đụng gì, trạng thái gốc còn nguyên.

Thêm test: takeSnapshot ném -> cm.stop và stopProxy không được gọi.

* fix(redshift): clean an orphan replacement container on failed reboot

containerManager.start có thể tạo container Docker rồi mới ném ở
waitForReady, nên cờ replacementStarted (set sau khi start return) bỏ sót
trường hợp này -> orphan chạy dưới tên cluster.

Bỏ replacementStarted, gate rollback theo mỗi originalTornDown: một khi
proxy + container gốc đã stop thì container gốc chắc chắn biến mất, nên
containerManager.stop (xoá theo tên) chỉ có thể chạm replacement — kể cả
replacement do start() tạo dở rồi ném.

Thêm test: start() ném -> rollback vẫn gọi cm.stop để dọn orphan.

* fix(redshift): remove orphan cluster metadata on failed create/restore

* fix(redshift): keep failed cluster metadata if proxy stop fails

* fix(redshift): fix TooManyActualInvocations in proxy tests

* fix(redshift): clear proxyPort on reboot rollback if port is released

* fix(redshift): retain reserved port on reboot startup failure

* fix(redshift): retain proxy port in reboot rollback and teardown failed startup recovery

* fix(redshift): skip failing cluster and retaining dump if reboot fails before teardown
2026-08-31 09:03:26 -04:00
Vũ Thế Huy a1383fdd3d feat(redshift): implement Redshift emulation with snapshot and parameter group support (#2472)
* feat: add redshift domain models

* feat: add redshift service and test

* feat: add redshift query handler and routing

* feat(redshift): implement data plane container manager and wire storage

This commit implements Redshift Container Manager, wires the StorageFactory into RedshiftService, uses AwsException for error handling, implements Describe/Delete Clusters, and adds integration tests with AWS SDK in the compatibility tests project.

* feat: add redshift operations models and service logic

* fix: correct yaml indentation for redshift storage config

* fix: remove invalid redshift storage properties

* feat: implement pg_dump and psql for redshift snapshots

* feat: add redshift core operations query actions

* test: add redshift operations integration test

* fix(redshift): Write snapshot SQL dumps to file storage and add Parameter model

* docs: add redshift implementation plan, design spec, and PR description

* chore: remove superpowers working files

* fix(redshift): scope snapshots and cluster recovery per account, restore original password

- Scope snapshot SQL dump files under redshift-dumps/{accountId}/ so
  same-identifier snapshots from different accounts no longer collide,
  overwrite, or delete each other's data.
- Restore uses the source cluster's real master password instead of a
  hardcoded value, falling back to "admin" only when the source cluster
  no longer exists.
- Recreate Docker containers for all persisted "available" clusters on
  startup, across every account (not just the default), fixing clusters
  that were reloaded with stale endpoints but no running container.
- Add AccountAwareStorageBackend.accountId() accessor needed for the
  account-scoped dump path.

* fix(redshift): add logging for cleanup failures in RedshiftOperationsTest

* fix(redshift): scope container identity per account, persist snapshot password

- RedshiftContainerManager now keys its in-memory container map and Docker
  container name by accountId + clusterIdentifier, instead of just the
  cluster identifier. Previously two accounts creating a cluster with the
  same identifier would share (and clobber) the same Docker container,
  so startup recovery for the second account silently skipped its own
  cluster and left it advertised with a stale endpoint.
- Snapshot now captures masterPassword at snapshot-creation time, so
  restoreFromClusterSnapshot can recover the original credential even
  after the source cluster has been deleted, instead of falling back to
  "admin".
- Clean up fully-qualified java.nio.file / commons-compress references in
  RedshiftContainerManager in favor of imports.

* feat(redshift): implement adoptOrStart method to reuse existing containers

* chore: gitignore subagent-driven-development scratch workspace

* feat(redshift): add tagging support to RedshiftService

- Add tags field to Cluster, Snapshot, and ClusterParameterGroup models
- Inject RegionResolver into RedshiftService constructor
- Implement tag CRUD methods: createTags, deleteTags, describeTags, listTagsForResource
- Add resolveTagHandle ARN resolver for tagging operations
- Add 6 new unit tests covering tag operations and error cases

* feat(redshift): wire CreateTags/DeleteTags/DescribeTags into the query handler

* feat(redshift): store real parameter values on ClusterParameterGroup

* fix(redshift): use proper imports and preserve parameter metadata on modify

* feat(redshift): wire ModifyClusterParameterGroup, return real DescribeClusterParameters values

* feat(redshift): add ClusterSubnetGroup model and CRUD

* feat(redshift): wire ClusterSubnetGroup CRUD into the query handler

* feat(redshift): add ClusterSubnetGroupName/VpcSecurityGroupIds metadata to Cluster

* feat(redshift): add RedshiftContainerManager.alterUserPassword

* fix(redshift): prevent SQL injection in alterUserPassword via username validation

* feat(redshift): add RedshiftService.modifyCluster

* feat(redshift): add RedshiftService.rebootCluster (dump/restore based, no data loss)

* feat(redshift): wire ModifyCluster/RebootCluster into the query handler

* test(redshift): add compatibility coverage for tagging, subnet groups, modify/reboot

* fix(redshift): use imports and unique names in compatibility test

Follow this file's established conventions: proper imports instead of
fully-qualified SDK types, and TestFixtures.uniqueName() instead of
hardcoded resource names, matching the pattern used by the sibling
test methods.

* fix(redshift): address final whole-branch review findings

* fix(redshift): address PR review feedback and green the CI

Review comments:
- Translate three Vietnamese comments in RedshiftContainerManager and
  RedshiftService to English (repo is English-only).
- alterUserPassword: reword the single-quote guard to cite the AWS
  ModifyCluster MasterUserPassword constraint rather than the psql SQL
  literal, and enforce the full documented set for parity — reject
  ' " \ / @, require length 8-64 and at least one upper/lower/digit.
- adoptOrStart: LOG.warnv on the container-gone branch so a fresh empty
  cluster after a lost container is a searchable line, not a silent one.
- Move the .superpowers/ scratch ignore from the shared .gitignore to
  .git/info/exclude (local tooling, not project output).

CI failures:
- Register redshift.model.Parameter for reflection so
  PersistedModelReflectionTest passes and native-image persistence works
  (fixes CI shard 3 and the native sdk-test-java compat run).
- Convert RedshiftQueryHandler.handle() from an if/else chain to
  switch (action) so the docs action-table generator can extract the
  action list, matching every other Query handler. Bodies unchanged.
- Register redshift in tools/docs/services.yaml, add docs/services/redshift.md
  with the generated action table, and add the Service Matrix row in
  docs/services/index.md (fixes Docs Action Tables / Action tables in sync).

* fix(redshift): reject path traversal in SnapshotIdentifier

createSnapshot spliced the request's SnapshotIdentifier straight into a
host path (<persistentPath>/redshift-dumps/<accountId>/<id>.sql). A value
with traversal segments or an absolute prefix escaped the account dump
directory: snapshot creation would write pg_dump output over an arbitrary
host file, and the resulting absolute path was persisted so a later
restore (arbitrary read into an attacker-controlled DB) or delete
(arbitrary unlink) trusted it.

- validateSnapshotIdentifier: enforce AWS's format (1-255 chars, leading
  letter, letters/digits/non-consecutive hyphens) — rejects '.', '/', '\'
  so no separator can appear.
- Keep a normalise + startsWith(dumpDir) containment check as defence in
  depth.
- restore/delete now verify the stored sqlDump path still resolves inside
  the account dump dir before touching it, so a path written by the
  pre-fix code can't be acted on.

Also replace inline java.* fully-qualified names in RedshiftService and
RedshiftQueryHandler with top-of-file imports.

* fix(redshift): validate snapshot dump path before restore provisioning

The trusted-dump-path check added in the previous commit ran inside the
try block, after restoreFromClusterSnapshot had already persisted the
target cluster as "creating" and started its container. Rejecting an
untrusted path then left the container running and a "failed" cluster
record behind, blocking a retry with the same identifier
(ClusterAlreadyExists).

Move the check ahead of all provisioning — right after the snapshot is
loaded, before clusters.put and containerManager.start — so a rejected
restore creates no resources.

---------

Signed-off-by: Vũ Thế Huy <31652864+vuthehuyht@users.noreply.github.com>
2026-08-29 15:25:02 -04:00