├── .eslintrc.json ├── .gitattributes ├── .github ├── dependabot.yml ├── pull_request_template.md └── workflows │ ├── automerge_dependabot.yml │ ├── build.yml │ └── release.yml ├── .gitignore ├── .gitpod.yml ├── .mergify.yml ├── .npmignore ├── .projen ├── deps.json ├── files.json └── tasks.json ├── .projenrc.js ├── API.md ├── LICENSE ├── README.md ├── cdk.json ├── frontend ├── README.md ├── package-lock.json ├── package.json ├── public │ ├── favicon.ico │ ├── index.html │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── robots.txt └── src │ ├── App.css │ ├── App.js │ ├── App.test.js │ ├── aws-exports.js │ ├── index.css │ ├── index.js │ ├── logo.svg │ ├── reportWebVitals.js │ └── setupTests.js ├── images └── architecture.png ├── package.json ├── src ├── index-function.ts ├── index.lambda.ts ├── index.ts └── integ.default.ts ├── test └── index.test.ts ├── tsconfig.dev.json └── yarn.lock /.eslintrc.json: -------------------------------------------------------------------------------- 1 | // ~~ Generated by projen. To modify, edit .projenrc.js and run "npx projen". 2 | { 3 | "env": { 4 | "jest": true, 5 | "node": true 6 | }, 7 | "root": true, 8 | "plugins": [ 9 | "@typescript-eslint", 10 | "import" 11 | ], 12 | "parser": "@typescript-eslint/parser", 13 | "parserOptions": { 14 | "ecmaVersion": 2018, 15 | "sourceType": "module", 16 | "project": "./tsconfig.dev.json" 17 | }, 18 | "extends": [ 19 | "plugin:import/typescript" 20 | ], 21 | "settings": { 22 | "import/parsers": { 23 | "@typescript-eslint/parser": [ 24 | ".ts", 25 | ".tsx" 26 | ] 27 | }, 28 | "import/resolver": { 29 | "node": {}, 30 | "typescript": { 31 | "project": "./tsconfig.dev.json", 32 | "alwaysTryTypes": true 33 | } 34 | } 35 | }, 36 | "ignorePatterns": [ 37 | "*.js", 38 | "!.projenrc.js", 39 | "*.d.ts", 40 | "node_modules/", 41 | "*.generated.ts", 42 | "coverage" 43 | ], 44 | "rules": { 45 | "indent": [ 46 | "off" 47 | ], 48 | "@typescript-eslint/indent": [ 49 | "error", 50 | 2 51 | ], 52 | "quotes": [ 53 | "error", 54 | "single", 55 | { 56 | "avoidEscape": true 57 | } 58 | ], 59 | "comma-dangle": [ 60 | "error", 61 | "always-multiline" 62 | ], 63 | "comma-spacing": [ 64 | "error", 65 | { 66 | "before": false, 67 | "after": true 68 | } 69 | ], 70 | "no-multi-spaces": [ 71 | "error", 72 | { 73 | "ignoreEOLComments": false 74 | } 75 | ], 76 | "array-bracket-spacing": [ 77 | "error", 78 | "never" 79 | ], 80 | "array-bracket-newline": [ 81 | "error", 82 | "consistent" 83 | ], 84 | "object-curly-spacing": [ 85 | "error", 86 | "always" 87 | ], 88 | "object-curly-newline": [ 89 | "error", 90 | { 91 | "multiline": true, 92 | "consistent": true 93 | } 94 | ], 95 | "object-property-newline": [ 96 | "error", 97 | { 98 | "allowAllPropertiesOnSameLine": true 99 | } 100 | ], 101 | "keyword-spacing": [ 102 | "error" 103 | ], 104 | "brace-style": [ 105 | "error", 106 | "1tbs", 107 | { 108 | "allowSingleLine": true 109 | } 110 | ], 111 | "space-before-blocks": [ 112 | "error" 113 | ], 114 | "curly": [ 115 | "error", 116 | "multi-line", 117 | "consistent" 118 | ], 119 | "@typescript-eslint/member-delimiter-style": [ 120 | "error" 121 | ], 122 | "semi": [ 123 | "error", 124 | "always" 125 | ], 126 | "max-len": [ 127 | "error", 128 | { 129 | "code": 150, 130 | "ignoreUrls": true, 131 | "ignoreStrings": true, 132 | "ignoreTemplateLiterals": true, 133 | "ignoreComments": true, 134 | "ignoreRegExpLiterals": true 135 | } 136 | ], 137 | "quote-props": [ 138 | "error", 139 | "consistent-as-needed" 140 | ], 141 | "@typescript-eslint/no-require-imports": [ 142 | "error" 143 | ], 144 | "import/no-extraneous-dependencies": [ 145 | "error", 146 | { 147 | "devDependencies": [ 148 | "**/test/**", 149 | "**/build-tools/**", 150 | "src/index.lambda.ts" 151 | ], 152 | "optionalDependencies": false, 153 | "peerDependencies": true 154 | } 155 | ], 156 | "import/no-unresolved": [ 157 | "error" 158 | ], 159 | "import/order": [ 160 | "warn", 161 | { 162 | "groups": [ 163 | "builtin", 164 | "external" 165 | ], 166 | "alphabetize": { 167 | "order": "asc", 168 | "caseInsensitive": true 169 | } 170 | } 171 | ], 172 | "no-duplicate-imports": [ 173 | "error" 174 | ], 175 | "no-shadow": [ 176 | "off" 177 | ], 178 | "@typescript-eslint/no-shadow": [ 179 | "error" 180 | ], 181 | "key-spacing": [ 182 | "error" 183 | ], 184 | "no-multiple-empty-lines": [ 185 | "error" 186 | ], 187 | "@typescript-eslint/no-floating-promises": [ 188 | "error" 189 | ], 190 | "no-return-await": [ 191 | "off" 192 | ], 193 | "@typescript-eslint/return-await": [ 194 | "error" 195 | ], 196 | "no-trailing-spaces": [ 197 | "error" 198 | ], 199 | "dot-notation": [ 200 | "error" 201 | ], 202 | "no-bitwise": [ 203 | "error" 204 | ], 205 | "@typescript-eslint/member-ordering": [ 206 | "error", 207 | { 208 | "default": [ 209 | "public-static-field", 210 | "public-static-method", 211 | "protected-static-field", 212 | "protected-static-method", 213 | "private-static-field", 214 | "private-static-method", 215 | "field", 216 | "constructor", 217 | "method" 218 | ] 219 | } 220 | ] 221 | }, 222 | "overrides": [ 223 | { 224 | "files": [ 225 | ".projenrc.js" 226 | ], 227 | "rules": { 228 | "@typescript-eslint/no-require-imports": "off", 229 | "import/no-extraneous-dependencies": "off" 230 | } 231 | } 232 | ] 233 | } 234 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # ~~ Generated by projen. To modify, edit .projenrc.js and run "npx projen". 2 | 3 | *.snap linguist-generated 4 | /.eslintrc.json linguist-generated 5 | /.gitattributes linguist-generated 6 | /.github/dependabot.yml linguist-generated 7 | /.github/pull_request_template.md linguist-generated 8 | /.github/workflows/build.yml linguist-generated 9 | /.github/workflows/release.yml linguist-generated 10 | /.gitignore linguist-generated 11 | /.gitpod.yml linguist-generated 12 | /.mergify.yml linguist-generated 13 | /.npmignore linguist-generated 14 | /.projen/** linguist-generated 15 | /.projen/deps.json linguist-generated 16 | /.projen/files.json linguist-generated 17 | /.projen/tasks.json linguist-generated 18 | /API.md linguist-generated 19 | /LICENSE linguist-generated 20 | /package.json linguist-generated 21 | /src/index-function.ts linguist-generated 22 | /tsconfig.dev.json linguist-generated 23 | /yarn.lock linguist-generated -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # ~~ Generated by projen. To modify, edit .projenrc.js and run "npx projen". 2 | 3 | version: 2 4 | updates: 5 | - package-ecosystem: npm 6 | versioning-strategy: lockfile-only 7 | directory: / 8 | schedule: 9 | interval: daily 10 | ignore: 11 | - dependency-name: projen 12 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | Fixes # -------------------------------------------------------------------------------- /.github/workflows/automerge_dependabot.yml: -------------------------------------------------------------------------------- 1 | name: auto-merge-dependabot 2 | 3 | on: 4 | pull_request: 5 | 6 | jobs: 7 | auto-merge: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v2 11 | - uses: ahmadnassri/action-dependabot-auto-merge@v2 12 | with: 13 | target: minor 14 | github-token: ${{ secrets.DEPENDABOT }} -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | # ~~ Generated by projen. To modify, edit .projenrc.js and run "npx projen". 2 | 3 | name: build 4 | on: 5 | pull_request: {} 6 | push: {} 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | permissions: 11 | contents: write 12 | outputs: 13 | self_mutation_happened: ${{ steps.self_mutation.outputs.self_mutation_happened }} 14 | env: 15 | CI: "true" 16 | steps: 17 | - name: Checkout 18 | uses: actions/checkout@v3 19 | with: 20 | ref: ${{ github.event.pull_request.head.ref }} 21 | repository: ${{ github.event.pull_request.head.repo.full_name }} 22 | - name: Install dependencies 23 | run: yarn install --check-files 24 | - name: build 25 | run: npx projen build 26 | - name: Find mutations 27 | id: self_mutation 28 | run: |- 29 | git add . 30 | git diff --staged --patch --exit-code > .repo.patch || echo "self_mutation_happened=true" >> $GITHUB_OUTPUT 31 | - name: Upload patch 32 | if: steps.self_mutation.outputs.self_mutation_happened 33 | uses: actions/upload-artifact@v3 34 | with: 35 | name: .repo.patch 36 | path: .repo.patch 37 | - name: Fail build on mutation 38 | if: steps.self_mutation.outputs.self_mutation_happened 39 | run: |- 40 | echo "::error::Files were changed during build (see build log). If this was triggered from a fork, you will need to update your branch." 41 | cat .repo.patch 42 | exit 1 43 | - name: Backup artifact permissions 44 | run: cd dist && getfacl -R . > permissions-backup.acl 45 | continue-on-error: true 46 | - name: Upload artifact 47 | uses: actions/upload-artifact@v3 48 | with: 49 | name: build-artifact 50 | path: dist 51 | container: 52 | image: jsii/superchain:1-buster-slim-node14 53 | self-mutation: 54 | needs: build 55 | runs-on: ubuntu-latest 56 | permissions: 57 | contents: write 58 | if: always() && needs.build.outputs.self_mutation_happened && !(github.event.pull_request.head.repo.full_name != github.repository) 59 | steps: 60 | - name: Checkout 61 | uses: actions/checkout@v3 62 | with: 63 | token: ${{ secrets.PROJEN_GITHUB_TOKEN }} 64 | ref: ${{ github.event.pull_request.head.ref }} 65 | repository: ${{ github.event.pull_request.head.repo.full_name }} 66 | - name: Download patch 67 | uses: actions/download-artifact@v3 68 | with: 69 | name: .repo.patch 70 | path: ${{ runner.temp }} 71 | - name: Apply patch 72 | run: '[ -s ${{ runner.temp }}/.repo.patch ] && git apply ${{ runner.temp }}/.repo.patch || echo "Empty patch. Skipping."' 73 | - name: Set git identity 74 | run: |- 75 | git config user.name "github-actions" 76 | git config user.email "github-actions@github.com" 77 | - name: Push changes 78 | run: |2- 79 | git add . 80 | git commit -s -m "chore: self mutation" 81 | git push origin HEAD:${{ github.event.pull_request.head.ref }} 82 | package-js: 83 | needs: build 84 | runs-on: ubuntu-latest 85 | permissions: {} 86 | if: "! needs.build.outputs.self_mutation_happened" 87 | steps: 88 | - uses: actions/setup-node@v3 89 | with: 90 | node-version: 14.x 91 | - name: Download build artifacts 92 | uses: actions/download-artifact@v3 93 | with: 94 | name: build-artifact 95 | path: dist 96 | - name: Restore build artifact permissions 97 | run: cd dist && setfacl --restore=permissions-backup.acl 98 | continue-on-error: true 99 | - name: Prepare Repository 100 | run: mv dist .repo 101 | - name: Install Dependencies 102 | run: cd .repo && yarn install --check-files --frozen-lockfile 103 | - name: Create js artifact 104 | run: cd .repo && npx projen package:js 105 | - name: Collect js Artifact 106 | run: mv .repo/dist dist 107 | package-java: 108 | needs: build 109 | runs-on: ubuntu-latest 110 | permissions: {} 111 | if: "! needs.build.outputs.self_mutation_happened" 112 | steps: 113 | - uses: actions/setup-java@v3 114 | with: 115 | distribution: temurin 116 | java-version: 11.x 117 | - uses: actions/setup-node@v3 118 | with: 119 | node-version: 14.x 120 | - name: Download build artifacts 121 | uses: actions/download-artifact@v3 122 | with: 123 | name: build-artifact 124 | path: dist 125 | - name: Restore build artifact permissions 126 | run: cd dist && setfacl --restore=permissions-backup.acl 127 | continue-on-error: true 128 | - name: Prepare Repository 129 | run: mv dist .repo 130 | - name: Install Dependencies 131 | run: cd .repo && yarn install --check-files --frozen-lockfile 132 | - name: Create java artifact 133 | run: cd .repo && npx projen package:java 134 | - name: Collect java Artifact 135 | run: mv .repo/dist dist 136 | package-python: 137 | needs: build 138 | runs-on: ubuntu-latest 139 | permissions: {} 140 | if: "! needs.build.outputs.self_mutation_happened" 141 | steps: 142 | - uses: actions/setup-node@v3 143 | with: 144 | node-version: 14.x 145 | - uses: actions/setup-python@v4 146 | with: 147 | python-version: 3.x 148 | - name: Download build artifacts 149 | uses: actions/download-artifact@v3 150 | with: 151 | name: build-artifact 152 | path: dist 153 | - name: Restore build artifact permissions 154 | run: cd dist && setfacl --restore=permissions-backup.acl 155 | continue-on-error: true 156 | - name: Prepare Repository 157 | run: mv dist .repo 158 | - name: Install Dependencies 159 | run: cd .repo && yarn install --check-files --frozen-lockfile 160 | - name: Create python artifact 161 | run: cd .repo && npx projen package:python 162 | - name: Collect python Artifact 163 | run: mv .repo/dist dist 164 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | # ~~ Generated by projen. To modify, edit .projenrc.js and run "npx projen". 2 | 3 | name: release 4 | on: 5 | workflow_dispatch: {} 6 | jobs: 7 | release: 8 | runs-on: ubuntu-latest 9 | permissions: 10 | contents: write 11 | outputs: 12 | latest_commit: ${{ steps.git_remote.outputs.latest_commit }} 13 | env: 14 | CI: "true" 15 | steps: 16 | - name: Checkout 17 | uses: actions/checkout@v3 18 | with: 19 | fetch-depth: 0 20 | - name: Set git identity 21 | run: |- 22 | git config user.name "github-actions" 23 | git config user.email "github-actions@github.com" 24 | - name: Install dependencies 25 | run: yarn install --check-files --frozen-lockfile 26 | - name: release 27 | run: npx projen release 28 | - name: Check for new commits 29 | id: git_remote 30 | run: echo "latest_commit=$(git ls-remote origin -h ${{ github.ref }} | cut -f1)" >> $GITHUB_OUTPUT 31 | - name: Backup artifact permissions 32 | if: ${{ steps.git_remote.outputs.latest_commit == github.sha }} 33 | run: cd dist && getfacl -R . > permissions-backup.acl 34 | continue-on-error: true 35 | - name: Upload artifact 36 | if: ${{ steps.git_remote.outputs.latest_commit == github.sha }} 37 | uses: actions/upload-artifact@v3 38 | with: 39 | name: build-artifact 40 | path: dist 41 | container: 42 | image: jsii/superchain:1-buster-slim-node14 43 | release_github: 44 | name: Publish to GitHub Releases 45 | needs: release 46 | runs-on: ubuntu-latest 47 | permissions: 48 | contents: write 49 | if: needs.release.outputs.latest_commit == github.sha 50 | steps: 51 | - uses: actions/setup-node@v3 52 | with: 53 | node-version: 14.x 54 | - name: Download build artifacts 55 | uses: actions/download-artifact@v3 56 | with: 57 | name: build-artifact 58 | path: dist 59 | - name: Restore build artifact permissions 60 | run: cd dist && setfacl --restore=permissions-backup.acl 61 | continue-on-error: true 62 | - name: Prepare Repository 63 | run: mv dist .repo 64 | - name: Collect GitHub Metadata 65 | run: mv .repo/dist dist 66 | - name: Release 67 | env: 68 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 69 | GITHUB_REPOSITORY: ${{ github.repository }} 70 | GITHUB_REF: ${{ github.ref }} 71 | run: errout=$(mktemp); gh release create $(cat dist/releasetag.txt) -R $GITHUB_REPOSITORY -F dist/changelog.md -t $(cat dist/releasetag.txt) --target $GITHUB_REF 2> $errout && true; exitcode=$?; if [ $exitcode -ne 0 ] && ! grep -q "Release.tag_name already exists" $errout; then cat $errout; exit $exitcode; fi 72 | release_npm: 73 | name: Publish to npm 74 | needs: release 75 | runs-on: ubuntu-latest 76 | permissions: 77 | contents: read 78 | if: needs.release.outputs.latest_commit == github.sha 79 | steps: 80 | - uses: actions/setup-node@v3 81 | with: 82 | node-version: 14.x 83 | - name: Download build artifacts 84 | uses: actions/download-artifact@v3 85 | with: 86 | name: build-artifact 87 | path: dist 88 | - name: Restore build artifact permissions 89 | run: cd dist && setfacl --restore=permissions-backup.acl 90 | continue-on-error: true 91 | - name: Prepare Repository 92 | run: mv dist .repo 93 | - name: Install Dependencies 94 | run: cd .repo && yarn install --check-files --frozen-lockfile 95 | - name: Create js artifact 96 | run: cd .repo && npx projen package:js 97 | - name: Collect js Artifact 98 | run: mv .repo/dist dist 99 | - name: Release 100 | env: 101 | NPM_DIST_TAG: latest 102 | NPM_REGISTRY: registry.npmjs.org 103 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 104 | run: npx -p publib@latest publib-npm 105 | release_maven: 106 | name: Publish to Maven Central 107 | needs: release 108 | runs-on: ubuntu-latest 109 | permissions: 110 | contents: read 111 | if: needs.release.outputs.latest_commit == github.sha 112 | steps: 113 | - uses: actions/setup-java@v3 114 | with: 115 | distribution: temurin 116 | java-version: 11.x 117 | - uses: actions/setup-node@v3 118 | with: 119 | node-version: 14.x 120 | - name: Download build artifacts 121 | uses: actions/download-artifact@v3 122 | with: 123 | name: build-artifact 124 | path: dist 125 | - name: Restore build artifact permissions 126 | run: cd dist && setfacl --restore=permissions-backup.acl 127 | continue-on-error: true 128 | - name: Prepare Repository 129 | run: mv dist .repo 130 | - name: Install Dependencies 131 | run: cd .repo && yarn install --check-files --frozen-lockfile 132 | - name: Create java artifact 133 | run: cd .repo && npx projen package:java 134 | - name: Collect java Artifact 135 | run: mv .repo/dist dist 136 | - name: Release 137 | env: 138 | MAVEN_ENDPOINT: https://s01.oss.sonatype.org 139 | MAVEN_GPG_PRIVATE_KEY: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} 140 | MAVEN_GPG_PRIVATE_KEY_PASSPHRASE: ${{ secrets.MAVEN_GPG_PRIVATE_KEY_PASSPHRASE }} 141 | MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }} 142 | MAVEN_USERNAME: ${{ secrets.MAVEN_USERNAME }} 143 | MAVEN_STAGING_PROFILE_ID: ${{ secrets.MAVEN_STAGING_PROFILE_ID }} 144 | run: npx -p publib@latest publib-maven 145 | release_pypi: 146 | name: Publish to PyPI 147 | needs: release 148 | runs-on: ubuntu-latest 149 | permissions: 150 | contents: read 151 | if: needs.release.outputs.latest_commit == github.sha 152 | steps: 153 | - uses: actions/setup-node@v3 154 | with: 155 | node-version: 14.x 156 | - uses: actions/setup-python@v4 157 | with: 158 | python-version: 3.x 159 | - name: Download build artifacts 160 | uses: actions/download-artifact@v3 161 | with: 162 | name: build-artifact 163 | path: dist 164 | - name: Restore build artifact permissions 165 | run: cd dist && setfacl --restore=permissions-backup.acl 166 | continue-on-error: true 167 | - name: Prepare Repository 168 | run: mv dist .repo 169 | - name: Install Dependencies 170 | run: cd .repo && yarn install --check-files --frozen-lockfile 171 | - name: Create python artifact 172 | run: cd .repo && npx projen package:python 173 | - name: Collect python Artifact 174 | run: mv .repo/dist dist 175 | - name: Release 176 | env: 177 | TWINE_USERNAME: ${{ secrets.TWINE_USERNAME }} 178 | TWINE_PASSWORD: ${{ secrets.TWINE_PASSWORD }} 179 | run: npx -p publib@latest publib-pypi 180 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # ~~ Generated by projen. To modify, edit .projenrc.js and run "npx projen". 2 | !/.gitattributes 3 | !/.projen/tasks.json 4 | !/.projen/deps.json 5 | !/.projen/files.json 6 | !/.gitpod.yml 7 | !/package.json 8 | !/LICENSE 9 | !/.npmignore 10 | logs 11 | *.log 12 | npm-debug.log* 13 | yarn-debug.log* 14 | yarn-error.log* 15 | lerna-debug.log* 16 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 17 | pids 18 | *.pid 19 | *.seed 20 | *.pid.lock 21 | lib-cov 22 | coverage 23 | *.lcov 24 | .nyc_output 25 | build/Release 26 | node_modules/ 27 | jspm_packages/ 28 | *.tsbuildinfo 29 | .eslintcache 30 | *.tgz 31 | .yarn-integrity 32 | .cache 33 | !/.projenrc.js 34 | /test-reports/ 35 | junit.xml 36 | /coverage/ 37 | !/.github/workflows/build.yml 38 | /dist/changelog.md 39 | /dist/version.txt 40 | !/.github/workflows/release.yml 41 | !/.mergify.yml 42 | !/.github/dependabot.yml 43 | !/.github/pull_request_template.md 44 | !/test/ 45 | !/tsconfig.dev.json 46 | !/src/ 47 | /lib 48 | /dist/ 49 | !/.eslintrc.json 50 | .jsii 51 | tsconfig.json 52 | !/API.md 53 | /assets/ 54 | !/src/index-function.ts 55 | .DS_Store 56 | cdk.out 57 | -------------------------------------------------------------------------------- /.gitpod.yml: -------------------------------------------------------------------------------- 1 | # ~~ Generated by projen. To modify, edit .projenrc.js and run "npx projen". 2 | 3 | image: jsii/superchain:1-buster-slim-node14 4 | tasks: 5 | - name: ConfigAlias 6 | command: echo 'alias pj="npx projen"' >> ~/.bashrc && echo 'alias cdk="npx cdk"' >> ~/.bashrc 7 | vscode: 8 | extensions: 9 | - dbaeumer.vscode-eslint 10 | - ms-azuretools.vscode-docker 11 | - AmazonWebServices.aws-toolkit-vscode 12 | -------------------------------------------------------------------------------- /.mergify.yml: -------------------------------------------------------------------------------- 1 | # ~~ Generated by projen. To modify, edit .projenrc.js and run "npx projen". 2 | 3 | queue_rules: 4 | - name: default 5 | conditions: 6 | - "#approved-reviews-by>=1" 7 | - -label~=(do-not-merge) 8 | - status-success=build 9 | - status-success=package-js 10 | - status-success=package-java 11 | - status-success=package-python 12 | pull_request_rules: 13 | - name: Automatic merge on approval and successful build 14 | actions: 15 | delete_head_branch: {} 16 | queue: 17 | method: squash 18 | name: default 19 | commit_message_template: |- 20 | {{ title }} (#{{ number }}) 21 | 22 | {{ body }} 23 | conditions: 24 | - "#approved-reviews-by>=1" 25 | - -label~=(do-not-merge) 26 | - status-success=build 27 | - status-success=package-js 28 | - status-success=package-java 29 | - status-success=package-python 30 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | # ~~ Generated by projen. To modify, edit .projenrc.js and run "npx projen". 2 | /.projen/ 3 | /test-reports/ 4 | junit.xml 5 | /coverage/ 6 | permissions-backup.acl 7 | /dist/changelog.md 8 | /dist/version.txt 9 | /.mergify.yml 10 | /test/ 11 | /tsconfig.dev.json 12 | /src/ 13 | !/lib/ 14 | !/lib/**/*.js 15 | !/lib/**/*.d.ts 16 | dist 17 | /tsconfig.json 18 | /.github/ 19 | /.vscode/ 20 | /.idea/ 21 | /.projenrc.js 22 | tsconfig.tsbuildinfo 23 | /.eslintrc.json 24 | !.jsii 25 | !/assets/ 26 | .DS_Store 27 | cdk.out 28 | front 29 | images 30 | -------------------------------------------------------------------------------- /.projen/deps.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": [ 3 | { 4 | "name": "@aws-sdk/client-s3", 5 | "type": "build" 6 | }, 7 | { 8 | "name": "@aws-sdk/s3-request-presigner", 9 | "type": "build" 10 | }, 11 | { 12 | "name": "@jest/globals", 13 | "type": "build" 14 | }, 15 | { 16 | "name": "@types/jest", 17 | "version": "^27", 18 | "type": "build" 19 | }, 20 | { 21 | "name": "@types/node", 22 | "version": "^14", 23 | "type": "build" 24 | }, 25 | { 26 | "name": "@typescript-eslint/eslint-plugin", 27 | "version": "^5", 28 | "type": "build" 29 | }, 30 | { 31 | "name": "@typescript-eslint/parser", 32 | "version": "^5", 33 | "type": "build" 34 | }, 35 | { 36 | "name": "aws-cdk-lib", 37 | "version": "2.54.0", 38 | "type": "build" 39 | }, 40 | { 41 | "name": "constructs", 42 | "version": "10.0.5", 43 | "type": "build" 44 | }, 45 | { 46 | "name": "es-mime-types", 47 | "type": "build" 48 | }, 49 | { 50 | "name": "esbuild", 51 | "type": "build" 52 | }, 53 | { 54 | "name": "eslint-import-resolver-node", 55 | "type": "build" 56 | }, 57 | { 58 | "name": "eslint-import-resolver-typescript", 59 | "type": "build" 60 | }, 61 | { 62 | "name": "eslint-plugin-import", 63 | "type": "build" 64 | }, 65 | { 66 | "name": "eslint", 67 | "version": "^8", 68 | "type": "build" 69 | }, 70 | { 71 | "name": "jest-junit", 72 | "version": "^13", 73 | "type": "build" 74 | }, 75 | { 76 | "name": "jest", 77 | "version": "^27", 78 | "type": "build" 79 | }, 80 | { 81 | "name": "jsii", 82 | "type": "build" 83 | }, 84 | { 85 | "name": "jsii-diff", 86 | "type": "build" 87 | }, 88 | { 89 | "name": "jsii-docgen", 90 | "type": "build" 91 | }, 92 | { 93 | "name": "jsii-pacmak", 94 | "type": "build" 95 | }, 96 | { 97 | "name": "json-schema", 98 | "type": "build" 99 | }, 100 | { 101 | "name": "projen", 102 | "type": "build" 103 | }, 104 | { 105 | "name": "standard-version", 106 | "version": "^9", 107 | "type": "build" 108 | }, 109 | { 110 | "name": "ts-jest", 111 | "version": "^27", 112 | "type": "build" 113 | }, 114 | { 115 | "name": "ts-node", 116 | "type": "build" 117 | }, 118 | { 119 | "name": "typescript", 120 | "type": "build" 121 | }, 122 | { 123 | "name": "@types/babel__traverse", 124 | "version": "7.18.2", 125 | "type": "override" 126 | }, 127 | { 128 | "name": "@types/prettier", 129 | "version": "2.6.0", 130 | "type": "override" 131 | }, 132 | { 133 | "name": "aws-cdk-lib", 134 | "version": "^2.54.0", 135 | "type": "peer" 136 | }, 137 | { 138 | "name": "constructs", 139 | "version": "^10.0.5", 140 | "type": "peer" 141 | } 142 | ], 143 | "//": "~~ Generated by projen. To modify, edit .projenrc.js and run \"npx projen\"." 144 | } 145 | -------------------------------------------------------------------------------- /.projen/files.json: -------------------------------------------------------------------------------- 1 | { 2 | "files": [ 3 | ".eslintrc.json", 4 | ".gitattributes", 5 | ".github/dependabot.yml", 6 | ".github/pull_request_template.md", 7 | ".github/workflows/build.yml", 8 | ".github/workflows/release.yml", 9 | ".gitignore", 10 | ".gitpod.yml", 11 | ".mergify.yml", 12 | ".projen/deps.json", 13 | ".projen/files.json", 14 | ".projen/tasks.json", 15 | "LICENSE", 16 | "src/index-function.ts", 17 | "tsconfig.dev.json" 18 | ], 19 | "//": "~~ Generated by projen. To modify, edit .projenrc.js and run \"npx projen\"." 20 | } 21 | -------------------------------------------------------------------------------- /.projen/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "tasks": { 3 | "build": { 4 | "name": "build", 5 | "description": "Full release build", 6 | "steps": [ 7 | { 8 | "spawn": "default" 9 | }, 10 | { 11 | "spawn": "pre-compile" 12 | }, 13 | { 14 | "spawn": "compile" 15 | }, 16 | { 17 | "spawn": "post-compile" 18 | }, 19 | { 20 | "spawn": "test" 21 | }, 22 | { 23 | "spawn": "package" 24 | } 25 | ] 26 | }, 27 | "bump": { 28 | "name": "bump", 29 | "description": "Bumps version based on latest git tag and generates a changelog entry", 30 | "env": { 31 | "OUTFILE": "package.json", 32 | "CHANGELOG": "dist/changelog.md", 33 | "BUMPFILE": "dist/version.txt", 34 | "RELEASETAG": "dist/releasetag.txt", 35 | "RELEASE_TAG_PREFIX": "" 36 | }, 37 | "steps": [ 38 | { 39 | "builtin": "release/bump-version" 40 | } 41 | ], 42 | "condition": "! git log --oneline -1 | grep -q \"chore(release):\"" 43 | }, 44 | "bundle": { 45 | "name": "bundle", 46 | "description": "Prepare assets", 47 | "steps": [ 48 | { 49 | "spawn": "bundle:index.lambda" 50 | } 51 | ] 52 | }, 53 | "bundle:index.lambda": { 54 | "name": "bundle:index.lambda", 55 | "description": "Create a JavaScript bundle from src/index.lambda.ts", 56 | "steps": [ 57 | { 58 | "exec": "esbuild --bundle src/index.lambda.ts --target=\"node18\" --platform=\"node\" --outfile=\"assets/index.lambda/index.js\" --tsconfig=\"tsconfig.dev.json\" --external:aws-sdk" 59 | } 60 | ] 61 | }, 62 | "bundle:index.lambda:watch": { 63 | "name": "bundle:index.lambda:watch", 64 | "description": "Continuously update the JavaScript bundle from src/index.lambda.ts", 65 | "steps": [ 66 | { 67 | "exec": "esbuild --bundle src/index.lambda.ts --target=\"node18\" --platform=\"node\" --outfile=\"assets/index.lambda/index.js\" --tsconfig=\"tsconfig.dev.json\" --external:aws-sdk --watch" 68 | } 69 | ] 70 | }, 71 | "clobber": { 72 | "name": "clobber", 73 | "description": "hard resets to HEAD of origin and cleans the local repo", 74 | "env": { 75 | "BRANCH": "$(git branch --show-current)" 76 | }, 77 | "steps": [ 78 | { 79 | "exec": "git checkout -b scratch", 80 | "name": "save current HEAD in \"scratch\" branch" 81 | }, 82 | { 83 | "exec": "git checkout $BRANCH" 84 | }, 85 | { 86 | "exec": "git fetch origin", 87 | "name": "fetch latest changes from origin" 88 | }, 89 | { 90 | "exec": "git reset --hard origin/$BRANCH", 91 | "name": "hard reset to origin commit" 92 | }, 93 | { 94 | "exec": "git clean -fdx", 95 | "name": "clean all untracked files" 96 | }, 97 | { 98 | "say": "ready to rock! (unpushed commits are under the \"scratch\" branch)" 99 | } 100 | ], 101 | "condition": "git diff --exit-code > /dev/null" 102 | }, 103 | "compat": { 104 | "name": "compat", 105 | "description": "Perform API compatibility check against latest version", 106 | "steps": [ 107 | { 108 | "exec": "jsii-diff npm:$(node -p \"require('./package.json').name\") -k --ignore-file .compatignore || (echo \"\nUNEXPECTED BREAKING CHANGES: add keys such as 'removed:constructs.Node.of' to .compatignore to skip.\n\" && exit 1)" 109 | } 110 | ] 111 | }, 112 | "compile": { 113 | "name": "compile", 114 | "description": "Only compile", 115 | "steps": [ 116 | { 117 | "exec": "jsii --silence-warnings=reserved-word" 118 | } 119 | ] 120 | }, 121 | "default": { 122 | "name": "default", 123 | "description": "Synthesize project files", 124 | "steps": [ 125 | { 126 | "exec": "node .projenrc.js" 127 | } 128 | ] 129 | }, 130 | "docgen": { 131 | "name": "docgen", 132 | "description": "Generate API.md from .jsii manifest", 133 | "steps": [ 134 | { 135 | "exec": "jsii-docgen -o API.md" 136 | } 137 | ] 138 | }, 139 | "eject": { 140 | "name": "eject", 141 | "description": "Remove projen from the project", 142 | "env": { 143 | "PROJEN_EJECTING": "true" 144 | }, 145 | "steps": [ 146 | { 147 | "spawn": "default" 148 | } 149 | ] 150 | }, 151 | "eslint": { 152 | "name": "eslint", 153 | "description": "Runs eslint against the codebase", 154 | "steps": [ 155 | { 156 | "exec": "eslint --ext .ts,.tsx --fix --no-error-on-unmatched-pattern src test build-tools .projenrc.js" 157 | } 158 | ] 159 | }, 160 | "package": { 161 | "name": "package", 162 | "description": "Creates the distribution package", 163 | "steps": [ 164 | { 165 | "exec": "if [ ! -z ${CI} ]; then rsync -a . .repo --exclude .git --exclude node_modules && rm -rf dist && mv .repo dist; else npx projen package-all; fi" 166 | } 167 | ] 168 | }, 169 | "package-all": { 170 | "name": "package-all", 171 | "description": "Packages artifacts for all target languages", 172 | "steps": [ 173 | { 174 | "spawn": "package:js" 175 | }, 176 | { 177 | "spawn": "package:java" 178 | }, 179 | { 180 | "spawn": "package:python" 181 | } 182 | ] 183 | }, 184 | "package:java": { 185 | "name": "package:java", 186 | "description": "Create java language bindings", 187 | "steps": [ 188 | { 189 | "exec": "jsii-pacmak -v --target java" 190 | } 191 | ] 192 | }, 193 | "package:js": { 194 | "name": "package:js", 195 | "description": "Create js language bindings", 196 | "steps": [ 197 | { 198 | "exec": "jsii-pacmak -v --target js" 199 | } 200 | ] 201 | }, 202 | "package:python": { 203 | "name": "package:python", 204 | "description": "Create python language bindings", 205 | "steps": [ 206 | { 207 | "exec": "jsii-pacmak -v --target python" 208 | } 209 | ] 210 | }, 211 | "post-compile": { 212 | "name": "post-compile", 213 | "description": "Runs after successful compilation", 214 | "steps": [ 215 | { 216 | "spawn": "docgen" 217 | } 218 | ] 219 | }, 220 | "pre-compile": { 221 | "name": "pre-compile", 222 | "description": "Prepare the project for compilation", 223 | "steps": [ 224 | { 225 | "spawn": "bundle" 226 | } 227 | ] 228 | }, 229 | "release": { 230 | "name": "release", 231 | "description": "Prepare a release from \"main\" branch", 232 | "env": { 233 | "RELEASE": "true" 234 | }, 235 | "steps": [ 236 | { 237 | "exec": "rm -fr dist" 238 | }, 239 | { 240 | "spawn": "bump" 241 | }, 242 | { 243 | "spawn": "build" 244 | }, 245 | { 246 | "spawn": "unbump" 247 | }, 248 | { 249 | "exec": "git diff --ignore-space-at-eol --exit-code" 250 | } 251 | ] 252 | }, 253 | "test": { 254 | "name": "test", 255 | "description": "Run tests", 256 | "steps": [ 257 | { 258 | "exec": "jest --passWithNoTests --updateSnapshot", 259 | "receiveArgs": true 260 | }, 261 | { 262 | "spawn": "eslint" 263 | } 264 | ] 265 | }, 266 | "test:watch": { 267 | "name": "test:watch", 268 | "description": "Run jest in watch mode", 269 | "steps": [ 270 | { 271 | "exec": "jest --watch" 272 | } 273 | ] 274 | }, 275 | "unbump": { 276 | "name": "unbump", 277 | "description": "Restores version to 0.0.0", 278 | "env": { 279 | "OUTFILE": "package.json", 280 | "CHANGELOG": "dist/changelog.md", 281 | "BUMPFILE": "dist/version.txt", 282 | "RELEASETAG": "dist/releasetag.txt", 283 | "RELEASE_TAG_PREFIX": "" 284 | }, 285 | "steps": [ 286 | { 287 | "builtin": "release/reset-version" 288 | } 289 | ] 290 | }, 291 | "watch": { 292 | "name": "watch", 293 | "description": "Watch & compile in the background", 294 | "steps": [ 295 | { 296 | "exec": "jsii -w --silence-warnings=reserved-word" 297 | } 298 | ] 299 | } 300 | }, 301 | "env": { 302 | "PATH": "$(npx -c \"node -e \\\"console.log(process.env.PATH)\\\"\")" 303 | }, 304 | "//": "~~ Generated by projen. To modify, edit .projenrc.js and run \"npx projen\"." 305 | } 306 | -------------------------------------------------------------------------------- /.projenrc.js: -------------------------------------------------------------------------------- 1 | const { awscdk } = require('projen'); 2 | const { ReleaseTrigger } = require('projen/lib/release'); 3 | 4 | const PROJECT_NAME = 'cdk-s3-upload-presignedurl-api'; 5 | const PYTHON_MODULE_NAME = 'cdk_s3_upload_presignedurl_api'; 6 | 7 | const project = new awscdk.AwsCdkConstructLibrary({ 8 | author: 'Jerome Van Der Linden', 9 | authorAddress: 'jeromevdl@gmail.com', 10 | cdkVersion: '2.54.0', 11 | defaultReleaseBranch: 'main', 12 | name: PROJECT_NAME, 13 | packageName: PROJECT_NAME, 14 | description: 'API to get an S3 presigned url for file uploads', 15 | keywords: ['aws', 'cdk', 's3', 'upload', 'presigned', 'api gateway'], 16 | repositoryUrl: `https://github.com/jeromevdl/${PROJECT_NAME}.git`, 17 | 18 | licensed: true, 19 | license: 'Apache-2.0', 20 | gitpod: true, 21 | docgen: true, 22 | docgenFilePath: 'API.md', 23 | dependabot: true, 24 | eslint: true, 25 | mergify: true, 26 | 27 | githubOptions: { 28 | pullRequestLint: false, 29 | }, 30 | 31 | // Build Trigger 32 | buildWorkflow: true, 33 | buildWorkflowTriggers: { pullRequest: {}, push: {} }, 34 | 35 | // Publish to Npm 36 | releaseToNpm: true, 37 | packageName: PROJECT_NAME, 38 | 39 | // Publish to Pypi 40 | publishToPypi: { 41 | distName: PROJECT_NAME, 42 | module: PYTHON_MODULE_NAME, 43 | }, 44 | 45 | // Publish to Maven Central 46 | publishToMaven: { 47 | javaPackage: 'io.github.jeromevdl.awscdk.s3uploadpresignedurlapi', 48 | mavenGroupId: 'io.github.jeromevdl.awscdk', 49 | mavenArtifactId: 's3-upload-presignedurl-api', 50 | mavenEndpoint: 'https://s01.oss.sonatype.org', 51 | }, 52 | 53 | // Release Trigger 54 | release: true, 55 | releaseEveryCommit: false, 56 | releaseTrigger: ReleaseTrigger.manual, 57 | defaultReleaseBranch: 'main', 58 | releaseWorkflow: true, 59 | 60 | lambdaOptions: { 61 | runtime: awscdk.LambdaRuntime.NODEJS_18_X, 62 | }, 63 | 64 | devDeps: [ 65 | 'ts-node', 66 | '@jest/globals', 67 | 'es-mime-types', 68 | 'esbuild', 69 | '@aws-sdk/s3-request-presigner', 70 | '@aws-sdk/client-s3', 71 | ], 72 | 73 | tsconfig: { 74 | compilerOptions: { 75 | lib: ['es2020', 'dom'], 76 | }, 77 | }, 78 | }); 79 | 80 | project.gitpod.addDockerImage({ 81 | image: 'jsii/superchain:1-buster-slim-node14', 82 | }); 83 | 84 | project.gitpod.addCustomTask({ 85 | name: 'ConfigAlias', 86 | command: 'echo \'alias pj="npx projen"\' >> ~/.bashrc && echo \'alias cdk="npx cdk"\' >> ~/.bashrc', 87 | }); 88 | 89 | project.gitpod.addVscodeExtensions( 90 | 'dbaeumer.vscode-eslint', 91 | 'ms-azuretools.vscode-docker', 92 | 'AmazonWebServices.aws-toolkit-vscode', 93 | ); 94 | 95 | const common_exclude = ['.DS_Store', 'cdk.out']; 96 | 97 | project.npmignore.exclude(...common_exclude, 'front', 'images'); 98 | project.gitignore.exclude(...common_exclude); 99 | 100 | project.synth(); -------------------------------------------------------------------------------- /API.md: -------------------------------------------------------------------------------- 1 | # API Reference 2 | 3 | ## Constructs 4 | 5 | ### S3UploadPresignedUrlApi 6 | 7 | #### Initializers 8 | 9 | ```typescript 10 | import { S3UploadPresignedUrlApi } from 'cdk-s3-upload-presignedurl-api' 11 | 12 | new S3UploadPresignedUrlApi(scope: Construct, id: string, props?: IS3UploadSignedUrlApiProps) 13 | ``` 14 | 15 | | **Name** | **Type** | **Description** | 16 | | --- | --- | --- | 17 | | scope | constructs.Construct | *No description.* | 18 | | id | string | *No description.* | 19 | | props | IS3UploadSignedUrlApiProps | *No description.* | 20 | 21 | --- 22 | 23 | ##### `scope`Required 24 | 25 | - *Type:* constructs.Construct 26 | 27 | --- 28 | 29 | ##### `id`Required 30 | 31 | - *Type:* string 32 | 33 | --- 34 | 35 | ##### `props`Optional 36 | 37 | - *Type:* IS3UploadSignedUrlApiProps 38 | 39 | --- 40 | 41 | #### Methods 42 | 43 | | **Name** | **Description** | 44 | | --- | --- | 45 | | toString | Returns a string representation of this construct. | 46 | 47 | --- 48 | 49 | ##### `toString` 50 | 51 | ```typescript 52 | public toString(): string 53 | ``` 54 | 55 | Returns a string representation of this construct. 56 | 57 | #### Static Functions 58 | 59 | | **Name** | **Description** | 60 | | --- | --- | 61 | | isConstruct | Checks if `x` is a construct. | 62 | 63 | --- 64 | 65 | ##### ~~`isConstruct`~~ 66 | 67 | ```typescript 68 | import { S3UploadPresignedUrlApi } from 'cdk-s3-upload-presignedurl-api' 69 | 70 | S3UploadPresignedUrlApi.isConstruct(x: any) 71 | ``` 72 | 73 | Checks if `x` is a construct. 74 | 75 | ###### `x`Required 76 | 77 | - *Type:* any 78 | 79 | Any object. 80 | 81 | --- 82 | 83 | #### Properties 84 | 85 | | **Name** | **Type** | **Description** | 86 | | --- | --- | --- | 87 | | node | constructs.Node | The tree node. | 88 | | bucket | aws-cdk-lib.aws_s3.Bucket | *No description.* | 89 | | restApi | aws-cdk-lib.aws_apigateway.RestApi | *No description.* | 90 | | userPool | any | *No description.* | 91 | | userPoolClient | any | *No description.* | 92 | 93 | --- 94 | 95 | ##### `node`Required 96 | 97 | ```typescript 98 | public readonly node: Node; 99 | ``` 100 | 101 | - *Type:* constructs.Node 102 | 103 | The tree node. 104 | 105 | --- 106 | 107 | ##### `bucket`Required 108 | 109 | ```typescript 110 | public readonly bucket: Bucket; 111 | ``` 112 | 113 | - *Type:* aws-cdk-lib.aws_s3.Bucket 114 | 115 | --- 116 | 117 | ##### `restApi`Required 118 | 119 | ```typescript 120 | public readonly restApi: RestApi; 121 | ``` 122 | 123 | - *Type:* aws-cdk-lib.aws_apigateway.RestApi 124 | 125 | --- 126 | 127 | ##### `userPool`Optional 128 | 129 | ```typescript 130 | public readonly userPool: any; 131 | ``` 132 | 133 | - *Type:* any 134 | 135 | --- 136 | 137 | ##### `userPoolClient`Optional 138 | 139 | ```typescript 140 | public readonly userPoolClient: any; 141 | ``` 142 | 143 | - *Type:* any 144 | 145 | --- 146 | 147 | 148 | 149 | 150 | ## Protocols 151 | 152 | ### IS3UploadSignedUrlApiProps 153 | 154 | - *Implemented By:* IS3UploadSignedUrlApiProps 155 | 156 | 157 | #### Properties 158 | 159 | | **Name** | **Type** | **Description** | 160 | | --- | --- | --- | 161 | | allowedOrigins | string[] | Optional CORS allowedOrigins. | 162 | | apiGatewayProps | any | Optional user provided props to override the default props for the API Gateway. | 163 | | existingBucketObj | aws-cdk-lib.aws_s3.Bucket | Optional bucket where files should be uploaded to. | 164 | | existingUserPoolObj | aws-cdk-lib.aws_cognito.UserPool | Optional Cognito User Pool to secure the API. | 165 | | expiration | number | Optional expiration time in second. | 166 | | logRetention | aws-cdk-lib.aws_logs.RetentionDays | Optional log retention time for Lambda and API Gateway. | 167 | | secured | boolean | Optional boolean to specify if the API is secured (with Cognito) or publicly open. | 168 | 169 | --- 170 | 171 | ##### `allowedOrigins`Optional 172 | 173 | ```typescript 174 | public readonly allowedOrigins: string[]; 175 | ``` 176 | 177 | - *Type:* string[] 178 | - *Default:* ['*'] 179 | 180 | Optional CORS allowedOrigins. 181 | 182 | Should allow your domain(s) as allowed origin to request the API 183 | 184 | --- 185 | 186 | ##### `apiGatewayProps`Optional 187 | 188 | ```typescript 189 | public readonly apiGatewayProps: any; 190 | ``` 191 | 192 | - *Type:* any 193 | - *Default:* Default props are used 194 | 195 | Optional user provided props to override the default props for the API Gateway. 196 | 197 | --- 198 | 199 | ##### `existingBucketObj`Optional 200 | 201 | ```typescript 202 | public readonly existingBucketObj: Bucket; 203 | ``` 204 | 205 | - *Type:* aws-cdk-lib.aws_s3.Bucket 206 | - *Default:* Default Bucket is created 207 | 208 | Optional bucket where files should be uploaded to. 209 | 210 | Should contains the CORS properties 211 | 212 | --- 213 | 214 | ##### `existingUserPoolObj`Optional 215 | 216 | ```typescript 217 | public readonly existingUserPoolObj: UserPool; 218 | ``` 219 | 220 | - *Type:* aws-cdk-lib.aws_cognito.UserPool 221 | - *Default:* Default User Pool (and User Pool Client) are created 222 | 223 | Optional Cognito User Pool to secure the API. 224 | 225 | You should have created a User Pool Client too. 226 | 227 | --- 228 | 229 | ##### `expiration`Optional 230 | 231 | ```typescript 232 | public readonly expiration: number; 233 | ``` 234 | 235 | - *Type:* number 236 | - *Default:* 300 237 | 238 | Optional expiration time in second. 239 | 240 | Time before the presigned url expires. 241 | 242 | --- 243 | 244 | ##### `logRetention`Optional 245 | 246 | ```typescript 247 | public readonly logRetention: RetentionDays; 248 | ``` 249 | 250 | - *Type:* aws-cdk-lib.aws_logs.RetentionDays 251 | - *Default:* one week 252 | 253 | Optional log retention time for Lambda and API Gateway. 254 | 255 | --- 256 | 257 | ##### `secured`Optional 258 | 259 | ```typescript 260 | public readonly secured: boolean; 261 | ``` 262 | 263 | - *Type:* boolean 264 | - *Default:* true 265 | 266 | Optional boolean to specify if the API is secured (with Cognito) or publicly open. 267 | 268 | --- 269 | 270 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cdk-s3-upload-presignedurl-api 2 | 3 | ![npmjs](https://img.shields.io/npm/v/cdk-s3-upload-presignedurl-api?color=red) ![PyPI](https://img.shields.io/pypi/v/cdk-s3-upload-presignedurl-api?color=yellow) ![Maven Central](https://img.shields.io/maven-central/v/io.github.jeromevdl.awscdk/s3-upload-presignedurl-api?color=blue) 4 | 5 | cdk-s3-upload-presignedurl-api is AWS CDK construct library that create an API to get a presigned url to upload a file in S3. 6 | 7 | ## Background 8 | 9 | In web and mobile applications, it's common to provide the ability to upload data (documents, images, ...). Uploading files on a web server can be challenging and AWS recommends to upload files directly to S3. To do that securely, you can use [pre-signed URLs](https://docs.aws.amazon.com/AmazonS3/latest/userguide/PresignedUrlUploadObject.html). This [blog post](https://aws.amazon.com/blogs/compute/uploading-to-amazon-s3-directly-from-a-web-or-mobile-application/) provides some more details. 10 | 11 | ## Architecture 12 | 13 | ![Architecture](images/architecture.png) 14 | 15 | 1. The client makes a call to the API, specifying the "contentType" of the file to upload in request parameters (eg. `?contentType=image/png` in the URL) 16 | 2. API Gateway handles the request and execute the Lambda function. 17 | 3. The Lambda function makes a call to the [`getSignedUrl`](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html) api for a `putObject` operation. 18 | 4. The Lambda function returns the generated URL and the key of the object in S3 to API Gateway. 19 | 5. The API returns the generated URL and the key of the object in S3 to the client. 20 | 6. The client can now use this URL to upload a file, directly to S3. 21 | 22 | 23 | ## Getting Started 24 | 25 | ### TypeScript 26 | 27 | #### Installation 28 | 29 | ```sh 30 | $ npm install --save cdk-s3-upload-presignedurl-api 31 | ``` 32 | 33 | #### Usage 34 | 35 | ```ts 36 | import * as cdk from '@aws-cdk/core'; 37 | import { S3UploadPresignedUrlApi } from 'cdk-s3-upload-presignedurl-api'; 38 | 39 | const app = new cdk.App(); 40 | const stack = new cdk.Stack(app, ''); 41 | 42 | new S3UploadPresignedUrlApi(stack, 'S3UploadSignedUrl'); 43 | ``` 44 | 45 | ### Python 46 | 47 | #### Installation 48 | 49 | ```sh 50 | $ pip install cdk-s3-upload-presignedurl-api 51 | ``` 52 | 53 | #### Usage 54 | 55 | ```py 56 | import aws_cdk as cdk 57 | from cdk_s3_upload_presignedurl_api import S3UploadPresignedUrlApi 58 | 59 | app = cdk.App() 60 | stack = cdk.Stack(app, "") 61 | 62 | S3UploadPresignedUrlApi(stack, 'S3UploadSignedUrl') 63 | ``` 64 | 65 | ### Java 66 | 67 | #### Maven configuration 68 | 69 | ```xml 70 | 71 | io.github.jeromevdl.awscdk 72 | s3-upload-presignedurl-api 73 | ... 74 | 75 | ``` 76 | 77 | #### Usage 78 | 79 | ```java 80 | import software.amazon.awscdk.App; 81 | import software.amazon.awscdk.Stack; 82 | import io.github.jeromevdl.awscdk.s3uploadpresignedurlapi.S3UploadPresignedUrlApi; 83 | 84 | App app = new App(); 85 | Stack stack = new Stack(app, ""); 86 | 87 | new S3UploadPresignedUrlApi(stack, "S3UploadSignedUrl"); 88 | ``` 89 | 90 | ## Configuration 91 | 92 | By default and without any property, the `S3UploadPresignedUrlApi` construct will create: 93 | - The S3 Bucket, with the appropriate CORS configuration 94 | - The Lambda function, that will genereate the pre-signed URL 95 | - The REST API, that will expose the Lambda function to the client 96 | - The Cognito User Pool and User Pool Client to secure the API 97 | 98 | You can shoose to let the construct do everything or you can reuse existing resources: 99 | - An S3 Bucket (`existingBucketObj`). Be carefull to configure CORS properly ([doc](https://docs.aws.amazon.com/AmazonS3/latest/userguide/cors.html)) 100 | - A Cognito User Pool (`existingUserPoolObj`). 101 | 102 | You can also customize the construct: 103 | - You can define the properties for the REST API (`apiGatewayProps`). Note that you cannot reuse an existing API. 104 | - You can configure the allowed origins (`allowedOrigins`) when configuring CORS. Default is *. 105 | - You can configure the expiration of the generated URLs, in seconds (`expiration`). 106 | - You can choose to let the API open, and remove Cognito, by setting `secured` to false. 107 | - You can choose the log retention period (`logRetention`) for Lambda and API Gateway. 108 | 109 | See [API reference](https://github.com/jeromevdl/cdk-s3-upload-presignedurl-api/blob/main/API.md#is3uploadsignedurlapiprops-) for the details. 110 | 111 | ## Client-side usage 112 | 113 | **_Hint_**: A complete example (ReactJS / Amplify) if provided in the GitHub repository ([frontend](https://github.com/jeromevdl/cdk-s3-upload-presignedurl-api/tree/main/frontend) folder). 114 | 115 | Once the components are deployed, you will need to query the API from the client. In order to do so, you need to retrieve the outputs of the CloudFormation Stack: 116 | - The API Endpoint (eg. `https://12345abcd.execute-api.eu-west-1.amazonaws.com/prod/`) 117 | - The User Pool Id (eg. `eu-west-1_2b4C6E8g`) 118 | - The User Pool Client Id (eg. `g5465n67cvfc7n6jn54768`) 119 | 120 | ### Create a user in Cognito User Pool 121 | If you let the Construct configuration by default (`secured = true` and no reuse of pre-existing User Pool), you will have to create users in the User Pool. See the [documentation](https://docs.aws.amazon.com/cognito/latest/developerguide/how-to-create-user-accounts.html). Note that the user pool allows self-registration of users. 122 | 123 | ### Client connection to Cognito User Pool 124 | To authenticate the users on your client, you can use the [`amazon-cognito-identity-js`](https://www.npmjs.com/package/amazon-cognito-identity-js) library or [Amplify](https://docs.amplify.aws/lib/auth/getting-started/q/platform/js/) which is much simpler to setup. 125 | 126 | ### Calling the API 127 | - HTTP Method: `GET` 128 | - URL: https://12345abcd.execute-api.eu-west-1.amazonaws.com/prod/ (replace with yours) 129 | - Query Parameters: `contentType` (a valid MIME Type, eg. `image/png` or `application/pdf`) 130 | - Headers: `Authorization` header must contain the JWT Token retrieve from Cognito 131 | - Ex with Amplify: `Auth.currentSession()).getIdToken().getJwtToken()` 132 | 133 | Ex with curl: 134 | ```bash 135 | curl "https://ab12cd34.execute-api.eu-west-1.amazonaws.com/prod/?contentType=image/png" -H "Authorization: eyJraW...AZjp4gQA" 136 | ``` 137 | 138 | The API will return a JSON containing the `uploadURL` and the `key` of the S3 object: 139 | ```json 140 | {"uploadURL":"https://yourbucknetname.s3.eu-west-1.amazonaws.com/0454dfa5-8ca5-448a-ae30-9b734313362a.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential=SADJKLJKJDF3%24NFDSFDFeu-west-1%2Fs3%2Faws4_request&X-Amz-Date=20221218T095711Z&X-Amz-Expires=300&X-Amz-Security-Token=1234cdef&X-Amz-Signature=13579abcde&X-Amz-SignedHeaders=host&x-id=PutObject","key":"0454dfa5-8ca5-448a-ae30-9b734313362a.png"} 141 | ``` 142 | 143 | ### Upload the file 144 | You can finally use the `uploadURL` and the `PUT` HTTP method to upload your file to S3. You need to specify the exact same content type in the headers. 145 | 146 | Ex with curl: 147 | ```bash 148 | curl "https://yourbucknetname.s3.eu-west-1.amazonaws.com/0454dfa5-8ca5-448a-ae30-9b734313362a.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential=SADJKLJKJDF3%24NFDSFDFeu-west-1%2Fs3%2Faws4_request&X-Amz-Date=20221218T095711Z&X-Amz-Expires=300&X-Amz-Security-Token=1234cdef&X-Amz-Signature=13579abcde&X-Amz-SignedHeaders=host&x-id=PutObject" --upload-file "path/to/my/file.png" -H "Content-Type: image/png" 149 | ``` 150 | -------------------------------------------------------------------------------- /cdk.json: -------------------------------------------------------------------------------- 1 | { 2 | "app": "npx ts-node --prefer-ts-exts src/integ.default.ts", 3 | "watch": { 4 | "include": [ 5 | "**" 6 | ], 7 | "exclude": [ 8 | "README.md", 9 | "cdk*.json", 10 | "**/*.d.ts", 11 | "**/*.js", 12 | "tsconfig.json", 13 | "package*.json", 14 | "yarn.lock", 15 | "node_modules", 16 | "test" 17 | ] 18 | }, 19 | "context": { 20 | "@aws-cdk/aws-lambda:recognizeLayerVersion": true, 21 | "@aws-cdk/core:checkSecretUsage": true, 22 | "@aws-cdk/core:target-partitions": [ 23 | "aws", 24 | "aws-cn" 25 | ], 26 | "@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true, 27 | "@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true, 28 | "@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true, 29 | "@aws-cdk/aws-iam:minimizePolicies": true, 30 | "@aws-cdk/core:validateSnapshotRemovalPolicy": true, 31 | "@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true, 32 | "@aws-cdk/aws-s3:createDefaultLoggingPolicy": true, 33 | "@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true, 34 | "@aws-cdk/aws-apigateway:disableCloudWatchRole": true, 35 | "@aws-cdk/core:enablePartitionLiterals": true, 36 | "@aws-cdk/aws-events:eventsTargetQueueSameAccount": true, 37 | "@aws-cdk/aws-iam:standardizedServicePrincipals": true, 38 | "@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /frontend/README.md: -------------------------------------------------------------------------------- 1 | # Getting Started with Create React App 2 | 3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 4 | 5 | ## Available Scripts 6 | 7 | In the project directory, you can run: 8 | 9 | ### `npm start` 10 | 11 | Runs the app in the development mode.\ 12 | Open [http://localhost:3000](http://localhost:3000) to view it in your browser. 13 | 14 | The page will reload when you make changes.\ 15 | You may also see any lint errors in the console. 16 | 17 | ### `npm test` 18 | 19 | Launches the test runner in the interactive watch mode.\ 20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 21 | 22 | ### `npm run build` 23 | 24 | Builds the app for production to the `build` folder.\ 25 | It correctly bundles React in production mode and optimizes the build for the best performance. 26 | 27 | The build is minified and the filenames include the hashes.\ 28 | Your app is ready to be deployed! 29 | 30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 31 | 32 | ### `npm run eject` 33 | 34 | **Note: this is a one-way operation. Once you `eject`, you can't go back!** 35 | 36 | If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 37 | 38 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own. 39 | 40 | You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it. 41 | 42 | ## Learn More 43 | 44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 45 | 46 | To learn React, check out the [React documentation](https://reactjs.org/). 47 | 48 | ### Code Splitting 49 | 50 | This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) 51 | 52 | ### Analyzing the Bundle Size 53 | 54 | This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) 55 | 56 | ### Making a Progressive Web App 57 | 58 | This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) 59 | 60 | ### Advanced Configuration 61 | 62 | This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) 63 | 64 | ### Deployment 65 | 66 | This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) 67 | 68 | ### `npm run build` fails to minify 69 | 70 | This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) 71 | -------------------------------------------------------------------------------- /frontend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "frontend", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@aws-amplify/ui-react": "^4.2.0", 7 | "@testing-library/jest-dom": "^5.16.5", 8 | "@testing-library/react": "^13.4.0", 9 | "@testing-library/user-event": "^13.5.0", 10 | "aws-amplify": "^5.0.5", 11 | "react": "^18.2.0", 12 | "react-dom": "^18.2.0", 13 | "react-dropzone": "^14.2.3", 14 | "react-scripts": "5.0.1", 15 | "web-vitals": "^2.1.4" 16 | }, 17 | "scripts": { 18 | "start": "react-scripts start", 19 | "build": "react-scripts build", 20 | "test": "react-scripts test", 21 | "eject": "react-scripts eject" 22 | }, 23 | "eslintConfig": { 24 | "extends": [ 25 | "react-app", 26 | "react-app/jest" 27 | ] 28 | }, 29 | "browserslist": { 30 | "production": [ 31 | ">0.2%", 32 | "not dead", 33 | "not op_mini all" 34 | ], 35 | "development": [ 36 | "last 1 chrome version", 37 | "last 1 firefox version", 38 | "last 1 safari version" 39 | ] 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /frontend/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeromevdl/cdk-s3-upload-presignedurl-api/c597a8314cfcd4b8535b355f92461b5058d891cb/frontend/public/favicon.ico -------------------------------------------------------------------------------- /frontend/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /frontend/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeromevdl/cdk-s3-upload-presignedurl-api/c597a8314cfcd4b8535b355f92461b5058d891cb/frontend/public/logo192.png -------------------------------------------------------------------------------- /frontend/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeromevdl/cdk-s3-upload-presignedurl-api/c597a8314cfcd4b8535b355f92461b5058d891cb/frontend/public/logo512.png -------------------------------------------------------------------------------- /frontend/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /frontend/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /frontend/src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | height: 40vmin; 7 | pointer-events: none; 8 | } 9 | 10 | @media (prefers-reduced-motion: no-preference) { 11 | .App-logo { 12 | animation: App-logo-spin infinite 20s linear; 13 | } 14 | } 15 | 16 | .App-header { 17 | background-color: #282c34; 18 | min-height: 100vh; 19 | display: flex; 20 | flex-direction: column; 21 | align-items: center; 22 | justify-content: center; 23 | font-size: calc(10px + 2vmin); 24 | color: white; 25 | } 26 | 27 | .App-link { 28 | color: #61dafb; 29 | } 30 | 31 | @keyframes App-logo-spin { 32 | from { 33 | transform: rotate(0deg); 34 | } 35 | to { 36 | transform: rotate(360deg); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /frontend/src/App.js: -------------------------------------------------------------------------------- 1 | import React, { useMemo, useState } from 'react'; 2 | import { API } from 'aws-amplify'; 3 | import './App.css'; 4 | import { withAuthenticator, Button, Heading, Card, Text } from '@aws-amplify/ui-react'; 5 | import { useDropzone } from 'react-dropzone'; 6 | import '@aws-amplify/ui-react/styles.css'; 7 | import axios from 'axios'; 8 | 9 | const apiName = 'S3SignedURLAPI'; 10 | 11 | const baseStyle = { 12 | flex: 1, 13 | width: '50%', 14 | display: 'inline-block', 15 | flexDirection: 'column', 16 | alignItems: 'center', 17 | padding: '20px', 18 | borderWidth: 3, 19 | borderRadius: 8, 20 | borderColor: '#eeeeee', 21 | borderStyle: 'dashed', 22 | backgroundColor: '#fafafa', 23 | color: '#bdbdbd', 24 | outline: 'none', 25 | transition: 'border .24s ease-in-out' 26 | }; 27 | 28 | const focusedStyle = { 29 | borderColor: '#2196f3' 30 | }; 31 | 32 | const acceptStyle = { 33 | borderColor: '#00e676' 34 | }; 35 | 36 | const rejectStyle = { 37 | borderColor: '#ff1744' 38 | }; 39 | 40 | function StyledDropzone(props) { 41 | const { 42 | getRootProps, 43 | getInputProps, 44 | isFocused, 45 | isDragAccept, 46 | isDragReject 47 | } = useDropzone({onDrop: props.onDrop, accept: {'image/*': []}}); 48 | 49 | 50 | const style = useMemo(() => ({ 51 | ...baseStyle, 52 | ...(isFocused ? focusedStyle : {}), 53 | ...(isDragAccept ? acceptStyle : {}), 54 | ...(isDragReject ? rejectStyle : {}) 55 | }), [ 56 | isFocused, 57 | isDragAccept, 58 | isDragReject 59 | ]); 60 | 61 | return ( 62 |
63 |
64 | 65 |

Drag 'n' drop some files here, or click to select files

66 |
67 |
68 | ); 69 | } 70 | 71 | function App({ signOut, user }) { 72 | 73 | const [file, setFile] = useState(); 74 | const [status, setStatus] = useState(); 75 | const [objectKey, setObjectKey] = useState(''); 76 | const [uploadURL, setUploadURL] = useState(''); 77 | const [error, setError] = useState(''); 78 | 79 | 80 | const onDrop = (files) => { 81 | let file = files[0]; 82 | 83 | API.get(apiName, '/', { 84 | queryStringParameters: { 85 | 'contentType': file.type 86 | } 87 | }) 88 | .then((response) => { 89 | setObjectKey(response.key); 90 | setUploadURL(response.uploadURL); 91 | axios.put(response.uploadURL, file, { 92 | headers: { 93 | 'content-type': file.type 94 | } 95 | }).then((response) => { 96 | setFile(file); 97 | setStatus(response.status); 98 | }).catch((error) => { 99 | setStatus(error.status); 100 | setError(error); 101 | console.error(error); 102 | }); 103 | }) 104 | .catch((error) => { 105 | setError(error); 106 | console.error(error); 107 | }); 108 | }; 109 | 110 | return ( 111 |
112 | 113 | Hello {user.username}
114 | 115 |
116 | 117 |
118 | 119 | 120 |
121 | { status && status === 200 ? ( 122 |
123 |

Your file was successfully uploaded:

124 | File name: {file.name} 125 | File size: {file.size} 126 | File type: {file.type}
127 |

The following URL was used

: (cannot be used twice) 128 | {uploadURL}
129 |

Your file is stored in S3 with the key:

130 | {objectKey} 131 |
132 | ) : error ? ( {error}) : (<>) 133 | } 134 |
135 |
136 | 137 | 138 |
139 | ); 140 | } 141 | 142 | export default withAuthenticator(App); 143 | -------------------------------------------------------------------------------- /frontend/src/App.test.js: -------------------------------------------------------------------------------- 1 | import { render, screen } from '@testing-library/react'; 2 | import App from './App'; 3 | 4 | test('renders learn react link', () => { 5 | render(); 6 | const linkElement = screen.getByText(/learn react/i); 7 | expect(linkElement).toBeInTheDocument(); 8 | }); 9 | -------------------------------------------------------------------------------- /frontend/src/aws-exports.js: -------------------------------------------------------------------------------- 1 | import { Auth } from 'aws-amplify'; 2 | 3 | const awsconfig = { 4 | Auth: { 5 | region: 'eu-west-1', 6 | userPoolId: 'eu-west-1_WOjKdlvy9', 7 | userPoolWebClientId: '225lk6pkqa5l2tgo87s3je374mb' 8 | }, 9 | API: { 10 | endpoints: [ 11 | { 12 | name: 'S3SignedURLAPI', 13 | endpoint: 'https://2koys5byc8.execute-api.eu-west-1.amazonaws.com/prod', 14 | custom_header: async () => { 15 | return { Authorization: `${(await Auth.currentSession()).getIdToken().getJwtToken()}` } 16 | } 17 | } 18 | ] 19 | } 20 | }; 21 | 22 | 23 | export default awsconfig; 24 | -------------------------------------------------------------------------------- /frontend/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /frontend/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom/client'; 3 | import './index.css'; 4 | import App from './App'; 5 | import reportWebVitals from './reportWebVitals'; 6 | import { Amplify } from 'aws-amplify'; 7 | import awsconfig from './aws-exports'; 8 | 9 | Amplify.configure(awsconfig); 10 | 11 | const root = ReactDOM.createRoot(document.getElementById('root')); 12 | root.render( 13 | 14 | 15 | 16 | ); 17 | 18 | // If you want to start measuring performance in your app, pass a function 19 | // to log results (for example: reportWebVitals(console.log)) 20 | // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals 21 | reportWebVitals(); 22 | -------------------------------------------------------------------------------- /frontend/src/logo.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /frontend/src/reportWebVitals.js: -------------------------------------------------------------------------------- 1 | const reportWebVitals = onPerfEntry => { 2 | if (onPerfEntry && onPerfEntry instanceof Function) { 3 | import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { 4 | getCLS(onPerfEntry); 5 | getFID(onPerfEntry); 6 | getFCP(onPerfEntry); 7 | getLCP(onPerfEntry); 8 | getTTFB(onPerfEntry); 9 | }); 10 | } 11 | }; 12 | 13 | export default reportWebVitals; 14 | -------------------------------------------------------------------------------- /frontend/src/setupTests.js: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom'; 6 | -------------------------------------------------------------------------------- /images/architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeromevdl/cdk-s3-upload-presignedurl-api/c597a8314cfcd4b8535b355f92461b5058d891cb/images/architecture.png -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cdk-s3-upload-presignedurl-api", 3 | "description": "API to get an S3 presigned url for file uploads", 4 | "repository": { 5 | "type": "git", 6 | "url": "https://github.com/jeromevdl/cdk-s3-upload-presignedurl-api.git" 7 | }, 8 | "scripts": { 9 | "build": "npx projen build", 10 | "bump": "npx projen bump", 11 | "bundle": "npx projen bundle", 12 | "bundle:index.lambda": "npx projen bundle:index.lambda", 13 | "bundle:index.lambda:watch": "npx projen bundle:index.lambda:watch", 14 | "clobber": "npx projen clobber", 15 | "compat": "npx projen compat", 16 | "compile": "npx projen compile", 17 | "default": "npx projen default", 18 | "docgen": "npx projen docgen", 19 | "eject": "npx projen eject", 20 | "eslint": "npx projen eslint", 21 | "package": "npx projen package", 22 | "package-all": "npx projen package-all", 23 | "package:java": "npx projen package:java", 24 | "package:js": "npx projen package:js", 25 | "package:python": "npx projen package:python", 26 | "post-compile": "npx projen post-compile", 27 | "pre-compile": "npx projen pre-compile", 28 | "release": "npx projen release", 29 | "test": "npx projen test", 30 | "test:watch": "npx projen test:watch", 31 | "unbump": "npx projen unbump", 32 | "watch": "npx projen watch", 33 | "projen": "npx projen" 34 | }, 35 | "author": { 36 | "name": "Jerome Van Der Linden", 37 | "email": "jeromevdl@gmail.com", 38 | "organization": false 39 | }, 40 | "devDependencies": { 41 | "@aws-sdk/client-s3": "^3.231.0", 42 | "@aws-sdk/s3-request-presigner": "^3.231.0", 43 | "@jest/globals": "^29.3.1", 44 | "@types/jest": "^27", 45 | "@types/node": "^14", 46 | "@typescript-eslint/eslint-plugin": "^5", 47 | "@typescript-eslint/parser": "^5", 48 | "aws-cdk-lib": "2.54.0", 49 | "constructs": "10.0.5", 50 | "es-mime-types": "*", 51 | "esbuild": "^0.16.4", 52 | "eslint": "^8", 53 | "eslint-import-resolver-node": "^0.3.6", 54 | "eslint-import-resolver-typescript": "^3.5.2", 55 | "eslint-plugin-import": "^2.26.0", 56 | "jest": "^27", 57 | "jest-junit": "^13", 58 | "jsii": "^1.72.0", 59 | "jsii-diff": "^1.72.0", 60 | "jsii-docgen": "^7.0.171", 61 | "jsii-pacmak": "^1.72.0", 62 | "json-schema": "^0.4.0", 63 | "projen": "^0.65.57", 64 | "standard-version": "^9", 65 | "ts-jest": "^27", 66 | "ts-node": "^10.9.1", 67 | "typescript": "^4.9.4" 68 | }, 69 | "peerDependencies": { 70 | "aws-cdk-lib": "^2.54.0", 71 | "constructs": "^10.0.5" 72 | }, 73 | "keywords": [ 74 | "api gateway", 75 | "aws", 76 | "cdk", 77 | "presigned", 78 | "s3", 79 | "upload" 80 | ], 81 | "main": "lib/index.js", 82 | "license": "Apache-2.0", 83 | "version": "0.0.0", 84 | "jest": { 85 | "testMatch": [ 86 | "/src/**/__tests__/**/*.ts?(x)", 87 | "/(test|src)/**/*(*.)@(spec|test).ts?(x)" 88 | ], 89 | "clearMocks": true, 90 | "collectCoverage": true, 91 | "coverageReporters": [ 92 | "json", 93 | "lcov", 94 | "clover", 95 | "cobertura", 96 | "text" 97 | ], 98 | "coverageDirectory": "coverage", 99 | "coveragePathIgnorePatterns": [ 100 | "/node_modules/" 101 | ], 102 | "testPathIgnorePatterns": [ 103 | "/node_modules/" 104 | ], 105 | "watchPathIgnorePatterns": [ 106 | "/node_modules/" 107 | ], 108 | "reporters": [ 109 | "default", 110 | [ 111 | "jest-junit", 112 | { 113 | "outputDirectory": "test-reports" 114 | } 115 | ] 116 | ], 117 | "preset": "ts-jest", 118 | "globals": { 119 | "ts-jest": { 120 | "tsconfig": "tsconfig.dev.json" 121 | } 122 | } 123 | }, 124 | "types": "lib/index.d.ts", 125 | "stability": "stable", 126 | "jsii": { 127 | "outdir": "dist", 128 | "targets": { 129 | "java": { 130 | "package": "io.github.jeromevdl.awscdk.s3uploadpresignedurlapi", 131 | "maven": { 132 | "groupId": "io.github.jeromevdl.awscdk", 133 | "artifactId": "s3-upload-presignedurl-api" 134 | } 135 | }, 136 | "python": { 137 | "distName": "cdk-s3-upload-presignedurl-api", 138 | "module": "cdk_s3_upload_presignedurl_api" 139 | } 140 | }, 141 | "tsc": { 142 | "outDir": "lib", 143 | "rootDir": "src" 144 | } 145 | }, 146 | "resolutions": { 147 | "@types/prettier": "2.6.0", 148 | "@types/babel__traverse": "7.18.2" 149 | }, 150 | "//": "~~ Generated by projen. To modify, edit .projenrc.js and run \"npx projen\"." 151 | } 152 | -------------------------------------------------------------------------------- /src/index-function.ts: -------------------------------------------------------------------------------- 1 | // ~~ Generated by projen. To modify, edit .projenrc.js and run "npx projen". 2 | import * as path from 'path'; 3 | import * as lambda from 'aws-cdk-lib/aws-lambda'; 4 | import { Construct } from 'constructs'; 5 | 6 | /** 7 | * Props for IndexFunction 8 | */ 9 | export interface IndexFunctionProps extends lambda.FunctionOptions { 10 | } 11 | 12 | /** 13 | * An AWS Lambda function which executes src/index. 14 | */ 15 | export class IndexFunction extends lambda.Function { 16 | constructor(scope: Construct, id: string, props?: IndexFunctionProps) { 17 | super(scope, id, { 18 | description: 'src/index.lambda.ts', 19 | ...props, 20 | runtime: new lambda.Runtime('nodejs18.x', lambda.RuntimeFamily.NODEJS), 21 | handler: 'index.handler', 22 | code: lambda.Code.fromAsset(path.join(__dirname, '../assets/index.lambda')), 23 | }); 24 | this.addEnvironment('AWS_NODEJS_CONNECTION_REUSE_ENABLED', '1', { removeInEdge: true }); 25 | } 26 | } -------------------------------------------------------------------------------- /src/index.lambda.ts: -------------------------------------------------------------------------------- 1 | import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3'; 2 | import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; 3 | import { extension as getExtension } from 'es-mime-types'; 4 | 5 | const client = new S3Client({ 6 | region: process.env.AWS_REGION, 7 | }); 8 | 9 | exports.handler = async (event: any) => { 10 | // console.log(event); 11 | 12 | const uploadURL = await getUploadURL(event); 13 | 14 | return { 15 | statusCode: 200, 16 | headers: { 17 | 'Content-Type': 'application/json', 18 | 'Access-Control-Allow-Headers': 'Authorization, *', 19 | 'Access-Control-Allow-Origin': process.env.ALLOWED_ORIGIN || '*', 20 | 'Access-Control-Allow-Methods': 'OPTIONS,GET', 21 | }, 22 | body: JSON.stringify(uploadURL), 23 | }; 24 | }; 25 | 26 | const getUploadURL = async function(event: any) { 27 | 28 | const apiRequestId = event.requestContext.requestId; 29 | const contentType = event.queryStringParameters.contentType; 30 | const extension = getExtension(contentType); 31 | const s3Key = `${apiRequestId}.${extension}`; 32 | 33 | // Get signed URL from S3 34 | const putObjectParams = { 35 | Bucket: process.env.UPLOAD_BUCKET, 36 | Key: s3Key, 37 | ContentType: contentType, 38 | }; 39 | const command = new PutObjectCommand(putObjectParams); 40 | 41 | const signedUrl = await getSignedUrl(client, command, { expiresIn: parseInt(process.env.URL_EXPIRATION_SECONDS || '300') }); 42 | 43 | return { 44 | uploadURL: signedUrl, 45 | key: s3Key, 46 | }; 47 | }; -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { Duration, CfnOutput, RemovalPolicy } from 'aws-cdk-lib'; 2 | import { AccessLogFormat, AuthorizationType, Authorizer, CfnMethod, CognitoUserPoolsAuthorizer, EndpointType, LambdaIntegration, LogGroupLogDestination, MethodLoggingLevel, RestApi, RestApiProps } from 'aws-cdk-lib/aws-apigateway'; 3 | import { CfnUserPool, UserPool, UserPoolClient } from 'aws-cdk-lib/aws-cognito'; 4 | import { Tracing } from 'aws-cdk-lib/aws-lambda'; 5 | import { LogGroup, RetentionDays } from 'aws-cdk-lib/aws-logs'; 6 | import { BlockPublicAccess, Bucket, BucketEncryption, HttpMethods } from 'aws-cdk-lib/aws-s3'; 7 | import { Construct } from 'constructs'; 8 | import { IndexFunction } from './index-function'; 9 | 10 | export interface IS3UploadSignedUrlApiProps { 11 | /** 12 | * Optional bucket where files should be uploaded to. Should contains the CORS properties 13 | * 14 | * @default - Default Bucket is created 15 | */ 16 | readonly existingBucketObj?: Bucket; 17 | 18 | /** 19 | * Optional Cognito User Pool to secure the API. You should have created a User Pool Client too. 20 | * 21 | * @default - Default User Pool (and User Pool Client) are created 22 | */ 23 | readonly existingUserPoolObj?: UserPool; 24 | 25 | /** 26 | * Optional CORS allowedOrigins. 27 | * Should allow your domain(s) as allowed origin to request the API 28 | * 29 | * @default ['*'] 30 | */ 31 | readonly allowedOrigins?: string[]; 32 | 33 | /** 34 | * Optional expiration time in second. Time before the presigned url expires. 35 | * 36 | * @default 300 37 | */ 38 | readonly expiration?: number; 39 | 40 | /** 41 | * Optional user provided props to override the default props for the API Gateway. 42 | * 43 | * @default - Default props are used 44 | */ 45 | readonly apiGatewayProps?: RestApiProps | any; 46 | 47 | /** 48 | * Optional boolean to specify if the API is secured (with Cognito) or publicly open 49 | * 50 | * @default true 51 | */ 52 | readonly secured?: boolean; 53 | 54 | /** 55 | * Optional log retention time for Lambda and API Gateway 56 | * 57 | * @default one week 58 | */ 59 | readonly logRetention?: RetentionDays; 60 | } 61 | 62 | export class S3UploadPresignedUrlApi extends Construct { 63 | 64 | public readonly bucket: Bucket; 65 | public readonly restApi: RestApi; 66 | public readonly userPool?: UserPool | any = undefined; 67 | public readonly userPoolClient?: UserPoolClient | any = undefined; 68 | 69 | constructor(scope: Construct, id: string, props?: IS3UploadSignedUrlApiProps) { 70 | super(scope, id); 71 | 72 | const securedApi : boolean = props?.secured === undefined ? true : props.secured; 73 | 74 | if (!securedApi && props?.existingUserPoolObj) { 75 | throw new Error('You don\'t need to pass a User Pool if the API is not secured'); 76 | } 77 | 78 | if (props?.existingBucketObj) { 79 | this.bucket = props.existingBucketObj; 80 | } else { 81 | const logBucket = new Bucket(this, 's3AccessLogsBucket', { 82 | versioned: true, 83 | publicReadAccess: false, 84 | blockPublicAccess: BlockPublicAccess.BLOCK_ALL, 85 | removalPolicy: RemovalPolicy.DESTROY, 86 | autoDeleteObjects: true, 87 | encryption: BucketEncryption.S3_MANAGED, 88 | }); 89 | 90 | this.bucket = new Bucket(this, 'uploadBucket', { 91 | publicReadAccess: false, 92 | blockPublicAccess: BlockPublicAccess.BLOCK_ALL, 93 | serverAccessLogsBucket: logBucket, 94 | removalPolicy: RemovalPolicy.RETAIN, 95 | encryption: BucketEncryption.S3_MANAGED, 96 | cors: [ 97 | { 98 | allowedMethods: [HttpMethods.HEAD, HttpMethods.GET, HttpMethods.PUT], 99 | allowedOrigins: props?.allowedOrigins || ['*'], 100 | allowedHeaders: ['Authorization', '*'], 101 | }, 102 | ], 103 | }); 104 | } 105 | 106 | // Lambda function in charge of creating the PreSigned URL 107 | const getS3SignedUrlLambda = new IndexFunction(this, 'getS3SignedUrlLambda', { 108 | description: 'Function that creates a presigned URL to upload a file into S3', 109 | environment: { 110 | UPLOAD_BUCKET: this.bucket.bucketName, 111 | URL_EXPIRATION_SECONDS: (props?.expiration || 300).toString(), 112 | ALLOWED_ORIGIN: props?.allowedOrigins?.join(',') || '*', 113 | }, 114 | tracing: Tracing.ACTIVE, 115 | logRetention: props?.logRetention || RetentionDays.ONE_WEEK, 116 | timeout: Duration.seconds(10), 117 | memorySize: 256, 118 | }); 119 | 120 | this.bucket.grantPut(getS3SignedUrlLambda); 121 | 122 | // Rest API 123 | const apiLogGroup = new LogGroup(this, 'S3SignedUrlApiLogGroup', { 124 | retention: props?.logRetention || RetentionDays.ONE_WEEK, 125 | }); 126 | 127 | let apiProps: RestApiProps = props?.apiGatewayProps || { 128 | description: 'API that retrieves a presigned URL to upload a file into S3', 129 | endpointTypes: [EndpointType.REGIONAL], 130 | deployOptions: { 131 | accessLogDestination: new LogGroupLogDestination(apiLogGroup), 132 | accessLogFormat: AccessLogFormat.jsonWithStandardFields(), 133 | loggingLevel: MethodLoggingLevel.INFO, 134 | metricsEnabled: true, 135 | tracingEnabled: true, 136 | dataTraceEnabled: false, 137 | stageName: 'prod', 138 | }, 139 | defaultMethodOptions: securedApi ? { authorizationType: AuthorizationType.COGNITO } : undefined, 140 | }; 141 | 142 | this.restApi = new RestApi(this, 'S3SignedUrlApi', apiProps); 143 | 144 | // Adding security on the API if needed 145 | var apiGatewayAuthorizer: Authorizer | any = undefined; 146 | 147 | if (securedApi) { 148 | if (!props?.existingUserPoolObj) { 149 | this.userPool = new UserPool(this, 'CognitoUserPool', { 150 | selfSignUpEnabled: true, 151 | passwordPolicy: { 152 | minLength: 8, 153 | requireLowercase: true, 154 | requireUppercase: true, 155 | requireSymbols: true, 156 | requireDigits: true, 157 | }, 158 | }); 159 | this.userPoolClient = new UserPoolClient(this, 'CognitoUserPoolClient', { 160 | userPool: this.userPool, 161 | }); 162 | const cfnUserPool = this.userPool.node.findChild('Resource') as CfnUserPool; 163 | cfnUserPool.userPoolAddOns = { 164 | advancedSecurityMode: 'ENFORCED', 165 | }; 166 | 167 | new CfnOutput(this, 'User Pool Id', { value: this.userPool.userPoolId }); 168 | new CfnOutput(this, 'User Pool Client Id', { value: this.userPoolClient.userPoolClientId }); 169 | } else { 170 | this.userPool = props.existingUserPoolObj; 171 | } 172 | 173 | apiGatewayAuthorizer = new CognitoUserPoolsAuthorizer(this, 'CognitoAuthorizer', { 174 | cognitoUserPools: [this.userPool], 175 | identitySource: 'method.request.header.Authorization', 176 | }); 177 | apiGatewayAuthorizer._attachToApi(this.restApi); 178 | } 179 | 180 | // Adding GET method on the API 181 | this.restApi.root.addMethod('GET', new LambdaIntegration(getS3SignedUrlLambda), { 182 | requestParameters: { 183 | 'method.request.querystring.contentType': true, 184 | }, 185 | requestValidatorOptions: { 186 | requestValidatorName: 'validate-request-param', 187 | validateRequestBody: false, 188 | validateRequestParameters: true, 189 | }, 190 | }); 191 | 192 | // CORS configuration for the API 193 | this.restApi.root.addCorsPreflight({ 194 | allowHeaders: ['Authorization', '*'], 195 | allowOrigins: props?.allowedOrigins || ['*'], 196 | allowMethods: ['OPTIONS', 'GET'], 197 | allowCredentials: true, 198 | }); 199 | 200 | if (securedApi) { 201 | this.restApi.methods.forEach(method => { 202 | const cfnmethod = method.node.defaultChild as CfnMethod; 203 | if (method.httpMethod == 'OPTIONS') { 204 | cfnmethod.addPropertyOverride('AuthorizationType', 'NONE'); 205 | } else { 206 | cfnmethod.addPropertyOverride('AuthorizationType', 'COGNITO_USER_POOLS'); 207 | cfnmethod.addPropertyOverride('AuthorizerId', apiGatewayAuthorizer.authorizerId); 208 | } 209 | }); 210 | } 211 | 212 | } 213 | 214 | } -------------------------------------------------------------------------------- /src/integ.default.ts: -------------------------------------------------------------------------------- 1 | import { App, Stack } from 'aws-cdk-lib'; 2 | import { S3UploadPresignedUrlApi } from './index'; 3 | 4 | const env = { 5 | region: process.env.CDK_DEFAULT_REGION, 6 | account: process.env.CDK_DEFAULT_ACCOUNT, 7 | }; 8 | 9 | const app = new App(); 10 | const stack = new Stack(app, 'TestS3UploadSignedUrl', { env }); 11 | 12 | new S3UploadPresignedUrlApi(stack, 'S3UploadSignedUrl'); -------------------------------------------------------------------------------- /test/index.test.ts: -------------------------------------------------------------------------------- 1 | import { App, Stack } from 'aws-cdk-lib'; 2 | import { Template } from 'aws-cdk-lib/assertions'; 3 | import { UserPool } from 'aws-cdk-lib/aws-cognito'; 4 | 5 | import { Bucket } from 'aws-cdk-lib/aws-s3'; 6 | import { S3UploadPresignedUrlApi } from '../src'; 7 | 8 | test('default config should create API / Lambda and User Pool', () => { 9 | const app = new App(); 10 | const stack = new Stack(app); 11 | new S3UploadPresignedUrlApi(stack, 'TestStackDefault'); 12 | 13 | const template = Template.fromStack(stack); 14 | 15 | template.hasResourceProperties('AWS::Lambda::Function', { 16 | Description: 'Function that creates a presigned URL to upload a file into S3', 17 | }); 18 | template.hasResourceProperties('AWS::ApiGateway::RestApi', { 19 | Description: 'API that retrieves a presigned URL to upload a file into S3', 20 | }); 21 | template.resourceCountIs('AWS::S3::Bucket', 2); 22 | template.resourceCountIs('AWS::Cognito::UserPool', 1); 23 | template.resourceCountIs('AWS::Cognito::UserPoolClient', 1); 24 | }); 25 | 26 | test('open config should not create User Pool', () => { 27 | const app = new App(); 28 | const stack = new Stack(app); 29 | new S3UploadPresignedUrlApi(stack, 'TestStackDefault', { secured: false }); 30 | 31 | const template = Template.fromStack(stack); 32 | 33 | template.resourceCountIs('AWS::Cognito::UserPool', 0); 34 | template.resourceCountIs('AWS::Cognito::UserPoolClient', 0); 35 | }); 36 | 37 | test('config with existing User Pool should not create new User Pool', () => { 38 | const app = new App(); 39 | const stack = new Stack(app); 40 | new S3UploadPresignedUrlApi(stack, 'TestStackDefault', { 41 | existingUserPoolObj: new UserPool(stack, 'userpool'), 42 | }); 43 | 44 | const template = Template.fromStack(stack); 45 | 46 | template.resourceCountIs('AWS::Cognito::UserPool', 1); 47 | template.resourceCountIs('AWS::Cognito::UserPoolClient', 0); 48 | }); 49 | 50 | test('config with existing S3 Bucket should not create new Bucket', () => { 51 | const app = new App(); 52 | const stack = new Stack(app); 53 | new S3UploadPresignedUrlApi(stack, 'TestStackDefault', { 54 | existingBucketObj: new Bucket(stack, 'bucket'), 55 | secured: false, 56 | }); 57 | 58 | const template = Template.fromStack(stack); 59 | 60 | template.resourceCountIs('AWS::S3::Bucket', 1); 61 | }); 62 | -------------------------------------------------------------------------------- /tsconfig.dev.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "alwaysStrict": true, 4 | "declaration": true, 5 | "esModuleInterop": true, 6 | "experimentalDecorators": true, 7 | "inlineSourceMap": true, 8 | "inlineSources": true, 9 | "lib": [ 10 | "es2020", 11 | "dom" 12 | ], 13 | "module": "CommonJS", 14 | "noEmitOnError": false, 15 | "noFallthroughCasesInSwitch": true, 16 | "noImplicitAny": true, 17 | "noImplicitReturns": true, 18 | "noImplicitThis": true, 19 | "noUnusedLocals": true, 20 | "noUnusedParameters": true, 21 | "resolveJsonModule": true, 22 | "strict": true, 23 | "strictNullChecks": true, 24 | "strictPropertyInitialization": true, 25 | "stripInternal": true, 26 | "target": "ES2019" 27 | }, 28 | "include": [ 29 | ".projenrc.js", 30 | "src/**/*.ts", 31 | "test/**/*.ts" 32 | ], 33 | "exclude": [ 34 | "node_modules" 35 | ], 36 | "//": "~~ Generated by projen. To modify, edit .projenrc.js and run \"npx projen\"." 37 | } 38 | --------------------------------------------------------------------------------