cdk-rds-sql 9.1.4 → 9.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.jsii +3 -3
- package/README.md +6 -0
- package/lib/database.js +1 -1
- package/lib/handler/index.js +92 -32
- package/lib/iam-grant.js +1 -1
- package/lib/provider.js +1 -1
- package/lib/role.js +1 -1
- package/lib/schema.js +1 -1
- package/lib/sql.js +1 -1
- package/package.json +1 -1
package/.jsii
CHANGED
|
@@ -9748,7 +9748,7 @@
|
|
|
9748
9748
|
},
|
|
9749
9749
|
"name": "cdk-rds-sql",
|
|
9750
9750
|
"readme": {
|
|
9751
|
-
"markdown": "# About\n\nThis CDK construct library makes it possible to create databases,\nschemas, and roles in an Aurora Serverless v2, RDS Database Cluster,\nDatabase Instance, or AWS DSQL clusters. PostgreSQL, MySQL, and DSQL\ndatabases are supported.\n\nThis construct library is intended to be used in enterprise\nenvironments, and works in isolated subnets.\n\n<p align=\"left\">\n <a href=\"https://github.com/semantic-release/semantic-release\"><img src=\"https://img.shields.io/badge/semantic--release-angular-e10079?logo=semantic-release\" alt=semantic-release: angular\"></a>\n <a href=\"https://github.com/berenddeboer/cdk-rds-sql/actions/workflows/release.yml\"><img src=\"https://github.com/berenddeboer/cdk-rds-sql/actions/workflows/release.yml/badge.svg\" alt=\"Release badge\"></a>\n</p>\n\n# Requirements\n\n- CDK v2.\n- Node.js 22.14 or newer for consumers, as declared in `package.json`'s `engines`.\n This is the library's supported minimum, independent of its development tools.\n\n# Installation\n\n npm i cdk-rds-sql\n\nFor .NET (available from the first NuGet release):\n\n```sh\ndotnet add package BerenddeBoer.CdkRdsSql\n```\n\nThe .NET namespace is `BerenddeBoer.CdkRdsSql`. Node.js is also required\nwhen using the .NET bindings.\n\n# Usage\n\n## Provider\n\nFirst setup your VPC and create your cluster:\n\n```ts\nimport { Duration, RemovalPolicy } from \"aws-cdk-lib\"\nimport * as ec2 from \"aws-cdk-lib/aws-ec2\"\nimport * as rds from \"aws-cdk-lib/aws-rds\"\n\nconst vpc = ec2.Vpc.fromLookup(this, \"Vpc\", {\n vpcId: this.node.tryGetContext(\"vpc-id\"),\n})\n\nconst cluster = new rds.ServerlessCluster(this, \"Cluster\", {\n vpc: vpc,\n vpcSubnets: {\n subnetType: ec2.SubnetType.PRIVATE_ISOLATED,\n },\n engine: rds.DatabaseClusterEngine.AURORA_POSTGRESQL,\n parameterGroup: rds.ParameterGroup.fromParameterGroupName(\n this,\n \"ParameterGroup\",\n \"default.aurora-postgresql11\"\n ),\n removalPolicy: RemovalPolicy.DESTROY,\n scaling: {\n autoPause: Duration.minutes(60),\n minCapacity: rds.AuroraCapacityUnit.ACU_2,\n maxCapacity: rds.AuroraCapacityUnit.ACU_2,\n },\n})\n```\n\nThen create a provider which will connect to your database. For a cluster:\n\n```ts\nimport { Provider } from \"cdk-rds-sql\"\n\nconst provider = new Provider(this, \"Provider\", {\n vpc: vpc,\n cluster: cluster,\n secret: cluster.secret!,\n})\n```\n\nFor an instance:\n\n```ts\nimport { Provider } from \"cdk-rds-sql\"\n\nconst provider = new Provider(this, \"Provider\", {\n vpc: vpc,\n instance: instance,\n secret: cluster.secret!,\n})\n```\n\nThe provider will setup a lambda, which normally lives in the same VPC\nas the database. You can give a different VPC, as long as that VPC has\naccess to the VPC of the database. Only the provider lambda will talk\nto your database.\n\nThe provider will by default use the private isolated subnet of the\nVPC. Your isolated network must have a VPC endpoint to AWS Secrets Manager\nand possibly KMS as well. If you want to use a subnet with egress\naccess in case you have no such VPC endpoints, specify the subnet as\nfollows:\n\n```ts\nimport { Provider } from \"cdk-rds-sql\"\n\nconst provider = new Provider(this, \"Provider\", {\n vpc: vpc,\n vpcSubnets: {\n subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS,\n },\n cluster: cluster,\n secret: cluster.secret!,\n})\n```\n\n## Roles\n\nCreate a postgres role (or mysql user) for a cluster as follows:\n\n```ts\nimport { Role } from \"cdk-rds-sql\"\n\nconst role = new Role(this, \"Role\", {\n provider: provider,\n roleName: \"myrole\",\n databaseName: \"mydb\",\n})\n```\n\nThis will automatically create a secret just like `ServerlessCluster`\ndoes, with all the connection info needed for this user. It's secret\nvalue is a JSON like:\n\n```json\n{\n \"dbClusterIdentifier\": \"teststack-clustereb1186t9-sh4wpqfdyfvu\",\n \"password\": \"very-long-and-boring\",\n \"dbname\": \"mydb\",\n \"engine\": \"postgres\",\n \"port\": 5432,\n \"host\": \"teststack-clustereb1186t9-sh4wpqfdyfvu.cluster-cgudolabssna.us-east-1.rds.amazonaws.com\",\n \"username\": \"myrole\"\n}\n```\n\nYou can access the secret via `role.secret`.\n\nInstead of `databaseName` you can also specify `database` to reference\nan existing database. The role will not be created until the database\nhas been created.\n\nIf you want to make the role the owner of a new database, just specify\nthe `databaseName` here, and create the database later.\n\n### Connection limit (MySQL/MariaDB)\n\nCap how many connections a MySQL or MariaDB user may open:\n\n```ts\nconst role = new Role(this, \"Role\", {\n provider: provider,\n roleName: \"myrole\",\n databaseName: \"mydb\",\n maxUserConnections: 5,\n})\n```\n\nCreate and update then run:\n\n```sql\nALTER USER 'myrole'@'%' WITH MAX_USER_CONNECTIONS 5\n```\n\nOmit `maxUserConnections` to leave the user unlimited, which is the\nexisting behaviour. Omitting it does not clear a limit that was already\napplied; set `0` to restore the server default (unlimited unless the\nglobal `max_user_connections` is set). PostgreSQL and DSQL throw if\nthis property is set.\n\n### IAM Authentication\n\nInstead of password-based authentication, you can create roles that\nuse AWS IAM database authentication. This eliminates the need to store\ndatabase passwords and provides enhanced security through AWS IAM\npolicies.\n\n```ts\nimport { Role } from \"cdk-rds-sql\"\n\nconst iamRole = new Role(this, \"IamRole\", {\n provider: provider,\n roleName: \"myiamrole\",\n databaseName: \"mydb\",\n enableIamAuth: true,\n})\n```\n\nWhen `enableIamAuth` is set to `true`:\n\n- **No secret is created** - the `role.secret` property will be `undefined`\n- The database role is created without a password\n- Your application must generate an IAM authentication token at runtime\n\nThis is the same behavior as DSQL clusters, which always use IAM authentication.\n\n**Requirements for IAM Authentication:**\n\n- SSL connections are required (enabled by default in this library)\n- Your application must have IAM permissions to connect to the database\n- The database user/role name must match the IAM identity\n\n**IAM Policy Example:**\n\nYour application will need an IAM policy like this to connect:\n\n```json\n{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Action\": [\"rds-db:connect\"],\n \"Resource\": [\n \"arn:aws:rds-db:region:account-id:dbuser:cluster-resource-id/myiamrole\"\n ]\n }\n ]\n}\n```\n\n**Generating an IAM Authentication Token:**\n\nAt runtime, your application needs to generate an authentication token\nusing the AWS SDK. Here's an example using the AWS SDK for JavaScript:\n\n```ts\nimport { Signer } from \"@aws-sdk/rds-signer\"\nimport { Client } from \"pg\"\n\nconst signer = new Signer({\n hostname: \"your-cluster.cluster-xxxxx.us-east-1.rds.amazonaws.com\",\n port: 5432,\n username: \"myiamrole\",\n region: \"us-east-1\",\n})\n\nconst token = await signer.getAuthToken()\n\nconst client = new Client({\n host: \"your-cluster.cluster-xxxxx.us-east-1.rds.amazonaws.com\",\n port: 5432,\n user: \"myiamrole\",\n database: \"mydb\",\n password: token,\n ssl: { rejectUnauthorized: true },\n})\n\nawait client.connect()\n```\n\nBoth PostgreSQL and MySQL databases support IAM authentication. For more details, see the [AWS RDS IAM Database Authentication documentation](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html).\n\n### MySQL support\n\nIn MySQL users are created with '%' as value for the host. It is hard\nto do this better:\n\n- Determine the CIDR blocks used by a VPC is not trivial.\n- For imported VPCs you cannot specify the IPv6 CIDR.\n- CIDRs might change without the system knowing, meaning applications\n could lose access to the database at random times, such as when a\n container is restarted.\n\n## Database\n\nCreate a database as follows:\n\n```ts\nimport { Database } from \"cdk-rds-sql\"\n\nconst database = new Database(this, \"Database\", {\n provider: provider,\n databaseName: \"mydb\",\n})\n```\n\nYou can provide an owner, which makes it easy to create database owned\nby a new user:\n\n```ts\nconst database = new Database(this, \"Database\", {\n provider: provider,\n databaseName: \"mydb\",\n owner: role,\n})\n```\n\n## Schema\n\nCreate a schema in the default database as follows:\n\n```ts\nimport { Schema } from \"cdk-rds-sql\"\n\nnew Schema(this, \"Schema\", {\n provider: provider,\n schemaName: \"myschema\",\n})\n```\n\nOr in another database:\n\n```ts\nconst database = new Database(this, \"Database\", {\n provider: provider,\n databaseName: \"mydb\",\n})\n\nnew Schema(this, \"Schema\", {\n provider: provider,\n schemaName: \"myschema\",\n databaseName: database.databaseName,\n})\n```\n\nOne may need a role permitted for using schema:\n\n```ts\nnew Schema(this, \"Schema\", {\n provider: provider,\n schemaName: \"myschema\",\n databaseName: database.databaseName,\n role: role,\n})\n```\n\n## Sql\n\nYou can insert arbitrary SQL into your database with the `Sql` construct:\n\n```ts\nimport { Sql } from \"cdk-rds-sql\"\n\nconst sql = new Sql(this, \"Sql\", {\n provider: provider,\n database: database,\n statement: \"create table t (i int)\",\n})\n```\n\nCreate a table if it does not exist, and grant a role privileges:\n\n```ts\nconst sql = new Sql(this, \"Sql\", {\n provider: provider,\n database: database,\n statement: `\ncreate table if not exists t (i int);\ngrant select on t to myrole;\n`,\n})\n```\n\nRollback sql on stack deletion:\n\n```ts\nconst sql = new Sql(this, \"Sql\", {\n provider: provider,\n database: database,\n statement: `\ncreate table if not exists t (i int);\ngrant select on t to myrole;\n`,\n rollback: `\nDO $$BEGIN\n IF EXISTS (select from pg_database WHERE datname = 't') THEN\n IF EXISTS (select from pg_catalog.pg_roles WHERE rolname = 'myrole') THEN\n revoke select t from myrole;\n END IF;\n drop table t;\n END IF;\nEND$$;\n`,\n})\n```\n\nNote that there is no synchronisation between various `Sql`\nconstructs, in particular the order in your code does not determine\nthe order in which your SQL is executed. This happens in parallel,\nunless you specify an explicit dependency via `sql.node.addDepency()`.\n\nThere are a lot of concerns when using `Sql`:\n\n- When you update your Sql, your previous Sql is not \"rolled back\",\n the new Sql is simply executed again.\n- When you delete your `Sql` construct the rollback is executed if specified\n- When permission are granted via `Sql` they must be removed via\n rollback to succesfully remove the role\n- Currently the `Sql` constructs has less than 5 minutes to execute\n its work.\n- It is unknown how large your SQL can be.\n\n# Parameters\n\nSome lambda constructs, in particular [Bref](https://bref.sh/), do not\nsupport secrets out of the box. Use the `parameterPrefix` property to\ncreate SSM parameters in addition to a secret:\n\n```ts\nconst role = new Role(this, \"Role\", {\n provider: provider,\n roleName: \"myrole\",\n databaseName: \"mydb\",\n parameterPrefix: \"/my-app/\",\n})\n```\n\nThis will create `/my-app/username`, `/my-app/password` and such.\n\nTo access parameters you will need IAM permissions such as:\n\n```ts\ninitialPolicy: [\n new iam.PolicyStatement({\n\tactions: [\"ssm:GetParameter\", \"ssm:GetParameters\"],\n\tresources: [\n\t // Grant access to all parameters under the base path\n\t `arn:aws:ssm:${this.region}:${this.account}:parameter/my-app/*`,\n\t],\n\teffect: iam.Effect.ALLOW,\n })\n],\n```\n\nNote that your VPC will need an SSM Parameters interface endpoint to support this.\n\n# AWS DSQL Support\n\nThis construct also supports AWS DSQL. DSQL is a great number of\nlimitations around it's postgresql support, so there is some learing\ncurve. This library supports creating roles, schemas, and executing\nSQL on DSQL clusters. Creating databases is not supported by DSQL.\n\n## DSQL Provider Setup\n\nDSQL clusters don't require a VPC or secrets since they use IAM authentication:\n\n```ts\nimport * as dsql from \"aws-cdk-lib/aws-dsql\"\nimport { Provider } from \"cdk-rds-sql\"\n\nconst dsqlCluster = new dsql.CfnCluster(this, \"DsqlCluster\", {\n deletionProtectionEnabled: false,\n})\n\nconst provider = new Provider(this, \"Provider\", {\n cluster: dsqlCluster,\n // No VPC or secret needed for DSQL\n})\n```\n\nYou can access DSQL from within a VPC, but cdk-rds-sql has not been\nspecifically tested with that scenario.\n\n## DSQL Roles\n\nDSQL always uses IAM authentication, so the `enableIamAuth` property is ignored:\n\n```ts\nimport { Role } from \"cdk-rds-sql\"\n\nconst role = new Role(this, \"Role\", {\n provider: provider,\n roleName: \"myrole\",\n})\n```\n\n## Using DSQL\n\nConnecting to DSQL requires a couple of things:\n\n1. Your IAM role needs the `dsql:DbConnect` IAM permission to connect to the cluster.\n2. You probably want a normal postgres role (not \"admin\") to use from your apps.\n3. Your IAM role needs to be connected to your postgres role: use the `IamGrant` construct for that:\n\n ```ts\n new IamGrant(this, \"LambdaIamGrant\", {\n provider: provider,\n roleName: role.roleName,\n resourceArn: queryLambda.role!.roleArn,\n })\n ```\n\n4. From your code use the Dsql signer to create the password:\n\n ```ts\n import { DsqlSigner } from \"@aws-sdk/dsql-signer\"\n import { Client } from \"pg\"\n\n const region =\n process.env[\"AWS_REGION\"] || process.env[\"AWS_DEFAULT_REGION\"] || \"us-west-2\"\n\n // Generate DSQL auth token using AWS SDK\n const signer = new DsqlSigner({\n hostname: host,\n region,\n })\n\n const authToken = await signer.getDbConnectAuthToken()\n\n const client = new Client({\n host,\n port: 5432,\n user: dbUser,\n database: dbName,\n password: authToken,\n ssl: { rejectUnauthorized: false },\n })\n\n await client.connect()\n ```\n\n# IPv6\n\nIf you use the provider in an IPv6 subnet you probably need these settings:\n\n```ts\nimport { Provider } from \"cdk-rds-sql\"\n\nconst provider = new Provider(this, \"Provider\", {\n ...\n functionProps: {\n\tipv6AllowedForDualStack: true,\n\tallowAllIpv6Outbound: true,\n },\n}\n```\n\n# Disabling SSL\n\nThe default connection to RDS is ssl enabled. You can disable ssl by\nsetting the `ssl` option to `false`:\n\n```ts\nconst provider = new Provider(this, \"Provider\", {\n vpc: vpc,\n instance: instance,\n secret: cluster.secret!,\n ssl: false, // default is true\n})\n```\n\n# Working on this code\n\nThis code is managed by [projen](https://github.com/projen/projen).\n[mise](https://mise.jdx.dev/) installs Node 24, pnpm 12, and\n[hk](https://hk.jdx.dev/) for Git hooks. Biome handles formatting and linting.\n\nDevelopment and CI use Node 24. Testcontainers is a development-only dependency;\nits dependency tree requires newer APIs than the consumer minimum of Node 22.14.\n\nAfter cloning:\n\n```sh\nmise trust\nmise install\nmise run setup\n```\n\nWhen migrating an existing clone, replace the old pre-commit hooks with\n`mise exec -- hk install --mise --force`.\n\nRun all checks with `mise run check`, or format and lint with\n`pnpm exec projen biome`. Tests require Docker. TypeScript stays on the\n6.0 release line supported by jsii 6.0.\n\nThe pre-commit hook runs the full build, tests, and packaging, so Docker must\nbe running. When `VPC_ID` is set, changes under `src/` also run CDK synthesis\nagainst that VPC; this requires AWS credentials. Unset `VPC_ID` to skip synthesis.\n\nThe development tsconfig uses `node16` module resolution, including package\nexports. Jest tasks enable Node's VM module support for native dynamic imports\nsuch as the MySQL driver import.\n\n## Testing\n\nTest code via projen with:\n\n pnpm exec projen test\n\nTests do not update snapshots automatically. To intentionally refresh them, run\n`pnpm exec projen test:update` and review the snapshot diff.\n\nYou can run the PostgreSQL sample stack with:\n\n pnpm exec projen integ:deploy:postgresql:serverless\n\nIf you want to use an existing vpc:\n\n pnpm exec cdk deploy --context vpc-id=vpc-0123456789 TestRdsSqlServerlessV2Stack\n\nYou can also test DSQL support with:\n\n pnpm exec projen integ:deploy:dsql\n\n# To do\n\n- Update role: will not revoke connect to previous database if database name has changed.\n"
|
|
9751
|
+
"markdown": "# About\n\nThis CDK construct library makes it possible to create databases,\nschemas, and roles in an Aurora Serverless v2, RDS Database Cluster,\nDatabase Instance, or AWS DSQL clusters. PostgreSQL, MySQL, and DSQL\ndatabases are supported.\n\nThis construct library is intended to be used in enterprise\nenvironments, and works in isolated subnets.\n\n<p align=\"left\">\n <a href=\"https://github.com/semantic-release/semantic-release\"><img src=\"https://img.shields.io/badge/semantic--release-angular-e10079?logo=semantic-release\" alt=semantic-release: angular\"></a>\n <a href=\"https://github.com/berenddeboer/cdk-rds-sql/actions/workflows/release.yml\"><img src=\"https://github.com/berenddeboer/cdk-rds-sql/actions/workflows/release.yml/badge.svg\" alt=\"Release badge\"></a>\n</p>\n\n# Requirements\n\n- CDK v2.\n- Node.js 22.14 or newer for consumers, as declared in `package.json`'s `engines`.\n This is the library's supported minimum, independent of its development tools.\n\n# Installation\n\n npm i cdk-rds-sql\n\nFor .NET (available from the first NuGet release):\n\n```sh\ndotnet add package BerenddeBoer.CdkRdsSql\n```\n\nThe .NET namespace is `BerenddeBoer.CdkRdsSql`. Node.js is also required\nwhen using the .NET bindings.\n\n# Usage\n\n## Provider\n\nFirst setup your VPC and create your cluster:\n\n```ts\nimport { Duration, RemovalPolicy } from \"aws-cdk-lib\"\nimport * as ec2 from \"aws-cdk-lib/aws-ec2\"\nimport * as rds from \"aws-cdk-lib/aws-rds\"\n\nconst vpc = ec2.Vpc.fromLookup(this, \"Vpc\", {\n vpcId: this.node.tryGetContext(\"vpc-id\"),\n})\n\nconst cluster = new rds.ServerlessCluster(this, \"Cluster\", {\n vpc: vpc,\n vpcSubnets: {\n subnetType: ec2.SubnetType.PRIVATE_ISOLATED,\n },\n engine: rds.DatabaseClusterEngine.AURORA_POSTGRESQL,\n parameterGroup: rds.ParameterGroup.fromParameterGroupName(\n this,\n \"ParameterGroup\",\n \"default.aurora-postgresql11\"\n ),\n removalPolicy: RemovalPolicy.DESTROY,\n scaling: {\n autoPause: Duration.minutes(60),\n minCapacity: rds.AuroraCapacityUnit.ACU_2,\n maxCapacity: rds.AuroraCapacityUnit.ACU_2,\n },\n})\n```\n\nThen create a provider which will connect to your database. For a cluster:\n\n```ts\nimport { Provider } from \"cdk-rds-sql\"\n\nconst provider = new Provider(this, \"Provider\", {\n vpc: vpc,\n cluster: cluster,\n secret: cluster.secret!,\n})\n```\n\nFor an instance:\n\n```ts\nimport { Provider } from \"cdk-rds-sql\"\n\nconst provider = new Provider(this, \"Provider\", {\n vpc: vpc,\n instance: instance,\n secret: cluster.secret!,\n})\n```\n\nThe provider will setup a lambda, which normally lives in the same VPC\nas the database. You can give a different VPC, as long as that VPC has\naccess to the VPC of the database. Only the provider lambda will talk\nto your database.\n\nThe provider will by default use the private isolated subnet of the\nVPC. Your isolated network must have a VPC endpoint to AWS Secrets Manager\nand possibly KMS as well. If you want to use a subnet with egress\naccess in case you have no such VPC endpoints, specify the subnet as\nfollows:\n\n```ts\nimport { Provider } from \"cdk-rds-sql\"\n\nconst provider = new Provider(this, \"Provider\", {\n vpc: vpc,\n vpcSubnets: {\n subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS,\n },\n cluster: cluster,\n secret: cluster.secret!,\n})\n```\n\n## Roles\n\nCreate a postgres role (or mysql user) for a cluster as follows:\n\n```ts\nimport { Role } from \"cdk-rds-sql\"\n\nconst role = new Role(this, \"Role\", {\n provider: provider,\n roleName: \"myrole\",\n databaseName: \"mydb\",\n})\n```\n\nThis will automatically create a secret just like `ServerlessCluster`\ndoes, with all the connection info needed for this user. It's secret\nvalue is a JSON like:\n\n```json\n{\n \"dbClusterIdentifier\": \"teststack-clustereb1186t9-sh4wpqfdyfvu\",\n \"password\": \"very-long-and-boring\",\n \"dbname\": \"mydb\",\n \"engine\": \"postgres\",\n \"port\": 5432,\n \"host\": \"teststack-clustereb1186t9-sh4wpqfdyfvu.cluster-cgudolabssna.us-east-1.rds.amazonaws.com\",\n \"username\": \"myrole\"\n}\n```\n\nYou can access the secret via `role.secret`.\n\nThe provider briefly retries role-secret `AccessDeniedException` errors to allow\nnew IAM grants to propagate, including when copying the password to SSM. A\npersistent denial still fails the deployment after the retry window. If it\npersists, check that the provider's Lambda execution role can read the secret\nand, when a customer-managed KMS key is used, decrypt it.\n\nInstead of `databaseName` you can also specify `database` to reference\nan existing database. The role will not be created until the database\nhas been created.\n\nIf you want to make the role the owner of a new database, just specify\nthe `databaseName` here, and create the database later.\n\n### Connection limit (MySQL/MariaDB)\n\nCap how many connections a MySQL or MariaDB user may open:\n\n```ts\nconst role = new Role(this, \"Role\", {\n provider: provider,\n roleName: \"myrole\",\n databaseName: \"mydb\",\n maxUserConnections: 5,\n})\n```\n\nCreate and update then run:\n\n```sql\nALTER USER 'myrole'@'%' WITH MAX_USER_CONNECTIONS 5\n```\n\nOmit `maxUserConnections` to leave the user unlimited, which is the\nexisting behaviour. Omitting it does not clear a limit that was already\napplied; set `0` to restore the server default (unlimited unless the\nglobal `max_user_connections` is set). PostgreSQL and DSQL throw if\nthis property is set.\n\n### IAM Authentication\n\nInstead of password-based authentication, you can create roles that\nuse AWS IAM database authentication. This eliminates the need to store\ndatabase passwords and provides enhanced security through AWS IAM\npolicies.\n\n```ts\nimport { Role } from \"cdk-rds-sql\"\n\nconst iamRole = new Role(this, \"IamRole\", {\n provider: provider,\n roleName: \"myiamrole\",\n databaseName: \"mydb\",\n enableIamAuth: true,\n})\n```\n\nWhen `enableIamAuth` is set to `true`:\n\n- **No secret is created** - the `role.secret` property will be `undefined`\n- The database role is created without a password\n- Your application must generate an IAM authentication token at runtime\n\nThis is the same behavior as DSQL clusters, which always use IAM authentication.\n\n**Requirements for IAM Authentication:**\n\n- SSL connections are required (enabled by default in this library)\n- Your application must have IAM permissions to connect to the database\n- The database user/role name must match the IAM identity\n\n**IAM Policy Example:**\n\nYour application will need an IAM policy like this to connect:\n\n```json\n{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Action\": [\"rds-db:connect\"],\n \"Resource\": [\n \"arn:aws:rds-db:region:account-id:dbuser:cluster-resource-id/myiamrole\"\n ]\n }\n ]\n}\n```\n\n**Generating an IAM Authentication Token:**\n\nAt runtime, your application needs to generate an authentication token\nusing the AWS SDK. Here's an example using the AWS SDK for JavaScript:\n\n```ts\nimport { Signer } from \"@aws-sdk/rds-signer\"\nimport { Client } from \"pg\"\n\nconst signer = new Signer({\n hostname: \"your-cluster.cluster-xxxxx.us-east-1.rds.amazonaws.com\",\n port: 5432,\n username: \"myiamrole\",\n region: \"us-east-1\",\n})\n\nconst token = await signer.getAuthToken()\n\nconst client = new Client({\n host: \"your-cluster.cluster-xxxxx.us-east-1.rds.amazonaws.com\",\n port: 5432,\n user: \"myiamrole\",\n database: \"mydb\",\n password: token,\n ssl: { rejectUnauthorized: true },\n})\n\nawait client.connect()\n```\n\nBoth PostgreSQL and MySQL databases support IAM authentication. For more details, see the [AWS RDS IAM Database Authentication documentation](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html).\n\n### MySQL support\n\nIn MySQL users are created with '%' as value for the host. It is hard\nto do this better:\n\n- Determine the CIDR blocks used by a VPC is not trivial.\n- For imported VPCs you cannot specify the IPv6 CIDR.\n- CIDRs might change without the system knowing, meaning applications\n could lose access to the database at random times, such as when a\n container is restarted.\n\n## Database\n\nCreate a database as follows:\n\n```ts\nimport { Database } from \"cdk-rds-sql\"\n\nconst database = new Database(this, \"Database\", {\n provider: provider,\n databaseName: \"mydb\",\n})\n```\n\nYou can provide an owner, which makes it easy to create database owned\nby a new user:\n\n```ts\nconst database = new Database(this, \"Database\", {\n provider: provider,\n databaseName: \"mydb\",\n owner: role,\n})\n```\n\n## Schema\n\nCreate a schema in the default database as follows:\n\n```ts\nimport { Schema } from \"cdk-rds-sql\"\n\nnew Schema(this, \"Schema\", {\n provider: provider,\n schemaName: \"myschema\",\n})\n```\n\nOr in another database:\n\n```ts\nconst database = new Database(this, \"Database\", {\n provider: provider,\n databaseName: \"mydb\",\n})\n\nnew Schema(this, \"Schema\", {\n provider: provider,\n schemaName: \"myschema\",\n databaseName: database.databaseName,\n})\n```\n\nOne may need a role permitted for using schema:\n\n```ts\nnew Schema(this, \"Schema\", {\n provider: provider,\n schemaName: \"myschema\",\n databaseName: database.databaseName,\n role: role,\n})\n```\n\n## Sql\n\nYou can insert arbitrary SQL into your database with the `Sql` construct:\n\n```ts\nimport { Sql } from \"cdk-rds-sql\"\n\nconst sql = new Sql(this, \"Sql\", {\n provider: provider,\n database: database,\n statement: \"create table t (i int)\",\n})\n```\n\nCreate a table if it does not exist, and grant a role privileges:\n\n```ts\nconst sql = new Sql(this, \"Sql\", {\n provider: provider,\n database: database,\n statement: `\ncreate table if not exists t (i int);\ngrant select on t to myrole;\n`,\n})\n```\n\nRollback sql on stack deletion:\n\n```ts\nconst sql = new Sql(this, \"Sql\", {\n provider: provider,\n database: database,\n statement: `\ncreate table if not exists t (i int);\ngrant select on t to myrole;\n`,\n rollback: `\nDO $$BEGIN\n IF EXISTS (select from pg_database WHERE datname = 't') THEN\n IF EXISTS (select from pg_catalog.pg_roles WHERE rolname = 'myrole') THEN\n revoke select t from myrole;\n END IF;\n drop table t;\n END IF;\nEND$$;\n`,\n})\n```\n\nNote that there is no synchronisation between various `Sql`\nconstructs, in particular the order in your code does not determine\nthe order in which your SQL is executed. This happens in parallel,\nunless you specify an explicit dependency via `sql.node.addDepency()`.\n\nThere are a lot of concerns when using `Sql`:\n\n- When you update your Sql, your previous Sql is not \"rolled back\",\n the new Sql is simply executed again.\n- When you delete your `Sql` construct the rollback is executed if specified\n- When permission are granted via `Sql` they must be removed via\n rollback to succesfully remove the role\n- Currently the `Sql` constructs has less than 5 minutes to execute\n its work.\n- It is unknown how large your SQL can be.\n\n# Parameters\n\nSome lambda constructs, in particular [Bref](https://bref.sh/), do not\nsupport secrets out of the box. Use the `parameterPrefix` property to\ncreate SSM parameters in addition to a secret:\n\n```ts\nconst role = new Role(this, \"Role\", {\n provider: provider,\n roleName: \"myrole\",\n databaseName: \"mydb\",\n parameterPrefix: \"/my-app/\",\n})\n```\n\nThis will create `/my-app/username`, `/my-app/password` and such.\n\nTo access parameters you will need IAM permissions such as:\n\n```ts\ninitialPolicy: [\n new iam.PolicyStatement({\n\tactions: [\"ssm:GetParameter\", \"ssm:GetParameters\"],\n\tresources: [\n\t // Grant access to all parameters under the base path\n\t `arn:aws:ssm:${this.region}:${this.account}:parameter/my-app/*`,\n\t],\n\teffect: iam.Effect.ALLOW,\n })\n],\n```\n\nNote that your VPC will need an SSM Parameters interface endpoint to support this.\n\n# AWS DSQL Support\n\nThis construct also supports AWS DSQL. DSQL is a great number of\nlimitations around it's postgresql support, so there is some learing\ncurve. This library supports creating roles, schemas, and executing\nSQL on DSQL clusters. Creating databases is not supported by DSQL.\n\n## DSQL Provider Setup\n\nDSQL clusters don't require a VPC or secrets since they use IAM authentication:\n\n```ts\nimport * as dsql from \"aws-cdk-lib/aws-dsql\"\nimport { Provider } from \"cdk-rds-sql\"\n\nconst dsqlCluster = new dsql.CfnCluster(this, \"DsqlCluster\", {\n deletionProtectionEnabled: false,\n})\n\nconst provider = new Provider(this, \"Provider\", {\n cluster: dsqlCluster,\n // No VPC or secret needed for DSQL\n})\n```\n\nYou can access DSQL from within a VPC, but cdk-rds-sql has not been\nspecifically tested with that scenario.\n\n## DSQL Roles\n\nDSQL always uses IAM authentication, so the `enableIamAuth` property is ignored:\n\n```ts\nimport { Role } from \"cdk-rds-sql\"\n\nconst role = new Role(this, \"Role\", {\n provider: provider,\n roleName: \"myrole\",\n})\n```\n\n## Using DSQL\n\nConnecting to DSQL requires a couple of things:\n\n1. Your IAM role needs the `dsql:DbConnect` IAM permission to connect to the cluster.\n2. You probably want a normal postgres role (not \"admin\") to use from your apps.\n3. Your IAM role needs to be connected to your postgres role: use the `IamGrant` construct for that:\n\n ```ts\n new IamGrant(this, \"LambdaIamGrant\", {\n provider: provider,\n roleName: role.roleName,\n resourceArn: queryLambda.role!.roleArn,\n })\n ```\n\n4. From your code use the Dsql signer to create the password:\n\n ```ts\n import { DsqlSigner } from \"@aws-sdk/dsql-signer\"\n import { Client } from \"pg\"\n\n const region =\n process.env[\"AWS_REGION\"] || process.env[\"AWS_DEFAULT_REGION\"] || \"us-west-2\"\n\n // Generate DSQL auth token using AWS SDK\n const signer = new DsqlSigner({\n hostname: host,\n region,\n })\n\n const authToken = await signer.getDbConnectAuthToken()\n\n const client = new Client({\n host,\n port: 5432,\n user: dbUser,\n database: dbName,\n password: authToken,\n ssl: { rejectUnauthorized: false },\n })\n\n await client.connect()\n ```\n\n# IPv6\n\nIf you use the provider in an IPv6 subnet you probably need these settings:\n\n```ts\nimport { Provider } from \"cdk-rds-sql\"\n\nconst provider = new Provider(this, \"Provider\", {\n ...\n functionProps: {\n\tipv6AllowedForDualStack: true,\n\tallowAllIpv6Outbound: true,\n },\n}\n```\n\n# Disabling SSL\n\nThe default connection to RDS is ssl enabled. You can disable ssl by\nsetting the `ssl` option to `false`:\n\n```ts\nconst provider = new Provider(this, \"Provider\", {\n vpc: vpc,\n instance: instance,\n secret: cluster.secret!,\n ssl: false, // default is true\n})\n```\n\n# Working on this code\n\nThis code is managed by [projen](https://github.com/projen/projen).\n[mise](https://mise.jdx.dev/) installs Node 24, pnpm 12, and\n[hk](https://hk.jdx.dev/) for Git hooks. Biome handles formatting and linting.\n\nDevelopment and CI use Node 24. Testcontainers is a development-only dependency;\nits dependency tree requires newer APIs than the consumer minimum of Node 22.14.\n\nAfter cloning:\n\n```sh\nmise trust\nmise install\nmise run setup\n```\n\nWhen migrating an existing clone, replace the old pre-commit hooks with\n`mise exec -- hk install --mise --force`.\n\nRun all checks with `mise run check`, or format and lint with\n`pnpm exec projen biome`. Tests require Docker. TypeScript stays on the\n6.0 release line supported by jsii 6.0.\n\nThe pre-commit hook runs the full build, tests, and packaging, so Docker must\nbe running. When `VPC_ID` is set, changes under `src/` also run CDK synthesis\nagainst that VPC; this requires AWS credentials. Unset `VPC_ID` to skip synthesis.\n\nThe development tsconfig uses `node16` module resolution, including package\nexports. Jest tasks enable Node's VM module support for native dynamic imports\nsuch as the MySQL driver import.\n\n## Testing\n\nTest code via projen with:\n\n pnpm exec projen test\n\nTests do not update snapshots automatically. To intentionally refresh them, run\n`pnpm exec projen test:update` and review the snapshot diff.\n\nYou can run the PostgreSQL sample stack with:\n\n pnpm exec projen integ:deploy:postgresql:serverless\n\nIf you want to use an existing vpc:\n\n pnpm exec cdk deploy --context vpc-id=vpc-0123456789 TestRdsSqlServerlessV2Stack\n\nYou can also test DSQL support with:\n\n pnpm exec projen integ:deploy:dsql\n\n# To do\n\n- Update role: will not revoke connect to previous database if database name has changed.\n"
|
|
9752
9752
|
},
|
|
9753
9753
|
"repository": {
|
|
9754
9754
|
"type": "git",
|
|
@@ -11289,6 +11289,6 @@
|
|
|
11289
11289
|
"symbolId": "src/sql:SqlProps"
|
|
11290
11290
|
}
|
|
11291
11291
|
},
|
|
11292
|
-
"version": "9.1.
|
|
11293
|
-
"fingerprint": "
|
|
11292
|
+
"version": "9.1.5",
|
|
11293
|
+
"fingerprint": "IeDyZQxWhYu6kvOr2mX1P9XrUKn+0lrWqf3RMlj7LOU="
|
|
11294
11294
|
}
|
package/README.md
CHANGED
|
@@ -147,6 +147,12 @@ value is a JSON like:
|
|
|
147
147
|
|
|
148
148
|
You can access the secret via `role.secret`.
|
|
149
149
|
|
|
150
|
+
The provider briefly retries role-secret `AccessDeniedException` errors to allow
|
|
151
|
+
new IAM grants to propagate, including when copying the password to SSM. A
|
|
152
|
+
persistent denial still fails the deployment after the retry window. If it
|
|
153
|
+
persists, check that the provider's Lambda execution role can read the secret
|
|
154
|
+
and, when a customer-managed KMS key is used, decrypt it.
|
|
155
|
+
|
|
150
156
|
Instead of `databaseName` you can also specify `database` to reference
|
|
151
157
|
an existing database. The role will not be created until the database
|
|
152
158
|
has been created.
|
package/lib/database.js
CHANGED
|
@@ -14,7 +14,7 @@ class ImportedDatabase extends constructs_1.Construct {
|
|
|
14
14
|
}
|
|
15
15
|
}
|
|
16
16
|
class Database extends aws_cdk_lib_1.CustomResource {
|
|
17
|
-
static [JSII_RTTI_SYMBOL_1] = { fqn: "cdk-rds-sql.Database", version: "9.1.
|
|
17
|
+
static [JSII_RTTI_SYMBOL_1] = { fqn: "cdk-rds-sql.Database", version: "9.1.5" };
|
|
18
18
|
/**
|
|
19
19
|
* Return a Database based upon name only. Use for importing existing databases.
|
|
20
20
|
*/
|
package/lib/handler/index.js
CHANGED
|
@@ -488,25 +488,25 @@ var require_backoff = __commonJS({
|
|
|
488
488
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
489
489
|
var options_1 = require_options();
|
|
490
490
|
var delay_factory_1 = require_delay_factory();
|
|
491
|
-
function
|
|
491
|
+
function backOff3(request, options) {
|
|
492
492
|
if (options === void 0) {
|
|
493
493
|
options = {};
|
|
494
494
|
}
|
|
495
495
|
return __awaiter(this, void 0, void 0, function() {
|
|
496
|
-
var sanitizedOptions,
|
|
496
|
+
var sanitizedOptions, backOff4;
|
|
497
497
|
return __generator(this, function(_a) {
|
|
498
498
|
switch (_a.label) {
|
|
499
499
|
case 0:
|
|
500
500
|
sanitizedOptions = options_1.getSanitizedOptions(options);
|
|
501
|
-
|
|
502
|
-
return [4,
|
|
501
|
+
backOff4 = new BackOff(request, sanitizedOptions);
|
|
502
|
+
return [4, backOff4.execute()];
|
|
503
503
|
case 1:
|
|
504
504
|
return [2, _a.sent()];
|
|
505
505
|
}
|
|
506
506
|
});
|
|
507
507
|
});
|
|
508
508
|
}
|
|
509
|
-
exports2.backOff =
|
|
509
|
+
exports2.backOff = backOff3;
|
|
510
510
|
var BackOff = (
|
|
511
511
|
/** @class */
|
|
512
512
|
(function() {
|
|
@@ -27102,10 +27102,10 @@ __export(handler_exports, {
|
|
|
27102
27102
|
handler: () => handler
|
|
27103
27103
|
});
|
|
27104
27104
|
module.exports = __toCommonJS(handler_exports);
|
|
27105
|
-
var
|
|
27105
|
+
var import_client_secrets_manager3 = require("@aws-sdk/client-secrets-manager");
|
|
27106
27106
|
var import_client_ssm = require("@aws-sdk/client-ssm");
|
|
27107
27107
|
var crypto = __toESM(require("crypto"));
|
|
27108
|
-
var
|
|
27108
|
+
var import_exponential_backoff2 = __toESM(require_backoff());
|
|
27109
27109
|
|
|
27110
27110
|
// src/enum.ts
|
|
27111
27111
|
var RdsSqlResource = /* @__PURE__ */ ((RdsSqlResource2) => {
|
|
@@ -27137,13 +27137,71 @@ var TypeOverrides = import_lib.default.TypeOverrides;
|
|
|
27137
27137
|
var defaults = import_lib.default.defaults;
|
|
27138
27138
|
|
|
27139
27139
|
// lambda/engine.abstract.ts
|
|
27140
|
+
var import_client_secrets_manager2 = require("@aws-sdk/client-secrets-manager");
|
|
27141
|
+
|
|
27142
|
+
// lambda/role-password-secret.ts
|
|
27140
27143
|
var import_client_secrets_manager = require("@aws-sdk/client-secrets-manager");
|
|
27144
|
+
var import_exponential_backoff = __toESM(require_backoff());
|
|
27145
|
+
var startingDelay = 500;
|
|
27146
|
+
var maxDelay = 5e3;
|
|
27147
|
+
var timeMultiple = 2;
|
|
27148
|
+
var retryRequestBudget = 1e4;
|
|
27149
|
+
var responseMargin = 250;
|
|
27150
|
+
function isAccessDenied(error) {
|
|
27151
|
+
return typeof error === "object" && error !== null && "name" in error && error.name === "AccessDeniedException";
|
|
27152
|
+
}
|
|
27153
|
+
function readRolePasswordSecret(client, arn, getRemainingTimeInMillis) {
|
|
27154
|
+
const command = new import_client_secrets_manager.GetSecretValueCommand({ SecretId: arn });
|
|
27155
|
+
let lastDenial;
|
|
27156
|
+
let retryTimedOut = false;
|
|
27157
|
+
async function read() {
|
|
27158
|
+
if (!getRemainingTimeInMillis || !lastDenial) return client.send(command);
|
|
27159
|
+
const requestBudget = Math.min(retryRequestBudget, getRemainingTimeInMillis() - responseMargin);
|
|
27160
|
+
if (requestBudget <= 0) {
|
|
27161
|
+
retryTimedOut = true;
|
|
27162
|
+
throw lastDenial;
|
|
27163
|
+
}
|
|
27164
|
+
const controller = new AbortController();
|
|
27165
|
+
const timeout = setTimeout(() => controller.abort(), requestBudget);
|
|
27166
|
+
try {
|
|
27167
|
+
return await client.send(command, { abortSignal: controller.signal });
|
|
27168
|
+
} catch (error) {
|
|
27169
|
+
if (!controller.signal.aborted) throw error;
|
|
27170
|
+
retryTimedOut = true;
|
|
27171
|
+
throw lastDenial;
|
|
27172
|
+
} finally {
|
|
27173
|
+
clearTimeout(timeout);
|
|
27174
|
+
}
|
|
27175
|
+
}
|
|
27176
|
+
return (0, import_exponential_backoff.backOff)(read, {
|
|
27177
|
+
numOfAttempts: 10,
|
|
27178
|
+
startingDelay,
|
|
27179
|
+
maxDelay,
|
|
27180
|
+
timeMultiple,
|
|
27181
|
+
delayFirstAttempt: false,
|
|
27182
|
+
jitter: "full",
|
|
27183
|
+
retry: (error, failedAttempts) => {
|
|
27184
|
+
if (retryTimedOut || !isAccessDenied(error)) return false;
|
|
27185
|
+
if (!getRemainingTimeInMillis) return true;
|
|
27186
|
+
const nextDelay = Math.min(maxDelay, startingDelay * timeMultiple ** (failedAttempts - 1));
|
|
27187
|
+
if (getRemainingTimeInMillis() <= nextDelay + retryRequestBudget + responseMargin) {
|
|
27188
|
+
return false;
|
|
27189
|
+
}
|
|
27190
|
+
lastDenial = error;
|
|
27191
|
+
return true;
|
|
27192
|
+
}
|
|
27193
|
+
});
|
|
27194
|
+
}
|
|
27195
|
+
|
|
27196
|
+
// lambda/engine.abstract.ts
|
|
27141
27197
|
var AbstractEngine = class {
|
|
27142
|
-
|
|
27143
|
-
|
|
27198
|
+
constructor(getRemainingTimeInMillis) {
|
|
27199
|
+
this.getRemainingTimeInMillis = getRemainingTimeInMillis;
|
|
27144
27200
|
this.log = process.env.LOGGER === "true" ? console.debug : (_message, ..._optionalParams) => {
|
|
27145
27201
|
};
|
|
27146
27202
|
}
|
|
27203
|
+
getRemainingTimeInMillis;
|
|
27204
|
+
log;
|
|
27147
27205
|
/**
|
|
27148
27206
|
* Load connection state required before SQL is rendered.
|
|
27149
27207
|
* MySQL literal escaping depends on the session SQL mode, so the handler
|
|
@@ -27152,20 +27210,17 @@ var AbstractEngine = class {
|
|
|
27152
27210
|
async prepare(_config) {
|
|
27153
27211
|
}
|
|
27154
27212
|
/**
|
|
27155
|
-
* Parse password field from secret
|
|
27213
|
+
* Parse the password field from the secret, if present.
|
|
27156
27214
|
*/
|
|
27157
27215
|
async getPassword(arn) {
|
|
27158
27216
|
if (!arn) return;
|
|
27159
|
-
const secrets_client2 = new
|
|
27217
|
+
const secrets_client2 = new import_client_secrets_manager2.SecretsManagerClient({
|
|
27160
27218
|
requestHandler: {
|
|
27161
27219
|
connectionTimeout: 5e3,
|
|
27162
27220
|
requestTimeout: 1e4
|
|
27163
27221
|
}
|
|
27164
27222
|
});
|
|
27165
|
-
const
|
|
27166
|
-
SecretId: arn
|
|
27167
|
-
});
|
|
27168
|
-
const secret = await secrets_client2.send(command);
|
|
27223
|
+
const secret = await readRolePasswordSecret(secrets_client2, arn, this.getRemainingTimeInMillis);
|
|
27169
27224
|
if (secret.SecretString) {
|
|
27170
27225
|
const json = JSON.parse(secret.SecretString);
|
|
27171
27226
|
return json.password;
|
|
@@ -27930,18 +27985,18 @@ END$$;`,
|
|
|
27930
27985
|
|
|
27931
27986
|
// lambda/engine.factory.ts
|
|
27932
27987
|
var EngineFactory = class {
|
|
27933
|
-
static createEngine(engine) {
|
|
27988
|
+
static createEngine(engine, getRemainingTimeInMillis) {
|
|
27934
27989
|
switch (engine.toLowerCase()) {
|
|
27935
27990
|
case "dsql":
|
|
27936
27991
|
return new DsqlEngine();
|
|
27937
27992
|
case "postgres":
|
|
27938
27993
|
case "postgresql":
|
|
27939
27994
|
case "aurora-postgresql":
|
|
27940
|
-
return new PostgresqlEngine();
|
|
27995
|
+
return new PostgresqlEngine(getRemainingTimeInMillis);
|
|
27941
27996
|
case "mysql":
|
|
27942
27997
|
case "mariadb":
|
|
27943
27998
|
case "aurora-mysql":
|
|
27944
|
-
return new MysqlEngine();
|
|
27999
|
+
return new MysqlEngine(getRemainingTimeInMillis);
|
|
27945
28000
|
default:
|
|
27946
28001
|
throw new Error(`Unsupported database engine: ${engine}`);
|
|
27947
28002
|
}
|
|
@@ -27952,7 +28007,7 @@ var EngineFactory = class {
|
|
|
27952
28007
|
var maxAttempts = 20;
|
|
27953
28008
|
var log = process.env.LOGGER === "true" ? console.debug : (_message, ..._optionalParams) => {
|
|
27954
28009
|
};
|
|
27955
|
-
var secrets_client = new
|
|
28010
|
+
var secrets_client = new import_client_secrets_manager3.SecretsManagerClient({});
|
|
27956
28011
|
function toDatabaseEngineProps(props) {
|
|
27957
28012
|
if (props.Resource !== "database" /* DATABASE */) {
|
|
27958
28013
|
throw new Error(`Expected DATABASE resource, got ${props.Resource}`);
|
|
@@ -27999,12 +28054,12 @@ function toIamGrantEngineProps(props) {
|
|
|
27999
28054
|
}
|
|
28000
28055
|
return props;
|
|
28001
28056
|
}
|
|
28002
|
-
var handler = async (event) => {
|
|
28057
|
+
var handler = async (event, context) => {
|
|
28003
28058
|
log(event);
|
|
28004
28059
|
const requestType = event.RequestType;
|
|
28005
|
-
const
|
|
28006
|
-
const
|
|
28007
|
-
const
|
|
28060
|
+
const props = event.ResourceProperties;
|
|
28061
|
+
const { Resource: resource, DatabaseName: databaseName } = props;
|
|
28062
|
+
const resourceId = props.ResourceId ?? "";
|
|
28008
28063
|
if (!Object.values(RdsSqlResource).includes(resource)) {
|
|
28009
28064
|
throw `Resource type '${resource}' not recognised.`;
|
|
28010
28065
|
}
|
|
@@ -28027,11 +28082,11 @@ var handler = async (event) => {
|
|
|
28027
28082
|
if (!secretArn) {
|
|
28028
28083
|
throw "SecretArn is required (not in event properties or environment)";
|
|
28029
28084
|
}
|
|
28030
|
-
const command = new
|
|
28085
|
+
const command = new import_client_secrets_manager3.GetSecretValueCommand({
|
|
28031
28086
|
SecretId: secretArn
|
|
28032
28087
|
});
|
|
28033
28088
|
log(`Fetching secret ${secretArn}`);
|
|
28034
|
-
const secret = await (0,
|
|
28089
|
+
const secret = await (0, import_exponential_backoff2.backOff)(
|
|
28035
28090
|
async () => {
|
|
28036
28091
|
try {
|
|
28037
28092
|
const result = await secrets_client.send(command);
|
|
@@ -28052,7 +28107,8 @@ var handler = async (event) => {
|
|
|
28052
28107
|
secretValues = JSON.parse(secret.SecretString);
|
|
28053
28108
|
engine = secretValues.engine || "postgresql";
|
|
28054
28109
|
}
|
|
28055
|
-
const
|
|
28110
|
+
const getRemainingTimeInMillis = context?.getRemainingTimeInMillis.bind(context);
|
|
28111
|
+
const dbEngine = EngineFactory.createEngine(engine, getRemainingTimeInMillis);
|
|
28056
28112
|
let database;
|
|
28057
28113
|
if (engine === "dsql") {
|
|
28058
28114
|
database = "postgres";
|
|
@@ -28099,7 +28155,7 @@ var handler = async (event) => {
|
|
|
28099
28155
|
break;
|
|
28100
28156
|
}
|
|
28101
28157
|
case "parameter_password" /* PARAMETER_PASSWORD */:
|
|
28102
|
-
await handleParameterPassword(
|
|
28158
|
+
await handleParameterPassword(props, getRemainingTimeInMillis);
|
|
28103
28159
|
break;
|
|
28104
28160
|
}
|
|
28105
28161
|
break;
|
|
@@ -28152,7 +28208,7 @@ var handler = async (event) => {
|
|
|
28152
28208
|
break;
|
|
28153
28209
|
}
|
|
28154
28210
|
case "parameter_password" /* PARAMETER_PASSWORD */:
|
|
28155
|
-
await handleParameterPassword(
|
|
28211
|
+
await handleParameterPassword(props, getRemainingTimeInMillis);
|
|
28156
28212
|
sql = void 0;
|
|
28157
28213
|
break;
|
|
28158
28214
|
}
|
|
@@ -28186,7 +28242,7 @@ var handler = async (event) => {
|
|
|
28186
28242
|
}
|
|
28187
28243
|
if (sql) {
|
|
28188
28244
|
try {
|
|
28189
|
-
await (0,
|
|
28245
|
+
await (0, import_exponential_backoff2.backOff)(
|
|
28190
28246
|
async () => {
|
|
28191
28247
|
return dbEngine.executeSQL(sql, config);
|
|
28192
28248
|
},
|
|
@@ -28223,14 +28279,18 @@ var errorFilter = (error, nextAttemptNumber) => {
|
|
|
28223
28279
|
);
|
|
28224
28280
|
return willRetry;
|
|
28225
28281
|
};
|
|
28226
|
-
async function handleParameterPassword(props) {
|
|
28282
|
+
async function handleParameterPassword(props, getRemainingTimeInMillis) {
|
|
28227
28283
|
const secretArn = props.PasswordArn;
|
|
28228
28284
|
const parameterName = props.ParameterName;
|
|
28229
|
-
const secretData = await
|
|
28285
|
+
const secretData = await readRolePasswordSecret(
|
|
28286
|
+
secrets_client,
|
|
28287
|
+
secretArn,
|
|
28288
|
+
getRemainingTimeInMillis
|
|
28289
|
+
);
|
|
28230
28290
|
if (!secretData.SecretString) throw "No secret string for parameter";
|
|
28231
28291
|
const secretObj = JSON.parse(secretData.SecretString);
|
|
28232
28292
|
const ssmClient = new import_client_ssm.SSMClient({});
|
|
28233
|
-
await (0,
|
|
28293
|
+
await (0, import_exponential_backoff2.backOff)(
|
|
28234
28294
|
() => ssmClient.send(
|
|
28235
28295
|
new import_client_ssm.PutParameterCommand({
|
|
28236
28296
|
Name: parameterName,
|
package/lib/iam-grant.js
CHANGED
|
@@ -6,7 +6,7 @@ const aws_cdk_lib_1 = require("aws-cdk-lib");
|
|
|
6
6
|
const enum_1 = require("./enum");
|
|
7
7
|
const provider_1 = require("./provider");
|
|
8
8
|
class IamGrant extends aws_cdk_lib_1.CustomResource {
|
|
9
|
-
static [JSII_RTTI_SYMBOL_1] = { fqn: "cdk-rds-sql.IamGrant", version: "9.1.
|
|
9
|
+
static [JSII_RTTI_SYMBOL_1] = { fqn: "cdk-rds-sql.IamGrant", version: "9.1.5" };
|
|
10
10
|
constructor(scope, id, props) {
|
|
11
11
|
// IAM grants are only supported on DSQL
|
|
12
12
|
if (props.provider.engine !== provider_1.DatabaseEngine.DSQL) {
|
package/lib/provider.js
CHANGED
|
@@ -60,7 +60,7 @@ var DatabaseEngine;
|
|
|
60
60
|
DatabaseEngine["DSQL"] = "dsql";
|
|
61
61
|
})(DatabaseEngine || (exports.DatabaseEngine = DatabaseEngine = {}));
|
|
62
62
|
class Provider extends constructs_1.Construct {
|
|
63
|
-
static [JSII_RTTI_SYMBOL_1] = { fqn: "cdk-rds-sql.Provider", version: "9.1.
|
|
63
|
+
static [JSII_RTTI_SYMBOL_1] = { fqn: "cdk-rds-sql.Provider", version: "9.1.5" };
|
|
64
64
|
/**
|
|
65
65
|
* Import an existing provider Lambda function
|
|
66
66
|
*/
|
package/lib/role.js
CHANGED
|
@@ -83,7 +83,7 @@ class Parameters extends constructs_1.Construct {
|
|
|
83
83
|
}
|
|
84
84
|
}
|
|
85
85
|
class Role extends constructs_1.Construct {
|
|
86
|
-
static [JSII_RTTI_SYMBOL_1] = { fqn: "cdk-rds-sql.Role", version: "9.1.
|
|
86
|
+
static [JSII_RTTI_SYMBOL_1] = { fqn: "cdk-rds-sql.Role", version: "9.1.5" };
|
|
87
87
|
/**
|
|
88
88
|
* The role name.
|
|
89
89
|
*/
|
package/lib/schema.js
CHANGED
|
@@ -5,7 +5,7 @@ const JSII_RTTI_SYMBOL_1 = Symbol.for("jsii.rtti");
|
|
|
5
5
|
const aws_cdk_lib_1 = require("aws-cdk-lib");
|
|
6
6
|
const enum_1 = require("./enum");
|
|
7
7
|
class Schema extends aws_cdk_lib_1.CustomResource {
|
|
8
|
-
static [JSII_RTTI_SYMBOL_1] = { fqn: "cdk-rds-sql.Schema", version: "9.1.
|
|
8
|
+
static [JSII_RTTI_SYMBOL_1] = { fqn: "cdk-rds-sql.Schema", version: "9.1.5" };
|
|
9
9
|
schemaName;
|
|
10
10
|
constructor(scope, id, props) {
|
|
11
11
|
super(scope, id, {
|
package/lib/sql.js
CHANGED
|
@@ -5,7 +5,7 @@ const JSII_RTTI_SYMBOL_1 = Symbol.for("jsii.rtti");
|
|
|
5
5
|
const aws_cdk_lib_1 = require("aws-cdk-lib");
|
|
6
6
|
const enum_1 = require("./enum");
|
|
7
7
|
class Sql extends aws_cdk_lib_1.CustomResource {
|
|
8
|
-
static [JSII_RTTI_SYMBOL_1] = { fqn: "cdk-rds-sql.Sql", version: "9.1.
|
|
8
|
+
static [JSII_RTTI_SYMBOL_1] = { fqn: "cdk-rds-sql.Sql", version: "9.1.5" };
|
|
9
9
|
constructor(scope, id, props) {
|
|
10
10
|
super(scope, id, {
|
|
11
11
|
serviceToken: props.provider.serviceToken,
|