Files
floci/docs/services/redshift.md
T
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

6.2 KiB

Redshift

Protocol: Query (XML) for the management API Management Endpoint: POST http://localhost:4566/ with Action= param Data Endpoint: the Endpoint and Port returned by DescribeClusters (PostgreSQL wire protocol)

Floci emulates Amazon Redshift by managing a real PostgreSQL Docker container per cluster behind a Redshift-shaped control plane. Redshift speaks the PostgreSQL wire protocol, so the cluster endpoint returned by DescribeClusters works with any standard PostgreSQL driver (psql, JDBC, psycopg, …).

Always read the host and port from DescribeClusters rather than assuming a fixed port. PostgreSQL listens on 5432 inside the container; the port you connect to is dynamically assigned on the host and returned as Clusters[0].Endpoint.Port. Redshift's conventional port is 5439, but the emulator does not bind it — use whatever DescribeClusters reports.

The container has no persistent volume: if the physical container survives a Floci restart it is adopted and its data is kept, but if the container itself is gone (host reboot, docker rm, a pruned dev box) the cluster comes back empty. Use CreateClusterSnapshot / RestoreFromClusterSnapshot to preserve data explicitly.

Supported Actions

Action Description
CreateCluster Create a cluster and start a PostgreSQL container for it
DescribeClusters List clusters and their connection details
DeleteCluster Stop and remove a cluster and its container
CreateClusterSnapshot Back up a cluster to a SQL dump via pg_dump
DescribeClusterSnapshots List snapshots, optionally filtered by snapshot or cluster identifier
DeleteClusterSnapshot Remove a snapshot and its stored dump
RestoreFromClusterSnapshot Create a new cluster and load a snapshot's dump into it via psql
CreateClusterParameterGroup Register a parameter group (metadata only)
DescribeClusterParameterGroups List parameter groups, optionally filtered by name
DescribeClusterParameters Return the parameters of a group, with any values set by ModifyClusterParameterGroup
ModifyClusterParameterGroup Update parameter values on a group
DeleteClusterParameterGroup Remove a parameter group
CreateTags Add or overwrite tags on a cluster, snapshot, subnet group or parameter group
DeleteTags Remove tags by key from a resource
DescribeTags List tagged resources and their tags
CreateClusterSubnetGroup Register a cluster subnet group (metadata only)
DescribeClusterSubnetGroups List subnet groups, optionally filtered by name
ModifyClusterSubnetGroup Update a subnet group's description or subnet list
DeleteClusterSubnetGroup Remove a subnet group
ModifyCluster Update node type, parameter group, security groups, or the master password
RebootCluster Restart a cluster's container

Configuration

Variable Default Description
FLOCI_SERVICES_REDSHIFT_ENABLED true Enable or disable Redshift
FLOCI_SERVICES_REDSHIFT_IMAGE_VERSION postgres:15-alpine PostgreSQL Docker image backing each cluster
FLOCI_SERVICES_REDSHIFT_DEFAULT_PORT 5439 Reported Redshift port hint (the real host port is dynamic and comes from DescribeClusters)

Redshift needs the Docker socket so it can launch PostgreSQL containers. Each cluster's container is published on a dynamically assigned host port, returned by DescribeClusters.

Docker Compose

services:
  floci:
    image: floci/floci:latest
    ports:
      - "4566:4566"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock

For private registry authentication and other Docker settings see Docker Configuration.

Examples

Management API (AWS CLI)

export AWS_ENDPOINT_URL=http://localhost:4566
export AWS_DEFAULT_REGION=us-east-1
export AWS_ACCESS_KEY_ID=test
export AWS_SECRET_ACCESS_KEY=test

# Create a cluster (starts a PostgreSQL container)
aws redshift create-cluster \
  --cluster-identifier my-warehouse \
  --node-type dc2.large \
  --master-username admin \
  --master-user-password Secret123

# Read the cluster endpoint and port
aws redshift describe-clusters \
  --cluster-identifier my-warehouse \
  --query 'Clusters[0].Endpoint'

# Snapshot and restore
aws redshift create-cluster-snapshot \
  --snapshot-identifier snap-1 \
  --cluster-identifier my-warehouse
aws redshift restore-from-cluster-snapshot \
  --cluster-identifier my-warehouse-restored \
  --snapshot-identifier snap-1

# Delete
aws redshift delete-cluster \
  --cluster-identifier my-warehouse \
  --skip-final-cluster-snapshot

Data plane (Python + psycopg)

import psycopg

# Read host and port from DescribeClusters — the host port is dynamic.
host, port = "localhost", 32768  # e.g. Clusters[0].Endpoint.Address / .Port
with psycopg.connect(f"host={host} port={port} dbname=dev user=admin password=Secret123") as conn:
    conn.execute("CREATE TABLE people (name text)")
    conn.execute("INSERT INTO people VALUES ('Alice')")
    for row in conn.execute("SELECT * FROM people"):
        print(row)

Management API (Python / boto3)

import boto3

redshift = boto3.client(
    "redshift",
    endpoint_url="http://localhost:4566",
    region_name="us-east-1",
)

cluster = redshift.create_cluster(
    ClusterIdentifier="my-warehouse",
    NodeType="dc2.large",
    MasterUsername="admin",
    MasterUserPassword="Secret123",
)
print(cluster["Cluster"]["Endpoint"])

Out of Scope

  • Real Redshift SQL semantics — the data plane is stock PostgreSQL, so Redshift-only SQL (distribution/sort keys, COPY/UNLOAD from S3, SUPER/SPECTRUM) is not emulated.
  • Multi-node clusters — NodeType and NumberOfNodes are stored as metadata; every cluster is a single PostgreSQL container.
  • Parameter groups apply no real engine settings; values are stored and echoed back only.
  • Subnet groups, VPC routing, and security groups are metadata only.
  • Resize, pause/resume, IAM authentication, snapshot schedules, and cross-region snapshot copy.