From f40128338d8b588a64de95ab5dda71b3f1cf0233 Mon Sep 17 00:00:00 2001 From: Kiro Agent <244629292+kiro-agent@users.noreply.github.com> Date: Sat, 14 Nov 2026 16:37:14 +0000 Subject: [PATCH 1/3] fix(aws-env-loader): prefer the exact logical id over a shared prefix a construct's children share its logical-id prefix (Dsql and DsqlAccessManifest1A2B3C4D), so the first prefix match depended on the order CloudFormation lists resources in --- .changeset/aws-env-loader-exact-logical-id.md | 5 ++++ packages/aws-env-loader/src/resolveConfig.ts | 12 +++++++-- .../tests/resolveConfig.test.ts | 25 +++++++++++++++++++ 3 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 .changeset/aws-env-loader-exact-logical-id.md diff --git a/.changeset/aws-env-loader-exact-logical-id.md b/.changeset/aws-env-loader-exact-logical-id.md new file mode 100644 index 00000000..1682ffe9 --- /dev/null +++ b/.changeset/aws-env-loader-exact-logical-id.md @@ -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. diff --git a/packages/aws-env-loader/src/resolveConfig.ts b/packages/aws-env-loader/src/resolveConfig.ts index 63643d10..2f9a6c1e 100644 --- a/packages/aws-env-loader/src/resolveConfig.ts +++ b/packages/aws-env-loader/src/resolveConfig.ts @@ -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; @@ -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; @@ -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: { diff --git a/packages/aws-env-loader/tests/resolveConfig.test.ts b/packages/aws-env-loader/tests/resolveConfig.test.ts index 6316e05f..311a75bb 100644 --- a/packages/aws-env-loader/tests/resolveConfig.test.ts +++ b/packages/aws-env-loader/tests/resolveConfig.test.ts @@ -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> = { From bffe6e7c43dc96f2d0ad4cc60587f4275f4bc3c5 Mon Sep 17 00:00:00 2001 From: Kiro Agent <244629292+kiro-agent@users.noreply.github.com> Date: Sat, 14 Nov 2026 16:37:15 +0000 Subject: [PATCH 2/3] add @beesolve/dsql-helpers package aurora dsql helpers: 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. docs, adrs and initial changeset --- .changeset/dsql-helpers-initial.md | 5 + .kiro/skills/sync-package-docs/SKILL.md | 1 + .kiro/steering/typescript.md | 1 + README.md | 1 + bun.lock | 204 ++++++++- bunup.config.ts | 7 + dependencies.json | 1 + package.json | 7 +- packages/helpers-dsql/DOCS.md | 23 + packages/helpers-dsql/README.md | 129 ++++++ packages/helpers-dsql/admin.ts | 6 + packages/helpers-dsql/cdk.ts | 4 + .../helpers-dsql/docs/adr-001-motivation.md | 55 +++ .../adr-002-manifest-and-admin-reconcile.md | 50 +++ .../docs/how-to/getting-started.md | 77 ++++ packages/helpers-dsql/index.ts | 4 + packages/helpers-dsql/package.json | 87 ++++ packages/helpers-dsql/src/access/manifest.ts | 118 +++++ packages/helpers-dsql/src/access/plan.ts | 189 ++++++++ packages/helpers-dsql/src/access/reconcile.ts | 80 ++++ packages/helpers-dsql/src/access/ssm.ts | 57 +++ packages/helpers-dsql/src/access/state.ts | 135 ++++++ packages/helpers-dsql/src/cdk/dsqlCluster.ts | 247 +++++++++++ packages/helpers-dsql/src/database.ts | 109 +++++ packages/helpers-dsql/src/env.ts | 41 ++ packages/helpers-dsql/src/envNames.ts | 9 + packages/helpers-dsql/src/errors.ts | 58 +++ packages/helpers-dsql/src/migrations.ts | 159 +++++++ packages/helpers-dsql/tests/access.test.ts | 410 ++++++++++++++++++ .../helpers-dsql/tests/dsqlCluster.test.ts | 216 +++++++++ packages/helpers-dsql/tsconfig.json | 5 + 31 files changed, 2493 insertions(+), 2 deletions(-) create mode 100644 .changeset/dsql-helpers-initial.md create mode 100644 packages/helpers-dsql/DOCS.md create mode 100644 packages/helpers-dsql/README.md create mode 100644 packages/helpers-dsql/admin.ts create mode 100644 packages/helpers-dsql/cdk.ts create mode 100644 packages/helpers-dsql/docs/adr-001-motivation.md create mode 100644 packages/helpers-dsql/docs/adr-002-manifest-and-admin-reconcile.md create mode 100644 packages/helpers-dsql/docs/how-to/getting-started.md create mode 100644 packages/helpers-dsql/index.ts create mode 100644 packages/helpers-dsql/package.json create mode 100644 packages/helpers-dsql/src/access/manifest.ts create mode 100644 packages/helpers-dsql/src/access/plan.ts create mode 100644 packages/helpers-dsql/src/access/reconcile.ts create mode 100644 packages/helpers-dsql/src/access/ssm.ts create mode 100644 packages/helpers-dsql/src/access/state.ts create mode 100644 packages/helpers-dsql/src/cdk/dsqlCluster.ts create mode 100644 packages/helpers-dsql/src/database.ts create mode 100644 packages/helpers-dsql/src/env.ts create mode 100644 packages/helpers-dsql/src/envNames.ts create mode 100644 packages/helpers-dsql/src/errors.ts create mode 100644 packages/helpers-dsql/src/migrations.ts create mode 100644 packages/helpers-dsql/tests/access.test.ts create mode 100644 packages/helpers-dsql/tests/dsqlCluster.test.ts create mode 100644 packages/helpers-dsql/tsconfig.json diff --git a/.changeset/dsql-helpers-initial.md b/.changeset/dsql-helpers-initial.md new file mode 100644 index 00000000..5b815887 --- /dev/null +++ b/.changeset/dsql-helpers-initial.md @@ -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. diff --git a/.kiro/skills/sync-package-docs/SKILL.md b/.kiro/skills/sync-package-docs/SKILL.md index d74e6e79..ac32f37c 100644 --- a/.kiro/skills/sync-package-docs/SKILL.md +++ b/.kiro/skills/sync-package-docs/SKILL.md @@ -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/` - **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"`. diff --git a/.kiro/steering/typescript.md b/.kiro/steering/typescript.md index d0a981d6..f2e93657 100644 --- a/.kiro/steering/typescript.md +++ b/.kiro/steering/typescript.md @@ -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 diff --git a/README.md b/README.md index 4707cd92..8f31948b 100644 --- a/README.md +++ b/README.md @@ -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 | diff --git a/bun.lock b/bun.lock index 9b803cdc..75b38dce 100644 --- a/bun.lock +++ b/bun.lock @@ -122,7 +122,7 @@ }, "packages/aws-env-loader": { "name": "@beesolve/aws-env-loader", - "version": "0.6.2", + "version": "0.7.0", "bin": { "aws-env-loader": "./dist/cli.js", }, @@ -323,6 +323,41 @@ "typescript", ], }, + "packages/helpers-dsql": { + "name": "@beesolve/dsql-helpers", + "version": "0.0.0", + "dependencies": { + "@aws-sdk/client-ssm": "catalog:", + "@aws-sdk/credential-providers": "catalog:", + "valibot": "catalog:", + }, + "devDependencies": { + "@aws/aurora-dsql-drizzle": "catalog:", + "@types/bun": "catalog:", + "@types/node": "catalog:", + "@types/pg": "catalog:", + "aws-cdk-lib": "catalog:", + "constructs": "catalog:", + "drizzle-orm": "catalog:", + "pg": "catalog:", + }, + "peerDependencies": { + "@aws/aurora-dsql-drizzle": "catalog:", + "aws-cdk-lib": "catalog:", + "constructs": "catalog:", + "drizzle-orm": "catalog:", + "pg": "catalog:", + "typescript": "catalog:", + }, + "optionalPeers": [ + "@aws/aurora-dsql-drizzle", + "aws-cdk-lib", + "constructs", + "drizzle-orm", + "pg", + "typescript", + ], + }, "packages/helpers-dynamo": { "name": "@beesolve/dynamo-helpers", "version": "0.2.2", @@ -645,20 +680,25 @@ "@aws-sdk/client-secrets-manager": "^3.1150.0", "@aws-sdk/client-sesv2": "^3.1158.0", "@aws-sdk/client-sqs": "^3.1158.0", + "@aws-sdk/client-ssm": "^3.1158.0", "@aws-sdk/client-sts": "^3.1150.0", "@aws-sdk/credential-providers": "^3.1158.0", "@aws-sdk/lib-dynamodb": "^3.1158.0", + "@aws/aurora-dsql-drizzle": "^0.2.0", "@react-email/components": "1.0.12", "@standard-schema/spec": "^1.1.0", "@types/aws-lambda": "^8.10.164", "@types/bun": "1.4.4", "@types/node": "^26.6.5", + "@types/pg": "^8.23.1", "@types/react": "^19.3.0", "aws-cdk": "^2.1146.1", "aws-cdk-lib": "^2.275.0", "constructs": "^10.8.1", + "drizzle-orm": "~0.45.4", "esbuild": "^0.28.2", "mimetext": "^3.0.28", + "pg": "^8.23.1", "react": "^19.3.1", "react-dom": "^19.3.1", "typescript": "^7.0.2", @@ -693,6 +733,8 @@ "@aws-sdk/client-sqs": ["@aws-sdk/client-sqs@3.1158.0", "", { "dependencies": { "@aws-sdk/core": "^3.978.6", "@aws-sdk/credential-provider-node": "^3.972.89", "@aws-sdk/middleware-sdk-sqs": "^3.972.47", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.37.0", "@smithy/fetch-http-handler": "^5.8.0", "@smithy/node-http-handler": "^4.13.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-JCIwxVX8F97JIOSH+JUD/Qwpq7rXaATmiuUs6eId3yBsSDGbm1ZuxRXqDsehQ/i5oDOEJSFETnFlO3scWqo5qw=="], + "@aws-sdk/client-ssm": ["@aws-sdk/client-ssm@3.1169.0", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/credential-provider-node": "^3.972.97", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-EAqUE22l8bOeCPMNxnahMhKrWW2n7siZjVL1rNWWaD9prTTwDbMf2xeaAOqVx5lLOz+3sSuicM6OMY5yYTR1Eg=="], + "@aws-sdk/client-sts": ["@aws-sdk/client-sts@3.1158.0", "", { "dependencies": { "@aws-sdk/core": "^3.978.6", "@aws-sdk/credential-provider-node": "^3.972.89", "@aws-sdk/signature-v4-multi-region": "^3.996.49", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.37.0", "@smithy/fetch-http-handler": "^5.8.0", "@smithy/node-http-handler": "^4.13.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-p2CMAfJirXA0KDd0qd83KRe2YUUXASn9zGN1ryIDHuzLCTl9VSDq3RuvMMgDZYHNyytrBHVFcxCDLBG5cWUNmw=="], "@aws-sdk/core": ["@aws-sdk/core@3.978.6", "", { "dependencies": { "@aws-sdk/types": "^3.975.0", "@aws-sdk/xml-builder": "^3.972.41", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.37.0", "@smithy/signature-v4": "^5.7.4", "@smithy/types": "^4.19.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-ykF/MiYoM15dgZwF/WLgjJXVbAK2wU6vjPigeEnOHwyUJ0rdlraO5uekecKNVPkvOnz+oju/5zljViQs1nI1FQ=="], @@ -717,6 +759,8 @@ "@aws-sdk/credential-providers": ["@aws-sdk/credential-providers@3.1158.0", "", { "dependencies": { "@aws-sdk/core": "^3.978.6", "@aws-sdk/credential-provider-cognito-identity": "^3.972.76", "@aws-sdk/credential-provider-env": "^3.972.77", "@aws-sdk/credential-provider-http": "^3.972.79", "@aws-sdk/credential-provider-ini": "^3.973.22", "@aws-sdk/credential-provider-login": "^3.972.84", "@aws-sdk/credential-provider-node": "^3.972.89", "@aws-sdk/credential-provider-process": "^3.972.77", "@aws-sdk/credential-provider-sso": "^3.973.21", "@aws-sdk/credential-provider-web-identity": "^3.972.83", "@aws-sdk/nested-clients": "^3.997.51", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.37.0", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-1t5ZJosanRE7rCV+sakvuCb0/jff0flOUFwCFLGtGz1OH3ijqNOq0xNwBt59PRp43oijiHrhwZT4RMCT01jUSg=="], + "@aws-sdk/dsql-signer": ["@aws-sdk/dsql-signer@3.1169.0", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/credential-provider-node": "^3.972.97", "@smithy/core": "^3.40.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-XdWNJvh6ThBHtqNJ7KPrbsfs0qY4ix4mO6nAkt/Ew9xFzCKdn2uhBOmEa15tu83dbxvSaZlcNVaR0Kr5SsVSsA=="], + "@aws-sdk/dynamodb-codec": ["@aws-sdk/dynamodb-codec@3.973.51", "", { "dependencies": { "@aws-sdk/core": "^3.978.6", "@smithy/core": "^3.37.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-4feXxG9ICb/IdyKP4thAXTW4ufA4ubOJe5KYYYUi44ls1NzLy4TuHUWurOH/QnfKpaw9RCjxKoHyya8MS6F5hA=="], "@aws-sdk/endpoint-cache": ["@aws-sdk/endpoint-cache@3.972.11", "", { "dependencies": { "mnemonist": "0.38.3", "tslib": "^2.6.2" } }, "sha512-8q1ICxcDjHId3bBryuu/j+1L9y5/3uQnwzLDt5j2ElcjZSoWmFtymdJy7OjLrluSMe0Z4mq5bcH4fxBXvlEHfw=="], @@ -741,6 +785,22 @@ "@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.41", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-ctjVSyCMegrWfXlx6VqzSBFI6UqmQ5ZlnfMhdLIiWmhoH8UAQxSCP5N3OpG7X3k4LnS7ou74C4mt20+bfTW2aQ=="], + "@aws/aurora-dsql-drizzle": ["@aws/aurora-dsql-drizzle@0.2.0", "", { "dependencies": { "@aws/aurora-dsql-node-postgres-connector": ">=0.1.9 <1", "@aws/dsql-lint": ">=0.2.17 <1" }, "peerDependencies": { "drizzle-orm": "^0.45", "pg": ">=8" }, "bin": { "aurora-dsql-drizzle": "dist/cli/index.js" } }, "sha512-e0oW9X7FL4YTKrAopiX6g8pzfzYkc7fCfV4tUfSQ94/V6AmmFwP8dz1dLz+Ly6rQZ706PluVBhK/0wNDkFZNIw=="], + + "@aws/aurora-dsql-node-postgres-connector": ["@aws/aurora-dsql-node-postgres-connector@0.1.9", "", { "dependencies": { "@aws-sdk/credential-providers": "^3.894.0", "@aws-sdk/dsql-signer": "^3.940.0", "@smithy/types": "^4.11.0" }, "peerDependencies": { "pg": "^8.16.3", "pg-connection-string": "^2.7.0" } }, "sha512-i8MHzHLdL/1YzsGH6RipLu0U3x8SxCQAtR1VtA7iAhBT4g4yujQ4/qG7HJ5ySAy4XPL/1iNs8m0dLp5LvsqYRw=="], + + "@aws/dsql-lint": ["@aws/dsql-lint@0.2.22", "", { "optionalDependencies": { "@aws/dsql-lint-darwin-arm64": "0.2.22", "@aws/dsql-lint-darwin-x64": "0.2.22", "@aws/dsql-lint-linux-arm64": "0.2.22", "@aws/dsql-lint-linux-x64": "0.2.22", "@aws/dsql-lint-win32-x64": "0.2.22" }, "bin": { "dsql-lint": "bin/dsql-lint" } }, "sha512-ygQxj4oySisWEBXeGkuOfa1sxvhW5VlO0v1+YIvQ9nWf7B+QfkhfaoaQ1LKkBrqKPG/eR7DCCvkkV/YXHPG4ew=="], + + "@aws/dsql-lint-darwin-arm64": ["@aws/dsql-lint-darwin-arm64@0.2.22", "", { "os": "darwin", "cpu": "arm64", "bin": { "dsql-lint": "bin/dsql-lint" } }, "sha512-B0jHmq8PNIkFLnSq2hguMX8IqgrUyJBQKgpElmgvxz8cRZUUCSSwRhuu+Yy5IfucRb3Ign40gj6C18ldYza2qw=="], + + "@aws/dsql-lint-darwin-x64": ["@aws/dsql-lint-darwin-x64@0.2.22", "", { "os": "darwin", "cpu": "x64", "bin": { "dsql-lint": "bin/dsql-lint" } }, "sha512-Z+tZcDAEYKwiaDEG4aMFOg0oHeeDj0s/SMPTmwol3+JN8XVcy1u5Ybh1w0FH8Kcis08LMy/t43MomkuLeAjpiQ=="], + + "@aws/dsql-lint-linux-arm64": ["@aws/dsql-lint-linux-arm64@0.2.22", "", { "os": "linux", "cpu": "arm64", "bin": { "dsql-lint": "bin/dsql-lint" } }, "sha512-hWzEjSB7P1X20RPp9gFvHMb4qoo1xBAX1YbC9lIfJmrDgNxzVaYb4Vh8l2FUHNJVJGUB0zSp0qNQhcIeyVTwLA=="], + + "@aws/dsql-lint-linux-x64": ["@aws/dsql-lint-linux-x64@0.2.22", "", { "os": "linux", "cpu": "x64", "bin": { "dsql-lint": "bin/dsql-lint" } }, "sha512-McsWDs2hMjpZkTHoPKTKGuC/rXtYO+pWX0TEDyD1jdDzrO0IywI1Vabw/wglCl1jEJHL/dVliJdgfpu3vjoHwQ=="], + + "@aws/dsql-lint-win32-x64": ["@aws/dsql-lint-win32-x64@0.2.22", "", { "os": "win32", "cpu": "x64", "bin": { "dsql-lint": "bin/dsql-lint.exe" } }, "sha512-wBD9c9wDZTb55U24YnDDcUfd03IR1HvMafleQV/Muyv6x9xF2d66ltmw0zIVjJoL9j7GEmhRFMZzS4sXq1BIng=="], + "@aws/lambda-invoke-store": ["@aws/lambda-invoke-store@0.3.0", "", {}, "sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ=="], "@babel/helper-string-parser": ["@babel/helper-string-parser@7.29.7", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="], @@ -777,6 +837,8 @@ "@beesolve/dmarc-reports": ["@beesolve/dmarc-reports@workspace:packages/dmarc-reports"], + "@beesolve/dsql-helpers": ["@beesolve/dsql-helpers@workspace:packages/helpers-dsql"], + "@beesolve/dynamo-helpers": ["@beesolve/dynamo-helpers@workspace:packages/helpers-dynamo"], "@beesolve/email-service": ["@beesolve/email-service@workspace:packages/service-email"], @@ -1199,6 +1261,8 @@ "@types/node": ["@types/node@26.6.5", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg=="], + "@types/pg": ["@types/pg@8.23.1", "", { "dependencies": { "@types/node": "*", "pg-protocol": "*", "pg-types": "^2.2.0" } }, "sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A=="], + "@types/react": ["@types/react@19.3.0", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg=="], "@types/react-dom": ["@types/react-dom@19.3.0", "", { "peerDependencies": { "@types/react": "^19.3.0" } }, "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q=="], @@ -1313,6 +1377,8 @@ "domutils": ["domutils@3.2.2", "", { "dependencies": { "dom-serializer": "^2.0.0", "domelementtype": "^2.3.0", "domhandler": "^5.0.3" } }, "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw=="], + "drizzle-orm": ["drizzle-orm@0.45.4", "", { "peerDependencies": { "@aws-sdk/client-rds-data": ">=3", "@cloudflare/workers-types": ">=4", "@electric-sql/pglite": ">=0.2.0", "@libsql/client": ">=0.10.0", "@libsql/client-wasm": ">=0.10.0", "@neondatabase/serverless": ">=0.10.0", "@netlify/db": ">=0.4.0", "@op-engineering/op-sqlite": ">=2", "@opentelemetry/api": "^1.4.1", "@planetscale/database": ">=1.13", "@prisma/client": "*", "@tidbcloud/serverless": "*", "@types/better-sqlite3": "*", "@types/pg": "*", "@types/sql.js": "*", "@upstash/redis": ">=1.34.7", "@vercel/postgres": ">=0.8.0", "@xata.io/client": "*", "better-sqlite3": ">=7", "bun-types": "*", "expo-sqlite": ">=14.0.0", "gel": ">=2", "knex": "*", "kysely": "*", "mysql2": ">=2", "pg": ">=8", "postgres": ">=3", "prisma": "*", "sql.js": ">=1", "sqlite3": ">=5" }, "optionalPeers": ["@aws-sdk/client-rds-data", "@cloudflare/workers-types", "@electric-sql/pglite", "@libsql/client", "@libsql/client-wasm", "@neondatabase/serverless", "@netlify/db", "@op-engineering/op-sqlite", "@opentelemetry/api", "@planetscale/database", "@prisma/client", "@tidbcloud/serverless", "@types/better-sqlite3", "@types/pg", "@types/sql.js", "@upstash/redis", "@vercel/postgres", "@xata.io/client", "better-sqlite3", "bun-types", "expo-sqlite", "gel", "knex", "kysely", "mysql2", "pg", "postgres", "prisma", "sql.js", "sqlite3"] }, "sha512-NiM1YZpJ2UxyeE67DpDDZ+Tsw4YLX3trSlkNT7Tm9eKoUNb1LvaAaQzXgYQsWs+AQ9TUmmwMmBOCXuqqxUWKKQ=="], + "encoding-japanese": ["encoding-japanese@2.4.0", "", {}, "sha512-PE0KjlsDy9JSsoU4C2Q8NXb1kC4c+bZRac9ZvHXUE4q1Ht63gScKMdEy9jst9+Fi3M4eDkqzkEhBZvix4blP2A=="], "entities": ["entities@7.0.1", "", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="], @@ -1451,12 +1517,36 @@ "peberminta": ["peberminta@0.10.0", "", {}, "sha512-80B2AsU+I4Qdb0ZAPSfe9UwvGzwkM37IKIFEvdS3D/3Ndgv2bsuJ0bfG1+iEYO+l7Gfd4EUJmuRyq7efLgRMzQ=="], + "pg": ["pg@8.23.1", "", { "dependencies": { "pg-connection-string": "^2.14.1", "pg-pool": "^3.14.0", "pg-protocol": "^1.16.1", "pg-types": "2.2.0", "pgpass": "1.0.5" }, "optionalDependencies": { "pg-cloudflare": "^1.4.1" }, "peerDependencies": { "pg-native": ">=3.0.1" }, "optionalPeers": ["pg-native"] }, "sha512-aL96AHANtWjPLDOLqnhx+ngp9+UK7ETEU8VJrDCGvsSSi/mGLcWYsS6Herg7lmaBJe4uwrfqsa7gTEFaSizDoQ=="], + + "pg-cloudflare": ["pg-cloudflare@1.4.1", "", {}, "sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ=="], + + "pg-connection-string": ["pg-connection-string@2.14.1", "", {}, "sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA=="], + + "pg-int8": ["pg-int8@1.0.1", "", {}, "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw=="], + + "pg-pool": ["pg-pool@3.14.0", "", { "peerDependencies": { "pg": ">=8.0" } }, "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw=="], + + "pg-protocol": ["pg-protocol@1.16.1", "", {}, "sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg=="], + + "pg-types": ["pg-types@2.2.0", "", { "dependencies": { "pg-int8": "1.0.1", "postgres-array": "~2.0.0", "postgres-bytea": "~1.0.0", "postgres-date": "~1.0.4", "postgres-interval": "^1.1.0" } }, "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA=="], + + "pgpass": ["pgpass@1.0.5", "", { "dependencies": { "split2": "^4.1.0" } }, "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug=="], + "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], "picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="], "postcss": ["postcss@8.5.30", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-zkd+e9S1AQHhmaBKye9zlFHWjOwVgqXl1q3ECYy8561K7qxR2cREf/STLskulBFd78k6AOFeA+ff1TtEzk9bAA=="], + "postgres-array": ["postgres-array@2.0.0", "", {}, "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA=="], + + "postgres-bytea": ["postgres-bytea@1.0.1", "", {}, "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ=="], + + "postgres-date": ["postgres-date@1.0.7", "", {}, "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q=="], + + "postgres-interval": ["postgres-interval@1.2.0", "", { "dependencies": { "xtend": "^4.0.0" } }, "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ=="], + "prettier": ["prettier@3.9.10", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-skGHTH1Yb9QvaTC4hWnRTzEYtCpApF0UMBPz+t/0ZPzP8ihefo/btKd+QA7pUE0fEwA1SbS/NmhyEcstdXOIdA=="], "prismjs": ["prismjs@1.30.0", "", {}, "sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw=="], @@ -1489,6 +1579,8 @@ "source-map-js": ["source-map-js@1.2.2", "", {}, "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw=="], + "split2": ["split2@4.2.0", "", {}, "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg=="], + "std-env": ["std-env@3.10.0", "", {}, "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg=="], "strip-json-comments": ["strip-json-comments@5.0.3", "", {}, "sha512-1tB5mhVo7U+ETBKNf92xT4hrQa3pm0MZ0PQvuDnWgAAGHDsfp4lPSpiS6psrSiet87wyGPh9ft6wmhOMQ0hDiw=="], @@ -1527,6 +1619,8 @@ "xml-naming": ["xml-naming@0.3.0", "", {}, "sha512-ghig2TBE/H11aOVgmahA3MhimvkBr6JIYknH/Dhdk10nXwdbIqBJsbfMxpvFPG8bAw77gN29aQWvKpmVoPlvPQ=="], + "xtend": ["xtend@4.0.2", "", {}, "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ=="], + "yaml": ["yaml@2.9.1", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw=="], "zimmerframe": ["zimmerframe@1.1.5", "", {}, "sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA=="], @@ -1537,6 +1631,26 @@ "@aws-cdk/cloud-assembly-schema/semver": ["semver@7.8.5", "", { "bundled": true, "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="], + "@aws-sdk/client-ssm/@aws-sdk/core": ["@aws-sdk/core@3.981.0", "", { "dependencies": { "@aws-sdk/types": "^3.975.1", "@aws-sdk/xml-builder": "^3.972.43", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.40.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.20.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-Mnu7gaDrC5UCdyH8uLxLfB2eWbjE/HbjKX1U1J2VQxG3TTATUDObW2wU3I8iH3e9YH5NN2CY6w1mlAIe2XJ3jg=="], + + "@aws-sdk/client-ssm/@aws-sdk/credential-provider-node": ["@aws-sdk/credential-provider-node@3.972.97", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.84", "@aws-sdk/credential-provider-http": "^3.972.86", "@aws-sdk/credential-provider-ini": "^3.973.30", "@aws-sdk/credential-provider-process": "^3.972.84", "@aws-sdk/credential-provider-sso": "^3.973.28", "@aws-sdk/credential-provider-web-identity": "^3.972.90", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-E4a0IXXJVsIdo/K9roX4JAEfI0JJr7KTPymkbKgETRDqEcLygE4ZlLTe24+7Qkh8Dl5YpnPd+Tt0DOPJDFXIwA=="], + + "@aws-sdk/client-ssm/@aws-sdk/types": ["@aws-sdk/types@3.975.1", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-7rGxUkCB2QPoQOeJmonmAICTN2zrH+fpmi1p4Iwu72lnxNaMhOgqcbpyddifnM1DBb19TWQ1u6z/XjkaFNEDWw=="], + + "@aws-sdk/client-ssm/@smithy/core": ["@smithy/core@3.40.0", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-DssGno52pzZ5m6RlDtyKuBIpZNPg9pqgs0CnNDKz9IatxCsmvNmJNn5Zn6rf77MthZo9wf89OvZFhTY/RwxhxQ=="], + + "@aws-sdk/client-ssm/@smithy/fetch-http-handler": ["@smithy/fetch-http-handler@5.8.1", "", { "dependencies": { "@smithy/core": "^3.39.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-h8BdMUrUBhMhMaeK7QqAdINRZezCGuYOCpcOZZ1ewxbHST9rdTd09xwNpvLTYfzDRehxQiReK4SKbdYZxBA+ew=="], + + "@aws-sdk/client-ssm/@smithy/node-http-handler": ["@smithy/node-http-handler@4.14.2", "", { "dependencies": { "@smithy/core": "^3.39.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-i1uORV1v3qBqP43ayRKzIdm1q5x14tf8N4Dd06/QUX1Szm6VxHMrTsu20X5E63UFsaNZCRjI4SXG0jDmqYa+3w=="], + + "@aws-sdk/dsql-signer/@aws-sdk/core": ["@aws-sdk/core@3.981.0", "", { "dependencies": { "@aws-sdk/types": "^3.975.1", "@aws-sdk/xml-builder": "^3.972.43", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.40.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.20.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-Mnu7gaDrC5UCdyH8uLxLfB2eWbjE/HbjKX1U1J2VQxG3TTATUDObW2wU3I8iH3e9YH5NN2CY6w1mlAIe2XJ3jg=="], + + "@aws-sdk/dsql-signer/@aws-sdk/credential-provider-node": ["@aws-sdk/credential-provider-node@3.972.97", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.84", "@aws-sdk/credential-provider-http": "^3.972.86", "@aws-sdk/credential-provider-ini": "^3.973.30", "@aws-sdk/credential-provider-process": "^3.972.84", "@aws-sdk/credential-provider-sso": "^3.973.28", "@aws-sdk/credential-provider-web-identity": "^3.972.90", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-E4a0IXXJVsIdo/K9roX4JAEfI0JJr7KTPymkbKgETRDqEcLygE4ZlLTe24+7Qkh8Dl5YpnPd+Tt0DOPJDFXIwA=="], + + "@aws-sdk/dsql-signer/@smithy/core": ["@smithy/core@3.40.0", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-DssGno52pzZ5m6RlDtyKuBIpZNPg9pqgs0CnNDKz9IatxCsmvNmJNn5Zn6rf77MthZo9wf89OvZFhTY/RwxhxQ=="], + + "@aws-sdk/dsql-signer/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="], + "@beesolve/analytics-dashboard/svelte-check": ["svelte-check@4.7.7", "", { "dependencies": { "@jridgewell/trace-mapping": "^0.3.25", "@sveltejs/load-config": "^0.2.3", "chokidar": "^4.0.1", "fdir": "^6.2.0", "picocolors": "^1.0.0", "sade": "^1.7.4" }, "peerDependencies": { "svelte": "^4.0.0 || ^5.0.0-next.0", "typescript": "^5.0.0 || ^6.0.0" }, "bin": { "svelte-check": "bin/svelte-check" } }, "sha512-Ge2IMdeTpbJuzNFGRiiMg0RWgbScysKQu7xwcyFJ22+DU9F5nPX51+Q3gHmGqRxYQMx2knreVWt5oCtfe0vf2g=="], "@beesolve/analytics-dashboard/typescript": ["typescript@6.0.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw=="], @@ -1601,6 +1715,40 @@ "svelte/magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], + "@aws-sdk/client-ssm/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.43", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-rG8QVx4DOrJWptsogu1Aq+CDsnPKaBrAlJpKLxrJrIDXAq1ElnW0yQjjBnlWSXll0cDakCG6UDvaqwz0A9d9Og=="], + + "@aws-sdk/client-ssm/@aws-sdk/core/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="], + + "@aws-sdk/client-ssm/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-env": ["@aws-sdk/credential-provider-env@3.972.84", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-akZJetiMVeLRHsKzYh3LamDCo74ZUCeo0XoyRKMEMZT5qP7ReM6LhpioBCyuqKP5Vav5gEOeCmaQV0VVQr1Meg=="], + + "@aws-sdk/client-ssm/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-http": ["@aws-sdk/credential-provider-http@3.972.86", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-U4mHaDRPWAn63yhl7FXIzbppNmW1F+4dSLeuiUpej2v3Xb6rGwvayEJ8SdlrdMV+/mZtd+GStTEP2HqurEzXtw=="], + + "@aws-sdk/client-ssm/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini": ["@aws-sdk/credential-provider-ini@3.973.30", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/credential-provider-env": "^3.972.84", "@aws-sdk/credential-provider-http": "^3.972.86", "@aws-sdk/credential-provider-login": "^3.972.92", "@aws-sdk/credential-provider-process": "^3.972.84", "@aws-sdk/credential-provider-sso": "^3.973.28", "@aws-sdk/credential-provider-web-identity": "^3.972.90", "@aws-sdk/nested-clients": "^3.998.3", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-r6r6499GWoGN943NA5YEhBEQ6TEOGTf7tTOBhHd/zw0UbNvSzd1/zPCNcDkPmRarA+e24X7KgxutqxjoWcskBg=="], + + "@aws-sdk/client-ssm/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-process": ["@aws-sdk/credential-provider-process@3.972.84", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-199C6OpNejd0nq9GFAkEFIKids1FL0R6LJtL9c1OTiDOXki7S1OduuPxW4+hE0LwndcYJ7YHOuYTlqScfpCocA=="], + + "@aws-sdk/client-ssm/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso": ["@aws-sdk/credential-provider-sso@3.973.28", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/nested-clients": "^3.998.3", "@aws-sdk/token-providers": "3.1166.0", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-bGg7wH8wVDJQIcJggO9lg1ZYbG7l+PbLwHuM3Bi/e1TlCZhU712JS1W3tdRpyptdJD1UGyhBNGO/YrhrQCHKbg=="], + + "@aws-sdk/client-ssm/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity": ["@aws-sdk/credential-provider-web-identity@3.972.90", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/nested-clients": "^3.998.3", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-duLeE3xlf0viHeH+1RM4z5duR3b32BCZTWVMu+MbxFPjQBxy7hmIGEqt5hekuFPRuXoyhMovjNl+PNNsb5oiGQ=="], + + "@aws-sdk/dsql-signer/@aws-sdk/core/@aws-sdk/types": ["@aws-sdk/types@3.975.1", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-7rGxUkCB2QPoQOeJmonmAICTN2zrH+fpmi1p4Iwu72lnxNaMhOgqcbpyddifnM1DBb19TWQ1u6z/XjkaFNEDWw=="], + + "@aws-sdk/dsql-signer/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.43", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-rG8QVx4DOrJWptsogu1Aq+CDsnPKaBrAlJpKLxrJrIDXAq1ElnW0yQjjBnlWSXll0cDakCG6UDvaqwz0A9d9Og=="], + + "@aws-sdk/dsql-signer/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-env": ["@aws-sdk/credential-provider-env@3.972.84", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-akZJetiMVeLRHsKzYh3LamDCo74ZUCeo0XoyRKMEMZT5qP7ReM6LhpioBCyuqKP5Vav5gEOeCmaQV0VVQr1Meg=="], + + "@aws-sdk/dsql-signer/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-http": ["@aws-sdk/credential-provider-http@3.972.86", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-U4mHaDRPWAn63yhl7FXIzbppNmW1F+4dSLeuiUpej2v3Xb6rGwvayEJ8SdlrdMV+/mZtd+GStTEP2HqurEzXtw=="], + + "@aws-sdk/dsql-signer/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini": ["@aws-sdk/credential-provider-ini@3.973.30", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/credential-provider-env": "^3.972.84", "@aws-sdk/credential-provider-http": "^3.972.86", "@aws-sdk/credential-provider-login": "^3.972.92", "@aws-sdk/credential-provider-process": "^3.972.84", "@aws-sdk/credential-provider-sso": "^3.973.28", "@aws-sdk/credential-provider-web-identity": "^3.972.90", "@aws-sdk/nested-clients": "^3.998.3", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-r6r6499GWoGN943NA5YEhBEQ6TEOGTf7tTOBhHd/zw0UbNvSzd1/zPCNcDkPmRarA+e24X7KgxutqxjoWcskBg=="], + + "@aws-sdk/dsql-signer/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-process": ["@aws-sdk/credential-provider-process@3.972.84", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-199C6OpNejd0nq9GFAkEFIKids1FL0R6LJtL9c1OTiDOXki7S1OduuPxW4+hE0LwndcYJ7YHOuYTlqScfpCocA=="], + + "@aws-sdk/dsql-signer/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso": ["@aws-sdk/credential-provider-sso@3.973.28", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/nested-clients": "^3.998.3", "@aws-sdk/token-providers": "3.1166.0", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-bGg7wH8wVDJQIcJggO9lg1ZYbG7l+PbLwHuM3Bi/e1TlCZhU712JS1W3tdRpyptdJD1UGyhBNGO/YrhrQCHKbg=="], + + "@aws-sdk/dsql-signer/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity": ["@aws-sdk/credential-provider-web-identity@3.972.90", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/nested-clients": "^3.998.3", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-duLeE3xlf0viHeH+1RM4z5duR3b32BCZTWVMu+MbxFPjQBxy7hmIGEqt5hekuFPRuXoyhMovjNl+PNNsb5oiGQ=="], + + "@aws-sdk/dsql-signer/@aws-sdk/credential-provider-node/@aws-sdk/types": ["@aws-sdk/types@3.975.1", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-7rGxUkCB2QPoQOeJmonmAICTN2zrH+fpmi1p4Iwu72lnxNaMhOgqcbpyddifnM1DBb19TWQ1u6z/XjkaFNEDWw=="], + "@beesolve/analytics-dashboard/svelte-check/chokidar": ["chokidar@4.0.3", "", { "dependencies": { "readdirp": "^4.0.1" } }, "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA=="], "@beesolve/dmarc-dashboard/svelte-check/chokidar": ["chokidar@4.0.3", "", { "dependencies": { "readdirp": "^4.0.1" } }, "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA=="], @@ -1617,6 +1765,30 @@ "aws-cdk-lib/@aws-cdk/cloud-assembly-schema/semver": ["semver@7.8.5", "", { "bundled": true, "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="], + "@aws-sdk/client-ssm/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/credential-provider-login": ["@aws-sdk/credential-provider-login@3.972.92", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/nested-clients": "^3.998.3", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-96bcp9Pe/Xd60OEwncZ+kAQTQSu+fJnpUGz1qE6ghF5jnETmrk8XMU86mIP3lolvnCgR61XbZ+Ht6hdBjiQOmQ=="], + + "@aws-sdk/client-ssm/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.998.3", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/signature-v4-multi-region": "^3.996.52", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-acHTTzMB13CU6dU4sxABYExMI3PQM2zStWH2MiUwJp/7QKTrLg2f7mbzSXoegW2kYOk2tdqQYagsZrWB8Xv7eA=="], + + "@aws-sdk/client-ssm/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.998.3", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/signature-v4-multi-region": "^3.996.52", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-acHTTzMB13CU6dU4sxABYExMI3PQM2zStWH2MiUwJp/7QKTrLg2f7mbzSXoegW2kYOk2tdqQYagsZrWB8Xv7eA=="], + + "@aws-sdk/client-ssm/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/token-providers": ["@aws-sdk/token-providers@3.1166.0", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/nested-clients": "^3.998.3", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-ngJ8mxXqtQ9mnp7QV6TWKJCxkpjVfPWxKQSc2FYhCyCfOVFIGdFv7P+/RqVffFrJAorwBPpktnv32gNlcEgF4g=="], + + "@aws-sdk/client-ssm/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.998.3", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/signature-v4-multi-region": "^3.996.52", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-acHTTzMB13CU6dU4sxABYExMI3PQM2zStWH2MiUwJp/7QKTrLg2f7mbzSXoegW2kYOk2tdqQYagsZrWB8Xv7eA=="], + + "@aws-sdk/dsql-signer/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-http/@smithy/fetch-http-handler": ["@smithy/fetch-http-handler@5.8.1", "", { "dependencies": { "@smithy/core": "^3.39.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-h8BdMUrUBhMhMaeK7QqAdINRZezCGuYOCpcOZZ1ewxbHST9rdTd09xwNpvLTYfzDRehxQiReK4SKbdYZxBA+ew=="], + + "@aws-sdk/dsql-signer/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-http/@smithy/node-http-handler": ["@smithy/node-http-handler@4.14.2", "", { "dependencies": { "@smithy/core": "^3.39.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-i1uORV1v3qBqP43ayRKzIdm1q5x14tf8N4Dd06/QUX1Szm6VxHMrTsu20X5E63UFsaNZCRjI4SXG0jDmqYa+3w=="], + + "@aws-sdk/dsql-signer/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/credential-provider-login": ["@aws-sdk/credential-provider-login@3.972.92", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/nested-clients": "^3.998.3", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-96bcp9Pe/Xd60OEwncZ+kAQTQSu+fJnpUGz1qE6ghF5jnETmrk8XMU86mIP3lolvnCgR61XbZ+Ht6hdBjiQOmQ=="], + + "@aws-sdk/dsql-signer/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.998.3", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/signature-v4-multi-region": "^3.996.52", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-acHTTzMB13CU6dU4sxABYExMI3PQM2zStWH2MiUwJp/7QKTrLg2f7mbzSXoegW2kYOk2tdqQYagsZrWB8Xv7eA=="], + + "@aws-sdk/dsql-signer/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.998.3", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/signature-v4-multi-region": "^3.996.52", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-acHTTzMB13CU6dU4sxABYExMI3PQM2zStWH2MiUwJp/7QKTrLg2f7mbzSXoegW2kYOk2tdqQYagsZrWB8Xv7eA=="], + + "@aws-sdk/dsql-signer/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/token-providers": ["@aws-sdk/token-providers@3.1166.0", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/nested-clients": "^3.998.3", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-ngJ8mxXqtQ9mnp7QV6TWKJCxkpjVfPWxKQSc2FYhCyCfOVFIGdFv7P+/RqVffFrJAorwBPpktnv32gNlcEgF4g=="], + + "@aws-sdk/dsql-signer/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.998.3", "", { "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/signature-v4-multi-region": "^3.996.52", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-acHTTzMB13CU6dU4sxABYExMI3PQM2zStWH2MiUwJp/7QKTrLg2f7mbzSXoegW2kYOk2tdqQYagsZrWB8Xv7eA=="], + "@beesolve/analytics-dashboard/svelte-check/chokidar/readdirp": ["readdirp@4.1.2", "", {}, "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg=="], "@beesolve/dmarc-dashboard/svelte-check/chokidar/readdirp": ["readdirp@4.1.2", "", {}, "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg=="], @@ -1627,8 +1799,38 @@ "@react-email/render/html-to-text/selderee/parseley": ["parseley@0.12.1", "", { "dependencies": { "leac": "^0.6.0", "peberminta": "^0.9.0" } }, "sha512-e6qHKe3a9HWr0oMRVDTRhKce+bRO8VGQR3NyVwcjwrbhMmFCX9KszEV35+rn4AdilFAq9VPxP/Fe1wC9Qjd2lw=="], + "@aws-sdk/client-ssm/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.52", "", { "dependencies": { "@aws-sdk/types": "^3.975.1", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-6W6SjGc8OXUhMzNxU1X922ghD+PP1XvzmCk5Scui0jaYsLezycMYR1RaLp5xTIOUrhTXyb4DnAbPr3fBgmdnzg=="], + + "@aws-sdk/client-ssm/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.52", "", { "dependencies": { "@aws-sdk/types": "^3.975.1", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-6W6SjGc8OXUhMzNxU1X922ghD+PP1XvzmCk5Scui0jaYsLezycMYR1RaLp5xTIOUrhTXyb4DnAbPr3fBgmdnzg=="], + + "@aws-sdk/client-ssm/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.52", "", { "dependencies": { "@aws-sdk/types": "^3.975.1", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-6W6SjGc8OXUhMzNxU1X922ghD+PP1XvzmCk5Scui0jaYsLezycMYR1RaLp5xTIOUrhTXyb4DnAbPr3fBgmdnzg=="], + + "@aws-sdk/dsql-signer/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.52", "", { "dependencies": { "@aws-sdk/types": "^3.975.1", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-6W6SjGc8OXUhMzNxU1X922ghD+PP1XvzmCk5Scui0jaYsLezycMYR1RaLp5xTIOUrhTXyb4DnAbPr3fBgmdnzg=="], + + "@aws-sdk/dsql-signer/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@smithy/fetch-http-handler": ["@smithy/fetch-http-handler@5.8.1", "", { "dependencies": { "@smithy/core": "^3.39.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-h8BdMUrUBhMhMaeK7QqAdINRZezCGuYOCpcOZZ1ewxbHST9rdTd09xwNpvLTYfzDRehxQiReK4SKbdYZxBA+ew=="], + + "@aws-sdk/dsql-signer/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@smithy/node-http-handler": ["@smithy/node-http-handler@4.14.2", "", { "dependencies": { "@smithy/core": "^3.39.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-i1uORV1v3qBqP43ayRKzIdm1q5x14tf8N4Dd06/QUX1Szm6VxHMrTsu20X5E63UFsaNZCRjI4SXG0jDmqYa+3w=="], + + "@aws-sdk/dsql-signer/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.52", "", { "dependencies": { "@aws-sdk/types": "^3.975.1", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-6W6SjGc8OXUhMzNxU1X922ghD+PP1XvzmCk5Scui0jaYsLezycMYR1RaLp5xTIOUrhTXyb4DnAbPr3fBgmdnzg=="], + + "@aws-sdk/dsql-signer/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@smithy/fetch-http-handler": ["@smithy/fetch-http-handler@5.8.1", "", { "dependencies": { "@smithy/core": "^3.39.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-h8BdMUrUBhMhMaeK7QqAdINRZezCGuYOCpcOZZ1ewxbHST9rdTd09xwNpvLTYfzDRehxQiReK4SKbdYZxBA+ew=="], + + "@aws-sdk/dsql-signer/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@smithy/node-http-handler": ["@smithy/node-http-handler@4.14.2", "", { "dependencies": { "@smithy/core": "^3.39.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-i1uORV1v3qBqP43ayRKzIdm1q5x14tf8N4Dd06/QUX1Szm6VxHMrTsu20X5E63UFsaNZCRjI4SXG0jDmqYa+3w=="], + + "@aws-sdk/dsql-signer/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.52", "", { "dependencies": { "@aws-sdk/types": "^3.975.1", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-6W6SjGc8OXUhMzNxU1X922ghD+PP1XvzmCk5Scui0jaYsLezycMYR1RaLp5xTIOUrhTXyb4DnAbPr3fBgmdnzg=="], + + "@aws-sdk/dsql-signer/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@smithy/fetch-http-handler": ["@smithy/fetch-http-handler@5.8.1", "", { "dependencies": { "@smithy/core": "^3.39.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-h8BdMUrUBhMhMaeK7QqAdINRZezCGuYOCpcOZZ1ewxbHST9rdTd09xwNpvLTYfzDRehxQiReK4SKbdYZxBA+ew=="], + + "@aws-sdk/dsql-signer/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@smithy/node-http-handler": ["@smithy/node-http-handler@4.14.2", "", { "dependencies": { "@smithy/core": "^3.39.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-i1uORV1v3qBqP43ayRKzIdm1q5x14tf8N4Dd06/QUX1Szm6VxHMrTsu20X5E63UFsaNZCRjI4SXG0jDmqYa+3w=="], + "@react-email/render/html-to-text/selderee/parseley/leac": ["leac@0.6.0", "", {}, "sha512-y+SqErxb8h7nE/fiEX07jsbuhrpO9lL8eca7/Y1nuWV2moNlXhyd59iDGcRf6moVyDMbmTNzL40SUyrFU/yDpg=="], "@react-email/render/html-to-text/selderee/parseley/peberminta": ["peberminta@0.9.0", "", {}, "sha512-XIxfHpEuSJbITd1H3EeQwpcZbTLHc+VVr8ANI9t5sit565tsI4/xK3KWTUFE2e6QiangUkh3B0jihzmGnNrRsQ=="], + + "@aws-sdk/client-ssm/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="], + + "@aws-sdk/client-ssm/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="], + + "@aws-sdk/client-ssm/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region/@smithy/signature-v4": ["@smithy/signature-v4@5.7.5", "", { "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg=="], } } diff --git a/bunup.config.ts b/bunup.config.ts index 69cdd4e7..cdd8002b 100644 --- a/bunup.config.ts +++ b/bunup.config.ts @@ -206,6 +206,13 @@ const workspace: Array = [ entry: ["index.ts"], }, }, + { + name: "@beesolve/dsql-helpers", + root: "packages/helpers-dsql", + config: { + entry: ["index.ts", "cdk.ts", "admin.ts"], + }, + }, { name: "@beesolve/analytics-processor", root: "packages/analytics-processor", diff --git a/dependencies.json b/dependencies.json index 9b0c1fb7..9627a160 100644 --- a/dependencies.json +++ b/dependencies.json @@ -5,6 +5,7 @@ "packages/dmarc-parser", "packages/helpers", "packages/cdk-constructs", + "packages/helpers-dsql", "packages/helpers-dynamo", "packages/hmac", "packages/ip-info", diff --git a/package.json b/package.json index dcb292cf..200fa689 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/packages/helpers-dsql/DOCS.md b/packages/helpers-dsql/DOCS.md new file mode 100644 index 00000000..2a6f3705 --- /dev/null +++ b/packages/helpers-dsql/DOCS.md @@ -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) diff --git a/packages/helpers-dsql/README.md b/packages/helpers-dsql/README.md new file mode 100644 index 00000000..606a7920 --- /dev/null +++ b/packages/helpers-dsql/README.md @@ -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 TO ''`). **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//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 `_read`, `_write`, `_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`, `Tx`, `Executor`, `Transact` and `DbProps` 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. diff --git a/packages/helpers-dsql/admin.ts b/packages/helpers-dsql/admin.ts new file mode 100644 index 00000000..05c4e690 --- /dev/null +++ b/packages/helpers-dsql/admin.ts @@ -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"; diff --git a/packages/helpers-dsql/cdk.ts b/packages/helpers-dsql/cdk.ts new file mode 100644 index 00000000..38bfb9a9 --- /dev/null +++ b/packages/helpers-dsql/cdk.ts @@ -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"; diff --git a/packages/helpers-dsql/docs/adr-001-motivation.md b/packages/helpers-dsql/docs/adr-001-motivation.md new file mode 100644 index 00000000..376af7ae --- /dev/null +++ b/packages/helpers-dsql/docs/adr-001-motivation.md @@ -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 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://dev.to/damien_pace_2c3ec240cbd46/how-i-made-dsql-easier-4je5 diff --git a/packages/helpers-dsql/docs/adr-002-manifest-and-admin-reconcile.md b/packages/helpers-dsql/docs/adr-002-manifest-and-admin-reconcile.md new file mode 100644 index 00000000..af4ac8cb --- /dev/null +++ b/packages/helpers-dsql/docs/adr-002-manifest-and-admin-reconcile.md @@ -0,0 +1,50 @@ +# ADR-002: Access Manifest in SSM, Applied by an Admin Step + +## Status + +Accepted + +## Context + +Roles, table privileges and IAM mappings live inside the cluster and can only be changed over an `admin` connection, which needs `dsql:DbConnectAdmin`. CDK knows the desired state (roles, and the Lambda role ARNs as deploy-time tokens) but cannot run SQL by itself. Something has to carry the desired state from the deploy to an admin connection, and something has to run the SQL. + +Tables only exist after migrations, and migrations already run in an admin step after deploy. + +## Decision + +- The construct writes the desired state, the access manifest, to the SSM parameter `/beesolve/dsql//access-manifest`. +- `reconcileAccess` runs in the same admin step as the migrations, after them. It reads the parameter (`readAccessManifest`, name derived from the endpoint), diffs it against the cluster, applies the difference, and verifies. + +## Rationale + +### 1. No new admin-capable resource in the stack + +Only the operator running the admin step holds admin access, as before. A deploy can only change the desired state, never run SQL. + +### 2. Runs after migrations + +A role without a table list covers every table in the schema. Applying it after migrations covers new tables without `ALTER DEFAULT PRIVILEGES`, which DSQL may reject with 0A000. + +### 3. The manifest does not fit a stack output + +A CloudFormation output is limited to 1,024 characters; a few Lambda role ARNs already exceed it. A standard SSM parameter holds 4 KB (advanced: 8 KB), and its name is derived from the cluster id, so the admin step needs no extra configuration. + +## Consequences + +- Between a deploy that changes a function's role and the admin step, that function cannot log in as its new role. The admin step must run right after such deploys. +- The manifest is untrusted input to SQL. It is validated (identifier allowlist, privilege allowlist, ARN pattern, principals in the cluster's account), and a manifest naming a different cluster than the endpoint is refused. +- Anyone with `ssm:PutParameter` on the parameter can change the desired state; the operator applies it. `dryRun` shows the plan first. + +## Alternatives Considered + +### CloudFormation custom resource + +A Lambda with `dsql:DbConnectAdmin` runs the reconciler on every deploy, with the manifest as resource properties (no SSM). Access would change in the same deploy, and Lambdas could depend on it so they never run with a role that does not exist yet. Rejected for now: it puts an admin-capable function in every stack, and on the first deploy it runs before migrations create the tables, so table-scoped roles and full coverage of new tables still need the post-migration run. Can be added later on top of the same `reconcileAccess`. + +### DynamoDB table and stream-triggered Lambda (Anvil's design) + +Deploys write items, a stream-triggered Lambda is the only admin connection. Equivalent to the custom resource in CDK, where CloudFormation is already the trusted writer, with more moving parts. + +### Stack output + +Rejected because of the 1,024-character limit. diff --git a/packages/helpers-dsql/docs/how-to/getting-started.md b/packages/helpers-dsql/docs/how-to/getting-started.md new file mode 100644 index 00000000..760138a9 --- /dev/null +++ b/packages/helpers-dsql/docs/how-to/getting-started.md @@ -0,0 +1,77 @@ +# Getting Started + +Declare an Aurora DSQL cluster and its database roles in CDK, apply the access after migrations, and connect from a Lambda. + +## 1. Install + +```bash +bun add @beesolve/dsql-helpers @aws/aurora-dsql-drizzle drizzle-orm pg +bun add -d aws-cdk-lib constructs +``` + +## 2. Declare the cluster and grant access + +```ts +import { DsqlCluster } from "@beesolve/dsql-helpers/cdk"; + +const dsql = new DsqlCluster(this, "Dsql", { + roles: { + digest: { privileges: ["SELECT", "UPDATE"], tables: ["pending_notifications"] }, + }, +}); + +dsql.grantReadWrite(apiHandler); +dsql.grant(digestHandler, "digest"); +``` + +Each grant gives the function `dsql:DbConnect` on the cluster and sets `DSQL_ENDPOINT`, `DSQL_REGION` and `DSQL_DB_USER` (the role name). Deploy; the desired access is written to the SSM parameter `/beesolve/dsql//access-manifest`. + +## 3. Apply access after migrations + +Run this as an admin step after every deploy (credentials with `dsql:DbConnectAdmin` and `ssm:GetParameter`): + +```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 }); + await reconcileAccess({ + client: db.$client, + manifest, + dryRun: process.argv.includes("--dry-run"), + }); +} finally { + await db.$client.end(); +} +``` + +Until this step has run, a function granted a new role cannot log in as it. Run it right after the deploy that adds or changes grants. + +## 4. Connect from the Lambda + +```ts +import { createDsqlDatabase, toDsqlConfig } from "@beesolve/dsql-helpers"; + +import * as schema from "./schema"; + +const { db, transact } = createDsqlDatabase({ + config: toDsqlConfig(), + schema, + casing: "snake_case", +}); + +export const handler = async () => { + await transact(async (tx) => { + await tx.update(schema.pendingNotifications).set({ sent: true }); + }); +}; +``` + +`transact` retries optimistic concurrency conflicts, so the callback may run more than once: keep emails, queue messages and other side effects after it returns. diff --git a/packages/helpers-dsql/index.ts b/packages/helpers-dsql/index.ts new file mode 100644 index 00000000..48c36dee --- /dev/null +++ b/packages/helpers-dsql/index.ts @@ -0,0 +1,4 @@ +export * from "./src/database"; +export * from "./src/env"; +export * from "./src/envNames"; +export * from "./src/errors"; diff --git a/packages/helpers-dsql/package.json b/packages/helpers-dsql/package.json new file mode 100644 index 00000000..5219845f --- /dev/null +++ b/packages/helpers-dsql/package.json @@ -0,0 +1,87 @@ +{ + "name": "@beesolve/dsql-helpers", + "version": "0.0.0", + "description": "Aurora DSQL helpers: CDK cluster construct with per-table role grants, an access reconciler, and a Drizzle database factory", + "homepage": "https://github.com/BeeSolve/packages/tree/main/packages/helpers-dsql#readme", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/BeeSolve/packages.git" + }, + "files": [ + "dist", + "docs/how-to", + "DOCS.md" + ], + "type": "module", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "./cdk": { + "import": { + "types": "./dist/cdk.d.ts", + "default": "./dist/cdk.js" + } + }, + "./admin": { + "import": { + "types": "./dist/admin.d.ts", + "default": "./dist/admin.js" + } + }, + "./package.json": "./package.json" + }, + "scripts": { + "test": "bun test", + "type-check": "tsc --noEmit" + }, + "dependencies": { + "@aws-sdk/client-ssm": "catalog:", + "@aws-sdk/credential-providers": "catalog:", + "valibot": "catalog:" + }, + "devDependencies": { + "@aws/aurora-dsql-drizzle": "catalog:", + "@types/bun": "catalog:", + "@types/node": "catalog:", + "@types/pg": "catalog:", + "aws-cdk-lib": "catalog:", + "constructs": "catalog:", + "drizzle-orm": "catalog:", + "pg": "catalog:" + }, + "peerDependencies": { + "@aws/aurora-dsql-drizzle": "catalog:", + "aws-cdk-lib": "catalog:", + "constructs": "catalog:", + "drizzle-orm": "catalog:", + "pg": "catalog:", + "typescript": "catalog:" + }, + "peerDependenciesMeta": { + "@aws/aurora-dsql-drizzle": { + "optional": true + }, + "aws-cdk-lib": { + "optional": true + }, + "constructs": { + "optional": true + }, + "drizzle-orm": { + "optional": true + }, + "pg": { + "optional": true + }, + "typescript": { + "optional": true + } + } +} diff --git a/packages/helpers-dsql/src/access/manifest.ts b/packages/helpers-dsql/src/access/manifest.ts new file mode 100644 index 00000000..5f50def0 --- /dev/null +++ b/packages/helpers-dsql/src/access/manifest.ts @@ -0,0 +1,118 @@ +import * as v from "valibot"; + +/** Table privileges a role can be granted. */ +export const dsqlPrivileges = ["SELECT", "INSERT", "UPDATE", "DELETE"] as const; +export type DsqlPrivilege = (typeof dsqlPrivileges)[number]; + +/** + * Identifiers are interpolated into SQL (identifiers cannot be bound parameters), so only plain + * lowercase PostgreSQL identifiers are accepted. Drizzle's `snake_case` names fit. + */ +const identifierPattern = /^[a-z_][a-z0-9_]{0,62}$/; +const reservedRoleNames: ReadonlySet = new Set(["admin", "public", "none", "postgres"]); +/** ARNs are interpolated into a quoted literal, so only the IAM role/user ARN charset is accepted. */ +const principalArnPattern = /^arn:aws[a-z-]*:iam::(\d{12}):(role|user)\/[\w+=,.@/-]+$/; + +export function assertRoleName(name: string): void { + if (!identifierPattern.test(name) || name.startsWith("pg_") || reservedRoleNames.has(name)) { + throw new Error( + `Invalid DSQL role name "${name}": use lowercase letters, digits and "_" (max 63), not starting with "pg_", and not ${[...reservedRoleNames].join(", ")}.`, + ); + } +} + +export function assertTableName(name: string): void { + if (!identifierPattern.test(name)) { + throw new Error( + `Invalid table name "${name}": use lowercase letters, digits and "_" (max 63).`, + ); + } +} + +export function assertSchemaName(name: string): void { + if (!identifierPattern.test(name) || name.startsWith("pg_") || name === "sys") { + throw new Error(`Invalid schema name "${name}".`); + } +} + +export function assertPrincipalArn(arn: string): void { + if (!principalArnPattern.test(arn)) { + throw new Error(`Not an IAM role or user ARN: "${arn}".`); + } +} + +export function toPrincipalAccount(arn: string): string | undefined { + return principalArnPattern.exec(arn)?.[1]; +} + +const roleNameSchema = v.pipe( + v.string(), + v.check((name) => { + try { + assertRoleName(name); + return true; + } catch { + return false; + } + }, "Invalid role name."), +); +const tableNameSchema = v.pipe(v.string(), v.regex(identifierPattern, "Invalid table name.")); +const schemaNameSchema = v.pipe( + v.string(), + v.regex(identifierPattern, "Invalid schema name."), + v.check((name) => !name.startsWith("pg_") && name !== "sys", "Invalid schema name."), +); +const principalArnSchema = v.pipe( + v.string(), + v.regex(principalArnPattern, "Invalid principal ARN."), +); + +const accessRoleSchema = v.object({ + name: roleNameSchema, + privileges: v.pipe(v.array(v.picklist(dsqlPrivileges)), v.minLength(1)), + tables: v.optional(v.pipe(v.array(tableNameSchema), v.minLength(1))), + principals: v.array(principalArnSchema), +}); + +const accessManifestSchema = v.pipe( + v.object({ + version: v.literal(1), + clusterId: v.pipe(v.string(), v.regex(/^[a-z0-9]+$/, "Invalid cluster id.")), + account: v.pipe(v.string(), v.regex(/^\d{12}$/, "Invalid account id.")), + schema: schemaNameSchema, + roles: v.array(accessRoleSchema), + }), + v.check( + (manifest) => new Set(manifest.roles.map((role) => role.name)).size === manifest.roles.length, + "Role names must be unique.", + ), +); + +/** One database role: what it may do, where, and which IAM principals log in as it. */ +export type AccessRole = { + readonly name: string; + readonly privileges: ReadonlyArray; + /** Tables the privileges apply to. Absent means every table in the schema, including later ones. */ + readonly tables?: ReadonlyArray | undefined; + /** IAM role or user ARNs mapped to this role with `AWS IAM GRANT`. */ + readonly principals: ReadonlyArray; +}; + +/** Desired database access, written by the CDK construct and applied by {@link reconcileAccess}. */ +export type AccessManifest = { + readonly version: 1; + readonly clusterId: string; + readonly account: string; + readonly schema: string; + readonly roles: ReadonlyArray; +}; + +/** Validates untrusted input (for example the SSM parameter value) as an {@link AccessManifest}. */ +export function parseAccessManifest(value: unknown): AccessManifest { + return v.parse(accessManifestSchema, value); +} + +/** SSM parameter that holds the manifest of a cluster. */ +export function toAccessManifestParameterName(clusterId: string): string { + return `/beesolve/dsql/${clusterId}/access-manifest`; +} diff --git a/packages/helpers-dsql/src/access/plan.ts b/packages/helpers-dsql/src/access/plan.ts new file mode 100644 index 00000000..90eacbbf --- /dev/null +++ b/packages/helpers-dsql/src/access/plan.ts @@ -0,0 +1,189 @@ +import { + type AccessManifest, + assertPrincipalArn, + assertRoleName, + assertSchemaName, + assertTableName, + type DsqlPrivilege, + dsqlPrivileges, + toPrincipalAccount, +} from "./manifest"; +import { type AccessState, toUndeclaredMappedRoles } from "./state"; + +export type AccessPlan = { + /** SQL to run, in order. Empty when the cluster already matches the manifest. */ + readonly statements: ReadonlyArray; + /** Mismatches that block applying the plan. */ + readonly problems: ReadonlyArray; + /** Drift that is reported but left alone (see `prune`). */ + readonly warnings: ReadonlyArray; +}; + +const emptyPrivileges: ReadonlySet = new Set(); + +function toPrivilegeList(privileges: Iterable): string { + const set = new Set(privileges); + return dsqlPrivileges.filter((privilege) => set.has(privilege)).join(", "); +} + +/** + * Computes the SQL that makes the cluster match the manifest. Pure: no database access. + * + * Declared roles converge in both directions: missing privileges and IAM mappings are granted, + * extra ones revoked. Roles that are mapped to IAM but not declared are only reported, unless + * `prune` is set, in which case their mappings and privileges are revoked and the role dropped. + * + * Privileges are granted before the IAM mapping, so a principal never logs in as a role that + * cannot yet use its tables. Stale mappings are revoked before new ones are granted, so moving + * a principal from one role to another works even if DSQL allows one role per principal. + */ +export function planAccess(props: { + readonly manifest: AccessManifest; + readonly state: AccessState; + readonly prune?: boolean; +}): AccessPlan { + const { manifest, state } = props; + const problems: Array = []; + const warnings: Array = []; + + assertSchemaName(manifest.schema); + const schema = manifest.schema; + const isPublicSchema = schema === "public"; + const qualified = (table: string) => `"${schema}"."${table}"`; + + if (!state.schemaExists) { + problems.push(`Schema "${schema}" does not exist. Create it in a migration first.`); + } + + const existingTables = new Set(state.tables); + const creates: Array = []; + const usageGrants: Array = []; + const tableGrants: Array = []; + const tableRevokes: Array = []; + const mappingRevokes: Array = []; + const mappingGrants: Array = []; + + for (const role of manifest.roles) { + assertRoleName(role.name); + const exists = state.existingRoles.has(role.name); + + if (!exists) { + creates.push(`CREATE ROLE ${role.name} WITH LOGIN`); + } + + if (exists && state.schemaExists && state.schemaUsage.get(role.name) !== true) { + if (isPublicSchema) { + problems.push( + `Role ${role.name} has no USAGE on schema public, and DSQL does not allow granting it on that system schema.`, + ); + } else { + usageGrants.push(`GRANT USAGE ON SCHEMA "${schema}" TO ${role.name}`); + } + } else if (!exists && !isPublicSchema) { + usageGrants.push(`GRANT USAGE ON SCHEMA "${schema}" TO ${role.name}`); + } + + for (const table of role.tables ?? []) { + assertTableName(table); + if (!existingTables.has(table)) { + problems.push( + `Role ${role.name} lists table "${table}", which does not exist in schema "${schema}".`, + ); + } + } + + const scopedTables = new Set(role.tables ?? state.tables); + const current = state.tablePrivileges.get(role.name); + for (const table of state.tables) { + const desired: ReadonlySet = scopedTables.has(table) + ? new Set(role.privileges) + : emptyPrivileges; + const held = current?.get(table) ?? emptyPrivileges; + const missing = [...desired].filter((privilege) => !held.has(privilege)); + const extra = [...held].filter((privilege) => !desired.has(privilege)); + if (missing.length > 0) { + tableGrants.push( + `GRANT ${toPrivilegeList(missing)} ON TABLE ${qualified(table)} TO ${role.name}`, + ); + } + if (extra.length > 0) { + tableRevokes.push( + `REVOKE ${toPrivilegeList(extra)} ON TABLE ${qualified(table)} FROM ${role.name}`, + ); + } + } + + const desiredPrincipals = new Set(role.principals); + const mappedPrincipals = new Set( + state.mappings.filter((mapping) => mapping.role === role.name).map((mapping) => mapping.arn), + ); + for (const arn of desiredPrincipals) { + assertPrincipalArn(arn); + if (toPrincipalAccount(arn) !== manifest.account) { + problems.push( + `Principal ${arn} of role ${role.name} is not in account ${manifest.account}, the account of the cluster.`, + ); + } + if (!mappedPrincipals.has(arn)) { + mappingGrants.push(`AWS IAM GRANT ${role.name} TO '${arn}'`); + } + const otherRoles = state.mappings + .filter((mapping) => mapping.arn === arn && mapping.role !== role.name) + .map((mapping) => mapping.role); + for (const other of otherRoles) { + if (!manifest.roles.some((declared) => declared.name === other) && !props.prune) { + warnings.push( + `${arn} is also mapped to undeclared role ${other}. Run with prune to revoke it.`, + ); + } + } + } + for (const arn of mappedPrincipals) { + if (!desiredPrincipals.has(arn)) { + assertPrincipalArn(arn); + mappingRevokes.push(`AWS IAM REVOKE ${role.name} FROM '${arn}'`); + } + } + } + + const pruneStatements: Array = []; + for (const role of toUndeclaredMappedRoles(manifest, state.mappings)) { + if (!props.prune) { + warnings.push( + `Role ${role} is mapped to IAM principals but not declared. Run with prune to revoke and drop it.`, + ); + continue; + } + assertRoleName(role); + for (const mapping of state.mappings.filter((candidate) => candidate.role === role)) { + assertPrincipalArn(mapping.arn); + pruneStatements.push(`AWS IAM REVOKE ${role} FROM '${mapping.arn}'`); + } + for (const [table, held] of state.tablePrivileges.get(role) ?? []) { + if (held.size > 0) { + assertTableName(table); + pruneStatements.push( + `REVOKE ${toPrivilegeList(held)} ON TABLE ${qualified(table)} FROM ${role}`, + ); + } + } + if (!isPublicSchema && state.schemaUsage.get(role) === true) { + pruneStatements.push(`REVOKE USAGE ON SCHEMA "${schema}" FROM ${role}`); + } + pruneStatements.push(`DROP ROLE ${role}`); + } + + return { + statements: [ + ...creates, + ...usageGrants, + ...tableGrants, + ...mappingRevokes, + ...mappingGrants, + ...tableRevokes, + ...pruneStatements, + ], + problems: [...new Set(problems)], + warnings: [...new Set(warnings)], + }; +} diff --git a/packages/helpers-dsql/src/access/reconcile.ts b/packages/helpers-dsql/src/access/reconcile.ts new file mode 100644 index 00000000..bccd64dd --- /dev/null +++ b/packages/helpers-dsql/src/access/reconcile.ts @@ -0,0 +1,80 @@ +import type { AccessManifest } from "./manifest"; +import { type AccessPlan, planAccess } from "./plan"; +import { readAccessState, type SqlClient } from "./state"; + +export type ReconcileAccessProps = { + /** Connected as `admin` (IAM `dsql:DbConnectAdmin`). */ + readonly client: SqlClient; + readonly manifest: AccessManifest; + /** Revoke and drop roles that are mapped to IAM principals but not declared. Default `false`. */ + readonly prune?: boolean; + /** Print the plan without running it. Default `false`. */ + readonly dryRun?: boolean; + /** Receives one line per statement, warning and problem. Defaults to `console.log`. */ + readonly log?: (line: string) => void; +}; + +export class AccessReconcileError extends Error { + readonly problems: ReadonlyArray; + + constructor(message: string, problems: ReadonlyArray) { + super(`${message}\n${problems.map((problem) => `- ${problem}`).join("\n")}`); + this.name = "AccessReconcileError"; + this.problems = problems; + } +} + +/** + * Makes the cluster's roles, table privileges and IAM mappings match the manifest, then reads + * the state again and fails unless nothing is left to do. Safe to re-run: the plan is a diff. + * Run it after migrations, so roles without a table list also cover newly created tables. + */ +export async function reconcileAccess(props: ReconcileAccessProps): Promise { + const { client, manifest } = props; + const prune = props.prune ?? false; + const log = props.log ?? ((line: string) => console.log(line)); + + const plan = planAccess({ + manifest, + state: await readAccessState({ client, manifest, prune }), + prune, + }); + for (const warning of plan.warnings) { + log(`warning: ${warning}`); + } + if (plan.problems.length > 0) { + throw new AccessReconcileError("The access manifest cannot be applied:", plan.problems); + } + if (plan.statements.length === 0) { + log("Access is up to date."); + return plan; + } + + for (const statement of plan.statements) { + log(`${props.dryRun ? "-- would run: " : "> "}${statement}`); + if (!props.dryRun) { + await client.query(statement); + } + } + if (props.dryRun) { + return plan; + } + + const verification = planAccess({ + manifest, + state: await readAccessState({ client, manifest, prune }), + prune, + }); + const remaining = [ + ...verification.problems, + ...verification.statements.map((statement) => `still pending: ${statement}`), + ]; + if (remaining.length > 0) { + throw new AccessReconcileError( + "Access does not match the manifest after applying it:", + remaining, + ); + } + log("Access matches the manifest."); + return plan; +} diff --git a/packages/helpers-dsql/src/access/ssm.ts b/packages/helpers-dsql/src/access/ssm.ts new file mode 100644 index 00000000..ec1a3f6e --- /dev/null +++ b/packages/helpers-dsql/src/access/ssm.ts @@ -0,0 +1,57 @@ +import { GetParameterCommand, SSMClient } from "@aws-sdk/client-ssm"; +import { fromIni } from "@aws-sdk/credential-providers"; + +import { + type AccessManifest, + parseAccessManifest, + toAccessManifestParameterName, +} from "./manifest"; + +const endpointPattern = /^([a-z0-9]+)\.dsql\.([a-z0-9-]+)\.on\.aws$/; + +/** Splits `.dsql..on.aws` into its parts. */ +export function parseDsqlEndpoint(endpoint: string): { + readonly clusterId: string; + readonly region: string; +} { + const match = endpointPattern.exec(endpoint); + if (match?.[1] == null || match[2] == null) { + throw new Error( + `Not a DSQL cluster endpoint: "${endpoint}" (expected .dsql..on.aws).`, + ); + } + return { clusterId: match[1], region: match[2] }; +} + +/** + * Loads the manifest the `DsqlCluster` construct wrote for the cluster behind `endpoint`. The + * parameter name is derived from the cluster id, and the manifest must name the same cluster, + * so one stage's manifest cannot be applied to another stage's cluster. Needs `ssm:GetParameter`. + */ +export async function readAccessManifest(props: { + readonly endpoint: string; + readonly profile?: string | undefined; + readonly ssm?: SSMClient; +}): Promise { + const { clusterId, region } = parseDsqlEndpoint(props.endpoint); + const ssm = + props.ssm ?? + new SSMClient({ + region, + ...(props.profile ? { credentials: fromIni({ profile: props.profile }) } : {}), + }); + const name = toAccessManifestParameterName(clusterId); + const response = await ssm.send(new GetParameterCommand({ Name: name })); + const value = response.Parameter?.Value; + if (value == null) { + throw new Error(`SSM parameter ${name} has no value.`); + } + + const manifest = parseAccessManifest(JSON.parse(value)); + if (manifest.clusterId !== clusterId) { + throw new Error( + `SSM parameter ${name} describes cluster ${manifest.clusterId}, not ${clusterId}.`, + ); + } + return manifest; +} diff --git a/packages/helpers-dsql/src/access/state.ts b/packages/helpers-dsql/src/access/state.ts new file mode 100644 index 00000000..207843b7 --- /dev/null +++ b/packages/helpers-dsql/src/access/state.ts @@ -0,0 +1,135 @@ +import * as v from "valibot"; + +import { type AccessManifest, type DsqlPrivilege, dsqlPrivileges } from "./manifest"; + +/** + * The part of a `pg` `Pool` or `Client` the admin helpers use. Every call runs on its own + * (autocommit), which DSQL requires for DDL and role statements. + */ +export type SqlClient = { + query(text: string, values?: Array): Promise<{ rows: Array }>; +}; + +export type RoleMapping = { + readonly role: string; + readonly arn: string; +}; + +/** What the cluster currently has, as far as the manifest's roles are concerned. */ +export type AccessState = { + readonly existingRoles: ReadonlySet; + readonly mappings: ReadonlyArray; + readonly schemaExists: boolean; + readonly tables: ReadonlyArray; + /** Per inspected role: whether it has USAGE on the manifest schema. */ + readonly schemaUsage: ReadonlyMap; + /** Per inspected role and table: the privileges it holds. */ + readonly tablePrivileges: ReadonlyMap>>; +}; + +const roleRowSchema = v.object({ rolname: v.string() }); +const mappingRowSchema = v.object({ pg_role_name: v.string(), arn: v.string() }); +const tableRowSchema = v.object({ relname: v.string() }); +const usageRowSchema = v.object({ usage: v.boolean() }); +const privilegeRowSchema = v.object({ + table: v.string(), + select: v.boolean(), + insert: v.boolean(), + update: v.boolean(), + delete: v.boolean(), +}); + +const privilegeColumns = { + SELECT: "select", + INSERT: "insert", + UPDATE: "update", + DELETE: "delete", +} as const satisfies Record; + +/** Roles the cluster maps to IAM principals but the manifest does not declare. */ +export function toUndeclaredMappedRoles( + manifest: AccessManifest, + mappings: ReadonlyArray, +): ReadonlyArray { + const declared = new Set(manifest.roles.map((role) => role.name)); + const undeclared = new Set( + mappings + .map((mapping) => mapping.role) + .filter((role) => role !== "admin" && !declared.has(role)), + ); + return [...undeclared].sort(); +} + +/** + * Reads the current roles, IAM mappings, tables and privileges. Read-only. With `prune`, the + * undeclared mapped roles are inspected too, so their privileges can be revoked. + */ +export async function readAccessState(props: { + readonly client: SqlClient; + readonly manifest: AccessManifest; + readonly prune?: boolean; +}): Promise { + const { client, manifest } = props; + + const roleRows = await client.query("SELECT rolname FROM pg_roles"); + const existingRoles = new Set(roleRows.rows.map((row) => v.parse(roleRowSchema, row).rolname)); + + const mappingRows = await client.query("SELECT pg_role_name, arn FROM sys.iam_pg_role_mappings"); + const mappings = mappingRows.rows.map((row) => { + const parsed = v.parse(mappingRowSchema, row); + return { role: parsed.pg_role_name, arn: parsed.arn }; + }); + + const schemaRows = await client.query("SELECT 1 FROM pg_namespace WHERE nspname = $1", [ + manifest.schema, + ]); + const schemaExists = schemaRows.rows.length > 0; + + const tableRows = schemaExists + ? await client.query( + `SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = $1 AND c.relkind = 'r' ORDER BY c.relname`, + [manifest.schema], + ) + : { rows: [] }; + const tables = tableRows.rows.map((row) => v.parse(tableRowSchema, row).relname); + + const inspectedRoles = [ + ...manifest.roles.map((role) => role.name), + ...(props.prune ? toUndeclaredMappedRoles(manifest, mappings) : []), + ].filter((role) => existingRoles.has(role)); + + const schemaUsage = new Map(); + const tablePrivileges = new Map>>(); + + for (const role of schemaExists ? inspectedRoles : []) { + const usageRows = await client.query("SELECT has_schema_privilege($1, $2, 'USAGE') AS usage", [ + role, + manifest.schema, + ]); + const usageRow = usageRows.rows[0]; + schemaUsage.set(role, usageRow != null && v.parse(usageRowSchema, usageRow).usage); + + const privilegeRows = await client.query( + `SELECT c.relname AS table, + has_table_privilege($1, c.oid, 'SELECT') AS select, + has_table_privilege($1, c.oid, 'INSERT') AS insert, + has_table_privilege($1, c.oid, 'UPDATE') AS update, + has_table_privilege($1, c.oid, 'DELETE') AS delete + FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = $2 AND c.relkind = 'r'`, + [role, manifest.schema], + ); + const byTable = new Map>(); + for (const row of privilegeRows.rows) { + const parsed = v.parse(privilegeRowSchema, row); + byTable.set( + parsed.table, + new Set(dsqlPrivileges.filter((privilege) => parsed[privilegeColumns[privilege]])), + ); + } + tablePrivileges.set(role, byTable); + } + + return { existingRoles, mappings, schemaExists, tables, schemaUsage, tablePrivileges }; +} diff --git a/packages/helpers-dsql/src/cdk/dsqlCluster.ts b/packages/helpers-dsql/src/cdk/dsqlCluster.ts new file mode 100644 index 00000000..f395784e --- /dev/null +++ b/packages/helpers-dsql/src/cdk/dsqlCluster.ts @@ -0,0 +1,247 @@ +import { Lazy, RemovalPolicy, Stack } from "aws-cdk-lib"; +import { CfnCluster } from "aws-cdk-lib/aws-dsql"; +import { Grant, type IRole } from "aws-cdk-lib/aws-iam"; +import { ParameterTier, StringParameter } from "aws-cdk-lib/aws-ssm"; +import { Construct } from "constructs"; + +import { + type AccessManifest, + assertRoleName, + assertSchemaName, + assertTableName, + type DsqlPrivilege, + dsqlPrivileges, + toAccessManifestParameterName, +} from "../access/manifest"; +import { dsqlEnvNames } from "../envNames"; + +/** A database role declared on the cluster. */ +export type DsqlRoleProps = { + readonly privileges: ReadonlyArray; + /** + * Tables the privileges apply to. Omit to cover every table in the schema, including tables + * added by later migrations. + */ + readonly tables?: ReadonlyArray; +}; + +export type DsqlClusterProps = { + /** Custom database roles, granted with {@link DsqlCluster.grant}. */ + readonly roles?: Readonly>; + /** Prefix of the built-in roles (`_read`, `_write`, `_readwrite`). Default `app`. */ + readonly roleNamePrefix?: string; + /** Schema the roles' privileges apply to. Default `public`. */ + readonly schema?: string; + /** Default `true`. */ + readonly deletionProtection?: boolean; + /** Default `RemovalPolicy.RETAIN`. */ + readonly removalPolicy?: RemovalPolicy; + /** Tier of the SSM parameter holding the access manifest. Standard holds 4 KB. Default standard. */ + readonly manifestParameterTier?: ParameterTier; +}; + +/** A Lambda function (gets IAM access and the `DSQL_*` env vars) or an IAM role (IAM access only). */ +export type DsqlGrantee = + | IRole + | { + readonly role?: IRole | undefined; + readonly node: Construct["node"]; + addEnvironment(key: string, value: string): unknown; + }; + +const builtInRoles = { + read: { method: "grantRead", privileges: ["SELECT"] }, + write: { method: "grantWrite", privileges: ["INSERT", "UPDATE", "DELETE"] }, + readwrite: { method: "grantReadWrite", privileges: ["SELECT", "INSERT", "UPDATE", "DELETE"] }, +} as const satisfies Record< + string, + { readonly method: string; readonly privileges: ReadonlyArray } +>; + +type RoleDefinition = { + readonly privileges: ReadonlyArray; + readonly tables?: ReadonlyArray | undefined; +}; + +function isRole(grantee: DsqlGrantee): grantee is IRole { + return !("addEnvironment" in grantee); +} + +/** + * An Aurora DSQL cluster with least-privilege database access declared in code. + * + * IAM only decides who may connect (`dsql:DbConnect`); which tables a connection may touch is + * decided by the database role its IAM principal is mapped to. Each `grant*` call adds the IAM + * permission, sets `DSQL_ENDPOINT`, `DSQL_REGION` and `DSQL_DB_USER` on a Lambda, and records the + * mapping in an access manifest (an SSM parameter). `reconcileAccess` from + * `@beesolve/dsql-helpers/admin` applies the manifest to the database: it creates roles, grants + * and revokes table privileges, and grants and revokes IAM mappings, so access follows the code. + * + * The cluster keeps the logical ID of this construct (`new DsqlCluster(this, "Dsql")` creates + * `Dsql`), so wrapping an existing `CfnCluster` with the same ID does not replace it. + */ +export class DsqlCluster extends Construct { + readonly cluster: CfnCluster; + /** Cluster identifier (`Ref`). */ + readonly clusterId: string; + readonly clusterArn: string; + /** `.dsql..on.aws`, the host the connector expects. */ + readonly endpoint: string; + readonly schema: string; + readonly accessManifestParameter: StringParameter; + + private readonly roleNamePrefix: string; + private readonly roles = new Map(); + private readonly builtInRoleNames = new Set(); + private readonly principalsByRole = new Map>(); + private readonly roleByPrincipal = new Map(); + + constructor(scope: Construct, id: string, props: DsqlClusterProps = {}) { + super(scope, id); + + this.schema = props.schema ?? "public"; + assertSchemaName(this.schema); + this.roleNamePrefix = props.roleNamePrefix ?? "app"; + + for (const [name, role] of Object.entries(props.roles ?? {})) { + this.defineRole(name, role); + } + + // The ID `Default` keeps the construct's own logical ID for the cluster. + this.cluster = new CfnCluster(this, "Default", { + deletionProtectionEnabled: props.deletionProtection ?? true, + }); + this.cluster.applyRemovalPolicy(props.removalPolicy ?? RemovalPolicy.RETAIN); + + const stack = Stack.of(this); + this.clusterId = this.cluster.ref; + this.clusterArn = this.cluster.attrResourceArn; + this.endpoint = `${this.clusterId}.dsql.${stack.region}.on.aws`; + + this.accessManifestParameter = new StringParameter(this, "AccessManifest", { + parameterName: toAccessManifestParameterName(this.clusterId), + simpleName: false, + description: "Database roles and IAM mappings of the DSQL cluster (@beesolve/dsql-helpers).", + tier: props.manifestParameterTier ?? ParameterTier.STANDARD, + stringValue: Lazy.string({ produce: () => stack.toJsonString(this.toAccessManifest()) }), + }); + } + + /** Maps the grantee to the custom role `role` declared in `roles`. */ + grant(grantee: DsqlGrantee, role: TRoles): Grant { + return this.grantRole(grantee, role); + } + + /** `SELECT` on every table. Role `_read`. */ + grantRead(grantee: DsqlGrantee): Grant { + return this.grantRole(grantee, this.useBuiltInRole("read")); + } + + /** + * `INSERT`, `UPDATE`, `DELETE` on every table, without `SELECT`. Role `_write`. + * PostgreSQL also requires `SELECT` for `UPDATE`/`DELETE` with a `WHERE` clause and for + * `RETURNING`, so this suits append-only writers; most code wants {@link grantReadWrite}. + */ + grantWrite(grantee: DsqlGrantee): Grant { + return this.grantRole(grantee, this.useBuiltInRole("write")); + } + + /** `SELECT`, `INSERT`, `UPDATE`, `DELETE` on every table. Role `_readwrite`. */ + grantReadWrite(grantee: DsqlGrantee): Grant { + return this.grantRole(grantee, this.useBuiltInRole("readwrite")); + } + + /** The desired access as recorded so far. Principal ARNs are unresolved tokens until deploy. */ + toAccessManifest(): AccessManifest { + const stack = Stack.of(this); + return { + version: 1, + clusterId: this.clusterId, + account: stack.account, + schema: this.schema, + roles: [...this.roles.entries()].map(([name, role]) => ({ + name, + privileges: role.privileges, + ...(role.tables == null ? {} : { tables: role.tables }), + principals: this.principalsByRole.get(name) ?? [], + })), + }; + } + + private defineRole(name: string, role: DsqlRoleProps): void { + assertRoleName(name); + if (this.roles.has(name)) { + throw new Error(`DSQL role ${name} is declared twice.`); + } + if (role.privileges.length === 0) { + throw new Error(`DSQL role ${name} has no privileges.`); + } + for (const privilege of role.privileges) { + if (!dsqlPrivileges.includes(privilege)) { + throw new Error(`DSQL role ${name} has unsupported privilege "${privilege}".`); + } + } + if (role.tables != null) { + if (role.tables.length === 0) { + throw new Error(`DSQL role ${name} has an empty table list. Omit it to cover every table.`); + } + role.tables.forEach(assertTableName); + } + this.roles.set(name, { + privileges: dsqlPrivileges.filter((privilege) => role.privileges.includes(privilege)), + ...(role.tables == null ? {} : { tables: [...new Set(role.tables)].sort() }), + }); + } + + private useBuiltInRole(kind: keyof typeof builtInRoles): string { + const builtIn = builtInRoles[kind]; + const name = `${this.roleNamePrefix}_${kind}`; + const existing = this.roles.get(name); + if (existing == null) { + this.defineRole(name, { privileges: builtIn.privileges }); + this.builtInRoleNames.add(name); + } else if (!this.builtInRoleNames.has(name)) { + throw new Error( + `Custom DSQL role ${name} collides with the built-in role of ${builtIn.method}(). Rename it or set roleNamePrefix.`, + ); + } + return name; + } + + private grantRole(grantee: DsqlGrantee, roleName: string): Grant { + if (!this.roles.has(roleName)) { + throw new Error(`DSQL role ${roleName} is not declared on ${this.node.path}.`); + } + + const role = isRole(grantee) ? grantee : grantee.role; + if (role == null) { + throw new Error(`Expected ${grantee.node.path} to have an execution role.`); + } + + const mapped = this.roleByPrincipal.get(role); + if (mapped != null && mapped !== roleName) { + throw new Error( + `${role.node.path} is already granted DSQL role ${mapped}; an IAM principal maps to one database role, so it cannot also get ${roleName}. Declare a role that combines both.`, + ); + } + if (mapped == null) { + this.roleByPrincipal.set(role, roleName); + const principals = this.principalsByRole.get(roleName) ?? []; + principals.push(role.roleArn); + this.principalsByRole.set(roleName, principals); + } + + if (!isRole(grantee)) { + const stack = Stack.of(this); + grantee.addEnvironment(dsqlEnvNames.endpoint, this.endpoint); + grantee.addEnvironment(dsqlEnvNames.region, stack.region); + grantee.addEnvironment(dsqlEnvNames.user, roleName); + } + + return Grant.addToPrincipal({ + grantee: role, + actions: ["dsql:DbConnect"], + resourceArns: [this.clusterArn], + }); + } +} diff --git a/packages/helpers-dsql/src/database.ts b/packages/helpers-dsql/src/database.ts new file mode 100644 index 00000000..255ab334 --- /dev/null +++ b/packages/helpers-dsql/src/database.ts @@ -0,0 +1,109 @@ +import { + type AwsDsqlDatabase, + type AwsDsqlRetryConfig, + type AwsDsqlRetryExhaustedError, + drizzle, +} from "@aws/aurora-dsql-drizzle"; +import type { ExtractTablesWithRelations } from "drizzle-orm"; +import type { PgDatabase, PgQueryResultHKT, PgTransaction } from "drizzle-orm/pg-core"; +import type { Pool } from "pg"; + +import type { DsqlConfig } from "./env"; +import { isRetryExhausted } from "./errors"; + +type AnySchema = Record; + +/** + * The common base of the DSQL database and a plain PostgreSQL one (for example PGlite in unit + * tests). Code that depends only on this type runs against either. + */ +export type Db = PgDatabase< + PgQueryResultHKT, + TSchema, + ExtractTablesWithRelations +>; + +/** What a transaction callback receives. Also valid wherever a {@link Db} query is built. */ +export type Tx = PgTransaction< + PgQueryResultHKT, + TSchema, + ExtractTablesWithRelations +>; + +/** Anything statements can run on: the database itself or an open transaction. */ +export type Executor = Db | Tx; + +/** + * Runs `fn` in one transaction. On DSQL, optimistic concurrency conflicts (SQLSTATE 40001) are + * retried, so `fn` may run more than once and must not cause side effects outside the database. + */ +export type Transact = ( + fn: (tx: Tx) => Promise, +) => Promise; + +/** Constructor props for repositories: `new Users({ db, transact })`. */ +export type DbProps = { + readonly db: Db; + readonly transact: Transact; +}; + +export type DsqlDatabase = { + /** The adapter's database; `db.$client` is the `pg` pool (needed by `migrate`). */ + readonly db: AwsDsqlDatabase & { $client: Pool }; + readonly transact: Transact; +}; + +export type CreateDsqlDatabaseProps = { + readonly config: DsqlConfig; + readonly schema?: TSchema; + readonly casing?: "snake_case" | "camelCase"; + readonly retry?: AwsDsqlRetryConfig; + /** + * Maps the error thrown when every retry hit a conflict, for example to a "please try again" + * domain error. The original error is rethrown when omitted. + */ + readonly toRetryExhaustedError?: (error: AwsDsqlRetryExhaustedError) => unknown; + /** Called for errors on idle pooled connections. Defaults to `console.error`. */ + readonly onIdleConnectionError?: (error: Error) => void; +}; + +/** + * Creates the Drizzle database for a DSQL cluster. Call it once per Lambda container (at module + * level): the pool opens connections lazily and the connector creates a fresh IAM token for each + * new connection. DSQL closes connections after one hour; the pool replaces them. + */ +export function createDsqlDatabase>( + props: CreateDsqlDatabaseProps, +): DsqlDatabase { + const { config } = props; + const db = drizzle({ + connection: { + host: config.host, + region: config.region, + user: config.user, + ...(config.profile ? { profile: config.profile } : {}), + }, + ...(props.schema == null ? {} : { schema: props.schema }), + ...(props.casing == null ? {} : { casing: props.casing }), + }); + + // Without a listener Node treats an error emitted by an idle pooled connection (for example + // at the one-hour limit) as an uncaught exception. + const onIdleConnectionError = + props.onIdleConnectionError ?? + ((error: Error) => console.error("Idle DSQL connection error", error.message)); + db.$client.on("error", onIdleConnectionError); + + const transact: Transact = async (fn) => { + try { + return await db.transactionWithRetry(fn, undefined, props.retry); + } catch (error) { + if (props.toRetryExhaustedError != null && isRetryExhausted(error)) { + throw props.toRetryExhaustedError(error); + } + throw error; + } + }; + + return { db, transact }; +} diff --git a/packages/helpers-dsql/src/env.ts b/packages/helpers-dsql/src/env.ts new file mode 100644 index 00000000..280ebddf --- /dev/null +++ b/packages/helpers-dsql/src/env.ts @@ -0,0 +1,41 @@ +import * as v from "valibot"; + +/** Connection settings for one DSQL database role. */ +export type DsqlConfig = { + /** Cluster endpoint, for example `abc123.dsql.eu-central-1.on.aws`. */ + readonly host: string; + readonly region: string; + /** Database role: `admin` or a role mapped to the caller's IAM identity with `AWS IAM GRANT`. */ + readonly user: string; + /** Local development only: credentials come from this shared-config profile. */ + readonly profile?: string | undefined; +}; + +/** + * Valibot entries for the DSQL connection env vars. Spread them into an entry point's own env + * schema so it validates everything in one place. + */ +export const dsqlEnvEntries: { + readonly DSQL_ENDPOINT: v.StringSchema; + readonly DSQL_REGION: v.StringSchema; + readonly DSQL_DB_USER: v.StringSchema; + readonly AWS_PROFILE: v.OptionalSchema, undefined>; +} = { + DSQL_ENDPOINT: v.string(), + DSQL_REGION: v.string(), + DSQL_DB_USER: v.string(), + AWS_PROFILE: v.optional(v.string()), +}; + +const dsqlEnvSchema = v.object(dsqlEnvEntries); + +/** Reads {@link DsqlConfig} from `DSQL_ENDPOINT`, `DSQL_REGION`, `DSQL_DB_USER` and optional `AWS_PROFILE`. */ +export function toDsqlConfig(env: Record = process.env): DsqlConfig { + const parsed = v.parse(dsqlEnvSchema, env); + return { + host: parsed.DSQL_ENDPOINT, + region: parsed.DSQL_REGION, + user: parsed.DSQL_DB_USER, + profile: parsed.AWS_PROFILE || undefined, + }; +} diff --git a/packages/helpers-dsql/src/envNames.ts b/packages/helpers-dsql/src/envNames.ts new file mode 100644 index 00000000..b140a588 --- /dev/null +++ b/packages/helpers-dsql/src/envNames.ts @@ -0,0 +1,9 @@ +/** + * Environment variables the CDK construct sets on every granted Lambda and that + * {@link toDsqlConfig} reads at runtime. + */ +export const dsqlEnvNames = { + endpoint: "DSQL_ENDPOINT", + region: "DSQL_REGION", + user: "DSQL_DB_USER", +} as const; diff --git a/packages/helpers-dsql/src/errors.ts b/packages/helpers-dsql/src/errors.ts new file mode 100644 index 00000000..c5a8bc71 --- /dev/null +++ b/packages/helpers-dsql/src/errors.ts @@ -0,0 +1,58 @@ +import { AwsDsqlRetryExhaustedError } from "@aws/aurora-dsql-drizzle"; + +/** + * SQLSTATE codes worth translating into domain errors. + * @link https://www.postgresql.org/docs/current/errcodes-appendix.html + */ +export const sqlState = { + uniqueViolation: "23505", + foreignKeyViolation: "23503", + checkViolation: "23514", + /** Aurora DSQL optimistic concurrency conflict (OC000 data, OC001 schema). */ + serializationFailure: "40001", +} as const; + +const maxCauseDepth = 5; +const sqlStatePattern = /^[0-9A-Z]{5}$/; + +/** + * Returns the SQLSTATE of a database error. Drizzle wraps driver errors in `DrizzleQueryError` + * and keeps the driver error (which carries `code`) in `cause`, so the cause chain is searched. + */ +export function toSqlState(error: unknown): string | undefined { + let current: unknown = error; + + for (let depth = 0; depth < maxCauseDepth; depth += 1) { + if (typeof current !== "object" || current == null) { + return undefined; + } + + if ( + "code" in current && + typeof current.code === "string" && + sqlStatePattern.test(current.code) + ) { + return current.code; + } + + current = "cause" in current ? current.cause : undefined; + } + + return undefined; +} + +export const isUniqueViolation = (error: unknown): boolean => + toSqlState(error) === sqlState.uniqueViolation; + +export const isForeignKeyViolation = (error: unknown): boolean => + toSqlState(error) === sqlState.foreignKeyViolation; + +export const isCheckViolation = (error: unknown): boolean => + toSqlState(error) === sqlState.checkViolation; + +export const isSerializationFailure = (error: unknown): boolean => + toSqlState(error) === sqlState.serializationFailure; + +/** The adapter gave up retrying an optimistic concurrency conflict (`transactionWithRetry`). */ +export const isRetryExhausted = (error: unknown): error is AwsDsqlRetryExhaustedError => + error instanceof AwsDsqlRetryExhaustedError; diff --git a/packages/helpers-dsql/src/migrations.ts b/packages/helpers-dsql/src/migrations.ts new file mode 100644 index 00000000..411cf3ce --- /dev/null +++ b/packages/helpers-dsql/src/migrations.ts @@ -0,0 +1,159 @@ +import { createHash } from "node:crypto"; + +import { readMigrationFiles } from "drizzle-orm/migrator"; +import * as v from "valibot"; + +import type { SqlClient } from "./access/state"; + +export type RepairResult = + | { readonly kind: "nothing-pending" } + | { + readonly kind: "recorded"; + readonly folderMillis: number; + readonly statementIndex: number; + readonly statement: string; + } + | { + readonly kind: "not-repairable"; + readonly folderMillis: number; + readonly statementIndex: number; + readonly statement: string; + readonly reason: string; + }; + +const appliedRowSchema = v.object({ + migration_folder_millis: v.union([v.string(), v.number()]), + statement_index: v.number(), +}); +const indexRowSchema = v.object({ valid: v.boolean() }); +const constraintRowSchema = v.object({ validated: v.boolean() }); + +const quotedIdentifierPattern = /^[A-Za-z_][A-Za-z0-9_]*$/; + +/** + * Recovers a migration run that stopped while DSQL was still building an index or validating a + * constraint. `@aws/aurora-dsql-drizzle` records an ASYNC statement only after + * `sys.wait_for_job` returns; if the client stops while waiting, the job can still finish and a + * re-run then fails with 42P07 ("already exists"). + * + * Looks at the FIRST pending statement only. It is recorded as applied, exactly as the adapter + * would record it, when it is `CREATE [UNIQUE] INDEX ASYNC ""` and that index is valid, or + * `ALTER TABLE ASYNC ... VALIDATE CONSTRAINT ""` and that constraint is validated. + * Anything else is left alone. + * + * Coupled to the adapter's tracking table (columns and sha256 of the trimmed statement), as of + * `@aws/aurora-dsql-drizzle` 0.2. + */ +export async function repairFirstPendingMigration(props: { + readonly client: SqlClient; + readonly migrationsFolder: string; + readonly migrationsSchema?: string; + readonly migrationsTable?: string; +}): Promise { + const { client } = props; + const migrationsSchema = props.migrationsSchema ?? "drizzle"; + const migrationsTable = props.migrationsTable ?? "__drizzle_migrations"; + for (const identifier of [migrationsSchema, migrationsTable]) { + if (!quotedIdentifierPattern.test(identifier)) { + throw new Error(`Invalid migrations table identifier "${identifier}".`); + } + } + const tracking = `"${migrationsSchema}"."${migrationsTable}"`; + + const appliedRows = await client.query( + `SELECT migration_folder_millis, statement_index FROM ${tracking}`, + ); + const applied = new Set( + appliedRows.rows.map((row) => { + const parsed = v.parse(appliedRowSchema, row); + return `${Number(parsed.migration_folder_millis)}:${parsed.statement_index}`; + }), + ); + + for (const migration of readMigrationFiles({ migrationsFolder: props.migrationsFolder })) { + for (const [statementIndex, raw] of migration.sql.entries()) { + if (applied.has(`${migration.folderMillis}:${statementIndex}`)) { + continue; + } + + const statement = raw.trim(); + const pending = { folderMillis: migration.folderMillis, statementIndex, statement }; + const indexName = /^CREATE\s+(?:UNIQUE\s+)?INDEX\s+ASYNC\s+"([^"]+)"/i.exec(statement)?.[1]; + const constraintName = + /^ALTER\s+TABLE\s+ASYNC\s+"[^"]+"\s+VALIDATE\s+CONSTRAINT\s+"([^"]+)"/i.exec( + statement, + )?.[1]; + + let done: boolean; + if (indexName != null) { + const { rows } = await client.query( + `SELECT i.indisvalid AS valid FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid + JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = 'public' AND c.relname = $1`, + [indexName], + ); + done = rows[0] != null && v.parse(indexRowSchema, rows[0]).valid; + if (!done) { + return { + kind: "not-repairable", + ...pending, + reason: `Index ${indexName} is missing or not valid yet.`, + }; + } + } else if (constraintName != null) { + const { rows } = await client.query( + "SELECT convalidated AS validated FROM pg_constraint WHERE conname = $1", + [constraintName], + ); + done = rows[0] != null && v.parse(constraintRowSchema, rows[0]).validated; + if (!done) { + return { + kind: "not-repairable", + ...pending, + reason: `Constraint ${constraintName} is missing or not validated yet.`, + }; + } + } else { + return { + kind: "not-repairable", + ...pending, + reason: "Not an ASYNC index or validation statement.", + }; + } + + await client.query( + `INSERT INTO ${tracking} (migration_hash, migration_folder_millis, statement_index, statement_hash) + VALUES ($1, $2, $3, $4) ON CONFLICT (migration_folder_millis, statement_index) DO NOTHING`, + [ + migration.hash, + migration.folderMillis, + statementIndex, + createHash("sha256").update(statement).digest("hex"), + ], + ); + return { kind: "recorded", ...pending }; + } + } + return { kind: "nothing-pending" }; +} + +/** + * Diagnostics for a migration that seems stuck: DSQL background jobs (`sys.jobs`) and the + * indexes of `schema` with their validity. Read-only. + */ +export async function readAsyncJobs(props: { + readonly client: SqlClient; + readonly schema?: string; +}): Promise<{ readonly jobs: ReadonlyArray; readonly indexes: ReadonlyArray }> { + const jobs = await props.client.query("SELECT * FROM sys.jobs"); + const indexes = await props.client.query( + `SELECT c.relname AS index, t.relname AS table, i.indisvalid AS valid, i.indisready AS ready + FROM pg_index i + JOIN pg_class c ON c.oid = i.indexrelid + JOIN pg_class t ON t.oid = i.indrelid + JOIN pg_namespace n ON n.oid = t.relnamespace + WHERE n.nspname = $1 + ORDER BY t.relname, c.relname`, + [props.schema ?? "public"], + ); + return { jobs: jobs.rows, indexes: indexes.rows }; +} diff --git a/packages/helpers-dsql/tests/access.test.ts b/packages/helpers-dsql/tests/access.test.ts new file mode 100644 index 00000000..4b6e1444 --- /dev/null +++ b/packages/helpers-dsql/tests/access.test.ts @@ -0,0 +1,410 @@ +import { describe, expect, test } from "bun:test"; + +import { + type AccessManifest, + type AccessState, + type DsqlPrivilege, + parseAccessManifest, + parseDsqlEndpoint, + planAccess, + reconcileAccess, + type SqlClient, +} from "../admin"; + +const site = "arn:aws:iam::123456789012:role/App-SiteRole-ABC"; +const digest = "arn:aws:iam::123456789012:role/App-DigestRole-DEF"; + +function makeManifest(overrides: Partial = {}): AccessManifest { + return { + version: 1, + clusterId: "abc123", + account: "123456789012", + schema: "public", + roles: [ + { + name: "app_readwrite", + privileges: ["SELECT", "INSERT", "UPDATE", "DELETE"], + principals: [site], + }, + { + name: "digest", + privileges: ["SELECT", "UPDATE"], + tables: ["pending"], + principals: [digest], + }, + ], + ...overrides, + }; +} + +function makeState(overrides: Partial = {}): AccessState { + return { + existingRoles: new Set(), + mappings: [], + schemaExists: true, + tables: ["pending", "users"], + schemaUsage: new Map(), + tablePrivileges: new Map(), + ...overrides, + }; +} + +const all: ReadonlyArray = ["SELECT", "INSERT", "UPDATE", "DELETE"]; + +describe("planAccess", () => { + test("creates roles, grants table privileges, then maps IAM principals", () => { + const plan = planAccess({ manifest: makeManifest(), state: makeState() }); + expect(plan.problems).toEqual([]); + expect(plan.statements).toEqual([ + "CREATE ROLE app_readwrite WITH LOGIN", + "CREATE ROLE digest WITH LOGIN", + 'GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "public"."pending" TO app_readwrite', + 'GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "public"."users" TO app_readwrite', + 'GRANT SELECT, UPDATE ON TABLE "public"."pending" TO digest', + `AWS IAM GRANT app_readwrite TO '${site}'`, + `AWS IAM GRANT digest TO '${digest}'`, + ]); + }); + + test("is empty when the cluster matches", () => { + const plan = planAccess({ + manifest: makeManifest(), + state: makeState({ + existingRoles: new Set(["app_readwrite", "digest"]), + mappings: [ + { role: "app_readwrite", arn: site }, + { role: "digest", arn: digest }, + ], + schemaUsage: new Map([ + ["app_readwrite", true], + ["digest", true], + ]), + tablePrivileges: new Map([ + [ + "app_readwrite", + new Map([ + ["pending", new Set(all)], + ["users", new Set(all)], + ]), + ], + [ + "digest", + new Map([ + ["pending", new Set(["SELECT", "UPDATE"])], + ["users", new Set()], + ]), + ], + ]), + }), + }); + expect(plan).toEqual({ statements: [], problems: [], warnings: [] }); + }); + + test("revokes privileges outside the role's scope and stale IAM mappings", () => { + const stale = "arn:aws:iam::123456789012:role/App-OldRole-XYZ"; + const plan = planAccess({ + manifest: makeManifest(), + state: makeState({ + existingRoles: new Set(["app_readwrite", "digest"]), + mappings: [ + { role: "app_readwrite", arn: site }, + { role: "digest", arn: digest }, + { role: "digest", arn: stale }, + ], + schemaUsage: new Map([ + ["app_readwrite", true], + ["digest", true], + ]), + tablePrivileges: new Map([ + [ + "app_readwrite", + new Map([ + ["pending", new Set(all)], + ["users", new Set(all)], + ]), + ], + [ + "digest", + new Map([ + ["pending", new Set(all)], + ["users", new Set(["SELECT"])], + ]), + ], + ]), + }), + }); + expect(plan.statements).toEqual([ + `AWS IAM REVOKE digest FROM '${stale}'`, + 'REVOKE INSERT, DELETE ON TABLE "public"."pending" FROM digest', + 'REVOKE SELECT ON TABLE "public"."users" FROM digest', + ]); + }); + + test("reports a declared table that does not exist", () => { + const plan = planAccess({ + manifest: makeManifest(), + state: makeState({ tables: ["users"] }), + }); + expect(plan.problems).toEqual([ + 'Role digest lists table "pending", which does not exist in schema "public".', + ]); + }); + + test("reports principals outside the cluster account", () => { + const foreign = "arn:aws:iam::999999999999:role/Other"; + const plan = planAccess({ + manifest: makeManifest({ + roles: [{ name: "app_read", privileges: ["SELECT"], principals: [foreign] }], + }), + state: makeState(), + }); + expect(plan.problems).toEqual([ + `Principal ${foreign} of role app_read is not in account 123456789012, the account of the cluster.`, + ]); + }); + + test("reports missing USAGE on public instead of granting it", () => { + const plan = planAccess({ + manifest: makeManifest({ + roles: [{ name: "app_read", privileges: ["SELECT"], principals: [] }], + }), + state: makeState({ + existingRoles: new Set(["app_read"]), + schemaUsage: new Map([["app_read", false]]), + }), + }); + expect(plan.problems[0]).toContain("has no USAGE on schema public"); + }); + + test("grants USAGE on a custom schema", () => { + const plan = planAccess({ + manifest: makeManifest({ + schema: "orders", + roles: [{ name: "app_read", privileges: ["SELECT"], principals: [] }], + }), + state: makeState({ tables: [] }), + }); + expect(plan.statements).toEqual([ + "CREATE ROLE app_read WITH LOGIN", + 'GRANT USAGE ON SCHEMA "orders" TO app_read', + ]); + }); + + test("only warns about undeclared mapped roles without prune", () => { + const plan = planAccess({ + manifest: makeManifest({ roles: [] }), + state: makeState({ mappings: [{ role: "expense_ease_app", arn: site }] }), + }); + expect(plan.statements).toEqual([]); + expect(plan.warnings).toEqual([ + "Role expense_ease_app is mapped to IAM principals but not declared. Run with prune to revoke and drop it.", + ]); + }); + + test("prune revokes mappings and privileges, then drops the role", () => { + const plan = planAccess({ + prune: true, + manifest: makeManifest({ roles: [] }), + state: makeState({ + existingRoles: new Set(["expense_ease_app"]), + mappings: [ + { role: "expense_ease_app", arn: site }, + { role: "admin", arn: site }, + ], + tablePrivileges: new Map([ + [ + "expense_ease_app", + new Map([ + ["users", new Set(all)], + ["pending", new Set()], + ]), + ], + ]), + }), + }); + expect(plan.statements).toEqual([ + `AWS IAM REVOKE expense_ease_app FROM '${site}'`, + 'REVOKE SELECT, INSERT, UPDATE, DELETE ON TABLE "public"."users" FROM expense_ease_app', + "DROP ROLE expense_ease_app", + ]); + }); +}); + +describe("parseAccessManifest", () => { + test("rejects identifiers and ARNs that could inject SQL", () => { + const base = makeManifest(); + expect(() => + parseAccessManifest({ ...base, roles: [{ ...base.roles[0], name: "x; DROP TABLE users" }] }), + ).toThrow(); + expect(() => + parseAccessManifest({ ...base, roles: [{ ...base.roles[0], tables: ['users"; --'] }] }), + ).toThrow(); + expect(() => + parseAccessManifest({ + ...base, + roles: [{ ...base.roles[0], principals: ["arn'; DROP ROLE x; --"] }], + }), + ).toThrow(); + expect(() => + parseAccessManifest({ ...base, roles: [{ ...base.roles[0], privileges: ["ALL"] }] }), + ).toThrow(); + expect(() => parseAccessManifest({ ...base, roles: [base.roles[0], base.roles[0]] })).toThrow(); + }); + + test("accepts a valid manifest", () => { + expect(parseAccessManifest(JSON.parse(JSON.stringify(makeManifest())))).toEqual(makeManifest()); + }); +}); + +describe("parseDsqlEndpoint", () => { + test("splits the endpoint", () => { + expect(parseDsqlEndpoint("abc123.dsql.eu-central-1.on.aws")).toEqual({ + clusterId: "abc123", + region: "eu-central-1", + }); + expect(() => parseDsqlEndpoint("example.com")).toThrow(/Not a DSQL cluster endpoint/); + }); +}); + +/** Answers the state queries from an in-memory cluster and applies the plan's statements to it. */ +function makeFakeCluster() { + const roles = new Set(["admin"]); + const mappings: Array<{ role: string; arn: string }> = []; + const privileges = new Map>(); + const tables = ["pending", "users"]; + const executed: Array = []; + const key = (role: string, table: string) => `${role}/${table}`; + + const client: SqlClient = { + async query(text, values = []) { + if (text.startsWith("SELECT rolname FROM pg_roles")) { + return { rows: [...roles].map((rolname) => ({ rolname })) }; + } + if (text.startsWith("SELECT pg_role_name, arn")) { + return { + rows: mappings.map((mapping) => ({ pg_role_name: mapping.role, arn: mapping.arn })), + }; + } + if (text.startsWith("SELECT 1 FROM pg_namespace")) { + return { rows: [{ "?column?": 1 }] }; + } + if (text.startsWith("SELECT c.relname FROM pg_class")) { + return { rows: tables.map((relname) => ({ relname })) }; + } + if (text.startsWith("SELECT has_schema_privilege")) { + return { rows: [{ usage: true }] }; + } + if (text.startsWith("SELECT c.relname AS table")) { + const role = String(values[0]); + return { + rows: tables.map((table) => { + const held = privileges.get(key(role, table)) ?? new Set(); + return { + table, + select: held.has("SELECT"), + insert: held.has("INSERT"), + update: held.has("UPDATE"), + delete: held.has("DELETE"), + }; + }), + }; + } + + executed.push(text); + const groups = (pattern: RegExp) => pattern.exec(text)?.slice(1).map(String); + const privilegeList = (list: string) => list.split(", "); + let parts: Array | undefined; + if ((parts = groups(/^CREATE ROLE (\w+) WITH LOGIN$/))) { + roles.add(String(parts[0])); + } else if ((parts = groups(/^GRANT ([A-Z, ]+) ON TABLE "public"\."(\w+)" TO (\w+)$/))) { + const [list = "", table = "", role = ""] = parts; + const held = privileges.get(key(role, table)) ?? new Set(); + privilegeList(list).forEach((privilege) => held.add(privilege)); + privileges.set(key(role, table), held); + } else if ((parts = groups(/^REVOKE ([A-Z, ]+) ON TABLE "public"\."(\w+)" FROM (\w+)$/))) { + const [list = "", table = "", role = ""] = parts; + const held = privileges.get(key(role, table)) ?? new Set(); + privilegeList(list).forEach((privilege) => held.delete(privilege)); + } else if ((parts = groups(/^AWS IAM GRANT (\w+) TO '(.+)'$/))) { + const [role = "", arn = ""] = parts; + mappings.push({ role, arn }); + } else if ((parts = groups(/^AWS IAM REVOKE (\w+) FROM '(.+)'$/))) { + const [role, arn] = parts; + mappings.splice( + mappings.findIndex((mapping) => mapping.role === role && mapping.arn === arn), + 1, + ); + } else if ((parts = groups(/^DROP ROLE (\w+)$/))) { + roles.delete(String(parts[0])); + } else { + throw new Error(`Unexpected statement: ${text}`); + } + return { rows: [] }; + }, + }; + return { client, executed, mappings, roles }; +} + +describe("reconcileAccess", () => { + test("applies the plan, verifies it, and is a no-op on the second run", async () => { + const cluster = makeFakeCluster(); + const log: Array = []; + await reconcileAccess({ + client: cluster.client, + manifest: makeManifest(), + log: (line) => log.push(line), + }); + expect(cluster.executed).toHaveLength(7); + expect(log.at(-1)).toBe("Access matches the manifest."); + + cluster.executed.length = 0; + const plan = await reconcileAccess({ + client: cluster.client, + manifest: makeManifest(), + log: () => {}, + }); + expect(plan.statements).toEqual([]); + expect(cluster.executed).toEqual([]); + }); + + test("dry run executes nothing", async () => { + const cluster = makeFakeCluster(); + const plan = await reconcileAccess({ + client: cluster.client, + manifest: makeManifest(), + dryRun: true, + log: () => {}, + }); + expect(plan.statements).toHaveLength(7); + expect(cluster.executed).toEqual([]); + }); + + test("moves a principal to another role and prunes the old one", async () => { + const cluster = makeFakeCluster(); + cluster.roles.add("expense_ease_app"); + cluster.mappings.push({ role: "expense_ease_app", arn: site }); + + await reconcileAccess({ + client: cluster.client, + manifest: makeManifest(), + prune: true, + log: () => {}, + }); + expect(cluster.executed.at(-1)).toBe("DROP ROLE expense_ease_app"); + expect(cluster.mappings).toEqual([ + { role: "app_readwrite", arn: site }, + { role: "digest", arn: digest }, + ]); + }); + + test("refuses to apply a manifest with problems", async () => { + const cluster = makeFakeCluster(); + const manifest = makeManifest({ + roles: [{ name: "app_read", privileges: ["SELECT"], tables: ["missing"], principals: [] }], + }); + expect(reconcileAccess({ client: cluster.client, manifest, log: () => {} })).rejects.toThrow( + /lists table "missing"/, + ); + expect(cluster.executed).toEqual([]); + }); +}); diff --git a/packages/helpers-dsql/tests/dsqlCluster.test.ts b/packages/helpers-dsql/tests/dsqlCluster.test.ts new file mode 100644 index 00000000..2ea6bacf --- /dev/null +++ b/packages/helpers-dsql/tests/dsqlCluster.test.ts @@ -0,0 +1,216 @@ +import { describe, expect, test } from "bun:test"; + +import { App, RemovalPolicy, Stack } from "aws-cdk-lib"; +import { Template } from "aws-cdk-lib/assertions"; +import { Role, ServicePrincipal } from "aws-cdk-lib/aws-iam"; +import { Code, Function, Runtime } from "aws-cdk-lib/aws-lambda"; + +import { DsqlCluster, type DsqlRoleProps } from "../cdk"; + +function makeStack() { + return new Stack(new App(), "TestStack", { + env: { account: "123456789012", region: "eu-central-1" }, + }); +} + +function makeLambda(stack: Stack, id: string) { + return new Function(stack, id, { + runtime: Runtime.NODEJS_24_X, + code: Code.fromInline("exports.handler = async () => {}"), + handler: "index.handler", + }); +} + +function resolvedManifest(stack: Stack, dsql: DsqlCluster) { + return stack.resolve(dsql.toAccessManifest()); +} + +describe("DsqlCluster", () => { + test("keeps the construct id as the cluster logical id", () => { + const stack = makeStack(); + new DsqlCluster(stack, "Dsql"); + const clusters = Template.fromStack(stack).findResources("AWS::DSQL::Cluster"); + expect(Object.keys(clusters)).toEqual(["Dsql"]); + }); + + test("defaults to deletion protection and RETAIN", () => { + const stack = makeStack(); + new DsqlCluster(stack, "Dsql"); + Template.fromStack(stack).hasResource("AWS::DSQL::Cluster", { + Properties: { DeletionProtectionEnabled: true }, + DeletionPolicy: "Retain", + UpdateReplacePolicy: "Retain", + }); + }); + + test("passes deletion protection and removal policy through", () => { + const stack = makeStack(); + new DsqlCluster(stack, "Dsql", { + deletionProtection: false, + removalPolicy: RemovalPolicy.DESTROY, + }); + Template.fromStack(stack).hasResource("AWS::DSQL::Cluster", { + Properties: { DeletionProtectionEnabled: false }, + DeletionPolicy: "Delete", + }); + }); + + test("grantReadWrite adds DbConnect on the cluster and the DSQL env vars", () => { + const stack = makeStack(); + const dsql = new DsqlCluster(stack, "Dsql"); + const fn = makeLambda(stack, "Fn"); + dsql.grantReadWrite(fn); + + const template = Template.fromStack(stack); + template.hasResourceProperties("AWS::IAM::Policy", { + PolicyDocument: { + Statement: [ + { + Action: "dsql:DbConnect", + Effect: "Allow", + Resource: { "Fn::GetAtt": ["Dsql", "ResourceArn"] }, + }, + ], + }, + }); + const functions = Object.values(template.findResources("AWS::Lambda::Function")); + const variables = functions[0]?.Properties.Environment.Variables; + expect(variables.DSQL_DB_USER).toBe("app_readwrite"); + expect(variables.DSQL_REGION).toBe("eu-central-1"); + expect(variables.DSQL_ENDPOINT).toEqual({ + "Fn::Join": ["", [{ Ref: "Dsql" }, ".dsql.eu-central-1.on.aws"]], + }); + }); + + test("never grants DbConnectAdmin", () => { + const stack = makeStack(); + const dsql = new DsqlCluster(stack, "Dsql", { + roles: { reporting: { privileges: ["SELECT"] } }, + }); + dsql.grantRead(makeLambda(stack, "A")); + dsql.grantWrite(makeLambda(stack, "B")); + dsql.grant(makeLambda(stack, "C"), "reporting"); + expect(JSON.stringify(Template.fromStack(stack).toJSON())).not.toContain("DbConnectAdmin"); + }); + + test("records roles, table scopes and principals in the manifest", () => { + const stack = makeStack(); + const dsql = new DsqlCluster(stack, "Dsql", { + roles: { + digest: { privileges: ["UPDATE", "SELECT", "SELECT"], tables: ["users", "pending"] }, + unused: { privileges: ["SELECT"] }, + }, + }); + const site = makeLambda(stack, "Site"); + const digest = makeLambda(stack, "Digest"); + dsql.grantReadWrite(site); + dsql.grant(digest, "digest"); + + const manifest = resolvedManifest(stack, dsql); + expect(manifest.version).toBe(1); + expect(manifest.account).toBe("123456789012"); + expect(manifest.schema).toBe("public"); + expect(manifest.clusterId).toEqual({ Ref: "Dsql" }); + expect(manifest.roles).toEqual([ + { + name: "digest", + privileges: ["SELECT", "UPDATE"], + tables: ["pending", "users"], + principals: [stack.resolve(digest.role?.roleArn)], + }, + { name: "unused", privileges: ["SELECT"], principals: [] }, + { + name: "app_readwrite", + privileges: ["SELECT", "INSERT", "UPDATE", "DELETE"], + principals: [stack.resolve(site.role?.roleArn)], + }, + ]); + }); + + test("writes the manifest to an SSM parameter named after the cluster id", () => { + const stack = makeStack(); + const dsql = new DsqlCluster(stack, "Dsql"); + dsql.grantRead(makeLambda(stack, "Fn")); + Template.fromStack(stack).hasResourceProperties("AWS::SSM::Parameter", { + Name: { "Fn::Join": ["", ["/beesolve/dsql/", { Ref: "Dsql" }, "/access-manifest"]] }, + Type: "String", + Tier: "Standard", + }); + }); + + test("granting the same role twice is idempotent", () => { + const stack = makeStack(); + const dsql = new DsqlCluster(stack, "Dsql"); + const fn = makeLambda(stack, "Fn"); + dsql.grantRead(fn); + dsql.grantRead(fn); + expect(resolvedManifest(stack, dsql).roles[0].principals).toHaveLength(1); + }); + + test("rejects a second database role for the same IAM principal", () => { + const stack = makeStack(); + const dsql = new DsqlCluster(stack, "Dsql"); + const fn = makeLambda(stack, "Fn"); + dsql.grantRead(fn); + expect(() => dsql.grantReadWrite(fn)).toThrow(/already granted DSQL role app_read/); + }); + + test("accepts an IAM role and does not need env vars", () => { + const stack = makeStack(); + const dsql = new DsqlCluster(stack, "Dsql"); + const role = new Role(stack, "TaskRole", { + assumedBy: new ServicePrincipal("ecs-tasks.amazonaws.com"), + }); + dsql.grantRead(role); + expect(resolvedManifest(stack, dsql).roles[0].principals).toHaveLength(1); + }); + + test("uses the role name prefix for built-in roles", () => { + const stack = makeStack(); + const dsql = new DsqlCluster(stack, "Dsql", { roleNamePrefix: "expense_ease" }); + dsql.grantRead(makeLambda(stack, "Fn")); + expect(resolvedManifest(stack, dsql).roles[0].name).toBe("expense_ease_read"); + }); + + test("rejects a custom role that collides with a built-in role", () => { + const stack = makeStack(); + const dsql = new DsqlCluster(stack, "Dsql", { + roles: { app_read: { privileges: ["SELECT"], tables: ["users"] } }, + }); + expect(() => dsql.grantRead(makeLambda(stack, "Fn"))).toThrow( + /collides with the built-in role/, + ); + }); + + test("validates role names, table names and privileges", () => { + const stack = makeStack(); + expect( + () => new DsqlCluster(stack, "A", { roles: { admin: { privileges: ["SELECT"] } } }), + ).toThrow(/Invalid DSQL role name/); + expect( + () => new DsqlCluster(stack, "B", { roles: { "x; drop": { privileges: ["SELECT"] } } }), + ).toThrow(/Invalid DSQL role name/); + expect( + () => + new DsqlCluster(stack, "C", { + roles: { r: { privileges: ["SELECT"], tables: ['users"; --'] } }, + }), + ).toThrow(/Invalid table name/); + const truncate: DsqlRoleProps = JSON.parse('{ "privileges": ["TRUNCATE"] }'); + expect(() => new DsqlCluster(stack, "D", { roles: { r: truncate } })).toThrow( + /unsupported privilege/, + ); + expect( + () => new DsqlCluster(stack, "E", { roles: { r: { privileges: ["SELECT"], tables: [] } } }), + ).toThrow(/empty table list/); + }); + + test("grant only accepts declared role names", () => { + const stack = makeStack(); + const dsql = new DsqlCluster(stack, "Dsql", { + roles: { reporting: { privileges: ["SELECT"] } }, + }); + // @ts-expect-error "typo" is not a declared role + expect(() => dsql.grant(makeLambda(stack, "Fn"), "typo")).toThrow(/not declared/); + }); +}); diff --git a/packages/helpers-dsql/tsconfig.json b/packages/helpers-dsql/tsconfig.json new file mode 100644 index 00000000..933c5096 --- /dev/null +++ b/packages/helpers-dsql/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { "declaration": true, "isolatedDeclarations": true }, + "include": ["src/**/*", "index.ts", "cdk.ts", "admin.ts", "tests/**/*"] +} From 53c0a050835101e41d697e4ac22e17e4abba6398 Mon Sep 17 00:00:00 2001 From: Kiro Agent <244629292+kiro-agent@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:55:07 +0000 Subject: [PATCH 3/3] refactor(dsql-helpers): infer manifest types from valibot schemas AccessRole and AccessManifest are now v.InferOutput of the schemas, so the validated shape and the type cannot drift. isolatedDeclarations is off and dts uses inferTypes + tsgo, as in the other packages that export inferred valibot types. link the anvil blog post in the adrs --- bunup.config.ts | 4 ++ .../helpers-dsql/docs/adr-001-motivation.md | 4 +- .../adr-002-manifest-and-admin-reconcile.md | 2 +- packages/helpers-dsql/src/access/manifest.ts | 37 ++++++++----------- packages/helpers-dsql/tsconfig.json | 2 +- 5 files changed, 23 insertions(+), 26 deletions(-) diff --git a/bunup.config.ts b/bunup.config.ts index cdd8002b..2252f5a9 100644 --- a/bunup.config.ts +++ b/bunup.config.ts @@ -211,6 +211,10 @@ const workspace: Array = [ root: "packages/helpers-dsql", config: { entry: ["index.ts", "cdk.ts", "admin.ts"], + dts: { + inferTypes: true, + tsgo: true, + }, }, }, { diff --git a/packages/helpers-dsql/docs/adr-001-motivation.md b/packages/helpers-dsql/docs/adr-001-motivation.md index 376af7ae..7c417c31 100644 --- a/packages/helpers-dsql/docs/adr-001-motivation.md +++ b/packages/helpers-dsql/docs/adr-001-motivation.md @@ -26,7 +26,7 @@ The env var names the construct sets are the ones `toDsqlConfig` reads, and the ### 2. Least privilege per function, declared next to the function -Anvil's DSQL component 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)`). +[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 @@ -52,4 +52,4 @@ Rejected for the same reason as in `@beesolve/sqs-handler`: entry points (`/cdk` - 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://dev.to/damien_pace_2c3ec240cbd46/how-i-made-dsql-easier-4je5 +- https://anvilcloud.dev/docs/blog/automating-dsql diff --git a/packages/helpers-dsql/docs/adr-002-manifest-and-admin-reconcile.md b/packages/helpers-dsql/docs/adr-002-manifest-and-admin-reconcile.md index af4ac8cb..b482e806 100644 --- a/packages/helpers-dsql/docs/adr-002-manifest-and-admin-reconcile.md +++ b/packages/helpers-dsql/docs/adr-002-manifest-and-admin-reconcile.md @@ -41,7 +41,7 @@ A CloudFormation output is limited to 1,024 characters; a few Lambda role ARNs a A Lambda with `dsql:DbConnectAdmin` runs the reconciler on every deploy, with the manifest as resource properties (no SSM). Access would change in the same deploy, and Lambdas could depend on it so they never run with a role that does not exist yet. Rejected for now: it puts an admin-capable function in every stack, and on the first deploy it runs before migrations create the tables, so table-scoped roles and full coverage of new tables still need the post-migration run. Can be added later on top of the same `reconcileAccess`. -### DynamoDB table and stream-triggered Lambda (Anvil's design) +### DynamoDB table and stream-triggered Lambda ([Anvil's design](https://anvilcloud.dev/docs/blog/automating-dsql)) Deploys write items, a stream-triggered Lambda is the only admin connection. Equivalent to the custom resource in CDK, where CloudFormation is already the trusted writer, with more moving parts. diff --git a/packages/helpers-dsql/src/access/manifest.ts b/packages/helpers-dsql/src/access/manifest.ts index 5f50def0..e5f79c49 100644 --- a/packages/helpers-dsql/src/access/manifest.ts +++ b/packages/helpers-dsql/src/access/manifest.ts @@ -67,12 +67,17 @@ const principalArnSchema = v.pipe( v.regex(principalArnPattern, "Invalid principal ARN."), ); -const accessRoleSchema = v.object({ - name: roleNameSchema, - privileges: v.pipe(v.array(v.picklist(dsqlPrivileges)), v.minLength(1)), - tables: v.optional(v.pipe(v.array(tableNameSchema), v.minLength(1))), - principals: v.array(principalArnSchema), -}); +const accessRoleSchema = v.pipe( + v.object({ + name: roleNameSchema, + privileges: v.pipe(v.array(v.picklist(dsqlPrivileges)), v.minLength(1), v.readonly()), + /** Tables the privileges apply to. Absent means every table in the schema, including later ones. */ + tables: v.optional(v.pipe(v.array(tableNameSchema), v.minLength(1), v.readonly())), + /** IAM role or user ARNs mapped to this role with `AWS IAM GRANT`. */ + principals: v.pipe(v.array(principalArnSchema), v.readonly()), + }), + v.readonly(), +); const accessManifestSchema = v.pipe( v.object({ @@ -80,32 +85,20 @@ const accessManifestSchema = v.pipe( clusterId: v.pipe(v.string(), v.regex(/^[a-z0-9]+$/, "Invalid cluster id.")), account: v.pipe(v.string(), v.regex(/^\d{12}$/, "Invalid account id.")), schema: schemaNameSchema, - roles: v.array(accessRoleSchema), + roles: v.pipe(v.array(accessRoleSchema), v.readonly()), }), v.check( (manifest) => new Set(manifest.roles.map((role) => role.name)).size === manifest.roles.length, "Role names must be unique.", ), + v.readonly(), ); /** One database role: what it may do, where, and which IAM principals log in as it. */ -export type AccessRole = { - readonly name: string; - readonly privileges: ReadonlyArray; - /** Tables the privileges apply to. Absent means every table in the schema, including later ones. */ - readonly tables?: ReadonlyArray | undefined; - /** IAM role or user ARNs mapped to this role with `AWS IAM GRANT`. */ - readonly principals: ReadonlyArray; -}; +export type AccessRole = v.InferOutput; /** Desired database access, written by the CDK construct and applied by {@link reconcileAccess}. */ -export type AccessManifest = { - readonly version: 1; - readonly clusterId: string; - readonly account: string; - readonly schema: string; - readonly roles: ReadonlyArray; -}; +export type AccessManifest = v.InferOutput; /** Validates untrusted input (for example the SSM parameter value) as an {@link AccessManifest}. */ export function parseAccessManifest(value: unknown): AccessManifest { diff --git a/packages/helpers-dsql/tsconfig.json b/packages/helpers-dsql/tsconfig.json index 933c5096..838c0b1c 100644 --- a/packages/helpers-dsql/tsconfig.json +++ b/packages/helpers-dsql/tsconfig.json @@ -1,5 +1,5 @@ { "extends": "../../tsconfig.base.json", - "compilerOptions": { "declaration": true, "isolatedDeclarations": true }, + "compilerOptions": { "declaration": true, "isolatedDeclarations": false }, "include": ["src/**/*", "index.ts", "cdk.ts", "admin.ts", "tests/**/*"] }