Commit Graph
7 Commits
Author SHA1 Message Date
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