mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
* 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.
122 lines
8.4 KiB
Markdown
122 lines
8.4 KiB
Markdown
# Redshift Data API
|
|
|
|
**Protocol:** JSON 1.1
|
|
**Endpoint:** `POST http://localhost:4566/` with `X-Amz-Target: RedshiftData.<Operation>` and `Content-Type: application/x-amz-json-1.1`
|
|
**Backing data plane:** the PostgreSQL container behind a Redshift cluster created through the Redshift emulator
|
|
|
|
Floci emulates the Amazon Redshift Data API: the HTTP API that Lambda, Step Functions, and EventBridge use to run SQL on a cluster without opening a PostgreSQL wire connection. Floci resolves the target cluster, connects straight to its container over JDBC, runs the SQL, and stores the statement and its result set in memory so the polling operations (`DescribeStatement`, `GetStatementResult`) can read them back.
|
|
|
|
For the upstream API shape, see the AWS documentation:
|
|
|
|
- [Using the Amazon Redshift Data API](https://docs.aws.amazon.com/redshift/latest/mgmt/data-api.html)
|
|
- [`ExecuteStatement`](https://docs.aws.amazon.com/redshift-data/latest/APIReference/API_ExecuteStatement.html)
|
|
- [`BatchExecuteStatement`](https://docs.aws.amazon.com/redshift-data/latest/APIReference/API_BatchExecuteStatement.html)
|
|
- [`DescribeStatement`](https://docs.aws.amazon.com/redshift-data/latest/APIReference/API_DescribeStatement.html)
|
|
- [`GetStatementResult`](https://docs.aws.amazon.com/redshift-data/latest/APIReference/API_GetStatementResult.html)
|
|
|
|
## Supported Actions
|
|
|
|
<!-- floci:actions:start -->
|
|
| Action | Description |
|
|
| --- | --- |
|
|
| `ExecuteStatement` | Run one SQL statement synchronously against the cluster container and store the result |
|
|
| `BatchExecuteStatement` | Run `Sqls` in order on one connection in a single transaction |
|
|
| `DescribeStatement` | Return a stored statement's status, timings, row counts, and sub-statements |
|
|
| `GetStatementResult` | Page through a finished statement's rows as typed `Records` |
|
|
| `GetStatementResultV2` | Same rows in the V2 envelope, with `CSVRecords` when the statement used `ResultFormat=CSV` |
|
|
| `ListStatements` | List stored statements newest first, filtered by `StatementName` or `Status` |
|
|
| `CancelStatement` | Mark a non-finished statement `ABORTED`; returns `{ "Status": true }` |
|
|
| `ListDatabases` | List databases on the cluster (`pg_database`) |
|
|
| `ListSchemas` | List schemas, optionally filtered by `SchemaPattern` |
|
|
| `ListTables` | List tables and views, optionally filtered by `SchemaPattern` and `TablePattern` |
|
|
| `DescribeTable` | List a table's columns from `information_schema.columns` |
|
|
<!-- floci:actions:end -->
|
|
|
|
## Authentication modes
|
|
|
|
A request identifies its target cluster one of two ways:
|
|
|
|
- **`ClusterIdentifier` + `DbUser` + `Database`.** The `DbUser` is the cluster master, or the prefixed name returned by `GetClusterCredentials` / `GetClusterCredentialsWithIAM` (for example `IAM:analyst`) while that credential is unexpired. Floci connects to the container as the cluster master in both cases. Any other `DbUser` returns `ValidationException`.
|
|
- **`SecretArn` + `ClusterIdentifier` + `Database`.** The secret must be a local Secrets Manager secret holding JSON credentials (`username` or `user`, plus `password`). A cross-region `SecretArn` is rejected.
|
|
|
|
`WorkgroupName` (Amazon Redshift Serverless) is rejected with `ValidationException`. Redshift Serverless is not emulated.
|
|
|
|
## Compatibility Notes
|
|
|
|
- **Execution is synchronous.** `ExecuteStatement` runs the SQL and returns only once the statement is terminal. `DescribeStatement` reports `FINISHED` or `FAILED`, or `ABORTED` after a `CancelStatement`. It never reports `SUBMITTED` or `STARTED`, and there is no progression over wall-clock time.
|
|
- **Execution errors are not HTTP errors.** A statement that fails to run is stored with `Status=FAILED` and an `Error` message, and `ExecuteStatement` still returns 200 with the statement `Id`. Callers see the failure through `DescribeStatement`, matching AWS.
|
|
- **Results are in memory.** Statement metadata and result sets are held in a store swept on a 24 hour TTL and are lost when Floci restarts. `ListStatements` returns only what is currently in memory.
|
|
- **`ExecuteStatement` takes one statement.** If the `Sql` contains more than one statement separated by `;`, it is rejected with `ValidationException`. Use `BatchExecuteStatement` for multiple statements.
|
|
- **`BatchExecuteStatement`** runs every entry of `Sqls` in order on one connection in a single transaction: it commits at the end, and on the first failing sub-statement it rolls back and marks the batch `FAILED` with that sub-statement's error. `DescribeStatement` on the parent id returns `SubStatements`, one per entry, each with its own id `<parentId>:<n>`. `GetStatementResult` on the parent id returns the rows of the last sub-statement that produced a result set; on a sub-statement id it returns that sub-statement's rows.
|
|
- **`GetStatementResult` and `GetStatementResultV2`** return the typed `Records` shape. `GetStatementResultV2` also returns `ResultFormat`, and when the statement was run with `ResultFormat=CSV` it returns `Records` as `CSVRecords` strings. A statement that produced no result set (an `INSERT`, `UPDATE`, `DELETE`, or DDL statement) returns `ValidationException` with the message `Statement has no result set`.
|
|
- **Paging.** The page size is 1000 rows. `NextToken` is an opaque base64 row offset; there is no server-side cursor.
|
|
- **`SqlParameters` / `Parameters`** are bound into a `PreparedStatement`. Named `:placeholder` markers are rewritten to positional JDBC bind parameters. Colons inside string literals, quoted identifiers, comments, PostgreSQL `::` casts, and dollar-quoted strings are left untouched. Redshift Data API parameter values are always strings on the wire; PostgreSQL coerces each bound value to the column type.
|
|
- **`CancelStatement`** returns `{ "Status": true }`. In Floci a statement is already terminal by the time it can be cancelled, so `CancelStatement` sets `Status=ABORTED` only when the statement was not already `FINISHED`. An unknown statement id returns `ResourceNotFoundException`.
|
|
- **`WithEvent`** is accepted and ignored: no EventBridge event is published.
|
|
- **`ExecuteSql` and `BatchExecuteSql`** (the deprecated pre-2020 operations) return `ValidationException`.
|
|
- **Type mapping.** JDBC `BOOLEAN` and `BIT` map to `booleanValue`; integer types to `longValue`; floating-point types to `doubleValue`; `NUMERIC` and `DECIMAL` to `stringValue` (as AWS does); binary types to `blobValue`; everything else, including dates, timestamps, uuid, and json, to `stringValue`. A SQL `NULL` maps to `isNull`.
|
|
|
|
## Configuration
|
|
|
|
| Variable | Default | Description |
|
|
|---|---|---|
|
|
| `FLOCI_SERVICES_REDSHIFT_DATA_ENABLED` | `true` | Enable or disable the Redshift Data API service |
|
|
| `FLOCI_SERVICES_REDSHIFT_DATA_RESULT_TTL_HOURS` | `24` | Hours a finished statement and its result set are kept in memory before the sweep evicts them |
|
|
|
|
The Redshift Data API also requires the Redshift service itself to be enabled, because it resolves `ClusterIdentifier` values to local Redshift clusters.
|
|
|
|
## Example
|
|
|
|
```bash
|
|
export AWS_ENDPOINT_URL=http://localhost:4566
|
|
|
|
aws redshift create-cluster \
|
|
--cluster-identifier wh \
|
|
--node-type dc2.large \
|
|
--master-username admin \
|
|
--master-user-password Secret123 \
|
|
--endpoint-url "$AWS_ENDPOINT_URL"
|
|
|
|
STATEMENT_ID=$(aws redshift-data execute-statement \
|
|
--cluster-identifier wh \
|
|
--db-user admin \
|
|
--database dev \
|
|
--sql "create table t (id int, name varchar(20))" \
|
|
--query Id --output text \
|
|
--endpoint-url "$AWS_ENDPOINT_URL")
|
|
|
|
aws redshift-data describe-statement --id "$STATEMENT_ID" --endpoint-url "$AWS_ENDPOINT_URL"
|
|
|
|
aws redshift-data execute-statement \
|
|
--cluster-identifier wh --db-user admin --database dev \
|
|
--sql "insert into t values (1, 'a'), (2, 'b')" \
|
|
--endpoint-url "$AWS_ENDPOINT_URL"
|
|
|
|
SELECT_ID=$(aws redshift-data execute-statement \
|
|
--cluster-identifier wh --db-user admin --database dev \
|
|
--sql "select id, name from t order by id" \
|
|
--query Id --output text \
|
|
--endpoint-url "$AWS_ENDPOINT_URL")
|
|
|
|
aws redshift-data get-statement-result --id "$SELECT_ID" --endpoint-url "$AWS_ENDPOINT_URL"
|
|
```
|
|
|
|
```python
|
|
import boto3
|
|
|
|
data = boto3.client("redshift-data", endpoint_url="http://localhost:4566")
|
|
|
|
started = data.execute_statement(
|
|
ClusterIdentifier="wh", DbUser="admin", Database="dev",
|
|
Sql="select id, name from t where id = :id",
|
|
Parameters=[{"name": "id", "value": "2"}],
|
|
)
|
|
statement_id = started["Id"]
|
|
|
|
while data.describe_statement(Id=statement_id)["Status"] not in ("FINISHED", "FAILED", "ABORTED"):
|
|
pass
|
|
|
|
result = data.get_statement_result(Id=statement_id)
|
|
print(result["ColumnMetadata"], result["Records"])
|
|
```
|