Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/aws-env-loader-exact-logical-id.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@beesolve/aws-env-loader": patch
---

Prefer the resource whose logical id is exactly the mapped prefix (plus an optional CDK hash) over other resources sharing the prefix, such as a construct's children.
5 changes: 5 additions & 0 deletions .changeset/dsql-helpers-initial.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@beesolve/dsql-helpers": minor
---

Initial release: `DsqlCluster` CDK construct with per-function, per-table database roles (`grantRead`, `grantWrite`, `grantReadWrite`, `grant`), an access manifest in SSM, `reconcileAccess` to apply it in both directions, migration repair helpers, and `createDsqlDatabase` for Lambda.
1 change: 1 addition & 0 deletions .kiro/skills/sync-package-docs/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ Substitute these into the generic skill's placeholders:
- `service-email` -> `@beesolve/email-service`
- `service-email-dashboard` -> `@beesolve/email-service-dashboard`
- `helpers-dynamo` -> `@beesolve/dynamo-helpers`
- `helpers-dsql` -> `@beesolve/dsql-helpers`
- all others: `@beesolve/<dir-name>`
- **Publish mechanism:** the `files` array in each `package.json` (no `.npmignore` in this repo).
- User-facing packages: `"files"` includes `"dist"`, `"docs/how-to"`, `"DOCS.md"`.
Expand Down
1 change: 1 addition & 0 deletions .kiro/steering/typescript.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
- `packages/dmarc-parser/` → `@beesolve/dmarc-parser`
- `packages/dmarc-reports/` → `@beesolve/dmarc-reports`
- `packages/dmarc-consumer/` → `@beesolve/dmarc-consumer`
- `packages/helpers-dsql/` → `@beesolve/dsql-helpers`
- `packages/service-email-dashboard/` → `@beesolve/email-service-dashboard`

## Build
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ All packages target Node.js 24+ and are published as ESM.
| [`@beesolve/dmarc-dashboard`](packages/dmarc-dashboard) | DMARC dashboard — SvelteKit app for viewing DMARC reports |
| [`@beesolve/helpers`](packages/helpers) | Shared TypeScript utilities (serialization, retry, type guards) |
| [`@beesolve/dynamo-helpers`](packages/helpers-dynamo) | Shared DynamoDB access helpers — document client, query pagination, single-table batch get |
| [`@beesolve/dsql-helpers`](packages/helpers-dsql) | Aurora DSQL — CDK cluster with per-table database roles, access reconciler, Drizzle factory |
| [`@beesolve/hmac`](packages/hmac) | HMAC signer — create and validate HMAC signatures and signed URLs |
| [`@beesolve/aws-env-loader`](packages/aws-env-loader) | Local dev env from CloudFormation + Secrets Manager, cached and injected into a command |
| [`@beesolve/lint-config`](packages/lint-config) | Shared Oxlint config, custom rules, and a `bun fmt` formatting config |
Expand Down
204 changes: 203 additions & 1 deletion bun.lock

Large diffs are not rendered by default.

11 changes: 11 additions & 0 deletions bunup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,17 @@ const workspace: Array<DefineWorkspaceItem> = [
entry: ["index.ts"],
},
},
{
name: "@beesolve/dsql-helpers",
root: "packages/helpers-dsql",
config: {
entry: ["index.ts", "cdk.ts", "admin.ts"],
dts: {
inferTypes: true,
tsgo: true,
},
},
},
{
name: "@beesolve/analytics-processor",
root: "packages/analytics-processor",
Expand Down
1 change: 1 addition & 0 deletions dependencies.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"packages/dmarc-parser",
"packages/helpers",
"packages/cdk-constructs",
"packages/helpers-dsql",
"packages/helpers-dynamo",
"packages/hmac",
"packages/ip-info",
Expand Down
7 changes: 6 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,12 @@
"@types/node": "^26.6.5",
"@types/bun": "1.4.4",
"esbuild": "^0.28.2",
"@standard-schema/spec": "^1.1.0"
"@standard-schema/spec": "^1.1.0",
"@aws/aurora-dsql-drizzle": "^0.2.0",
"@aws-sdk/client-ssm": "^3.1158.0",
"drizzle-orm": "~0.45.4",
"pg": "^8.23.1",
"@types/pg": "^8.23.1"
}
},
"type": "module",
Expand Down
12 changes: 10 additions & 2 deletions packages/aws-env-loader/src/resolveConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import type {
TemplateMapping,
ResourceMapping,
} from "../index.ts";
import { toStackNames } from "./emit.ts";
import { stripCdkHash, toStackNames } from "./emit.ts";

export interface CloudFormationLike {
send(command: ListStackResourcesCommand): Promise<ListStackResourcesCommandOutput>;
Expand Down Expand Up @@ -213,7 +213,7 @@ function findMatchingResource(props: {
readonly mapping: ResourceReference;
}): StackResourceSummary | undefined {
const { stackResources, mapping } = props;
return stackResources.find((resource) => {
const candidates = stackResources.filter((resource) => {
const logicalId = resource.LogicalResourceId;
if (logicalId == null || !logicalId.startsWith(mapping.logicalIdPrefix)) {
return false;
Expand All @@ -223,6 +223,14 @@ function findMatchingResource(props: {
}
return true;
});
// A construct's children share its logical-id prefix (`Dsql` and `DsqlAccessManifest1A2B3C4D`),
// so the resource whose id is exactly the prefix plus an optional CDK hash wins over the order
// CloudFormation happens to list them in.
return (
candidates.find(
(resource) => stripCdkHash(resource.LogicalResourceId ?? "") === mapping.logicalIdPrefix,
) ?? candidates[0]
);
}

function describeNoMatch(props: {
Expand Down
25 changes: 25 additions & 0 deletions packages/aws-env-loader/tests/resolveConfig.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,31 @@ describe("resolveStackResources resourceType filter", () => {
});
});

describe("resolveStackResources shared prefix", () => {
it("prefers the resource whose logical id is exactly the prefix over a child listed first", async () => {
const cfn = makeCfn([
stackResource({
LogicalResourceId: "DsqlAccessManifest82103489",
ResourceType: "AWS::SSM::Parameter",
PhysicalResourceId: "/beesolve/dsql/abc123/access-manifest",
}),
stackResource({
LogicalResourceId: "Dsql",
ResourceType: "AWS::DSQL::Cluster",
PhysicalResourceId: "abc123",
}),
]);

const resolved = await resolveStackResources({
config: baseConfig,
resources: [{ envVar: "DSQL_CLUSTER_ID", logicalIdPrefix: "Dsql" }],
cfnClient: cfn.client,
});

expect(resolved).toEqual({ DSQL_CLUSTER_ID: "abc123" });
});
});

describe("resolveStackResources multiple stacks", () => {
it("looks a mapping up only in its own stack and describes every stack", async () => {
const byStack: Record<string, ReadonlyArray<StackResourceSummary>> = {
Expand Down
23 changes: 23 additions & 0 deletions packages/helpers-dsql/DOCS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# @beesolve/dsql-helpers - Documentation

**Keywords:** Aurora DSQL, DsqlCluster, grantRead, grantWrite, grantReadWrite, grant, reconcileAccess, planAccess, readAccessManifest, createDsqlDatabase, toDsqlConfig, dsqlEnvEntries, AWS IAM GRANT, dsql:DbConnect, database role, table privileges, least privilege, Drizzle, transactionWithRetry, repairFirstPendingMigration, CDK

> This documentation is published inside the installed package and matches the installed version. Prefer it over prior knowledge or older examples found online.

> Full source, examples, and ADRs: https://github.com/BeeSolve/packages/tree/main/packages/helpers-dsql

## How-To Guides

| Guide | Description |
| --------------------------------------------------- | --------------------------------------------------------------------------------- |
| [Getting Started](./docs/how-to/getting-started.md) | Declare the cluster and roles, apply access after migrations, connect from Lambda |

## Working Examples

No dedicated sample exists for this package yet; see the how-to guides above.

## Further Reading

- [README](./README.md) - API reference and configuration
- [CHANGELOG](./CHANGELOG.md) - Version history
- [Architecture Decision Records](https://github.com/BeeSolve/packages/tree/main/packages/helpers-dsql/docs) (GitHub only)
129 changes: 129 additions & 0 deletions packages/helpers-dsql/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
# @beesolve/dsql-helpers

Aurora DSQL helpers: a CDK cluster construct with least-privilege, per-table database roles declared in code, an access reconciler that applies them to the database, and a Drizzle database factory for Lambda.

> [!WARNING]
> **Pre-1.0 — unstable API.** This package is `0.x` and under active
> development. Breaking changes can land in any `0.x` release without a major
> version bump. Pin an exact version and review the changelog before upgrading.
> Once the API stabilizes and the package reaches `1.0.0`, it follows semantic
> versioning and this notice is removed.

## Installation

```bash
bun add @beesolve/dsql-helpers
# or: npm install @beesolve/dsql-helpers
```

Every entry point needs different peers, so they are optional. Install what you use:

| Entry point | Peers |
| ------------------------------ | ------------------------------------------------- |
| `@beesolve/dsql-helpers/cdk` | `aws-cdk-lib`, `constructs` |
| `@beesolve/dsql-helpers` | `@aws/aurora-dsql-drizzle`, `drizzle-orm`, `pg` |
| `@beesolve/dsql-helpers/admin` | `drizzle-orm` (for `repairFirstPendingMigration`) |

## How access works

IAM only decides **who may connect**: a principal with `dsql:DbConnect` on the cluster can log in as the database role its ARN is mapped to (`AWS IAM GRANT <role> TO '<arn>'`). **What it may touch** is decided by that role's table privileges. IAM cannot restrict which database role is used, so least privilege lives in the database.

1. The CDK construct declares roles and records which IAM principals map to which role. Each grant adds only `dsql:DbConnect` (never `DbConnectAdmin`) and, for a Lambda, sets `DSQL_ENDPOINT`, `DSQL_REGION` and `DSQL_DB_USER`.
2. The desired state is written to an SSM parameter, `/beesolve/dsql/<cluster id>/access-manifest`.
3. An admin step, after migrations, runs `reconcileAccess`: it creates missing roles, grants and revokes table privileges, and grants and revokes IAM mappings so the database matches the code. It then reads the state again and fails unless nothing is left to do.

## CDK: `DsqlCluster`

```ts
import { DsqlCluster } from "@beesolve/dsql-helpers/cdk";

const dsql = new DsqlCluster(this, "Dsql", {
deletionProtection: isProd,
removalPolicy: isProd ? RemovalPolicy.RETAIN : RemovalPolicy.DESTROY,
roles: {
digest: { privileges: ["SELECT", "UPDATE"], tables: ["pending_notifications", "users"] },
reporting: { privileges: ["SELECT"] },
},
});

dsql.grantReadWrite(siteHandler); // role app_readwrite: SELECT, INSERT, UPDATE, DELETE on every table
dsql.grantRead(statsHandler); // role app_read: SELECT on every table
dsql.grantWrite(importer); // role app_write: INSERT, UPDATE, DELETE, no SELECT
dsql.grant(digestHandler, "digest"); // custom role, typed: only declared names compile
```

- A role without `tables` covers every table in the schema, including tables created by later migrations. With `tables`, it covers only those.
- `grantWrite` has no `SELECT`. PostgreSQL also needs `SELECT` for `UPDATE`/`DELETE` with a `WHERE` clause and for `RETURNING`, so it only suits append-only writers.
- An IAM principal maps to one database role. Granting a second, different role to the same function throws at synth; declare a role that combines both.
- Grantees are Lambda functions or IAM roles (IAM permission only, no env vars).
- `new DsqlCluster(this, "Dsql")` gives the cluster the logical ID `Dsql`, so replacing an existing `new CfnCluster(this, "Dsql")` keeps the same cluster.

| Prop | Default | Description |
| ----------------------- | ----------------- | ----------------------------------------------------------------- |
| `roles` | `{}` | Custom roles: `privileges` and optional `tables` |
| `roleNamePrefix` | `app` | Prefix of `<prefix>_read`, `<prefix>_write`, `<prefix>_readwrite` |
| `schema` | `public` | Schema the privileges apply to |
| `deletionProtection` | `true` | Cluster deletion protection |
| `removalPolicy` | `RETAIN` | Cluster removal policy |
| `manifestParameterTier` | `STANDARD` (4 KB) | SSM tier of the manifest parameter |

Properties: `cluster` (`CfnCluster`), `clusterId`, `clusterArn`, `endpoint`, `schema`, `accessManifestParameter`, and `toAccessManifest()`.

Names are validated at synth: roles and tables must be plain lowercase identifiers (`[a-z_][a-z0-9_]*`, max 63), privileges one of `SELECT`, `INSERT`, `UPDATE`, `DELETE`.

## Admin: apply access

```ts
import { drizzle, migrate } from "@aws/aurora-dsql-drizzle";
import { readAccessManifest, reconcileAccess } from "@beesolve/dsql-helpers/admin";

const endpoint = process.env.DSQL_ENDPOINT!;
const db = drizzle({ connection: { host: endpoint, user: "admin" } });

try {
const result = await migrate(db, "./drizzle");
if (!result.success) throw new Error(result.error.message);

const manifest = await readAccessManifest({ endpoint, profile: process.env.AWS_PROFILE });
await reconcileAccess({ client: db.$client, manifest, prune: false, dryRun: false });
} finally {
await db.$client.end();
}
```

The caller needs `dsql:DbConnectAdmin` on the cluster and `ssm:GetParameter` on the manifest parameter.

- `dryRun: true` prints the plan and runs nothing.
- `prune: true` also handles roles that are mapped to IAM principals but no longer declared: their mappings and privileges are revoked and the role is dropped. Without it they are reported as warnings.
- The manifest is validated before use (identifiers, privileges, ARNs, and that every principal is in the cluster's account), and `readAccessManifest` refuses a manifest that names a different cluster than the endpoint.
- `planAccess({ manifest, state })` is the pure diff and `readAccessState({ client, manifest })` the read-only query, if you want to build your own tooling.

Statement order: create roles, grant schema usage, grant table privileges, revoke stale IAM mappings, grant IAM mappings, revoke extra table privileges, then prune. A principal therefore never logs in as a role that cannot yet use its tables.

### Migrations

- `repairFirstPendingMigration({ client, migrationsFolder })` records the first pending `CREATE INDEX ASYNC` / `ALTER TABLE ASYNC ... VALIDATE CONSTRAINT` statement as applied when the index or constraint already exists and is valid. Use it when a migration run stopped while DSQL was still running the job and a re-run fails with 42P07.
- `readAsyncJobs({ client })` returns `sys.jobs` and the schema's indexes with their validity.

## Runtime: `createDsqlDatabase`

```ts
import { createDsqlDatabase, toDsqlConfig } from "@beesolve/dsql-helpers";

import * as schema from "./schema";

const { db, transact } = createDsqlDatabase({
config: toDsqlConfig(), // DSQL_ENDPOINT, DSQL_REGION, DSQL_DB_USER, optional AWS_PROFILE
schema,
casing: "snake_case",
toRetryExhaustedError: () => new BadRequestError("Please try again."),
});
```

- Create it once per Lambda container. The connector creates an IAM token per new connection; DSQL closes connections after one hour and the pool replaces them.
- `transact(fn)` runs `transactionWithRetry`, which retries optimistic concurrency conflicts (SQLSTATE 40001). `fn` may run more than once, so keep side effects outside it.
- `dsqlEnvEntries` are the Valibot entries for the env vars, to spread into an entry point's own schema.
- Types `Db<TSchema>`, `Tx<TSchema>`, `Executor<TSchema>`, `Transact<TSchema>` and `DbProps<TSchema>` are the plain PostgreSQL bases, so repositories also run against PGlite in tests.
- Errors: `toSqlState`, `isUniqueViolation`, `isForeignKeyViolation`, `isCheckViolation`, `isSerializationFailure`, `isRetryExhausted`, `sqlState`.

See [DOCS.md](./DOCS.md) for how-to guides.
6 changes: 6 additions & 0 deletions packages/helpers-dsql/admin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export * from "./src/access/manifest";
export * from "./src/access/plan";
export * from "./src/access/reconcile";
export * from "./src/access/ssm";
export * from "./src/access/state";
export * from "./src/migrations";
4 changes: 4 additions & 0 deletions packages/helpers-dsql/cdk.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export { dsqlPrivileges, toAccessManifestParameterName } from "./src/access/manifest";
export type { AccessManifest, AccessRole, DsqlPrivilege } from "./src/access/manifest";
export * from "./src/cdk/dsqlCluster";
export * from "./src/envNames";
55 changes: 55 additions & 0 deletions packages/helpers-dsql/docs/adr-001-motivation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# ADR-001: Why This Package Exists

## Status

Accepted

## Context

Aurora DSQL splits access control in two. IAM decides who may connect: `dsql:DbConnect` for custom database roles, `dsql:DbConnectAdmin` for `admin`. The database decides what a connection may touch: a role created with `CREATE ROLE ... WITH LOGIN`, mapped to an IAM principal with `AWS IAM GRANT`, and given table privileges with `GRANT`. IAM cannot restrict which database role a principal uses; the mapping lives in the cluster.

The first DSQL consumer (expense-ease) wired this by hand: a CDK helper that granted `dsql:DbConnect` and set the connection env vars on every Lambda, a stack output with the comma-joined Lambda role ARNs, and an admin script that created one shared application role with `SELECT, INSERT, UPDATE, DELETE` on every table and mapped every Lambda to it. Every Lambda got the same full access, the role ARNs had to be copied from a stack output, mappings were only ever added, and the runtime side (Drizzle database factory, SQLSTATE helpers, retry handling) was app code that the next DSQL project would copy.

## Decision

Ship one package with three entry points that share one contract, the access manifest:

- `@beesolve/dsql-helpers/cdk`: `DsqlCluster`, which declares database roles (built-in read, write, read/write, and custom roles with privileges and optional table scope), grants them to Lambdas or IAM roles, and writes the desired access to an SSM parameter.
- `@beesolve/dsql-helpers/admin`: `reconcileAccess`, which applies the manifest to the database in both directions, plus migration recovery helpers.
- `@beesolve/dsql-helpers`: `createDsqlDatabase`, env parsing, shared Drizzle types and SQLSTATE helpers for Lambda code.

## Rationale

### 1. The two halves of the contract must agree

The env var names the construct sets are the ones `toDsqlConfig` reads, and the manifest the construct writes is the one the reconciler validates. Keeping both sides in one package means they cannot drift apart.

### 2. Least privilege per function, declared next to the function

[Anvil's DSQL component](https://anvilcloud.dev/docs/blog/automating-dsql) showed that roles declared with the infrastructure, attached per function and optionally scoped per table, make least privilege the easy path. The same model fits CDK's `grant*` convention (`grantRead`, `grantReadWrite`, `grant(fn, role)`).

### 3. Access follows the code

A diff-based reconciler grants what is missing and revokes what is no longer declared, so removing a grant removes access instead of leaving a stale mapping behind.

## Consequences

- Each Lambda can get a narrower role than the application as a whole.
- The admin step must run after every deploy that changes grants; until it runs, a function granted a new role cannot log in as it (see ADR-002).
- The package is coupled to `@aws/aurora-dsql-drizzle` 0.x and `drizzle-orm` 0.45 through optional peers, so applications control those versions.

## Alternatives Considered

### Keep the code in each application

Rejected: the CDK helper, the role SQL, the SQLSTATE helpers and the migration repair logic are not application-specific, and each copy would re-learn the same DSQL limits (for example that `GRANT ... ON SCHEMA public` fails with 0A000).

### Separate CDK and runtime packages

Rejected for the same reason as in `@beesolve/sqs-handler`: entry points (`/cdk`, `/admin`, `.`) already keep CDK out of Lambda bundles, and one package keeps the manifest and env contract versioned together.

## References

- https://docs.aws.amazon.com/aurora-dsql/latest/userguide/using-database-and-iam-roles.html
- https://docs.aws.amazon.com/aurora-dsql/latest/userguide/authentication-authorization.html
- https://anvilcloud.dev/docs/blog/automating-dsql
Loading