Skip to content

Commit

Permalink
chore(aws-cdk-lib): prevent deep imports (#17707)
Browse files Browse the repository at this point in the history
Sometimes, IDEs like VSCode will autocomplete deep imports into the CDK
library. For example, they may generate the following:

```ts
import { Bucket } from 'aws-cdk-lib/aws-s3/lib/bucket';
```

Whereas the correct import should have been:

```ts
import { Bucket } from 'aws-cdk-lib/aws-s3';
```

If we allow people to write the former, they will be broken every time
we change the internal file layout of our module (or conversely, we
will not be allowed to change the file layout at all).

Use the `package.json` `"exports"` mechanism to advertise the select
paths that users are allowed to import from, and disallow the rest.


----

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
  • Loading branch information
rix0rrr authored Nov 25, 2021
1 parent b8a4a9a commit 53620e9
Show file tree
Hide file tree
Showing 6 changed files with 546 additions and 11 deletions.
7 changes: 7 additions & 0 deletions packages/@aws-cdk/pipelines/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@
"build+extract": "yarn build && yarn rosetta:extract",
"build+test+extract": "yarn build+test && yarn rosetta:extract"
},
"exports": {
".": "./lib/index.js",
"./package.json": "./package.json",
"./.jsii": "./.jsii",
"./.warnings.jsii.js": "./.warnings.jsii.js",
"./lib/helpers-internal": "./lib/helpers-internal/index.js"
},
"author": {
"name": "Amazon Web Services",
"url": "https://aws.amazon.com",
Expand Down
215 changes: 214 additions & 1 deletion packages/aws-cdk-lib/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@
},
"stripDeprecated": true,
"post": [
"node ./scripts/verify-imports-resolve-same.js"
"node ./scripts/verify-imports-resolve-same.js",
"node ./scripts/verify-imports-shielded.js"
]
},
"cdk-package": {
Expand Down Expand Up @@ -361,5 +362,217 @@
"ubergen": {
"exclude": true,
"excludeExperimentalModules": true
},
"exports": {
".": "./index.js",
"./alexa-ask": "./alexa-ask/index.js",
"./assertions": "./assertions/index.js",
"./assets": "./assets/index.js",
"./aws-accessanalyzer": "./aws-accessanalyzer/index.js",
"./aws-acmpca": "./aws-acmpca/index.js",
"./aws-amazonmq": "./aws-amazonmq/index.js",
"./aws-amplify": "./aws-amplify/index.js",
"./aws-apigateway": "./aws-apigateway/index.js",
"./aws-apigatewayv2": "./aws-apigatewayv2/index.js",
"./aws-appconfig": "./aws-appconfig/index.js",
"./aws-appflow": "./aws-appflow/index.js",
"./aws-appintegrations": "./aws-appintegrations/index.js",
"./aws-applicationautoscaling": "./aws-applicationautoscaling/index.js",
"./aws-applicationinsights": "./aws-applicationinsights/index.js",
"./aws-appmesh": "./aws-appmesh/index.js",
"./aws-apprunner": "./aws-apprunner/index.js",
"./aws-appstream": "./aws-appstream/index.js",
"./aws-appsync": "./aws-appsync/index.js",
"./aws-aps": "./aws-aps/index.js",
"./aws-athena": "./aws-athena/index.js",
"./aws-auditmanager": "./aws-auditmanager/index.js",
"./aws-autoscaling": "./aws-autoscaling/index.js",
"./aws-autoscaling-common": "./aws-autoscaling-common/index.js",
"./aws-autoscaling-hooktargets": "./aws-autoscaling-hooktargets/index.js",
"./aws-autoscalingplans": "./aws-autoscalingplans/index.js",
"./aws-backup": "./aws-backup/index.js",
"./aws-batch": "./aws-batch/index.js",
"./aws-budgets": "./aws-budgets/index.js",
"./aws-cassandra": "./aws-cassandra/index.js",
"./aws-ce": "./aws-ce/index.js",
"./aws-certificatemanager": "./aws-certificatemanager/index.js",
"./aws-chatbot": "./aws-chatbot/index.js",
"./aws-cloud9": "./aws-cloud9/index.js",
"./aws-cloudformation": "./aws-cloudformation/index.js",
"./aws-cloudfront": "./aws-cloudfront/index.js",
"./aws-cloudfront-origins": "./aws-cloudfront-origins/index.js",
"./aws-cloudtrail": "./aws-cloudtrail/index.js",
"./aws-cloudwatch": "./aws-cloudwatch/index.js",
"./aws-cloudwatch-actions": "./aws-cloudwatch-actions/index.js",
"./aws-codeartifact": "./aws-codeartifact/index.js",
"./aws-codebuild": "./aws-codebuild/index.js",
"./aws-codecommit": "./aws-codecommit/index.js",
"./aws-codedeploy": "./aws-codedeploy/index.js",
"./aws-codeguruprofiler": "./aws-codeguruprofiler/index.js",
"./aws-codegurureviewer": "./aws-codegurureviewer/index.js",
"./aws-codepipeline": "./aws-codepipeline/index.js",
"./aws-codepipeline-actions": "./aws-codepipeline-actions/index.js",
"./aws-codestar": "./aws-codestar/index.js",
"./aws-codestarconnections": "./aws-codestarconnections/index.js",
"./aws-codestarnotifications": "./aws-codestarnotifications/index.js",
"./aws-cognito": "./aws-cognito/index.js",
"./aws-config": "./aws-config/index.js",
"./aws-connect": "./aws-connect/index.js",
"./aws-cur": "./aws-cur/index.js",
"./aws-customerprofiles": "./aws-customerprofiles/index.js",
"./aws-databrew": "./aws-databrew/index.js",
"./aws-datapipeline": "./aws-datapipeline/index.js",
"./aws-datasync": "./aws-datasync/index.js",
"./aws-dax": "./aws-dax/index.js",
"./aws-detective": "./aws-detective/index.js",
"./aws-devopsguru": "./aws-devopsguru/index.js",
"./aws-directoryservice": "./aws-directoryservice/index.js",
"./aws-dlm": "./aws-dlm/index.js",
"./aws-dms": "./aws-dms/index.js",
"./aws-docdb": "./aws-docdb/index.js",
"./aws-dynamodb": "./aws-dynamodb/index.js",
"./aws-ec2": "./aws-ec2/index.js",
"./aws-ecr": "./aws-ecr/index.js",
"./aws-ecr-assets": "./aws-ecr-assets/index.js",
"./aws-ecs": "./aws-ecs/index.js",
"./aws-ecs-patterns": "./aws-ecs-patterns/index.js",
"./aws-efs": "./aws-efs/index.js",
"./aws-eks": "./aws-eks/index.js",
"./aws-elasticache": "./aws-elasticache/index.js",
"./aws-elasticbeanstalk": "./aws-elasticbeanstalk/index.js",
"./aws-elasticloadbalancing": "./aws-elasticloadbalancing/index.js",
"./aws-elasticloadbalancingv2": "./aws-elasticloadbalancingv2/index.js",
"./aws-elasticloadbalancingv2-actions": "./aws-elasticloadbalancingv2-actions/index.js",
"./aws-elasticloadbalancingv2-targets": "./aws-elasticloadbalancingv2-targets/index.js",
"./aws-elasticsearch": "./aws-elasticsearch/index.js",
"./aws-emr": "./aws-emr/index.js",
"./aws-emrcontainers": "./aws-emrcontainers/index.js",
"./aws-events": "./aws-events/index.js",
"./aws-events-targets": "./aws-events-targets/index.js",
"./aws-eventschemas": "./aws-eventschemas/index.js",
"./aws-finspace": "./aws-finspace/index.js",
"./aws-fis": "./aws-fis/index.js",
"./aws-fms": "./aws-fms/index.js",
"./aws-frauddetector": "./aws-frauddetector/index.js",
"./aws-fsx": "./aws-fsx/index.js",
"./aws-gamelift": "./aws-gamelift/index.js",
"./aws-globalaccelerator": "./aws-globalaccelerator/index.js",
"./aws-globalaccelerator-endpoints": "./aws-globalaccelerator-endpoints/index.js",
"./aws-glue": "./aws-glue/index.js",
"./aws-greengrass": "./aws-greengrass/index.js",
"./aws-greengrassv2": "./aws-greengrassv2/index.js",
"./aws-groundstation": "./aws-groundstation/index.js",
"./aws-guardduty": "./aws-guardduty/index.js",
"./aws-healthlake": "./aws-healthlake/index.js",
"./aws-iam": "./aws-iam/index.js",
"./aws-imagebuilder": "./aws-imagebuilder/index.js",
"./aws-inspector": "./aws-inspector/index.js",
"./aws-iot": "./aws-iot/index.js",
"./aws-iot1click": "./aws-iot1click/index.js",
"./aws-iotanalytics": "./aws-iotanalytics/index.js",
"./aws-iotcoredeviceadvisor": "./aws-iotcoredeviceadvisor/index.js",
"./aws-iotevents": "./aws-iotevents/index.js",
"./aws-iotfleethub": "./aws-iotfleethub/index.js",
"./aws-iotsitewise": "./aws-iotsitewise/index.js",
"./aws-iotthingsgraph": "./aws-iotthingsgraph/index.js",
"./aws-iotwireless": "./aws-iotwireless/index.js",
"./aws-ivs": "./aws-ivs/index.js",
"./aws-kendra": "./aws-kendra/index.js",
"./aws-kinesis": "./aws-kinesis/index.js",
"./aws-kinesisanalytics": "./aws-kinesisanalytics/index.js",
"./aws-kinesisfirehose": "./aws-kinesisfirehose/index.js",
"./aws-kms": "./aws-kms/index.js",
"./aws-lakeformation": "./aws-lakeformation/index.js",
"./aws-lambda": "./aws-lambda/index.js",
"./aws-lambda-destinations": "./aws-lambda-destinations/index.js",
"./aws-lambda-event-sources": "./aws-lambda-event-sources/index.js",
"./aws-lambda-nodejs": "./aws-lambda-nodejs/index.js",
"./aws-licensemanager": "./aws-licensemanager/index.js",
"./aws-lightsail": "./aws-lightsail/index.js",
"./aws-location": "./aws-location/index.js",
"./aws-logs": "./aws-logs/index.js",
"./aws-logs-destinations": "./aws-logs-destinations/index.js",
"./aws-lookoutequipment": "./aws-lookoutequipment/index.js",
"./aws-lookoutmetrics": "./aws-lookoutmetrics/index.js",
"./aws-lookoutvision": "./aws-lookoutvision/index.js",
"./aws-macie": "./aws-macie/index.js",
"./aws-managedblockchain": "./aws-managedblockchain/index.js",
"./aws-mediaconnect": "./aws-mediaconnect/index.js",
"./aws-mediaconvert": "./aws-mediaconvert/index.js",
"./aws-medialive": "./aws-medialive/index.js",
"./aws-mediapackage": "./aws-mediapackage/index.js",
"./aws-mediastore": "./aws-mediastore/index.js",
"./aws-memorydb": "./aws-memorydb/index.js",
"./aws-msk": "./aws-msk/index.js",
"./aws-mwaa": "./aws-mwaa/index.js",
"./aws-neptune": "./aws-neptune/index.js",
"./aws-networkfirewall": "./aws-networkfirewall/index.js",
"./aws-networkmanager": "./aws-networkmanager/index.js",
"./aws-nimblestudio": "./aws-nimblestudio/index.js",
"./aws-opensearchservice": "./aws-opensearchservice/index.js",
"./aws-opsworks": "./aws-opsworks/index.js",
"./aws-opsworkscm": "./aws-opsworkscm/index.js",
"./aws-panorama": "./aws-panorama/index.js",
"./aws-pinpoint": "./aws-pinpoint/index.js",
"./aws-pinpointemail": "./aws-pinpointemail/index.js",
"./aws-qldb": "./aws-qldb/index.js",
"./aws-quicksight": "./aws-quicksight/index.js",
"./aws-ram": "./aws-ram/index.js",
"./aws-rds": "./aws-rds/index.js",
"./aws-redshift": "./aws-redshift/index.js",
"./aws-rekognition": "./aws-rekognition/index.js",
"./aws-resourcegroups": "./aws-resourcegroups/index.js",
"./aws-robomaker": "./aws-robomaker/index.js",
"./aws-route53": "./aws-route53/index.js",
"./aws-route53-patterns": "./aws-route53-patterns/index.js",
"./aws-route53-targets": "./aws-route53-targets/index.js",
"./aws-route53recoverycontrol": "./aws-route53recoverycontrol/index.js",
"./aws-route53recoveryreadiness": "./aws-route53recoveryreadiness/index.js",
"./aws-route53resolver": "./aws-route53resolver/index.js",
"./aws-s3": "./aws-s3/index.js",
"./aws-s3-assets": "./aws-s3-assets/index.js",
"./aws-s3-deployment": "./aws-s3-deployment/index.js",
"./aws-s3-notifications": "./aws-s3-notifications/index.js",
"./aws-s3objectlambda": "./aws-s3objectlambda/index.js",
"./aws-s3outposts": "./aws-s3outposts/index.js",
"./aws-sagemaker": "./aws-sagemaker/index.js",
"./aws-sam": "./aws-sam/index.js",
"./aws-sdb": "./aws-sdb/index.js",
"./aws-secretsmanager": "./aws-secretsmanager/index.js",
"./aws-securityhub": "./aws-securityhub/index.js",
"./aws-servicecatalog": "./aws-servicecatalog/index.js",
"./aws-servicecatalogappregistry": "./aws-servicecatalogappregistry/index.js",
"./aws-servicediscovery": "./aws-servicediscovery/index.js",
"./aws-ses": "./aws-ses/index.js",
"./aws-ses-actions": "./aws-ses-actions/index.js",
"./aws-signer": "./aws-signer/index.js",
"./aws-sns": "./aws-sns/index.js",
"./aws-sns-subscriptions": "./aws-sns-subscriptions/index.js",
"./aws-sqs": "./aws-sqs/index.js",
"./aws-ssm": "./aws-ssm/index.js",
"./aws-ssmcontacts": "./aws-ssmcontacts/index.js",
"./aws-ssmincidents": "./aws-ssmincidents/index.js",
"./aws-sso": "./aws-sso/index.js",
"./aws-stepfunctions": "./aws-stepfunctions/index.js",
"./aws-stepfunctions-tasks": "./aws-stepfunctions-tasks/index.js",
"./aws-synthetics": "./aws-synthetics/index.js",
"./aws-timestream": "./aws-timestream/index.js",
"./aws-transfer": "./aws-transfer/index.js",
"./aws-waf": "./aws-waf/index.js",
"./aws-wafregional": "./aws-wafregional/index.js",
"./aws-wafv2": "./aws-wafv2/index.js",
"./aws-wisdom": "./aws-wisdom/index.js",
"./aws-workspaces": "./aws-workspaces/index.js",
"./aws-xray": "./aws-xray/index.js",
"./cloud-assembly-schema": "./cloud-assembly-schema/index.js",
"./cloudformation-include": "./cloudformation-include/index.js",
"./custom-resources": "./custom-resources/index.js",
"./cx-api": "./cx-api/index.js",
"./lambda-layer-awscli": "./lambda-layer-awscli/index.js",
"./lambda-layer-kubectl": "./lambda-layer-kubectl/index.js",
"./lambda-layer-node-proxy-agent": "./lambda-layer-node-proxy-agent/index.js",
"./pipelines": "./pipelines/index.js",
"./pipelines/lib/helpers-internal": "./pipelines/lib/helpers-internal/index.js",
"./region-info": "./region-info/index.js"
}
}
57 changes: 57 additions & 0 deletions packages/aws-cdk-lib/scripts/verify-imports-shielded.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/**
* Check that the imports from 'aws-cdk-lib' we expect to work, work, and those we have shielded off don't work.
*/
import * as os from 'os';
import * as path from 'path';
import * as fs from 'fs-extra';

async function main() {
// First make a tempdir and symlink `aws-cdk-lib` into it so we can refer to it
// as if it was an installed module.
await withTemporaryDirectory(async (tmpDir) => {
await fs.mkdirp(path.join(tmpDir, 'node_modules'));
await fs.symlink(path.resolve(__dirname, '..'), path.join(tmpDir, 'node_modules', 'aws-cdk-lib'));

assertImportSucceeds('aws-cdk-lib');
assertImportFails('aws-cdk-lib/LICENSE', 'ERR_PACKAGE_PATH_NOT_EXPORTED');
assertImportFails('aws-cdk-lib/aws-s3/lib/bucket', 'ERR_PACKAGE_PATH_NOT_EXPORTED');
assertImportSucceeds('aws-cdk-lib/aws-s3');

function assertImportSucceeds(name: string) {
require.resolve(name, { paths: [tmpDir] });
}

function assertImportFails(name: string, code: string) {
try {
require.resolve(name, { paths: [tmpDir] });

// eslint-disable-next-line no-console
console.error(`Import of '${name}' should have produced an error, but didn't.`);
process.exitCode = 1;
} catch (e) {
if ((e as any).code !== code) {
// eslint-disable-next-line no-console
console.error(`Import of '${name}' should have produced error ${code}, but got ${(e as any).code}.`);
process.exitCode = 1;
}
}
}
});
}


export async function withTemporaryDirectory<T>(callback: (dir: string) => Promise<T>): Promise<T> {
const tmpdir = await fs.mkdtemp(path.join(os.tmpdir(), path.basename(__filename)));
try {
return await callback(tmpdir);
} finally {
await fs.remove(tmpdir);
}
}


main().catch((e) => {
// eslint-disable-next-line no-console
console.error(e);
process.exitCode = 1;
});
11 changes: 1 addition & 10 deletions packages/decdk/lib/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,7 @@ export async function readTemplate(templateFile: string) {

export async function loadTypeSystem(validate = true) {
const typeSystem = new jsiiReflect.TypeSystem();
const packageJson = require('../package.json');

for (const depName of Object.keys(packageJson.dependencies || {})) {
const jsiiModuleDir = path.dirname(require.resolve(`${depName}/package.json`));
if (!fs.existsSync(path.resolve(jsiiModuleDir, '.jsii'))) {
continue;
}
await typeSystem.load(jsiiModuleDir, { validate });
}

await typeSystem.loadNpmDependencies(path.resolve(__dirname, '..'), { validate });
return typeSystem;
}

Expand Down
Loading

0 comments on commit 53620e9

Please sign in to comment.