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

228 lines
14 KiB
Markdown

# Redshift
**Protocol:** Query (XML) for the management API
**Management Endpoint:** `POST http://localhost:4566/` with `Action=` param
**Data Endpoint:** Floci's auth proxy on the `Endpoint` and `Port` returned by `DescribeClusters` (PostgreSQL wire protocol)
Floci emulates Amazon Redshift by managing a real [PostgreSQL](https://www.postgresql.org/) Docker container per cluster behind a Redshift-shaped control plane. Each cluster sits behind a lightweight auth proxy on the Floci host, so the endpoint is reachable from outside Docker and the master password is validated at the proxy, a `ModifyCluster` password change takes effect for new connections immediately. 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.
For running SQL without a PostgreSQL wire connection (the way Lambda and Step Functions do), see the [Redshift Data API](redshift-data.md).
## Supported Actions
<!-- floci:actions:start -->
| 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 |
| `GetClusterCredentials` | Issue a short-lived DbUser / DbPassword pair the auth proxy and Data API accept for a non-master user |
| `GetClusterCredentialsWithIAM` | Issue short-lived credentials with the DbUser derived from the caller's IAM identity |
<!-- floci:actions:end -->
## 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`) |
| `FLOCI_SERVICES_REDSHIFT_PROXY_BASE_PORT` | `7100` | Lowest host port the per-cluster auth proxies bind |
| `FLOCI_SERVICES_REDSHIFT_PROXY_MAX_PORT` | `7199` | Highest host port the per-cluster auth proxies bind |
| `FLOCI_SERVICES_REDSHIFT_ENDPOINT_HOST` | _(unset)_ | Hostname advertised in `DescribeClusters`; unset resolves from the Docker host |
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
```yaml
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](../configuration/docker.md).
## Examples
### Management API (AWS CLI)
```bash
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)
```python
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)
```python
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"])
```
## SQL Interceptor
Floci's Redshift auth proxy inspects frontend queries on the PostgreSQL wire protocol (Simple Query `'Q'` protocol) and rewrites common Redshift-specific table DDL so it runs on the plain PostgreSQL backend.
### DDL compatibility
- Redshift-only table DDL keywords are stripped before the statement is forwarded: `DISTSTYLE ALL|EVEN|KEY|AUTO`, `DISTKEY (<col>)` and column-level `DISTKEY`, `[COMPOUND|INTERLEAVED] SORTKEY (<cols>)` and column-level `SORTKEY`, and `ENCODE <codec>` for the real Redshift column encodings (`raw`, `az64`, `bytedict`, `delta`, `delta32k`, `lzo`, `mostly8`, `mostly16`, `mostly32`, `runlength`, `text255`, `text32k`, `zstd`) or `auto`.
- The rewrite only runs when the statement's first keyword is `CREATE TABLE` or `ALTER TABLE`. A `SELECT`, `INSERT`, function body, or string literal that merely contains one of these keywords is forwarded byte-for-byte. Single-quoted and dollar-quoted string literals are masked before the rewrite, so a keyword inside a quoted value (including in a later statement of a multi-statement query) is preserved.
- Columns legitimately named `distkey`, `sortkey`, or `encode` survive.
### COPY from S3
`COPY <table> [(<columns>)] FROM 's3://<bucket>/<keyOrPrefix>' [options]` sent over the Simple
Query protocol is emulated: Floci reads the object (or every object under the prefix, in key
order) through its own S3 service and streams the rows into the backing PostgreSQL container with
`COPY ... FROM STDIN`.
- Supported options: `DELIMITER`, `FORMAT CSV` (or a bare `CSV`), `GZIP`, `IGNOREHEADER <n>` and
`HEADER`, `NULL AS`, and an explicit column list.
- The default framing is pipe-delimited text, matching Redshift. `FORMAT CSV` switches to CSV with
a comma default delimiter.
- `IGNOREHEADER` and `HEADER` skip lines from the first resolved object only.
- `GZIP` is the only input compression recognized; `BZIP2`, `LZOP` and `ZSTD` are not.
- S3 access is authorized as an unsigned request: with `FLOCI_SERVICES_S3_ENFORCE_AUTH` off it is
unrestricted; with it on, bucket policy and public access settings apply.
- Any other clause (`FIXEDWIDTH`, `JSON`, `PARQUET`, `AVRO`, `ORC`, `MANIFEST`, `MAXERROR`,
`DATEFORMAT`, `TIMEFORMAT`, `REGION`, `ENCODING`, `ESCAPE`, `REMOVEQUOTES`, `BLANKSASNULL`,
`EMPTYASNULL`, `TRUNCATECOLUMNS`, `ACCEPTINVCHARS`, credentials clauses, and so on) is not
recognized: the statement is forwarded unchanged and PostgreSQL returns its own error.
- A multi-statement query whose COPY is followed by another statement is not intercepted; send the
COPY on its own.
- Extended Query protocol COPY (a JDBC `PreparedStatement`, or pgjdbc's default
`preferQueryMode=extended`) is not intercepted. Use `preferQueryMode=simple`.
### Limitations
- Emulation runs on the **Simple Query protocol** (`'Q'`) only. Extended Query protocol statements (`Parse`/`Bind`/`Execute`) pass through untouched, including anything a JDBC `PreparedStatement` sends, and, with the pgjdbc default `preferQueryMode=extended`, plain `Statement` calls too. Connect with `preferQueryMode=simple` to exercise the interceptor from JDBC.
- The rewrite is textual (regex-based). It masks single-quoted string literals first, so `DEFAULT` / `CHECK` string values are safe, but it is **not** comment-aware and does not recognize escape strings (`E'...'`): an apostrophe inside a `--` or `/* */` comment can make the rewrite skip a Redshift clause. That fails safe: the statement then reaches PostgreSQL, which returns its own syntax error, but avoid apostrophes-in-comments in `CREATE TABLE` / `ALTER TABLE`.
- A `rewrite` failure or any statement the interceptor does not recognize is forwarded unmodified (fail-open); PostgreSQL then rejects the Redshift-only syntax itself.
- Simple Query ('Q') messages larger than 16 MiB bypass the interceptor and stream through verbatim without heap buffering; non-query traffic also streams through with no size limit.
- `GetClusterCredentials` / `GetClusterCredentialsWithIAM` mint a short-lived password held in memory (lost on restart). As in AWS, `GetClusterCredentials` prefixes the returned `DbUser` with `IAM:` when `AutoCreate` is false and `IAMA:` when it is true; that prefixed name is what the auth proxy and Data API accept. The returned `DbUser` is nominal: the session runs as the cluster master, not a distinct PostgreSQL role, so `current_user`, `GRANT`, and object ownership are the master's.
### UNLOAD to S3
`UNLOAD ('<select-statement>') TO 's3://<bucket>/<prefix>' [options]` sent over the
Simple Query protocol runs the select on the backing PostgreSQL container and writes
the result to S3 as one or more objects under `<prefix>`.
- Framing defaults to pipe-delimited text; `FORMAT CSV` (or `CSV`) switches to CSV
with a `,` default. `DELIMITER`, `HEADER`, `NULL AS`, and `ADDQUOTES` are honoured
(`ADDQUOTES` and `HEADER` force CSV framing on PostgreSQL 15).
- `PARALLEL ON` (default) names objects `<prefix>0000_part_00`,
`<prefix>0001_part_00`, and so on; `PARALLEL OFF` names them `<prefix>000`,
`<prefix>001`, and so on. The emulator has a single backend node, so more than one
object appears only when the result exceeds the per-file size. When `HEADER` is
set, the header row is repeated at the top of every object.
- `MAXFILESIZE [AS] <n> [MB|GB]` sets the per-file size; a bare number is bytes.
Each file is buffered in memory, so the default is 6 MiB (real Redshift defaults
to 6.2 GB) and a whole UNLOAD result is capped at 256 MiB; a larger result fails
with a SQL error (54000). A `MAXFILESIZE` above that 256 MiB cap is not
intercepted at all: the statement is forwarded and PostgreSQL reports its own error.
- A zero-row result still writes one object (empty, or the header row alone when
`HEADER` is set).
- `GZIP` compresses each object and appends `.gz` to its key.
- `MANIFEST` writes `<prefix>manifest` listing every object with its
`content_length`.
- Without `ALLOWOVERWRITE`, a non-empty target prefix fails with SQL error XX000 and the select
does not run. A failed UNLOAD then removes any objects it had already written. With
`ALLOWOVERWRITE` a failed UNLOAD leaves its objects in place (they may have replaced prior data,
so they are not deleted); a `MANIFEST` request that fails this way can leave data objects without
a manifest, and rerunning the same statement overwrites them.
- S3 access is authorized as an unsigned request, like COPY from S3.
- Any other option (`PARQUET`, `ENCRYPTED`, `REGION`, `IAM_ROLE` / `CREDENTIALS`,
`ZSTD`, `EXTENSION`, `CLEANPATH`, `PARTITION`, and so on) is not intercepted; the
statement is forwarded and PostgreSQL reports its own error.
- Extended Query protocol UNLOAD (a JDBC `PreparedStatement`) is not intercepted.
## Out of Scope
- Real Redshift SQL semantics: the data plane is stock PostgreSQL. Redshift-only table DDL keywords (DISTSTYLE / DISTKEY / SORTKEY / ENCODE) are stripped so CREATE TABLE / ALTER TABLE executes (see [SQL Interceptor](#sql-interceptor)), but the distribution/sort behavior they request is not; SUPER/SPECTRUM are 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.
- The auth proxy validates the master user's password and any live `GetClusterCredentials` credential. Other non-master users pass straight through to PostgreSQL, which remains the authority for their credentials.
- IAM database authentication over the wire, and `sslmode=verify-full` against the self-signed proxy certificate.