diff --git a/.github/.dependabot.yml b/.github/.dependabot.yml index 77b915d..01a6a15 100644 --- a/.github/.dependabot.yml +++ b/.github/.dependabot.yml @@ -3,7 +3,7 @@ updates: # Enable version updates for npm - package-ecosystem: 'npm' # Look for `package.json` and `lock` files in the `root` directory - directory: '/' + directory: '/application/enquiry' # Check the npm registry for updates every day (weekdays) schedule: interval: 'daily' diff --git a/.github/workflows/build-and-test.yaml b/.github/workflows/build-and-test.yaml new file mode 100644 index 0000000..177f486 --- /dev/null +++ b/.github/workflows/build-and-test.yaml @@ -0,0 +1,87 @@ +name: ๐Ÿงฑ Build and Test +run-name: ๐Ÿงฑ Build and Test ${{ github.ref_name }} +on: + push: + paths: + - 'application/**' + workflow_call: + workflow_dispatch: + inputs: + ignore-test-failures: + type: boolean + description: Ignore Test Failures + default: false + +concurrency: + group: ${{ github.workflow }}-${{ github.ref_name }} + cancel-in-progress: true + +jobs: + environment: + name: ๐Ÿงน Prepare Environment + runs-on: ubuntu-latest + outputs: + environment-name: ${{ steps.environment.outputs.environment-name }} + environment-type: ${{ steps.environment.outputs.environment-type }} + github-branch: ${{ steps.environment.outputs.github-branch }} + commit: ${{ steps.commit.outputs.commit }} + package-name: ${{ steps.name.outputs.package-name }} + + steps: + - name: Generate Package Name + id: name + run: | + repo=${{ github.repository }} + echo "package-name=${repo#dvsa/}" >> $GITHUB_OUTPUT + echo "Package Name: ${repo#dvsa/}" >> $GITHUB_STEP_SUMMARY + + - name: ๐Ÿ“ฅ Get Codebase + uses: actions/checkout@v4 + with: + ref: ${{ github.ref_name }} + + - name: โ†•๏ธ Get Environment Details + id: environment + uses: dvsa/cvs-github-actions/environment@develop + with: + environment: ${{ github.ref_name }} + + - name: Get Commit SHA + id: commit + run: | + # Get the branch Commit ID + commit_id=$(git rev-parse HEAD) + echo "commit=${commit_id}" + echo "commit=${commit_id}" >> $GITHUB_OUTPUT + echo "Commit ID: ${commit_id}" >> $GITHUB_STEP_SUMMARY + + build-service: + name: ๐Ÿงฑ Build ${{ needs.environment.outputs.package-name }} + runs-on: ubuntu-latest + environment: ${{ needs.environment.outputs.environment-type }} + needs: environment + steps: + - name: ๐Ÿ“ฅ Get Codebase + uses: actions/checkout@v4 + + - name: ๐Ÿ—’๏ธ Process Manifest Data + id: manifest + run: | + # Generate Manifest Outputs & Identify Build Requirements + hash_files="[]" + if [[ -f "manifest.json" ]]; then + package=$(jq -r '.name' manifest.json) + echo "package=$(jq -r '.name' manifest.json)" >> $GITHUB_OUTPUT + echo "language=$(jq -r '.language' manifest.json)" >> $GITHUB_OUTPUT + echo "liquibase=$(jq -r '.liquibase' manifest.json)" >> $GITHUB_OUTPUT + fi + + - name: ๐Ÿ—๏ธ Build Node Function + uses: dvsa/cvs-github-actions/build-node-function@develop + with: + commit-sha: ${{ needs.environment.outputs.commit }} + branch: ${{needs.environment.outputs.github-branch }} + mysql_liquibase: ${{ steps.manifest.outputs.liquibase }} + mysql_user: ${{ secrets.MYSQL_USER }} + mysql_password: ${{ secrets.MYSQL_PASS }} + continue-on-error: ${{ inputs.ignore-test-failures }} diff --git a/.github/workflows/build_hash.yaml b/.github/workflows/build_hash.yaml deleted file mode 100644 index 8f14a19..0000000 --- a/.github/workflows/build_hash.yaml +++ /dev/null @@ -1,15 +0,0 @@ -name: Build hash and deploy to S3 -run-name: "${{ github.actor }} - ${{ github.ref_name }} - ${{ github.run_id }} ๐Ÿš€" - -on: - workflow_dispatch: - push: - branches: - - 'feature/*' - -jobs: - Build: - uses: dvsa/cvs-github-actions/.github/workflows/build-node-hash.yaml@develop - secrets: - CVS_MGMT_AWS_ROLE: ${{ secrets.CVS_MGMT_AWS_ROLE }} - DVSA_AWS_REGION: ${{ secrets.DVSA_AWS_REGION }} diff --git a/.github/workflows/ci.yaml.old b/.github/workflows/ci.yaml.old deleted file mode 100644 index c32e78c..0000000 --- a/.github/workflows/ci.yaml.old +++ /dev/null @@ -1,21 +0,0 @@ -name: CI -on: - workflow_dispatch: - push: - branches: - - develop - - 'release/*' - pull_request: - branches: - - develop - -permissions: - id-token: write - contents: read - -jobs: - ci: - uses: dvsa/cvs-github-actions/.github/workflows/node-ci.yaml@develop - secrets: - CVS_MGMT_AWS_ROLE: ${{ secrets.CVS_MGMT_AWS_ROLE }} - CVS_SERVICES_S3: ${{ secrets.CVS_SERVICES_S3 }} diff --git a/.github/workflows/pr-plan.yaml b/.github/workflows/pr-plan.yaml index 58bfb6a..47b4882 100644 --- a/.github/workflows/pr-plan.yaml +++ b/.github/workflows/pr-plan.yaml @@ -12,29 +12,22 @@ jobs: id-token: write contents: write pull-requests: write - runs-on: X64 + runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v4 with: node-version-file: '.nvmrc' - - uses: aws-actions/configure-aws-credentials@v4 - with: - role-to-assume: ${{ secrets.CVS_MGMT_AWS_ROLE }} - aws-region: ${{ secrets.DVSA_AWS_REGION }} - role-session-name: 'cvs-svc-technical-records-v3' - - uses: aws-actions/aws-secretsmanager-get-secrets@v1 - with: - secret-ids: sonarqube-gha - parse-json-secrets: true - name: Install dependencies run: npm ci + - name: Build and Test + uses: ./.github/workflows/build-and-test.yaml - name: Run SonarQube scanner run: | npm run test && \ npm run sonar-scanner -- \ - -Dsonar.host.url=${{ env.SONARQUBE_GHA_URL }} \ - -Dsonar.token=${{ env.SONARQUBE_GHA_TOKEN }} \ - -Dsonar.login=${{ env.SONARQUBE_GHA_TOKEN }} \ + -Dsonar.host.url=${{ secrets.SONARQUBE_GHA_URL }} \ + -Dsonar.token=${{ secrets.SONARQUBE_GHA_TOKEN }} \ + -Dsonar.login=${{ secrets.SONARQUBE_GHA_TOKEN }} \ -Dsonar.projectName=${{ github.repository }} \ -Dsonar.projectVersion=1.0.${{ github.run_id }} diff --git a/.gitignore b/.gitignore index 113380e..d5148da 100644 --- a/.gitignore +++ b/.gitignore @@ -46,3 +46,13 @@ reports # Idea specific hidden files .idea/** + +# Terraform Files +**/.tfstate* +**/.terraform/* +**/.terraform-lock.hcl +**/.terraform.lock.hcl +**/*.tfplan + +# Local variables/secrets +**/local.auto.tfvars* diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index f1ef525..0000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "cvs-nop"] - path = cvs-nop - url = https://github.com/dvsa/cvs-nop diff --git a/.editorconfig b/application/enquiry/.editorconfig similarity index 100% rename from .editorconfig rename to application/enquiry/.editorconfig diff --git a/.eslintignore b/application/enquiry/.eslintignore similarity index 100% rename from .eslintignore rename to application/enquiry/.eslintignore diff --git a/.eslintrc.js b/application/enquiry/.eslintrc.js similarity index 100% rename from .eslintrc.js rename to application/enquiry/.eslintrc.js diff --git a/.npm-version b/application/enquiry/.npm-version similarity index 100% rename from .npm-version rename to application/enquiry/.npm-version diff --git a/.npmrc b/application/enquiry/.npmrc similarity index 100% rename from .npmrc rename to application/enquiry/.npmrc diff --git a/.nvmrc b/application/enquiry/.nvmrc similarity index 100% rename from .nvmrc rename to application/enquiry/.nvmrc diff --git a/.prettierignore b/application/enquiry/.prettierignore similarity index 100% rename from .prettierignore rename to application/enquiry/.prettierignore diff --git a/.prettierrc.js b/application/enquiry/.prettierrc.js similarity index 100% rename from .prettierrc.js rename to application/enquiry/.prettierrc.js diff --git a/.secignore b/application/enquiry/.secignore similarity index 100% rename from .secignore rename to application/enquiry/.secignore diff --git a/src/app/index.ts b/application/enquiry/CHANGELOG.md similarity index 100% rename from src/app/index.ts rename to application/enquiry/CHANGELOG.md diff --git a/application/enquiry/LICENSE b/application/enquiry/LICENSE new file mode 100644 index 0000000..2fcf053 --- /dev/null +++ b/application/enquiry/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Driver & Vehicle Standards Agency + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/application/enquiry/README.md b/application/enquiry/README.md new file mode 100644 index 0000000..70294cc --- /dev/null +++ b/application/enquiry/README.md @@ -0,0 +1,167 @@ +# cvs-svc-enquiry + +Lambda service to retrieve vehicle and test information for commerical vehicles + +## Dependencies + +The project runs on node 18.x with typescript and serverless framework. For further details about project dependencies, please refer to the `package.json` file. +[nvm](https://github.com/nvm-sh/nvm/blob/master/README.md) is used to managed node versions and configuration explicitely done per project using an `.npmrc` file. + +## Running the project + +Once the dependencies are installed, you will be required to rename the `/config/env.example` file to `.env.local` as we use dotenv files for configuration for local local development for example. Further information about [variables](https://www.serverless.com/framework/docs/providers/aws/guide/variables/) and [environment variables](https://www.serverless.com/framework/docs/environment-variables/) with serverless. + +The application runs on port `:3001` by default when no stage is provided. + +Serverless is used for local development, to get started after running `nvm use && npm i`. +You will need to initialize the external dependencies loaded as submodules, please refer to the [External dependencies](#external-dependencies) section. +Once the SQL database has been populated with liquibase, you can run `npm run start:dev`. + +Docker container might fail to boot, should it happen, delete the Docker container and rerun the `start:dev` script. + +### Environments + +We use `NODE_ENV` environment variable to set multi-stage builds (region, stages) with the help of dotenv through npm scripts to load the relevant `.env.` file from `./config` folder into the `serverless.yml` file as we don't rely on serverless for deployment. +If no `NODE_ENV` value is provided when running the scripts, it will default its `NODE_ENV` value to 'development' with the `.env.development` config file. + +The defaulted values for 'stage' and 'region' are `'local'`. Please refer to the values provided in the `serverless.yml` file. + +The following values can be provided when running the scripts with `NODE_ENV`: + +```ts +// ./config/.env. files +'local'; // used for local development +'development'; // used development staging should we wish to require external services +'test'; // used during test scripts where local services, mocks can be used in conjonction +``` + +```ts +/** Running serverless offline as an example for a specific stage - 'local'. +* Stage 'local' will be injected in the serverless.yml +**/ +NODE_ENV=local serverless offline + +``` + +Further details about environment setup can be found in the provided documentation and `env.example` file. + +All secrets the secrets are will stored in `AWS Secrets Manager`. + +### Scripts + +The following scripts are available, for further information please refer to the project `package.json` file: + +- start: `npm start` - _launch serverless offline service_ +- start:dev: `npm run start:dev` - _launch serverless offline service with dockerised DB_ +- dev: `npm run dev` - _run in parallel the service and unit tests in_ `--watch` _mode with live reload_. +- test: `npm t` - _execute the unit test suite_ +- build: `npm run build` - _bundle the project for production_ + +### Local database + +The project needs a database available in order to run locally. The `npm run start:dev` command, and by extension `npm run dev` as well, will automatically set up a database running in a docker container in the background for you and populate it with sample data. The connection details for viewing the database can be found in `src/infrastructure/localSecretsManagerService.ts`. Running `npm run start:dev` repeatedly will only initialise a single docker container, and your changes to the database will only be removed if you delete the container. +For more information about the Docker cli, please refer to the [documentation](https://docs.docker.com/engine/reference/commandline/cli/). + +### Offline + +Serverless-offline with webpack is used to run the project locally. Please use `npm run dev` script to do so. Go to `http://localhost:3001/local/version` to confirm that everything has loaded correctly, you should see that the version is the same as the version in the `package.json` + +### Lambda locally + +Serverless can invoke lambda functions locally which provide a close experience to the real service if you decide not use the offline mode. `events` and `paths` can be found under `/local` folder. +For further details using lambda locally please refer to the [serverless documentation](https://www.serverless.com/framework/docs/providers/aws/cli-reference/invoke-local/). + +### Debugging + +Existing configuration to debug the running service has been made available for vscode, please refer to `.vscode/launch.json` file. Serverless offline will be available on port `:4000`. 2 jest configurations are also provided which will allow to run a test or multiple tests. + +For further information about debugging, please refer to the following documentation: + +- [Run-a-function-locally-on-source-changes](https://github.com/serverless-heaven/serverless-webpack#run-a-function-locally-on-source-changes) + +- [VSCode debugging](https://github.com/serverless-heaven/serverless-webpack#vscode-debugging) + +- [Debug process section](https://www.serverless.com/plugins/serverless-offline#usage-with-webpack) + +### Unit + +Jest is used for unit testing. +Please refer to the [Jest documentation](https://jestjs.io/docs/en/getting-started) for further details. + +### Integration + +To be added and customised depending on needs, supertest is used but we could be looking at other packages such as nock, ts-mockito, typemoq, wiremock, etc.. or testing (pactjs, hoverfly, mockserver, etc..) + +## Infrastructure + + + +### Release + +Releases (tag, release notes, changelog, github release, assets) are automatically managed by [semantic-release](https://semantic-release.gitbook.io/semantic-release/) and when pushing (or merging) to `master` branch which is protected. [semver](https://semver.org/) convention is followed. + +Please be familiar with conventional commit as described in the Contributing section below. + +Default preset used is angular for conventional commits, please see the [angular conventions](https://github.com/conventional-changelog/commitlint/tree/master/%40commitlint/config-conventional#type-enum). + +The `` `'breaking'` in the commit message will trigger a major version bump as well as any of the following text contained in the commit body: `"BREAKING CHANGE", "BREAKING CHANGES", "BREAKING_CHANGES", "BREAKING", "BREAKING_CHANGE"`. Please refer to the `.releaserc.json` file for the full configuration. + +The script `npm run release` will automatically trigger the release in CI. To manually test the release the following flags -`--dry-run --no-ci` - can be passed to the release script. + +Publishing and artifacts are managed separately by the pipeline. + +## Contributing + +To facilitate the standardisation of the code, a few helpers and tools have been adopted for this repository. + +### External dependencies + +The project depends on the cvs-nop repository as a git module. Use `--recurse-submodules` when cloning the project to automatically set up the submodule, or use `git submodule init` followed by `git submodule update` to pull the submodule in if you already have the project checked out. + +The projects has multiple hooks configured using [husky](https://github.com/typicode/husky#readme) which will execute the following scripts: `audit`, `lint`, `build`, `test` and format your code with [eslint](https://github.com/typescript-eslint/typescript-eslint#readme) and [prettier](https://github.com/prettier/prettier). + +You will be required to install [git-secrets](https://github.com/awslabs/git-secrets) (_brew approach is recommended_) and DVSA [repo-security-scanner](https://github.com/UKHomeOffice/repo-security-scanner) that runs against your git log history to find accidentally committed passwords, private keys. + +We follow the [conventional commit format](https://www.conventionalcommits.org/en/v1.0.0/) when we commit code to the repository and follow the [angular convention](https://github.com/conventional-changelog/commitlint/tree/master/%40commitlint/config-conventional#type-enum). + +The type is mandatory and must be all lowercase. +The scope of your commit remain is also mandatory, it must include your ticket number and be all lowercase. The format for the ticket number can be set in the commitlint.config.js file. + +```js +// Please see /commitlint.config.js for customised format + +type(scope?): subject + +// examples +'chore(cvsb-1234): my commit msg' // pass +'CHORE(cvsb-1234): my commit msg' // will fail + +``` + +### Code standards + +#### Code structure + +Domain Drive Design diagram with Interfaces, Application, Domain layers and Infrastructure across the layers. + +

+ Domain Drive Design diagram with Interfaces, Application, Domain layers and Infrastructure across the layers +

+ +Please refer to the the [docs](./docs/README.md) for the API specification and samples of postman requests. + +#### Toolings + +The code uses [eslint](https://eslint.org/docs/user-guide/getting-started), [typescript clean code standards](https://github.com/labs42io/clean-code-typescript) as well as sonarqube for static analysis. +SonarQube is available locally, please follow the instructions below if you wish to run the service locally (brew is the preferred approach): + +- _Brew_: + + - Install sonarqube using brew + - Change `sonar.host.url` to point to localhost, by default, sonar runs on `http://localhost:9000` + - run the sonar server `sonar start`, then perform your analysis `npm run sonar-scanner` + +- _Manual_: + - Add sonar-scanner in environment variables in your \_profile file add the line: `export PATH=/sonar-scanner-3.3.0.1492-macosx/bin:$PATH` + - Start the SonarQube server: `cd /bin/macosx-universal-64 ./sonar.sh start` + - In the microservice folder run the command: `npm run sonar-scanner` diff --git a/commitlint.config.js b/application/enquiry/commitlint.config.js similarity index 100% rename from commitlint.config.js rename to application/enquiry/commitlint.config.js diff --git a/config/env.example b/application/enquiry/config/env.example similarity index 100% rename from config/env.example rename to application/enquiry/config/env.example diff --git a/docs/DDD_architecture.jpg b/application/enquiry/docs/DDD_architecture.jpg similarity index 100% rename from docs/DDD_architecture.jpg rename to application/enquiry/docs/DDD_architecture.jpg diff --git a/docs/README.md b/application/enquiry/docs/README.md similarity index 100% rename from docs/README.md rename to application/enquiry/docs/README.md diff --git a/docs/enquiry.postman_collection.json b/application/enquiry/docs/enquiry.postman_collection.json similarity index 100% rename from docs/enquiry.postman_collection.json rename to application/enquiry/docs/enquiry.postman_collection.json diff --git a/docs/spec.yml b/application/enquiry/docs/spec.yml similarity index 100% rename from docs/spec.yml rename to application/enquiry/docs/spec.yml diff --git a/jest.config.ts b/application/enquiry/jest.config.ts similarity index 100% rename from jest.config.ts rename to application/enquiry/jest.config.ts diff --git a/local/data/base-path.json b/application/enquiry/local/data/base-path.json similarity index 100% rename from local/data/base-path.json rename to application/enquiry/local/data/base-path.json diff --git a/local/data/version.json b/application/enquiry/local/data/version.json similarity index 100% rename from local/data/version.json rename to application/enquiry/local/data/version.json diff --git a/package-lock.json b/application/enquiry/package-lock.json similarity index 100% rename from package-lock.json rename to application/enquiry/package-lock.json diff --git a/package.json b/application/enquiry/package.json similarity index 100% rename from package.json rename to application/enquiry/package.json diff --git a/scripts/webpack.config.build.js b/application/enquiry/scripts/webpack.config.build.js similarity index 100% rename from scripts/webpack.config.build.js rename to application/enquiry/scripts/webpack.config.build.js diff --git a/scripts/webpack.config.js b/application/enquiry/scripts/webpack.config.js similarity index 100% rename from scripts/webpack.config.js rename to application/enquiry/scripts/webpack.config.js diff --git a/serverless.yml b/application/enquiry/serverless.yml similarity index 100% rename from serverless.yml rename to application/enquiry/serverless.yml diff --git a/sonar-project.properties b/application/enquiry/sonar-project.properties similarity index 100% rename from sonar-project.properties rename to application/enquiry/sonar-project.properties diff --git a/src/app/databaseService.ts b/application/enquiry/src/app/databaseService.ts similarity index 100% rename from src/app/databaseService.ts rename to application/enquiry/src/app/databaseService.ts diff --git a/src/app/evlFeedQueryFunctionFactory.ts b/application/enquiry/src/app/evlFeedQueryFunctionFactory.ts similarity index 100% rename from src/app/evlFeedQueryFunctionFactory.ts rename to application/enquiry/src/app/evlFeedQueryFunctionFactory.ts diff --git a/src/app/use_cases/index.ts b/application/enquiry/src/app/index.ts similarity index 100% rename from src/app/use_cases/index.ts rename to application/enquiry/src/app/index.ts diff --git a/src/app/queries/evlQuery.ts b/application/enquiry/src/app/queries/evlQuery.ts similarity index 100% rename from src/app/queries/evlQuery.ts rename to application/enquiry/src/app/queries/evlQuery.ts diff --git a/src/app/queries/technicalRecord/axleQuery.ts b/application/enquiry/src/app/queries/technicalRecord/axleQuery.ts similarity index 100% rename from src/app/queries/technicalRecord/axleQuery.ts rename to application/enquiry/src/app/queries/technicalRecord/axleQuery.ts diff --git a/src/app/queries/technicalRecord/axleSpacingQuery.ts b/application/enquiry/src/app/queries/technicalRecord/axleSpacingQuery.ts similarity index 100% rename from src/app/queries/technicalRecord/axleSpacingQuery.ts rename to application/enquiry/src/app/queries/technicalRecord/axleSpacingQuery.ts diff --git a/src/app/queries/technicalRecord/brakeQuery.ts b/application/enquiry/src/app/queries/technicalRecord/brakeQuery.ts similarity index 100% rename from src/app/queries/technicalRecord/brakeQuery.ts rename to application/enquiry/src/app/queries/technicalRecord/brakeQuery.ts diff --git a/src/app/queries/technicalRecord/index.ts b/application/enquiry/src/app/queries/technicalRecord/index.ts similarity index 100% rename from src/app/queries/technicalRecord/index.ts rename to application/enquiry/src/app/queries/technicalRecord/index.ts diff --git a/src/app/queries/technicalRecord/platingQuery.ts b/application/enquiry/src/app/queries/technicalRecord/platingQuery.ts similarity index 100% rename from src/app/queries/technicalRecord/platingQuery.ts rename to application/enquiry/src/app/queries/technicalRecord/platingQuery.ts diff --git a/src/app/queries/technicalRecord/technicalRecordQuery.ts b/application/enquiry/src/app/queries/technicalRecord/technicalRecordQuery.ts similarity index 100% rename from src/app/queries/technicalRecord/technicalRecordQuery.ts rename to application/enquiry/src/app/queries/technicalRecord/technicalRecordQuery.ts diff --git a/src/app/queries/technicalRecord/vehicleDetailsQuery.ts b/application/enquiry/src/app/queries/technicalRecord/vehicleDetailsQuery.ts similarity index 100% rename from src/app/queries/technicalRecord/vehicleDetailsQuery.ts rename to application/enquiry/src/app/queries/technicalRecord/vehicleDetailsQuery.ts diff --git a/src/app/queries/testResults/customDefectQuery.ts b/application/enquiry/src/app/queries/testResults/customDefectQuery.ts similarity index 100% rename from src/app/queries/testResults/customDefectQuery.ts rename to application/enquiry/src/app/queries/testResults/customDefectQuery.ts diff --git a/src/app/queries/testResults/index.ts b/application/enquiry/src/app/queries/testResults/index.ts similarity index 100% rename from src/app/queries/testResults/index.ts rename to application/enquiry/src/app/queries/testResults/index.ts diff --git a/src/app/queries/testResults/testDefectQuery.ts b/application/enquiry/src/app/queries/testResults/testDefectQuery.ts similarity index 100% rename from src/app/queries/testResults/testDefectQuery.ts rename to application/enquiry/src/app/queries/testResults/testDefectQuery.ts diff --git a/src/app/queries/testResults/testResultQuery.ts b/application/enquiry/src/app/queries/testResults/testResultQuery.ts similarity index 100% rename from src/app/queries/testResults/testResultQuery.ts rename to application/enquiry/src/app/queries/testResults/testResultQuery.ts diff --git a/src/app/queries/tflQuery.ts b/application/enquiry/src/app/queries/tflQuery.ts similarity index 100% rename from src/app/queries/tflQuery.ts rename to application/enquiry/src/app/queries/tflQuery.ts diff --git a/src/app/testResultsQueryFunctionFactory.ts b/application/enquiry/src/app/testResultsQueryFunctionFactory.ts similarity index 100% rename from src/app/testResultsQueryFunctionFactory.ts rename to application/enquiry/src/app/testResultsQueryFunctionFactory.ts diff --git a/src/app/tflFeedQueryFunctionFactory.ts b/application/enquiry/src/app/tflFeedQueryFunctionFactory.ts similarity index 100% rename from src/app/tflFeedQueryFunctionFactory.ts rename to application/enquiry/src/app/tflFeedQueryFunctionFactory.ts diff --git a/src/domain/index.ts b/application/enquiry/src/app/use_cases/index.ts similarity index 100% rename from src/domain/index.ts rename to application/enquiry/src/app/use_cases/index.ts diff --git a/src/app/vehicleQueryFunctionFactory.ts b/application/enquiry/src/app/vehicleQueryFunctionFactory.ts similarity index 100% rename from src/app/vehicleQueryFunctionFactory.ts rename to application/enquiry/src/app/vehicleQueryFunctionFactory.ts diff --git a/src/constants.ts b/application/enquiry/src/constants.ts similarity index 100% rename from src/constants.ts rename to application/enquiry/src/constants.ts diff --git a/src/domain/enquiryService.ts b/application/enquiry/src/domain/enquiryService.ts similarity index 100% rename from src/domain/enquiryService.ts rename to application/enquiry/src/domain/enquiryService.ts diff --git a/src/infrastructure/index.ts b/application/enquiry/src/domain/index.ts similarity index 100% rename from src/infrastructure/index.ts rename to application/enquiry/src/domain/index.ts diff --git a/src/errors/InvalidIdentifierError.ts b/application/enquiry/src/errors/InvalidIdentifierError.ts similarity index 100% rename from src/errors/InvalidIdentifierError.ts rename to application/enquiry/src/errors/InvalidIdentifierError.ts diff --git a/src/errors/MissingSecretError.ts b/application/enquiry/src/errors/MissingSecretError.ts similarity index 100% rename from src/errors/MissingSecretError.ts rename to application/enquiry/src/errors/MissingSecretError.ts diff --git a/src/errors/NotFoundError.ts b/application/enquiry/src/errors/NotFoundError.ts similarity index 100% rename from src/errors/NotFoundError.ts rename to application/enquiry/src/errors/NotFoundError.ts diff --git a/src/errors/ParametersError.ts b/application/enquiry/src/errors/ParametersError.ts similarity index 100% rename from src/errors/ParametersError.ts rename to application/enquiry/src/errors/ParametersError.ts diff --git a/src/handler.ts b/application/enquiry/src/handler.ts similarity index 100% rename from src/handler.ts rename to application/enquiry/src/handler.ts diff --git a/src/infrastructure/api/index.ts b/application/enquiry/src/infrastructure/api/index.ts similarity index 100% rename from src/infrastructure/api/index.ts rename to application/enquiry/src/infrastructure/api/index.ts diff --git a/src/infrastructure/databaseService.ts b/application/enquiry/src/infrastructure/databaseService.ts similarity index 100% rename from src/infrastructure/databaseService.ts rename to application/enquiry/src/infrastructure/databaseService.ts diff --git a/src/interfaces/index.ts b/application/enquiry/src/infrastructure/index.ts similarity index 100% rename from src/interfaces/index.ts rename to application/enquiry/src/infrastructure/index.ts diff --git a/src/infrastructure/localSecretsManagerService.ts b/application/enquiry/src/infrastructure/localSecretsManagerService.ts similarity index 100% rename from src/infrastructure/localSecretsManagerService.ts rename to application/enquiry/src/infrastructure/localSecretsManagerService.ts diff --git a/src/infrastructure/s3BucketService.ts b/application/enquiry/src/infrastructure/s3BucketService.ts similarity index 100% rename from src/infrastructure/s3BucketService.ts rename to application/enquiry/src/infrastructure/s3BucketService.ts diff --git a/src/infrastructure/secretsManagerService.ts b/application/enquiry/src/infrastructure/secretsManagerService.ts similarity index 100% rename from src/infrastructure/secretsManagerService.ts rename to application/enquiry/src/infrastructure/secretsManagerService.ts diff --git a/src/interfaces/DatabaseService.ts b/application/enquiry/src/interfaces/DatabaseService.ts similarity index 100% rename from src/interfaces/DatabaseService.ts rename to application/enquiry/src/interfaces/DatabaseService.ts diff --git a/src/interfaces/EvlEvent.ts b/application/enquiry/src/interfaces/EvlEvent.ts similarity index 100% rename from src/interfaces/EvlEvent.ts rename to application/enquiry/src/interfaces/EvlEvent.ts diff --git a/src/interfaces/FeedTypes.ts b/application/enquiry/src/interfaces/FeedTypes.ts similarity index 100% rename from src/interfaces/FeedTypes.ts rename to application/enquiry/src/interfaces/FeedTypes.ts diff --git a/src/interfaces/ResultsEvent.ts b/application/enquiry/src/interfaces/ResultsEvent.ts similarity index 100% rename from src/interfaces/ResultsEvent.ts rename to application/enquiry/src/interfaces/ResultsEvent.ts diff --git a/src/interfaces/SecretsManagerService.ts b/application/enquiry/src/interfaces/SecretsManagerService.ts similarity index 100% rename from src/interfaces/SecretsManagerService.ts rename to application/enquiry/src/interfaces/SecretsManagerService.ts diff --git a/src/interfaces/VehicleEvent.ts b/application/enquiry/src/interfaces/VehicleEvent.ts similarity index 100% rename from src/interfaces/VehicleEvent.ts rename to application/enquiry/src/interfaces/VehicleEvent.ts diff --git a/src/interfaces/controllers/index..ts b/application/enquiry/src/interfaces/controllers/index..ts similarity index 100% rename from src/interfaces/controllers/index..ts rename to application/enquiry/src/interfaces/controllers/index..ts diff --git a/src/interfaces/middlewares/index.ts b/application/enquiry/src/interfaces/index.ts similarity index 100% rename from src/interfaces/middlewares/index.ts rename to application/enquiry/src/interfaces/index.ts diff --git a/src/interfaces/routes/index.ts b/application/enquiry/src/interfaces/middlewares/index.ts similarity index 100% rename from src/interfaces/routes/index.ts rename to application/enquiry/src/interfaces/middlewares/index.ts diff --git a/src/interfaces/queryResults/evlFeedData.ts b/application/enquiry/src/interfaces/queryResults/evlFeedData.ts similarity index 100% rename from src/interfaces/queryResults/evlFeedData.ts rename to application/enquiry/src/interfaces/queryResults/evlFeedData.ts diff --git a/src/interfaces/queryResults/technical/axleSpacing.ts b/application/enquiry/src/interfaces/queryResults/technical/axleSpacing.ts similarity index 100% rename from src/interfaces/queryResults/technical/axleSpacing.ts rename to application/enquiry/src/interfaces/queryResults/technical/axleSpacing.ts diff --git a/src/interfaces/queryResults/technical/axles.ts b/application/enquiry/src/interfaces/queryResults/technical/axles.ts similarity index 100% rename from src/interfaces/queryResults/technical/axles.ts rename to application/enquiry/src/interfaces/queryResults/technical/axles.ts diff --git a/src/interfaces/queryResults/technical/makeModel.ts b/application/enquiry/src/interfaces/queryResults/technical/makeModel.ts similarity index 100% rename from src/interfaces/queryResults/technical/makeModel.ts rename to application/enquiry/src/interfaces/queryResults/technical/makeModel.ts diff --git a/src/interfaces/queryResults/technical/plate.ts b/application/enquiry/src/interfaces/queryResults/technical/plate.ts similarity index 100% rename from src/interfaces/queryResults/technical/plate.ts rename to application/enquiry/src/interfaces/queryResults/technical/plate.ts diff --git a/src/interfaces/queryResults/technical/psvBrakes.ts b/application/enquiry/src/interfaces/queryResults/technical/psvBrakes.ts similarity index 100% rename from src/interfaces/queryResults/technical/psvBrakes.ts rename to application/enquiry/src/interfaces/queryResults/technical/psvBrakes.ts diff --git a/src/interfaces/queryResults/technical/technicalRecord.ts b/application/enquiry/src/interfaces/queryResults/technical/technicalRecord.ts similarity index 100% rename from src/interfaces/queryResults/technical/technicalRecord.ts rename to application/enquiry/src/interfaces/queryResults/technical/technicalRecord.ts diff --git a/src/interfaces/queryResults/technical/tyre.ts b/application/enquiry/src/interfaces/queryResults/technical/tyre.ts similarity index 100% rename from src/interfaces/queryResults/technical/tyre.ts rename to application/enquiry/src/interfaces/queryResults/technical/tyre.ts diff --git a/src/interfaces/queryResults/technical/vehicleDetails.ts b/application/enquiry/src/interfaces/queryResults/technical/vehicleDetails.ts similarity index 100% rename from src/interfaces/queryResults/technical/vehicleDetails.ts rename to application/enquiry/src/interfaces/queryResults/technical/vehicleDetails.ts diff --git a/src/interfaces/queryResults/test/customDefect.ts b/application/enquiry/src/interfaces/queryResults/test/customDefect.ts similarity index 100% rename from src/interfaces/queryResults/test/customDefect.ts rename to application/enquiry/src/interfaces/queryResults/test/customDefect.ts diff --git a/src/interfaces/queryResults/test/defect.ts b/application/enquiry/src/interfaces/queryResults/test/defect.ts similarity index 100% rename from src/interfaces/queryResults/test/defect.ts rename to application/enquiry/src/interfaces/queryResults/test/defect.ts diff --git a/src/interfaces/queryResults/test/fuelEmission.ts b/application/enquiry/src/interfaces/queryResults/test/fuelEmission.ts similarity index 100% rename from src/interfaces/queryResults/test/fuelEmission.ts rename to application/enquiry/src/interfaces/queryResults/test/fuelEmission.ts diff --git a/src/interfaces/queryResults/test/location.ts b/application/enquiry/src/interfaces/queryResults/test/location.ts similarity index 100% rename from src/interfaces/queryResults/test/location.ts rename to application/enquiry/src/interfaces/queryResults/test/location.ts diff --git a/src/interfaces/queryResults/test/testDefect.ts b/application/enquiry/src/interfaces/queryResults/test/testDefect.ts similarity index 100% rename from src/interfaces/queryResults/test/testDefect.ts rename to application/enquiry/src/interfaces/queryResults/test/testDefect.ts diff --git a/src/interfaces/queryResults/test/testResult.ts b/application/enquiry/src/interfaces/queryResults/test/testResult.ts similarity index 100% rename from src/interfaces/queryResults/test/testResult.ts rename to application/enquiry/src/interfaces/queryResults/test/testResult.ts diff --git a/src/interfaces/queryResults/test/testStation.ts b/application/enquiry/src/interfaces/queryResults/test/testStation.ts similarity index 100% rename from src/interfaces/queryResults/test/testStation.ts rename to application/enquiry/src/interfaces/queryResults/test/testStation.ts diff --git a/src/interfaces/queryResults/test/testType.ts b/application/enquiry/src/interfaces/queryResults/test/testType.ts similarity index 100% rename from src/interfaces/queryResults/test/testType.ts rename to application/enquiry/src/interfaces/queryResults/test/testType.ts diff --git a/src/interfaces/queryResults/test/tester.ts b/application/enquiry/src/interfaces/queryResults/test/tester.ts similarity index 100% rename from src/interfaces/queryResults/test/tester.ts rename to application/enquiry/src/interfaces/queryResults/test/tester.ts diff --git a/src/interfaces/queryResults/tflFeedData.ts b/application/enquiry/src/interfaces/queryResults/tflFeedData.ts similarity index 100% rename from src/interfaces/queryResults/tflFeedData.ts rename to application/enquiry/src/interfaces/queryResults/tflFeedData.ts diff --git a/src/interfaces/queryResults/vehicleClass.ts b/application/enquiry/src/interfaces/queryResults/vehicleClass.ts similarity index 100% rename from src/interfaces/queryResults/vehicleClass.ts rename to application/enquiry/src/interfaces/queryResults/vehicleClass.ts diff --git a/application/enquiry/src/interfaces/routes/index.ts b/application/enquiry/src/interfaces/routes/index.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/resources/changelog-master.xml b/application/enquiry/src/resources/changelog-master.xml similarity index 100% rename from src/resources/changelog-master.xml rename to application/enquiry/src/resources/changelog-master.xml diff --git a/src/resources/data-seed.sql b/application/enquiry/src/resources/data-seed.sql similarity index 100% rename from src/resources/data-seed.sql rename to application/enquiry/src/resources/data-seed.sql diff --git a/src/resources/localDatabase.ts b/application/enquiry/src/resources/localDatabase.ts similarity index 100% rename from src/resources/localDatabase.ts rename to application/enquiry/src/resources/localDatabase.ts diff --git a/src/resources/localDatabaseScript.ts b/application/enquiry/src/resources/localDatabaseScript.ts similarity index 100% rename from src/resources/localDatabaseScript.ts rename to application/enquiry/src/resources/localDatabaseScript.ts diff --git a/src/resources/mysql-connector-java-8.0.23.jar b/application/enquiry/src/resources/mysql-connector-java-8.0.23.jar similarity index 100% rename from src/resources/mysql-connector-java-8.0.23.jar rename to application/enquiry/src/resources/mysql-connector-java-8.0.23.jar diff --git a/src/utils/index.ts b/application/enquiry/src/utils/index.ts similarity index 100% rename from src/utils/index.ts rename to application/enquiry/src/utils/index.ts diff --git a/src/utils/logger.ts b/application/enquiry/src/utils/logger.ts similarity index 100% rename from src/utils/logger.ts rename to application/enquiry/src/utils/logger.ts diff --git a/src/utils/tflHelpers.ts b/application/enquiry/src/utils/tflHelpers.ts similarity index 100% rename from src/utils/tflHelpers.ts rename to application/enquiry/src/utils/tflHelpers.ts diff --git a/src/utils/validationService.ts b/application/enquiry/src/utils/validationService.ts similarity index 100% rename from src/utils/validationService.ts rename to application/enquiry/src/utils/validationService.ts diff --git a/tests/unit/app/databaseService.test.ts b/application/enquiry/tests/unit/app/databaseService.test.ts similarity index 100% rename from tests/unit/app/databaseService.test.ts rename to application/enquiry/tests/unit/app/databaseService.test.ts diff --git a/tests/unit/app/evlFeedQueryFunctionFactory.test.ts b/application/enquiry/tests/unit/app/evlFeedQueryFunctionFactory.test.ts similarity index 100% rename from tests/unit/app/evlFeedQueryFunctionFactory.test.ts rename to application/enquiry/tests/unit/app/evlFeedQueryFunctionFactory.test.ts diff --git a/tests/unit/app/testResultsQueryFunctionFactory.test.ts b/application/enquiry/tests/unit/app/testResultsQueryFunctionFactory.test.ts similarity index 100% rename from tests/unit/app/testResultsQueryFunctionFactory.test.ts rename to application/enquiry/tests/unit/app/testResultsQueryFunctionFactory.test.ts diff --git a/tests/unit/app/tflFeedQueryFunctionFactory.test.ts b/application/enquiry/tests/unit/app/tflFeedQueryFunctionFactory.test.ts similarity index 100% rename from tests/unit/app/tflFeedQueryFunctionFactory.test.ts rename to application/enquiry/tests/unit/app/tflFeedQueryFunctionFactory.test.ts diff --git a/tests/unit/app/vehicleQueryFunctionFactory.test.ts b/application/enquiry/tests/unit/app/vehicleQueryFunctionFactory.test.ts similarity index 100% rename from tests/unit/app/vehicleQueryFunctionFactory.test.ts rename to application/enquiry/tests/unit/app/vehicleQueryFunctionFactory.test.ts diff --git a/tests/unit/domain/enquiryService.test.ts b/application/enquiry/tests/unit/domain/enquiryService.test.ts similarity index 100% rename from tests/unit/domain/enquiryService.test.ts rename to application/enquiry/tests/unit/domain/enquiryService.test.ts diff --git a/tests/unit/getEnquiry.test.ts b/application/enquiry/tests/unit/getEnquiry.test.ts similarity index 100% rename from tests/unit/getEnquiry.test.ts rename to application/enquiry/tests/unit/getEnquiry.test.ts diff --git a/tests/unit/handler.test.ts b/application/enquiry/tests/unit/handler.test.ts similarity index 100% rename from tests/unit/handler.test.ts rename to application/enquiry/tests/unit/handler.test.ts diff --git a/tests/unit/infrastructure/api/index.test.ts b/application/enquiry/tests/unit/infrastructure/api/index.test.ts similarity index 100% rename from tests/unit/infrastructure/api/index.test.ts rename to application/enquiry/tests/unit/infrastructure/api/index.test.ts diff --git a/tests/unit/infrastructure/databaseService.test.ts b/application/enquiry/tests/unit/infrastructure/databaseService.test.ts similarity index 100% rename from tests/unit/infrastructure/databaseService.test.ts rename to application/enquiry/tests/unit/infrastructure/databaseService.test.ts diff --git a/tests/unit/infrastructure/s3BucketService.test.ts b/application/enquiry/tests/unit/infrastructure/s3BucketService.test.ts similarity index 100% rename from tests/unit/infrastructure/s3BucketService.test.ts rename to application/enquiry/tests/unit/infrastructure/s3BucketService.test.ts diff --git a/tests/unit/infrastructure/secretsManagerService.test.ts b/application/enquiry/tests/unit/infrastructure/secretsManagerService.test.ts similarity index 100% rename from tests/unit/infrastructure/secretsManagerService.test.ts rename to application/enquiry/tests/unit/infrastructure/secretsManagerService.test.ts diff --git a/tests/unit/resources/localDatabase.test.ts b/application/enquiry/tests/unit/resources/localDatabase.test.ts similarity index 100% rename from tests/unit/resources/localDatabase.test.ts rename to application/enquiry/tests/unit/resources/localDatabase.test.ts diff --git a/tests/unit/utils/index.test.ts b/application/enquiry/tests/unit/utils/index.test.ts similarity index 100% rename from tests/unit/utils/index.test.ts rename to application/enquiry/tests/unit/utils/index.test.ts diff --git a/tests/unit/utils/logger.test.ts b/application/enquiry/tests/unit/utils/logger.test.ts similarity index 100% rename from tests/unit/utils/logger.test.ts rename to application/enquiry/tests/unit/utils/logger.test.ts diff --git a/tests/unit/utils/tflHelpers.test.ts b/application/enquiry/tests/unit/utils/tflHelpers.test.ts similarity index 100% rename from tests/unit/utils/tflHelpers.test.ts rename to application/enquiry/tests/unit/utils/tflHelpers.test.ts diff --git a/tests/unit/utils/validationService.test.ts b/application/enquiry/tests/unit/utils/validationService.test.ts similarity index 100% rename from tests/unit/utils/validationService.test.ts rename to application/enquiry/tests/unit/utils/validationService.test.ts diff --git a/tsconfig.json b/application/enquiry/tsconfig.json similarity index 100% rename from tsconfig.json rename to application/enquiry/tsconfig.json diff --git a/cvs-nop b/cvs-nop deleted file mode 160000 index 39b9c83..0000000 --- a/cvs-nop +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 39b9c8301c3468ce1cfa8aa6bdd7145c84978e28 diff --git a/infrastructure/.terraform-version b/infrastructure/.terraform-version new file mode 100644 index 0000000..bb9ffd3 --- /dev/null +++ b/infrastructure/.terraform-version @@ -0,0 +1 @@ +latest:^1.8 diff --git a/infrastructure/api_deployment.tf b/infrastructure/api_deployment.tf new file mode 100644 index 0000000..b58d114 --- /dev/null +++ b/infrastructure/api_deployment.tf @@ -0,0 +1,65 @@ +resource "aws_api_gateway_deployment" "deployment" { + rest_api_id = aws_api_gateway_rest_api.this_gateway.id + # triggers = { + # spec = module.apigw.redeployment_spec + # workspace = terraform.workspace + # } + lifecycle { + create_before_destroy = true + } +} + +resource "aws_api_gateway_stage" "stage" { + rest_api_id = aws_api_gateway_rest_api.this_gateway.id + deployment_id = aws_api_gateway_deployment.deployment.id + stage_name = "v1" + xray_tracing_enabled = true + + tags = { + Environment = terraform.workspace + } + depends_on = [aws_api_gateway_deployment.deployment] + lifecycle { + create_before_destroy = true + } +} + +resource "aws_api_gateway_method_settings" "settings" { + rest_api_id = aws_api_gateway_stage.stage.rest_api_id + stage_name = aws_api_gateway_stage.stage.stage_name + method_path = "*/*" + + settings { + data_trace_enabled = true + logging_level = "INFO" + metrics_enabled = true + } +} + +# resource "aws_api_gateway_base_path_mapping" "main" { +# api_id = aws_api_gateway_stage.stage.rest_api_id +# stage_name = aws_api_gateway_stage.stage.stage_name +# domain_name = local.api_domain +# base_path = aws_api_gateway_stage.stage.stage_name +# depends_on = [aws_api_gateway_stage.stage] +# lifecycle { +# create_before_destroy = true +# } +# } + +resource "aws_cloudwatch_metric_alarm" "api-5XX" { + count = var.enable_cw_alarms ? 1 : 0 + alarm_name = "${terraform.workspace}-API-5XXErrors" + comparison_operator = "GreaterThanOrEqualToThreshold" + evaluation_periods = 2 + threshold = 1 + period = 60 + unit = "Count" + + namespace = "AWS/ApiGateway" + metric_name = "5XXError" + statistic = "Maximum" + dimensions = { + ApiName = terraform.workspace + } +} \ No newline at end of file diff --git a/infrastructure/api_enquiry_test_results.tf b/infrastructure/api_enquiry_test_results.tf new file mode 100644 index 0000000..3b976be --- /dev/null +++ b/infrastructure/api_enquiry_test_results.tf @@ -0,0 +1,57 @@ +resource "aws_api_gateway_resource" "resource" { + for_each = local.api_resources + parent_id = aws_api_gateway_resource.enquiry.id + path_part = each.key + rest_api_id = aws_api_gateway_rest_api.this_gateway.id +} + +resource "aws_api_gateway_method" "resource" { + for_each = local.api_resources + authorization = "NONE" + http_method = "ANY" + resource_id = aws_api_gateway_resource.resource[each.key].id + rest_api_id = aws_api_gateway_rest_api.this_gateway.id + # authorizer_id = aws_api_gateway_authorizer.lambda_auth.id + # api_key_required = true +} + + +resource "aws_api_gateway_method_response" "response_200" { + for_each = local.api_resources + rest_api_id = aws_api_gateway_rest_api.this_gateway.id + resource_id = aws_api_gateway_resource.resource[each.key].id + http_method = aws_api_gateway_method.resource[each.key].http_method + status_code = "200" + response_parameters = { + "method.response.header.Access-Control-Allow-Methods" : true, + "method.response.header.Access-Control-Allow-Headers" : true, + "method.response.header.Access-Control-Allow-Origin" : true + } + response_models = { + "application/json" = "EmptySchema" + } +} + +resource "aws_api_gateway_integration" "resource" { + for_each = local.api_resources + rest_api_id = aws_api_gateway_rest_api.this_gateway.id + resource_id = aws_api_gateway_resource.resource[each.key].id + http_method = aws_api_gateway_method.resource[each.key].http_method + integration_http_method = "POST" + type = "AWS_PROXY" + timeout_milliseconds = 29000 + passthrough_behavior = "WHEN_NO_MATCH" + content_handling = "CONVERT_TO_TEXT" + uri = "arn:aws:apigateway:eu-west-1:lambda:path/2015-03-31/functions/arn:aws:lambda:eu-west-1:${var.AWS_ACCOUNT}:function:${module.enquiry_lambda.function_name}/invocations" +} + +resource "aws_api_gateway_integration_response" "resource" { + for_each = local.api_resources + rest_api_id = aws_api_gateway_rest_api.this_gateway.id + resource_id = aws_api_gateway_resource.resource[each.key].id + http_method = aws_api_gateway_method.resource[each.key].http_method + status_code = aws_api_gateway_method_response.response_200[each.key].status_code + depends_on = [ + aws_api_gateway_integration.resource + ] +} diff --git a/infrastructure/api_enquiry_vehicle.tf.bak b/infrastructure/api_enquiry_vehicle.tf.bak new file mode 100644 index 0000000..1f509bc --- /dev/null +++ b/infrastructure/api_enquiry_vehicle.tf.bak @@ -0,0 +1,60 @@ +resource "aws_api_gateway_resource" "enquiry_vehicle" { + parent_id = aws_api_gateway_resource.enquiry.id + path_part = "vehicle" + rest_api_id = aws_api_gateway_rest_api.this_gateway.id +} + +resource "aws_api_gateway_method" "enquiry_vehicle" { + authorization = "NONE" + http_method = "ANY" + resource_id = aws_api_gateway_resource.enquiry_vehicle.id + rest_api_id = aws_api_gateway_rest_api.this_gateway.id + # authorizer_id = aws_api_gateway_authorizer.lambda_auth.id + # api_key_required = true +} + +# module "enquiry_vehicle_options" { +# source = "./standardendpoint" +# account_id = var.account_id +# authoriser_id = aws_api_gateway_authorizer.lambda_auth.id +# resource_id = aws_api_gateway_resource.enquiry_vehicle.id +# api_id = aws_api_gateway_rest_api.this_gateway.id +# include_verb = false +# } + +resource "aws_api_gateway_method_response" "enquiry_vehicle_200" { + rest_api_id = aws_api_gateway_rest_api.this_gateway.id + resource_id = aws_api_gateway_resource.enquiry_vehicle.id + http_method = aws_api_gateway_method.enquiry_vehicle.http_method + status_code = "200" + response_parameters = { + "method.response.header.Access-Control-Allow-Methods" : true, + "method.response.header.Access-Control-Allow-Headers" : true, + "method.response.header.Access-Control-Allow-Origin" : true + } + response_models = { + "application/json" = "EmptySchema" + } +} + +resource "aws_api_gateway_integration" "enquiry_vehicle" { + rest_api_id = aws_api_gateway_rest_api.this_gateway.id + resource_id = aws_api_gateway_resource.enquiry_vehicle.id + http_method = aws_api_gateway_method.enquiry_vehicle.http_method + integration_http_method = "POST" + type = "AWS_PROXY" + timeout_milliseconds = 29000 + passthrough_behavior = "WHEN_NO_MATCH" + content_handling = "CONVERT_TO_TEXT" + uri = "arn:aws:apigateway:eu-west-1:lambda:path/2015-03-31/functions/arn:aws:lambda:eu-west-1:${var.AWS_ACCOUNT}:function:${module.enquiry_lambda.function_name}/invocations" +} + +resource "aws_api_gateway_integration_response" "enquiry_vehicle" { + rest_api_id = aws_api_gateway_rest_api.this_gateway.id + resource_id = aws_api_gateway_resource.enquiry_vehicle.id + http_method = aws_api_gateway_method.enquiry_vehicle.http_method + status_code = aws_api_gateway_method_response.enquiry_vehicle_200.status_code + depends_on = [ + aws_api_gateway_integration.enquiry_vehicle + ] +} diff --git a/infrastructure/api_gateway.tf b/infrastructure/api_gateway.tf new file mode 100644 index 0000000..34ffbaa --- /dev/null +++ b/infrastructure/api_gateway.tf @@ -0,0 +1,58 @@ +resource "aws_api_gateway_rest_api" "this_gateway" { + name = "enquiries-${terraform.workspace}" + binary_media_types = ["application/octet-stream"] + tags = local.tags +} + +resource "aws_api_gateway_gateway_response" "default_4xx" { + rest_api_id = aws_api_gateway_rest_api.this_gateway.id + response_type = "DEFAULT_4XX" + + response_templates = { + "application/json" = "{\"message\":$context.error.messageString}" + } + + response_parameters = { + "gatewayresponse.header.Access-Control-Allow-Methods" : "'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT'", + "gatewayresponse.header.Access-Control-Allow-Origin" : "'*'", + "gatewayresponse.header.Access-Control-Allow-Headers" : "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'" + } +} + +resource "aws_api_gateway_gateway_response" "default_5xx" { + rest_api_id = aws_api_gateway_rest_api.this_gateway.id + response_type = "DEFAULT_5XX" + + response_templates = { + "application/json" = "{\"message\":$context.error.messageString}" + } + + response_parameters = { + "gatewayresponse.header.Access-Control-Allow-Methods" : "'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT'", + "gatewayresponse.header.Access-Control-Allow-Origin" : "'*'", + "gatewayresponse.header.Access-Control-Allow-Headers" : "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'" + } +} + + +resource "aws_api_gateway_resource" "enquiry" { + parent_id = aws_api_gateway_rest_api.this_gateway.root_resource_id + path_part = "enquiry" + rest_api_id = aws_api_gateway_rest_api.this_gateway.id + depends_on = [aws_api_gateway_model.EmptySchema] +} + +resource "aws_api_gateway_model" "EmptySchema" { + rest_api_id = aws_api_gateway_rest_api.this_gateway.id + name = "EmptySchema" + description = "Empty Schema" + content_type = "application/json" + + schema = < + + + + + + + + \ No newline at end of file diff --git a/infrastructure/modules/api_gw/api_logs.tf b/infrastructure/modules/api_gw/api_logs.tf new file mode 100644 index 0000000..77600b3 --- /dev/null +++ b/infrastructure/modules/api_gw/api_logs.tf @@ -0,0 +1,32 @@ +# TODO - Remove these log parts in the future and use the new log endpoint for a simpler logging method. +resource "aws_api_gateway_resource" "logs" { + parent_id = aws_api_gateway_rest_api.apigw.root_resource_id + path_part = "logs" + rest_api_id = aws_api_gateway_rest_api.apigw.id + depends_on = [aws_api_gateway_model.EmptySchema] +} + +module "logs" { + source = "./standardendpoint" + account_id = var.account_id + authoriser_id = aws_api_gateway_authorizer.lambda_auth.id + resource_id = aws_api_gateway_resource.logs.id + api_id = aws_api_gateway_rest_api.apigw.id + lambda_name = var.lambdas.logs +} + +resource "aws_api_gateway_resource" "unauth_logs" { + parent_id = aws_api_gateway_rest_api.apigw.root_resource_id + path_part = "unauth-logs" + rest_api_id = aws_api_gateway_rest_api.apigw.id + depends_on = [aws_api_gateway_model.EmptySchema] +} + +module "unauth_logs" { + source = "./standardendpoint" + account_id = var.account_id + authoriser_id = aws_api_gateway_authorizer.lambda_auth.id + resource_id = aws_api_gateway_resource.unauth_logs.id + api_id = aws_api_gateway_rest_api.apigw.id + lambda_name = var.lambdas.logs +} diff --git a/infrastructure/modules/api_gw/api_minimum_version.tf b/infrastructure/modules/api_gw/api_minimum_version.tf new file mode 100644 index 0000000..26923f4 --- /dev/null +++ b/infrastructure/modules/api_gw/api_minimum_version.tf @@ -0,0 +1,15 @@ +resource "aws_api_gateway_resource" "minimum_version" { + parent_id = aws_api_gateway_rest_api.apigw.root_resource_id + path_part = "minimum-version" + rest_api_id = aws_api_gateway_rest_api.apigw.id + depends_on = [aws_api_gateway_model.EmptySchema] +} + +module "minimum_version" { + source = "./standardendpoint" + account_id = var.account_id + authoriser_id = aws_api_gateway_authorizer.lambda_auth.id + resource_id = aws_api_gateway_resource.minimum_version.id + api_id = aws_api_gateway_rest_api.apigw.id + lambda_name = var.lambdas.minimum_application_version +} \ No newline at end of file diff --git a/infrastructure/modules/api_gw/api_s3_get.tf b/infrastructure/modules/api_gw/api_s3_get.tf new file mode 100644 index 0000000..e56e150 --- /dev/null +++ b/infrastructure/modules/api_gw/api_s3_get.tf @@ -0,0 +1,85 @@ +resource "aws_api_gateway_method" "s3_get" { + authorization = "CUSTOM" + http_method = "GET" + resource_id = aws_api_gateway_resource.item.id + rest_api_id = aws_api_gateway_rest_api.apigw.id + authorizer_id = aws_api_gateway_authorizer.lambda_auth.id + request_parameters = { + "method.request.header.Accept" = true + "method.request.path.item" = true + "method.request.path.folder" = true + } +} + +resource "aws_api_gateway_integration" "s3_get" { + rest_api_id = aws_api_gateway_rest_api.apigw.id + resource_id = aws_api_gateway_resource.item.id + http_method = aws_api_gateway_method.s3_get.http_method + integration_http_method = "GET" + type = "AWS" + timeout_milliseconds = 29000 + passthrough_behavior = "WHEN_NO_MATCH" + credentials = aws_iam_role.apigw_s3_cvs_signature_access_role.arn + uri = "arn:aws:apigateway:eu-west-1:s3:path/{bucket}/{object}" + request_parameters = { + "integration.request.path.object" = "method.request.path.item", + "integration.request.path.bucket" = "method.request.path.folder", + "integration.request.header.Accept" = "method.request.header.Accept" + } +} + +resource "aws_api_gateway_integration_response" "s3_get_201" { + rest_api_id = aws_api_gateway_rest_api.apigw.id + resource_id = aws_api_gateway_resource.item.id + http_method = aws_api_gateway_method.s3_get.http_method + status_code = "201" + response_parameters = { + "method.response.header.Access-Control-Allow-Origin" : "'*'" + } + depends_on = [ + aws_api_gateway_integration.s3_get + ] +} + +resource "aws_api_gateway_method_response" "s3_get_201" { + rest_api_id = aws_api_gateway_rest_api.apigw.id + resource_id = aws_api_gateway_resource.item.id + http_method = aws_api_gateway_method.s3_get.http_method + status_code = "201" + response_parameters = { + "method.response.header.Access-Control-Allow-Origin" : true + } + response_models = { + "application/json" = "Empty" + } + depends_on = [ + aws_api_gateway_integration.s3_get + ] +} + +resource "aws_api_gateway_method_response" "s3_get_non_201" { + for_each = toset(["301", "307", "400", "403", "404", "405", "409", "411", "412", "416", "500", "501", "503"]) + rest_api_id = aws_api_gateway_rest_api.apigw.id + resource_id = aws_api_gateway_resource.item.id + http_method = aws_api_gateway_method.s3_get.http_method + status_code = each.key + response_parameters = { + "method.response.header.Access-Control-Allow-Origin" : true + } +} + +resource "aws_api_gateway_integration_response" "s3_get_non_201" { + for_each = toset(["301", "307", "400", "403", "404", "405", "409", "411", "412", "416", "500", "501", "503"]) + rest_api_id = aws_api_gateway_rest_api.apigw.id + resource_id = aws_api_gateway_resource.item.id + http_method = aws_api_gateway_method.s3_get.http_method + selection_pattern = each.key + status_code = each.key + response_parameters = { + "method.response.header.Access-Control-Allow-Origin" : "'*'" + } + + depends_on = [ + aws_api_gateway_integration.s3_get + ] +} diff --git a/infrastructure/modules/api_gw/api_s3_options.tf b/infrastructure/modules/api_gw/api_s3_options.tf new file mode 100644 index 0000000..c0c7f55 --- /dev/null +++ b/infrastructure/modules/api_gw/api_s3_options.tf @@ -0,0 +1,52 @@ +resource "aws_api_gateway_method" "s3_options" { + authorization = "NONE" + http_method = "OPTIONS" + resource_id = aws_api_gateway_resource.item.id + rest_api_id = aws_api_gateway_rest_api.apigw.id +} + +resource "aws_api_gateway_method_response" "s3_options_response_200" { + rest_api_id = aws_api_gateway_rest_api.apigw.id + resource_id = aws_api_gateway_resource.item.id + http_method = aws_api_gateway_method.s3_options.http_method + status_code = "200" + response_parameters = { + "method.response.header.Access-Control-Allow-Methods" : false, + "method.response.header.Access-Control-Allow-Headers" : false, + "method.response.header.Access-Control-Allow-Origin" : false + } + response_models = { + "application/json" = "Empty" + } + depends_on = [aws_api_gateway_model.EmptySchema] +} + +resource "aws_api_gateway_integration" "s3_options" { + rest_api_id = aws_api_gateway_rest_api.apigw.id + resource_id = aws_api_gateway_resource.item.id + http_method = aws_api_gateway_method.s3_options.http_method + type = "MOCK" + timeout_milliseconds = 29000 + passthrough_behavior = "WHEN_NO_MATCH" + + request_templates = { + "application/json" = < 1000), + #set($dynamoKey = "{""resourceType"":{""S"":""$inputRoot.Items.get(999).resourceType.S""}, ""resourceKey"":{""S"":""$inputRoot.Items.get(999).resourceKey.S""}}") +"paginationToken":"$util.base64Encode($dynamoKey)" + #end +} +#end +EOF + } + + reference_data_item_response_template = { + "application/json" = < "$.detail.${path}" } + ) + input_template = var.target_input_template + } + + dead_letter_config { + arn = aws_sqs_queue.dlq.arn + } +} diff --git a/infrastructure/modules/eventbridge/cloudwatch_event_target_lambda.tf b/infrastructure/modules/eventbridge/cloudwatch_event_target_lambda.tf new file mode 100644 index 0000000..0072323 --- /dev/null +++ b/infrastructure/modules/eventbridge/cloudwatch_event_target_lambda.tf @@ -0,0 +1,6 @@ +resource "aws_cloudwatch_event_target" "lambda" { + count = var.rule_schedule_expression == "" ? 0 : 1 + arn = var.event_target_lambda + rule = aws_cloudwatch_event_rule.lambda[count.index].name + target_id = local.csi +} diff --git a/infrastructure/modules/eventbridge/cloudwatch_event_target_lambda_main.tf b/infrastructure/modules/eventbridge/cloudwatch_event_target_lambda_main.tf new file mode 100644 index 0000000..664b6e4 --- /dev/null +++ b/infrastructure/modules/eventbridge/cloudwatch_event_target_lambda_main.tf @@ -0,0 +1,16 @@ +resource "aws_cloudwatch_event_target" "lambda_target_no_schedule" { + count = var.endpoint_url == "" ? 1 : 0 + event_bus_name = var.event_bus_name + arn = var.event_target_lambda + rule = aws_cloudwatch_event_rule.main.name + target_id = local.csi + + retry_policy { + maximum_retry_attempts = 10 + maximum_event_age_in_seconds = 14400 + } + + dead_letter_config { + arn = aws_sqs_queue.dlq.arn + } +} diff --git a/infrastructure/modules/eventbridge/cloudwatch_metric_alarm.tf b/infrastructure/modules/eventbridge/cloudwatch_metric_alarm.tf new file mode 100644 index 0000000..f98b8ed --- /dev/null +++ b/infrastructure/modules/eventbridge/cloudwatch_metric_alarm.tf @@ -0,0 +1,17 @@ +resource "aws_cloudwatch_metric_alarm" "deadletter_alarm" { + alarm_name = "${aws_sqs_queue.dlq.name}-not-empty-alarm" + comparison_operator = "GreaterThanOrEqualToThreshold" + evaluation_periods = "1" + metric_name = "ApproximateNumberOfMessagesVisible" + namespace = "AWS/Events" + period = "300" + statistic = "Sum" + threshold = "1" + alarm_description = "Items are on the ${aws_sqs_queue.dlq.name} queue" + alarm_actions = [aws_sns_topic.deadletter_alarm.arn] + treat_missing_data = "notBreaching" + tags = local.default_tags + dimensions = { + "QueueName" = aws_sqs_queue.dlq.name + } +} diff --git a/infrastructure/modules/eventbridge/data_iam_policy_document_assume_role.tf b/infrastructure/modules/eventbridge/data_iam_policy_document_assume_role.tf new file mode 100644 index 0000000..4a422e8 --- /dev/null +++ b/infrastructure/modules/eventbridge/data_iam_policy_document_assume_role.tf @@ -0,0 +1,12 @@ +data "aws_iam_policy_document" "assume_role" { + + statement { + sid = "AllowEventBridgeToAssumeRole" + actions = ["sts:AssumeRole"] + + principals { + type = "Service" + identifiers = ["events.amazonaws.com"] + } + } +} diff --git a/infrastructure/modules/eventbridge/data_iam_policy_document_invoke_api.tf b/infrastructure/modules/eventbridge/data_iam_policy_document_invoke_api.tf new file mode 100644 index 0000000..5885866 --- /dev/null +++ b/infrastructure/modules/eventbridge/data_iam_policy_document_invoke_api.tf @@ -0,0 +1,15 @@ +data "aws_iam_policy_document" "eventbridge_invoke_api" { + count = var.endpoint_url != "" ? 1 : 0 + statement { + sid = "Allow${var.name}ToPushEvents" + effect = "Allow" + + actions = [ + "events:InvokeApiDestination" + ] + + resources = [ + aws_cloudwatch_event_api_destination.main[count.index].arn + ] + } +} diff --git a/infrastructure/modules/eventbridge/data_iam_policy_document_sns_topic.tf b/infrastructure/modules/eventbridge/data_iam_policy_document_sns_topic.tf new file mode 100644 index 0000000..1699a71 --- /dev/null +++ b/infrastructure/modules/eventbridge/data_iam_policy_document_sns_topic.tf @@ -0,0 +1,38 @@ +data "aws_iam_policy_document" "sns_topic_policy" { + policy_id = "AllowDeadLetterQueueAlarm" + + statement { + sid = "AllowDeadLetterQueueAlarm" + effect = "Allow" + + actions = [ + "SNS:Subscribe", + "SNS:SetTopicAttributes", + "SNS:RemovePermission", + "SNS:Receive", + "SNS:Publish", + "SNS:ListSubscriptionsByTopic", + "SNS:GetTopicAttributes", + "SNS:DeleteTopic", + "SNS:AddPermission", + ] + + condition { + test = "StringEquals" + variable = "AWS:SourceOwner" + + values = [ + var.aws_account_id, + ] + } + + principals { + type = "AWS" + identifiers = ["*"] + } + + resources = [ + aws_sns_topic.deadletter_alarm.arn, + ] + } +} diff --git a/infrastructure/modules/eventbridge/data_secretsmanager_secret_version.tf b/infrastructure/modules/eventbridge/data_secretsmanager_secret_version.tf new file mode 100644 index 0000000..7d8aaa3 --- /dev/null +++ b/infrastructure/modules/eventbridge/data_secretsmanager_secret_version.tf @@ -0,0 +1,4 @@ +data "aws_secretsmanager_secret_version" "api_key" { + count = var.secret_env_name != "" ? 1 : 0 + secret_id = "${var.secret_env_name}/${var.api_key}" +} diff --git a/infrastructure/modules/eventbridge/iam_policy_invoke_api.tf b/infrastructure/modules/eventbridge/iam_policy_invoke_api.tf new file mode 100644 index 0000000..e02dd25 --- /dev/null +++ b/infrastructure/modules/eventbridge/iam_policy_invoke_api.tf @@ -0,0 +1,11 @@ +resource "aws_iam_policy" "eventbridge_invoke_api" { + count = var.endpoint_url != "" ? 1 : 0 + name = "${local.csi}-eventbridge-invoke-api" + policy = data.aws_iam_policy_document.eventbridge_invoke_api[count.index].json +} + +resource "aws_iam_role_policy_attachment" "eventbridge_invoke_api" { + count = var.endpoint_url != "" ? 1 : 0 + role = aws_iam_role.eventbridge.name + policy_arn = aws_iam_policy.eventbridge_invoke_api[count.index].arn +} diff --git a/infrastructure/modules/eventbridge/iam_role.tf b/infrastructure/modules/eventbridge/iam_role.tf new file mode 100644 index 0000000..dd09908 --- /dev/null +++ b/infrastructure/modules/eventbridge/iam_role.tf @@ -0,0 +1,5 @@ +resource "aws_iam_role" "eventbridge" { + name = "${local.csi}-eb" + assume_role_policy = data.aws_iam_policy_document.assume_role.json + tags = local.default_tags +} diff --git a/infrastructure/modules/eventbridge/locals.tf b/infrastructure/modules/eventbridge/locals.tf new file mode 100644 index 0000000..9684868 --- /dev/null +++ b/infrastructure/modules/eventbridge/locals.tf @@ -0,0 +1,39 @@ +locals { + is_acct_env = var.is_develop || var.is_prod + + # Compound Scope Identifier + csi = replace( + format( + "%s-%s-%s-%s-%s", + var.project, + var.environment, + var.component, + var.module, + var.service_name, + ), + "_", + "", + ) + + # CSI for use in resources with a global namespace, i.e. S3 Buckets + csi_global = replace( + format( + "%s-%s-%s-%s-%s-%s", + var.project, + var.aws_account_id, + var.region, + var.environment, + var.component, + var.module, + ), + "_", + "", + ) + + default_tags = merge( + var.default_tags, + { + "Module" = var.module + }, + ) +} diff --git a/infrastructure/modules/eventbridge/output.tf b/infrastructure/modules/eventbridge/output.tf new file mode 100644 index 0000000..d6c0bc9 --- /dev/null +++ b/infrastructure/modules/eventbridge/output.tf @@ -0,0 +1,23 @@ +output "eventbridge_rule_name" { + value = aws_cloudwatch_event_rule.main.name +} + +output "eventbridge_rule_arn" { + value = aws_cloudwatch_event_rule.main.arn +} + +output "eventbridge_target" { + value = aws_cloudwatch_event_target.main.*.arn +} + +output "dlq_alarm_name" { + value = aws_cloudwatch_metric_alarm.deadletter_alarm.alarm_name +} + +output "dlq_arn" { + value = aws_sqs_queue.dlq.arn +} + +output "dlq_name" { + value = aws_sqs_queue.dlq.name +} diff --git a/infrastructure/modules/eventbridge/sns_topic.tf b/infrastructure/modules/eventbridge/sns_topic.tf new file mode 100644 index 0000000..7e7d2f3 --- /dev/null +++ b/infrastructure/modules/eventbridge/sns_topic.tf @@ -0,0 +1,4 @@ +resource "aws_sns_topic" "deadletter_alarm" { + name = "${local.csi}-alarm" + tags = local.default_tags +} diff --git a/infrastructure/modules/eventbridge/sns_topic_policy.tf b/infrastructure/modules/eventbridge/sns_topic_policy.tf new file mode 100644 index 0000000..ab04c59 --- /dev/null +++ b/infrastructure/modules/eventbridge/sns_topic_policy.tf @@ -0,0 +1,4 @@ +resource "aws_sns_topic_policy" "topic_policy" { + arn = aws_sns_topic.deadletter_alarm.arn + policy = data.aws_iam_policy_document.sns_topic_policy.json +} diff --git a/infrastructure/modules/eventbridge/sqs_queue_dlq.tf b/infrastructure/modules/eventbridge/sqs_queue_dlq.tf new file mode 100644 index 0000000..1bb5073 --- /dev/null +++ b/infrastructure/modules/eventbridge/sqs_queue_dlq.tf @@ -0,0 +1,6 @@ +resource "aws_sqs_queue" "dlq" { + name = "${local.csi}-dlq" + message_retention_seconds = var.message_retention_seconds + tags = local.default_tags + sqs_managed_sse_enabled = true +} diff --git a/infrastructure/modules/eventbridge/variables.tf b/infrastructure/modules/eventbridge/variables.tf new file mode 100644 index 0000000..4087d36 --- /dev/null +++ b/infrastructure/modules/eventbridge/variables.tf @@ -0,0 +1,168 @@ +## +# Basic Required Variabless +## + +variable "project" { + type = string + description = "The name of the tfscaffold project" +} + +variable "environment" { + type = string + description = "The name of the tfscaffold environment" +} + +variable "component" { + type = string + description = "The name of the tfscaffold component" +} + +variable "aws_account_id" { + type = string + description = "The AWS Account ID (numeric)" +} + +variable "region" { + type = string + description = "The AWS Region" +} + +variable "module" { + type = string + description = "The name of the module" + default = "eventbridge" +} + +variable "default_tags" { + description = "The default tags to apply to all resources" + type = map(string) + default = {} +} + +variable "is_prod" { + type = bool + description = "Is prod?" +} + +variable "is_main_env" { + type = bool + description = "Is main?" +} + +variable "is_develop" { + type = bool + description = "Is develop?" +} + +variable "is_feature" { + type = bool + description = "Is feature?" +} + +variable "account_id" { + type = string + description = "The AWS Account ID" +} + +variable "acct_ids" { + type = map(string) + description = "The AWS Account IDs" +} + +variable "message_retention_seconds" { + type = number + default = 1209600 + description = "The number of seconds Amazon SQS retains a message" +} + +variable "secret_env_name" { + type = string + description = "Secret Environment Name" + default = "" +} + +variable "endpoint_url" { + type = string + description = "CloudWatch event API destination endpoint URL" + default = "" +} + +variable "service_name" { + type = string + description = "Name of the Service" +} + +variable "name" { + type = string + description = "Service Name without space" +} + +variable "auth_endpoint" { + type = string + description = "CloudWatch event connection authorization endpoint" + default = "" +} + +variable "oauth_key" { + type = string + description = "CloudWatch event connection Oauth http body's key" + default = "" +} + +variable "oauth_value" { + type = string + description = "CloudWatch event connection Oauth http body's value" + default = "" +} + +variable "description" { + type = string + description = "CloudWatch event rule description" +} + +variable "iam_role" { + type = string + description = "Lambda Exec Role Name" +} + +variable "api_key" { + type = string + description = "Secret Name API key" + default = "" +} + +variable "rule_event_pattern" { + type = any + description = "Event pattern described a JSON object" +} + +variable "input_path" { + type = list(string) + description = "Key value pairs specified in the form of JSONPath for event target" +} + +variable "target_input_template" { + type = any + description = "JSON Template to customize data sent to the event target" +} + +variable "rule_schedule_expression" { + type = string + description = "CloudWatch Event rule schedule expression" + default = "" +} + +variable "event_target_lambda" { + type = string + description = "Event Target Lambda ARN" +} + +variable "is_enabled" { + type = string + description = "Optional Resource" +} + +variable "event_bus_name" { + type = string + description = "Event Bus name" +} diff --git a/infrastructure/modules/kms/data_aws.tf b/infrastructure/modules/kms/data_aws.tf new file mode 100644 index 0000000..9013883 --- /dev/null +++ b/infrastructure/modules/kms/data_aws.tf @@ -0,0 +1,4 @@ +# The current AWS identity in use by terraform +data "aws_caller_identity" "current" { +} + diff --git a/infrastructure/modules/kms/data_iam_kms_admin_policy.tf b/infrastructure/modules/kms/data_iam_kms_admin_policy.tf new file mode 100644 index 0000000..1870bcf --- /dev/null +++ b/infrastructure/modules/kms/data_iam_kms_admin_policy.tf @@ -0,0 +1,31 @@ +data "aws_iam_policy_document" "admin" { + policy_id = "${local.csi}-admin" + + statement { + sid = "AllowKeyAdmin" + effect = "Allow" + + actions = [ + "kms:Create*", + "kms:Describe*", + "kms:Enable*", + "kms:List*", + "kms:Put*", + "kms:Update*", + "kms:Revoke*", + "kms:Disable*", + "kms:Get*", + "kms:Delete*", + "kms:TagResource", + "kms:UntagResource", + "kms:ScheduleKeyDeletion", + "kms:CancelKeyDeletion", + ] + + resources = [ + aws_kms_key.main.arn, + aws_kms_alias.main.arn, + ] + } +} + diff --git a/infrastructure/modules/kms/data_iam_kms_key_policy.tf b/infrastructure/modules/kms/data_iam_kms_key_policy.tf new file mode 100644 index 0000000..159e867 --- /dev/null +++ b/infrastructure/modules/kms/data_iam_kms_key_policy.tf @@ -0,0 +1,30 @@ +data "aws_iam_policy_document" "key" { + policy_id = "${local.csi}-key" + + statement { + sid = "EnableIAMUserPermissions" + effect = "Allow" + + principals { + type = "AWS" + + identifiers = [ + format( + "%s:%s:%s", + "arn:aws:iam:", + data.aws_caller_identity.current.account_id, + "root", + ), + ] + } + + actions = [ + "kms:*", + ] + + resources = [ + "*", + ] + } +} + diff --git a/infrastructure/modules/kms/data_iam_kms_user_policy.tf b/infrastructure/modules/kms/data_iam_kms_user_policy.tf new file mode 100644 index 0000000..7e43a12 --- /dev/null +++ b/infrastructure/modules/kms/data_iam_kms_user_policy.tf @@ -0,0 +1,43 @@ +data "aws_iam_policy_document" "user" { + policy_id = "${local.csi}-user" + + statement { + sid = "AllowUseOfTheKmskey" + effect = "Allow" + + actions = [ + "kms:Encrypt", + "kms:Decrypt", + "kms:ReEncrypt*", + "kms:GenerateDataKey*", + "kms:DescribeKey", + ] + + resources = [ + aws_kms_key.main.arn, + ] + } + + statement { + sid = "AllowDelegationToAwsServiceViaGrant" + effect = "Allow" + + actions = [ + "kms:CreateGrant", + ] + + resources = [ + aws_kms_key.main.arn, + ] + + condition { + test = "Bool" + variable = "kms:GrantIsForAWSResource" + + values = [ + "true", + ] + } + } +} + diff --git a/infrastructure/modules/kms/iam_policy_admin.tf b/infrastructure/modules/kms/iam_policy_admin.tf new file mode 100644 index 0000000..70fd734 --- /dev/null +++ b/infrastructure/modules/kms/iam_policy_admin.tf @@ -0,0 +1,7 @@ +# Create the Key Policy for the AWS KMS Key +resource "aws_iam_policy" "admin" { + name = "${local.csi}-admin" + path = "/" + policy = data.aws_iam_policy_document.admin.json +} + diff --git a/infrastructure/modules/kms/iam_policy_user.tf b/infrastructure/modules/kms/iam_policy_user.tf new file mode 100644 index 0000000..c487b2e --- /dev/null +++ b/infrastructure/modules/kms/iam_policy_user.tf @@ -0,0 +1,7 @@ +# Create the Key Policy for the AWS KMS Key +resource "aws_iam_policy" "user" { + name = "${local.csi}-user" + path = "/" + policy = data.aws_iam_policy_document.user.json +} + diff --git a/infrastructure/modules/kms/kms_key.tf b/infrastructure/modules/kms/kms_key.tf new file mode 100644 index 0000000..36b14ed --- /dev/null +++ b/infrastructure/modules/kms/kms_key.tf @@ -0,0 +1,8 @@ +resource "aws_kms_key" "main" { + description = local.csi + deletion_window_in_days = var.deletion_window + policy = var.key_policy_document == "" ? data.aws_iam_policy_document.key.json : var.key_policy_document + enable_key_rotation = true + tags = local.default_tags +} + diff --git a/infrastructure/modules/kms/kms_key_alias.tf b/infrastructure/modules/kms/kms_key_alias.tf new file mode 100644 index 0000000..fc6b910 --- /dev/null +++ b/infrastructure/modules/kms/kms_key_alias.tf @@ -0,0 +1,5 @@ +resource "aws_kms_alias" "main" { + name = "${var.alias}-${var.namespace}" + target_key_id = aws_kms_key.main.key_id +} + diff --git a/infrastructure/modules/kms/locals.tf b/infrastructure/modules/kms/locals.tf new file mode 100644 index 0000000..9d31c76 --- /dev/null +++ b/infrastructure/modules/kms/locals.tf @@ -0,0 +1,18 @@ +locals { + csi = format( + "%s-%s-%s-%s-%s", + var.project, + var.environment, + var.component, + var.module, + var.name, + ) + + default_tags = merge( + var.default_tags, + { + Name = local.csi + Module = var.module + }, + ) +} diff --git a/infrastructure/modules/kms/outputs.tf b/infrastructure/modules/kms/outputs.tf new file mode 100644 index 0000000..42995b6 --- /dev/null +++ b/infrastructure/modules/kms/outputs.tf @@ -0,0 +1,16 @@ +output "key_arn" { + value = aws_kms_key.main.arn +} + +output "key_id" { + value = aws_kms_key.main.key_id +} + +output "admin_policy_arn" { + value = aws_iam_policy.admin.arn +} + +output "user_policy_arn" { + value = aws_iam_policy.user.arn +} + diff --git a/infrastructure/modules/kms/variables.tf b/infrastructure/modules/kms/variables.tf new file mode 100644 index 0000000..318383f --- /dev/null +++ b/infrastructure/modules/kms/variables.tf @@ -0,0 +1,68 @@ +## +# Basic inherited variables for terraformscaffold modules +## + +variable "project" { + type = string + description = "The name of the terraformscaffold project calling the module" +} + +variable "environment" { + type = string + description = "The name of the terraformscaffold environment the module is called for" +} + +variable "component" { + type = string + description = "The name of the terraformscaffold component calling this module" +} + +## +# Module self-identification +## + +variable "module" { + type = string + description = "The name of this module. This is a special variable, it should be set only here and never overridden." + default = "kms" +} + +## +# Variable specific to the module +## + +# We presume this will always be specified. The default of {} will cause an error if a valid map is not specified. +# If we ever want to define this but allow it to not be specified, then we must provide a default tag keypair will be applied +# as the true default. In any other case default_tags should be removed from the module. +variable "default_tags" { + type = map(string) + description = "Default tag map for application to all taggable resources in the module" + default = {} +} + +variable "name" { + type = string + description = "A unique name to distinguish this module invocation from others within the same CSI scope" +} + +variable "deletion_window" { + type = string + description = "KMS key deletion window" +} + +variable "alias" { + type = string + description = "Alias name for the hieradata KMS key" +} + +variable "key_policy_document" { + type = string + description = "KMS Key Policy JSON Document" + default = "" +} + +variable "namespace" { + type = string + description = "The name of the environment/workspace" +} + diff --git a/infrastructure/modules/kms/versions.tf b/infrastructure/modules/kms/versions.tf new file mode 100644 index 0000000..1ac101d --- /dev/null +++ b/infrastructure/modules/kms/versions.tf @@ -0,0 +1,9 @@ + +terraform { + required_version = ">= 0.12" + required_providers { + aws = { + source = "hashicorp/aws" + } + } +} diff --git a/infrastructure/modules/lambda-iam/cloudwatch_metric_alarm.tf b/infrastructure/modules/lambda-iam/cloudwatch_metric_alarm.tf new file mode 100644 index 0000000..276d584 --- /dev/null +++ b/infrastructure/modules/lambda-iam/cloudwatch_metric_alarm.tf @@ -0,0 +1,39 @@ +resource "aws_cloudwatch_metric_alarm" "lambda_timeouts" { + count = local.is_main_env ? 1 : 0 + alarm_name = "${var.service_map.name}-${terraform.workspace}-Timeouts" + comparison_operator = "GreaterThanOrEqualToThreshold" + evaluation_periods = var.timeout_alarm_evaluation_periods + threshold = var.timeout_alarm_threshold + period = var.timeout_alarm_period + unit = "Count" + + namespace = "CVS" + metric_name = "Timeouts" + statistic = "Maximum" + dimensions = { + Environment = terraform.workspace + Service = "/aws/lambda/${var.service_map.name}" + } + lifecycle { + ignore_changes = [alarm_actions] + } +} + +resource "aws_cloudwatch_metric_alarm" "lambda_errors" { + count = local.is_main_env ? 1 : 0 + alarm_name = "${var.service_map.name}-${terraform.workspace}-Errors" + comparison_operator = "GreaterThanOrEqualToThreshold" + evaluation_periods = var.errors_alarm_evaluation_periods + threshold = var.errors_alarm_threshold + period = var.errors_alarm_period + unit = "Count" + namespace = "AWS/Lambda" + metric_name = "Errors" + statistic = "Maximum" + dimensions = { + FunctionName = var.service_map.name + } + lifecycle { + ignore_changes = [alarm_actions] + } +} \ No newline at end of file diff --git a/infrastructure/modules/lambda-iam/data.tf b/infrastructure/modules/lambda-iam/data.tf new file mode 100644 index 0000000..2c97bc3 --- /dev/null +++ b/infrastructure/modules/lambda-iam/data.tf @@ -0,0 +1,14 @@ +data "aws_s3_objects" "service_hashes" { + bucket = var.s3_bucket + prefix = "${local.bucket_prefix}/latestHash_${terraform.workspace}" +} + +data "aws_s3_object" "service_hash" { + bucket = var.s3_bucket + key = try(data.aws_s3_objects.service_hashes.keys[0], "${local.bucket_prefix}/latestHash_develop.txt") +} + +data "aws_s3_object" "service" { + bucket = var.s3_bucket + key = "${local.bucket_prefix}/${data.aws_s3_object.service_hash.body}.zip" +} \ No newline at end of file diff --git a/infrastructure/modules/lambda-iam/iam_policy_assume_role.tf b/infrastructure/modules/lambda-iam/iam_policy_assume_role.tf new file mode 100644 index 0000000..6a70e81 --- /dev/null +++ b/infrastructure/modules/lambda-iam/iam_policy_assume_role.tf @@ -0,0 +1,12 @@ +data "aws_iam_policy_document" "assumerole" { + statement { + sid = "AllowLambdaAssumeRole" + effect = "Allow" + actions = ["sts:AssumeRole"] + + principals { + type = "Service" + identifiers = ["lambda.amazonaws.com"] + } + } +} diff --git a/infrastructure/modules/lambda-iam/iam_policy_read_app_config.tf b/infrastructure/modules/lambda-iam/iam_policy_read_app_config.tf new file mode 100644 index 0000000..65d8040 --- /dev/null +++ b/infrastructure/modules/lambda-iam/iam_policy_read_app_config.tf @@ -0,0 +1,19 @@ +data "aws_iam_policy_document" "read_app_config" { + statement { + effect = "Allow" + actions = [ + "appconfig:StartConfigurationSession", + "appconfig:GetLatestConfiguration", + ] + resources = [ + "arn:aws:appconfig:${var.region}:${var.aws_account_id}:application/${var.app_config_id}/environment/${var.app_config_environment_id}/*" + ] + } +} + +resource "aws_iam_role_policy" "role-policy-attachment-app-config" { + count = var.read_from_app_config ? 1 : 0 + name = "${var.service_map.name}-read-app-config" + role = aws_iam_role.main.name + policy = data.aws_iam_policy_document.read_app_config.json +} diff --git a/infrastructure/modules/lambda-iam/iam_role.tf b/infrastructure/modules/lambda-iam/iam_role.tf new file mode 100644 index 0000000..d24f6d4 --- /dev/null +++ b/infrastructure/modules/lambda-iam/iam_role.tf @@ -0,0 +1,24 @@ +resource "aws_iam_role" "main" { + name = local.csi_name + + assume_role_policy = data.aws_iam_policy_document.assumerole.json + + tags = merge( + { + "Name" = "${local.csi}/${var.service_name}", + }, + ) +} + +resource "aws_iam_role_policy_attachment" "role-policy-attachment-default" { + for_each = toset(concat(local.default_iam_policies, var.managed_policies)) + role = aws_iam_role.main.name + policy_arn = each.value +} + +resource "aws_iam_role_policy" "role-policy-attachment-managed" { + count = var.custom_policy_enabled ? 1 : 0 + name = "${var.service_map.name}-custom-policy" + role = aws_iam_role.main.name + policy = var.custom_policy +} diff --git a/infrastructure/modules/lambda-iam/lambda_alias.tf b/infrastructure/modules/lambda-iam/lambda_alias.tf new file mode 100644 index 0000000..bfbde0b --- /dev/null +++ b/infrastructure/modules/lambda-iam/lambda_alias.tf @@ -0,0 +1,6 @@ +resource "aws_lambda_alias" "main" { + name = var.environment + description = "Alias for ${aws_lambda_function.service.function_name}" + function_name = aws_lambda_function.service.arn + function_version = "$LATEST" +} diff --git a/infrastructure/modules/lambda-iam/lambda_permissions.tf b/infrastructure/modules/lambda-iam/lambda_permissions.tf new file mode 100644 index 0000000..69c073d --- /dev/null +++ b/infrastructure/modules/lambda-iam/lambda_permissions.tf @@ -0,0 +1,8 @@ +resource "aws_lambda_permission" "allow_invoke" { + count = length(var.principal_services) + statement_id = "Allow${var.principal_services[count.index]}InvokeLambdaFunction${count.index > 0 ? count.index : ""}" + function_name = aws_lambda_function.service.function_name + action = "lambda:InvokeFunction" + principal = "${var.principal_services[count.index]}.amazonaws.com" + source_arn = var.invoker_source_arns[count.index] +} \ No newline at end of file diff --git a/infrastructure/modules/lambda-iam/locals.tf b/infrastructure/modules/lambda-iam/locals.tf new file mode 100644 index 0000000..c22d9e9 --- /dev/null +++ b/infrastructure/modules/lambda-iam/locals.tf @@ -0,0 +1,59 @@ +locals { + csi_name = replace( + format( + "%s-%s-%s-%s-%s", + var.project, + var.environment, + var.component, + var.module, + var.service_name, + ), + "_", + "", + ) + + # CSI for use in resources with a global namespace, i.e. S3 Buckets + csi = replace( + format( + "%s-%s-%s-%s-%s-%s", + var.project, + var.aws_account_id, + var.region, + var.environment, + var.component, + var.module, + ), + "_", + "", + ) + + tags = { + Component = var.service_map.component + Project = "cvs" + Name = "cvs-${terraform.workspace}-${var.service_map.name}/api" + Environment = terraform.workspace + Module = "cvs-tf-service" + } + + default_env_vars = { + BRANCH = terraform.workspace + } + vpc_config = length(var.lambda_sgs) > 0 && length(var.subnet_ids) > 0 ? { enabled = { security_group_ids = var.lambda_sgs, subnet_ids = var.subnet_ids } } : {} + bucket_prefix = length(var.s3_prefix) == 0 ? var.service_map.name : var.s3_prefix + default_iam_policies = [ + "arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole", + "arn:aws:iam::aws:policy/AWSXRayDaemonWriteAccess", + "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" + ] + + accounts_to_alert_in = ["prod", "preprod", "integration", "develop"] + is_main_env = contains(local.accounts_to_alert_in, terraform.workspace) + + is_feature = length(regexall("[A-Za-z0-9]+-\\d+", terraform.workspace)) > 0 + is_devops = length(regexall("^devops$", terraform.workspace)) > 0 + is_develop = length(regexall("^develop$", terraform.workspace)) > 0 + is_preprod = length(regexall("^preprod$", terraform.workspace)) > 0 + is_prod = length(regexall("^prod$", terraform.workspace)) > 0 + is_dev_env = local.is_feature || local.is_develop || local.is_devops + is_devops_feature = local.is_feature || local.is_devops +} diff --git a/infrastructure/modules/lambda-iam/main.tf b/infrastructure/modules/lambda-iam/main.tf new file mode 100644 index 0000000..9eddf1e --- /dev/null +++ b/infrastructure/modules/lambda-iam/main.tf @@ -0,0 +1,51 @@ +resource "aws_lambda_function" "service" { + function_name = "${var.service_map.name}-${terraform.workspace}" + s3_bucket = data.aws_s3_object.service.bucket + s3_key = data.aws_s3_object.service.key + + # This should be generated from the zip file as follows: + # openssl dgst -sha256 -binary lambda.zip | openssl enc -base64 + source_code_hash = data.aws_s3_object.service.metadata.sha256sum + + handler = var.service_map.handler + runtime = var.runtime + role = aws_iam_role.main.arn + description = "${var.service_map.description} ${terraform.workspace}" + memory_size = var.service_map.memory + timeout = var.service_map.timeout + reserved_concurrent_executions = var.concurrent_executions + dynamic "vpc_config" { + for_each = local.vpc_config + content { + security_group_ids = vpc_config.value["security_group_ids"] + subnet_ids = vpc_config.value["subnet_ids"] + } + } + + tracing_config { + mode = "Active" + } + + environment { + variables = merge(local.default_env_vars, var.additional_env_vars) + } + + dynamic "dead_letter_config" { + for_each = var.dlq_arn == "" ? [] : [var.dlq_arn] + content { + target_arn = var.dlq_arn + } + } + + tags = local.tags + + depends_on = [ + aws_cloudwatch_log_group.logs + ] +} + +resource "aws_cloudwatch_log_group" "logs" { + name = "/aws/lambda/${var.service_map.name}-${terraform.workspace}" + retention_in_days = var.log_retention_days + tags = local.tags +} diff --git a/infrastructure/modules/lambda-iam/output.tf b/infrastructure/modules/lambda-iam/output.tf new file mode 100644 index 0000000..ff0a71d --- /dev/null +++ b/infrastructure/modules/lambda-iam/output.tf @@ -0,0 +1,20 @@ +output "arn" { + value = aws_lambda_function.service.arn +} + +output "invoke_arn" { + value = aws_lambda_function.service.invoke_arn +} + +output "function_name" { + value = aws_lambda_function.service.function_name +} + +output "log_group_name" { + value = aws_cloudwatch_log_group.logs.name +} + +output "role_name" { + value = aws_iam_role.main.name + description = "The name of the role" +} diff --git a/infrastructure/modules/lambda-iam/variables.tf b/infrastructure/modules/lambda-iam/variables.tf new file mode 100644 index 0000000..bddfa8a --- /dev/null +++ b/infrastructure/modules/lambda-iam/variables.tf @@ -0,0 +1,176 @@ +variable "s3_bucket" { + type = string + default = "cvs-services" + description = "The S3 bucket to pull the lambda zip from, defaults to `cvs-services`" +} + +variable "service_map" { + type = object({ + name = string, + version = string, + handler = string, + description = string, + component = string + memory = number, + timeout = number, + }) + description = "Pass the service map from environment here, certain values will be stripped off as they are not used." +} + +variable "runtime" { + type = string + default = "nodejs18.x" + description = "The lambda runtime, defaults to `nodejs14.x`" +} + +variable "managed_policies" { + type = list(string) + default = [] + description = "List of aws managed Iam policies to be attached to lambda" +} + +variable "custom_policy" { + description = "custom policy" + type = string + default = "" +} + +variable "custom_policy_enabled" { + type = bool + default = true +} + +variable "lambda_sgs" { + type = list(string) + default = [] + description = "A list of security group ids" +} + +variable "subnet_ids" { + type = list(string) + default = [] + description = "A list of subnet ids" +} + +variable "additional_env_vars" { + type = map(string) + default = {} + description = "A map of key value pairs for environment variables." +} + +variable "region" { + type = string + default = "eu-west-1" + description = "The AWS region to deploy into. Defaults to `eu-west-1`" +} + +variable "concurrent_executions" { + type = number + default = null + description = "Lambda concurrency" +} + +variable "project" { + type = string + description = "The name of the tfscaffold project" +} + +variable "component" { + type = string + description = "The name of the tfscaffold component" +} + +variable "environment" { + type = string + description = "The name of the tfscaffold environment" +} + +variable "module" { + type = string + description = "The name of the module" + default = "eventbridge" +} + +variable "aws_account_id" { + type = string + description = "The AWS Account ID (numeric)" +} + +variable "service_name" { + type = string + description = "Name of the Service" +} + + +variable "principal_services" { + type = list(string) + description = "A list of service names allowed to invoke lambda. Accepted values: apigateway, events" + default = [""] +} + +variable "invoker_source_arns" { + type = list(string) + description = "A list of arn of the Principal Service" + default = [""] +} + +variable "dlq_arn" { + type = string + description = "Arn for DLQ" + default = "" +} + +variable "s3_prefix" { + type = string + default = "" +} + +variable "timeout_alarm_threshold" { + type = number + default = 1 +} + +variable "timeout_alarm_evaluation_periods" { + type = number + default = 2 +} + +variable "timeout_alarm_period" { + type = number + default = 60 +} + +variable "errors_alarm_threshold" { + type = number + default = 1 +} + +variable "errors_alarm_evaluation_periods" { + type = number + default = 2 +} + +variable "errors_alarm_period" { + type = number + default = 60 +} + +variable "log_retention_days" { + type = number + default = 90 +} + +variable "read_from_app_config" { + type = bool + default = false +} + +variable "app_config_id" { + type = string + default = "" +} + +variable "app_config_environment_id" { + type = string + default = "" +} diff --git a/infrastructure/modules/s3/main.tf b/infrastructure/modules/s3/main.tf new file mode 100644 index 0000000..ca508e0 --- /dev/null +++ b/infrastructure/modules/s3/main.tf @@ -0,0 +1,80 @@ +resource "aws_s3_bucket" "this" { + bucket = var.bucket_name + force_destroy = true + #checkov:skip=CKV_AWS_144:This bucket does not require cross region replication. + #checkov:skip=CKV_AWS_145:This bucket is encrypted with default aws kms key. +} + +resource "aws_s3_bucket_versioning" "this" { + bucket = aws_s3_bucket.this.id + versioning_configuration { + status = "Enabled" + } +} + +resource "aws_s3_bucket_ownership_controls" "enable_acl" { + bucket = aws_s3_bucket.this.id + rule { + object_ownership = "ObjectWriter" + } +} + +resource "aws_s3_bucket_acl" "this" { + depends_on = [aws_s3_bucket_ownership_controls.enable_acl] + bucket = aws_s3_bucket.this.id + acl = "private" +} + +resource "aws_s3_bucket_public_access_block" "this" { + bucket = aws_s3_bucket.this.id + block_public_acls = true + block_public_policy = true + ignore_public_acls = true + restrict_public_buckets = true +} + +resource "aws_s3_bucket_logging" "this" { + count = var.bucket_logging_target_bucket ? 1 : 0 + bucket = aws_s3_bucket.this.id + target_bucket = var.bucket_logging_target_bucket + target_prefix = "${var.bucket_name}/" +} + +resource "aws_s3_bucket_server_side_encryption_configuration" "this" { + bucket = aws_s3_bucket.this.bucket + + rule { + apply_server_side_encryption_by_default { + sse_algorithm = "AES256" + } + } +} + +resource "aws_s3_bucket_policy" "this" { + bucket = aws_s3_bucket.this.id + policy = data.aws_iam_policy_document.this.json +} + +data "aws_iam_policy_document" "this" { + statement { + effect = "Deny" + principals { + type = "AWS" + identifiers = ["*"] + } + actions = [ + "s3:*", + ] + + resources = [ + "${aws_s3_bucket.this.arn}/*", + aws_s3_bucket.this.arn + ] + + condition { + test = "Bool" + values = ["false"] + variable = "aws:SecureTransport" + } + } +} \ No newline at end of file diff --git a/infrastructure/modules/s3/outputs.tf b/infrastructure/modules/s3/outputs.tf new file mode 100644 index 0000000..29c3b92 --- /dev/null +++ b/infrastructure/modules/s3/outputs.tf @@ -0,0 +1,11 @@ +output "bucket" { + value = aws_s3_bucket.this.bucket +} + +output "arn" { + value = aws_s3_bucket.this.arn +} + +output "id" { + value = aws_s3_bucket.this.id +} diff --git a/infrastructure/modules/s3/variables.tf b/infrastructure/modules/s3/variables.tf new file mode 100644 index 0000000..e51049b --- /dev/null +++ b/infrastructure/modules/s3/variables.tf @@ -0,0 +1,10 @@ +variable "bucket_name" { + description = "Name of s3 bucket" + type = string +} + +variable "bucket_logging_target_bucket" { + description = "Access Logging bucket name to enable bucket access logging or not" + type = string + default = null +} \ No newline at end of file diff --git a/infrastructure/options.tf.bak b/infrastructure/options.tf.bak new file mode 100644 index 0000000..f90ce50 --- /dev/null +++ b/infrastructure/options.tf.bak @@ -0,0 +1,99 @@ +resource "aws_api_gateway_method" "api_gateway" { + for_each = local.api_resources + authorization = "NONE" + http_method = "OPTIONS" + resource_id = aws_api_gateway_resource.resource[each.key].id + rest_api_id = aws_api_gateway_rest_api.this_gateway.id +} + +resource "aws_api_gateway_method_response" "response_200" { + for_each = local.api_resources + rest_api_id = aws_api_gateway_rest_api.this_gateway.id + resource_id = aws_api_gateway_resource.resource[each.key].id + http_method = aws_api_gateway_method.api_gateway[0].http_method + status_code = "200" + response_parameters = { + "method.response.header.Access-Control-Allow-Methods" : true, + "method.response.header.Access-Control-Allow-Headers" : true, + "method.response.header.Access-Control-Allow-Origin" : true + } + response_models = { + "application/json" = "EmptySchema" + } +} + +resource "aws_api_gateway_integration" "api_gateway" { + for_each = local.api_resources + rest_api_id = aws_api_gateway_rest_api.this_gateway.id + resource_id = aws_api_gateway_resource.resource[each.key].id + http_method = aws_api_gateway_method.api_gateway[0].http_method + type = "MOCK" + timeout_milliseconds = 29000 + passthrough_behavior = "WHEN_NO_MATCH" + + request_templates = { + "application/json" = <