From 32216be968e8fe2a810d7a2e979251159b157a37 Mon Sep 17 00:00:00 2001 From: Jairo Suarez Date: Wed, 18 Nov 2026 17:19:55 +0000 Subject: [PATCH 01/11] docs(bb-kv-store): state that there is no atomic increment; errors after the options The conditional-writes section pointed to `transaction()` on `Database` (`@aws-blocks/bb-data`) or `DistributedDatabase` (`@aws-blocks/bb-distributed-data`); neither package exists, so it now names `transaction()` on `Database`. The same section now says that KVStore has no atomic increment and gives two ways to keep a concurrent counter: a `get()`/conditional `put()` loop that creates the item with `ifNotExists: true` and retries on `KVStoreErrors.ConditionalCheckFailed`, or one item per event aggregated with `query()`. The errors table moves to directly after the options, with the causes of `ValidationFailedException` and `InvalidQueryException` as lists, and the options table has a `Default` column. `scan` has its own section, and "Best practices" and "Scaling and cost (AWS)" keep only the items that are not stated earlier in the README. The README keeps 17 `typescript` blocks and 4 compile-error lines; `scripts/generate-readme-test.mjs` requires at least 15 and 4. --- packages/bb-kv-store/README.md | 166 ++++++++++++++++----------------- 1 file changed, 80 insertions(+), 86 deletions(-) diff --git a/packages/bb-kv-store/README.md b/packages/bb-kv-store/README.md index 773833bc8f..bc10ac9d3e 100644 --- a/packages/bb-kv-store/README.md +++ b/packages/bb-kv-store/README.md @@ -2,7 +2,7 @@ Key-value and document storage backed by DynamoDB, with optional secondary indexes. -**When to use:** Any data that you read by key. With no options, `KVStore` is a string-keyed store for caches, sessions, feature flags, and config values. With a `schema` and a `key`, it holds app records that you list or query as a collection, such as todos, orders, or messages. Add `indexes` to read the same records by other fields. +**When to use:** Any data that you read by key. [Pick a form](#pick-a-form) lists the three forms. **Declare a key for anything you list.** A store fixes its key when you create it. A store with a string key reads one item for each key, and it cannot list its keys in order or by prefix. @@ -12,9 +12,9 @@ The examples import from the umbrella package `aws-cdk-blocks`, which every app > Design and mock parity details: [DESIGN.md](./DESIGN.md) -## Pick a form +For an app that has a `KVStore` from release 0.4.0 or earlier, see [Upgrade from release 0.4.0 or earlier](#upgrade-from-release-040-or-earlier). -Pick the form by how you read the data. +## Pick a form | You read the data | Form | Examples | |---|---|---| @@ -71,8 +71,6 @@ const store = new KVStore(scope, id, options?) | `KVStore.fromExisting(tableName)` | `ExternalTableRef` | Refer to a DynamoDB table that exists. | | `KVStore.fromKmsKey(keyArn)` | `ExternalKmsKeyRef` | Refer to a KMS key that exists. | -For an app that has a `KVStore` from release 0.4.0 or earlier, see [Upgrade from release 0.4.0 or earlier](#upgrade-from-release-040-or-earlier). - `Results` is an `AsyncIterable` of `{ key, value, expiresAt }` entries with one more property, `cursor`. `expiresAt` is present when the item has an expiry. Collect it with `await Array.fromAsync(results)` or read it with `for await`. **Runtime only.** The data methods run at request time. Call them inside an `ApiNamespace` method, a `RawRoute` handler, a job handler, or a runtime script. Do not call them at the top level of `cdk-blocks/index.ts`. Top-level code runs during CDK synth, where a data method throws an `Error` that reads `KVStore.() cannot be called during CDK synth`. You can construct the block at module scope. @@ -81,21 +79,56 @@ For an app that has a `KVStore` from release 0.4.0 or earlier, see [Upgrade from ### Options -| Option | Type | Description | -|--------|------|-------------| -| `schema` | `StandardSchemaV1` | Validates every `put` and sets the value types. Required for `key`, `indexes`, and `ttl`. | -| `key` | `{ partitionKey, sortKey? }` | Names the fields of the value that form the key. Each field is required in the schema and holds a string or a number. The schema must state which: a field that accepts a number is a number key, and any other field is a string key. Without `key`, the key is a string. | -| `indexes` | `Record` | Secondary indexes over fields of the value. | -| `ttl` | field name | Names the number field of the value that holds the expiry, in Unix epoch seconds. Without `ttl`, the block keeps the expiry outside the value. | -| `readValidation` | `'off' \| 'coerce' \| 'strict'` | How a read reconciles a stored value with `schema`. Defaults to `'coerce'`. See [Reads and schema changes](#reads-and-schema-changes). | -| `protection` | `'disposable' \| 'retained' \| 'locked'` | How hard the table is to destroy. Defaults to the stack `defaults`. | -| `pointInTimeRecovery` | `boolean \| { retentionDays: number }` | Continuous backups. Defaults to the stack `defaults`. | -| `encryption` | `'aws-managed' \| 'customer-managed' \| ExternalKmsKeyRef` | The key for encryption at rest. Defaults to `'aws-managed'`. | -| `table` | `ExternalTableRef` | Use a table that exists. See [Use a table that exists](#use-a-table-that-exists). | -| `logger` | `ChildLogger` | A logger for internal operations. Defaults to a logger at warn level. | +| Option | Type | Default | Description | +|--------|------|---------|-------------| +| `schema` | `StandardSchemaV1` | none | Validates every `put` and sets the value types. Required for `key`, `indexes`, and `ttl`. | +| `key` | `{ partitionKey, sortKey? }` | a string key | Names the fields of the value that form the key. Each field is required in the schema and holds a string or a number. The schema must state which: a field that accepts a number is a number key, and any other field is a string key. | +| `indexes` | `Record` | none | Secondary indexes over fields of the value. | +| `ttl` | field name | none | Names the number field of the value that holds the expiry, in Unix epoch seconds. Without `ttl`, the block keeps the expiry outside the value. | +| `readValidation` | `'off' \| 'coerce' \| 'strict'` | `'coerce'` | How a read reconciles a stored value with `schema`. See [Reads and schema changes](#reads-and-schema-changes). | +| `protection` | `'disposable' \| 'retained' \| 'locked'` | the stack `defaults` | How hard the table is to destroy. See [Durability and security defaults](#durability-and-security-defaults). | +| `pointInTimeRecovery` | `boolean \| { retentionDays: number }` | the stack `defaults` | Continuous backups. | +| `encryption` | `'aws-managed' \| 'customer-managed' \| ExternalKmsKeyRef` | `'aws-managed'` | The key for encryption at rest. | +| `table` | `ExternalTableRef` | a new table | Use a table that exists. See [Use a table that exists](#use-a-table-that-exists). | +| `logger` | `ChildLogger` | a logger at warn level | A logger for internal operations. | The mock and browser runtimes ignore `protection`, `pointInTimeRecovery`, and `encryption`. +## Errors + +Match an error by name with `isBlocksError`. + +| Constant | `error.name` | Thrown when | +|----------|--------------|-------------| +| `KVStoreErrors.ConditionalCheckFailed` | `ConditionalCheckFailedException` | A condition on `put` or `delete` failed. Status 409 in the JSON-RPC error. The HTTP status is also 409 when the namespace sets `httpErrorStatus: true`. | +| `KVStoreErrors.ValidationFailed` | `ValidationFailedException` | A value or an expiry is not valid. The causes are listed below. | +| `KVStoreErrors.InvalidQuery` | `InvalidQueryException` | The call has the wrong shape. The causes are listed below. | +| `KVStoreErrors.ItemTooLarge` | `ItemTooLargeException` | An item is larger than 400 KB. | +| `KVStoreErrors.BatchIncomplete` | `BatchIncompleteException` | A batch call left entries unprocessed. AWS runtime only. | + +`ValidationFailedException` is thrown for a value that: + +- fails the schema +- disagrees with its key +- has a `_bkv_` field or a `__proto__` field +- has an empty string in a key field or an indexed field +- has a key or indexed field over DynamoDB's size limit (2,048 bytes for a partition key, 1,024 for a sort key) +- nests lists or maps more than 32 levels deep + +It is also thrown for a bad expiry. + +`InvalidQueryException` is thrown for: + +- a bad key +- a bad `where`: a partition value or a sort value of the wrong type, a sort condition that does not exist, or a `between` with its bounds reversed +- an unknown index +- an `order` that is not `'asc'` or `'desc'` +- a bad `limit` +- a bad cursor +- an `indexes` option that is not an object +- `ifValueEquals` with an object +- a batch that repeats a key within one DynamoDB request (25 writes or 100 reads) + ## Keys A store with no `key` option takes a string key. A store with a `key` option takes an object that has exactly the key fields. @@ -112,7 +145,10 @@ await todos.get({ userId: 'alice', todoId: '001' }); A key field cannot hold an empty string. -The key is the identity of an item. `get`, `put`, `delete`, and the conditions `ifNotExists` and `ifExists` match the whole key. The whole key is the partition field, and the sort field if the store has one. In a store with a sort field, the sort field is unique only in its partition. Two items can have the same `todoId` if they have different `userId` values. To make one field unique in the whole store, make it the partition field of a key with no sort field. To list the items by another field, add an index. +- `get`, `put`, `delete`, and the conditions `ifNotExists` and `ifExists` match the whole key: the partition field, and the sort field if the store has one. +- A sort field is unique only in its partition. +- To make one field unique in the whole store, make it the partition field of a key with no sort field. +- To list the items by another field, add an index. ### Branded key fields @@ -190,7 +226,7 @@ await sessions.put({ sessionId: 's1' }, { userId: 'alice', expiresAt: Math.floor Do not change `ttl` on a deployed store. Items from before the change would keep their expiry in the old attribute and stop expiring. To change it, copy the items to a new store. See [Move a store between forms](#move-a-store-between-forms). -Expiry controls how long data stays. It does not control access. Check on every read that a session or a token is still valid. +Expiry controls how long data stays. It does not control access. To revoke a session or a token before it expires, delete the item. ## Conditional writes @@ -229,19 +265,24 @@ Use `ifFieldEquals` for an object value and `ifValueEquals` for any other value. The error has a `retriable` flag. It is true when a value check took part in a failed `put`, and when a failed `delete` had a value check and no `ifExists`. When `retriable` is true, read the item again and retry. A failed `ifNotExists` or `ifExists` alone is not retriable. -A conditional write is atomic for its item. No other write to that item lands between the call's check and its write. On AWS, each call is one DynamoDB `PutItem` or `DeleteItem` with a condition expression. The local mock runs the check and the write with no `await` in between, so no other request runs between them. +A conditional write is atomic for its item, on AWS and in the local mock. No other write to that item lands between the call's check and its write. + +There is no transaction across items. A batch call is not atomic on AWS. After a `BatchIncompleteException`, the entries that DynamoDB processed stay written. For a transaction, use `transaction()` on `Database`. -There is no transaction across items. A batch call is not atomic on AWS. After a `BatchIncompleteException`, the entries that DynamoDB processed stay written. For a transaction, use `transaction()` on [`Database`](../bb-database/README.md#transactions). +There is no atomic increment. To keep a counter that several writers change, use one of: + +- A loop. `get()` the item. `put()` the new value with `ifNotExists: true` if `get()` returned `null`, and otherwise with `ifValueEquals` or `ifFieldEquals` on the value you read. Retry on `KVStoreErrors.ConditionalCheckFailed`. Give such a counter no expiry: `get()` returns `null` for an expired item that a condition still sees (see [Expiry](#expiry)). +- One item per event. Aggregate the items with `query()`. ## Read consistency -`get` is a strongly consistent read by default. It returns a value that a `put` wrote a moment before. A consistent read uses twice the read capacity. Pass `{ consistentRead: false }` where a stale value is acceptable. +`get` is a strongly consistent read by default. A consistent read uses twice the read capacity. Pass `{ consistentRead: false }` where a stale value is acceptable. `getBatch`, `scan`, and `query` are eventually consistent. A `query` on an index is always eventually consistent. The local mock is always strongly consistent. ## Query -`query` reads the items of one partition in sort order. The store needs a `key` with a sort field, or an index. +The store needs a `key` with a sort field, or an index. ```typescript for await (const { key, value } of todos.query({ @@ -279,6 +320,8 @@ const lastHour = readings.query({ }); ``` +## Scan + `scan` reads the whole table and has no prefix option. Prefer `get` or `query`. `scan` takes these options. | Field | Required | Description | @@ -289,7 +332,7 @@ const lastHour = readings.query({ ## Pages -`query` and `scan` return a `cursor`. Pass it to the same call to read the next page, in this request or in a later one. The cursor is `undefined` when the read reached the end. A `cursor` of `undefined` starts at the first entry, so a client can pass back the `cursor` of the page before as it is. A `cursor` of `null` also starts at the first entry, because an option with the value `null` counts as an option that you did not pass. +`query` and `scan` return a `cursor`. Pass it to the same call to read the next page, in this request or in a later one. The cursor is `undefined` when the read reached the end. A `cursor` of `undefined` or `null` starts at the first entry, so a client can pass back the `cursor` of the page before as it is. ```typescript import { ApiNamespace, Auth } from 'aws-cdk-blocks'; @@ -304,12 +347,6 @@ export const todoApi = new ApiNamespace(scope, 'todo-api', (context) => ({ const entries = await Array.fromAsync(page); return { todos: entries.map((entry) => entry.value), cursor: page.cursor }; }, - async addTodo(title: string) { - const user = await auth.requireAuth(context); - const todoId = crypto.randomUUID(); - await todos.put({ userId: user.userSub, todoId }, { title, done: false, version: 1 }, { ifNotExists: true }); - return { todoId }; - }, })); ``` @@ -319,13 +356,10 @@ A cursor holds key values in a readable encoding. It is not a secret and not a p ## Indexes -An index reads the same items by other fields of the value. `indexes` needs a `schema`. - - An index field holds a string or a number. The schema states which, as for a key field. - An index holds an item only when each indexed field is present, is not an empty string, and has the declared type. `put` rejects an empty string in an indexed field. - To keep an item out of an index, leave the field out. Don't set it to `null`. On AWS, DynamoDB rejects a `put` whose indexed field holds `null` or a value of the other type with a `ValidationException`. The local mock accepts that write, so the error shows only on AWS. - An index query returns whole items, because every index that the block creates holds all fields of the value. A table from `fromExisting` keeps the indexes you gave it. -- A read from an index is eventually consistent. - A store can have up to 20 indexes. - To add or remove an index, change `indexes` and deploy. DynamoDB fills a new index from the items that exist. On a large table that takes minutes to hours. @@ -360,32 +394,6 @@ A `put` always validates against `schema`. A stored item can still differ from t `'coerce'` keeps stored fields that the schema does not declare, so a read followed by a `put` does not delete them. A default reaches the table only when you `put` the value back. -## Errors - -Match an error by name with `isBlocksError`. - -| Constant | `error.name` | Thrown when | -|----------|--------------|-------------| -| `KVStoreErrors.ConditionalCheckFailed` | `ConditionalCheckFailedException` | A condition on `put` or `delete` failed. Status 409 in the JSON-RPC error. The HTTP status is also 409 when the namespace sets `httpErrorStatus: true`. | -| `KVStoreErrors.ValidationFailed` | `ValidationFailedException` | A value fails the schema, disagrees with its key, has a `_bkv_` field, has a `__proto__` field, has an empty string in a key field or an indexed field, has a key or indexed field over DynamoDB's size limit (2,048 bytes for a partition key, 1,024 for a sort key), or nests lists or maps more than 32 levels deep. Also a bad expiry. | -| `KVStoreErrors.InvalidQuery` | `InvalidQueryException` | The call has the wrong shape: a bad key, a bad `where` (this includes a partition value or a sort value of the wrong type, a sort condition that does not exist, and a `between` with its bounds reversed), an unknown index, an `order` that is not `'asc'` or `'desc'`, a bad `limit`, a bad cursor, an `indexes` option that is not an object, `ifValueEquals` with an object, or a batch that repeats a key within one DynamoDB request (25 writes or 100 reads). | -| `KVStoreErrors.ItemTooLarge` | `ItemTooLargeException` | An item is larger than 400 KB. | -| `KVStoreErrors.BatchIncomplete` | `BatchIncompleteException` | A batch call left entries unprocessed. AWS runtime only. | - -```typescript -import { isBlocksError, KVStoreErrors } from 'aws-cdk-blocks'; - -try { - await cache.put('lock:report', 'worker-3', { ifNotExists: true }); -} catch (e: unknown) { - if (isBlocksError(e, KVStoreErrors.ConditionalCheckFailed)) { - // another worker holds the lock - } else { - throw e; - } -} -``` - ## Use a table that exists Pass the table name and the `key` that matches the table. The block does not create, change, or delete that table, and it ignores `protection`, `pointInTimeRecovery`, and `encryption` for it. @@ -416,6 +424,9 @@ You own the indexes and the TTL setting of that table. A string has no fields, so an index cannot read it. Do the move in three steps. ```typescript +import { isBlocksError } from '@aws-cdk-blocks/core'; +import { KVStoreErrors } from '@aws-cdk-blocks/bb-kv-store'; + const memberSchema = z.object({ name: z.string(), email: z.string() }); type Member = z.infer; @@ -437,8 +448,6 @@ for await (const { key, value, expiresAt } of members.scan()) { // new KVStore(scope, 'members', { schema: memberSchema, indexes: { byEmail: { partitionKey: 'email' } } }); ``` -In step 1, the code that reads the store must accept both shapes. - ### Copy a store to a new key Give the new store a new id, deploy, and copy. Then point the app at the new store and remove the old one. @@ -464,7 +473,7 @@ for await (const { value, expiresAt } of todos.scan()) { Release 0.4.0 or earlier keeps each item as `{ pk, value: , ttl? }`. This release keeps one attribute for each field, under another key attribute. DynamoDB cannot change the key of a table, so a `KVStore` of this release cannot take over the table of such a store. The deploy fails with `CloudFormation cannot update a stack when a custom-named resource requires replacing`, and the table keeps its items. -`LegacyKVStore` keeps the old table usable during the upgrade. It has the four data methods of release 0.4.0, `get`, `put`, `delete`, and `scan`, so the code that calls the old store runs as before. You migrate the data into a `KVStore` with a new id, in your own code, however is appropriate for your app. +`LegacyKVStore` keeps the old table usable during the upgrade. It has the four data methods of release 0.4.0, `get`, `put`, `delete`, and `scan`, so the code that calls the old store runs as before. You copy the data into a `KVStore` with a new id in your own code. `LegacyKVStore` is deprecated and frozen. Use it only for this upgrade. It gets no new features, and a later release can remove it. Use `KVStore` for new data. When the data is in the new store, remove the `LegacyKVStore` from your app. @@ -475,7 +484,7 @@ Release 0.4.0 or earlier keeps each item as `{ pk, value: , ttl? }`. | `scan(options?)` | `Results` | Read every entry of the old store, with its expiry. Takes `limit`, `cursor`, and `includeExpired`. | | `delete(key, conditions?)` | `Promise` | Remove a key from the old store. Takes the conditions `ifExists` and `ifValueEquals`. | -`put` validates the value with the `schema`. With both `put` conditions, the write goes ahead if the key is absent or its value matches. With both `delete` conditions, both must hold. Two things differ from release 0.4.0: `scan` takes `limit` and `cursor` and returns `expiresAt`, and `get` is a consistent read by default. +`put` validates the value with the `schema`. With both `put` conditions, the write goes ahead if the key is absent or its value matches. With both `delete` conditions, both must hold. ### What to know before you start @@ -503,13 +512,13 @@ const prefs = new KVStore(scope, 'prefs-v2'); The deploy creates the table of `prefs`. It does not change the table of `oldPrefs`, and the app's role keeps its access to that table. -`LegacyKVStore` takes the options that `KVStore` took in release 0.4.0: `ttl`, `removalPolicy`, `deletionProtection`, `pointInTimeRecovery`, `encryption`, `table`, `schema`, and `logger`. Keep each option that the old store had, with its value, also a `KVStore.fromExisting()` table and a `KVStore.fromKmsKey()` key. The block declares the old table from them, and a changed or missing option makes CloudFormation change that table. +`LegacyKVStore` takes the options that `KVStore` took in release 0.4.0: `ttl`, `removalPolicy`, `deletionProtection`, `pointInTimeRecovery`, `encryption`, `table`, `schema`, and `logger`. Pass exactly the options that the old store had, with their values, including a `KVStore.fromExisting()` table and a `KVStore.fromKmsKey()` key. The block declares the old table from them, and a changed or missing option makes CloudFormation change that table. ### Step 2. Migrate the data -Migrate the data however is appropriate for your app. The block does not copy the items, and it does not carry a write from one store to the other. +The block does not copy the items, and it does not carry a write from one store to the other. -Steps that are suitable for some migrations are as follows: +One way to migrate while the app stays live: 1. Deploy the app with reads that try the new store first and then the old one, and with writes that go to the new store. 2. Copy the items of the old store to the new store, in a handler or a job, for example an `AsyncJob`. @@ -521,7 +530,7 @@ A copy uses these tools: - **`put` of the `KVStore`** takes `expiresAt`, so a copied entry keeps its expiry. With `ifNotExists` it keeps a value that the new store has, so a copy is safe to run again. - **`AsyncJob`** runs a copy outside a request. Each run can copy one page, and submit the next run with the cursor. -These steps do not fit every app. While the app reads both stores, these limits apply: +While the app reads both stores, these limits apply: - A read that falls back to the old store returns the old value of a key that the new store does not have. This is the case after a delete, and after a value with an expiry expires. - A condition on the new store does not see the old store. A `put` with `ifNotExists` goes ahead for a key that only the old store has. @@ -534,25 +543,14 @@ When the data is in the new store, remove the `LegacyKVStore` line and the code ## Best practices -- Declare a `key` for anything that you list. -- Take the partition of user data from the signed-in user, not from the request. - Give a store that accepts user input a `schema`. -- Choose a partition field that spreads the data, such as `userId` or `tenantId`. -- Use a sort field for range queries, such as a timestamp. -- Declare indexes for the access patterns that you know when you create the store. -- Use `{ ifNotExists: true }` for a create that is safe to repeat. -- Use `ifFieldEquals` with a version field when several writers can change one item. -- Store one kind of entity in each store. -- Prefer `get` and `query` to `scan`. +- Take the partition of user data from the signed-in user, not from the request. ## Scaling and cost (AWS) -- **Billing.** On-demand. You pay for each read and each write, with no capacity to manage. See [DynamoDB pricing](https://aws.amazon.com/dynamodb/pricing/on-demand/). -- **Reads.** A consistent `get` uses twice the read capacity of an eventually consistent read. +- **Billing.** On-demand. You pay for each read and each write. See [DynamoDB pricing](https://aws.amazon.com/dynamodb/pricing/on-demand/). - **Indexes.** Each index adds a write for every item that it holds. - **Latency.** Single-digit milliseconds for a read or a write by key. -- **Limits.** 400 KB for each item, and 20 indexes for each store. -- **Replication.** DynamoDB keeps the data in three Availability Zones of the Region. ## Durability and security defaults @@ -583,14 +581,10 @@ const audit = new KVStore(scope, 'audit', { ## Local development -The mock keeps data on disk in `.cdk-blocks/local/data/{fullId}/`, so data stays across restarts of the dev server. To delete it, run `rm -rf .cdk-blocks/local/data .bb-data`. The data file is `store.json`, with a version field. +The mock keeps data on disk in `.bb-data/{fullId}/store.json`, so data stays across restarts of the dev server. To delete it, run `rm -rf .bb-data`. The mock applies the schema, the conditions, expiry, the 400 KB limit (measured the way DynamoDB measures it), DynamoDB's key and nesting limits, and the cursor checks as AWS does. It runs an index query in memory, so the result is correct and the speed differs from DynamoDB. The mock has no throughput limits and no IAM. -The mock handles a data file of an earlier release as follows: - -- It converts a `store.json` of an earlier `KVStore`, or a `data.json` of `DistributedTable`, when it first loads the file. -- It keeps a copy of the `store.json` from before the conversion as `store.json.bak`. -- It renames a file that it cannot read to a `.bak` file and logs a warning. It does not write over that file. +The mock converts a data file of an earlier release when it first loads the file, and keeps a copy of the `store.json` from before the conversion as `store.json.bak`. It renames a file that it cannot read to a `.bak` file and logs a warning. It does not write over that file. The mock keeps the store in the memory of the dev server, and reads `store.json` only when it constructs the store. Two processes on the same `.cdk-blocks/local/data` folder (two dev servers, or a script beside the dev server) do not see the writes of the other process, and can write over them. From 73737a7b0c9b575954cccc35016027cc20496035 Mon Sep 17 00:00:00 2001 From: Jairo Suarez Date: Wed, 18 Nov 2026 17:19:56 +0000 Subject: [PATCH 02/11] docs(bb-database): list the real error.name values; document npm run db in one section The errors table listed short names such as `QueryFailed`; it now lists each `DatabaseErrors` constant with the `error.name` a caller sees (`QueryFailedException`), and the four errors that are not for `catch` are a second table. `npm run db` was documented in two sections; it is now one `## Command line` section with a column for the kind of block each command applies to, and it says that a command with `--block` refuses `--name`. The options of `transaction()` and of the block and cluster are tables with a `Default` column. "Migrations" has one subsection per target (`dsql` cluster, `aurora` cluster, existing database), and the `dsql-lint` check is scoped to files for a `dsql` cluster. The steps to move or rename a block are their own section, and `## Local mode` is renamed `## Local development` and is the last section. --- packages/bb-database/README.md | 443 +++++++++++++++++++-------------- 1 file changed, 250 insertions(+), 193 deletions(-) diff --git a/packages/bb-database/README.md b/packages/bb-database/README.md index cb3bf1e870..5fc4f6689b 100644 --- a/packages/bb-database/README.md +++ b/packages/bb-database/README.md @@ -8,9 +8,16 @@ npm install @aws-cdk-blocks/bb-database **When to use:** relational data, joins, foreign keys, views, and multi-statement transactions, on a cluster with no VPC to manage. -**When not to use:** data that one key or one table pattern can serve. `KVStore` has no cluster to manage. +**When NOT to use:** data that one key or one table pattern can serve. `KVStore` has no cluster to manage. -**Which cluster:** the default `dsql` cluster for most apps. Triggers, PL/pgSQL, extensions, Row Level Security on raw SQL, and transactions over 3,000 rows need full PostgreSQL: put the block on an `aurora` cluster (`new DatabaseCluster(scope, 'main', { type: 'aurora' })`). It is created in seconds, scales to zero, needs no VPC, and runs the PostgreSQL migration files you already have. Its storage is encrypted with an AWS-owned key (the express configuration accepts no customer managed KMS key) and the first request after five idle minutes waits about 20 seconds for the cluster to resume unless `minCapacity` is at least `0.5`. +**Which cluster:** the default `dsql` cluster for most apps. Put the block on an `aurora` cluster (`new DatabaseCluster(scope, 'main', { type: 'aurora' })`) when it needs full PostgreSQL: + +- triggers, PL/pgSQL or extensions +- Row Level Security on raw SQL +- transactions over 3,000 rows +- PostgreSQL migration files that you already have + +An `aurora` cluster needs no VPC. Its storage is encrypted with an AWS-owned key (the express configuration accepts no customer managed KMS key). The first request after five idle minutes waits about 20 seconds for the cluster to resume unless `minCapacity` is at least `0.5`. The umbrella package `aws-cdk-blocks` exports this block: `import { Database, DatabaseCluster, sql } from 'aws-cdk-blocks'`. Every app made with `npm create @aws-cdk-blocks/blocks-app` depends on it, and the examples import from it. The `/kysely` and `/testing` entry points come from `@aws-cdk-blocks/bb-database`. Internals and local-versus-AWS differences are in [DESIGN.md](./DESIGN.md). @@ -19,22 +26,19 @@ The umbrella package `aws-cdk-blocks` exports this block: `import { Database, Da Define the blocks in `cdk-blocks/index.ts`: ```ts -import { ApiNamespace, Auth, Database, DatabaseCluster, Scope, sql } from 'aws-cdk-blocks'; +import { ApiNamespace, Scope } from '@aws-cdk-blocks/core'; +import { Auth } from '@aws-cdk-blocks/bb-auth'; +import { Database, sql } from '@aws-cdk-blocks/bb-database'; const scope = new Scope('app'); const auth = new Auth(scope, 'auth'); -export const authApi = auth.createApi(); // clients sign up with authApi.setAuthState({ action: 'signUp', username, password }), then confirm the emailed code +export const authApi = auth.createApi(); -// 1. Default. The block owns an Aurora DSQL cluster. +// The block owns an Aurora DSQL cluster. const shop = new Database(scope, 'shop'); - -// 2. Several blocks on one cluster. Each gets its own schema. -const shared = new DatabaseCluster(scope, 'shared', { type: 'dsql' }); -const audit = new Database(scope, 'audit', { cluster: shared }); -const search = new Database(scope, 'search', { cluster: shared }); ``` -> **⚠️ Data lives on the cluster. AWS CDK Blocks does not move it.** Treat the cluster a `Database` first deploys to as permanent. If you change its `cluster` option, or rename a `Database` or `DatabaseCluster` id, the block points at a different, empty cluster or schema. Nothing copies the rows. The old data stays where it was. A schema on a shared cluster is never dropped. An owned cluster that leaves the template is kept under `removalPolicy: 'retain'` (the production default). Under `'destroy'` (the sandbox default) it is **deleted in that same deploy**. To move data: 1. Add a new block on the target cluster. 2. Copy the rows. 3. Switch your handlers. 4. Remove the old block. See [Sharing a cluster](#sharing-a-cluster). +> **Data lives on the cluster. AWS CDK Blocks does not move it.** Treat the cluster a `Database` first deploys to as permanent. A changed `cluster` option, or a renamed `Database` or `DatabaseCluster` id, points the block at a different, empty cluster or schema. See [Moving or renaming a block](#moving-or-renaming-a-block). Create tables in a migration file, not in a handler. The deployed app can only read and write rows. Put the file at `cdk-blocks/migrations/shop/001_init.sql`, written in DSQL (see [Migrations](#migrations)): @@ -65,8 +69,6 @@ export const api = new ApiNamespace(scope, 'api', (context) => ({ })); ``` -The 404 thrown inside the transaction reaches the client as an `ApiError` with `status` 404. - `npm run dev` runs this with no AWS account. `npm run deploy` creates the cluster and applies the migration before the new code goes live. ## API @@ -77,7 +79,7 @@ new DatabaseCluster(scope: ScopeParent, id: string, options: DatabaseClusterOpti DatabaseCluster.fromExisting(options: ExistingClusterOptions): ExistingClusterRef ``` -Both option types are described under [Options](#options). A `DatabaseCluster` has no methods; it exists to be passed as a `Database`'s `cluster`. `DatabaseCluster.fromExisting()` returns a reference to a PostgreSQL database that already exists, for the same `cluster` option; see [Existing database](#existing-database). The methods below are on `Database`: +A `DatabaseCluster` has no methods; pass it as a `Database`'s `cluster`. `DatabaseCluster.fromExisting()` returns a reference to a PostgreSQL database that already exists, for the same `cluster` option; see [Existing database](#existing-database). The methods below are on `Database`: | Method | Returns | Description | |---|---|---| @@ -94,9 +96,69 @@ Both option types are described under [Options](#options). A `DatabaseCluster` h `bigint` values (identity columns, `count(*)`, `sum()` over integers) come back as JavaScript numbers, locally and on DSQL. A value outside the safe-integer range comes back as a `BigInt`. JSON cannot serialize a `BigInt`, so an `ApiNamespace` method that returns one fails at the RPC serializer. Cast the column in the query: `::text`, or `::float8` if you accept the precision loss. -### Typed results +**Runtime only.** Construct the block at module scope. Call the data methods only inside an `ApiNamespace` method, a `RawRoute` handler, a job handler, or a runtime script. Top-level code also runs during CDK synth, where every data method throws. Every `ApiNamespace` method is a public endpoint, so gate it with `await auth.requireAuth(context)` from an auth block. + +### Options + +`DatabaseClusterOptions`: + +| Option | Type | Default | Description | +|---|---|---|---| +| `type` | `'dsql' \| 'aurora'` | required | `dsql` is Aurora DSQL. `aurora` is Aurora PostgreSQL Serverless v2 created with the express configuration: all of PostgreSQL, no VPC, IAM authentication, scales to zero. | +| `removalPolicy` | `'retain' \| 'destroy' \| 'snapshot'` | the stack-wide `defaults` | What happens to the cluster when it leaves the stack. Under the stack-wide `defaults`, `production` retains with deletion protection on and `sandbox` destroys. `snapshot` (an `aurora` cluster only) takes a final snapshot before deleting it. | +| `minCapacity` | `number` | `0` | `aurora` only. The floor in Aurora Capacity Units, in 0.5 steps. At `0` the cluster pauses after five idle minutes and costs nothing while paused; the first connection afterwards takes about 20 seconds. The pause can come later than five minutes after the last request. `0.5` keeps it warm. | +| `maxCapacity` | `number` | `2` | `aurora` only. The ceiling in ACUs, 1 to 256 in 0.5 steps. Raised in place, without replacing the cluster. Raise it when the load needs more than the default. | +| `pointInTimeRecovery` | `boolean \| { retentionDays }` | the stack-wide `defaults.pointInTimeRecovery`: on in production, off in a sandbox | `aurora` only. Automated backups, which are Aurora's point-in-time recovery window: `true` keeps 15 days, `{ retentionDays: n }` pins the window (1 to 35), `false` keeps the one day the service always keeps. | + +`DatabaseOptions`: + +| Option | Type | Default | Description | +|---|---|---|---| +| `cluster` | `DatabaseCluster`, `LegacyDatabaseCluster` or the result of `DatabaseCluster.fromExisting()` | an owned `dsql` cluster | The cluster to run on. Use `LegacyDatabaseCluster` only to [upgrade from `@aws-blocks/bb-data`](#upgrade-from-aws-blocksbb-data). | +| `migrationsPath` | `string` | `./cdk-blocks/migrations/{id}` | Directory of `.sql` files, relative to the project root. The default may be missing; an explicit path must exist. | +| `schemaName` | `string` | `public` when the block owns its cluster, otherwise the block id as a PostgreSQL identifier (lower-cased, `_` for other characters) | The PostgreSQL schema for this block's tables. Two blocks on one cluster cannot share a schema. | +| `removalPolicy` | `'retain' \| 'destroy'` | the stack-wide `defaults` | Only when `cluster` is omitted. With a shared cluster, set it on the `DatabaseCluster`. | +| `logger` | `ChildLogger` | a `Logger` at error level | Logger for internal operations. | + +`Database` and `DatabaseCluster` ids are unique per app. A second block with the same id is an error at construction. The ids of two blocks that each own a cluster must also differ in a letter or a digit. Ids that differ only in punctuation, such as `db-a` and `dba` in one scope, are an error at synth. + +The options of `DatabaseCluster.fromExisting()` are under [Existing database](#existing-database), and those of `transaction()` under [Transactions](#transactions). + +## Errors -A query's row type can come from a value instead of a type argument. Pass `{ schema }` with any [Standard Schema](https://standardschema.dev) (Zod, Valibot, ArkType, or your own). The method validates every row and returns the schema's output type. A row that does not match throws `DatabaseErrors.ResultValidationFailed`. The client sees the row index and the column name, never the values. The same option is on the `tx` inside `transaction()`. +Query and transaction failures carry a `DatabaseErrors` name. Match them with `isBlocksError(e, DatabaseErrors.X)` on the server or the client. Only the name and a message free of row values cross the wire; the driver error stays on the server. + +```ts +import { isBlocksError } from '@aws-cdk-blocks/core'; +import { DatabaseErrors } from '@aws-cdk-blocks/bb-database'; +``` + +| Constant | `error.name` | Thrown when | Retried automatically | +|---|---|---|---| +| `DatabaseErrors.ConnectionFailed` | `ConnectionFailedException` | The connection to the cluster failed or was lost (SQLSTATE class `08`), or was never made: the address did not answer, the server certificate was not accepted, or the login was refused. The function's log names which | A lost connection, for a single `query` or `execute`: once, on a fresh connection. Inside a transaction, and for a connection that was never made: no | +| `DatabaseErrors.TransactionFailed` | `TransactionFailedException` | The callback threw an error that is not an `ApiError`, a Blocks error or a database error, or a statement reached the transaction after it ended (a promise the callback did not await) | No | +| `DatabaseErrors.UniqueConstraintViolation` | `UniqueConstraintViolationException` | SQLSTATE `23505` (HTTP 409) | No | +| `DatabaseErrors.NotNullViolation` | `NotNullViolationException` | A required value is missing: SQLSTATE `23502` (HTTP 400) | No | +| `DatabaseErrors.CheckViolation` | `CheckViolationException` | A value breaks a `CHECK` constraint: SQLSTATE `23514` (HTTP 400) | No | +| `DatabaseErrors.ForeignKeyViolation` | `ForeignKeyViolationException` | The row refers to a row that does not exist, or other rows still refer to the row being deleted: SQLSTATE `23503` (HTTP 409) | No | +| `DatabaseErrors.PermissionDenied` | `PermissionDeniedException` | A statement on a database from `asUser()` was refused: a Row Level Security policy rejected the row (SQLSTATE `42501`, HTTP 403) | No | +| `DatabaseErrors.SerializationFailure` | `SerializationFailureException` | SQLSTATE `40001`, usually at commit (HTTP 409, retriable) | A single `query` or `execute`: three times. A `transaction()` callback: only with `retryOnConflict: true` (see [Transactions](#transactions)) | +| `DatabaseErrors.TransactionRowLimitExceeded` | `TransactionRowLimitExceededException` | More than 3,000 rows changed (cascades included) or more than 10 MiB written in one transaction, locally and on DSQL (SQLSTATE `54000`) | No; split the work | +| `DatabaseErrors.ResultValidationFailed` | `ResultValidationFailedException` | A row did not match the `schema` passed to `query()` or `queryOne()`. The message, which reaches the client, names the row index and the first issue's path; the library's issue messages stay on the server-side `cause` | No; fix the schema or the query | +| `DatabaseErrors.QueryFailed` | `QueryFailedException` | Any other SQL error | No | + +These errors are not for `catch`. Fix the cause. + +| `error.name` | Cause | +|---|---| +| `DatabaseConfigurationError` | A setup mistake: a duplicate id, a missing `migrationsPath`. | +| `MigrationValidationError` | A migration file finding: a `dsql-lint` finding, or a DSQL-only form in a file for an `aurora` cluster. | +| `DsqlValidationError` | A `dsql-lint` finding in a handler's statement. | +| `MigrationFailedException` | A migration failure. | + +## Typed results + +Pass `{ schema }` with any [Standard Schema](https://standardschema.dev) (Zod, Valibot, ArkType, or your own). The method validates every row and returns the schema's output type. A row that does not match throws `DatabaseErrors.ResultValidationFailed`. The same option is on the `tx` inside `transaction()`. ```ts import { z } from 'zod'; @@ -112,54 +174,53 @@ const one = await shop.queryOne(sql`SELECT id, email FROM customers WHERE id = $ `query(sql)` with a type argument still works. The argument is an unchecked assertion, so prefer `schema` where the shape matters. -**Runtime only.** Construct the block at module scope. Call the data methods only inside an `ApiNamespace` method, a `RawRoute` handler, a job handler, or a runtime script. Top-level code also runs during CDK synth, where every data method throws. Every `ApiNamespace` method is a public endpoint, so gate it with `await auth.requireAuth(context)` from an auth block. +## Sharing a cluster -## Options +```ts +const shared = new DatabaseCluster(scope, 'shared', { type: 'dsql' }); +const audit = new Database(scope, 'audit', { cluster: shared }); +const search = new Database(scope, 'search', { cluster: shared }); -An option goes on the cluster if every block on that cluster must share it, and on the block otherwise. +// An `aurora` cluster: PostgreSQL migrations, triggers, large transactions. +const main = new DatabaseCluster(scope, 'main', { type: 'aurora', minCapacity: 0.5 }); +const reports = new Database(scope, 'reports', { cluster: main }); +``` -Cluster options: +Each `Database` on the cluster gets a schema named after its id, with its own migrations and tables. An unqualified table name resolves to the block's schema: ``audit.query(sql`SELECT * FROM events`)`` reads `audit.events`, and the same text on `search` reads `search.events`. Locally the cluster is one PGlite with the same schemas. -| Option | Type | Description | -|---|---|---| -| `type` | `'dsql' \| 'aurora'` | Required. `dsql` is Aurora DSQL. `aurora` is Aurora PostgreSQL Serverless v2 created with the express configuration: all of PostgreSQL, no VPC, IAM authentication, scales to zero. | -| `removalPolicy` | `'retain' \| 'destroy' \| 'snapshot'` | What happens to the cluster when it leaves the stack. When omitted, the stack-wide `defaults` apply: `production` retains with deletion protection on, `sandbox` destroys. `snapshot` (an `aurora` cluster only) takes a final snapshot before deleting it. Data stays on the cluster when a block is renamed or moved; see the callout in [Quick start](#quick-start). | -| `minCapacity` | `number` | `aurora` only. The floor in Aurora Capacity Units, in 0.5 steps. Default `0`: the cluster pauses after five idle minutes and costs nothing while paused; the first connection afterwards takes about 20 seconds. `0.5` keeps it warm. | -| `maxCapacity` | `number` | `aurora` only. The ceiling in ACUs, 1 to 256 in 0.5 steps. Default `2`. Raised in place, without replacing the cluster. The ceiling bounds throughput: a cluster under sustained load stays at the ceiling and does not go faster, so raise `maxCapacity` when the load needs more than the default. | -| `pointInTimeRecovery` | `boolean \| { retentionDays }` | `aurora` only. Automated backups, which are Aurora's point-in-time recovery window: `true` keeps 15 days, `{ retentionDays: n }` pins the window (1 to 35), `false` keeps the one day the service always keeps. Defaults to the stack-wide `defaults.pointInTimeRecovery`: on in production, off in a sandbox. | +**Isolation is by namespace, not by permission.** Both blocks connect as one role that has DML on every schema on the cluster. Qualified table names and joins across schemas work from any block on the cluster. A block that must not see another block's data belongs on its own cluster. -Block options: +Share a cluster for: -| Option | Type | Description | -|---|---|---| -| `cluster` | `DatabaseCluster` or the result of `DatabaseCluster.fromExisting()` | The cluster to run on. Omit it and the block owns a `dsql` cluster. | -| `migrationsPath` | `string` | Directory of `.sql` files, relative to the project root. Defaults to `./cdk-blocks/migrations/{id}`. The default may be missing; an explicit path must exist. | -| `schemaName` | `string` | The PostgreSQL schema for this block's tables. `public` when the block owns its cluster, otherwise the block id as a PostgreSQL identifier (lower-cased, `_` for other characters). Two blocks on one cluster cannot share a schema. | -| `removalPolicy` | `'retain' \| 'destroy'` | Only when `cluster` is omitted. With a shared cluster, set it on the `DatabaseCluster`. | -| `logger` | `ChildLogger` | Logger for internal operations. Defaults to a `Logger` at error level. | +- one migration pipeline instead of one per block +- queries across the blocks' tables +- one [cluster quota](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/CHAP_quotas.html) slot instead of one per block -`Database` and `DatabaseCluster` ids are unique per app. A second block with the same id is an error at construction. The ids of two blocks that each own a cluster must also differ in a letter or a digit. Ids that differ only in punctuation, such as `db-a` and `dba` in one scope, are an error at synth. +Keep separate clusters when the blocks have different lifecycles: -## Sharing a cluster +- The removal policy is set on the cluster. +- Blocks on one cluster migrate one at a time. +- A block cannot move to another cluster later without you copying its data. -```ts -const shared = new DatabaseCluster(scope, 'shared', { type: 'dsql' }); -const audit = new Database(scope, 'audit', { cluster: shared }); -const search = new Database(scope, 'search', { cluster: shared }); -``` +## Moving or renaming a block -The `DatabaseCluster` provisions the cluster, of either type: +The block points at a different, empty cluster or schema when you: -```ts -const main = new DatabaseCluster(scope, 'main', { type: 'aurora', minCapacity: 0.5 }); -const reports = new Database(scope, 'reports', { cluster: main }); // PostgreSQL migrations, triggers, large transactions -``` +- change the `cluster` option of a `Database` +- rename a `Database` or `DatabaseCluster` id + +Nothing copies the rows. The old data stays where it was: -Each `Database` on it gets a schema named after its id, with its own migrations and tables. An unqualified table name resolves to the block's schema: ``audit.query(sql`SELECT * FROM events`)`` reads `audit.events`, and the same text on `search` reads `search.events`. Locally the cluster is one PGlite with the same schemas. +- A schema on a shared cluster is never dropped. +- An owned cluster that leaves the template is kept under `removalPolicy: 'retain'` (the production default). +- Under `'destroy'` (the sandbox default) the cluster is deleted in that same deploy. -**Isolation is by namespace, not by permission.** Both blocks connect as one role that has DML on every schema on the cluster. Qualified table names and joins across schemas work from any block on the cluster. The schema is a naming convention that keeps two blocks' tables apart. It is not a boundary between tenants or trust levels. A block that must not see another block's data belongs on its own cluster. +To move data: -**Why share.** For one migration pipeline instead of one per block, for queries across the blocks' tables, or to use one [cluster quota](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/CHAP_quotas.html) slot instead of one per block. Keep separate clusters when the blocks have different lifecycles: the removal policy is set on the cluster, blocks on one cluster migrate one at a time, and a block cannot move to another cluster later without you copying its data. +1. Add a new block on the target cluster. +2. Copy the rows. +3. Switch your handlers. +4. Remove the old block. ## Existing database @@ -187,34 +248,15 @@ const open = await db.query<{ id: string; title: string }>(sql`SELECT id, title | `dataApi` | `{ clusterArn, secretArn, database }` | An Aurora PostgreSQL cluster that the block reaches through the RDS Data API. See [An Aurora cluster through the Data API](#an-aurora-cluster-through-the-data-api). | | `ca` | `string` | The certificate authority that signed the server certificate, as PEM text. Supabase uses its own authority, so it needs one. Without `ca`, Node's trust store applies. | -**The connection string is never written in code.** It is a secret: store it with the command below, or in your own `AppSetting` or `Secret`. +Do not write the connection string in code. It is a secret: store it with `npm run db connect`, or in your own `AppSetting` or `Secret`. **The server certificate is always verified.** No option turns verification off, and a connection string that carries a TLS parameter (`sslmode`, `ssl`, `sslrootcert`, `sslcert`, `sslkey`) is refused, because the driver would let it replace the block's settings. -### The command line - -```sh -npm run db -- connect --ca ./prod-ca-2021.crt # local: asks for the string, checks, stores -npm run db -- connect --stage production --ca ./prod-ca-2021.crt # the same for a deployed stage -npm run db migrate # apply ./migrations to the local database -npm run db types # write cdk-blocks/database.types.ts -npm run db -- status --stage production # applied and pending files -npm run db -- migrate --mark-applied 000_baseline.sql # record a file as applied, without running it -``` - -| Command | What it does | -|---|---| -| `connect [--name ] [--stage sandbox\|production] [--ca ] [--value-stdin] [--check-only]` | Reads the connection string from a hidden prompt, or from stdin with `--value-stdin`. Connects with the certificate verified and reports the server version, what the role can do (superuser, `BYPASSRLS`, the roles it may switch to), the tables whose policies call `auth.uid()`, `auth.email()` or `auth.role()`, and for a Supabase host which endpoint it is. Then stores the string: for local mode by default, as the SSM SecureString of the stage with `--stage`. With `--ca` it also writes the certificate module of the connection: `cdk-blocks/database.ca.ts`, or `cdk-blocks/database..ca.ts` for a name other than `db-url`. Every later command for that connection, and a later `connect` without `--ca`, verifies the server with it. `--name` defaults to `db-url`. The lines it prints for your backend file name `./migrations` as `migrationsPath`, the directory that `migrate` applies, so a deploy runs the same files. | -| `migrate [dir] [--types \| --no-types]` | Applies the pending files of `dir` (default `./migrations`) to the database of the local value, with the code a deploy uses, then writes the types file. Shows the host and asks first; `--yes` skips the question. It does not take `--stage`: the deploy migrates a stage. | -| `migrate [dir] --mark-applied [--stage sandbox\|production]` | Records `` as applied without running it, on the database of the local value or of a stage. For a file that describes what the database already has; see [Starting from the schema you have](#starting-from-the-schema-you-have). Repeat the option for more files. Shows the host and asks first. | -| `types [--out ]` | Writes one `Tables` interface for Kysely from the live schema (default `cdk-blocks/database.types.ts`). The file needs no import: its `Generated` type is structurally Kysely's. | -| `status [dir] [--stage sandbox\|production]` | Lists the applied and the pending files. | - -`npm run db` runs the block's own command line (the `bb-database` binary of this package) from the project root, so `@aws-cdk-blocks/bb-database` must be installed in the app. Every command takes `--name` and `--schema`, and the `--yes` and `--no-input` of the task runner. To request JSON explicitly, pass `--output json` through both npm and the runner: `npm run -s db -- status -- --output json`. Use `-s` to omit npm’s banner. The exit code is 0 for success, 1 for a failure and 2 for a usage error. The connection string is never an argument and never printed. +Store the connection string with `npm run db -- connect`; see [Command line](#command-line). -### What to know +### Running on an existing database -- **Use the transaction pooler string for a deployed stage.** A Lambda function outside a VPC has no IPv6 route and no fixed address, so it cannot reach an IPv6-only host or pass an IP allow-list. On Supabase that means the shared pooler, port 6543. Every function instance holds its own connections, and only a transaction pooler shares them. +- **Use the transaction pooler string for a deployed stage.** On Supabase that means the shared pooler, port 6543. A host with no IPv4 address, or one behind an IP allow-list, is unreachable from the deployed function. Every function instance holds its own connections, and only a transaction pooler shares them. - **The block connects as the role in the connection string.** What that role may do is decided by your database, not by the block. A role that owns the tables, a superuser and a role with `BYPASSRLS` are not filtered by Row Level Security policies: a statement on the block itself reads every row. Use [`asRole()`](#row-level-security) to run as a role that policies apply to, or connect as a role with only the grants the app needs. - **Local mode is the real database.** `npm run dev` connects to the database of the local value, with the same certificate check. It never runs migration files; `npm run db migrate` and a deploy do. Use a development project locally, not production. - **A schema other than `public` needs a session setting** (`search_path`), which a transaction pooler does not keep. Through one, write schema-qualified names. @@ -222,7 +264,7 @@ npm run db -- migrate --mark-applied 000_baseline.sql # record a fi ### Starting from the schema you have -Migration files describe changes from now on. A database that was built before them, in a dashboard or by another tool, has tables that no file creates, so a new database made from the files alone does not have those tables. Put the schema in the first file, and record that file as applied where the schema already exists. +If the database already has tables that no migration file creates, a new database made from the files alone does not have those tables. Put the schema in the first file, and record that file as applied where the schema already exists. 1. Write the schema of `public` to the first file. With `pg_dump`, at the server's major version or later, on a direct or session-mode connection string (not a transaction pooler): @@ -233,7 +275,7 @@ Migration files describe changes from now on. A database that was built before t `--exclude-table` leaves out the block's own two tables. The `grep` removes `CREATE SCHEMA public;`, which fails because every database has that schema; without `grep`, delete that line in an editor. Take the dump while the directory has no files that are already applied: the dump contains their changes. -2. Remove what your provider owns. A hosted database has roles and objects that the provider made, and a new database of that provider has them too, or refuses them. +2. Remove what your provider owns. | Database | Remove from the file | |---|---| @@ -323,11 +365,7 @@ An app that deployed `Database` of `@aws-blocks/bb-data` has an Aurora PostgreSQ ## Migrations -A `Database` on an `aurora` cluster runs PostgreSQL: write its migrations as you would for any PostgreSQL 17, nothing is rewritten (except [`${app_role}`](#the-app-role-in-a-migration)), and each file runs in one transaction, so it applies entirely or not at all; on AWS a file must finish within the migration function's ten-minute invocation (see [How migrations deploy](#how-migrations-deploy)). The only check is for the two DSQL-only forms, `ASYNC` and `sys.wait_for_job()`; a file that carries them is stopped at `npm run dev` and at `cdk synth` with a message that names the file and what to change. The rest of this section is about the default `dsql` cluster. A statement PostgreSQL refuses inside a transaction block (`CREATE INDEX CONCURRENTLY`, `VACUUM`, `ALTER SYSTEM`, `CREATE DATABASE`) stops the file at construction with a message that names it: drop `CONCURRENTLY`, and keep the rest out of migrations. - -A `Database` on Aurora DSQL needs its migrations written in DSQL, as the AWS documentation shows them: [DDL and distributed transactions](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/working-with-ddl.html), [`CREATE TABLE`](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/create-table-syntax-support.html), [`ALTER TABLE`](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/alter-table-syntax-support.html), [`CREATE SEQUENCE`](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/create-sequence-syntax-support.html) and [Asynchronous indexes](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/working-with-create-index-async.html). What is in the file is what runs on the cluster. Every file is checked with [`dsql-lint`](https://github.com/awslabs/aurora-dsql-tools/tree/main/dsql-lint) before anything runs (see [What is rejected](#what-is-rejected)). - -Each block has one directory of `.sql` files, `./cdk-blocks/migrations/{id}` unless `migrationsPath` says otherwise. Block ids are unique per app because they name this directory and, on a shared cluster, the block's schema. Files run in name order, once each: +Each block has one directory of `.sql` files, `./cdk-blocks/migrations/{id}` unless `migrationsPath` says otherwise. Files run in name order, once each: ``` cdk-blocks/migrations/ @@ -338,30 +376,32 @@ cdk-blocks/migrations/ 001_events.sql ``` -#### The app role in a migration +Write the files for the cluster's engine. The block runs them unchanged. -A file names the role that the app's statements run as with `${app_role}`. Before the file runs, every occurrence is replaced with that role's quoted name, so one file works in every place it runs: +### On a `dsql` cluster -| Where the file runs | `${app_role}` becomes | -|---|---| -| A cluster the block provisions, on AWS | `"blocks_app_{cluster}"`, the role the migration function creates for the cluster before any file runs (see [Access through the AWS SDK](#access-through-the-aws-sdk)) | -| Local mode (`npm run dev`, `npm run db -- types --block`) | `"blocks_app_local"` | -| An [existing database](#existing-database) (a deploy, `npm run db migrate`) | The role of the connection string | +Write the migrations in DSQL, as the AWS documentation shows them: -```sql --- cdk-blocks/migrations/app/003_roles.sql -GRANT authenticated TO ${app_role} WITH INHERIT FALSE, SET TRUE; -``` +- [DDL and distributed transactions](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/working-with-ddl.html) +- [`CREATE TABLE`](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/create-table-syntax-support.html) +- [`ALTER TABLE`](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/alter-table-syntax-support.html) +- [`CREATE SEQUENCE`](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/create-sequence-syntax-support.html) +- [Asynchronous indexes](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/working-with-create-index-async.html) -The replacement is plain text, in string literals and comments too. Nothing else in a file is replaced, and the file's hash is of the text as you wrote it. +Every file is checked with [`dsql-lint`](https://github.com/awslabs/aurora-dsql-tools/tree/main/dsql-lint) before anything runs (see [What is rejected](#what-is-rejected)). ### Coming from PostgreSQL Most DDL is the same on DSQL. Four spellings differ: `SERIAL`, a plain `CREATE INDEX`, an `ADD CONSTRAINT` without `NOT VALID`, and a sequence without a cache. The first `npm run dev` stops on each and prints the DSQL form (see [What is rejected](#what-is-rejected)). -To convert an existing PostgreSQL or `pg_dump` file once, run `npx dsql-lint --fix old.sql -o 001_init.sql` and review the output. The binary is installed with the block. If `npx` cannot find it, run `node_modules/@aws/dsql-lint/bin/dsql-lint`. Exit code 3 means it fixed everything but changed a meaning, such as an index becoming asynchronous. It writes `CACHE 1` (see below), and it adds `NOT VALID` to constraints without the `ALTER TABLE ASYNC … VALIDATE CONSTRAINT` that validates existing rows; add that statement yourself. +To convert an existing PostgreSQL or `pg_dump` file once: -**Identity columns and sequences** need a cache. `CACHE 65536` gives each session a local block of values: fast inserts, unique values, but gaps and out-of-order values. `CACHE 1` keeps values close to sequential at one round trip per value. The lint error repeats this trade-off when a cache is missing. +1. Run `npx dsql-lint --fix old.sql -o 001_init.sql`. The binary is installed with the block. If `npx` cannot find it, run `node_modules/@aws/dsql-lint/bin/dsql-lint`. +2. Review the output. Exit code 3 means it fixed everything but changed a meaning, such as an index becoming asynchronous. +3. Choose the cache of each identity column and sequence. The command writes `CACHE 1` (see below). +4. For each constraint that it marked `NOT VALID`, add the `ALTER TABLE ASYNC … VALIDATE CONSTRAINT` that validates existing rows. + +**Identity columns and sequences** need a cache. `CACHE 65536` gives each session a local block of values: fast inserts, unique values, but gaps and out-of-order values. `CACHE 1` keeps values close to sequential at one round trip per value. **Changes DSQL cannot express** are adding a column with a `DEFAULT` or `NOT NULL`, and `ALTER COLUMN … SET NOT NULL` or `… TYPE`. To add a constrained column: @@ -371,13 +411,15 @@ To convert an existing PostgreSQL or `pg_dump` file once, run `npx dsql-lint --f To change a column's type: add a new column, copy the values in batches, switch your queries, then drop the old column. -You do not need to write `sys.wait_for_job(…)` after an `ASYNC` statement; the block waits for the job. A wait copied from the AWS examples runs anyway (see [Local mode](#local-mode)). +You do not need to write `sys.wait_for_job(…)` after an `ASYNC` statement; the block waits for the job. A wait copied from the AWS examples runs anyway (see [Local development](#local-development)). On DSQL the rows an `ON DELETE CASCADE` foreign key deletes count toward the 3,000-row transaction limit. A delete that fans out past it fails whole. Prefer `NO ACTION` or `RESTRICT` for unbounded parent-child relationships. ### What is rejected -Every file is checked with [`dsql-lint`](https://github.com/awslabs/aurora-dsql-tools/tree/main/dsql-lint) at `npm run dev` and at `cdk synth`, before any deploy, for what DSQL cannot run (triggers, extensions, policies, `TRUNCATE`, array columns) and for the PostgreSQL spellings of DSQL forms. Nothing is rewritten for you. The error names the file, the rule, dsql-lint's suggestion and the DSQL documentation page: +Every file for a `dsql` cluster is checked with [`dsql-lint`](https://github.com/awslabs/aurora-dsql-tools/tree/main/dsql-lint) at `npm run dev` and at `cdk synth`, before any deploy, for what DSQL cannot run (triggers, extensions, policies, `TRUNCATE`, array columns) and for the PostgreSQL spellings of DSQL forms. + +The error names the file, the rule, dsql-lint's suggestion and the DSQL documentation page: ``` MigrationValidationError: Migration validation failed for Aurora DSQL (cluster kind 'dsql'): @@ -387,6 +429,13 @@ MigrationValidationError: Migration validation failed for Aurora DSQL (cluster k `dsql-lint` is a native binary installed as an optional dependency of `@aws/dsql-lint`. If your package manager skipped optional dependencies, run `npm install @aws/dsql-lint --include=optional`, or point `DSQL_LINT_PATH` at a build. +### On an `aurora` cluster + +- Write the migrations as you would for any PostgreSQL 17. +- Each file runs in one transaction, so it applies entirely or not at all. +- The only check is for the two DSQL-only forms, `ASYNC` and `sys.wait_for_job()`. A file that carries them is stopped at `npm run dev` and at `cdk synth` with a message that names the file and what to change. +- A statement PostgreSQL refuses inside a transaction block (`CREATE INDEX CONCURRENTLY`, `VACUUM`, `ALTER SYSTEM`, `CREATE DATABASE`) stops the file at construction with a message that names it. Drop `CONCURRENTLY`, and keep the rest out of migrations. + ### How migrations deploy Locally, a block applies its pending files before its first query. On AWS they run during `cdk deploy`, before any function on the stack is updated, so new code never runs against the old schema. Blocks on one cluster migrate one at a time. @@ -397,11 +446,26 @@ On an `aurora` cluster the file is one transaction, so nothing from it was appli On a `dsql` cluster the file resumes where it stopped. A failed index build or constraint validation usually means the data does not satisfy it: fix the rows, then deploy again. Do not edit a `dsql` file that has partly run. The next deploy detects the edit, refuses the file and names it. Put the change in a new file instead. +### Migrations on an existing database -On an existing database ([Existing database](#existing-database)) the files run as written: the block does not check them, because they may be older than the block, and PostgreSQL reports what it refuses. Each pending file is one transaction, and the file is recorded in that same transaction, so two runs at the same time cannot both apply it: one commits, and the other is rolled back and says so. The server ends a transaction that sits idle for a minute, so a run that stops in the middle of a file does not keep its locks. A deploy runs the files in a function outside any VPC, with the stored connection string; a failure stops the deploy and names the file, the statement, the SQLSTATE and the server's message. A file made by `pg_dump` runs too: its session settings are reset before the commit, and its `SET transaction_timeout` line is skipped on a server older than PostgreSQL 17. A file's own `SET` of a limit that the run applies is also skipped, so that the limit holds for the whole file: `idle_in_transaction_session_timeout` in every run, and `statement_timeout` and `transaction_timeout` in a deploy. +On an [existing database](#existing-database): -An app that used `@aws-blocks/bb-data` with `fromExisting()` keeps its files and its `_migrations` table: point `migrationsPath` at the same directory (`./migrations`), and no file runs a second time. Its connection string is already in SSM as `/-db-url`, which is what `name: 'db-url'` reads. A new stage needs `npm run db -- connect --stage ` once: `sandbox` and `deploy` do not copy a `*_DB_URL` variable from the env file any more. -### Types and status from the command line +- The files run as written. The block does not check them, and PostgreSQL reports what it refuses. +- Each pending file is one transaction, and the file is recorded in that same transaction. Of two runs at the same time, one commits, and the other is rolled back and says so. +- The server ends a transaction that sits idle for a minute, so a run that stops in the middle of a file does not keep its locks. +- A deploy runs the files in a function outside any VPC, with the stored connection string. A failure stops the deploy and names the file, the statement, the SQLSTATE and the server's message. +- A file made by `pg_dump` runs too: its session settings are reset before the commit, and its `SET transaction_timeout` line is skipped on a server older than PostgreSQL 17. +- A file's own `SET` of a limit that the run applies is skipped, so that the limit holds for the whole file: `idle_in_transaction_session_timeout` in every run, and `statement_timeout` and `transaction_timeout` in a deploy. + +An app that used `@aws-blocks/bb-data` with `fromExisting()` in an earlier AWS CDK Blocks release: + +- keeps its migration files and its `_migrations` table. Point `migrationsPath` at the same directory (`./migrations`), and no file runs a second time. +- has its connection string in SSM as `/-db-url`, which is what `name: 'db-url'` reads. +- needs `npm run db -- connect --stage ` once for a new stage: `sandbox` and `deploy` do not copy a `*_DB_URL` variable from the env file. + +## Command line + +`npm run db` runs the block's own command line (the `bb-database` binary of this package) from the project root, so `@aws-cdk-blocks/bb-database` must be installed in the app. For a block that provisions its cluster, name the block. These two commands need no AWS account and no connection string. @@ -412,18 +476,66 @@ npm run db -- status --block shop # applied and npm run db -- status --block orders --cluster main # a block on the DatabaseCluster 'main' ``` -| Command | What it does | -|---|---| -| `types [dir] --block [--type dsql\|aurora] [--cluster ] [--schema ] [--out ]` | Writes one `Tables` interface for Kysely from the block's migration files (`cdk-blocks/migrations/`, or `dir` for a block with `migrationsPath`). The files are applied to a new local database in a temporary directory, with the code `npm run dev` runs them with, so the result does not depend on `.cdk-blocks/local/data/` and a running dev server is not touched. Pass `--type aurora` for a block on an `aurora` cluster. Run it again after you add a file. | -| `status [dir] --block [--cluster ] [--schema ]` | Lists the applied and the pending files in the block's local database under `.cdk-blocks/local/data/`. For a block on a `DatabaseCluster`, pass the cluster's id as `--cluster`. It reads a copy of the database, so it is safe while `npm run dev` runs; it then shows what the dev server had written to disk. It does not read a deployed stage. | +For an [existing database](#existing-database) with a stored connection string, use the commands below. The CLI does not support a `dataApi` source; deploy to apply its migrations. + +```sh +npm run db -- connect --ca ./prod-ca-2021.crt # local: asks for the string, checks, stores +npm run db -- connect --stage production --ca ./prod-ca-2021.crt # the same for a deployed stage +npm run db migrate # apply ./migrations to the local database +npm run db types # write cdk-blocks/database.types.ts +npm run db -- status --stage production # applied and pending files +npm run db -- migrate --mark-applied 000_baseline.sql # record a file as applied, without running it +``` + +| Command | Block | What it does | +|---|---|---| +| `types [dir] --block [--type dsql\|aurora] [--cluster ] [--schema ] [--out ]` | provisions its cluster | Writes one `Tables` interface for Kysely from the block's migration files (`cdk-blocks/migrations/`, or `dir` for a block with `migrationsPath`). It does not read `.bb-data/` and does not touch a running dev server. Pass `--type aurora` for a block on an `aurora` cluster. Run it again after you add a file. | +| `status [dir] --block [--cluster ] [--schema ]` | provisions its cluster | Lists the applied and the pending files in the block's local database under `.bb-data/`. For a block on a `DatabaseCluster`, pass the cluster's id as `--cluster`. It reads a copy of the database, so it is safe while `npm run dev` runs; it then shows what the dev server had written to disk. It does not read a deployed stage. | +| `connect [--name ] [--stage sandbox\|production] [--ca ] [--value-stdin] [--check-only]` | existing database | Checks the database and stores its connection string. See [`connect`](#connect). | +| `migrate [dir] [--types \| --no-types]` | existing database | Applies the pending files of `dir` (default `./migrations`) to the database of the local value, with the code a deploy uses, then writes the types file. Shows the host and asks first; `--yes` skips the question. It does not take `--stage`: the deploy migrates a stage. | +| `migrate [dir] --mark-applied [--stage sandbox\|production]` | existing database | Records `` as applied without running it, on the database of the local value or of a stage. For a file that describes what the database already has; see [Starting from the schema you have](#starting-from-the-schema-you-have). Repeat the option for more files. Shows the host and asks first. | +| `types [--out ]` | existing database | Writes one `Tables` interface for Kysely from the live schema (default `cdk-blocks/database.types.ts`). The file needs no import: its `Generated` type is structurally Kysely's. | +| `status [dir] [--stage sandbox\|production]` | existing database | Lists the applied and the pending files. | + +A block that provisions its cluster applies its files itself, so `connect` and `migrate` are only for an existing database. + +Every command: -`connect` and `migrate` are for an [existing database](#existing-database): a block that provisions its cluster applies its files itself. +- takes `--schema`, and the `--yes` and `--no-input` of the task runner. The commands for an existing database also take `--name`; a command with `--block` refuses it. +- prints JSON with `--output json`, passed through both npm and the runner: `npm run -s db -- status -- --output json`. `-s` omits npm’s banner. +- exits with 0 for success, 1 for a failure and 2 for a usage error. +- never takes the connection string as an argument and never prints it. + +### `connect` + +`connect`: + +- reads the connection string from a hidden prompt, or from stdin with `--value-stdin`. +- connects with the certificate verified and reports: + - the server version + - what the role can do (superuser, `BYPASSRLS`, the roles it may switch to) + - the tables whose policies call `auth.uid()`, `auth.email()` or `auth.role()` + - for a Supabase host, which endpoint it is +- stores the string: for local mode by default, as the SSM SecureString of the stage with `--stage`. +- with `--ca`, also writes the certificate module of the connection: `cdk-blocks/database.ca.ts`, or `cdk-blocks/database..ca.ts` for a name other than `db-url`. Every later command for that connection, and a later `connect` without `--ca`, verifies the server with it. +- prints the lines for your backend file. They name `./migrations` as `migrationsPath`, the directory that `migrate` applies, so a deploy runs the same files. + +`--name` defaults to `db-url`. ## Transactions DSQL uses [optimistic concurrency](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/working-with-concurrency-control.html): a transaction never waits on a lock. Two transactions that change the same row both run to the end. Then one commit fails with `SerializationFailure` (SQLSTATE `40001`, HTTP 409, flagged retriable). `SELECT … FOR UPDATE` is supported and makes a read conflict with concurrent writes, which is how a read-modify-write stays correct. -- Pass `{ retryOnConflict: true }` to re-run the callback on a conflict. It is off by default because a callback may have side effects. `maxRetries` defaults to 8. Before each re-run the block waits a random time between 0 and a ceiling: 50 ms for the first retry, doubled with each retry, 2,000 ms at most. The random wait keeps transactions that conflicted together from re-running together. With the default, the waits add up to 7.15 seconds at most; set a smaller `maxRetries` when the caller cannot wait that long. Pass `signal: context.request.signal` to stop the retries at the request deadline: without it, a retry can commit after the caller received a timeout. The wait is the same in local mode and on AWS. A single `query` or `execute` outside a transaction is always retried (see [Errors](#errors)). +`transaction(fn, options?)` takes these options: + +| Option | Type | Default | Description | +|---|---|---|---| +| `retryOnConflict` | `boolean` | `false` | Re-run the callback on a conflict. It is off by default because a callback may have side effects. | +| `maxRetries` | `number` | `8` | The most re-runs, with `retryOnConflict`. Before each re-run the block waits a random time between 0 and a ceiling: 50 ms for the first retry, doubled with each retry, 2,000 ms at most. With the default, the waits add up to 7.15 seconds at most; set a smaller `maxRetries` when the caller cannot wait that long. | +| `signal` | `AbortSignal` | none | Stops the retries when it aborts. Pass `signal: context.request.signal` to stop the retries at the request deadline: without it, a retry can commit after the caller received a timeout. | + +- The wait before a re-run is the same in local mode and on AWS. +- A single `query` or `execute` outside a transaction is always retried (see [Errors](#errors)). - A transaction may change at most 3,000 rows (cascaded deletes included) and 10 MiB of data. Past either it fails with `TransactionRowLimitExceeded` and nothing is kept. Split bulk work into batches. - A throw inside the callback rolls the transaction back. An `ApiError`, a branded Blocks error or a `DatabaseErrors` error reaches the caller unchanged. Any other error becomes `TransactionFailed` and its text stays on the server. - Inside the callback, `shop.query()`, `shop.queryOne()` and `shop.execute()` on the block that opened the transaction run in it, as `tx` does. Prefer `tx`: it shows the transaction where the statement is written. @@ -443,7 +555,7 @@ For tests, `simulateConflict(shop)` from `@aws-cdk-blocks/bb-database/testing` m ## Kysely -`DatabaseDialect` is a [Kysely](https://kysely.dev) dialect for a `Database`. Kysely is the supported query builder. It is an optional peer dependency of the block: install it in your application (`npm install kysely`) and import the dialect from `@aws-cdk-blocks/bb-database/kysely`. An application that does not use Kysely does not load it. +`DatabaseDialect` is a [Kysely](https://kysely.dev) dialect for a `Database`. Kysely is the supported query builder. It is an optional peer dependency of the block: install it in your application (`npm install kysely`) and import the dialect from `@aws-cdk-blocks/bb-database/kysely`. ```ts import { type Generated, Kysely } from 'kysely'; @@ -460,7 +572,7 @@ const recent = await kysely.selectFrom('orders').select(['id', 'total']).where(' Statements run through the same engine as `query()`: they use the block's schema, the same DML-only access and the errors under [Errors](#errors). Create the Kysely instance at module scope; it is safe during CDK synth. Plugins and logging are options of Kysely. -- **Types.** Declare the tables yourself, or generate them from the block's migration files: `npm run db -- types --block ` writes one `Tables` interface (see [Types and status from the command line](#types-and-status-from-the-command-line)). A `bigint` column is a `number`, a `numeric` column is a `string` and a `timestamp` column is a `Date`, locally and on AWS. +- **Types.** Declare the tables yourself, or generate them from the block's migration files: `npm run db -- types --block ` writes one `Tables` interface (see [Command line](#command-line)). A `bigint` column is a `number`, a `numeric` column is a `string` and a `timestamp` column is a `Date`, locally and on AWS. - **Transactions.** Inside a Kysely transaction, run every statement on `trx`. A statement on the block or on the root Kysely instance is not part of that transaction: on AWS it runs on another connection, and in local mode it fails after five seconds. A Kysely statement inside the block's `transaction()` callback runs in that transaction. - **Errors.** An error that the callback of a Kysely transaction throws reaches the caller as thrown; the block does not change it to `TransactionFailed`. A Kysely transaction is not re-run on a conflict, so on a `dsql` cluster use `transaction(fn, { retryOnConflict: true })` for work that can conflict. - **`dsql` clusters.** Isolation levels and savepoints are not available. @@ -490,13 +602,6 @@ export const api = new ApiNamespace(scope, 'api', (context) => ({ `asUser(user, claims?)` returns the block with `query`, `queryOne`, `execute` and `transaction`. Each transaction on it starts by setting `request.jwt.claims` to `{ ...claims, sub: user.userId }`, for that transaction only. A single statement runs in a transaction of its own. Only `userId` is read from `user`, so the result of `requireAuth()` passes as it is. `claims` is for other values that your policies read, such as an organization id; `sub` is always the user id. -For Kysely, give the dialect the scoped database. Every statement, in a transaction or not, runs as the user: - -```ts -const kysely = new Kysely({ dialect: new DatabaseDialect(app.asUser(user)) }); -const mine = await kysely.selectFrom('notes').select(['id', 'body']).execute(); -``` - - **`asUser()` does not turn Row Level Security on.** A table without `ENABLE ROW LEVEL SECURITY` and a policy returns every row to every user. - **A statement on the block itself has no user.** With the policy above it reads no rows and cannot insert. Code that must see every row, such as a scheduled job, passes a claim that a policy admits: `app.asUser({ userId: 'system' }, { service: true })`, with `CREATE POLICY notes_service ON notes USING ((current_setting('request.jwt.claims', true)::jsonb ->> 'service')::boolean)`. Only your server code sets claims, so a policy can trust them. - **Write policies without a `TO` clause.** The app connects as one database role on every request; the user is the claim, not the role. @@ -531,21 +636,7 @@ Each transaction on the returned object starts with one statement, `SELECT set_c - **Write a policy so that it accepts an empty claims setting.** After a transaction that set the claims, PostgreSQL leaves `request.jwt.claims` on that connection as an empty string, and `''::jsonb` is an error. A later statement on the block itself then fails with `QueryFailed` instead of reading no rows, when the connection role is one that policies apply to. Write `nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub'`. A cluster that the block provisions gives every connection the default `{}`; a transaction pooler does not keep such a default. - **A statement can undo the switch** with `RESET ROLE` inside its own transaction. The app writes the SQL, so this is a rule for the app's own statements, not a boundary. -On an `aurora` cluster that the block provisions, the app connects as the cluster's app role, which owns nothing, so `asUser()` already filters rows. Use `asRole()` there for policies written for a role. Create the role, give it what the policies need, and grant it to the app role, all in a migration; the app role exists before the first file runs, so this works from the first deploy: - -```sql --- cdk-blocks/migrations/app/003_roles.sql -CREATE ROLE authenticated NOLOGIN; -GRANT USAGE ON SCHEMA app TO authenticated; -- the block's schema (db.schemaName): its id on a shared cluster -GRANT SELECT ON todos TO authenticated; -CREATE POLICY todos_owner ON todos FOR SELECT TO authenticated - USING (user_id = nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub'); -GRANT authenticated TO ${app_role} WITH INHERIT FALSE, SET TRUE; -``` - -A role belongs to the cluster, not to a block: create it in the migrations of one block on the cluster. - -With Kysely, keep one instance for the database and set the identity inside a transaction: +With Kysely, `new DatabaseDialect(db.asRole('authenticated', claims))` needs no transaction of your own; it is a dialect, and so a Kysely instance, per request. To keep one instance for the database, set the identity inside a transaction: ```ts import { Kysely, sql as raw } from 'kysely'; @@ -561,85 +652,51 @@ const mine = await kysely.transaction().execute(async (trx) => { }); ``` -`new DatabaseDialect(db.asRole('authenticated', claims))` also works and needs no transaction of your own; it is a dialect, and so a Kysely instance, per request. -## Errors - -Query and transaction failures carry a `DatabaseErrors` name. Match them with `isBlocksError(e, DatabaseErrors.X)` on the server or the client. Only the name and a message free of row values cross the wire; the driver error stays on the server. Three kinds of error are not for `catch`: setup mistakes (`DatabaseConfigurationError`: a duplicate id, a missing `migrationsPath`), migration file findings (`MigrationValidationError`: a `dsql-lint` finding, or a DSQL-only form in a file for an `aurora` cluster; `DsqlValidationError` in a handler's statement), and migration failures (`MigrationFailedException`). Fix the cause. - -| Error | When | Retried automatically | -|---|---|---| -| `QueryFailed` | Any other SQL error | No | -| `ConnectionFailed` | The connection to the cluster failed or was lost (SQLSTATE class `08`), or was never made: the address did not answer, the server certificate was not accepted, or the login was refused. The function's log names which | A lost connection, for a single `query` or `execute`: once, on a fresh connection. Inside a transaction, and for a connection that was never made: no | -| `TransactionFailed` | The callback threw an error that is not an `ApiError`, a Blocks error or a database error, or a statement reached the transaction after it ended (a promise the callback did not await) | No | -| `UniqueConstraintViolation` | SQLSTATE `23505` (HTTP 409) | No | -| `NotNullViolation` | A required value is missing: SQLSTATE `23502` (HTTP 400) | No | -| `CheckViolation` | A value breaks a `CHECK` constraint: SQLSTATE `23514` (HTTP 400) | No | -| `ForeignKeyViolation` | The row refers to a row that does not exist, or other rows still refer to the row being deleted: SQLSTATE `23503` (HTTP 409) | No | -| `PermissionDenied` | A statement on a database from `asUser()` was refused: a Row Level Security policy rejected the row (SQLSTATE `42501`, HTTP 403) | No | -| `SerializationFailure` | SQLSTATE `40001`, usually at commit (HTTP 409, retriable) | A single `query` or `execute`: three times. A `transaction()` callback: only with `retryOnConflict: true` (see [Transactions](#transactions)) | -| `TransactionRowLimitExceeded` | More than 3,000 rows changed (cascades included) or more than 10 MiB written in one transaction, locally and on DSQL (SQLSTATE `54000`) | No; split the work | -| `ResultValidationFailed` | A row did not match the `schema` passed to `query()` or `queryOne()`. The message, which reaches the client, names the row index and the first issue's path; the library's issue messages stay on the server-side `cause` | No; fix the schema or the query | - -```ts -import { DatabaseErrors, isBlocksError, sql } from 'aws-cdk-blocks'; - -try { - await shop.execute(sql`INSERT INTO customers (id, email) VALUES (${id}, ${email})`); -} catch (err) { - if (isBlocksError(err, DatabaseErrors.UniqueConstraintViolation)) return { conflict: 'email already registered' }; - throw err; -} -``` - -## Local mode - -`npm run dev` needs no AWS account. Each cluster is one PGlite (PostgreSQL compiled to WebAssembly) under `.cdk-blocks/local/data/`, with one schema per block, as on AWS. - -A `dsql` cluster adds DSQL's checks locally: `dsql-lint` on every handler statement (cached per statement text) and the 3,000-row and 10 MiB transaction limits (see [Transactions](#transactions)). Unsupported SQL fails on your machine, not in production. An `aurora` cluster is PostgreSQL on both sides and needs neither. DSQL's forms (`ASYNC`, `sys.wait_for_job`) are rejected locally on an `aurora` cluster, as Aurora rejects them. - -On an `aurora` cluster, a migration can run `CREATE EXTENSION` for these extensions locally. PGlite includes them and Aurora PostgreSQL supports them: `amcheck`, `bloom`, `btree_gin`, `btree_gist`, `citext`, `cube`, `dict_int`, `dict_xsyn`, `earthdistance`, `fuzzystrmatch`, `hstore`, `intarray`, `isn`, `lo`, `ltree`, `moddatetime`, `pg_buffercache`, `pg_freespacemap`, `pg_trgm`, `pg_visibility`, `pgcrypto`, `seg`, `tablefunc`, `tcn`, `tsm_system_rows`, `tsm_system_time`, `unaccent` and `uuid-ossp`. An extension that PGlite lacks fails locally even though Aurora has it. `vector` (pgvector) is one: the migration fails with `extension "vector" is not available`, and the message lists the extensions above. `pg_stat_statements` is not loaded locally either. A `dsql` cluster has no extensions, and `CREATE EXTENSION` fails `dsql-lint`. - -On both kinds, your statements run locally as a plain database role with the grants the deployed app role gets: `SELECT`, `INSERT`, `UPDATE` and `DELETE` on the block's tables. Migrations run as the admin. PostgreSQL therefore refuses the same statements in both places, with `QueryFailed`: DDL and `TRUNCATE` outside a migration, and any read of the migration ledger (`_migrations`, `_migration_progress`). A Row Level Security policy on a table of an `aurora` cluster applies to your statements under `npm run dev` as it does on AWS. - -A connection to an `aurora` cluster is closed ten seconds after its last statement while the function is running, so a cluster at `minCapacity: 0` can pause between requests (an open connection keeps it running); the next request reconnects. A frozen Lambda execution environment keeps its socket until it is thawed or reclaimed, so the pause can come later than five minutes after the last request. - -Your DSQL migration files run unchanged. `ASYNC` index builds and constraint validations complete at once, and a `sys.wait_for_job(…)` copied from the AWS examples returns immediately. - -| | Owned default | `DatabaseCluster` | -|---|---|---| -| Engine | PGlite with `dsql-lint` and the DSQL limits | One PGlite per cluster, one schema per block; the DSQL checks for `type: 'dsql'`, plain PostgreSQL for `type: 'aurora'` | -| Data | `.cdk-blocks/local/data/{fullId}/pglite/` | `.cdk-blocks/local/data/{clusterFullId}/pglite/` | -| Migrations | Before the block's first query | Same, per block, into its schema | - -PGlite has one session, so local work on a cluster runs one statement or transaction at a time. Bugs that need two requests to overlap do not reproduce locally; `simulateConflict()` from `@aws-cdk-blocks/bb-database/testing` covers the retry path. - -A call to another block on the same cluster from inside a `transaction()` callback behaves differently in the two places. Locally it runs inside the transaction and rolls back with it. On DSQL it runs on its own connection and commits on its own. Write such a call so both outcomes are acceptable, or move it after the transaction. +## Access through the AWS SDK -Tests that call gated methods through the dev server need the auth cookie to persist between requests. Call `installCookieJar()` from `aws-cdk-blocks/utils` once at the top of the test file. +`getSdkIdentifiers(db)` from `@aws-cdk-blocks/core` returns the block's `clusterId` and `schemaName`. In a deployed Lambda it also returns the cluster's `clusterEndpoint` and `region`, which is what a `DsqlSigner` (`dsql`) or an RDS `Signer` from `@aws-sdk/rds-signer` (`aurora`, port 5432) needs to open your own `pg` connection as the same role. `getSdkIdentifiers` from `aws-cdk-blocks` types this result. ## What it provisions (AWS) Per cluster, whether a block owns it or a `DatabaseCluster` declares it: -- **One cluster.** `dsql`: an Aurora DSQL cluster (`AWS::DSQL::Cluster`). `aurora`: an Aurora PostgreSQL Serverless v2 cluster created with the express configuration (`AWS::RDS::DBCluster` with `WithExpressConfiguration`), which also creates its writer instance; IAM authentication for the master user (`postgres`, no password), the capacity range from `minCapacity`/`maxCapacity`, backups from `pointInTimeRecovery` (15 days under production defaults), storage encrypted with an AWS-owned key (the express configuration accepts no customer managed KMS key). Either way: IAM token authentication; no VPC, no secret, no security group, no proxy. Deletion protection follows the stack `defaults`. +- **One cluster.** + - `dsql`: an Aurora DSQL cluster (`AWS::DSQL::Cluster`). + - `aurora`: an Aurora PostgreSQL Serverless v2 cluster created with the express configuration (`AWS::RDS::DBCluster` with `WithExpressConfiguration`), which also creates its writer instance. The master user (`postgres`) has IAM authentication and no password. The capacity range comes from `minCapacity`/`maxCapacity`, and the backups from `pointInTimeRecovery` (15 days under production defaults). The storage is encrypted with an AWS-owned key. + - Either way: IAM token authentication; no VPC, no secret, no security group, no proxy. Deletion protection follows the stack `defaults`. - **Two migration Lambdas** (`onEvent` and `isComplete`), one log group, and a custom-resource provider that waits for DSQL index and validation jobs for up to 55 minutes. - **IAM:** on `dsql`, the app's execution role gets `dsql:DbConnect` on the cluster and the migration Lambdas get `dsql:DbConnectAdmin`. On `aurora`, the execution role gets `rds-db:connect` for the app's database role and the migration Lambdas get it for `postgres`. - **Config:** `BLOCKS_{CLUSTER_ID}_ENDPOINT` and `BLOCKS_{CLUSTER_ID}_REGION` (the cluster's full id upper-cased, with `_` for other characters), injected through the config bucket. A `LegacyDatabaseCluster` declares what `Database` of `@aws-blocks/bb-data` 0.5.0 declared: an Aurora PostgreSQL Serverless v2 cluster with one writer instance and the Data API enabled, its credentials secret, a security group, and a VPC with two isolated subnets when the app provides none. The execution role gets the Data API actions on the cluster and the read of the secret, and the config has `BLOCKS_{CLUSTER_ID}_CLUSTER_ARN`, `_SECRET_ARN` and `_DATABASE`. A block on it has two migration Lambdas of its own, outside the VPC. -Per block: one CloudFormation custom resource that applies its migrations, and one S3 asset with the migration files when it has any. Before the files run, the migration Lambda creates a per-cluster database role for the app (`blocks_app_{cluster}`, see [Access through the AWS SDK](#access-through-the-aws-sdk)) when it does not exist yet and maps it to IAM (`AWS IAM GRANT` to the execution role on `dsql`; `GRANT rds_iam` on `aurora`, where the `rds-db:connect` grant decides who gets a token for it). After the files, it grants the role `SELECT`, `INSERT`, `UPDATE` and `DELETE` on the block's tables, `SELECT` on its views, and `USAGE, SELECT` on its sequences. DDL needs the admin token, which only the migration Lambdas hold. +Per block: one CloudFormation custom resource that applies its migrations, and one S3 asset with the migration files when it has any. -**Cost.** See [Aurora DSQL pricing](https://aws.amazon.com/rds/aurora/dsql/pricing/) and [Aurora pricing](https://aws.amazon.com/rds/aurora/pricing/) (Serverless v2 is billed per ACU-second; an `aurora` cluster with `minCapacity: 0` costs nothing while paused, `0.5` is about $44 a month). The migration Lambdas run only during deploys. A `Database` that owns its cluster takes one slot of the account's [cluster quota](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/CHAP_quotas.html); blocks on a shared `DatabaseCluster` take one together. +The migration Lambda also creates a per-cluster database role for the app: -## Access through the AWS SDK +- It maps the role to IAM: `AWS IAM GRANT` to the execution role on `dsql`; `GRANT rds_iam` on `aurora`, where the `rds-db:connect` grant decides who gets a token for it. +- It grants the role `SELECT`, `INSERT`, `UPDATE` and `DELETE` on the block's tables, `SELECT` on its views, and `USAGE, SELECT` on its sequences. +- DDL needs the admin token, which only the migration Lambdas hold. -`getSdkIdentifiers(db)` from `@aws-cdk-blocks/core` returns the block's `clusterId` and `schemaName`. In a deployed Lambda it also returns the cluster's `clusterEndpoint` and `region`, which is what a `DsqlSigner` (`dsql`) or an RDS `Signer` from `@aws-sdk/rds-signer` (`aurora`, port 5432) needs to open your own `pg` connection as the same role. `getSdkIdentifiers` from `aws-cdk-blocks` types this result. +## Scaling and cost (AWS) -On a cluster the block provisions it also returns `roleName`, the PostgreSQL role the block connects as: `blocks_app_local` in local mode, and on AWS `blocks_app_` followed by the cluster's full id in lower case, with `_` for every character other than a letter or a digit. When that name is longer than 63 characters it is `blocks_app_` and the first 12 hex characters of the SHA-256 of the full id. A block on an existing database or a `LegacyDatabaseCluster` connects as the role of its connection and has no `roleName`. In a migration, write [`${app_role}`](#the-app-role-in-a-migration) instead of the name. +- **Pricing.** See [Aurora DSQL pricing](https://aws.amazon.com/rds/aurora/dsql/pricing/) and [Aurora pricing](https://aws.amazon.com/rds/aurora/pricing/). Serverless v2 is billed per ACU-second. +- **An idle `aurora` cluster.** With `minCapacity: 0` it costs nothing while paused. With `0.5` it costs about $44 a month. +- **Migration Lambdas.** They run only during deploys. +- **Cluster quota.** A `Database` that owns its cluster takes one slot of the account's [cluster quota](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/CHAP_quotas.html); blocks on a shared `DatabaseCluster` take one together. -```ts -import { getSdkIdentifiers } from 'aws-cdk-blocks'; +## Local development -const { roleName, schemaName } = getSdkIdentifiers(db); // roleName: 'blocks_app_local' under npm run dev -``` +Each cluster is one PGlite (PostgreSQL compiled to WebAssembly) under `.bb-data/`, with one schema per block, as on AWS. The data directory is `.bb-data/{fullId}/pglite/` for a block that owns its cluster, and `.bb-data/{clusterFullId}/pglite/` for a `DatabaseCluster`. + +A `dsql` cluster adds DSQL's checks locally: `dsql-lint` on every handler statement (cached per statement text) and the 3,000-row and 10 MiB transaction limits (see [Transactions](#transactions)). An `aurora` cluster is PostgreSQL on both sides and needs neither. DSQL's forms (`ASYNC`, `sys.wait_for_job`) are rejected locally on an `aurora` cluster, as Aurora rejects them. + +On both kinds, your statements run locally as a plain database role with the grants the deployed app role gets: `SELECT`, `INSERT`, `UPDATE` and `DELETE` on the block's tables. Migrations run as the admin. PostgreSQL therefore refuses the same statements in both places, with `QueryFailed`: DDL and `TRUNCATE` outside a migration, and any read of the migration ledger (`_migrations`, `_migration_progress`). A Row Level Security policy on a table of an `aurora` cluster applies to your statements under `npm run dev` as it does on AWS. + +Locally, `ASYNC` index builds and constraint validations complete at once, and a `sys.wait_for_job(…)` copied from the AWS examples returns immediately. + +PGlite has one session, so local work on a cluster runs one statement or transaction at a time. Bugs that need two requests to overlap do not reproduce locally. For the retry path, use `simulateConflict()` (see [Transactions](#transactions)). + +A call to another block on the same cluster from inside a `transaction()` callback behaves differently in the two places. Locally it runs inside the transaction and rolls back with it. On DSQL it runs on its own connection and commits on its own. Write such a call so both outcomes are acceptable, or move it after the transaction. + +A test that calls a gated method through the dev server needs `installCookieJar()` from `aws-cdk-blocks/utils`. From 444e77370647971da918c44ef3fac637f5a57ae6 Mon Sep 17 00:00:00 2001 From: Jairo Suarez Date: Wed, 18 Nov 2026 17:19:56 +0000 Subject: [PATCH 03/11] docs(bb-file-bucket): correct the FileNotFound and FileTooLarge rows; one errors table The errors table said `FileBucketErrors.FileNotFound` was "surfaced by presigned-URL 404s etc." and `FileTooLarge` meant "file exceeds size limits"; no FileBucket method throws either, and an upload over `maxUploadBytes` throws `ValidationFailed`. `ValidationFailed` is now the first row of the table, as a name with no `FileBucketErrors` constant that is matched with `isBlocksError(e, 'ValidationFailed')`. Two bullets gave opposite advice on handles and raw presigned URLs; the method table now says when to return each. The README gains a quick start, the `FileBucket.fromKmsKey(keyArn)` method row, tables for `FileContent`, `FileInfo`, `FileDownloadClient` and `FileUploadClient`, a `Default` column in the options table and a `## Scaling and cost (AWS)` section that says an upload is one `PutObject` request. The "Best Practices" list and the Batch Delete example are removed; the reason to encode an OIDC `userId` moves to "Access control and per-user isolation". --- packages/bb-file-bucket/README.md | 381 ++++++++++++++---------------- 1 file changed, 181 insertions(+), 200 deletions(-) diff --git a/packages/bb-file-bucket/README.md b/packages/bb-file-bucket/README.md index 3c65e1f752..98130c243a 100644 --- a/packages/bb-file-bucket/README.md +++ b/packages/bb-file-bucket/README.md @@ -10,6 +10,33 @@ File storage backed by Amazon S3. > Production settings (access logging, KMS encryption, Object Lock, scaling & cost): [PRODUCTION.md](./PRODUCTION.md) +## Quick start + +```typescript +const auth = new Auth(scope, 'auth'); +const bucket = new FileBucket(scope, 'uploads'); + +/** The caller's key for `name`, under a prefix only they can reach. */ +function userKey(userId: string, name: string): string { + return `uploads/${encodeURIComponent(userId)}/${encodeURIComponent(name)}`; +} + +export const api = new ApiNamespace(scope, 'api', (context) => ({ + async uploadFile(name: string, content: string) { + const user = await auth.requireAuth(context); + await bucket.put(userKey(user.userId, name), content, { contentType: 'text/plain' }); + }, + async getFile(name: string) { + const user = await auth.requireAuth(context); + const file = await bucket.get(userKey(user.userId, name)); + if (!file) return null; + return { contentType: file.contentType, size: file.size }; + }, +})); +``` + +`Auth` is the auth block from `@aws-cdk-blocks/bb-auth`. Keys are built on the server under a per-user prefix: see [Access control and per-user isolation](#access-control-and-per-user-isolation). + ## API ```typescript @@ -22,42 +49,43 @@ const bucket = new FileBucket(scope, id, options?) | `get(path, options?)` | `Promise` | Download a file. Returns `null` if absent. Pass `{ versionId }` on versioned buckets. It always reads the whole body: there is no metadata-only (HEAD) read, so `get()` is the only call that returns `contentType` and `metadata`. `scan()` returns `size` and `lastModified` without the body. | | `delete(path, options?)` | `Promise` | Delete a file. No-op if absent. Pass `{ versionId }` on versioned buckets to permanently delete a version. | | `deleteBatch(paths)` | `Promise` | Delete multiple files. Chunks internally at 1,000 keys. | -| `getUrl(path, options?)` | `Promise` | Generate a presigned download URL. Accepts `versionId` on versioned buckets. | -| `putUrl(path, options?)` | `Promise` | Generate a presigned upload URL. | -| `getFileHandle(path, options?)` | `Promise` | Get a download handle for browser-side use. Accepts `versionId` on versioned buckets. | -| `createUploadHandle(path, options?)` | `Promise` | Get an upload handle for browser-side use. | +| `getUrl(path, options?)` | `Promise` | Generate a presigned download URL. Accepts `versionId` on versioned buckets. Use it when the caller needs the URL itself (``, ``); for a browser `fetch`, return a handle. | +| `putUrl(path, options?)` | `Promise` | Generate a presigned upload URL. The caller must send the signed `Content-Type` itself; for a browser upload, return a handle. | +| `getFileHandle(path, options?)` | `Promise` | Get a download handle to return from an API method; the browser calls `download()` on it. Accepts `versionId` on versioned buckets. | +| `createUploadHandle(path, options?)` | `Promise` | Get an upload handle to return from an API method; the browser calls `upload()` on it. | | `scan(options?)` | `AsyncIterable` | List files. Use `prefix` to scope. | | `listVersions(path)` | `Promise` | List all versions of a file (versioned buckets only). Newest first. | | `restoreVersion(path, versionId)` | `Promise` | Restore a previous version as the current version. | -| `FileBucket.fromExisting(bucketName)` | `ExternalBucketRef` | Wrap a pre-existing S3 bucket. | +| `FileBucket.fromExisting(bucketName)` | `ExternalBucketRef` | Wrap a pre-existing S3 bucket. Pass to `options.bucket`. | +| `FileBucket.fromKmsKey(keyArn)` | `ExternalKmsKeyRef` | Reference an existing customer-managed KMS key. Pass to `options.encryption`. | ### Options -| Option | Type | Description | -|--------|------|-------------| -| `versioned` | `boolean` | Enable S3 object versioning. **Default: `true`.** Pass `versioned: false` to opt out. Note: the version-aware method typings (`versionId` on `get`/`delete`/`getUrl`/`getFileHandle`) are selected only by the literal `versioned: false`; a non-literal `boolean` or an absent value resolves to the versioned-aware typings. | -| `noncurrentVersionExpirationDays` | `number` | Days after which **noncurrent** (superseded) object versions are permanently expired, bounding the storage cost that versioning would otherwise let grow unbounded. Only applies when versioning is enabled (the default). **Default: `90`.** Must be a positive integer — a non-positive or non-integer value throws at synth. There is no disable sentinel; to drop the rule entirely, disable versioning (`versioned: false`). Ignored by the mock and browser runtimes. | -| `corsRules` | `CorsRule[]` | CORS rules for browser-based access. **Default: none — browsers block every cross-origin `fetch()` to the deployed bucket.** Required whenever browser code fetches a presigned URL directly (`download()` / `upload()` on a file handle, or `fetch()` on a `getUrl()` / `putUrl()` URL) against a deployed sandbox or production stack. Not inherited from the stack's `defaults.allowedOrigins` or the Hosting domain. Ignored when `bucket` wraps an existing bucket. See [Browser Uploads and Downloads (CORS)](#browser-uploads-and-downloads-cors), and [CorsRule](#corsrule) for the wildcard-origin synth guard. | -| `lifecycleRules` | `LifecycleRule[]` | Lifecycle rules for automatic expiration or storage class transitions. | -| `accessLogging` | `boolean` | Enable S3 server access logging. **Default: falls back to the stack posture (`BlocksDefaults.storageAccessLogging`, then `BlocksDefaults.accessLogging`)** when omitted — so a stack can opt every FileBucket into logging without a per-block flag. When enabled, a dedicated, locked-down log bucket is provisioned (all public access blocked, S3-managed encryption, SSL enforced) and the main bucket delivers its access logs there under the `access-logs/` prefix. Access logs expire automatically after the stack posture's `logRetention` (`ONE_WEEK` in sandbox / `ONE_YEAR` in production; `RetentionDays.INFINITE` keeps them indefinitely). Ignored by the mock and browser runtimes. | -| `encryption` | `'aws-managed' \| 'customer-managed' \| ExternalKmsKeyRef` | Server-side encryption at rest. **Default: `'aws-managed'` (SSE-S3).** `'customer-managed'` creates a dedicated KMS key for this bucket (rotation on, removed with the bucket); `FileBucket.fromKmsKey(arn)` uses a key you already own. Both use SSE-KMS with S3 Bucket Keys. Any other value (e.g. a typo from untyped JavaScript or config) fails the synth with an error listing the valid values, rather than falling back to SSE-S3. See [Encryption with KMS](./PRODUCTION.md#encryption-with-kms). Ignored, with a synth warning, when `bucket` wraps an existing bucket. Ignored by the mock and browser runtimes. | -| `objectLock` | `{ mode: 'governance' \| 'compliance'; retentionDays: number }` | Enable S3 Object Lock with a default retention for every new object version. **Default: off.** Requires versioning and a retained bucket (`removalPolicy: 'retain'` in a sandbox); both are checked at synth. Can be added to a deployed bucket, but can't be turned off once on. Presigned uploads (`putUrl`, `createUploadHandle`) are not supported on these buckets — upload with `put()`. See [Object Lock](./PRODUCTION.md#object-lock). Ignored, with a synth warning, when `bucket` wraps an existing bucket. Validated, but not enforced, by the mock. | -| `allowedContentTypes` | `string[]` | Content types the bucket accepts on upload. **Default: any.** Entries are exact media types (`'application/pdf'`) or `type/*` wildcards (`'image/*'`), without parameters; matching ignores case and parameters. A wildcard does not match `text/html`, `image/svg+xml`, `application/xhtml+xml`, `text/xml`, `application/xml`, `text/xsl`, `text/javascript`, `text/ecmascript`, `application/javascript`, `application/ecmascript` and `application/x-javascript`, and any subtype ending in `+xml`; list one exactly to accept it. Checked by `put()`, `putUrl()` and `createUploadHandle()` against the effective content type (`application/octet-stream` when the caller passes none — list it to accept those uploads). An unlisted type throws `ValidationFailed`. Must be a non-empty array of `type/subtype` or `type/*` strings (checked at synth). See [Upload constraints](#upload-constraints). | -| `maxUploadBytes` | `number` | Largest upload, in bytes. **Default: no limit.** When set, `putUrl()` / `createUploadHandle()` require `contentLength` and reject one above the limit, and `put()` rejects a larger body (`ValidationFailed`). Must be a positive integer (checked at synth). See [Upload constraints](#upload-constraints). | -| `bucket` | `ExternalBucketRef` | Wrap an existing S3 bucket instead of creating one. | -| `logger` | `ChildLogger` | Optional logger for internal operations. When omitted, a default error-level logger is created. | -| `removalPolicy` | `'destroy' \| 'retain'` | CDK removal behavior for the underlying S3 bucket. When omitted, it falls back to the stack posture default (`BlocksDefaults.removalPolicy` — `DESTROY` in sandbox, `RETAIN` in production); pass `'destroy'` or `'retain'` to set it explicitly per-block. `'destroy'` also enables `autoDeleteObjects` so the bucket can be emptied on teardown. Ignored by the mock and browser runtimes. | - -All FileBucket-provisioned buckets **enforce TLS unconditionally** (`enforceSSL: true`) — CDK attaches a bucket policy denying any request where `aws:SecureTransport` is `false`, closing the in-transit exposure gap. This is not configurable. - -The S3 bucket name is derived from the scope chain: the FileBucket id joined to its parent scope ids with `-`. If that name fits S3's 63-character limit, it is used as-is. If it is longer, it is shortened to the start of the name plus `-` and an 8-character hash. The shortened name is the same on every deploy and different from the names of other buckets. A name that breaks any other S3 naming rule (for example, one with uppercase letters) still fails `cdk synth` with a `ValidationFailed` error. To read the resolved name, call `getSdkIdentifiers(bucket).bucketName` (from `aws-cdk-blocks`). +| Option | Type | Default | Description | +|--------|------|---------|-------------| +| `versioned` | `boolean` | `true` | Enable S3 object versioning. Only the literal `versioned: false` removes `versionId` from the option types of `get`/`delete`/`getUrl`/`getFileHandle`; a non-literal `boolean` or an absent value keeps it. | +| `noncurrentVersionExpirationDays` | `number` | `90` | Days after which noncurrent (superseded) object versions are permanently expired. Only applies when versioning is enabled. Must be a positive integer — a non-positive or non-integer value throws at synth. To drop the rule, disable versioning (`versioned: false`). Ignored by the mock and browser runtimes. | +| `corsRules` | `CorsRule[]` | none | CORS rules for browser-based access. Without a rule, browsers block every cross-origin `fetch()` to the deployed bucket, including `download()` / `upload()` on a file handle. Not inherited from the stack's `defaults.allowedOrigins` or the Hosting domain. Ignored when `bucket` wraps an existing bucket. See [Browser Uploads and Downloads (CORS)](#browser-uploads-and-downloads-cors), and [CorsRule](#corsrule) for the wildcard-origin synth guard. | +| `lifecycleRules` | `LifecycleRule[]` | none | Lifecycle rules for automatic expiration or storage class transitions. See [LifecycleRule](#lifecyclerule). | +| `accessLogging` | `boolean` | stack posture (`BlocksDefaults.storageAccessLogging`, then `BlocksDefaults.accessLogging`) | Enable S3 server access logging to a dedicated log bucket. See [PRODUCTION.md](./PRODUCTION.md). Ignored by the mock and browser runtimes. | +| `encryption` | `'aws-managed' \| 'customer-managed' \| ExternalKmsKeyRef` | `'aws-managed'` | Server-side encryption at rest. `'aws-managed'` is SSE-S3. `'customer-managed'` creates a dedicated KMS key for this bucket (rotation on, removed with the bucket); `FileBucket.fromKmsKey(arn)` uses a key you already own. Both use SSE-KMS with S3 Bucket Keys. Any other value fails the synth with an error listing the valid values. See [Encryption with KMS](./PRODUCTION.md#encryption-with-kms). Ignored, with a synth warning, when `bucket` wraps an existing bucket. Ignored by the mock and browser runtimes. | +| `objectLock` | `{ mode: 'governance' \| 'compliance'; retentionDays: number }` | off | Enable S3 Object Lock with a default retention for every new object version. Requires versioning and a retained bucket (`removalPolicy: 'retain'` in a sandbox); both are checked at synth. Can't be turned off once on. Presigned uploads (`putUrl`, `createUploadHandle`) throw `PresignedUploadUnsupported` — upload with `put()`. See [Object Lock](./PRODUCTION.md#object-lock). Ignored, with a synth warning, when `bucket` wraps an existing bucket. Validated, but not enforced, by the mock. | +| `allowedContentTypes` | `string[]` | any | Content types the bucket accepts on upload: exact media types (`'application/pdf'`) or `type/*` wildcards (`'image/*'`), without parameters. A wildcard does not match the types a browser can run, such as `text/html` and `image/svg+xml`. Checked by `put()`, `putUrl()` and `createUploadHandle()`; an unlisted type throws `ValidationFailed`. Must be a non-empty array of `type/subtype` or `type/*` strings (checked at synth). See [Upload constraints](#upload-constraints) for the matching rules. | +| `maxUploadBytes` | `number` | no limit | Largest upload, in bytes. When set, `putUrl()` / `createUploadHandle()` require `contentLength` and reject one above the limit, and `put()` rejects a larger body (`ValidationFailed`). Must be a positive integer (checked at synth). See [Upload constraints](#upload-constraints). | +| `bucket` | `ExternalBucketRef` | — | Wrap an existing S3 bucket instead of creating one. See [Wrapping an Existing Bucket](#wrapping-an-existing-bucket). | +| `logger` | `ChildLogger` | error-level logger | Logger for internal operations. | +| `removalPolicy` | `'destroy' \| 'retain'` | stack posture (`BlocksDefaults.removalPolicy` — `DESTROY` in sandbox, `RETAIN` in production) | CDK removal behavior for the underlying S3 bucket. `'destroy'` also enables `autoDeleteObjects` so the bucket can be emptied on teardown. Ignored by the mock and browser runtimes. | + +All FileBucket-provisioned buckets reject requests that do not use TLS (`enforceSSL: true`). This is not configurable. + +The S3 bucket name is derived from the scope chain: the FileBucket id joined to its parent scope ids with `-`. A name longer than S3's 63-character limit is shortened to the start of the name plus `-` and an 8-character hash; the shortened name is the same on every deploy. A name that breaks any other S3 naming rule (for example, one with uppercase letters) fails `cdk synth` with a `ValidationFailed` error. To read the resolved name, call `getSdkIdentifiers(bucket).bucketName` (from `aws-cdk-blocks`). ### PutOptions | Option | Type | Description | |--------|------|-------------| | `contentType` | `string` | MIME type (e.g., `image/png`). Default: `application/octet-stream`. Must be in `allowedContentTypes` when the bucket sets it. | -| `metadata` | `Record` | Custom metadata key-value pairs, set when the object is written. It can't be edited in place: each `put()` replaces it, so a `put()` without `metadata` leaves none. See [Changing Metadata](#changing-metadata). S3 stores the keys in lowercase, so use lowercase keys. | +| `metadata` | `Record` | Custom metadata key-value pairs, set when the object is written. It can't be edited in place: each `put()` replaces it, so a `put()` without `metadata` leaves none. See [Changing Metadata](#changing-metadata). S3 stores the keys in lowercase and the local mock keeps the case you wrote, so use lowercase keys. | | `cacheControl` | `string` | Cache-Control header value. | ### Presigned URL options @@ -68,19 +96,17 @@ The S3 bucket name is derived from the scope chain: the FileBucket id joined to | Option | Type | Description | |--------|------|-------------| -| `contentType` | `string` | Content type of the upload. **Default: `application/octet-stream`.** Always signed into the URL: the upload must send exactly this `Content-Type` header, or S3 rejects it with `403 SignatureDoesNotMatch`. `createUploadHandle().upload()` sends it for you, whatever the uploaded file's own type; to store a browser `File`'s type, pass `contentType: file.type`. | +| `contentType` | `string` | Content type of the upload. Default: `application/octet-stream`. Always signed into the URL: the upload must send exactly this `Content-Type` header, or S3 rejects it with `403 SignatureDoesNotMatch`. `createUploadHandle().upload()` sends it for you, whatever the uploaded file's own type; to store a browser `File`'s type, pass `contentType: file.type`. | | `contentLength` | `number` | Exact size of the upload in bytes. When set, it is signed into the URL and S3 only accepts a body of exactly this size (browsers set `Content-Length` from the body). Required when the bucket sets `maxUploadBytes`. | `getUrl` and `getFileHandle` also accept: | Option | Type | Description | |--------|------|-------------| -| `attachment` | `boolean \| string` | Make the browser download the file instead of displaying it. **Default: off** (the file is displayed inline when the browser can render it). `true` signs `Content-Disposition: attachment` into the URL; a filename (e.g. `'report.pdf'`) also suggests that name. Control characters, directional formatting characters and zero-width characters are removed from the filename, and `/` and `\` are replaced with `_`; a filename that is empty, `.` or `..` afterwards throws `ValidationFailed`. See [Serving user uploads](#serving-user-uploads). | +| `attachment` | `boolean \| string` | Make the browser download the file instead of displaying it. Default: off (the file is displayed inline when the browser can render it). `true` signs `Content-Disposition: attachment` into the URL; a filename (e.g. `'report.pdf'`) also suggests that name. Control characters, directional formatting characters and zero-width characters are removed from the filename, and `/` and `\` are replaced with `_`; a filename that is empty, `.` or `..` afterwards throws `ValidationFailed`. See [Serving user uploads](#serving-user-uploads). | ### CorsRule -CORS configuration for browser-based access. Supplied via the `corsRules` option. - | Field | Type | Description | |-------|------|-------------| | `allowedOrigins` | `string[]` | Origins permitted to make cross-origin requests (e.g., `['https://app.example.com']`). | @@ -93,17 +119,34 @@ CORS configuration for browser-based access. Supplied via the `corsRules` option ### LifecycleRule -Lifecycle configuration for automatic expiration or storage-class transitions. Supplied via the `lifecycleRules` option. - | Field | Type | Description | |-------|------|-------------| | `prefix` | `string` | Optional. Prefix filter — the rule applies only to keys starting with this prefix. Omit to apply to all objects. | | `expirationDays` | `number` | Optional. Days after creation to expire (delete) objects. | | `transitionToIaDays` | `number` | Optional. Days after creation to transition objects to Infrequent Access storage. | -### FileVersionInfo +### FileContent -Returned by `listVersions()` — one entry per object version, newest first. +Returned by `get()`. + +| Field | Type | Description | +|-------|------|-------------| +| `body` | `Buffer` | The file body. | +| `contentType` | `string` | MIME type of the file. | +| `metadata` | `Record` | Custom metadata key-value pairs. | +| `size` | `number` | Size in bytes. | + +### FileInfo + +Yielded by `scan()`. + +| Field | Type | Description | +|-------|------|-------------| +| `path` | `string` | The object key. | +| `size` | `number` | Size in bytes. | +| `lastModified` | `Date` | Last modification timestamp. | + +### FileVersionInfo | Field | Type | Description | |-------|------|-------------| @@ -112,40 +155,48 @@ Returned by `listVersions()` — one entry per object version, newest first. | `size` | `number` | Size in bytes. | | `isCurrent` | `boolean` | Whether this is the current (latest) version. | -### Error Handling +### FileDownloadClient and FileUploadClient -`get()` returns `null` for a missing file — it does **not** throw `FileNotFound`. Check for null: +Returned by `getFileHandle()` and `createUploadHandle()`. A handle returned from an API method arrives in the browser client with the same methods. -```typescript -const file = await bucket.get('missing.txt'); -if (!file) { - // file does not exist -} -``` +| Type | Method | Returns | Description | +|------|--------|---------|-------------| +| `FileDownloadClient` | `download()` | `Promise` | Fetch the file from the presigned URL. Throws an `Error` (`Download failed: `) when the response is not OK. | +| `FileDownloadClient` | `getUrl()` | `string` | The presigned URL. | +| `FileUploadClient` | `upload(body)` | `Promise` | `PUT` a `Blob`, `File` or `ArrayBuffer` to the presigned URL with the signed `Content-Type`. Throws an `Error` (`Upload failed: `) when the response is not OK. | +| `FileUploadClient` | `getUrl()` | `string` | The presigned URL. | + +## Errors -Invalid input — a key or `scan()` prefix that breaks the [key rules](#object-keys), an out-of-range `expiresIn`, a content type or size the bucket does not accept, or an invalid `attachment` — throws an error named `ValidationFailed` (match it with `isBlocksError(e, 'ValidationFailed')`). It is an `ApiError` with status `400`, so an API method that lets it propagate answers the client with HTTP 400. Its message is fixed text and never includes the key or other input. +Match an error by name with `isBlocksError`: -`FileBucketErrors` are thrown by other operations and matched with `isBlocksError`: +```typescript +import { isBlocksError } from '@aws-cdk-blocks/core'; +import { FileBucketErrors } from '@aws-cdk-blocks/bb-file-bucket'; +``` | Constant | `error.name` | Thrown when | |----------|--------------|-------------| -| `FileBucketErrors.FileNotFound` | `NoSuchKey` | Surfaced by presigned-URL 404s etc. **Not** thrown by `get()`, which returns `null`. | -| `FileBucketErrors.FileTooLarge` | `EntityTooLarge` | File exceeds size limits. | +| None; match it with `isBlocksError(e, 'ValidationFailed')` | `ValidationFailed` | Any method: a key or `scan()` prefix breaks the [key rules](#object-keys). The URL and handle methods: `expiresIn` is out of range, or `attachment` is invalid. `put()`, `putUrl()`, `createUploadHandle()`: the content type or size is malformed or one the bucket does not accept. | | `FileBucketErrors.VersionNotFound` | `NoSuchVersion` | Thrown by `restoreVersion()` when the target `versionId` cannot be resolved. | | `FileBucketErrors.PresignedUploadUnsupported` | `PresignedUploadUnsupported` | Thrown by `putUrl()` and `createUploadHandle()` on a bucket with `objectLock` — see [Object Lock](./PRODUCTION.md#object-lock). | +| `FileBucketErrors.FileNotFound` | `NoSuchKey` | No FileBucket method throws it: `get()` returns `null` for a missing file. It is the error code of the HTTP 404 that a presigned download URL returns for a missing or deleted file, on AWS and locally. | +| `FileBucketErrors.FileTooLarge` | `EntityTooLarge` | No FileBucket method throws it: an upload over `maxUploadBytes` throws `ValidationFailed`. | -```typescript -import { FileBucketErrors, isBlocksError } from 'aws-cdk-blocks'; - -try { - await bucket.restoreVersion('report.pdf', 'non-existent-version'); -} catch (e: unknown) { - if (isBlocksError(e, FileBucketErrors.VersionNotFound)) { - // that version does not exist - } - throw e; -} -``` +`ValidationFailed` is an `ApiError` with status `400`, so an API method that lets it propagate answers the client with HTTP 400. Its message is fixed text and never includes the key or other input. + +## Object keys + +Keys are validated identically in local dev and on AWS. A key that breaks any of these rules throws `ValidationFailed` (HTTP 400): + +- not empty, and at most 1,024 bytes once UTF-8 encoded (S3's key limit); +- no leading `/`; +- no empty segment (`a//b`) or trailing `/`; +- no `.` or `..` segment, including one spelled with `%2e`, `%2f` or `%5c` in either case (`a/%2e%2e/b`, `a/..%2f../b`, `a/%2e%2e%2fb`) — other `%` sequences, such as `100%done.txt`, are allowed; +- no backslash (`\`); +- no control characters (U+0000–U+001F, U+007F–U+009F), line or paragraph separators (U+2028, U+2029), or bidirectional formatting characters (U+202A–U+202E, U+2066–U+2069). + +A `scan()` prefix follows the same rules, except that it may be empty or end with `/`. ## Access control and per-user isolation @@ -154,23 +205,14 @@ FileBucket has no per-object permissions of its own. Every API method reads and - Gate each method with your auth block (`await auth.requireAuth(context)`). - Build keys on the server under a per-user prefix derived from the authenticated identity (`uploads/${encodeURIComponent(user.userId)}/…`). Never pass a client-supplied full key, or a client-supplied `scan()` prefix, straight to `put`, `get`, `delete`, `getUrl`, `putUrl`, `scan` or the handle methods. - Accept only a file *name* from the client and wrap it in `encodeURIComponent()`, so it stays a single path segment and can't add `/` to reach another prefix. FileBucket rejects `.`/`..` segments and other unsafe keys with `ValidationFailed`; see [Object keys](#object-keys). +- Wrap the `userId` segment in `encodeURIComponent()` too: an OIDC `userId` of `${iss}:${sub}` (like `https://issuer:sub`) contains `//`, an empty path segment that throws `ValidationFailed`. - For a resource shared between users (a document, a team folder), check that the caller may access it — for example by looking up an ownership record — before building its key. -The examples below assume an auth block (`Auth` from `@aws-cdk-blocks/bb-auth`) and a helper that builds the caller's keys: - -```typescript -const auth = new Auth(scope, 'auth'); -const bucket = new FileBucket(scope, 'uploads'); - -/** The caller's key for `name`, under a prefix only they can reach. */ -function userKey(userId: string, name: string): string { - return `uploads/${encodeURIComponent(userId)}/${encodeURIComponent(name)}`; -} -``` +The snippets below use the `auth` block, `bucket` and `userKey()` helper from [Quick start](#quick-start). ## Upload constraints -Presigned uploads always sign a `Content-Type` — the `contentType` you pass, or `application/octet-stream` when you pass none — so the uploader can't send a different one. To restrict what a bucket accepts: +To restrict what a bucket accepts: ```typescript const avatars = new FileBucket(scope, 'avatars', { @@ -199,13 +241,12 @@ await slot.upload(file); - A wildcard matches every subtype of its type except the types a browser can display as a page or run as a script: `text/html`, `image/svg+xml`, `application/xhtml+xml`, `text/xml`, `application/xml`, `text/xsl`, `text/javascript`, `text/ecmascript`, `application/javascript`, `application/ecmascript` and `application/x-javascript`, and any subtype ending in `+xml` (`application/atom+xml`, …). These can run script when displayed inline (see [Serving user uploads](#serving-user-uploads)), so `image/*` does not accept `image/svg+xml` and `text/*` does not accept `text/html`. To accept one, list it exactly (`allowedContentTypes: ['image/*', 'image/svg+xml']`), and serve its downloads with `attachment`. - A `contentType` must be a single media type — `type/subtype` with optional `; name=value` parameters, ASCII only. A comma-separated list, control characters or an empty value throws `ValidationFailed`, with or without `allowedContentTypes`. - The content type is signed, stored and returned in canonical form: each parameter as `; name=value`, with one space after `;` and none around `=` (`text/plain;charset=utf-8` becomes `text/plain; charset=utf-8`). A quoted parameter value is written without quotes when its content is a token (`charset="utf-8"` becomes `charset=utf-8`), and otherwise stays quoted with only `"` and `\` escaped (`name="a b"` is unchanged). An upload to a `putUrl()` URL must send that canonical value; `createUploadHandle().upload()` and the native clients send it for you. -- With `maxUploadBytes`, `putUrl()` and `createUploadHandle()` require `contentLength` and sign it, so S3 only accepts a body of exactly that size. `put()` checks the body size directly. - An upload to a URL or handle signed with `contentLength` must send exactly that many bytes with a `Content-Length` header. Browsers and `fetch` set it from the body. With the native Kotlin client, pass the same `contentLength` to `uploadFrom(source, contentLength)`: without it the stream is sent with no `Content-Length` and the upload is rejected. The native Swift `uploadFrom(fileURL:)` sends the file's size, so the file must be exactly `contentLength` bytes. - The checks run in the API method, before a URL is signed, identically in local dev and on AWS — including for a bucket wrapped with `FileBucket.fromExisting`. The local dev server also rejects an upload whose `Content-Type` or size differs from the signed values with `403`, as S3 does. ## Serving user uploads -A presigned download URL serves the file with its stored content type, and the browser displays it inline when it can render it. **A file displayed inline can run as a page:** an uploaded HTML or SVG file executes script in the origin that serves it. For user-uploaded content, either restrict uploads to safe types with `allowedContentTypes` (for example `image/*`, which does not accept `image/svg+xml` unless you list it exactly — see [Upload constraints](#upload-constraints)), or make downloads attachments: +A presigned download URL serves the file with its stored content type, and the browser displays it inline when it can render it. **A file displayed inline can run as a page:** an uploaded HTML or SVG file executes script in the origin that serves it. For user-uploaded content, either restrict uploads to safe types with `allowedContentTypes` (for example `image/*`; see [Upload constraints](#upload-constraints)), or make downloads attachments: ```typescript export const api = new ApiNamespace(scope, 'api', (context) => ({ @@ -219,73 +260,9 @@ export const api = new ApiNamespace(scope, 'api', (context) => ({ Never serve uploaded files inline from your application's own origin (for example by proxying them through an API route). If they must render inline, serve them from a separate origin. -## Examples - -The examples use the `auth` block, `bucket` and `userKey()` helper from [Access control and per-user isolation](#access-control-and-per-user-isolation). +## Browser Uploads and Downloads (CORS) -### Basic Put/Get - -```typescript -export const api = new ApiNamespace(scope, 'api', (context) => ({ - async uploadFile(name: string, content: string) { - const user = await auth.requireAuth(context); - await bucket.put(userKey(user.userId, name), content, { contentType: 'text/plain' }); - }, - async getFile(name: string) { - const user = await auth.requireAuth(context); - const file = await bucket.get(userKey(user.userId, name)); - if (!file) return null; - return { contentType: file.contentType, size: file.size }; - }, -})); -``` - -### Changing Metadata - -Object metadata is fixed when the object is written: S3 can only change metadata by rewriting the object, and FileBucket doesn't expose S3's server-side copy (`CopyObject`), so there is no call that edits it. Every `put()` replaces the object's metadata with what it passes, and a `put()` without `metadata` leaves the object with none. To change metadata, `put()` the same body again with the complete new set: - -```typescript -export const api = new ApiNamespace(scope, 'api', (context) => ({ - async markReviewed(name: string) { - const user = await auth.requireAuth(context); - // Derive the key from the caller — never act on a client-supplied full key. - const path = userKey(user.userId, name); - const file = await bucket.get(path); - if (!file) return null; - await bucket.put(path, file.body, { - contentType: file.contentType, - metadata: { ...file.metadata, status: 'reviewed' }, - }); - return { status: 'reviewed' }; - }, -})); -``` - -- The rewrite downloads and re-uploads the whole object, so it costs a GET and a PUT and takes longer for a large file. -- `get()` doesn't return `cacheControl`. If you set one, pass it again. -- Versioning is on by default (see [Versioned Bucket](#versioned-bucket)), so each rewrite stores another full copy of the object as a noncurrent version. It's kept, and billed, for `noncurrentVersionExpirationDays` (default 90). Until then the previous metadata stays on the previous version, and `restoreVersion()` brings it back with that version. -- The rewrite isn't atomic. Anything written to the object between the `get()` and the `put()` (a new body or other metadata) is overwritten with what was read, and FileBucket has no conditional write to guard against it. Avoid rewriting objects that other code may be updating at the same time. -- Uploads through presigned URLs (`putUrl()`, `createUploadHandle()`) carry no custom metadata. Set it afterwards with a rewrite like the one above. -- S3 stores metadata keys in lowercase, so `get()` on AWS returns `{ owner: … }` for a key written as `Owner`. The local mock keeps the case you wrote (see [Mock vs AWS Behavior Differences](./DESIGN.md#mock-vs-aws-behavior-differences)). Use lowercase keys so both return the same thing. - -### Presigned Upload URL - -```typescript -export const api = new ApiNamespace(scope, 'api', (context) => ({ - async getUploadUrl(name: string) { - const user = await auth.requireAuth(context); - const url = await bucket.putUrl(userKey(user.userId, name), { - expiresIn: 600, - contentType: 'image/jpeg', // signed: the upload must send `Content-Type: image/jpeg` - }); - return { uploadUrl: url }; - }, -})); -``` - -### Browser Uploads and Downloads (CORS) - -Presigned URLs and file handles are fetched by the browser **directly from S3**, which is a different origin from your frontend. The deployed bucket must therefore allow your frontend's origin through `corsRules`. FileBucket configures **no CORS by default**, and — unlike the API endpoint — it does **not** pick up the stack's `defaults.allowedOrigins` or the Hosting domain. Without a matching rule, every browser upload or download against a deployed sandbox or production stack fails with: +Presigned URLs and file handles are fetched by the browser **directly from S3**, which is a different origin from your frontend. Without a `corsRules` entry that allows your frontend's origin, every browser upload or download against a deployed sandbox or production stack fails with: ```text Access to fetch at 'https://.s3..amazonaws.com/...' from origin 'http://localhost:3000' @@ -296,7 +273,12 @@ For `upload()` / `PUT`, the browser fails at the preflight instead, and the mess `npm run dev` does not surface this: the local dev file-server accepts any origin, so the error first appears after you deploy. -List every origin your frontend is served from — the local dev frontend (`http://localhost:3000`, when it talks to a deployed sandbox) and your deployed app's origin. With Hosting, that is the stack's `HostingUrl` output: your custom domain if you configured one, otherwise the generated `https://.cloudfront.net` domain, which only exists after the first deploy (deploy once, copy `HostingUrl` into `corsRules`, then redeploy): +List every origin your frontend is served from: + +- the local dev frontend (`http://localhost:3000`), when it talks to a deployed sandbox; +- your deployed app's origin. With Hosting, that is the stack's `HostingUrl` output: your custom domain if you configured one, otherwise the generated `https://.cloudfront.net` domain. + +The generated domain only exists after the first deploy: deploy once, copy `HostingUrl` into `corsRules`, then deploy again. ```typescript const bucket = new FileBucket(scope, 'uploads', { @@ -308,47 +290,42 @@ const bucket = new FileBucket(scope, 'uploads', { }); ``` -`cdk-blocks/index.ts` is shared by sandbox and production deploys, so this rule also allows `http://localhost:3000` on the production bucket. Only a sandbox needs it; leaving it in production is low-risk because presigned URLs authenticate through their query-string signature, not ambient browser credentials. +`cdk-blocks/index.ts` is shared by sandbox and production deploys, so this rule also allows `http://localhost:3000` on the production bucket. Only a sandbox needs it; presigned URLs authenticate through their query-string signature, not ambient browser credentials. - `GET` covers `download()` and `fetch()` on a `getUrl()` URL; `PUT` covers `upload()` and a `putUrl()` URL. -- `allowedHeaders` must list every header the browser sends. A cross-origin `PUT` always triggers a CORS preflight, and S3 rejects the preflight if a request header — such as the `Content-Type` that `upload()` sends — is not allowed. +- `allowedHeaders` must list every header the browser sends, such as the `Content-Type` that `upload()` sends. S3 rejects the preflight of a `PUT` with a header that is not allowed. - `allowedOrigins` entries are S3 origin strings (scheme + host + port, no trailing slash), optionally with a single `*` wildcard such as `https://*.example.com` — not the regex patterns used by `defaults.allowedOrigins`. -- Use exact origins for `PUT`, `POST`, and `DELETE`. A bare `'*'` origin with a mutating method throws at synth (see [CorsRule](#corsrule)); a partial wildcard such as `https://*` is not caught, so avoid it for mutating methods. +- Use exact origins for `PUT`, `POST`, and `DELETE`. The synth check (see [CorsRule](#corsrule)) catches only a bare `'*'` origin; a partial wildcard such as `https://*` is not caught, so avoid it for mutating methods. - Plain navigations to a `getUrl()` URL (``, ``) are not CORS requests and work without a rule; `fetch()`, `download()`, and `upload()` do need one. - `exposedHeaders` (for example `ETag` or `x-amz-version-id`) is only needed when custom `fetch()` code reads response headers; the built-in handles don't. Every `PUT` preflights, so a `maxAge` (for example `3000`) saves a round trip per upload. - CORS is bucket configuration: redeploy after changing `corsRules`. -- `corsRules` is ignored when `bucket` wraps an existing bucket (see [Wrapping an Existing Bucket](#wrapping-an-existing-bucket)) — configure CORS on that bucket itself. -### Listing Files with Scan +## Changing Metadata -```typescript -export const api = new ApiNamespace(scope, 'api', (context) => ({ - async listMyFiles() { - const user = await auth.requireAuth(context); - const files: FileInfo[] = []; - // The prefix is built from the caller's identity, so the listing only covers their files. - for await (const file of bucket.scan({ prefix: `uploads/${encodeURIComponent(user.userId)}/` })) { - files.push(file); - } - return files; - }, -})); -``` - -A `scan()` prefix follows the [key rules](#object-keys), except that it may be empty or end with `/`. - -### Batch Delete +Object metadata can't be edited in place, and FileBucket doesn't expose S3's server-side copy (`CopyObject`). To change metadata, `get()` the object and `put()` the same body again with the complete new set: ```typescript export const api = new ApiNamespace(scope, 'api', (context) => ({ - async deleteFiles(names: string[]) { + async markReviewed(name: string) { const user = await auth.requireAuth(context); - await bucket.deleteBatch(names.map(name => userKey(user.userId, name))); + const path = userKey(user.userId, name); + const file = await bucket.get(path); + if (!file) return null; + await bucket.put(path, file.body, { + contentType: file.contentType, + metadata: { ...file.metadata, status: 'reviewed' }, + }); + return { status: 'reviewed' }; }, })); ``` -### Wrapping an Existing Bucket +- `get()` doesn't return `cacheControl`. If you set one, pass it again. +- On a versioned bucket (the default), each rewrite stores another full copy of the object as a noncurrent version. It's kept, and billed, for `noncurrentVersionExpirationDays`. Until then the previous metadata stays on the previous version, and `restoreVersion()` brings it back with that version. +- The rewrite isn't atomic. Anything written to the object between the `get()` and the `put()` (a new body or other metadata) is overwritten with what was read, and FileBucket has no conditional write to guard against it. Avoid rewriting objects that other code may be updating at the same time. +- Uploads through presigned URLs (`putUrl()`, `createUploadHandle()`) carry no custom metadata. Set it afterwards with a rewrite like the one above. + +## Wrapping an Existing Bucket ```typescript const bucket = new FileBucket(scope, 'legacy', { @@ -356,20 +333,16 @@ const bucket = new FileBucket(scope, 'legacy', { }); ``` -> **A wrapped bucket does not receive FileBucket's secure defaults.** When you supply `bucket`, FileBucket binds to the existing bucket as-is and returns early — none of the secure defaults it normally applies are applied: not `enforceSSL`, versioning / noncurrent-version expiration, server access logging, `blockPublicAccess`, encryption, nor `corsRules` or the wildcard-CORS guard. You own that bucket's security posture; configure these on the bucket itself (or via its own CDK construct) before wrapping it. +> **A wrapped bucket does not receive FileBucket's secure defaults.** None of these are applied: `enforceSSL`, versioning / noncurrent-version expiration, server access logging, `blockPublicAccess`, encryption, `corsRules`, the wildcard-CORS guard. You own that bucket's security posture; configure these on the bucket itself (or via its own CDK construct) before wrapping it. -### Versioned Bucket +## Versioned Bucket -Versioning is **on by default**, so the version-aware methods (`listVersions`, `restoreVersion`, and optional `versionId` on `get`/`delete`/`getUrl`/`getFileHandle`) are available without any option. Pass `versioned: false` to opt out (which also removes the `versionId` option typings). The example below passes `versioned: true` explicitly for clarity: +Versioning is on by default, so `listVersions`, `restoreVersion` and the optional `versionId` on `get`/`delete`/`getUrl`/`getFileHandle` need no option: ```typescript -const docs = new FileBucket(scope, 'docs', { versioned: true }); +const docs = new FileBucket(scope, 'docs'); export const api = new ApiNamespace(scope, 'api', (context) => ({ - async upload(name: string, content: string) { - const user = await auth.requireAuth(context); - await docs.put(userKey(user.userId, name), content); - }, async getVersion(name: string, versionId?: string) { const user = await auth.requireAuth(context); const file = await docs.get(userKey(user.userId, name), versionId ? { versionId } : undefined); @@ -392,50 +365,58 @@ stored data versions; `get()` returns `null` and `scan()` omits the file. On S3, deleting the current data version exposes the next entry in the version history, which may be another data version or a delete marker. -The local mock reconciles its current body and metadata with the next stored -data version when the newest data version is permanently deleted, or removes -the current copies when none remain. This creates no replacement version and -does not remove an active delete-marker flag; `get()` and `scan()` still honor -that flag. - **Local limitation:** the mock keeps only an active delete-marker flag, not delete markers ordered within the version history. A subsequent `put()` removes the flag. Consequently, `put(old)` → `delete()` → `put(replacement)` → permanent deletion of the replacement can expose `old` locally, whereas S3 would make the -earlier delete marker current and treat the key as deleted. This case is not -fixed by current-copy reconciliation. See +earlier delete marker current and treat the key as deleted. See [Mock vs AWS Behavior Differences](./DESIGN.md#mock-vs-aws-behavior-differences) and use a sandbox when testing deletion history across re-uploads. -## Object keys +## Examples -Keys are validated identically in local dev and on AWS. A key that breaks any of these rules throws `ValidationFailed` (HTTP 400): +### Presigned Upload URL -- not empty, and at most 1,024 bytes once UTF-8 encoded (S3's key limit); -- no leading `/`; -- no empty segment (`a//b`) or trailing `/`; -- no `.` or `..` segment, including one spelled with `%2e`, `%2f` or `%5c` in either case (`a/%2e%2e/b`, `a/..%2f../b`, `a/%2e%2e%2fb`) — other `%` sequences, such as `100%done.txt`, are allowed; -- no backslash (`\`); -- no control characters (U+0000–U+001F, U+007F–U+009F), line or paragraph separators (U+2028, U+2029), or bidirectional formatting characters (U+202A–U+202E, U+2066–U+2069). +```typescript +export const api = new ApiNamespace(scope, 'api', (context) => ({ + async getUploadUrl(name: string) { + const user = await auth.requireAuth(context); + const url = await bucket.putUrl(userKey(user.userId, name), { + expiresIn: 600, + contentType: 'image/jpeg', // signed: the upload must send `Content-Type: image/jpeg` + }); + return { uploadUrl: url }; + }, +})); +``` -## Best Practices +### Listing Files with Scan -- Use path prefixes to organize files (e.g., `uploads/{userId}/`, `reports/`). If a segment can contain URL-shaped or special characters (e.g. an OIDC `userId` of `${iss}:${sub}` like `https://issuer:sub`), wrap it in `encodeURIComponent()` first — an un-encoded `//` is an empty path segment, which FileBucket rejects (`ValidationFailed`) on both the local mock and AWS so a key can't mean one object locally and another in production. -- Derive keys from the authenticated user on the server, never from a client-supplied key or prefix (see [Access control and per-user isolation](#access-control-and-per-user-isolation)) -- Set `contentType` on `put()` to ensure correct MIME handling on download -- For user uploads, set `allowedContentTypes` / `maxUploadBytes`, and serve downloads with `attachment` (see [Upload constraints](#upload-constraints) and [Serving user uploads](#serving-user-uploads)) -- Use presigned URLs (`getUrl` / `putUrl`) for direct browser upload/download — and set `corsRules` for your frontend's origins, or the browser blocks them once deployed (see [Browser Uploads and Downloads (CORS)](#browser-uploads-and-downloads-cors)) -- Prefer `scan({ prefix })` over unscoped `scan()` to limit enumeration cost -- For browser uploads/downloads returned from API methods, prefer `createUploadHandle`/`getFileHandle` over raw presigned URLs — they encode the fetch protocol into typed methods so the client can't misuse them -- Use `deleteBatch()` instead of looping `delete()` for bulk operations -- Versioning is **on by default**; noncurrent (superseded) versions are automatically expired after **90 days** (`noncurrentVersionExpirationDays`, default `90`) so version history doesn't grow storage cost unbounded. Tune the window per-block, or disable versioning (`versioned: false`) to drop the expiration rule along with versioning. +```typescript +export const api = new ApiNamespace(scope, 'api', (context) => ({ + async listMyFiles() { + const user = await auth.requireAuth(context); + const files: FileInfo[] = []; + for await (const file of bucket.scan({ prefix: `uploads/${encodeURIComponent(user.userId)}/` })) { + files.push(file); + } + return files; + }, +})); +``` -## Local Development +## Scaling and cost (AWS) -Mock data persists to disk at `.cdk-blocks/local/data/{fullId}/` across dev server restarts. Internal data is segregated into sibling roots so it never collides with your keys: file bodies live under `content/`, metadata under `meta/`, and version history under `versions/`. Wipe with `rm -rf .cdk-blocks/local/data .bb-data`. Presigned URLs are served by the dev server at `/.bb-file-bucket/{fullId}/{path}?token=...`. Version-aware operations are available locally, with the historical delete-marker limitation described under [Versioned Bucket](#versioned-bucket). Lifecycle rules and `corsRules` have no effect locally — the dev file-server accepts browser requests from any origin, so a missing or wrong `corsRules` only shows up after deploy (see [Browser Uploads and Downloads (CORS)](#browser-uploads-and-downloads-cors)). +- **Billing:** per request plus storage; no provisioned throughput. Prices and throughput limits are in [PRODUCTION.md](./PRODUCTION.md). +- **Upload size:** FileBucket has no multipart upload: `put()` and a presigned upload each send one `PutObject` request, so S3's size limit for a single `PutObject` request applies. `put()` and `get()` hold the whole body in memory as a `Buffer`. -The dev server enforces what an upload URL signs, as S3 does: an upload whose `Content-Type` (or, when `contentLength` was signed, size) differs from the signed value fails with `403 SignatureDoesNotMatch`. Local downloads are always served with `X-Content-Type-Options: nosniff` and a `Content-Disposition` — the one signed with `attachment`, or plain `attachment` otherwise — so files never display inline in local dev even though they can on AWS (see [Serving user uploads](#serving-user-uploads)). +## Local development -When a local download URL specifies a `versionId`, only that version is served. An unknown or permanently deleted version returns HTTP 404; it never falls back to the current file. URLs without `versionId` select the current file. +- Mock data is stored under `.bb-data/{fullId}/`. +- Presigned URLs are served by the dev server at `/.bb-file-bucket/{fullId}/{path}?token=...`. +- Version-aware operations are available locally, with the historical delete-marker limitation described under [Versioned Bucket](#versioned-bucket). +- Lifecycle rules and `corsRules` have no effect locally (see [Browser Uploads and Downloads (CORS)](#browser-uploads-and-downloads-cors)). +Local downloads are always served with `X-Content-Type-Options: nosniff` and a `Content-Disposition` — the one signed with `attachment`, or plain `attachment` otherwise — so files never display inline in local dev even though they can on AWS (see [Serving user uploads](#serving-user-uploads)). +When a local download URL specifies a `versionId`, only that version is served. An unknown or permanently deleted version returns HTTP 404; it never falls back to the current file. URLs without `versionId` select the current file. From cad852a30dc5819e69e50fb6a2ba3fd5e6eb0081 Mon Sep 17 00:00:00 2001 From: Jairo Suarez Date: Wed, 18 Nov 2026 17:19:57 +0000 Subject: [PATCH 04/11] docs(bb-app-setting): document fromExisting and how a secret: true value is set The options table said `value` was not required; it is required unless `secret: true`. The README said a missing parameter throws `ParameterNotFound` in both the AWS and mock runtimes; a missing parameter throws on AWS, and an empty `secret: true` value throws on AWS and locally. `AppSetting.fromExisting` was not documented; it now has a method row and a section that says the app's role gets read access only and that `put()` on such a setting is denied on AWS although it succeeds locally. A new section on `secret: true` says the first deploy stores a random value, how to set the real value with `put()` or in the console, and that `get()` parses the stored text as JSON. Errors are one table, and the options table has a `Default` column and absorbs the "Validation Rules" list. --- packages/bb-app-setting/README.md | 173 ++++++++++++++---------------- 1 file changed, 79 insertions(+), 94 deletions(-) diff --git a/packages/bb-app-setting/README.md b/packages/bb-app-setting/README.md index e4dbe8d758..c3964cc357 100644 --- a/packages/bb-app-setting/README.md +++ b/packages/bb-app-setting/README.md @@ -2,12 +2,29 @@ A single application configuration value backed by SSM Parameter Store. -**When to use:** You need a non-sensitive configuration value (feature flag, API URL, threshold) stored as a single SSM parameter. Each `AppSetting` instance maps to exactly one parameter. +**When to use:** You need a non-sensitive configuration value (feature flag, API URL, threshold) stored as a single SSM parameter. -**When NOT to use:** For a production secret (API key, OAuth client secret, database connection string, token), use [`Secret`](../bb-secret/README.md) — it is the recommended home for credentials that protect a production app, [in line with AWS guidance](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html). `AppSetting` with `secret: true` does encrypt the value at rest and is free, so it is a fine fallback for a *low-value* secret in a prototype — but it is not the recommended place for production secrets. If you need structured key-value data with conditional writes and queries, use `KVStore`. +**When NOT to use:** For a credential that protects a production app (API key, OAuth client secret, database connection string, token), use [`Secret`](../bb-secret/README.md). `AppSetting` with `secret: true` encrypts the value at rest and is free: use it for a low-value secret in a prototype. If you need structured key-value data with conditional writes and queries, use `KVStore`. > Design & mock parity details: [DESIGN.md](./DESIGN.md) +## Quick start + +```typescript +const apiUrl = new AppSetting(scope, 'apiUrl', { + value: 'https://api.example.com', +}); + +export const api = new ApiNamespace(scope, 'api', (context) => ({ + async getApiUrl() { + return { url: await apiUrl.get() }; + }, + async setApiUrl(url: string) { + await apiUrl.put(url); + }, +})); +``` + ## API ```typescript @@ -18,6 +35,7 @@ const setting = new AppSetting(scope, id, options) |--------|---------|-------------| | `get()` | `Promise` | Read the current value. | | `put(value)` | `Promise` | Update the value at runtime. | +| `AppSetting.fromExisting(scope, id, { name, secret?, kmsKeyArn? })` | `AppSetting` | Read a parameter that is created outside the stack. See [Existing parameter](#existing-parameter-fromexisting). | **CDK layer (synth time) only** — read-only properties on the construct, for CDK code and for other Building Blocks' CDK layers. They are not on the local or Lambda runtime class. @@ -26,81 +44,78 @@ const setting = new AppSetting(scope, id, options) | `parameterName` | `string` | The SSM parameter name: the explicit `name` (always set for `fromExisting`), else the derived `/${fullId}`. The same name the runtime reads. | | `secret` | `boolean` | `true` for an SSM SecureString (`secret: true`), for created and `fromExisting` settings alike. | -For example, `Auth` reads both when an `AppSetting` is passed as an identity provider's client secret: it registers the provider against `parameterName`, so a secret with an explicit `name` or from `AppSetting.fromExisting` works, and it refuses a setting whose `secret` is `false`. +`Auth` accepts an `AppSetting` as an identity provider's client secret only when its `secret` is `true`. A setting with an explicit `name` or from `AppSetting.fromExisting` works. ### Options -| Option | Type | Required | Description | -|--------|------|----------|-------------| -| `name` | `string` | No | SSM parameter path. When omitted, derived from the scope tree as `/${fullId}`, guaranteeing uniqueness within the stack. | -| `value` | `T` | No | Initial value. Required for non-secret parameters. Must not be provided when `secret` is set. | -| `schema` | `StandardSchemaV1` | No | Runtime validation schema (Zod, Valibot, ArkType). Infers `T` from the schema. Cannot be used with `secret`. | -| `secret` | `boolean` | No | When `true`, creates an SSM SecureString encrypted with the default `aws/ssm` KMS key (or `kmsKeyArn` when set). Cannot be used with `schema` or `value`. For a production secret, prefer [`Secret`](../bb-secret/README.md) (AWS Secrets Manager) — see **When NOT to use** above. | -| `kmsKeyArn` | `string` | No | ARN of a customer-managed KMS key to encrypt the SecureString, instead of the default `aws/ssm` key. Only valid with `secret: true`. See the note below. | -| `logger` | `ChildLogger` | No | Optional logger for internal operations. When omitted, a default Logger at error level is created. | - -> **Customer-managed KMS key (`kmsKeyArn`):** Provide a CMK ARN to control the -> decrypt/grant scope of a secret (e.g. cross-account access or a dedicated key -> policy). The construct grants the shared handler `kms:Decrypt` (plus -> `kms:Encrypt` for secrets it writes) on that specific key ARN. Because AWS -> Blocks does not own a bring-your-own key, **the key's own key policy must also -> allow the app's Lambda execution role** to use it (or delegate to IAM via the -> account-root statement CDK adds to same-account keys). Adding or changing -> `kmsKeyArn` on an already-deployed secret re-encrypts its current value under -> the new key on the next deploy, so decryption keeps working. - -> **Naming:** When you omit `name`, the framework derives a unique SSM path from -> the construct scope tree (`/${fullId}`). This is the recommended approach — it -> prevents collisions across stacks automatically. If you provide an explicit -> `name`, **you** are responsible for ensuring it is unique across all stacks -> deployed to the same AWS account and region. - -### Error Handling +Pass exactly one of `value` or `secret: true`. + +| Option | Type | Default | Description | +|--------|------|---------|-------------| +| `name` | `string` | `/${fullId}` | SSM parameter path. The default is unique within the stack. An explicit `name` must be unique across all stacks in the same AWS account and Region. | +| `value` | `T` | — | Initial value. Required unless `secret: true`. Must not be provided when `secret` is set. | +| `schema` | `StandardSchemaV1` | — | Runtime validation schema (Zod, Valibot, ArkType). Infers `T` from the schema. Requires `value`. Cannot be used with `secret`. | +| `secret` | `boolean` | `false` | When `true`, creates an SSM SecureString encrypted with the default `aws/ssm` KMS key (or `kmsKeyArn` when set). The value is a plain string. Cannot be used with `schema` or `value`. See [Secret values](#secret-values-secret-true). | +| `kmsKeyArn` | `string` | `aws/ssm` key | ARN of a customer-managed KMS key to encrypt the SecureString. Only valid with `secret: true`. | +| `logger` | `ChildLogger` | error-level `Logger` | Logger for internal operations. | + +An invalid combination throws `ValidationFailed` at CDK synth, and at construction in local development. + +With `kmsKeyArn`: + +- The app's Lambda execution role is granted `kms:Decrypt`, plus `kms:Encrypt` for a secret the stack creates, on that key ARN. +- **The key's own key policy must also allow the app's Lambda execution role** to use it (or delegate to IAM via the account-root statement CDK adds to same-account keys). +- Adding or changing `kmsKeyArn` on a deployed secret re-encrypts its current value under the new key on the next deploy. + +## Errors + +Match an error by name with `isBlocksError`: ```typescript -import { AppSettingErrors, isBlocksError } from 'aws-cdk-blocks'; - -try { - await setting.put(value); -} catch (e: unknown) { - if (isBlocksError(e, AppSettingErrors.ValidationFailed)) { - // schema validation failed or value exceeds 4 KB - } - throw e; -} - -try { - const value = await setting.get(); -} catch (e: unknown) { - if (isBlocksError(e, AppSettingErrors.ParameterNotFound)) { - // the parameter is missing (e.g., deleted out-of-band) or a secret has an empty value - } - throw e; -} +import { isBlocksError } from '@aws-cdk-blocks/core'; +import { AppSettingErrors } from '@aws-cdk-blocks/bb-app-setting'; ``` -`get()` can throw `AppSettingErrors.ParameterNotFound` when the parameter does not exist or a secret parameter has an empty value (in both the AWS and mock runtimes). - -## Examples +| Constant | `error.name` | Thrown when | +|----------|--------------|-------------| +| `AppSettingErrors.ValidationFailed` | `ValidationFailedException` | `put()`: the value fails the schema, or its JSON form is over 4 KB (4,096 bytes; a `secret: true` value is not checked). Constructor: the options are an invalid combination. | +| `AppSettingErrors.ParameterNotFound` | `ParameterNotFoundException` | `get()`: the parameter does not exist or has no value (AWS), or a `secret: true` value is an empty string (AWS and local). | -### Plain String Setting +## Secret values (`secret: true`) ```typescript -// Recommended: let the framework manage the SSM name (unique by default) -const apiUrl = new AppSetting(scope, 'apiUrl', { - value: 'https://api.example.com', +const stripeKey = new AppSetting(scope, 'stripeKey', { + secret: true, }); export const api = new ApiNamespace(scope, 'api', (context) => ({ - async getApiUrl() { - return { url: await apiUrl.get() }; - }, - async setApiUrl(url: string) { - await apiUrl.put(url); + async charge(amount: number) { + const key = await stripeKey.get(); // decrypted from SSM SecureString + // use key... }, })); ``` +- The first deploy stores a random value (32 random bytes, base64url). Later deploys keep the stored value. +- Set the real value with `put()`, or in the AWS console: the deployed app's `/cdk-blocks/settings` route redirects to the stack's settings resource group, which lists the parameter. +- `get()` parses the stored text as JSON and falls back to the raw text. A console value that is valid JSON (`12345`, `true`) is returned as a number or boolean: set such a value with `put()`, which stores it as a JSON string (shown in the console with double quotes). +- Locally the value is a random string in `.bb-data/settings.json`. Edit the file to change it; the next `get()` reads it. + +## Existing parameter (`fromExisting`) + +`AppSetting.fromExisting` reads a parameter that something else creates, for example a connection string stored by `npm run db -- connect --stage`. + +```typescript +const dbUrl = AppSetting.fromExisting(scope, 'db-url', { name: '/my-app/db-url', secret: true }); +``` + +- The stack does not create, seed, tag or delete the parameter. +- The app's role gets read access only: `ssm:GetParameter`, plus `kms:Decrypt` with `secret: true`. Do not call `put()` on it: the role has no `ssm:PutParameter`, so the write is denied on AWS, although it succeeds locally. +- The parameter must exist before the app runs. If it does not, the deploy succeeds and `get()` throws `ParameterNotFound`. +- Locally the value is the entry under the setting's `fullId` in `.bb-data/settings.json`: a random string with `secret: true`, an empty string otherwise. Edit the file to set it. + +## Examples + ### Typed Object with Schema ```typescript @@ -121,28 +136,10 @@ export const api = new ApiNamespace(scope, 'api', (context) => ({ })); ``` -### Secret - -```typescript -const stripeKey = new AppSetting(scope, 'stripeKey', { - secret: true, -}); - -export const api = new ApiNamespace(scope, 'api', (context) => ({ - async charge(amount: number) { - const key = await stripeKey.get(); // decrypted from SSM SecureString - // use key... - }, -})); -``` - ### Explicit Name (Cross-Service Reads) Use an explicit `name` when the SSM parameter must be read by other services or follow a well-known path convention. -> ⚠️ You must ensure this name is unique across all stacks deployed to the -> same AWS account and region to avoid collisions. - ```typescript const apiUrl = new AppSetting(scope, 'apiUrl', { name: '/my-app/production/api-url', @@ -150,25 +147,13 @@ const apiUrl = new AppSetting(scope, 'apiUrl', { }); ``` -## Validation Rules - -These are enforced at CDK synth time and in local development (the mock rejects the same combinations at construction): - -- `secret` + `schema` → error (secrets are plain strings) -- `schema` without `value` → error (parameter needs a valid initial value) -- `secret` with `value` → error (don't put secrets in source code) -- Non-secret without `value` → error (settings require an initial value) - -## Scaling & Cost (AWS) +## Scaling and cost (AWS) - **String parameters:** Standard tier, free, 4 KB limit, 10,000 per account/region -- **SecureString parameters:** Standard tier, free, encrypted with `aws/ssm` KMS key +- **SecureString parameters:** Standard tier, free - **Throughput:** 40 TPS default for GetParameter (can be increased) - **Latency:** Single-digit ms reads and writes -## Local Development - -Mock data persists to disk in the shared `.cdk-blocks/local/data/settings.json`, keyed by the setting's `fullId` (the file `Secret` uses too), across dev server restarts. Wipe with `rm -rf .cdk-blocks/local/data .bb-data`. Secrets generate a random value locally (no KMS encryption in mock mode). - - +## Local development +Local values are in the shared `.bb-data/settings.json` (the file `Secret` uses too), keyed by the setting's `fullId`. A `secret: true` setting gets a random value locally (no KMS encryption in mock mode). From 9593f8f25e134de077b2a0e31975140de8676853 Mon Sep 17 00:00:00 2001 From: Jairo Suarez Date: Wed, 18 Nov 2026 17:19:57 +0000 Subject: [PATCH 05/11] docs(bb-secret): one errors table with NotSupported; state the cache scope of put() `SecretErrors.NotSupported` was mentioned only for browser code; the errors table now also lists the deployed case of a `Secret` with no registered secret ARN. The rotation note now says that `put()` clears the cache of the calling instance only, and that other running instances read the new value once their cache entry expires (`cacheTtlSeconds`). Errors are one `## Errors` table, and the options table has a `Default` column instead of `Required`. "Managing secret values" opens with the scenario table, and "Scaling & cost (AWS)" is split into `## What it provisions (AWS)` and `## Scaling and cost (AWS)`. A quick start replaces the "Manually-configured credential" example. --- packages/bb-secret/README.md | 195 ++++++++++++++++------------------- 1 file changed, 88 insertions(+), 107 deletions(-) diff --git a/packages/bb-secret/README.md b/packages/bb-secret/README.md index 2550817ce5..dc5236c286 100644 --- a/packages/bb-secret/README.md +++ b/packages/bb-secret/README.md @@ -2,16 +2,28 @@ A single application secret backed by AWS Secrets Manager. -**When to use:** You need to store a high-value credential — a third-party API key, OAuth client secret, database connection string, webhook signing key, or encryption key. Each `Secret` instance maps to exactly one Secrets Manager secret. +**When to use:** You need to store a high-value credential — a third-party API key, OAuth client secret, database connection string, webhook signing key, or encryption key. Use `Secret` for any credential that protects a production app. -**When NOT to use:** For non-sensitive configuration (feature flags, API URLs, thresholds) use [`AppSetting`](../bb-app-setting/README.md) — it is free for standard values. For application state, use `KVStore`. - -> **`Secret` is the recommended home for production secrets.** For any credential that protects a production app — a database connection string, API key, OAuth token, or private key — use `Secret`. It is purpose-built for secrets: a dedicated per-secret resource with its own access controls, cross-account sharing, and version history. This mirrors [AWS's own guidance](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html) on where credentials belong. -> -> `AppSetting` with `secret: true` also encrypts the value at rest and is free, so it is a reasonable choice for a *low-value* secret in a prototype, or when you want to avoid the per-secret cost. But for anything protecting a production app, reach for `Secret`. +**When NOT to use:** For non-sensitive configuration (feature flags, API URLs, thresholds) use [`AppSetting`](../bb-app-setting/README.md) — it is free for standard values. For a low-value secret in a prototype, `AppSetting` with `secret: true` is free and encrypts the value at rest. For application state, use `KVStore`. > Design & mock/AWS parity details: [DESIGN.md](./DESIGN.md) +## Quick start + +```typescript +const stripeKey = new Secret(scope, 'stripe-api-key'); + +export const api = new ApiNamespace(scope, 'api', (context) => ({ + async charge(amount: number) { + const key = await stripeKey.get(); + if (key === null) throw new Error('Stripe key not configured'); + // use key... + }, +})); +``` + +The secret starts empty. Set the value after deploy: see [Managing secret values](#managing-secret-values). + ## API ```typescript @@ -21,27 +33,25 @@ const secret = new Secret(scope, id, options?) | Method | Returns | Description | |--------|---------|-------------| | `get(options?)` | `Promise` | Read the value. `null` when unset/missing. `options.version` selects `'current'` (default), `'previous'`, or a `SecretVersion` from `listVersions()`. | -| `put(value)` | `Promise` | Set or update the value at runtime. **Only present when the secret was created with `allowRuntimeWrite: true`** — otherwise it is absent from the object (and the type). The prior value becomes the `'previous'` version. | +| `put(value)` | `Promise` | Set or update the value at runtime. Present only when the secret was created with `allowRuntimeWrite: true`; otherwise it is absent from the object and the type. The prior value becomes the `'previous'` version. | | `listVersions()` | `Promise` | List retained versions (metadata only, newest first — never values). | | `Secret.fromExisting(arn)` | `ExternalSecretRef` | Reference an existing Secrets Manager secret (static). Pass to `options.secret`. | ### Options -| Option | Type | Required | Description | -|--------|------|----------|-------------| -| `name` | `string` | No | Explicit Secrets Manager secret name. When omitted, derived from the scope tree (unique per stack). Provide a well-known name when a team/CI pipeline sets or rotates the value out-of-band via the `aws` CLI. You own uniqueness across the account/region when set. Ignored for `fromExisting`. | -| `allowRuntimeWrite` | `boolean` | No | **Defaults to `false`.** When `false`/omitted the secret is **read-only at runtime**: no `put()` method on the object, and the execution role gets read-only IAM (no `PutSecretValue`). Set `true` only when the app sets/rotates the value itself at runtime — then `put()` is present and write IAM is granted. Applies to every secret, including `fromExisting`. | -| `schema` | `StandardSchemaV1` | No | Runtime validation schema (Zod, Valibot, ArkType). Infers `T`, treats the stored value as JSON, and validates on `get()`/`put()`. Omit for an opaque `string`. | -| `secret` | `ExternalSecretRef` | No | Wrap an existing Secrets Manager secret from `Secret.fromExisting(arn)` instead of creating one. | -| `generate` | `boolean` | No | When `true`, seed a random value on first create (for a signing/HMAC key that only needs to exist). Otherwise the secret starts empty and `get()` returns `null` until set. Don't combine with `schema`. | -| `cacheTtlSeconds` | `number` | No | How long the runtime reuses a cached value before re-fetching. **Defaults to 300s (5 min)**, matching the AWS Secrets Manager agent — a bounded default so a long-running process can't serve a rotated value indefinitely. Raise it to cut fetches, lower it for fresher reads, or set `0` to disable caching. `put()` always clears the cache. Ignored by the mock. | -| `removalPolicy` | `'destroy' \| 'retain'` | No | Override the stack-wide removal default for the created secret. Ignored by the mock and when wrapping an existing secret. | -| `logger` | `ChildLogger` | No | Optional logger for internal operations. Defaults to an error-level logger. | +| Option | Type | Default | Description | +|--------|------|---------|-------------| +| `name` | `string` | derived from the scope tree | Explicit Secrets Manager secret name. The default is unique per stack. Provide a well-known name when a team/CI pipeline sets or rotates the value out-of-band via the `aws` CLI. You own uniqueness across the account/region when set. Ignored for `fromExisting`. | +| `allowRuntimeWrite` | `boolean` | `false` | When `false` the secret is read-only at runtime: no `put()` method on the object, and the execution role gets read-only IAM (no `PutSecretValue`). Set `true` only when the app sets/rotates the value itself at runtime — then `put()` is present and write IAM is granted. Applies to every secret, including `fromExisting`. | +| `schema` | `StandardSchemaV1` | — | Runtime validation schema (Zod, Valibot, ArkType). Infers `T`, treats the stored value as JSON, and validates on `get()`/`put()`. Omit for an opaque `string`. | +| `secret` | `ExternalSecretRef` | — | Wrap an existing Secrets Manager secret from `Secret.fromExisting(arn)` instead of creating one. | +| `generate` | `boolean` | `false` | When `true`, seed a random value on first create (for a signing/HMAC key that only needs to exist). Otherwise the secret starts empty and `get()` returns `null` until set. Don't combine with `schema`. | +| `cacheTtlSeconds` | `number` | `300` | Seconds the runtime reuses a cached value before re-fetching. `0` disables caching. `put()` clears the cache. Ignored by the mock. | +| `removalPolicy` | `'destroy' \| 'retain'` | stack `defaults` | Override the stack-wide removal default for the created secret. Ignored by the mock and when wrapping an existing secret. | +| `logger` | `ChildLogger` | error-level logger | Logger for internal operations. | ### Read-only by default (`allowRuntimeWrite`) -A `Secret` is **read-only at runtime unless you opt in**. By default the instantiated object exposes only `get()` and `listVersions()` — there is no `put()` (a call is a compile error), and the deployed execution role is granted read-only IAM. This is least-privilege: most apps read a credential that is set out-of-band (console, `aws` CLI, or CI), so the running app never needs write access. - ```typescript // Read-only (default): no put(). Set the value out-of-band, read it with get(). const stripeKey = new Secret(scope, 'stripe-api-key'); @@ -54,44 +64,29 @@ const token = new Secret(scope, 'self-rotating-token', { allowRuntimeWrite: true await token.put('t-abc123'); ``` -This also applies to a secret wrapped via `fromExisting` — it is read-only unless you pass `allowRuntimeWrite: true`. +## Errors -### Error handling +Match an error by name with `isBlocksError`: ```typescript -import { isBlocksError, Secret, SecretErrors } from 'aws-cdk-blocks'; - -const secret = new Secret(scope, 'api-key', { allowRuntimeWrite: true }); - -try { - await secret.put(value); -} catch (e: unknown) { - if (isBlocksError(e, SecretErrors.ValidationFailed)) { - // schema validation failed - } - if (isBlocksError(e, SecretErrors.SecretNotFound)) { - // the underlying Secrets Manager secret does not exist - } - throw e; -} +import { isBlocksError } from '@aws-cdk-blocks/core'; +import { SecretErrors } from '@aws-cdk-blocks/bb-secret'; ``` -A `ValidationFailed` error's message is fixed and never contains the secret value or the schema library's issue text, because schema libraries often quote the received value and the message reaches the client. It doesn't name the failing field either, because a record or map schema reports the value's own keys as the path: the message is always `ValidationFailedException: The secret value did not match the schema`. The original issues and the first failing path stay on the error's non-enumerable `cause` (`cause.issues`, `cause.path`) for server-side logging. - -`get()` returns `null` for a missing value rather than throwing, so a missing secret is normal control flow, not an exception: - -```typescript -const key = await stripeKey.get(); -if (key === null) throw new Error('Stripe key not configured'); -``` +| Constant | `error.name` | Thrown when | +|----------|--------------|-------------| +| `SecretErrors.ValidationFailed` | `ValidationFailedException` | With a `schema`: `put()` is given a value that fails the schema, or `get()` reads a stored value that fails the schema or is not valid JSON. | +| `SecretErrors.SecretNotFound` | `ResourceNotFoundException` | `put()` on AWS: the Secrets Manager secret does not exist. | +| `SecretErrors.NotSupported` | `NotSupportedException` | `Secret` is instantiated in browser/client code (it runs server-side only), or a deployed `Secret` has no registered secret ARN. | -On AWS that `null` is cached like any other value, so a value set afterwards is seen once the cache entry expires (`cacheTtlSeconds`). +- `get()` returns `null` for a missing value; it does not throw. On AWS that `null` is cached like any other value, so a value set afterwards is seen once the cache entry expires (`cacheTtlSeconds`). +- A schema failure's message is always `ValidationFailedException: The secret value did not match the schema`. It never contains the secret value, the failing field or the schema library's issue text. The original issues and the first failing path are on the error's non-enumerable `cause` (`cause.issues`, `cause.path`) for server-side logging. ## Examples ### Auto-generated signing key (the app creates the value) -Pass `generate: true` and never set a value — Secrets Manager creates a random one on first deploy (the mock seeds an equivalent value locally). Good for a JWT/session signing key or HMAC key, where the app generates the secret and nobody needs to read it. +Use `generate: true` for a JWT/session signing key or HMAC key that nobody needs to read. ```typescript const signingKey = new Secret(scope, 'session-signing-key', { generate: true }); @@ -108,29 +103,6 @@ export const api = new ApiNamespace(scope, 'api', (context) => ({ > > If the app also rotates the key itself, add `allowRuntimeWrite: true` and call `put()` with the new key — see [Reading an earlier version](#reading-an-earlier-version-rotation-grace-window) for the complete pattern. -### Manually-configured credential (you set an externally-issued value) - -A third-party key (Stripe, an OAuth client secret) is **not** auto-generated — you set it out-of-band after deploy. The declaration is the same; the difference is that someone provides the value. - -```typescript -const stripeKey = new Secret(scope, 'stripe-api-key'); - -export const api = new ApiNamespace(scope, 'api', (context) => ({ - async charge(amount: number) { - const key = await stripeKey.get(); - if (key === null) throw new Error('Stripe key not configured'); - // use key... - }, -})); -``` - -Set the value once — via the settings console route, a deploy script, or the AWS CLI (see "Managing secret values"). If the app itself updates the value at runtime, create the secret with `allowRuntimeWrite: true` and call `put()`: - -```typescript -const stripeKey = new Secret(scope, 'stripe-api-key', { allowRuntimeWrite: true }); -await stripeKey.put('sk_live_...'); -``` - ### Typed JSON secret with schema validation ```typescript @@ -162,19 +134,22 @@ AWS CDK Blocks will not create, seed, or delete the referenced secret — it onl ## Managing secret values -A `Secret` declaration carries only the *name* — never the value. How you set the value depends on how centrally the secret is managed. There are three complementary approaches: +The declaration never holds the value: the constructor takes none, and a secret cannot be seeded from source code or an environment variable. Set the value one of these ways: -### 1. Auto-generated (random) — no value to set - -Pass `generate: true` and never call `put()`: the secret is created with a **random value** on first deploy (the mock seeds an equivalent value locally). Use this for opaque values nobody needs to know — session signing keys, HMAC keys. Read it with `get()`; it is stable across redeploys. Without `generate: true` the secret starts empty and `get()` returns `null` until you set a value. +| Scenario | Approach | +|----------|----------| +| An opaque value nobody needs to read | `generate: true` — nothing to set; the value is stable across redeploys | +| A normal app, set the value once after deploy | [Settings route and console](#settings-route-and-console) | +| Scripted / CI/CD-driven provisioning | [Well-known `name` and the `aws` CLI](#well-known-name-and-the-aws-cli) | +| Centrally-managed credential shared across many app installations | `fromExisting(arn)` — reference it; the app never owns or sets it | -### 2. Set via the settings endpoint → console — the default for most apps +### Settings route and console -Every AWS CDK Blocks app exposes a built-in **`/cdk-blocks/settings`** route. Deployed, it redirects to the stack's *settings* resource group in the AWS console, where your `Secret` values appear alongside your `AppSetting` parameters — set or rotate them in the console UI. Locally, the same route opens `.cdk-blocks/local/data/settings.json`, where secret values live next to settings (plaintext, dev-only). One route, one place, local and deployed. +Every AWS CDK Blocks app exposes a built-in `/cdk-blocks/settings` route. Deployed, it redirects to the stack's *settings* resource group in the AWS console, where your `Secret` values appear alongside your `AppSetting` parameters — set or rotate them in the console UI. Locally, the same route opens `.bb-data/settings.json`, where secret values live next to settings (plaintext, dev-only). -### 3. Well-known `name` + the `aws` CLI — for CI/CD-driven workflows +### Well-known `name` and the `aws` CLI -If your deployment model is scripted, give the secret an explicit, stable `name` and set/rotate it with the standard AWS CLI. The value travels machine → Secrets Manager over the AWS API; it never enters source, git, or the CloudFormation template. +Give the secret an explicit, stable `name` and set/rotate it with the standard AWS CLI. ```typescript const stripeKey = new Secret(scope, 'stripe-key', { name: 'my-app/stripe-key' }); @@ -192,29 +167,27 @@ printf '%s' "$STRIPE_KEY" \ aws secretsmanager describe-secret --secret-id my-app/stripe-key ``` -The Blocks app **creates** the secret (empty/random) when you deploy, so the value is set against a secret that already exists — run the CLI once the secret exists. The exact sequencing in your pipeline is up to you. Re-running `put-secret-value` overwrites (rotation); running instances pick up the new value once their cached copy expires (`cacheTtlSeconds`, default 300 s). Write to the **same region** the app deploys to, or reads see an unset secret. +- Run the CLI after the first deploy: the deploy creates the secret. +- Re-running `put-secret-value` overwrites the value. Running instances pick up the new value once their cached copy expires (`cacheTtlSeconds`). +- Write to the same region the app deploys to, or reads see an unset secret. Without an explicit `name`, the secret name is derived from the scope tree; find it in the settings resource group, the console, or `aws secretsmanager list-secrets`. ### As an `Auth` provider secret -A string-valued `Secret` can be the `clientSecret` (or Sign in with Apple's `privateKey`) of an `Auth` provider. For a provider that federates through Cognito (a social or `type: 'oidc'` entry on `Auth`'s default store), the deploy reads the value and registers it with the user pool, so set the value and **deploy again** for a new value to take effect — and give the secret `generate: true`, so the first deploy has a placeholder value to register. See the `Auth` README's social sign-in recipe (`@aws-cdk-blocks/bb-auth`). +A string-valued `Secret` can be the `clientSecret` (or Sign in with Apple's `privateKey`) of an `Auth` provider. For a provider that federates through Cognito (a social or `type: 'oidc'` entry on `Auth`'s default store), the deploy reads the value and registers it with the user pool: -### Rotating & removing +1. Declare the secret with `generate: true`, so the first deploy has a placeholder value to register. +2. Deploy. +3. Set the value. +4. Deploy again. A new value takes effect only after a deploy. -- **Rotate:** set a new value (console or `put-secret-value`); a warm runtime that already cached the old value picks up the change once its cache entry expires (`cacheTtlSeconds`, default 300 s) — no redeploy needed. (A `put()` from within the app clears that instance's cache immediately.) -- **Remove:** `aws secretsmanager delete-secret --secret-id ` (recoverable by default; `--force-delete-without-recovery` to skip the recovery window). +See the `Auth` README's social sign-in recipe (`@aws-cdk-blocks/bb-auth`). -### Which approach, when - -| Scenario | Approach | -|----------|----------| -| Centrally-managed credential shared across **many** app installations | `fromExisting(arn)` — reference it; the app never owns or sets it | -| A normal app, set the value once after deploy | **Settings endpoint → console** (approach 2) | -| Scripted / CI/CD-driven provisioning | Well-known `name` + `aws` CLI (approach 3) | -| An opaque value nobody needs to read | Auto-generated (approach 1) | +### Rotating & removing -> There is intentionally **no** way to seed a secret's value from source code or an environment variable through the constructor — a literal in source would land in git and the template, and env-seeding is kept out of the declaration (consistent with how hosting `secret()` separates *declare* from *set*). Set values out-of-band via the console or CLI. +- **Rotate:** set a new value (console, `put-secret-value`, or `put()` from within the app). No redeploy is needed. A running instance that cached the old value reads the new one once its cache entry expires (`cacheTtlSeconds`); `put()` clears the cache of the instance that calls it only. +- **Remove:** `aws secretsmanager delete-secret --secret-id ` (recoverable for 30 days by default; `--force-delete-without-recovery` to skip the recovery window). ## Reading an earlier version (rotation grace window) @@ -263,11 +236,14 @@ async function isValidSignature(payload: string, signature: string): Promise` (join the settings resource group); `fromExisting` secrets are not tagged. -## Scaling & cost (AWS) +## Scaling and cost (AWS) - **Billing:** $0.40 per secret per month (prorated hourly) + $0.05 per 10,000 API calls. No free tier. -- **Latency:** low-tens-of-ms per API call; the runtime caches the fetched value in-process, so steady-state reads hit the cache, not the API. A cached value is held for `cacheTtlSeconds` — **default 5 minutes** (matching the AWS Secrets Manager agent) — so a rotated value is picked up within the TTL even on a long-running process; raise it to cut fetches, or set `0` to disable caching. -- **Throughput:** GetSecretValue scales to thousands of requests/sec per account (default quotas, raisable). Reads are the hot path; `put()` is rare. +- **Latency:** low-tens-of-ms per API call. The runtime caches the fetched value in-process for `cacheTtlSeconds`, so steady-state reads hit the cache, not the API. +- **Throughput:** GetSecretValue scales to thousands of requests/sec per account (default quotas, raisable). - **Value size limit:** 64 KB per secret value. -- **Version history:** `listVersions()` returns the **labeled** versions — current + previous. Secrets Manager retains additional unlabeled versions internally (until >100, never removing any created in the last 24h), but the BB surfaces only current/previous; reach for the AWS SDK for deeper history. -- **Encryption:** KMS at rest, using the default `aws/secretsmanager` key. -- **IAM:** the construct grants the shared execution role `secretsmanager:GetSecretValue` + `ListSecretVersionIds` scoped to the single secret (not a wildcard). `PutSecretValue` is granted **only** when `allowRuntimeWrite: true` — the default is read-only. KMS grants Secrets Manager attaches as needed. -- **Deletion:** recoverable by default (30-day recovery window); `--force-delete-without-recovery` to delete immediately. -- Removal policy follows the stack-wide `defaults` (production retains, sandbox destroys); override per-instance with `removalPolicy`. BB-created secrets are tagged `aws-blocks-stack=` (join the settings resource group); `fromExisting` secrets are not tagged. +- **Version history:** `listVersions()` returns the labeled versions — current + previous. Secrets Manager retains additional unlabeled versions internally (until >100, never removing any created in the last 24h). ## Local development -The mock stores the current value as **plaintext** in the shared `.cdk-blocks/local/data/settings.json` (the same file `AppSetting` uses, keyed by the secret's `name` or `fullId`) and logs a one-time warning. This is why the local `/cdk-blocks/settings` route surfaces secrets alongside settings. The previous value (for `get({ version: 'previous' })` / `listVersions()`) is kept in a small `.cdk-blocks/local/data/secret-versions.json` sidecar — current + previous only; deeper history is an AWS-only capability. It is **not** secure — never use real credentials in local development. Wipe with `rm -rf .cdk-blocks/local/data .bb-data`. +- The mock stores the current value as plaintext in the shared `.bb-data/settings.json` (the same file `AppSetting` uses) and logs a one-time warning. Never use real credentials in local development. +- The key in that file is the secret's `name` when you pass one, otherwise its `fullId` (for example `new Secret(new Scope('my-app'), 'stripe-key')` is stored under `my-app-stripe-key`). +- The previous value (for `get({ version: 'previous' })` / `listVersions()`) is kept in `.bb-data/secret-versions.json` — current + previous only. +- The mock has no cache: every `get()` reads `.bb-data/settings.json` again, so a value written to that file reaches the next call without a restart. +- Wipe with `rm -rf .bb-data`. -The mock has no cache: every `get()` reads `.cdk-blocks/local/data/settings.json` again, so a value written to that file reaches the next call without a restart. The key is the secret's `name` when you pass one, otherwise its `fullId` (for example `new Secret(new Scope('my-app'), 'stripe-key')` is stored under `my-app-stripe-key`). To simulate an externally set secret in a local test, add the value under that key, keeping the entries already in the file — for the secret declared with `{ name: 'my-app/stripe-key' }` above: +To simulate an externally set secret in a local test, add the value under that key, keeping the entries already in the file — for the secret declared with `{ name: 'my-app/stripe-key' }` above: ```json { "my-app/stripe-key": "sk_test_123" } @@ -301,8 +284,6 @@ The mock has no cache: every `get()` reads `.cdk-blocks/local/data/settings.json Delete the key to simulate an unset secret (`get()` returns `null`). A value written this way replaces only the current value — it is not recorded as a version, so to exercise `get({ version: 'previous' })` locally, rotate with `put()`. A `generate: true` secret seeds its random value only when its key is absent, so a value you write before the backend starts is kept. -`Secret` runs server-side only. Importing and instantiating it in browser/client code throws `SecretErrors.NotSupported` — a secret read in the browser would expose it to the client. - ## Keys AWS CDK Blocks generates for its own blocks -Keys that AWS CDK Blocks generates for its own blocks are created through an internal part of this package. Where they are stored follows the stack's `defaults.secretsStore`: a `Secret` in Secrets Manager (`'secrets-manager'`, the production preset) or an `AppSetting` SSM SecureString (`'ssm'`, the sandbox preset). This covers the `Auth` session secret and the `Realtime` connection token key. That internal part is for AWS CDK Blocks' own blocks only and is not a public API; it does not change the defaults of a `Secret` you declare. +AWS CDK Blocks stores the keys it generates for its own blocks (the `Auth` session secret and the `Realtime` connection token key) where the stack's `defaults.secretsStore` says: a `Secret` in Secrets Manager (`'secrets-manager'`, the production preset) or an `AppSetting` SSM SecureString (`'ssm'`, the sandbox preset). The setting does not change the defaults of a `Secret` you declare. From 398b3f60c7a0a15ee8ae210936657d0a04dd0bc6 Mon Sep 17 00:00:00 2001 From: Jairo Suarez Date: Thu, 19 Nov 2026 18:11:37 +0000 Subject: [PATCH 06/11] docs: changeset for the data block README revisions --- .changeset/docs-readme-data-blocks.md | 42 +++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 .changeset/docs-readme-data-blocks.md diff --git a/.changeset/docs-readme-data-blocks.md b/.changeset/docs-readme-data-blocks.md new file mode 100644 index 0000000000..8c039c840b --- /dev/null +++ b/.changeset/docs-readme-data-blocks.md @@ -0,0 +1,42 @@ +--- +"@aws-cdk-blocks/bb-kv-store": patch +"@aws-cdk-blocks/bb-database": patch +"@aws-cdk-blocks/bb-file-bucket": patch +"@aws-cdk-blocks/bb-app-setting": patch +"@aws-cdk-blocks/bb-secret": patch +"aws-cdk-blocks": patch +--- + +docs(bb-kv-store, bb-database, bb-file-bucket, bb-app-setting, bb-secret): the READMEs of the data blocks correct their errors tables and document counters in `KVStore`, `AppSetting.fromExisting` and how a `secret: true` setting gets its value. + +**`KVStore`** + +- Corrected: for a transaction the README named two packages that do not exist; it names `transaction()` on `Database`. +- Added: there is no atomic increment. The conditional-writes section gives two ways to keep a concurrent counter: a `get()` and conditional `put()` loop (`ifNotExists: true` for a new item, otherwise `ifValueEquals` or `ifFieldEquals`, retry on `KVStoreErrors.ConditionalCheckFailed`, no expiry on the counter), or one item per event aggregated with `query()`. +- Added: a `Default` column in the options table. The errors table follows the options, and `scan` has its own section. +- Removed: "Best practices" and "Scaling and cost (AWS)" items that repeated earlier sections. + +**`Database`** + +- Corrected: the errors table lists each `DatabaseErrors` constant with the `error.name` the caller sees (`QueryFailedException`, not `QueryFailed`). +- Added: a table of the `transaction()` options (`retryOnConflict`, `maxRetries`, `signal`), `Default` columns in the options tables, and a second table for the four errors that are not for `catch`. +- Moved: `npm run db` is documented once, in `## Command line`, which says which commands apply to a block that provisions its cluster and which to an existing database, and that a command with `--block` refuses `--name`. The steps to move or rename a block are their own section. "Migrations" has one subsection per target. `## Local mode` is now `## Local development`. + +**`FileBucket`** + +- Corrected: no method throws `FileBucketErrors.FileNotFound` or `FileBucketErrors.FileTooLarge`. `get()` returns `null` for a missing file, and an upload over `maxUploadBytes` throws `ValidationFailed`, which has no `FileBucketErrors` constant and is matched with `isBlocksError(e, 'ValidationFailed')`. +- Corrected: the method table says when to return a download or upload handle and when a raw presigned URL; two bullets gave opposite advice. +- Added: a quick start, the `FileBucket.fromKmsKey(keyArn)` row, tables for `FileContent`, `FileInfo`, `FileDownloadClient` and `FileUploadClient`, a `Default` column in the options table, and a `## Scaling and cost (AWS)` section: an upload is one `PutObject` request, with no multipart upload. +- Removed: the "Best Practices" list, the Batch Delete example, and the on-disk layout of the local mock (it is in `DESIGN.md`). + +**`AppSetting`** + +- Corrected: `value` is required unless `secret: true`. A missing parameter throws `ParameterNotFound` on AWS only; an empty `secret: true` value throws on AWS and locally. A `secret: true` value is not checked against the 4 KB limit. +- Added: `AppSetting.fromExisting`, with a section: the stack does not create the parameter, the app's role can only read it, and `put()` is denied on AWS although it succeeds locally. +- Added: a section on `secret: true`: the first deploy stores a random value; set the real one with `put()` or in the console; `get()` parses the stored text as JSON, so a console value such as `12345` comes back as a number. + +**`Secret`** + +- Corrected: `SecretErrors.NotSupported` is also thrown by a deployed `Secret` that has no registered secret ARN, not only in browser code. +- Corrected: `put()` clears the cache of the instance that calls it only; other running instances read the new value once their cache entry expires (`cacheTtlSeconds`). +- Added: one errors table, a `Default` column in the options table, a quick start, and a separate `## What it provisions (AWS)` section. From 299baf64645f63b3dd014e537e022af347514c3c Mon Sep 17 00:00:00 2001 From: Jairo Suarez Date: Thu, 19 Nov 2026 18:37:35 +0000 Subject: [PATCH 07/11] docs(app-setting): restrict example writes and clarify imported permissions --- .changeset/docs-readme-data-blocks.md | 2 +- packages/bb-app-setting/README.md | 41 ++++++++++++++------------- 2 files changed, 23 insertions(+), 20 deletions(-) diff --git a/.changeset/docs-readme-data-blocks.md b/.changeset/docs-readme-data-blocks.md index 8c039c840b..4773aaec2c 100644 --- a/.changeset/docs-readme-data-blocks.md +++ b/.changeset/docs-readme-data-blocks.md @@ -32,7 +32,7 @@ docs(bb-kv-store, bb-database, bb-file-bucket, bb-app-setting, bb-secret): the R **`AppSetting`** - Corrected: `value` is required unless `secret: true`. A missing parameter throws `ParameterNotFound` on AWS only; an empty `secret: true` value throws on AWS and locally. A `secret: true` value is not checked against the 4 KB limit. -- Added: `AppSetting.fromExisting`, with a section: the stack does not create the parameter, the app's role can only read it, and `put()` is denied on AWS although it succeeds locally. +- Added: `AppSetting.fromExisting` does not create the parameter or grant write access. The mock permits `put()`; on AWS, it can overwrite the parameter if another policy allows the write. For an imported SecureString, the external owner manages re-encryption. - Added: a section on `secret: true`: the first deploy stores a random value; set the real one with `put()` or in the console; `get()` parses the stored text as JSON, so a console value such as `12345` comes back as a number. **`Secret`** diff --git a/packages/bb-app-setting/README.md b/packages/bb-app-setting/README.md index c3964cc357..6c283190d6 100644 --- a/packages/bb-app-setting/README.md +++ b/packages/bb-app-setting/README.md @@ -11,18 +11,18 @@ A single application configuration value backed by SSM Parameter Store. ## Quick start ```typescript +const auth = new Auth(scope, 'auth', { users: { groups: ['admin'] } }); const apiUrl = new AppSetting(scope, 'apiUrl', { value: 'https://api.example.com', }); -export const api = new ApiNamespace(scope, 'api', (context) => ({ - async getApiUrl() { - return { url: await apiUrl.get() }; - }, - async setApiUrl(url: string) { - await apiUrl.put(url); - }, -})); +export const api = auth.protect(scope, 'api', { + methods: () => ({ + async getApiUrl() { + return { url: await apiUrl.get() }; + }, + }), +}); ``` ## API @@ -64,8 +64,8 @@ An invalid combination throws `ValidationFailed` at CDK synth, and at constructi With `kmsKeyArn`: - The app's Lambda execution role is granted `kms:Decrypt`, plus `kms:Encrypt` for a secret the stack creates, on that key ARN. -- **The key's own key policy must also allow the app's Lambda execution role** to use it (or delegate to IAM via the account-root statement CDK adds to same-account keys). -- Adding or changing `kmsKeyArn` on a deployed secret re-encrypts its current value under the new key on the next deploy. +- The key policy must authorize the app's execution role. For a stack-created secret, it must also authorize the secret initializer's role (or delegate to IAM). +- For a stack-created secret, changing `kmsKeyArn` re-encrypts its current value on deploy. For an imported secret, its owner must change the encryption key; this option only changes the app's grant. ## Errors @@ -110,7 +110,7 @@ const dbUrl = AppSetting.fromExisting(scope, 'db-url', { name: '/my-app/db-url', ``` - The stack does not create, seed, tag or delete the parameter. -- The app's role gets read access only: `ssm:GetParameter`, plus `kms:Decrypt` with `secret: true`. Do not call `put()` on it: the role has no `ssm:PutParameter`, so the write is denied on AWS, although it succeeds locally. +- The construct grants `ssm:GetParameter` and, with `secret: true`, `kms:Decrypt`. It does not grant or deny `ssm:PutParameter`. Do not call `put()` on an imported setting: the mock permits it, and on AWS it can overwrite the parameter if another policy grants write access. - The parameter must exist before the app runs. If it does not, the deploy succeeds and `get()` throws `ParameterNotFound`. - Locally the value is the entry under the setting's `fullId` in `.bb-data/settings.json`: a random string with `secret: true`, an empty string otherwise. Edit the file to set it. @@ -126,14 +126,17 @@ const config = new AppSetting(scope, 'config', { schema: z.object({ maxRetries: z.number(), timeout: z.number() }), }); -export const api = new ApiNamespace(scope, 'api', (context) => ({ - async getConfig() { - return await config.get(); // { maxRetries: number; timeout: number } - }, - async updateConfig(cfg: { maxRetries: number; timeout: number }) { - await config.put(cfg); // validated against schema - }, -})); +// Only members of the admin group can read or change this configuration. +export const settingsAdmin = auth.protect(scope, 'settingsAdmin', { + methods: () => ({ + async getConfig() { + return config.get(); + }, + async updateConfig(cfg: { maxRetries: number; timeout: number }) { + await config.put(cfg); // validated against the schema after authorization + }, + }), +}, { role: 'admin' }); ``` ### Explicit Name (Cross-Service Reads) From 32386bf38ae610b86b46c86754b4dc10321eee1c Mon Sep 17 00:00:00 2001 From: Jairo Suarez Date: Thu, 19 Nov 2026 18:52:58 +0000 Subject: [PATCH 08/11] docs: correct data block examples and operational limits --- .changeset/docs-readme-data-blocks.md | 2 +- packages/bb-app-setting/DESIGN.md | 4 ++-- packages/bb-app-setting/README.md | 23 +++++++++---------- packages/bb-database/README.md | 6 ++--- packages/bb-file-bucket/PRODUCTION.md | 2 +- packages/bb-kv-store/README.md | 2 +- packages/bb-secret/README.md | 32 ++++++++++++++------------- 7 files changed, 36 insertions(+), 35 deletions(-) diff --git a/.changeset/docs-readme-data-blocks.md b/.changeset/docs-readme-data-blocks.md index 4773aaec2c..8a1329e927 100644 --- a/.changeset/docs-readme-data-blocks.md +++ b/.changeset/docs-readme-data-blocks.md @@ -31,7 +31,7 @@ docs(bb-kv-store, bb-database, bb-file-bucket, bb-app-setting, bb-secret): the R **`AppSetting`** -- Corrected: `value` is required unless `secret: true`. A missing parameter throws `ParameterNotFound` on AWS only; an empty `secret: true` value throws on AWS and locally. A `secret: true` value is not checked against the 4 KB limit. +- Corrected: `value` is required unless `secret: true`. A missing parameter throws `ParameterNotFound` on AWS only; an empty `secret: true` value throws on AWS and locally. The block skips its own size check for secrets; Parameter Store still enforces its tier's limit. - Added: `AppSetting.fromExisting` does not create the parameter or grant write access. The mock permits `put()`; on AWS, it can overwrite the parameter if another policy allows the write. For an imported SecureString, the external owner manages re-encryption. - Added: a section on `secret: true`: the first deploy stores a random value; set the real one with `put()` or in the console; `get()` parses the stored text as JSON, so a console value such as `12345` comes back as a number. diff --git a/packages/bb-app-setting/DESIGN.md b/packages/bb-app-setting/DESIGN.md index dd4b1e481f..ca8cedc7e5 100644 --- a/packages/bb-app-setting/DESIGN.md +++ b/packages/bb-app-setting/DESIGN.md @@ -73,8 +73,8 @@ The 4 KB (4096 bytes) size limit applies to the **JSON-encoded** value of non-se ## Mock Implementation -- Data stored in the shared `.cdk-blocks/local/data/settings.json`, keyed by `scope.fullId`. -- Data persists across dev server restarts. Customers can wipe with `rm -rf .cdk-blocks/local/data .bb-data`. +- Values share `.bb-data/settings.json`, keyed by the setting's `fullId`. +- Data persists across dev server restarts. Customers can wipe with `rm -rf .bb-data`. - `get()` returns the stored value from disk, or the initial `value` from constructor if no file exists. - `put()` writes the value to disk immediately. - Schema validation on `put()` when configured, throws `ValidationFailedException`. diff --git a/packages/bb-app-setting/README.md b/packages/bb-app-setting/README.md index 6c283190d6..2830a80ac3 100644 --- a/packages/bb-app-setting/README.md +++ b/packages/bb-app-setting/README.md @@ -78,22 +78,21 @@ import { AppSettingErrors } from '@aws-cdk-blocks/bb-app-setting'; | Constant | `error.name` | Thrown when | |----------|--------------|-------------| -| `AppSettingErrors.ValidationFailed` | `ValidationFailedException` | `put()`: the value fails the schema, or its JSON form is over 4 KB (4,096 bytes; a `secret: true` value is not checked). Constructor: the options are an invalid combination. | +| `AppSettingErrors.ValidationFailed` | `ValidationFailedException` | `put()`: the value fails the schema, or a non-secret value's JSON exceeds 4 KB (4,096 bytes). The block skips the size check for secrets; SSM still enforces the [parameter tier's limit](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-advanced-parameters.html). Constructor: the options are an invalid combination. | | `AppSettingErrors.ParameterNotFound` | `ParameterNotFoundException` | `get()`: the parameter does not exist or has no value (AWS), or a `secret: true` value is an empty string (AWS and local). | ## Secret values (`secret: true`) ```typescript -const stripeKey = new AppSetting(scope, 'stripeKey', { - secret: true, -}); +import { createHmac } from 'node:crypto'; + +const signingKey = new AppSetting(scope, 'prototype-signing-key', { secret: true }); -export const api = new ApiNamespace(scope, 'api', (context) => ({ - async charge(amount: number) { - const key = await stripeKey.get(); // decrypted from SSM SecureString - // use key... - }, -})); +// In a server-side handler, after authorizing the operation: +async function signForPrototype(payload: string) { + const key = await signingKey.get(); + return createHmac('sha256', key).update(payload).digest('hex'); +} ``` - The first deploy stores a random value (32 random bytes, base64url). Later deploys keep the stored value. @@ -103,10 +102,10 @@ export const api = new ApiNamespace(scope, 'api', (context) => ({ ## Existing parameter (`fromExisting`) -`AppSetting.fromExisting` reads a parameter that something else creates, for example a connection string stored by `npm run db -- connect --stage`. +`AppSetting.fromExisting` reads a parameter that something else creates. For example, `npm run db -- connect --stage production` stores the default connection string at `/-db-url`. Use the parameter name printed by the command; for a stack named `my-app`: ```typescript -const dbUrl = AppSetting.fromExisting(scope, 'db-url', { name: '/my-app/db-url', secret: true }); +const dbUrl = AppSetting.fromExisting(scope, 'db-url', { name: '/my-app-db-url', secret: true }); ``` - The stack does not create, seed, tag or delete the parameter. diff --git a/packages/bb-database/README.md b/packages/bb-database/README.md index 5fc4f6689b..4aceca946b 100644 --- a/packages/bb-database/README.md +++ b/packages/bb-database/README.md @@ -126,7 +126,7 @@ The options of `DatabaseCluster.fromExisting()` are under [Existing database](#e ## Errors -Query and transaction failures carry a `DatabaseErrors` name. Match them with `isBlocksError(e, DatabaseErrors.X)` on the server or the client. Only the name and a message free of row values cross the wire; the driver error stays on the server. +Match query and transaction failures with `isBlocksError(e, DatabaseErrors.X)` on the server or the client. The driver error stays on the server. Result-validation messages include the first issue's path, which can contain data-dependent keys; do not put sensitive identifiers in those paths. ```ts import { isBlocksError } from '@aws-cdk-blocks/core'; @@ -432,8 +432,8 @@ MigrationValidationError: Migration validation failed for Aurora DSQL (cluster k ### On an `aurora` cluster - Write the migrations as you would for any PostgreSQL 17. -- Each file runs in one transaction, so it applies entirely or not at all. -- The only check is for the two DSQL-only forms, `ASYNC` and `sys.wait_for_job()`. A file that carries them is stopped at `npm run dev` and at `cdk synth` with a message that names the file and what to change. +- Each file runs in one transaction, so it applies entirely or not at all. Omit transaction controls such as `BEGIN` and `COMMIT`: the migration runner owns that transaction and rejects files that try to control it. +- `npm run dev` and `cdk synth` reject the DSQL-only forms `ASYNC` and `sys.wait_for_job()` with a message naming the file and what to change. - A statement PostgreSQL refuses inside a transaction block (`CREATE INDEX CONCURRENTLY`, `VACUUM`, `ALTER SYSTEM`, `CREATE DATABASE`) stops the file at construction with a message that names it. Drop `CONCURRENTLY`, and keep the rest out of migrations. ### How migrations deploy diff --git a/packages/bb-file-bucket/PRODUCTION.md b/packages/bb-file-bucket/PRODUCTION.md index 1c3cb504ca..504c604eeb 100644 --- a/packages/bb-file-bucket/PRODUCTION.md +++ b/packages/bb-file-bucket/PRODUCTION.md @@ -59,6 +59,6 @@ Object Lock can be added to a bucket that is already deployed, but S3 can't turn - **Billing:** Per-request plus storage — no provisioned throughput - **Latency:** First-byte latency typically 100–200 ms - **Throughput:** Scales automatically, 5,500 GET and 3,500 PUT requests/second per prefix -- **Object size limit:** 5 TB per object +- **Upload size:** FileBucket uses a single `PutObject` request (up to [5 GB on S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/upload-objects.html)). For larger objects, use S3's multipart upload API directly. - **Cost:** ~$0.005 per 1,000 PUT requests, ~$0.0004 per 1,000 GET requests, ~$0.023/GB/month storage - **Durability:** 99.999999999% (11 nines) across 3+ AZs diff --git a/packages/bb-kv-store/README.md b/packages/bb-kv-store/README.md index bc10ac9d3e..95eb3c4c43 100644 --- a/packages/bb-kv-store/README.md +++ b/packages/bb-kv-store/README.md @@ -271,7 +271,7 @@ There is no transaction across items. A batch call is not atomic on AWS. After a There is no atomic increment. To keep a counter that several writers change, use one of: -- A loop. `get()` the item. `put()` the new value with `ifNotExists: true` if `get()` returned `null`, and otherwise with `ifValueEquals` or `ifFieldEquals` on the value you read. Retry on `KVStoreErrors.ConditionalCheckFailed`. Give such a counter no expiry: `get()` returns `null` for an expired item that a condition still sees (see [Expiry](#expiry)). +- A loop. `get()` the item and compute the new value. Use `put()` with `ifNotExists: true` if the item was absent, or compare the value you read with `ifValueEquals` or `ifFieldEquals`. On `KVStoreErrors.ConditionalCheckFailed`, start again at `get()`; even if a competing writer created the item (`retriable: false`), you can now read and increment it. Do not repeat the stale `put()`. Give the counter no expiry: `get()` hides expired items that conditions still see (see [Expiry](#expiry)). - One item per event. Aggregate the items with `query()`. ## Read consistency diff --git a/packages/bb-secret/README.md b/packages/bb-secret/README.md index dc5236c286..542022866b 100644 --- a/packages/bb-secret/README.md +++ b/packages/bb-secret/README.md @@ -13,13 +13,12 @@ A single application secret backed by AWS Secrets Manager. ```typescript const stripeKey = new Secret(scope, 'stripe-api-key'); -export const api = new ApiNamespace(scope, 'api', (context) => ({ - async charge(amount: number) { - const key = await stripeKey.get(); - if (key === null) throw new Error('Stripe key not configured'); - // use key... - }, -})); +// In a server-side billing job, never an API method that returns the key. +async function withStripeKey(charge: (key: string) => Promise): Promise { + const key = await stripeKey.get(); + if (key === null) throw new Error('Stripe key not configured'); + return charge(key); +} ``` The secret starts empty. Set the value after deploy: see [Managing secret values](#managing-secret-values). @@ -89,14 +88,16 @@ import { SecretErrors } from '@aws-cdk-blocks/bb-secret'; Use `generate: true` for a JWT/session signing key or HMAC key that nobody needs to read. ```typescript +import { createHmac } from 'node:crypto'; + const signingKey = new Secret(scope, 'session-signing-key', { generate: true }); -export const api = new ApiNamespace(scope, 'api', (context) => ({ - async issueToken(userId: string) { - const key = await signingKey.get(); // random value, created on first deploy - // sign(userId, key)... - }, -})); +// Sign a server-generated webhook body before sending it to its recipient. +async function signWebhook(body: string): Promise { + const key = await signingKey.get(); + if (key === null) throw new Error('Signing key not configured'); + return createHmac('sha256', key).update(body).digest('hex'); +} ``` > Without `generate: true`, a BB-created secret starts **empty**: `get()` returns `null` until a value is set. Don't combine `generate` with `schema` — a random string isn't valid JSON. @@ -130,7 +131,7 @@ const legacy = new Secret(scope, 'legacy-key', { const value = await legacy.get(); ``` -AWS CDK Blocks will not create, seed, or delete the referenced secret — it only reads its value (and writes it when `allowRuntimeWrite: true`) and grants the app access. +The stack does not create, seed, tag or delete the referenced secret. It grants Secrets Manager access for reads and, with `allowRuntimeWrite: true`, writes. Importing the ARN does not grant access to a customer-managed KMS key: authorize the app's role to decrypt with that key, and to generate a data key if it writes new values. ## Managing secret values @@ -228,7 +229,7 @@ function matches(payload: string, signature: string, key: string | null): boolea return expected.length === given.length && timingSafeEqual(expected, given); } -// Call from your request handlers. Signatures made with the previous key stay valid until the next rotation. +// Check the current and previous keys visible to this verifier. async function isValidSignature(payload: string, signature: string): Promise { const current = await signingKey.get(); const previous = await signingKey.get({ version: 'previous' }); // null until the first rotation @@ -240,6 +241,7 @@ async function isValidSignature(payload: string, signature: string): Promise Date: Thu, 19 Nov 2026 22:14:01 +0000 Subject: [PATCH 09/11] docs: preserve the new local data directory after rebase --- packages/bb-app-setting/DESIGN.md | 4 ++-- packages/bb-app-setting/README.md | 6 +++--- packages/bb-database/README.md | 6 +++--- packages/bb-file-bucket/README.md | 2 +- packages/bb-kv-store/README.md | 2 +- packages/bb-secret/README.md | 10 +++++----- 6 files changed, 15 insertions(+), 15 deletions(-) diff --git a/packages/bb-app-setting/DESIGN.md b/packages/bb-app-setting/DESIGN.md index ca8cedc7e5..8ddd37e403 100644 --- a/packages/bb-app-setting/DESIGN.md +++ b/packages/bb-app-setting/DESIGN.md @@ -73,8 +73,8 @@ The 4 KB (4096 bytes) size limit applies to the **JSON-encoded** value of non-se ## Mock Implementation -- Values share `.bb-data/settings.json`, keyed by the setting's `fullId`. -- Data persists across dev server restarts. Customers can wipe with `rm -rf .bb-data`. +- Values share `.cdk-blocks/local/data/settings.json`, keyed by the setting's `fullId`. +- Data persists across dev server restarts. Customers can wipe with `rm -rf .cdk-blocks/local/data .bb-data`. - `get()` returns the stored value from disk, or the initial `value` from constructor if no file exists. - `put()` writes the value to disk immediately. - Schema validation on `put()` when configured, throws `ValidationFailedException`. diff --git a/packages/bb-app-setting/README.md b/packages/bb-app-setting/README.md index 2830a80ac3..a9b3a5424b 100644 --- a/packages/bb-app-setting/README.md +++ b/packages/bb-app-setting/README.md @@ -98,7 +98,7 @@ async function signForPrototype(payload: string) { - The first deploy stores a random value (32 random bytes, base64url). Later deploys keep the stored value. - Set the real value with `put()`, or in the AWS console: the deployed app's `/cdk-blocks/settings` route redirects to the stack's settings resource group, which lists the parameter. - `get()` parses the stored text as JSON and falls back to the raw text. A console value that is valid JSON (`12345`, `true`) is returned as a number or boolean: set such a value with `put()`, which stores it as a JSON string (shown in the console with double quotes). -- Locally the value is a random string in `.bb-data/settings.json`. Edit the file to change it; the next `get()` reads it. +- Locally the value is a random string in `.cdk-blocks/local/data/settings.json`. Edit the file to change it; the next `get()` reads it. ## Existing parameter (`fromExisting`) @@ -111,7 +111,7 @@ const dbUrl = AppSetting.fromExisting(scope, 'db-url', { name: '/my-app-db-url', - The stack does not create, seed, tag or delete the parameter. - The construct grants `ssm:GetParameter` and, with `secret: true`, `kms:Decrypt`. It does not grant or deny `ssm:PutParameter`. Do not call `put()` on an imported setting: the mock permits it, and on AWS it can overwrite the parameter if another policy grants write access. - The parameter must exist before the app runs. If it does not, the deploy succeeds and `get()` throws `ParameterNotFound`. -- Locally the value is the entry under the setting's `fullId` in `.bb-data/settings.json`: a random string with `secret: true`, an empty string otherwise. Edit the file to set it. +- Locally the value is the entry under the setting's `fullId` in `.cdk-blocks/local/data/settings.json`: a random string with `secret: true`, an empty string otherwise. Edit the file to set it. ## Examples @@ -158,4 +158,4 @@ const apiUrl = new AppSetting(scope, 'apiUrl', { ## Local development -Local values are in the shared `.bb-data/settings.json` (the file `Secret` uses too), keyed by the setting's `fullId`. A `secret: true` setting gets a random value locally (no KMS encryption in mock mode). +Local values are in the shared `.cdk-blocks/local/data/settings.json` (the file `Secret` uses too), keyed by the setting's `fullId`. A `secret: true` setting gets a random value locally (no KMS encryption in mock mode). diff --git a/packages/bb-database/README.md b/packages/bb-database/README.md index 4aceca946b..81300478f0 100644 --- a/packages/bb-database/README.md +++ b/packages/bb-database/README.md @@ -489,8 +489,8 @@ npm run db -- migrate --mark-applied 000_baseline.sql # record a fi | Command | Block | What it does | |---|---|---| -| `types [dir] --block [--type dsql\|aurora] [--cluster ] [--schema ] [--out ]` | provisions its cluster | Writes one `Tables` interface for Kysely from the block's migration files (`cdk-blocks/migrations/`, or `dir` for a block with `migrationsPath`). It does not read `.bb-data/` and does not touch a running dev server. Pass `--type aurora` for a block on an `aurora` cluster. Run it again after you add a file. | -| `status [dir] --block [--cluster ] [--schema ]` | provisions its cluster | Lists the applied and the pending files in the block's local database under `.bb-data/`. For a block on a `DatabaseCluster`, pass the cluster's id as `--cluster`. It reads a copy of the database, so it is safe while `npm run dev` runs; it then shows what the dev server had written to disk. It does not read a deployed stage. | +| `types [dir] --block [--type dsql\|aurora] [--cluster ] [--schema ] [--out ]` | provisions its cluster | Writes one `Tables` interface for Kysely from the block's migration files (`cdk-blocks/migrations/`, or `dir` for a block with `migrationsPath`). It does not read `.cdk-blocks/local/data/` and does not touch a running dev server. Pass `--type aurora` for a block on an `aurora` cluster. Run it again after you add a file. | +| `status [dir] --block [--cluster ] [--schema ]` | provisions its cluster | Lists the applied and the pending files in the block's local database under `.cdk-blocks/local/data/`. For a block on a `DatabaseCluster`, pass the cluster's id as `--cluster`. It reads a copy of the database, so it is safe while `npm run dev` runs; it then shows what the dev server had written to disk. It does not read a deployed stage. | | `connect [--name ] [--stage sandbox\|production] [--ca ] [--value-stdin] [--check-only]` | existing database | Checks the database and stores its connection string. See [`connect`](#connect). | | `migrate [dir] [--types \| --no-types]` | existing database | Applies the pending files of `dir` (default `./migrations`) to the database of the local value, with the code a deploy uses, then writes the types file. Shows the host and asks first; `--yes` skips the question. It does not take `--stage`: the deploy migrates a stage. | | `migrate [dir] --mark-applied [--stage sandbox\|production]` | existing database | Records `` as applied without running it, on the database of the local value or of a stage. For a file that describes what the database already has; see [Starting from the schema you have](#starting-from-the-schema-you-have). Repeat the option for more files. Shows the host and asks first. | @@ -687,7 +687,7 @@ The migration Lambda also creates a per-cluster database role for the app: ## Local development -Each cluster is one PGlite (PostgreSQL compiled to WebAssembly) under `.bb-data/`, with one schema per block, as on AWS. The data directory is `.bb-data/{fullId}/pglite/` for a block that owns its cluster, and `.bb-data/{clusterFullId}/pglite/` for a `DatabaseCluster`. +Each cluster is one PGlite (PostgreSQL compiled to WebAssembly) under `.cdk-blocks/local/data/`, with one schema per block, as on AWS. The data directory is `.cdk-blocks/local/data/{fullId}/pglite/` for a block that owns its cluster, and `.cdk-blocks/local/data/{clusterFullId}/pglite/` for a `DatabaseCluster`. A `dsql` cluster adds DSQL's checks locally: `dsql-lint` on every handler statement (cached per statement text) and the 3,000-row and 10 MiB transaction limits (see [Transactions](#transactions)). An `aurora` cluster is PostgreSQL on both sides and needs neither. DSQL's forms (`ASYNC`, `sys.wait_for_job`) are rejected locally on an `aurora` cluster, as Aurora rejects them. diff --git a/packages/bb-file-bucket/README.md b/packages/bb-file-bucket/README.md index 98130c243a..9c46929118 100644 --- a/packages/bb-file-bucket/README.md +++ b/packages/bb-file-bucket/README.md @@ -412,7 +412,7 @@ export const api = new ApiNamespace(scope, 'api', (context) => ({ ## Local development -- Mock data is stored under `.bb-data/{fullId}/`. +- Mock data is stored under `.cdk-blocks/local/data/{fullId}/`. - Presigned URLs are served by the dev server at `/.bb-file-bucket/{fullId}/{path}?token=...`. - Version-aware operations are available locally, with the historical delete-marker limitation described under [Versioned Bucket](#versioned-bucket). - Lifecycle rules and `corsRules` have no effect locally (see [Browser Uploads and Downloads (CORS)](#browser-uploads-and-downloads-cors)). diff --git a/packages/bb-kv-store/README.md b/packages/bb-kv-store/README.md index 95eb3c4c43..c7a7f3dae4 100644 --- a/packages/bb-kv-store/README.md +++ b/packages/bb-kv-store/README.md @@ -581,7 +581,7 @@ const audit = new KVStore(scope, 'audit', { ## Local development -The mock keeps data on disk in `.bb-data/{fullId}/store.json`, so data stays across restarts of the dev server. To delete it, run `rm -rf .bb-data`. +The mock keeps data on disk in `.cdk-blocks/local/data/{fullId}/store.json`, so data stays across restarts of the dev server. To delete it, run `rm -rf .cdk-blocks/local/data .bb-data`. The mock applies the schema, the conditions, expiry, the 400 KB limit (measured the way DynamoDB measures it), DynamoDB's key and nesting limits, and the cursor checks as AWS does. It runs an index query in memory, so the result is correct and the speed differs from DynamoDB. The mock has no throughput limits and no IAM. diff --git a/packages/bb-secret/README.md b/packages/bb-secret/README.md index 542022866b..09cb1d408e 100644 --- a/packages/bb-secret/README.md +++ b/packages/bb-secret/README.md @@ -146,7 +146,7 @@ The declaration never holds the value: the constructor takes none, and a secret ### Settings route and console -Every AWS CDK Blocks app exposes a built-in `/cdk-blocks/settings` route. Deployed, it redirects to the stack's *settings* resource group in the AWS console, where your `Secret` values appear alongside your `AppSetting` parameters — set or rotate them in the console UI. Locally, the same route opens `.bb-data/settings.json`, where secret values live next to settings (plaintext, dev-only). +Every AWS CDK Blocks app exposes a built-in `/cdk-blocks/settings` route. Deployed, it redirects to the stack's *settings* resource group in the AWS console, where your `Secret` values appear alongside your `AppSetting` parameters — set or rotate them in the console UI. Locally, the same route opens `.cdk-blocks/local/data/settings.json`, where secret values live next to settings (plaintext, dev-only). ### Well-known `name` and the `aws` CLI @@ -272,11 +272,11 @@ For anything deeper than the current/previous pair (full history, custom staging ## Local development -- The mock stores the current value as plaintext in the shared `.bb-data/settings.json` (the same file `AppSetting` uses) and logs a one-time warning. Never use real credentials in local development. +- The mock stores the current value as plaintext in the shared `.cdk-blocks/local/data/settings.json` (the same file `AppSetting` uses) and logs a one-time warning. Never use real credentials in local development. - The key in that file is the secret's `name` when you pass one, otherwise its `fullId` (for example `new Secret(new Scope('my-app'), 'stripe-key')` is stored under `my-app-stripe-key`). -- The previous value (for `get({ version: 'previous' })` / `listVersions()`) is kept in `.bb-data/secret-versions.json` — current + previous only. -- The mock has no cache: every `get()` reads `.bb-data/settings.json` again, so a value written to that file reaches the next call without a restart. -- Wipe with `rm -rf .bb-data`. +- The previous value (for `get({ version: 'previous' })` / `listVersions()`) is kept in `.cdk-blocks/local/data/secret-versions.json` — current + previous only. +- The mock has no cache: every `get()` reads `.cdk-blocks/local/data/settings.json` again, so a value written to that file reaches the next call without a restart. +- Wipe with `rm -rf .cdk-blocks/local/data .bb-data`. To simulate an externally set secret in a local test, add the value under that key, keeping the entries already in the file — for the secret declared with `{ name: 'my-app/stripe-key' }` above: From 42363c29b07082db50a4485d6f3d0f4788a0cacc Mon Sep 17 00:00:00 2001 From: Jairo Suarez Date: Fri, 20 Nov 2026 09:24:08 +0000 Subject: [PATCH 10/11] docs: keep mainline umbrella imports in data block examples --- packages/bb-database/README.md | 7 ++----- packages/bb-kv-store/README.md | 5 ++--- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/packages/bb-database/README.md b/packages/bb-database/README.md index 81300478f0..3398e7ccae 100644 --- a/packages/bb-database/README.md +++ b/packages/bb-database/README.md @@ -26,9 +26,7 @@ The umbrella package `aws-cdk-blocks` exports this block: `import { Database, Da Define the blocks in `cdk-blocks/index.ts`: ```ts -import { ApiNamespace, Scope } from '@aws-cdk-blocks/core'; -import { Auth } from '@aws-cdk-blocks/bb-auth'; -import { Database, sql } from '@aws-cdk-blocks/bb-database'; +import { ApiNamespace, Auth, Database, Scope, sql } from 'aws-cdk-blocks'; const scope = new Scope('app'); const auth = new Auth(scope, 'auth'); @@ -129,8 +127,7 @@ The options of `DatabaseCluster.fromExisting()` are under [Existing database](#e Match query and transaction failures with `isBlocksError(e, DatabaseErrors.X)` on the server or the client. The driver error stays on the server. Result-validation messages include the first issue's path, which can contain data-dependent keys; do not put sensitive identifiers in those paths. ```ts -import { isBlocksError } from '@aws-cdk-blocks/core'; -import { DatabaseErrors } from '@aws-cdk-blocks/bb-database'; +import { DatabaseErrors, isBlocksError } from 'aws-cdk-blocks'; ``` | Constant | `error.name` | Thrown when | Retried automatically | diff --git a/packages/bb-kv-store/README.md b/packages/bb-kv-store/README.md index c7a7f3dae4..24e14e709c 100644 --- a/packages/bb-kv-store/README.md +++ b/packages/bb-kv-store/README.md @@ -267,7 +267,7 @@ The error has a `retriable` flag. It is true when a value check took part in a f A conditional write is atomic for its item, on AWS and in the local mock. No other write to that item lands between the call's check and its write. -There is no transaction across items. A batch call is not atomic on AWS. After a `BatchIncompleteException`, the entries that DynamoDB processed stay written. For a transaction, use `transaction()` on `Database`. +There is no transaction across items. A batch call is not atomic on AWS. After a `BatchIncompleteException`, the entries that DynamoDB processed stay written. For a transaction, use `transaction()` on [`Database`](../bb-database/README.md#transactions). There is no atomic increment. To keep a counter that several writers change, use one of: @@ -424,8 +424,7 @@ You own the indexes and the TTL setting of that table. A string has no fields, so an index cannot read it. Do the move in three steps. ```typescript -import { isBlocksError } from '@aws-cdk-blocks/core'; -import { KVStoreErrors } from '@aws-cdk-blocks/bb-kv-store'; +import { isBlocksError, KVStoreErrors } from 'aws-cdk-blocks'; const memberSchema = z.object({ name: z.string(), email: z.string() }); type Member = z.infer; From 5ed981fb9f7a79821411a5310026f9282b6b3b48 Mon Sep 17 00:00:00 2001 From: Jairo Suarez Date: Fri, 20 Nov 2026 12:24:32 +0000 Subject: [PATCH 11/11] docs: address data block review and preserve mainline guidance --- .changeset/docs-readme-data-blocks.md | 2 +- docs/guides/upgrading-older-apps.md | 4 +- packages/bb-app-setting/README.md | 5 ++- packages/bb-database/README.md | 55 ++++++++++++++++++++++++--- packages/bb-file-bucket/README.md | 3 +- packages/bb-kv-store/README.md | 38 +++++++++++++++--- packages/bb-secret/README.md | 32 ++++++++++------ 7 files changed, 108 insertions(+), 31 deletions(-) diff --git a/.changeset/docs-readme-data-blocks.md b/.changeset/docs-readme-data-blocks.md index 8a1329e927..2edb5a2b98 100644 --- a/.changeset/docs-readme-data-blocks.md +++ b/.changeset/docs-readme-data-blocks.md @@ -7,7 +7,7 @@ "aws-cdk-blocks": patch --- -docs(bb-kv-store, bb-database, bb-file-bucket, bb-app-setting, bb-secret): the READMEs of the data blocks correct their errors tables and document counters in `KVStore`, `AppSetting.fromExisting` and how a `secret: true` setting gets its value. +docs: correct the data blocks' error tables, explain concurrent counters in `KVStore`, and document how to import an existing `AppSetting` and set the value of a `secret: true` setting. **`KVStore`** diff --git a/docs/guides/upgrading-older-apps.md b/docs/guides/upgrading-older-apps.md index 0796088e3e..746c546663 100644 --- a/docs/guides/upgrading-older-apps.md +++ b/docs/guides/upgrading-older-apps.md @@ -113,9 +113,9 @@ Keep the old table with `LegacyKVStore`, and migrate its items to a `KVStore` wi const prefs = new KVStore(scope, 'prefs-v2'); ``` - Deploy. The deploy goes through: it creates the table of `prefs-v2` and doesn't change the old one. `LegacyKVStore` has the `get`, `put`, `delete`, and `scan` of release 0.4.0, so code that still calls the old store keeps working. + Deploy. The deploy goes through: it creates the table of `prefs-v2` and doesn't change the old one. `LegacyKVStore` has the `get`, `put`, `delete`, and `scan` of release 0.4.0. Its `scan` adds `limit`, `cursor`, and expiry metadata; its `get` defaults to a strongly consistent read at twice the read capacity. Pass `{ consistentRead: false }` to keep eventually consistent reads. -2. Migrate the data however is appropriate for your app. `LegacyKVStore` does not copy the items. The [`KVStore` README](../../packages/bb-kv-store/README.md#upgrade-from-release-040-or-earlier) lists the tools for a copy and steps that are suitable for some migrations. +2. Migrate the data however is appropriate for your app. `LegacyKVStore` does not copy the items. The [`KVStore` README](../../packages/bb-kv-store/README.md#step-2-migrate-the-data) describes one way to migrate while the app stays live and explains its limits. 3. When the data is in the new store, remove the `LegacyKVStore` line and any read of the old store, and deploy. The old table leaves the stack. A table with a removal policy of `destroy` is deleted. A retained table, which is the default of the production preset, stays in your account until you delete it. diff --git a/packages/bb-app-setting/README.md b/packages/bb-app-setting/README.md index a9b3a5424b..1509157c71 100644 --- a/packages/bb-app-setting/README.md +++ b/packages/bb-app-setting/README.md @@ -72,8 +72,7 @@ With `kmsKeyArn`: Match an error by name with `isBlocksError`: ```typescript -import { isBlocksError } from '@aws-cdk-blocks/core'; -import { AppSettingErrors } from '@aws-cdk-blocks/bb-app-setting'; +import { AppSettingErrors, isBlocksError } from 'aws-cdk-blocks'; ``` | Constant | `error.name` | Thrown when | @@ -117,6 +116,8 @@ const dbUrl = AppSetting.fromExisting(scope, 'db-url', { name: '/my-app-db-url', ### Typed Object with Schema +This example uses the `auth` block and its `admin` group from [Quick start](#quick-start). + ```typescript import { z } from 'zod'; diff --git a/packages/bb-database/README.md b/packages/bb-database/README.md index 3398e7ccae..52c5b106d3 100644 --- a/packages/bb-database/README.md +++ b/packages/bb-database/README.md @@ -149,7 +149,7 @@ These errors are not for `catch`. Fix the cause. | `error.name` | Cause | |---|---| | `DatabaseConfigurationError` | A setup mistake: a duplicate id, a missing `migrationsPath`. | -| `MigrationValidationError` | A migration file finding: a `dsql-lint` finding, or a DSQL-only form in a file for an `aurora` cluster. | +| `MigrationValidationError` | A `dsql-lint` finding in a `dsql` migration, or a DSQL-only form, a statement PostgreSQL refuses inside a transaction, or explicit transaction control in an `aurora` migration. | | `DsqlValidationError` | A `dsql-lint` finding in a handler's statement. | | `MigrationFailedException` | A migration failure. | @@ -373,7 +373,24 @@ cdk-blocks/migrations/ 001_events.sql ``` -Write the files for the cluster's engine. The block runs them unchanged. +Write the files for the cluster's engine. The only substitution is [`${app_role}`](#the-app-role-in-a-migration). + +### The app role in a migration + +A file names the role that the app's statements run as with `${app_role}`. Before the file runs, every occurrence is replaced with that role's quoted name, so one file works in every place it runs: + +| Where the file runs | `${app_role}` becomes | +|---|---| +| A cluster the block provisions, on AWS | `"blocks_app_{cluster}"`, the role the migration function creates for the cluster before any file runs (see [Access through the AWS SDK](#access-through-the-aws-sdk)) | +| Local mode (`npm run dev`, `npm run db -- types --block`) | `"blocks_app_local"` | +| An [existing database](#existing-database) (a deploy, `npm run db migrate`) | The role of the connection string | + +```sql +-- cdk-blocks/migrations/app/003_roles.sql +GRANT authenticated TO ${app_role} WITH INHERIT FALSE, SET TRUE; +``` + +The replacement is plain text, in string literals and comments too. Nothing else in a file is replaced, and the file's hash is of the text as you wrote it. ### On a `dsql` cluster @@ -447,7 +464,7 @@ On a `dsql` cluster the file resumes where it stopped. A failed index build or c On an [existing database](#existing-database): -- The files run as written. The block does not check them, and PostgreSQL reports what it refuses. +- The block substitutes [`${app_role}`](#the-app-role-in-a-migration) but does not validate the SQL. PostgreSQL reports what it refuses. - Each pending file is one transaction, and the file is recorded in that same transaction. Of two runs at the same time, one commits, and the other is rolled back and says so. - The server ends a transaction that sits idle for a minute, so a run that stops in the middle of a file does not keep its locks. - A deploy runs the files in a function outside any VPC, with the stored connection string. A failure stops the deploy and names the file, the statement, the SQLSTATE and the server's message. @@ -633,6 +650,20 @@ Each transaction on the returned object starts with one statement, `SELECT set_c - **Write a policy so that it accepts an empty claims setting.** After a transaction that set the claims, PostgreSQL leaves `request.jwt.claims` on that connection as an empty string, and `''::jsonb` is an error. A later statement on the block itself then fails with `QueryFailed` instead of reading no rows, when the connection role is one that policies apply to. Write `nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub'`. A cluster that the block provisions gives every connection the default `{}`; a transaction pooler does not keep such a default. - **A statement can undo the switch** with `RESET ROLE` inside its own transaction. The app writes the SQL, so this is a rule for the app's own statements, not a boundary. +On an `aurora` cluster that the block provisions, the app connects as the cluster's app role, which owns nothing, so `asUser()` already filters rows. Use `asRole()` there for policies written for a role. Create the role, give it what the policies need, and grant it to the app role, all in a migration; the app role exists before the first file runs, so this works from the first deploy: + +```sql +-- cdk-blocks/migrations/app/003_roles.sql +CREATE ROLE authenticated NOLOGIN; +GRANT USAGE ON SCHEMA app TO authenticated; -- the block's schema (db.schemaName): its id on a shared cluster +GRANT SELECT ON todos TO authenticated; +CREATE POLICY todos_owner ON todos FOR SELECT TO authenticated + USING (user_id = nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub'); +GRANT authenticated TO ${app_role} WITH INHERIT FALSE, SET TRUE; +``` + +A role belongs to the cluster, not to a block: create it in the migrations of one block on the cluster. + With Kysely, `new DatabaseDialect(db.asRole('authenticated', claims))` needs no transaction of your own; it is a dialect, and so a Kysely instance, per request. To keep one instance for the database, set the identity inside a transaction: ```ts @@ -653,6 +684,14 @@ const mine = await kysely.transaction().execute(async (trx) => { `getSdkIdentifiers(db)` from `@aws-cdk-blocks/core` returns the block's `clusterId` and `schemaName`. In a deployed Lambda it also returns the cluster's `clusterEndpoint` and `region`, which is what a `DsqlSigner` (`dsql`) or an RDS `Signer` from `@aws-sdk/rds-signer` (`aurora`, port 5432) needs to open your own `pg` connection as the same role. `getSdkIdentifiers` from `aws-cdk-blocks` types this result. +On a cluster the block provisions it also returns `roleName`, the PostgreSQL role the block connects as: `blocks_app_local` in local mode, and on AWS `blocks_app_` followed by the cluster's full id in lower case, with `_` for every character other than a letter or a digit. When that name is longer than 63 characters it is `blocks_app_` and the first 12 hex characters of the SHA-256 of the full id. A block on an existing database or a `LegacyDatabaseCluster` connects as the role of its connection and has no `roleName`. In a migration, write [`${app_role}`](#the-app-role-in-a-migration) instead of the name. + +```ts +import { getSdkIdentifiers } from 'aws-cdk-blocks'; + +const { roleName, schemaName } = getSdkIdentifiers(db); // roleName: 'blocks_app_local' under npm run dev +``` + ## What it provisions (AWS) Per cluster, whether a block owns it or a `DatabaseCluster` declares it: @@ -669,10 +708,10 @@ A `LegacyDatabaseCluster` declares what `Database` of `@aws-blocks/bb-data` 0.5. Per block: one CloudFormation custom resource that applies its migrations, and one S3 asset with the migration files when it has any. -The migration Lambda also creates a per-cluster database role for the app: +On a provisioned cluster, the migration Lambda sets up the [app role](#access-through-the-aws-sdk) in two stages: -- It maps the role to IAM: `AWS IAM GRANT` to the execution role on `dsql`; `GRANT rds_iam` on `aurora`, where the `rds-db:connect` grant decides who gets a token for it. -- It grants the role `SELECT`, `INSERT`, `UPDATE` and `DELETE` on the block's tables, `SELECT` on its views, and `USAGE, SELECT` on its sequences. +- Before any migration file runs, it creates the per-cluster app role if needed and maps it to IAM: `AWS IAM GRANT` to the execution role on `dsql`; `GRANT rds_iam` on `aurora`, where the `rds-db:connect` grant decides who gets a token for it. +- After the files run, it grants the role `SELECT`, `INSERT`, `UPDATE` and `DELETE` on the block's tables, `SELECT` on its views, and `USAGE, SELECT` on its sequences. - DDL needs the admin token, which only the migration Lambdas hold. ## Scaling and cost (AWS) @@ -682,12 +721,16 @@ The migration Lambda also creates a per-cluster database role for the app: - **Migration Lambdas.** They run only during deploys. - **Cluster quota.** A `Database` that owns its cluster takes one slot of the account's [cluster quota](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/CHAP_quotas.html); blocks on a shared `DatabaseCluster` take one together. +A connection to an `aurora` cluster is closed ten seconds after its last statement while the function is running, so a cluster at `minCapacity: 0` can pause between requests (an open connection keeps it running); the next request reconnects. A frozen Lambda execution environment keeps its socket until it is thawed or reclaimed, so the pause can come later than five minutes after the last request. + ## Local development Each cluster is one PGlite (PostgreSQL compiled to WebAssembly) under `.cdk-blocks/local/data/`, with one schema per block, as on AWS. The data directory is `.cdk-blocks/local/data/{fullId}/pglite/` for a block that owns its cluster, and `.cdk-blocks/local/data/{clusterFullId}/pglite/` for a `DatabaseCluster`. A `dsql` cluster adds DSQL's checks locally: `dsql-lint` on every handler statement (cached per statement text) and the 3,000-row and 10 MiB transaction limits (see [Transactions](#transactions)). An `aurora` cluster is PostgreSQL on both sides and needs neither. DSQL's forms (`ASYNC`, `sys.wait_for_job`) are rejected locally on an `aurora` cluster, as Aurora rejects them. +On an `aurora` cluster, a migration can run `CREATE EXTENSION` for these extensions locally. PGlite includes them and Aurora PostgreSQL supports them: `amcheck`, `bloom`, `btree_gin`, `btree_gist`, `citext`, `cube`, `dict_int`, `dict_xsyn`, `earthdistance`, `fuzzystrmatch`, `hstore`, `intarray`, `isn`, `lo`, `ltree`, `moddatetime`, `pg_buffercache`, `pg_freespacemap`, `pg_trgm`, `pg_visibility`, `pgcrypto`, `seg`, `tablefunc`, `tcn`, `tsm_system_rows`, `tsm_system_time`, `unaccent` and `uuid-ossp`. An extension that PGlite lacks fails locally even though Aurora has it. `vector` (pgvector) is one: the migration fails with `extension "vector" is not available`, and the message lists the extensions above. `pg_stat_statements` is not loaded locally either. A `dsql` cluster has no extensions, and `CREATE EXTENSION` fails `dsql-lint`. + On both kinds, your statements run locally as a plain database role with the grants the deployed app role gets: `SELECT`, `INSERT`, `UPDATE` and `DELETE` on the block's tables. Migrations run as the admin. PostgreSQL therefore refuses the same statements in both places, with `QueryFailed`: DDL and `TRUNCATE` outside a migration, and any read of the migration ledger (`_migrations`, `_migration_progress`). A Row Level Security policy on a table of an `aurora` cluster applies to your statements under `npm run dev` as it does on AWS. Locally, `ASYNC` index builds and constraint validations complete at once, and a `sys.wait_for_job(…)` copied from the AWS examples returns immediately. diff --git a/packages/bb-file-bucket/README.md b/packages/bb-file-bucket/README.md index 9c46929118..a24cbefab3 100644 --- a/packages/bb-file-bucket/README.md +++ b/packages/bb-file-bucket/README.md @@ -171,8 +171,7 @@ Returned by `getFileHandle()` and `createUploadHandle()`. A handle returned from Match an error by name with `isBlocksError`: ```typescript -import { isBlocksError } from '@aws-cdk-blocks/core'; -import { FileBucketErrors } from '@aws-cdk-blocks/bb-file-bucket'; +import { FileBucketErrors, isBlocksError } from 'aws-cdk-blocks'; ``` | Constant | `error.name` | Thrown when | diff --git a/packages/bb-kv-store/README.md b/packages/bb-kv-store/README.md index 24e14e709c..c901bcf702 100644 --- a/packages/bb-kv-store/README.md +++ b/packages/bb-kv-store/README.md @@ -96,7 +96,7 @@ The mock and browser runtimes ignore `protection`, `pointInTimeRecovery`, and `e ## Errors -Match an error by name with `isBlocksError`. +Match an error by name with `isBlocksError`. See the catch in [Rewrite a store of strings as objects](#rewrite-a-store-of-strings-as-objects). | Constant | `error.name` | Thrown when | |----------|--------------|-------------| @@ -120,13 +120,16 @@ It is also thrown for a bad expiry. `InvalidQueryException` is thrown for: - a bad key -- a bad `where`: a partition value or a sort value of the wrong type, a sort condition that does not exist, or a `between` with its bounds reversed +- a missing `where`, or a partition key not given as `{ equals: value }` +- a partition value or sort operand of the wrong type +- more than one sort condition, an unknown sort condition, or a `between` with its bounds reversed - an unknown index - an `order` that is not `'asc'` or `'desc'` - a bad `limit` - a bad cursor - an `indexes` option that is not an object - `ifValueEquals` with an object +- an empty `ifFieldEquals` - a batch that repeats a key within one DynamoDB request (25 writes or 100 reads) ## Keys @@ -269,10 +272,33 @@ A conditional write is atomic for its item, on AWS and in the local mock. No oth There is no transaction across items. A batch call is not atomic on AWS. After a `BatchIncompleteException`, the entries that DynamoDB processed stay written. For a transaction, use `transaction()` on [`Database`](../bb-database/README.md#transactions). -There is no atomic increment. To keep a counter that several writers change, use one of: +There is no atomic increment. For a shared counter, read its value and write the increment only if the value has not changed. Give the counter no expiry: `get()` hides expired items that write conditions still see. -- A loop. `get()` the item and compute the new value. Use `put()` with `ifNotExists: true` if the item was absent, or compare the value you read with `ifValueEquals` or `ifFieldEquals`. On `KVStoreErrors.ConditionalCheckFailed`, start again at `get()`; even if a competing writer created the item (`retriable: false`), you can now read and increment it. Do not repeat the stale `put()`. Give the counter no expiry: `get()` hides expired items that conditions still see (see [Expiry](#expiry)). -- One item per event. Aggregate the items with `query()`. +```typescript +import { isBlocksError, KVStoreErrors } from 'aws-cdk-blocks'; + +const counters = new KVStore(scope, 'counters'); + +async function increment(name: string): Promise { + for (let attempt = 0; attempt < 10; attempt++) { + const current = await counters.get(name); + const next = (current ?? 0) + 1; + try { + await counters.put(name, next, current === null ? { ifNotExists: true } : { ifValueEquals: current }); + return next; + } catch (e: unknown) { + if (!isBlocksError(e, KVStoreErrors.ConditionalCheckFailed)) throw e; + } + } + throw new Error(`Could not increment ${name} after 10 attempts`); +} + +await increment('visits'); +``` + +If another writer creates the counter first, the failed create has `retriable: false`. The loop does not repeat that `put()`: it reads the new value and computes a new increment. + +Alternatively, write one item per event in a store with a `key` such as `{ partitionKey: 'counterId', sortKey: 'eventId' }`. To get the total, use `query()` on the counter's partition and count the items. Each total reads every event for that counter and is eventually consistent on AWS. ## Read consistency @@ -472,7 +498,7 @@ for await (const { value, expiresAt } of todos.scan()) { Release 0.4.0 or earlier keeps each item as `{ pk, value: , ttl? }`. This release keeps one attribute for each field, under another key attribute. DynamoDB cannot change the key of a table, so a `KVStore` of this release cannot take over the table of such a store. The deploy fails with `CloudFormation cannot update a stack when a custom-named resource requires replacing`, and the table keeps its items. -`LegacyKVStore` keeps the old table usable during the upgrade. It has the four data methods of release 0.4.0, `get`, `put`, `delete`, and `scan`, so the code that calls the old store runs as before. You copy the data into a `KVStore` with a new id in your own code. +`LegacyKVStore` keeps the old table usable during the upgrade. It has the four data methods of release 0.4.0: `get`, `put`, `delete`, and `scan`. Two things differ: `scan` takes `limit` and `cursor` and returns `expiresAt` for items with an expiry; `get` now defaults to a strongly consistent read, which uses twice the read capacity. Pass `{ consistentRead: false }` to keep eventually consistent reads. You copy the data into a `KVStore` with a new id in your own code. `LegacyKVStore` is deprecated and frozen. Use it only for this upgrade. It gets no new features, and a later release can remove it. Use `KVStore` for new data. When the data is in the new store, remove the `LegacyKVStore` from your app. diff --git a/packages/bb-secret/README.md b/packages/bb-secret/README.md index 09cb1d408e..5318240244 100644 --- a/packages/bb-secret/README.md +++ b/packages/bb-secret/README.md @@ -11,6 +11,8 @@ A single application secret backed by AWS Secrets Manager. ## Quick start ```typescript +import { Secret } from 'aws-cdk-blocks'; + const stripeKey = new Secret(scope, 'stripe-api-key'); // In a server-side billing job, never an API method that returns the key. @@ -45,15 +47,14 @@ const secret = new Secret(scope, id, options?) | `schema` | `StandardSchemaV1` | — | Runtime validation schema (Zod, Valibot, ArkType). Infers `T`, treats the stored value as JSON, and validates on `get()`/`put()`. Omit for an opaque `string`. | | `secret` | `ExternalSecretRef` | — | Wrap an existing Secrets Manager secret from `Secret.fromExisting(arn)` instead of creating one. | | `generate` | `boolean` | `false` | When `true`, seed a random value on first create (for a signing/HMAC key that only needs to exist). Otherwise the secret starts empty and `get()` returns `null` until set. Don't combine with `schema`. | -| `cacheTtlSeconds` | `number` | `300` | Seconds the runtime reuses a cached value before re-fetching. `0` disables caching. `put()` clears the cache. Ignored by the mock. | +| `cacheTtlSeconds` | `number` | `300` | Seconds each instance reuses a cached value before re-fetching. A successful `put()` clears only the calling instance's cache; other instances keep their entries until they expire. `0` disables caching. Ignored by the mock. | | `removalPolicy` | `'destroy' \| 'retain'` | stack `defaults` | Override the stack-wide removal default for the created secret. Ignored by the mock and when wrapping an existing secret. | | `logger` | `ChildLogger` | error-level logger | Logger for internal operations. | ### Read-only by default (`allowRuntimeWrite`) ```typescript -// Read-only (default): no put(). Set the value out-of-band, read it with get(). -const stripeKey = new Secret(scope, 'stripe-api-key'); +// The quick start's stripeKey is read-only. Set it out-of-band, then read it. const key = await stripeKey.get(); // stripeKey.put('…') ❌ compile error — put is absent @@ -65,11 +66,21 @@ await token.put('t-abc123'); ## Errors -Match an error by name with `isBlocksError`: +When rotating the writable `token` above, distinguish a missing secret from other write failures: ```typescript -import { isBlocksError } from '@aws-cdk-blocks/core'; -import { SecretErrors } from '@aws-cdk-blocks/bb-secret'; +import { isBlocksError, SecretErrors } from 'aws-cdk-blocks'; + +async function rotateToken(nextValue: string): Promise { + try { + await token.put(nextValue); + } catch (e: unknown) { + if (isBlocksError(e, SecretErrors.SecretNotFound)) { + throw new Error('Token rotation failed: the Secrets Manager secret does not exist.', { cause: e }); + } + throw e; + } +} ``` | Constant | `error.name` | Thrown when | @@ -153,7 +164,7 @@ Every AWS CDK Blocks app exposes a built-in `/cdk-blocks/settings` route. Deploy Give the secret an explicit, stable `name` and set/rotate it with the standard AWS CLI. ```typescript -const stripeKey = new Secret(scope, 'stripe-key', { name: 'my-app/stripe-key' }); +const namedStripeKey = new Secret(scope, 'stripe-key', { name: 'my-app/stripe-key' }); ``` ```bash @@ -198,10 +209,7 @@ A key the app generates and rotates itself is **one** `Secret` with `generate: t ```typescript import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto'; -import { CronJob } from '@aws-cdk-blocks/bb-cron-job'; -import { KVStore, KVStoreErrors } from '@aws-cdk-blocks/bb-kv-store'; -import { Secret } from '@aws-cdk-blocks/bb-secret'; -import { isBlocksError } from '@aws-cdk-blocks/core'; +import { CronJob, isBlocksError, KVStore, KVStoreErrors, Secret } from 'aws-cdk-blocks'; const signingKey = new Secret(scope, 'signing-key', { generate: true, allowRuntimeWrite: true }); const rotations = new KVStore(scope, 'signing-key-rotations'); // one marker per tick, never key material @@ -258,7 +266,7 @@ For anything deeper than the current/previous pair (full history, custom staging ## What it provisions (AWS) - **Encryption:** KMS at rest, using the default `aws/secretsmanager` key. -- **IAM:** the construct grants the shared execution role `secretsmanager:GetSecretValue` + `ListSecretVersionIds` scoped to the single secret (not a wildcard), and `PutSecretValue` only when `allowRuntimeWrite: true`. +- **IAM:** For a secret you declare, the shared execution role gets `secretsmanager:GetSecretValue`, `secretsmanager:DescribeSecret` and `secretsmanager:ListSecretVersionIds` on that secret. Framework-generated keys in Secrets Manager get only `secretsmanager:GetSecretValue`. With `allowRuntimeWrite: true`, CDK also grants `secretsmanager:PutSecretValue`, `secretsmanager:UpdateSecret` and `secretsmanager:UpdateSecretVersionStage` on the secret. When CDK knows the encryption key, it grants KMS decrypt for reads and encrypt for writes via Secrets Manager. For an imported ARN, see [Wrap an existing secret](#wrap-an-existing-secret). - **Removal policy:** follows the stack-wide `defaults` (production retains, sandbox destroys); override per-instance with `removalPolicy`. - **Tags:** BB-created secrets are tagged `aws-blocks-stack=` (join the settings resource group); `fromExisting` secrets are not tagged.