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