├── .eslintrc.json ├── .github ├── ISSUE_TEMPLATE │ ├── bug-report.md │ ├── feature-request.md │ └── help.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ └── staticChecks.yml ├── .github_changelog_generator ├── .gitignore ├── .npmignore ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── NOTICE ├── README.md ├── __tests__ ├── index.test.ts └── util │ └── cookie.test.ts ├── doc └── architecture.png ├── jest.config.js ├── package-lock.json ├── package.json ├── src ├── index.ts └── util │ ├── cookie.ts │ └── csrf.ts ├── tsconfig.json └── tsconfig.test.json /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "es6": true, 4 | "node": true, 5 | "amd": true, 6 | "jest": true 7 | }, 8 | "extends": [ 9 | "eslint:recommended", 10 | "plugin:@typescript-eslint/eslint-recommended", 11 | "plugin:@typescript-eslint/recommended" 12 | ], 13 | "parser": "@typescript-eslint/parser", 14 | "plugins": [ 15 | "@typescript-eslint" 16 | ], 17 | "ignorePatterns": [ "/dist/**" ], 18 | "rules": { 19 | "indent": ["error", 2], 20 | "linebreak-style": ["error", "unix"], 21 | "quotes": ["error", "single", { "avoidEscape": true }], 22 | "camelcase": [2, { "properties": "never" }], 23 | "semi": ["error", "always"], 24 | "comma-dangle": ["error", "always-multiline"], 25 | "no-console": "off" 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug-report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug Report 3 | about: Report a bug encountered while using cognito-at-edge 4 | labels: kind/bug 5 | --- 6 | 7 | 9 | 10 | #### What happened: 11 | 12 | #### What did you expect to have happen: 13 | 14 | #### How to reproduce this (as precisely and succinctly as possible): 15 | 16 | #### Anything else you think we should know? 17 | 18 | #### Environment: 19 | - version of cognito-at-edge being used: 20 | - node version of code base which uses cognito-at-edge: 21 | - other: 22 | 23 | - 24 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature-request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Enhancement Tracking Issue 3 | about: Provide supporting details for a feature in development 4 | labels: kind/feature 5 | --- 6 | 7 | #### What would you like to be added: 8 | 9 | #### Why is this needed: -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/help.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "⁉️ Need help with cognito-at-edge?" 3 | about: Please file an issue in our help repo. 4 | 5 | --- 6 | 7 | #### How can we help? 8 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | *Issue # (if available):* 2 | 3 | *Description of changes:* 4 | 5 | By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license. -------------------------------------------------------------------------------- /.github/workflows/staticChecks.yml: -------------------------------------------------------------------------------- 1 | name: Static checks 2 | 3 | on: [ pull_request, push ] 4 | 5 | jobs: 6 | ci-static-checks: 7 | runs-on: ubuntu-latest 8 | permissions: 9 | contents: read 10 | steps: 11 | - name: Checkout PR 12 | uses: actions/checkout@v4 13 | with: 14 | persist-credentials: false 15 | - name: Setup NodeJS 16 | uses: actions/setup-node@v4.0.1 17 | with: 18 | node-version-file: 'package.json' 19 | - name: Install dependencies 20 | run: npm ci 21 | - name: Build code 22 | run: npm run build 23 | - name: Run linters 24 | run: npm run lint 25 | - name: Run unit tests 26 | run: npm run test 27 | -------------------------------------------------------------------------------- /.github_changelog_generator: -------------------------------------------------------------------------------- 1 | unreleased=true 2 | future-release=1.5.3 3 | issues-wo-labels=false 4 | enhancement-label=**Added:** 5 | enhancement-labels=added-feature 6 | bugs-label=**Fixed:** 7 | exclude-labels=duplicate,question,invalid,wontfix,no-changelog 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | output-template.yml 3 | *.tgz 4 | coverage/ 5 | dist/ 6 | .DS_Store 7 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | package-lock.json 3 | output-template.yml 4 | *.tgz 5 | coverage/ -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## [1.5.3](https://github.com/awslabs/cognito-at-edge/tree/1.5.3) (2024-08-14) 4 | 5 | [Full Changelog](https://github.com/awslabs/cognito-at-edge/compare/1.5.2...1.5.3) 6 | 7 | **Merged pull requests:** 8 | 9 | - chore: bump axios from 1.6.7 to 1.7.4 [\#99](https://github.com/awslabs/cognito-at-edge/pull/99) ([dependabot[bot]](https://github.com/apps/dependabot)) 10 | 11 | ## [1.5.2](https://github.com/awslabs/cognito-at-edge/tree/1.5.2) (2024-06-28) 12 | 13 | [Full Changelog](https://github.com/awslabs/cognito-at-edge/compare/1.5.1...1.5.2) 14 | 15 | **Merged pull requests:** 16 | 17 | - chore: bump ws from 7.5.9 to 7.5.10 [\#97](https://github.com/awslabs/cognito-at-edge/pull/97) ([dependabot[bot]](https://github.com/apps/dependabot)) 18 | - chore: bump braces from 3.0.2 to 3.0.3 [\#96](https://github.com/awslabs/cognito-at-edge/pull/96) ([dependabot[bot]](https://github.com/apps/dependabot)) 19 | - chore: bump follow-redirects from 1.15.5 to 1.15.6 [\#95](https://github.com/awslabs/cognito-at-edge/pull/95) ([dependabot[bot]](https://github.com/apps/dependabot)) 20 | 21 | ## [1.5.1](https://github.com/awslabs/cognito-at-edge/tree/1.5.1) (2024-03-04) 22 | 23 | [Full Changelog](https://github.com/awslabs/cognito-at-edge/compare/1.5.0...1.5.1) 24 | 25 | **Fixed:** 26 | 27 | - Add support for custom cognito redirect path [\#87](https://github.com/awslabs/cognito-at-edge/pull/87) ([fknittel](https://github.com/fknittel)) 28 | 29 | **Merged pull requests:** 30 | 31 | - Bump @babel/traverse from 7.20.13 to 7.24.0 [\#91](https://github.com/awslabs/cognito-at-edge/pull/91) ([dependabot[bot]](https://github.com/apps/dependabot)) 32 | - Bump tough-cookie from 4.1.2 to 4.1.3 [\#90](https://github.com/awslabs/cognito-at-edge/pull/90) ([dependabot[bot]](https://github.com/apps/dependabot)) 33 | - chore: update axios to 1.6.5 to resolve npm audit alarm [\#85](https://github.com/awslabs/cognito-at-edge/pull/85) ([elliotsegler](https://github.com/elliotsegler)) 34 | 35 | ## [1.5.0](https://github.com/awslabs/cognito-at-edge/tree/1.5.0) (2023-07-24) 36 | 37 | [Full Changelog](https://github.com/awslabs/cognito-at-edge/compare/1.4.0...1.5.0) 38 | 39 | **Added:** 40 | 41 | - Add additional handlers and CSRF protection [\#68](https://github.com/awslabs/cognito-at-edge/pull/68) ([vikas-reddy](https://github.com/vikas-reddy)) 42 | 43 | **Merged pull requests:** 44 | 45 | - Improve types and type checks [\#71](https://github.com/awslabs/cognito-at-edge/pull/71) ([peternedap](https://github.com/peternedap)) 46 | 47 | ## [1.4.0](https://github.com/awslabs/cognito-at-edge/tree/1.4.0) (2023-04-18) 48 | 49 | [Full Changelog](https://github.com/awslabs/cognito-at-edge/compare/1.3.2...1.4.0) 50 | 51 | **Added:** 52 | 53 | - Use refetch token, if available [\#51](https://github.com/awslabs/cognito-at-edge/pull/51) ([maverick089](https://github.com/maverick089)) 54 | 55 | ## [1.3.2](https://github.com/awslabs/cognito-at-edge/tree/1.3.2) (2023-02-20) 56 | 57 | [Full Changelog](https://github.com/awslabs/cognito-at-edge/compare/1.3.1...1.3.2) 58 | 59 | **Added:** 60 | 61 | - Support SameSite cookie [\#50](https://github.com/awslabs/cognito-at-edge/pull/50) ([ckifer](https://github.com/ckifer)) 62 | 63 | **Fixed:** 64 | 65 | - Unhandled error if cookies disabled [\#52](https://github.com/awslabs/cognito-at-edge/issues/52) 66 | - Handle missing cookies in request [\#53](https://github.com/awslabs/cognito-at-edge/pull/53) ([foxbox-doug](https://github.com/foxbox-doug)) 67 | 68 | ## [1.3.1](https://github.com/awslabs/cognito-at-edge/tree/1.3.1) (2022-12-05) 69 | 70 | [Full Changelog](https://github.com/awslabs/cognito-at-edge/compare/1.3.0...1.3.1) 71 | 72 | **Fixed:** 73 | 74 | - Incorrect Regex of idToken With Subdomains [\#43](https://github.com/awslabs/cognito-at-edge/issues/43) 75 | 76 | ## [1.3.0](https://github.com/awslabs/cognito-at-edge/tree/1.3.0) (2022-11-22) 77 | 78 | [Full Changelog](https://github.com/awslabs/cognito-at-edge/compare/1.2.2...1.3.0) 79 | 80 | **Added:** 81 | 82 | - feat: httpOnly param [\#41](https://github.com/awslabs/cognito-at-edge/pull/41) ([tsop14](https://github.com/tsop14)) 83 | 84 | ## [1.2.2](https://github.com/awslabs/cognito-at-edge/tree/1.2.2) (2022-04-12) 85 | 86 | [Full Changelog](https://github.com/awslabs/cognito-at-edge/compare/1.2.1...1.2.2) 87 | 88 | **Fixed:** 89 | 90 | - Fix type mismatch of the status code [\#35](https://github.com/awslabs/cognito-at-edge/pull/35) ([piotrekwitkowski](https://github.com/piotrekwitkowski)) 91 | - fix: update regex to account for idToken being last key value pair in cookie string [\#33](https://github.com/awslabs/cognito-at-edge/pull/33) ([timbakkum](https://github.com/timbakkum)) 92 | 93 | **Merged pull requests:** 94 | 95 | - Update axios and aws-jwt-verify dependencies [\#30](https://github.com/awslabs/cognito-at-edge/pull/30) ([ottokruse](https://github.com/ottokruse)) 96 | 97 | ## [1.2.1](https://github.com/awslabs/cognito-at-edge/tree/1.2.1) (2022-01-17) 98 | 99 | [Full Changelog](https://github.com/awslabs/cognito-at-edge/compare/1.2.0...1.2.1) 100 | 101 | **Fixed:** 102 | 103 | - Add npmignore to include dist files in npm releases [\#28](https://github.com/awslabs/cognito-at-edge/pull/28) ([pedromgarcia](https://github.com/pedromgarcia)) 104 | 105 | ## [1.2.0](https://github.com/awslabs/cognito-at-edge/tree/1.2.0) (2022-01-14) 106 | 107 | [Full Changelog](https://github.com/awslabs/cognito-at-edge/compare/1.1.1...1.2.0) 108 | 109 | **Added:** 110 | 111 | - Add typescript support [\#26](https://github.com/awslabs/cognito-at-edge/pull/26) ([piotrekwitkowski](https://github.com/piotrekwitkowski)) 112 | 113 | **Closed issues:** 114 | 115 | - Switch to typescript [\#20](https://github.com/awslabs/cognito-at-edge/issues/20) 116 | 117 | ## [1.1.1](https://github.com/awslabs/cognito-at-edge/tree/1.1.1) (2022-01-10) 118 | 119 | [Full Changelog](https://github.com/awslabs/cognito-at-edge/compare/1.1.0...1.1.1) 120 | 121 | **Fixed:** 122 | 123 | - Double Decoding of the QueryParams [\#23](https://github.com/awslabs/cognito-at-edge/issues/23) 124 | - Add Cache-Control headers to redirect responses [\#18](https://github.com/awslabs/cognito-at-edge/issues/18) 125 | - Fix for double query params decoding [\#24](https://github.com/awslabs/cognito-at-edge/pull/24) ([akhudiakov97](https://github.com/akhudiakov97)) 126 | - Add cache-control & pragma headers to redirect responses [\#19](https://github.com/awslabs/cognito-at-edge/pull/19) ([ineale2](https://github.com/ineale2)) 127 | 128 | **Merged pull requests:** 129 | 130 | - Use aws-jwt-verify to verify JSON Web Tokens [\#15](https://github.com/awslabs/cognito-at-edge/pull/15) ([ottokruse](https://github.com/ottokruse)) 131 | 132 | ## [1.1.0](https://github.com/awslabs/cognito-at-edge/tree/1.1.0) (2021-10-05) 133 | 134 | [Full Changelog](https://github.com/awslabs/cognito-at-edge/compare/1.0.0...1.1.0) 135 | 136 | Merge PRs by external contributors to add support for new use cases 137 | 138 | **Added:** 139 | 140 | - added optional disableCookieDomain parameter [\#11](https://github.com/awslabs/cognito-at-edge/pull/11) ([jwwheeleriv](https://github.com/jwwheeleriv)) 141 | - add authentication to the fetch tokens from code [\#9](https://github.com/awslabs/cognito-at-edge/pull/9) ([yoavya](https://github.com/yoavya)) 142 | 143 | **Closed issues:** 144 | 145 | - Cookie domain attribute should optionally be disabled [\#10](https://github.com/awslabs/cognito-at-edge/issues/10) 146 | - Cognito client Id with secret [\#7](https://github.com/awslabs/cognito-at-edge/issues/7) 147 | 148 | ## [1.0.0](https://github.com/awslabs/cognito-at-edge/tree/1.0.0) (2021-06-28) 149 | 150 | [Full Changelog](https://github.com/awslabs/cognito-at-edge/compare/9ad4d41623deafb8c217b9071fe2e63a4d4f30c7...1.0.0) 151 | 152 | Initial open-source release of `cognito-at-edge`. 153 | 154 | **Merged pull requests:** 155 | 156 | - Update README and package.json and add a PR template [\#3](https://github.com/awslabs/cognito-at-edge/pull/3) ([jeandek](https://github.com/jeandek)) 157 | - Add unit test cases to achieve full coverage [\#2](https://github.com/awslabs/cognito-at-edge/pull/2) ([jeandek](https://github.com/jeandek)) 158 | - Readme updates [\#1](https://github.com/awslabs/cognito-at-edge/pull/1) ([jenirain](https://github.com/jenirain)) 159 | 160 | 161 | 162 | \* *This Changelog was automatically generated by [github_changelog_generator](https://github.com/github-changelog-generator/github-changelog-generator)* 163 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional 4 | documentation, we greatly value feedback and contributions from our community. 5 | 6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary 7 | information to effectively respond to your bug report or contribution. 8 | 9 | 10 | ## Reporting Bugs/Feature Requests 11 | 12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 13 | 14 | When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already 15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 16 | 17 | * A reproducible test case or series of steps 18 | * The version of our code being used 19 | * Any modifications you've made relevant to the bug 20 | * Anything unusual about your environment or deployment 21 | 22 | 23 | ## Contributing via Pull Requests 24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 25 | 26 | 1. You are working against the latest source on the *master* branch. 27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 29 | 30 | To send us a pull request, please: 31 | 32 | 1. Fork the repository. 33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 34 | 3. Ensure local tests pass. 35 | 4. Commit to your fork using clear commit messages. 36 | 5. Send us a pull request, answering any default questions in the pull request interface. 37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 38 | 39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and 40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 41 | 42 | 43 | ## Finding contributions to work on 44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start. 45 | 46 | ## Development Process 47 | 48 | ### Setting up for local development 49 | 50 | ``` 51 | git clone git@github.com:awslabs/cognito-at-edge.git 52 | cd cognito-at-edge/ 53 | 54 | npm install 55 | ``` 56 | 57 | ### Testing the code 58 | Tests are written using jest. To run tests invoke 59 | ``` 60 | npm test 61 | ``` 62 | 63 | 64 | ## Code of Conduct 65 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 66 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 67 | opensource-codeofconduct@amazon.com with any additional questions or comments. 68 | 69 | 70 | ## Security issue notifications 71 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. 72 | 73 | 74 | ## Licensing 75 | 76 | See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 77 | 78 | We may ask you to sign a [Contributor License Agreement (CLA)](http://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes. 79 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | cognito-at-edge 2 | Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Cognito@Edge 2 | 3 | *Cognito authentication made easy to protect your website with CloudFront and Lambda@Edge.* 4 | 5 | This Node.js package helps you verify that users making requests to a CloudFront distribution are authenticated using a Cognito user pool. It achieves that by looking at the cookies included in the request and, if the requester is not authenticated, it will redirect then to the user pool's login page. 6 | 7 | ![Architecture](./doc/architecture.png) 8 | 9 | ### Alternatives 10 | 11 | This package allows you to easily parse and verify Cognito cookies in a Lambda@Edge function. If you want full control over the configuration of AWS resources (CloudFront, Cognito, Lambda@Edge...), this is the solution for you. 12 | 13 | If you want to try it out easily or to quickstart a new project, we recommend having a look at the [cognito-at-edge-federated-ui-sample](https://github.com/aws-samples/cognito-at-edge-federated-ui-sample) repository. It allows you to configure and deploy a sample application which uses Cognito@Edge in a few CLI commands. 14 | 15 | If you need more configuration options (e.g. bring your own user pool or CloudFront distribution), you may want to use [this Serverless Application Repository application](https://console.aws.amazon.com/lambda/home?region=us-east-1#/create/app?applicationId=arn:aws:serverlessrepo:us-east-1:520945424137:applications/cloudfront-authorization-at-edge) ([GitHub](https://github.com/aws-samples/cloudfront-authorization-at-edge)) which provides a complete Auth@Edge solution. It does not use Cognito@Edge, but provides similar functionality. 16 | 17 | ## Getting started 18 | 19 | ### How To Install 20 | 21 | The preferred way to install the AWS cognito-at-edge for Node.js is to use the [npm](http://npmjs.org/) package manager for Node.js. Simply type the following into a terminal window: 22 | 23 | ``` shell 24 | npm install cognito-at-edge 25 | ``` 26 | 27 | ### Usage 28 | 29 | To use the package, you must create a [Lambda@Edge function](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-at-the-edge.html) and associate it with the CloudFront distribution's *viewer request* events. 30 | 31 | Within your Lambda@Edge function, you can import and use the `Authenticator` class as shown here: 32 | 33 | ``` js 34 | const { Authenticator } = require('cognito-at-edge'); 35 | 36 | const authenticator = new Authenticator({ 37 | // Replace these parameter values with those of your own environment 38 | region: 'us-east-1', // user pool region 39 | userPoolId: 'us-east-1_tyo1a1FHH', // user pool ID 40 | userPoolAppId: '63gcbm2jmskokurt5ku9fhejc6', // user pool app client ID 41 | userPoolDomain: 'domain.auth.us-east-1.amazoncognito.com', // user pool domain 42 | }); 43 | 44 | exports.handler = async (request) => authenticator.handle(request); 45 | ``` 46 | 47 | For an explanation of the interactions between CloudFront, Cognito and Lambda@Edge, we recommend reading this [AWS blog article](https://aws.amazon.com/blogs/networking-and-content-delivery/authorizationedge-how-to-use-lambdaedge-and-json-web-tokens-to-enhance-web-application-security/) which describe the required architecture to authenticate requests in CloudFront with Cognito. 48 | 49 | ## Reference - Authenticator Class 50 | 51 | ### Authenticator(params) 52 | 53 | * `params` *Object* Authenticator parameters: 54 | * `region` *string* Cognito UserPool region (eg: `us-east-1`) 55 | * `userPoolId` *string* Cognito UserPool ID (eg: `us-east-1_tyo1a1FHH`) 56 | * `userPoolAppId` *string* Cognito UserPool Application ID (eg: `63gcbm2jmskokurt5ku9fhejc6`) 57 | * `userPoolAppSecret` *string* (Optional) Cognito UserPool Application Secret (eg: `oh470px2i0uvy4i2ha6sju0vxe4ata9ol3m63ufhs2t8yytwjn7p`) 58 | * `userPoolDomain` *string* Cognito UserPool domain (eg: `your-domain.auth.us-east-1.amazoncognito.com`) 59 | * `cookieExpirationDays` *number* (Optional) Number of day to set cookies expiration date, default to 365 days (eg: `365`). It's recommended to set this value to match `refreshTokenValidity` parameter of the pool client. 60 | * `disableCookieDomain` *boolean* (Optional) Sets domain attribute in cookies, defaults to false (eg: `false`) 61 | * `httpOnly` *boolean* (Optional) Forbids JavaScript from accessing the cookies, defaults to false (eg: `false`). Note, if this is set to `true`, the cookies will not be accessible to Amplify auth if you are using it client side. 62 | * `sameSite` *Strict | Lax | None* (Optional) Allows you to declare if your cookie should be restricted to a first-party or same-site context (eg: `SameSite=None`). 63 | * `parseAuthPath` *string* (Optional) URI path used as redirect target after successful Cognito authentication (eg: `/oauth2/idpresponse`), defaults to the web domain root. Needs to be a path that is handled by the library. When using this parameter, you should also provide a value for `cookiePath` to ensure your cookies are available for the right paths. 64 | * `cookiePath` *string* (Optional) Sets Path attribute in cookies 65 | * `cookieDomain` *string* (Optional) Sets the domain name used for the token cookies 66 | * `cookieSettingsOverrides` *object* (Optional) Cookie settings overrides for different token cookies -- idToken, accessToken and refreshToken 67 | * `idToken` *CookieSettings* (Optional) Setting overrides to use for idToken 68 | * `expirationDays` *number* (Optional) Number of day to set cookies expiration date, default to 365 days (eg: `365`). It's recommended to set this value to match `refreshTokenValidity` parameter of the pool client. 69 | * `path` *string* (Optional) Sets Path attribute in cookies 70 | * `httpOnly` *boolean* (Optional) Forbids JavaScript from accessing the cookies, defaults to false (eg: `false`). Note, if this is set to `true`, the cookies will not be accessible to Amplify auth if you are using it client side. 71 | * `sameSite` *Strict | Lax | None* (Optional) Allows you to declare if your cookie should be restricted to a first-party or same-site context (eg: `SameSite=None`). 72 | * `accessToken` *CookieSettings* (Optional) Setting overrides to use for accessToken 73 | * `refreshToken` *CookieSettings* (Optional) Setting overrides to use for refreshToken 74 | * `logoutConfiguration` *object* (Optional) Enables logout functionality 75 | * `logoutUri` *string* URI path, which when matched with request, logs user out by revoking tokens and clearing cookies 76 | * `logoutRedirectUri` *string* The URI to which the user is redirected to after logging them out 77 | * `csrfProtection` *object* (Optional) Enables CSRF protection 78 | * `nonceSigningSecret` *string* Secret used for signing nonce cookies 79 | * `logLevel` *string* (Optional) Logging level. Default: `'silent'`. One of `'fatal'`, `'error'`, `'warn'`, `'info'`, `'debug'`, `'trace'` or `'silent'`. 80 | 81 | *This is the class constructor.* 82 | 83 | ### handle(request) 84 | 85 | * `request` *Object* Lambda@Edge request object 86 | * See AWS doc for details: [Lambda@Edge events](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html) 87 | 88 | Use it as your Lambda Handler. It will authenticate each query. 89 | 90 | ```js 91 | const authenticator = new Authenticator( ... ); 92 | exports.handler = async (request) => authenticator.handle(request); 93 | ``` 94 | 95 | ### Authentication Gateway Setup 96 | This library can also be used in an authentication gateway setup. If you have a frontend client application that uses AWS Cognito for authentication, it fetches and stores authentication tokens in the browser. Depending on where the tokens are stored in the browser (localStorage, cookies, sessionStorage), they may susceptible to token theft and XSS (Cross-Site Scripting). In order to mitigate this risk, a set of Lambda@Edge handlers can be deployed on a CloudFront distribution which act as an authentication gateway intermediary between the frontend app and Cognito. These handlers will authenticate and fetch tokens on the frontend's behalf and set them as [Secure; HttpOnly](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies) tokens inside the browser, thereby restricting access to other scripts in the app. 97 | 98 | Handlers 99 | 1. `handleSignIn` (Can be mapped to `/signIn` in Cloudfront setup): Redirect users to Cognito's authorize endpoint after replacing redirect uri with its own -- for instance, `/parseAuth`. 100 | 1. `handleParseAuth` (Can be mapped to `/parseAuth`): Exchange Cognito's OAuth code for tokens. Store tokens in browser as HttpOnly cookies 101 | 1. `handleRefreshToken` (Can be mapped to `/refreshToken`): Refresh idToken and accessToken using refreshToken 102 | 1. `handleSignOut` (Can be mapped to `/signOut`): Revoke tokens, clear cookies and redirect user to the URL supplied 103 | 104 | ```js 105 | // signIn Lambda Handler 106 | const authenticator = new Authenticator( ... ); 107 | exports.handler = async (request) => authenticator.handleSignIn(request); 108 | 109 | // Similar setup for parseAuth, refreshToken and signOut handlers 110 | ``` 111 | 112 | 113 | ### Getting Help 114 | 115 | The best way to interact with our team is through GitHub. You can [open an issue](https://github.com/awslabs/cognito-at-edge/issues/new/choose) 116 | and choose from one of our templates for [bug reports](https://github.com/awslabs/cognito-at-edge/issues/new?assignees=&labels=bug%2C+needs-triage&template=---bug-report.md&title=), 117 | [feature requests](https://github.com/awslabs/cognito-at-edge/issues/new?assignees=&labels=feature-request&template=---feature-request.md&title=) or 118 | [question](https://github.com/awslabs/cognito-at-edge/issues/new?assignees=&labels=question%2C+needs-triage&template=---questions---help.md&title=). 119 | 120 | ## Contributing 121 | 122 | We welcome community contributions and pull requests. See [CONTRIBUTING.md](https://github.com/awslabs/cognito-at-edge/blob/main/CONTRIBUTING.md) for information on how to set up a development environment and submit code. 123 | 124 | ### License 125 | 126 | This project is licensed under the [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0.html), see LICENSE.txt and NOTICE.txt for more information. 127 | -------------------------------------------------------------------------------- /__tests__/index.test.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable @typescript-eslint/ban-ts-comment */ 2 | import axios from 'axios'; 3 | 4 | jest.mock('axios'); 5 | 6 | import { CloudFrontRequest } from 'aws-lambda'; 7 | import { Authenticator } from '../src/'; 8 | import { Cookies } from '../src/util/cookie'; 9 | import { NONCE_COOKIE_NAME_SUFFIX, NONCE_HMAC_COOKIE_NAME_SUFFIX, PKCE_COOKIE_NAME_SUFFIX } from '../src/util/csrf'; 10 | 11 | const DATE = new Date('2017'); 12 | // @ts-ignore 13 | global.Date = class extends Date { 14 | constructor() { 15 | super(); 16 | return DATE; 17 | } 18 | }; 19 | 20 | describe('private functions', () => { 21 | let authenticator : Authenticator; 22 | 23 | beforeEach(() => { 24 | authenticator = new Authenticator({ 25 | region: 'us-east-1', 26 | userPoolId: 'us-east-1_abcdef123', 27 | userPoolAppId: '123456789qwertyuiop987abcd', 28 | userPoolDomain: 'my-cognito-domain.auth.us-east-1.amazoncognito.com', 29 | cookieExpirationDays: 365, 30 | disableCookieDomain: false, 31 | httpOnly: false, 32 | }); 33 | }); 34 | 35 | test('should fetch token', () => { 36 | axios.request = jest.fn().mockResolvedValue({ data: tokenData }); 37 | 38 | return authenticator._fetchTokensFromCode('htt://redirect', 'AUTH_CODE') 39 | .then(res => { 40 | expect(res).toMatchObject({refreshToken: tokenData.refresh_token, accessToken: tokenData.access_token, idToken: tokenData.id_token}); 41 | }); 42 | }); 43 | 44 | test('should throw if unable to fetch token', () => { 45 | axios.request = jest.fn().mockRejectedValue(new Error('Unexpected error')); 46 | return expect(() => authenticator._fetchTokensFromCode('htt://redirect', 'AUTH_CODE')).rejects.toThrow(); 47 | }); 48 | 49 | test('should getRedirectResponse', async () => { 50 | const username = 'toto'; 51 | const domain = 'example.com'; 52 | const path = '/test'; 53 | jest.spyOn(authenticator._jwtVerifier, 'verify'); 54 | authenticator._jwtVerifier.verify.mockReturnValueOnce(Promise.resolve({ token_use: 'id', 'cognito:username': username })); 55 | 56 | const response = await authenticator._getRedirectResponse({refreshToken: tokenData.refresh_token, accessToken: tokenData.access_token, idToken: tokenData.id_token}, domain, path); 57 | expect(response).toMatchObject({ 58 | status: '302', 59 | headers: { 60 | location: [{ 61 | key: 'Location', 62 | value: path, 63 | }], 64 | }, 65 | }); 66 | expect(response?.headers?.['set-cookie']).toEqual(expect.arrayContaining([ 67 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.accessToken=${tokenData.access_token}; Domain=${domain}; Expires=${DATE.toUTCString()}; Secure`}, 68 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.refreshToken=${tokenData.refresh_token}; Domain=${domain}; Expires=${DATE.toUTCString()}; Secure`}, 69 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.tokenScopesString=phone%20email%20profile%20openid%20aws.cognito.signin.user.admin; Domain=${domain}; Expires=${DATE.toUTCString()}; Secure`}, 70 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.idToken=${tokenData.id_token}; Domain=${domain}; Expires=${DATE.toUTCString()}; Secure`}, 71 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.LastAuthUser=${username}; Domain=${domain}; Expires=${DATE.toUTCString()}; Secure`}, 72 | ])); 73 | expect(authenticator._jwtVerifier.verify).toHaveBeenCalled(); 74 | }); 75 | 76 | test('should not return cookie domain', async () => { 77 | const authenticatorWithNoCookieDomain = new Authenticator({ 78 | region: 'us-east-1', 79 | userPoolId: 'us-east-1_abcdef123', 80 | userPoolAppId: '123456789qwertyuiop987abcd', 81 | userPoolDomain: 'my-cognito-domain.auth.us-east-1.amazoncognito.com', 82 | cookieExpirationDays: 365, 83 | disableCookieDomain: true, 84 | }); 85 | authenticatorWithNoCookieDomain._jwtVerifier.cacheJwks(jwksData); 86 | 87 | const username = 'toto'; 88 | const domain = 'example.com'; 89 | const path = '/test'; 90 | jest.spyOn(authenticatorWithNoCookieDomain._jwtVerifier, 'verify'); 91 | authenticatorWithNoCookieDomain._jwtVerifier.verify.mockReturnValueOnce(Promise.resolve({ token_use: 'id', 'cognito:username': username })); 92 | 93 | const response = await authenticatorWithNoCookieDomain._getRedirectResponse({'accessToken': tokenData.access_token, 'idToken': tokenData.id_token, 'refreshToken': tokenData.refresh_token}, domain, path); 94 | expect(response).toMatchObject({ 95 | status: '302', 96 | headers: { 97 | location: [{ 98 | key: 'Location', 99 | value: path, 100 | }], 101 | }, 102 | }); 103 | expect(response?.headers?.['set-cookie']).toEqual(expect.arrayContaining([ 104 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.accessToken=${tokenData.access_token}; Expires=${DATE.toUTCString()}; Secure`}, 105 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.refreshToken=${tokenData.refresh_token}; Expires=${DATE.toUTCString()}; Secure`}, 106 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.tokenScopesString=phone%20email%20profile%20openid%20aws.cognito.signin.user.admin; Expires=${DATE.toUTCString()}; Secure`}, 107 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.idToken=${tokenData.id_token}; Expires=${DATE.toUTCString()}; Secure`}, 108 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.LastAuthUser=${username}; Expires=${DATE.toUTCString()}; Secure`}, 109 | ])); 110 | expect(authenticatorWithNoCookieDomain._jwtVerifier.verify).toHaveBeenCalled(); 111 | }); 112 | 113 | test('should set HttpOnly on cookies', async () => { 114 | const authenticatorWithHttpOnly = new Authenticator({ 115 | region: 'us-east-1', 116 | userPoolId: 'us-east-1_abcdef123', 117 | userPoolAppId: '123456789qwertyuiop987abcd', 118 | userPoolDomain: 'my-cognito-domain.auth.us-east-1.amazoncognito.com', 119 | cookieExpirationDays: 365, 120 | disableCookieDomain: false, 121 | httpOnly: true, 122 | }); 123 | authenticatorWithHttpOnly._jwtVerifier.cacheJwks(jwksData); 124 | 125 | const username = 'toto'; 126 | const domain = 'example.com'; 127 | const path = '/test'; 128 | jest.spyOn(authenticatorWithHttpOnly._jwtVerifier, 'verify'); 129 | authenticatorWithHttpOnly._jwtVerifier.verify.mockReturnValueOnce(Promise.resolve({ token_use: 'id', 'cognito:username': username })); 130 | 131 | const response = await authenticatorWithHttpOnly._getRedirectResponse({ accessToken: tokenData.access_token, idToken: tokenData.id_token, refreshToken: tokenData.refresh_token }, domain, path); 132 | expect(response).toMatchObject({ 133 | status: '302', 134 | headers: { 135 | location: [{ 136 | key: 'Location', 137 | value: path, 138 | }], 139 | }, 140 | }); 141 | expect(response?.headers?.['set-cookie']).toEqual(expect.arrayContaining([ 142 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.accessToken=${tokenData.access_token}; Domain=${domain}; Expires=${DATE.toUTCString()}; Secure; HttpOnly`}, 143 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.refreshToken=${tokenData.refresh_token}; Domain=${domain}; Expires=${DATE.toUTCString()}; Secure; HttpOnly`}, 144 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.tokenScopesString=phone%20email%20profile%20openid%20aws.cognito.signin.user.admin; Domain=${domain}; Expires=${DATE.toUTCString()}; Secure; HttpOnly`}, 145 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.idToken=${tokenData.id_token}; Domain=${domain}; Expires=${DATE.toUTCString()}; Secure; HttpOnly`}, 146 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.LastAuthUser=${username}; Domain=${domain}; Expires=${DATE.toUTCString()}; Secure; HttpOnly`}, 147 | ])); 148 | expect(authenticatorWithHttpOnly._jwtVerifier.verify).toHaveBeenCalled(); 149 | }); 150 | 151 | test('should set SameSite on cookies', async () => { 152 | const authenticatorWithSameSite = new Authenticator({ 153 | region: 'us-east-1', 154 | userPoolId: 'us-east-1_abcdef123', 155 | userPoolAppId: '123456789qwertyuiop987abcd', 156 | userPoolDomain: 'my-cognito-domain.auth.us-east-1.amazoncognito.com', 157 | cookieExpirationDays: 365, 158 | disableCookieDomain: false, 159 | httpOnly: true, 160 | sameSite: 'Strict', 161 | }); 162 | authenticatorWithSameSite._jwtVerifier.cacheJwks(jwksData); 163 | 164 | const username = 'toto'; 165 | const domain = 'example.com'; 166 | const path = '/test'; 167 | jest.spyOn(authenticatorWithSameSite._jwtVerifier, 'verify'); 168 | authenticatorWithSameSite._jwtVerifier.verify.mockReturnValueOnce(Promise.resolve({ token_use: 'id', 'cognito:username': username })); 169 | 170 | const response = await authenticatorWithSameSite._getRedirectResponse({ accessToken: tokenData.access_token, idToken: tokenData.id_token, refreshToken: tokenData.refresh_token }, domain, path); 171 | expect(response).toMatchObject({ 172 | status: '302', 173 | headers: { 174 | location: [{ 175 | key: 'Location', 176 | value: path, 177 | }], 178 | }, 179 | }); 180 | expect(response?.headers?.['set-cookie']).toEqual(expect.arrayContaining([ 181 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.accessToken=${tokenData.access_token}; Domain=${domain}; Expires=${DATE.toUTCString()}; Secure; HttpOnly; SameSite=Strict`}, 182 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.refreshToken=${tokenData.refresh_token}; Domain=${domain}; Expires=${DATE.toUTCString()}; Secure; HttpOnly; SameSite=Strict`}, 183 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.tokenScopesString=phone%20email%20profile%20openid%20aws.cognito.signin.user.admin; Domain=${domain}; Expires=${DATE.toUTCString()}; Secure; HttpOnly; SameSite=Strict`}, 184 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.idToken=${tokenData.id_token}; Domain=${domain}; Expires=${DATE.toUTCString()}; Secure; HttpOnly; SameSite=Strict`}, 185 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.LastAuthUser=${username}; Domain=${domain}; Expires=${DATE.toUTCString()}; Secure; HttpOnly; SameSite=Strict`}, 186 | ])); 187 | expect(authenticatorWithSameSite._jwtVerifier.verify).toHaveBeenCalled(); 188 | }); 189 | 190 | test('should set Path on cookies', async () => { 191 | const cookiePath = '/test/path'; 192 | const authenticatorWithPath = new Authenticator({ 193 | region: 'us-east-1', 194 | userPoolId: 'us-east-1_abcdef123', 195 | userPoolAppId: '123456789qwertyuiop987abcd', 196 | userPoolDomain: 'my-cognito-domain.auth.us-east-1.amazoncognito.com', 197 | cookieExpirationDays: 365, 198 | disableCookieDomain: false, 199 | cookiePath, 200 | }); 201 | authenticatorWithPath._jwtVerifier.cacheJwks(jwksData); 202 | 203 | const username = 'toto'; 204 | const domain = 'example.com'; 205 | const path = '/test'; 206 | jest.spyOn(authenticatorWithPath._jwtVerifier, 'verify'); 207 | authenticatorWithPath._jwtVerifier.verify.mockReturnValueOnce(Promise.resolve({ token_use: 'id', 'cognito:username': username })); 208 | 209 | const response = await authenticatorWithPath._getRedirectResponse({ accessToken: tokenData.access_token, idToken: tokenData.id_token, refreshToken: tokenData.refresh_token }, domain, path); 210 | expect(response).toMatchObject({ 211 | status: '302', 212 | headers: { 213 | location: [{ 214 | key: 'Location', 215 | value: path, 216 | }], 217 | }, 218 | }); 219 | expect(response?.headers?.['set-cookie']).toEqual(expect.arrayContaining([ 220 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.accessToken=${tokenData.access_token}; Domain=${domain}; Path=${cookiePath}; Expires=${DATE.toUTCString()}; Secure`}, 221 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.refreshToken=${tokenData.refresh_token}; Domain=${domain}; Path=${cookiePath}; Expires=${DATE.toUTCString()}; Secure`}, 222 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.tokenScopesString=phone%20email%20profile%20openid%20aws.cognito.signin.user.admin; Domain=${domain}; Path=${cookiePath}; Expires=${DATE.toUTCString()}; Secure`}, 223 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.idToken=${tokenData.id_token}; Domain=${domain}; Path=${cookiePath}; Expires=${DATE.toUTCString()}; Secure`}, 224 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.LastAuthUser=${username}; Domain=${domain}; Path=${cookiePath}; Expires=${DATE.toUTCString()}; Secure`}, 225 | ])); 226 | expect(authenticatorWithPath._jwtVerifier.verify).toHaveBeenCalled(); 227 | }); 228 | 229 | test('should set csrf tokens when the feature is enabled', async () => { 230 | const cookiePath = '/test/path'; 231 | const authenticatorWithPath = new Authenticator({ 232 | region: 'us-east-1', 233 | userPoolId: 'us-east-1_abcdef123', 234 | userPoolAppId: '123456789qwertyuiop987abcd', 235 | userPoolDomain: 'my-cognito-domain.auth.us-east-1.amazoncognito.com', 236 | cookieExpirationDays: 365, 237 | disableCookieDomain: false, 238 | cookiePath, 239 | csrfProtection: { 240 | nonceSigningSecret: 'foo-bar', 241 | }, 242 | }); 243 | authenticatorWithPath._jwtVerifier.cacheJwks(jwksData); 244 | 245 | const username = 'toto'; 246 | const domain = 'example.com'; 247 | const path = '/test'; 248 | jest.spyOn(authenticatorWithPath._jwtVerifier, 'verify'); 249 | authenticatorWithPath._jwtVerifier.verify.mockReturnValueOnce(Promise.resolve({ token_use: 'id', 'cognito:username': username })); 250 | 251 | const response = await authenticatorWithPath._getRedirectResponse({ accessToken: tokenData.access_token, idToken: tokenData.id_token, refreshToken: tokenData.refresh_token }, domain, path); 252 | expect(response).toMatchObject({ 253 | status: '302', 254 | headers: { 255 | location: [{ 256 | key: 'Location', 257 | value: path, 258 | }], 259 | }, 260 | }); 261 | expect(response?.headers?.['set-cookie']).toEqual(expect.arrayContaining([ 262 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.accessToken=${tokenData.access_token}; Domain=${domain}; Path=${cookiePath}; Expires=${DATE.toUTCString()}; Secure`}, 263 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.refreshToken=${tokenData.refresh_token}; Domain=${domain}; Path=${cookiePath}; Expires=${DATE.toUTCString()}; Secure`}, 264 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.tokenScopesString=phone%20email%20profile%20openid%20aws.cognito.signin.user.admin; Domain=${domain}; Path=${cookiePath}; Expires=${DATE.toUTCString()}; Secure`}, 265 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.idToken=${tokenData.id_token}; Domain=${domain}; Path=${cookiePath}; Expires=${DATE.toUTCString()}; Secure`}, 266 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.LastAuthUser=${username}; Domain=${domain}; Path=${cookiePath}; Expires=${DATE.toUTCString()}; Secure`}, 267 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${PKCE_COOKIE_NAME_SUFFIX}=; Path=${cookiePath}; Expires=${DATE.toUTCString()}; Secure`}, 268 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${NONCE_COOKIE_NAME_SUFFIX}=; Path=${cookiePath}; Expires=${DATE.toUTCString()}; Secure`}, 269 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${NONCE_HMAC_COOKIE_NAME_SUFFIX}=; Path=${cookiePath}; Expires=${DATE.toUTCString()}; Secure`}, 270 | ])); 271 | expect(authenticatorWithPath._jwtVerifier.verify).toHaveBeenCalled(); 272 | }); 273 | 274 | test('should use overriden cookie settings', async () => { 275 | const cookiePath = '/test/path'; 276 | const authenticatorWithPath = new Authenticator({ 277 | region: 'us-east-1', 278 | userPoolId: 'us-east-1_abcdef123', 279 | userPoolAppId: '123456789qwertyuiop987abcd', 280 | userPoolDomain: 'my-cognito-domain.auth.us-east-1.amazoncognito.com', 281 | cookieExpirationDays: 365, 282 | disableCookieDomain: false, 283 | cookiePath, 284 | httpOnly: true, 285 | csrfProtection: { 286 | nonceSigningSecret: 'foo-bar', 287 | }, 288 | cookieSettingsOverrides: { 289 | accessToken: { 290 | httpOnly: false, 291 | sameSite: 'Lax', 292 | path: '/foo', 293 | expirationDays: 2, 294 | }, 295 | }, 296 | }); 297 | authenticatorWithPath._jwtVerifier.cacheJwks(jwksData); 298 | 299 | const username = 'toto'; 300 | const domain = 'example.com'; 301 | const path = '/test'; 302 | jest.spyOn(authenticatorWithPath._jwtVerifier, 'verify'); 303 | authenticatorWithPath._jwtVerifier.verify.mockReturnValueOnce(Promise.resolve({ token_use: 'id', 'cognito:username': username })); 304 | 305 | const response = await authenticatorWithPath._getRedirectResponse({ accessToken: tokenData.access_token, idToken: tokenData.id_token, refreshToken: tokenData.refresh_token }, domain, path); 306 | expect(response).toMatchObject({ 307 | status: '302', 308 | headers: { 309 | location: [{ 310 | key: 'Location', 311 | value: path, 312 | }], 313 | }, 314 | }); 315 | expect(response?.headers?.['set-cookie']).toEqual(expect.arrayContaining([ 316 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.accessToken=${tokenData.access_token}; Domain=${domain}; Path=${'/foo'}; Expires=${DATE.toUTCString()}; Secure; SameSite=Lax`}, 317 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.refreshToken=${tokenData.refresh_token}; Domain=${domain}; Path=${cookiePath}; Expires=${DATE.toUTCString()}; Secure; HttpOnly`}, 318 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.tokenScopesString=phone%20email%20profile%20openid%20aws.cognito.signin.user.admin; Domain=${domain}; Path=${cookiePath}; Expires=${DATE.toUTCString()}; Secure; HttpOnly`}, 319 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.idToken=${tokenData.id_token}; Domain=${domain}; Path=${cookiePath}; Expires=${DATE.toUTCString()}; Secure; HttpOnly`}, 320 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.LastAuthUser=${username}; Domain=${domain}; Path=${cookiePath}; Expires=${DATE.toUTCString()}; Secure; HttpOnly`}, 321 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${PKCE_COOKIE_NAME_SUFFIX}=; Path=${cookiePath}; Expires=${DATE.toUTCString()}; Secure; HttpOnly`}, 322 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${NONCE_COOKIE_NAME_SUFFIX}=; Path=${cookiePath}; Expires=${DATE.toUTCString()}; Secure; HttpOnly`}, 323 | {key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${NONCE_HMAC_COOKIE_NAME_SUFFIX}=; Path=${cookiePath}; Expires=${DATE.toUTCString()}; Secure; HttpOnly`}, 324 | ])); 325 | expect(authenticatorWithPath._jwtVerifier.verify).toHaveBeenCalled(); 326 | }); 327 | 328 | test('should getIdTokenFromCookie', () => { 329 | const appClientName = 'toto,./;;..-_lol123'; 330 | expect( 331 | authenticator._getTokensFromCookie([{ 332 | key: 'Cookie', 333 | value: [ 334 | Cookies.serialize(`CognitoIdentityServiceProvider.5uka3k8840tap1g1i1617jh8pi.${appClientName}.idToken`, 'wrong'), 335 | Cookies.serialize(`CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${appClientName}.idToken`, tokenData.id_token), 336 | Cookies.serialize(`CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${appClientName}.idToken`, tokenData.id_token), 337 | Cookies.serialize(`CognitoIdentityServiceProvider.5ukasw8840tap1g1i1617jh8pi.${appClientName}.idToken`, 'wrong'), 338 | ].join('; '), 339 | }]), 340 | ).toMatchObject({idToken: tokenData.id_token}); 341 | 342 | expect( 343 | authenticator._getTokensFromCookie([{ 344 | key: 'Cookie', 345 | value: [ 346 | Cookies.serialize(`CognitoIdentityServiceProvider.5uka3k8840tap1g1i1617jh8pi.${appClientName}.accessToken`, tokenData.access_token), 347 | Cookies.serialize(`CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${appClientName}.idToken`, tokenData.id_token), 348 | ].join('; '), 349 | }]), 350 | ).toMatchObject({ idToken: tokenData.id_token}); 351 | 352 | 353 | expect( 354 | authenticator._getTokensFromCookie([{ 355 | key: 'Cookie', 356 | value: [ 357 | Cookies.serialize(`CognitoIdentityServiceProvider.5uka3k8840tap1g1i1617jh8pi.${appClientName}.accessToken`, tokenData.access_token), 358 | Cookies.serialize(`CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${appClientName}.idToken`, tokenData.id_token), 359 | Cookies.serialize(`CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${appClientName}.refreshToken`, tokenData.refresh_token), 360 | ].join('; '), 361 | }]), 362 | ).toMatchObject({ idToken: tokenData.id_token, refreshToken: tokenData.refresh_token}); 363 | }); 364 | 365 | test('should getTokensFromCookie throw on cookies', () => { 366 | expect(() => authenticator._getTokensFromCookie([])).toThrow('idToken'); 367 | }); 368 | 369 | describe('_validateCSRFCookies', () => { 370 | function buildRequest(tokensInState = {}, tokensInCookie = {}): CloudFrontRequest { 371 | const state = Buffer.from(JSON.stringify(tokensInState)).toString('base64'); 372 | 373 | const cookieHeaders: Array<{ key?: string | undefined; value: string; }> = []; 374 | for (const [name, value] of Object.entries(tokensInCookie)) { 375 | cookieHeaders.push({key: 'cookie', value: `${authenticator._cookieBase}.${name}=${value}`}); 376 | } 377 | return { 378 | clientIp: '', 379 | method: '', 380 | uri: '', 381 | querystring: `state=${state}`, 382 | headers: { 383 | 'cookie': cookieHeaders, 384 | }, 385 | }; 386 | } 387 | 388 | beforeEach(() => { 389 | authenticator._csrfProtection = { 390 | nonceSigningSecret: 'foo-bar', 391 | }; 392 | }); 393 | 394 | it('should throw error when nonce cookie is not present', () => { 395 | const request = buildRequest( 396 | {nonce: 'nonce-value'}, 397 | {} 398 | ); 399 | expect(() => authenticator._validateCSRFCookies(request)).toThrow( 400 | 'Your browser didn\'t send the nonce cookie along, but it is required for security (prevent CSRF).', 401 | ); 402 | }); 403 | 404 | it('should throw error when nonce cookie is different than the one encoded in state', () => { 405 | const request = buildRequest( 406 | {[NONCE_COOKIE_NAME_SUFFIX]: 'nonce-value'}, 407 | {[NONCE_COOKIE_NAME_SUFFIX]: 'nonce-value-different'} 408 | ); 409 | expect(() => authenticator._validateCSRFCookies(request)).toThrow( 410 | 'Nonce mismatch. This can happen if you start multiple authentication attempts in parallel (e.g. in separate tabs)', 411 | ); 412 | }); 413 | 414 | it('should throw error when pkce cookie is absent', () => { 415 | const request = buildRequest( 416 | {[NONCE_COOKIE_NAME_SUFFIX]: 'nonce-value', [PKCE_COOKIE_NAME_SUFFIX]: 'pkce-value'}, 417 | {[NONCE_COOKIE_NAME_SUFFIX]: 'nonce-value'} 418 | ); 419 | expect(() => authenticator._validateCSRFCookies(request)).toThrow( 420 | 'Your browser didn\'t send the pkce cookie along, but it is required for security (prevent CSRF).' 421 | ); 422 | }); 423 | 424 | it('should throw error when calculated Hmac is different than the one stored in the cookie', () => { 425 | jest.mock('../src/util/csrf', () => ({signNonce: () => 'nonce-hmac-value-different'})); 426 | const request = buildRequest( 427 | {[NONCE_COOKIE_NAME_SUFFIX]: 'nonce-value', [PKCE_COOKIE_NAME_SUFFIX]: 'pkce-value'}, 428 | {[NONCE_COOKIE_NAME_SUFFIX]: 'nonce-value', [PKCE_COOKIE_NAME_SUFFIX]: 'pkce-value', [NONCE_HMAC_COOKIE_NAME_SUFFIX]: 'nonce-hmac-value'} 429 | ); 430 | expect(() => authenticator._validateCSRFCookies(request)).toThrow( 431 | 'Nonce signature mismatch!' 432 | ); 433 | }); 434 | }); 435 | 436 | test('_revokeTokens', () => { 437 | axios.request = jest.fn().mockResolvedValue({ data: tokenData }); 438 | authenticator._revokeTokens({refreshToken: tokenData.refresh_token}); 439 | expect(axios.request).toHaveBeenCalledWith(expect.objectContaining({ 440 | url: 'https://my-cognito-domain.auth.us-east-1.amazoncognito.com/oauth2/revoke', 441 | method: 'POST', 442 | })); 443 | }); 444 | 445 | describe('_clearCookies', () => { 446 | it('should verify tokens and clear cookies', async () => { 447 | jest.spyOn(authenticator._jwtVerifier, 'verify'); 448 | authenticator._jwtVerifier.cacheJwks(jwksData); 449 | authenticator._jwtVerifier.verify.mockReturnValueOnce(Promise.resolve({})); 450 | const tokens = {idToken: tokenData.id_token, refreshToken: tokenData.refresh_token}; 451 | const response = await (authenticator as any)._clearCookies(getCloudfrontRequest(), tokens); 452 | expect(response).toEqual(expect.objectContaining({ 453 | status: '302', 454 | })); 455 | expect(response.headers['set-cookie']).toBeDefined(); 456 | expect(response.headers['set-cookie'].length).toBe(5); 457 | }); 458 | 459 | it('should clear cookies even if tokens cannot be verified', async () => { 460 | jest.spyOn(authenticator._jwtVerifier, 'verify'); 461 | authenticator._jwtVerifier.cacheJwks(jwksData); 462 | authenticator._jwtVerifier.verify.mockReturnValueOnce(Promise.reject({})); 463 | const tokens = {idToken: tokenData.id_token, refreshToken: tokenData.refresh_token}; 464 | const request = getCloudfrontRequest(); 465 | const numCookiesToBeCleared = request.Records[0].cf.request.headers['cookie']?.length || 0; 466 | const response = await (authenticator as any)._clearCookies(request, tokens); 467 | expect(response).toEqual(expect.objectContaining({ 468 | status: '302', 469 | })); 470 | expect(response.headers['set-cookie']).toBeDefined(); 471 | expect(response.headers['set-cookie'].length).toBe(numCookiesToBeCleared); 472 | }); 473 | 474 | it('should clear cookies and redirect to logoutRedirectUri', async () => { 475 | jest.spyOn(authenticator._jwtVerifier, 'verify'); 476 | authenticator._logoutConfiguration = { 477 | logoutUri: '/logout', 478 | logoutRedirectUri: 'https://foobar.com', 479 | }; 480 | authenticator._jwtVerifier.cacheJwks(jwksData); 481 | authenticator._jwtVerifier.verify.mockReturnValueOnce(Promise.resolve({})); 482 | const tokens = {idToken: tokenData.id_token, refreshToken: tokenData.refresh_token}; 483 | const response = await (authenticator as any)._clearCookies(getCloudfrontRequest(), tokens); 484 | expect(response).toEqual(expect.objectContaining({ status: '302' })); 485 | expect(response.headers['location']?.[0]?.value).toEqual('https://foobar.com'); 486 | }); 487 | 488 | it('should clear cookies and redirect to redirect_uri query param', async () => { 489 | jest.spyOn(authenticator._jwtVerifier, 'verify'); 490 | authenticator._jwtVerifier.cacheJwks(jwksData); 491 | authenticator._jwtVerifier.verify.mockReturnValueOnce(Promise.resolve({})); 492 | const request = getCloudfrontRequest(); 493 | request.Records[0].cf.request.querystring = 'redirect_uri=https://foobar.com'; 494 | const response = await (authenticator as any)._clearCookies(request); 495 | expect(response).toEqual(expect.objectContaining({ status: '302' })); 496 | expect(response.headers['location']?.[0]?.value).toEqual('https://foobar.com'); 497 | }); 498 | 499 | it('should clear cookies and redirect to cf domain', async () => { 500 | jest.spyOn(authenticator._jwtVerifier, 'verify'); 501 | authenticator._jwtVerifier.cacheJwks(jwksData); 502 | authenticator._jwtVerifier.verify.mockReturnValueOnce(Promise.resolve({})); 503 | const request = getCloudfrontRequest(); 504 | const response = await (authenticator as any)._clearCookies(request); 505 | expect(response).toEqual(expect.objectContaining({ status: '302' })); 506 | expect(response.headers['location']?.[0]?.value).toEqual('https://d111111abcdef8.cloudfront.net'); 507 | }); 508 | }); 509 | 510 | }); 511 | 512 | describe('createAuthenticator', () => { 513 | let params; 514 | 515 | beforeEach(() => { 516 | params = { 517 | region: 'us-east-1', 518 | userPoolId: 'us-east-1_abcdef123', 519 | userPoolAppId: '123456789qwertyuiop987abcd', 520 | userPoolDomain: 'my-cognito-domain.auth.us-east-1.amazoncognito.com', 521 | cookieExpirationDays: 365, 522 | disableCookieDomain: true, 523 | httpOnly: false, 524 | }; 525 | }); 526 | 527 | test('should create authenticator', () => { 528 | expect(typeof new Authenticator(params)).toBe('object'); 529 | }); 530 | 531 | test('should create authenticator without cookieExpirationDays', () => { 532 | delete params.cookieExpirationDays; 533 | expect(typeof new Authenticator(params)).toBe('object'); 534 | }); 535 | 536 | test('should create authenticator without disableCookieDomain', () => { 537 | delete params.disableCookieDomain; 538 | expect(typeof new Authenticator(params)).toBe('object'); 539 | }); 540 | 541 | test('should create authenticator without cookieDomain', () => { 542 | delete params.cookieDomain; 543 | expect(typeof new Authenticator(params)).toBe('object'); 544 | }); 545 | 546 | test('should create authenticator without httpOnly', () => { 547 | delete params.httpOnly; 548 | expect(typeof new Authenticator(params)).toBe('object'); 549 | }); 550 | 551 | test('should create authenticator without cookiePath', () => { 552 | delete params.cookiePath; 553 | expect(typeof new Authenticator(params)).toBe('object'); 554 | }); 555 | 556 | test('should create authenticator with unvalidated samesite', () => { 557 | params.sameSite = '123'; 558 | expect(() => new Authenticator(params)).toThrow('Expected params'); 559 | }); 560 | 561 | test('should fail when creating authenticator without params', () => { 562 | // @ts-ignore 563 | // ts-ignore is used here to override typescript's type check in the constructor 564 | // this test is still useful when the library is imported to a js file 565 | expect(() => new Authenticator()).toThrow('Expected params'); 566 | }); 567 | 568 | test('should fail when creating authenticator without region', () => { 569 | delete params.region; 570 | expect(() => new Authenticator(params)).toThrow('region'); 571 | }); 572 | 573 | test('should fail when creating authenticator without userPoolId', () => { 574 | delete params.userPoolId; 575 | expect(() => new Authenticator(params)).toThrow('userPoolId'); 576 | }); 577 | 578 | test('should fail when creating authenticator without userPoolAppId', () => { 579 | delete params.userPoolAppId; 580 | expect(() => new Authenticator(params)).toThrow('userPoolAppId'); 581 | }); 582 | 583 | test('should fail when creating authenticator without userPoolDomain', () => { 584 | delete params.userPoolDomain; 585 | expect(() => new Authenticator(params)).toThrow('userPoolDomain'); 586 | }); 587 | 588 | test('should fail when creating authenticator with invalid region', () => { 589 | params.region = 123; 590 | expect(() => new Authenticator(params)).toThrow('region'); 591 | }); 592 | 593 | test('should fail when creating authenticator with invalid userPoolId', () => { 594 | params.userPoolId = 123; 595 | expect(() => new Authenticator(params)).toThrow('userPoolId'); 596 | }); 597 | 598 | test('should fail when creating authenticator with invalid userPoolAppId', () => { 599 | params.userPoolAppId = 123; 600 | expect(() => new Authenticator(params)).toThrow('userPoolAppId'); 601 | }); 602 | 603 | test('should fail when creating authenticator with invalid userPoolDomain', () => { 604 | params.userPoolDomain = 123; 605 | expect(() => new Authenticator(params)).toThrow('userPoolDomain'); 606 | }); 607 | 608 | test('should fail when creating authenticator with invalid cookieExpirationDays', () => { 609 | params.cookieExpirationDays = '123'; 610 | expect(() => new Authenticator(params)).toThrow('cookieExpirationDays'); 611 | }); 612 | 613 | test('should fail when creating authenticator with invalid disableCookieDomain', () => { 614 | params.disableCookieDomain = '123'; 615 | expect(() => new Authenticator(params)).toThrow('disableCookieDomain'); 616 | }); 617 | 618 | test('should fail when creating authenticator with invalid cookie domain', () => { 619 | params.cookieDomain = 123; 620 | expect(() => new Authenticator(params)).toThrow('cookieDomain'); 621 | }); 622 | 623 | test('should fail when creating authenticator with invalid httpOnly', () => { 624 | params.httpOnly = '123'; 625 | expect(() => new Authenticator(params)).toThrow('httpOnly'); 626 | }); 627 | 628 | test('should fail when creating authenticator with invalid cookiePath', () => { 629 | params.cookiePath = 123; 630 | expect(() => new Authenticator(params)).toThrow('cookiePath'); 631 | }); 632 | 633 | test('should fail when creating authenticator with invalid logoutUri', () => { 634 | params.logoutConfiguration = { logoutUri: '' }; 635 | expect(() => new Authenticator(params)).toThrow('logoutUri'); 636 | 637 | params.logoutConfiguration = { logoutUri: '/' }; 638 | expect(() => new Authenticator(params)).toThrow('logoutUri'); 639 | }); 640 | }); 641 | 642 | describe('handle', () => { 643 | let authenticator; 644 | 645 | beforeEach(() => { 646 | authenticator = new Authenticator({ 647 | region: 'us-east-1', 648 | userPoolId: 'us-east-1_abcdef123', 649 | userPoolAppId: '123456789qwertyuiop987abcd', 650 | userPoolDomain: 'my-cognito-domain.auth.us-east-1.amazoncognito.com', 651 | cookieExpirationDays: 365, 652 | }); 653 | authenticator._jwtVerifier.cacheJwks(jwksData); 654 | jest.spyOn(authenticator, '_getTokensFromCookie'); 655 | jest.spyOn(authenticator, '_fetchTokensFromCode'); 656 | jest.spyOn(authenticator, '_fetchTokensFromRefreshToken'); 657 | jest.spyOn(authenticator, '_getRedirectResponse'); 658 | jest.spyOn(authenticator, '_getRedirectToCognitoUserPoolResponse'); 659 | jest.spyOn(authenticator, '_revokeTokens'); 660 | jest.spyOn(authenticator, '_clearCookies'); 661 | jest.spyOn(authenticator._jwtVerifier, 'verify'); 662 | }); 663 | 664 | test('should forward request if authenticated', () => { 665 | authenticator._jwtVerifier.verify.mockReturnValueOnce(Promise.resolve({})); 666 | return expect(authenticator.handle(getCloudfrontRequest())).resolves.toEqual(getCloudfrontRequest().Records[0].cf.request) 667 | .then(() => { 668 | expect(authenticator._getTokensFromCookie).toHaveBeenCalled(); 669 | expect(authenticator._jwtVerifier.verify).toHaveBeenCalled(); 670 | }); 671 | }); 672 | 673 | test('should fetch with refresh token if available', () => { 674 | authenticator._jwtVerifier.verify.mockReturnValueOnce(Promise.reject({})); 675 | authenticator._getTokensFromCookie.mockReturnValueOnce({refreshToken: tokenData.refresh_token}); 676 | authenticator._fetchTokensFromRefreshToken.mockResolvedValueOnce(tokenData); 677 | authenticator._getRedirectResponse.mockReturnValueOnce({ response: 'toto' }); 678 | const request = getCloudfrontRequest(); 679 | request.Records[0].cf.request.querystring = 'code=54fe5f4e&state=/lol'; 680 | return expect(authenticator.handle(request)).resolves.toEqual({ response: 'toto' }) 681 | .then(() => { 682 | expect(authenticator._getTokensFromCookie).toHaveBeenCalled(); 683 | expect(authenticator._jwtVerifier.verify).toHaveBeenCalled(); 684 | expect(authenticator._fetchTokensFromRefreshToken).toHaveBeenCalled(); 685 | expect(authenticator._getRedirectResponse).toHaveBeenCalledWith(tokenData, 'd111111abcdef8.cloudfront.net', '/lol'); 686 | }); 687 | }); 688 | 689 | test('should redirect to cognito if refresh token is invalid', () => { 690 | authenticator._jwtVerifier.verify.mockReturnValueOnce(Promise.reject({})); 691 | authenticator._getTokensFromCookie.mockReturnValueOnce({refreshToken: tokenData.refresh_token}); 692 | authenticator._fetchTokensFromRefreshToken.mockReturnValueOnce(Promise.reject({})); 693 | authenticator._getRedirectToCognitoUserPoolResponse.mockReturnValueOnce({ response: 'toto' }); 694 | const request = getCloudfrontRequest(); 695 | return expect(authenticator.handle(request)).resolves.toEqual({ response: 'toto' }) 696 | .then(() => { 697 | expect(authenticator._getTokensFromCookie).toHaveBeenCalled(); 698 | expect(authenticator._jwtVerifier.verify).toHaveBeenCalled(); 699 | expect(authenticator._fetchTokensFromRefreshToken).toHaveBeenCalled(); 700 | }); 701 | }); 702 | 703 | test('should fetch and set token if code is present', () => { 704 | authenticator._jwtVerifier.verify.mockImplementationOnce(async () => { throw new Error(); }); 705 | authenticator._fetchTokensFromCode.mockResolvedValueOnce(tokenData); 706 | authenticator._getRedirectResponse.mockReturnValueOnce({ response: 'toto' }); 707 | const request = getCloudfrontRequest(); 708 | request.Records[0].cf.request.querystring = 'code=54fe5f4e&state=/lol'; 709 | return expect(authenticator.handle(request)).resolves.toEqual({ response: 'toto' }) 710 | .then(() => { 711 | expect(authenticator._jwtVerifier.verify).toHaveBeenCalled(); 712 | expect(authenticator._fetchTokensFromCode).toHaveBeenCalled(); 713 | expect(authenticator._getRedirectResponse).toHaveBeenCalledWith(tokenData, 'd111111abcdef8.cloudfront.net', '/lol'); 714 | }); 715 | }); 716 | 717 | test('should fetch and set token if code is present (custom redirect)', () => { 718 | const authenticatorWithCustomRedirect : any = new Authenticator({ 719 | region: 'us-east-1', 720 | userPoolId: 'us-east-1_abcdef123', 721 | userPoolAppId: '123456789qwertyuiop987abcd', 722 | userPoolDomain: 'my-cognito-domain.auth.us-east-1.amazoncognito.com', 723 | parseAuthPath: '/custom/login/path', 724 | }); 725 | jest.spyOn(authenticatorWithCustomRedirect._jwtVerifier, 'verify'); 726 | jest.spyOn(authenticatorWithCustomRedirect, '_fetchTokensFromCode'); 727 | jest.spyOn(authenticatorWithCustomRedirect, '_getRedirectResponse'); 728 | authenticatorWithCustomRedirect._jwtVerifier.verify.mockImplementationOnce(async () => { throw new Error(); }); 729 | authenticatorWithCustomRedirect._fetchTokensFromCode.mockResolvedValueOnce(tokenData); 730 | authenticatorWithCustomRedirect._getRedirectResponse.mockReturnValueOnce({ response: 'toto' }); 731 | const request = getCloudfrontRequest(); 732 | request.Records[0].cf.request.querystring = 'code=54fe5f4e&state=/lol'; 733 | return expect(authenticatorWithCustomRedirect.handle(request)).resolves.toEqual({ response: 'toto' }) 734 | .then(() => { 735 | expect(authenticatorWithCustomRedirect._jwtVerifier.verify).toHaveBeenCalled(); 736 | expect(authenticatorWithCustomRedirect._fetchTokensFromCode).toHaveBeenCalledWith('https://d111111abcdef8.cloudfront.net/custom/login/path', '54fe5f4e'); 737 | expect(authenticatorWithCustomRedirect._getRedirectResponse).toHaveBeenCalledWith(tokenData, 'd111111abcdef8.cloudfront.net', '/lol'); 738 | }); 739 | }); 740 | 741 | 742 | test('should fetch and set token if code is present and when csrfProtection is enabled', () => { 743 | authenticator._jwtVerifier.verify.mockImplementationOnce(async () => { throw new Error(); }); 744 | authenticator._fetchTokensFromCode.mockResolvedValueOnce(tokenData); 745 | authenticator._getRedirectResponse.mockReturnValueOnce({ response: 'toto' }); 746 | authenticator._csrfProtection = { 747 | nonceSigningSecret: 'foobar', 748 | }; 749 | const encodedState = Buffer.from( 750 | JSON.stringify({ redirect_uri: '/lol' }) 751 | ).toString('base64'); 752 | const request = getCloudfrontRequest(); 753 | request.Records[0].cf.request.querystring = `code=54fe5f4e&state=${encodedState}`; 754 | return expect(authenticator.handle(request)).resolves.toEqual({ response: 'toto' }) 755 | .then(() => { 756 | expect(authenticator._jwtVerifier.verify).toHaveBeenCalled(); 757 | expect(authenticator._fetchTokensFromCode).toHaveBeenCalled(); 758 | expect(authenticator._getRedirectResponse).toHaveBeenCalledWith(tokenData, 'd111111abcdef8.cloudfront.net', '/lol'); 759 | }); 760 | }); 761 | 762 | test('should redirect to auth domain if unauthenticated and no code', () => { 763 | authenticator._jwtVerifier.verify.mockImplementationOnce(async () => { throw new Error();}); 764 | return expect(authenticator.handle(getCloudfrontRequest())).resolves.toEqual( 765 | { 766 | status: '302', 767 | headers: { 768 | 'location': [{ 769 | key: 'Location', 770 | value: 'https://my-cognito-domain.auth.us-east-1.amazoncognito.com/authorize?redirect_uri=https://d111111abcdef8.cloudfront.net&response_type=code&client_id=123456789qwertyuiop987abcd&state=/lol%3F%3Fparam%3D1', 771 | }], 772 | 'cache-control': [{ 773 | key: 'Cache-Control', 774 | value: 'no-cache, no-store, max-age=0, must-revalidate', 775 | }], 776 | 'pragma': [{ 777 | key: 'Pragma', 778 | value: 'no-cache', 779 | }], 780 | }, 781 | }, 782 | ) 783 | .then(() => { 784 | expect(authenticator._jwtVerifier.verify).toHaveBeenCalled(); 785 | }); 786 | }); 787 | 788 | test('should redirect to auth domain if unauthenticated and no code (custom redirect)', () => { 789 | const authenticatorWithCustomRedirect : any = new Authenticator({ 790 | region: 'us-east-1', 791 | userPoolId: 'us-east-1_abcdef123', 792 | userPoolAppId: '123456789qwertyuiop987abcd', 793 | userPoolDomain: 'my-cognito-domain.auth.us-east-1.amazoncognito.com', 794 | parseAuthPath: '/custom/login/path', 795 | }); 796 | jest.spyOn(authenticatorWithCustomRedirect._jwtVerifier, 'verify'); 797 | authenticator._jwtVerifier.verify.mockImplementationOnce(async () => { throw new Error();}); 798 | return expect(authenticatorWithCustomRedirect.handle(getCloudfrontRequest())).resolves.toEqual( 799 | { 800 | status: '302', 801 | headers: { 802 | 'location': [{ 803 | key: 'Location', 804 | value: 'https://my-cognito-domain.auth.us-east-1.amazoncognito.com/authorize?redirect_uri=https://d111111abcdef8.cloudfront.net/custom/login/path&response_type=code&client_id=123456789qwertyuiop987abcd&state=/lol%3F%3Fparam%3D1', 805 | }], 806 | 'cache-control': [{ 807 | key: 'Cache-Control', 808 | value: 'no-cache, no-store, max-age=0, must-revalidate', 809 | }], 810 | 'pragma': [{ 811 | key: 'Pragma', 812 | value: 'no-cache', 813 | }], 814 | }, 815 | }, 816 | ) 817 | .then(() => { 818 | expect(authenticatorWithCustomRedirect._jwtVerifier.verify).toHaveBeenCalled(); 819 | }); 820 | }); 821 | 822 | test('should redirect to auth domain and clear csrf cookies if unauthenticated and no code', async () => { 823 | authenticator._jwtVerifier.verify.mockImplementationOnce(async () => { throw new Error(); }); 824 | authenticator._csrfProtection = { 825 | nonceSigningSecret: 'foo-bar', 826 | }; 827 | const response = await authenticator.handle(getCloudfrontRequest()); 828 | expect(response).toMatchObject({ 829 | status: '302', 830 | headers: { 831 | 'cache-control': [{ 832 | key: 'Cache-Control', 833 | value: 'no-cache, no-store, max-age=0, must-revalidate', 834 | }], 835 | 'pragma': [{ 836 | key: 'Pragma', 837 | value: 'no-cache', 838 | }], 839 | }, 840 | }); 841 | const url = new URL(response.headers['location'][0].value); 842 | expect(url.origin).toEqual('https://my-cognito-domain.auth.us-east-1.amazoncognito.com'); 843 | expect(url.pathname).toEqual('/authorize'); 844 | expect(url.searchParams.get('redirect_uri')).toEqual('https://d111111abcdef8.cloudfront.net'); 845 | expect(url.searchParams.get('response_type')).toEqual('code'); 846 | expect(url.searchParams.get('client_id')).toEqual('123456789qwertyuiop987abcd'); 847 | expect(url.searchParams.get('state')).toBeDefined(); 848 | 849 | // Cookies 850 | expect(response.headers['set-cookie']).toBeDefined(); 851 | const cookies = response.headers['set-cookie'].map(h => h.value); 852 | expect(cookies.find(c => c.match(`.${NONCE_COOKIE_NAME_SUFFIX}=`))).toBeDefined(); 853 | expect(cookies.find(c => c.match(`.${NONCE_HMAC_COOKIE_NAME_SUFFIX}=`))).toBeDefined(); 854 | expect(cookies.find(c => c.match(`.${PKCE_COOKIE_NAME_SUFFIX}=`))).toBeDefined(); 855 | }); 856 | 857 | test('should redirect to auth domain with custom return redirect if unauthenticated', async () => { 858 | const authenticatorWithCustomRedirect : any = new Authenticator({ 859 | region: 'us-east-1', 860 | userPoolId: 'us-east-1_abcdef123', 861 | userPoolAppId: '123456789qwertyuiop987abcd', 862 | userPoolDomain: 'my-cognito-domain.auth.us-east-1.amazoncognito.com', 863 | parseAuthPath: '/custom/login/path', 864 | }); 865 | jest.spyOn(authenticatorWithCustomRedirect._jwtVerifier, 'verify'); 866 | authenticatorWithCustomRedirect._jwtVerifier.verify.mockImplementationOnce(async () => { throw new Error(); }); 867 | const response = await authenticatorWithCustomRedirect.handle(getCloudfrontRequest()); 868 | const url = new URL(response.headers['location'][0].value); 869 | expect(url.searchParams.get('redirect_uri')).toEqual('https://d111111abcdef8.cloudfront.net/custom/login/path'); 870 | }); 871 | 872 | test('should revoke tokens and clear cookies if logoutConfiguration is set', () => { 873 | authenticator._logoutConfiguration = { logoutUri: '/logout' }; 874 | authenticator._getTokensFromCookie.mockReturnValueOnce({ refreshToken: tokenData.refresh_token }); 875 | authenticator._revokeTokens.mockReturnValueOnce(Promise.resolve()); 876 | authenticator._clearCookies.mockReturnValueOnce(Promise.resolve({ status: '302' })); 877 | const request = getCloudfrontRequest(); 878 | request.Records[0].cf.request.uri = '/logout'; 879 | return expect(authenticator.handle(request)).resolves.toEqual(expect.objectContaining({ status: '302' })) 880 | .then(() => { 881 | expect(authenticator._getTokensFromCookie).toHaveBeenCalled(); 882 | expect(authenticator._revokeTokens).toHaveBeenCalled(); 883 | expect(authenticator._clearCookies).toHaveBeenCalled(); 884 | }); 885 | }); 886 | 887 | test('should clear cookies if logoutConfiguration is set even if user is unauthenticated', async () => { 888 | authenticator._logoutConfiguration = { logoutUri: '/logout' }; 889 | authenticator._getTokensFromCookie.mockImplementationOnce(() => { throw new Error(); }); 890 | authenticator._clearCookies.mockReturnValueOnce(Promise.resolve({ status: '302' })); 891 | const request = getCloudfrontRequest(); 892 | request.Records[0].cf.request.uri = '/logout'; 893 | return expect(authenticator.handle(request)).resolves.toEqual(expect.objectContaining({ status: '302' })) 894 | .then(() => { 895 | expect(authenticator._getTokensFromCookie).toHaveBeenCalled(); 896 | expect(authenticator._revokeTokens).not.toHaveBeenCalled(); 897 | expect(authenticator._clearCookies).toHaveBeenCalled(); 898 | }); 899 | }); 900 | }); 901 | 902 | describe('handleSignIn', () => { 903 | let authenticator; 904 | 905 | beforeEach(() => { 906 | authenticator = new Authenticator({ 907 | region: 'us-east-1', 908 | userPoolId: 'us-east-1_abcdef123', 909 | userPoolAppId: '123456789qwertyuiop987abcd', 910 | userPoolDomain: 'my-cognito-domain.auth.us-east-1.amazoncognito.com', 911 | cookieExpirationDays: 365, 912 | parseAuthPath: 'parseAuth', 913 | }); 914 | authenticator._jwtVerifier.cacheJwks(jwksData); 915 | jest.spyOn(authenticator, '_getTokensFromCookie'); 916 | jest.spyOn(authenticator, '_getRedirectToCognitoUserPoolResponse'); 917 | jest.spyOn(authenticator._jwtVerifier, 'verify'); 918 | }); 919 | 920 | test('should forward request if authenticated', async () => { 921 | authenticator._jwtVerifier.verify.mockReturnValueOnce(Promise.resolve({})); 922 | const request = getCloudfrontRequest(); 923 | request.Records[0].cf.request.querystring = 'redirect_uri=https://example.aws.com'; 924 | const response = await authenticator.handleSignIn(request); 925 | expect(response.status).toEqual('302'); 926 | expect(response.headers?.location).toBeDefined(); 927 | expect(response.headers.location[0].value).toEqual('https://example.aws.com'); 928 | }); 929 | 930 | test('should redirect to cognito if refresh token is invalid', () => { 931 | authenticator._jwtVerifier.verify.mockReturnValueOnce(Promise.reject({})); 932 | authenticator._getTokensFromCookie.mockReturnValueOnce({refreshToken: tokenData.refresh_token}); 933 | authenticator._getRedirectToCognitoUserPoolResponse.mockReturnValueOnce({ response: 'toto' }); 934 | const request = getCloudfrontRequest(); 935 | return expect(authenticator.handleSignIn(request)).resolves.toEqual({ response: 'toto' }) 936 | .then(() => { 937 | expect(authenticator._getTokensFromCookie).toHaveBeenCalled(); 938 | expect(authenticator._jwtVerifier.verify).toHaveBeenCalled(); 939 | expect(authenticator._getRedirectToCognitoUserPoolResponse).toHaveBeenCalled(); 940 | }); 941 | }); 942 | }); 943 | 944 | describe('handleParseAuth', () => { 945 | let authenticator; 946 | 947 | beforeEach(() => { 948 | authenticator = new Authenticator({ 949 | region: 'us-east-1', 950 | userPoolId: 'us-east-1_abcdef123', 951 | userPoolAppId: '123456789qwertyuiop987abcd', 952 | userPoolDomain: 'my-cognito-domain.auth.us-east-1.amazoncognito.com', 953 | cookieExpirationDays: 365, 954 | parseAuthPath: 'parseAuth', 955 | }); 956 | authenticator._jwtVerifier.cacheJwks(jwksData); 957 | jest.spyOn(authenticator, '_validateCSRFCookies'); 958 | jest.spyOn(authenticator, '_fetchTokensFromCode'); 959 | jest.spyOn(authenticator, '_getTokensFromCookie'); 960 | jest.spyOn(authenticator, '_getRedirectResponse'); 961 | }); 962 | 963 | describe('if code is present', () => { 964 | test('should redirect successfully if csrfProtection is not enabled', async () => { 965 | authenticator._fetchTokensFromCode.mockReturnValueOnce(Promise.resolve({ 966 | idToken: tokenData.id_token, 967 | refreshToken: tokenData.refresh_token, 968 | accessToken: tokenData.access_token, 969 | })); 970 | authenticator._getRedirectResponse.mockReturnValueOnce({ response: 'toto' }); 971 | const state = Buffer.from(JSON.stringify({ 972 | nonce: 'nonceValue', 973 | nonceHmac: 'nonceHmacValue', 974 | pkce: 'pkceValue', 975 | })).toString('base64'); 976 | const request = getCloudfrontRequest(); 977 | request.Records[0].cf.request.querystring = `code=code&state=${state}`; 978 | return expect(authenticator.handleParseAuth(request)).resolves.toEqual({ response: 'toto' }) 979 | .then(() => { 980 | expect(authenticator._validateCSRFCookies).not.toHaveBeenCalled(); 981 | expect(authenticator._fetchTokensFromCode).toHaveBeenCalled(); 982 | expect(authenticator._getRedirectResponse).toHaveBeenCalled(); 983 | }); 984 | }); 985 | 986 | test('should redirect successfully after validating CSRF tokens', async () => { 987 | authenticator._csrfProtection = { 988 | nonceSigningSecret: 'foo-bar', 989 | }; 990 | authenticator._validateCSRFCookies.mockReturnValueOnce(); 991 | authenticator._fetchTokensFromCode.mockReturnValueOnce(Promise.resolve({ 992 | idToken: tokenData.id_token, 993 | refreshToken: tokenData.refresh_token, 994 | accessToken: tokenData.access_token, 995 | })); 996 | authenticator._getRedirectResponse.mockReturnValueOnce({ response: 'toto' }); 997 | const state = Buffer.from(JSON.stringify({ 998 | nonce: 'nonceValue', 999 | nonceHmac: 'nonceHmacValue', 1000 | pkce: 'pkceValue', 1001 | })).toString('base64'); 1002 | const request = getCloudfrontRequest(); 1003 | request.Records[0].cf.request.querystring = `code=code&state=${state}`; 1004 | return expect(authenticator.handleParseAuth(request)).resolves.toEqual({ response: 'toto' }) 1005 | .then(() => { 1006 | expect(authenticator._validateCSRFCookies).toHaveBeenCalled(); 1007 | expect(authenticator._fetchTokensFromCode).toHaveBeenCalled(); 1008 | expect(authenticator._getRedirectResponse).toHaveBeenCalled(); 1009 | }); 1010 | }); 1011 | }); 1012 | 1013 | test('should throw error when parseAuthPath is not set', async () => { 1014 | authenticator._parseAuthPath = ''; 1015 | authenticator._getRedirectResponse.mockReturnValueOnce({ response: 'toto' }); 1016 | return expect(authenticator.handleParseAuth(getCloudfrontRequest())).resolves.toEqual({ status: '400', body: expect.stringContaining('parseAuthPath')}) 1017 | .then(() => { 1018 | expect(authenticator._validateCSRFCookies).not.toHaveBeenCalled(); 1019 | expect(authenticator._fetchTokensFromCode).not.toHaveBeenCalled(); 1020 | expect(authenticator._getRedirectResponse).not.toHaveBeenCalled(); 1021 | }); 1022 | }); 1023 | 1024 | test('should throw if code is absent', async () => { 1025 | authenticator._validateCSRFCookies.mockImplementationOnce(async () => { throw new Error(); }); 1026 | return expect(authenticator.handleParseAuth(getCloudfrontRequest())).resolves.toEqual(expect.objectContaining({ status: '400' })) 1027 | .then(() => { 1028 | expect(authenticator._validateCSRFCookies).not.toHaveBeenCalled(); 1029 | expect(authenticator._fetchTokensFromCode).not.toHaveBeenCalled(); 1030 | expect(authenticator._getRedirectResponse).not.toHaveBeenCalled(); 1031 | }); 1032 | }); 1033 | }); 1034 | 1035 | describe('handleRefreshToken', () => { 1036 | let authenticator; 1037 | 1038 | beforeEach(() => { 1039 | authenticator = new Authenticator({ 1040 | region: 'us-east-1', 1041 | userPoolId: 'us-east-1_abcdef123', 1042 | userPoolAppId: '123456789qwertyuiop987abcd', 1043 | userPoolDomain: 'my-cognito-domain.auth.us-east-1.amazoncognito.com', 1044 | cookieExpirationDays: 365, 1045 | }); 1046 | authenticator._jwtVerifier.cacheJwks(jwksData); 1047 | jest.spyOn(authenticator, '_getTokensFromCookie'); 1048 | jest.spyOn(authenticator._jwtVerifier, 'verify'); 1049 | jest.spyOn(authenticator, '_fetchTokensFromRefreshToken'); 1050 | jest.spyOn(authenticator, '_getRedirectResponse'); 1051 | jest.spyOn(authenticator, '_getRedirectToCognitoUserPoolResponse'); 1052 | }); 1053 | 1054 | test('should refresh tokens successfully', async () => { 1055 | const username = 'toto'; 1056 | authenticator._getTokensFromCookie.mockReturnValueOnce({ refreshToken: tokenData.refresh_token }); 1057 | authenticator._jwtVerifier.verify.mockReturnValueOnce(Promise.resolve({ token_use: 'id', 'cognito:username': username })); 1058 | authenticator._fetchTokensFromRefreshToken.mockReturnValueOnce(Promise.resolve({ 1059 | idToken: tokenData.id_token, 1060 | refreshToken: tokenData.refresh_token, 1061 | accessToken: tokenData.access_token, 1062 | })); 1063 | authenticator._getRedirectResponse.mockReturnValueOnce({ response: 'toto' }); 1064 | return expect(authenticator.handleRefreshToken(getCloudfrontRequest())).resolves.toEqual({ response: 'toto' }) 1065 | .then(() => { 1066 | expect(authenticator._getTokensFromCookie).toHaveBeenCalled(); 1067 | expect(authenticator._jwtVerifier.verify).toHaveBeenCalled(); 1068 | expect(authenticator._fetchTokensFromRefreshToken).toHaveBeenCalled(); 1069 | expect(authenticator._getRedirectResponse).toHaveBeenCalled(); 1070 | }); 1071 | }); 1072 | 1073 | test('should redirect to cognito user pool if refresh token is invalid', () => { 1074 | authenticator._getTokensFromCookie.mockReturnValueOnce({ refreshToken: tokenData.refresh_token }); 1075 | authenticator._jwtVerifier.verify.mockReturnValueOnce(Promise.reject()); 1076 | return expect(authenticator.handleRefreshToken(getCloudfrontRequest())).resolves.toEqual(expect.objectContaining({ status: '302' })) 1077 | .then(() => { 1078 | expect(authenticator._getTokensFromCookie).toHaveBeenCalled(); 1079 | expect(authenticator._jwtVerifier.verify).toHaveBeenCalled(); 1080 | expect(authenticator._fetchTokensFromRefreshToken).not.toHaveBeenCalled(); 1081 | expect(authenticator._getRedirectResponse).not.toHaveBeenCalled(); 1082 | }); 1083 | }); 1084 | }); 1085 | 1086 | describe('handleSignOut', () => { 1087 | let authenticator; 1088 | 1089 | beforeEach(() => { 1090 | authenticator = new Authenticator({ 1091 | region: 'us-east-1', 1092 | userPoolId: 'us-east-1_abcdef123', 1093 | userPoolAppId: '123456789qwertyuiop987abcd', 1094 | userPoolDomain: 'my-cognito-domain.auth.us-east-1.amazoncognito.com', 1095 | cookieExpirationDays: 365, 1096 | }); 1097 | authenticator._jwtVerifier.cacheJwks(jwksData); 1098 | jest.spyOn(authenticator, '_getTokensFromCookie'); 1099 | jest.spyOn(authenticator, '_revokeTokens'); 1100 | jest.spyOn(authenticator, '_clearCookies'); 1101 | }); 1102 | 1103 | test('should revoke tokens and clear cookies successfully', async () => { 1104 | authenticator._getTokensFromCookie.mockReturnValueOnce({ refreshToken: tokenData.refresh_token }); 1105 | authenticator._revokeTokens.mockReturnValueOnce(Promise.resolve()); 1106 | authenticator._clearCookies.mockReturnValueOnce(Promise.resolve({ status: '302' })); 1107 | return expect(authenticator.handleSignOut(getCloudfrontRequest())).resolves.toEqual(expect.objectContaining({ status: '302' })) 1108 | .then(() => { 1109 | expect(authenticator._getTokensFromCookie).toHaveBeenCalled(); 1110 | expect(authenticator._revokeTokens).toHaveBeenCalled(); 1111 | expect(authenticator._clearCookies).toHaveBeenCalled(); 1112 | }); 1113 | }); 1114 | 1115 | test('should clear cookies successfully even if tokens cannot be revoked', async () => { 1116 | authenticator._getTokensFromCookie.mockReturnValueOnce({ refreshToken: tokenData.refresh_token }); 1117 | authenticator._revokeTokens.mockReturnValueOnce(Promise.reject()); 1118 | authenticator._clearCookies.mockReturnValueOnce(Promise.resolve({ status: '302' })); 1119 | return expect(authenticator.handleSignOut(getCloudfrontRequest())).resolves.toEqual(expect.objectContaining({ status: '302' })) 1120 | .then(() => { 1121 | expect(authenticator._getTokensFromCookie).toHaveBeenCalled(); 1122 | expect(authenticator._revokeTokens).toHaveBeenCalled(); 1123 | expect(authenticator._clearCookies).toHaveBeenCalled(); 1124 | }); 1125 | }); 1126 | }); 1127 | /* eslint-disable quotes, comma-dangle */ 1128 | 1129 | const jwksData = { 1130 | "keys": [ 1131 | { "kid": "1234example=", "alg": "RS256", "kty": "RSA", "e": "AQAB", "n": "1234567890", "use": "sig" }, 1132 | { "kid": "5678example=", "alg": "RS256", "kty": "RSA", "e": "AQAB", "n": "987654321", "use": "sig" }, 1133 | ] 1134 | }; 1135 | 1136 | const tokenData = { 1137 | "access_token":"eyJz9sdfsdfsdfsd", 1138 | "refresh_token":"dn43ud8uj32nk2je", 1139 | "id_token":"dmcxd329ujdmkemkd349r", 1140 | "token_type":"Bearer", 1141 | 'expires_in':3600, 1142 | }; 1143 | 1144 | const getCloudfrontRequest = () => ({ 1145 | "Records": [ 1146 | { 1147 | "cf": { 1148 | "config": { 1149 | "distributionDomainName": "d123.cloudfront.net", 1150 | "distributionId": "EDFDVBD6EXAMPLE", 1151 | "eventType": "viewer-request", 1152 | "requestId": "MRVMF7KydIvxMWfJIglgwHQwZsbG2IhRJ07sn9AkKUFSHS9EXAMPLE==" 1153 | }, 1154 | "request": { 1155 | "body": { 1156 | "action": "read-only", 1157 | "data": "eyJ1c2VybmFtZSI6IkxhbWJkYUBFZGdlIiwiY29tbWVudCI6IlRoaXMgaXMgcmVxdWVzdCBib2R5In0=", 1158 | "encoding": "base64", 1159 | "inputTruncated": false 1160 | }, 1161 | "clientIp": "2001:0db8:85a3:0:0:8a2e:0370:7334", 1162 | "querystring": "?param=1", 1163 | "uri": "/lol", 1164 | "method": "GET", 1165 | "headers": { 1166 | "host": [ 1167 | { 1168 | "key": "Host", 1169 | "value": "d111111abcdef8.cloudfront.net" 1170 | } 1171 | ], 1172 | "user-agent": [ 1173 | { 1174 | "key": "User-Agent", 1175 | "value": "curl/7.51.0" 1176 | }, 1177 | ], 1178 | "cookie": [ 1179 | { 1180 | key: 'cookie', 1181 | value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.toto.idToken=${tokenData.access_token};` 1182 | } 1183 | ] 1184 | }, 1185 | "origin": { 1186 | "custom": { 1187 | "customHeaders": { 1188 | "my-origin-custom-header": [ 1189 | { 1190 | "key": "My-Origin-Custom-Header", 1191 | "value": "Test" 1192 | } 1193 | ] 1194 | }, 1195 | "domainName": "example.com", 1196 | "keepaliveTimeout": 5, 1197 | "path": "/custom_path", 1198 | "port": 443, 1199 | "protocol": "https", 1200 | "readTimeout": 5, 1201 | "sslProtocols": [ 1202 | "TLSv1", 1203 | "TLSv1.1" 1204 | ] 1205 | }, 1206 | "s3": { 1207 | "authMethod": "origin-access-identity", 1208 | "customHeaders": { 1209 | "my-origin-custom-header": [ 1210 | { 1211 | "key": "My-Origin-Custom-Header", 1212 | "value": "Test" 1213 | } 1214 | ] 1215 | }, 1216 | "domainName": "my-bucket.s3.amazonaws.com", 1217 | "path": "/s3_path", 1218 | "region": "us-east-1" 1219 | } 1220 | } 1221 | } 1222 | } 1223 | } 1224 | ] 1225 | }); 1226 | -------------------------------------------------------------------------------- /__tests__/util/cookie.test.ts: -------------------------------------------------------------------------------- 1 | import { CookieAttributes, Cookies, SAME_SITE_VALUES, getCookieDomain } from '../../src/util/cookie'; 2 | 3 | describe('parse tests', () => { 4 | test('should parse valid cookie string', () => { 5 | const cookieString = [ 6 | 'test.cookie.one=test.value.one', 7 | 'test.cookie.two=test.value.two', 8 | ].join(';'); 9 | 10 | expect(Cookies.parse(cookieString)) 11 | .toStrictEqual([ 12 | { name: 'test.cookie.one', value: 'test.value.one' }, 13 | { name: 'test.cookie.two', value: 'test.value.two' }, 14 | ]); 15 | }); 16 | 17 | test('should parse valid cookie string with URI encoded characters', () => { 18 | const cookieString = '%F0%9F%91%BB%28%29%3C%3E%40%2C%3B%3A%5C%22%2F%5B%5D%3F%3D%7B%7D%20=%20%22%2C%3B=%5C%F0%9F%91%BB'; 19 | 20 | expect(Cookies.parse(cookieString)) 21 | .toStrictEqual([ 22 | { name: '👻()<>@,;:\\"/[]?={} ', value: ' ",;=\\👻' }, 23 | ]); 24 | }); 25 | 26 | test('should try to parse cookie even with not-encoded illegal characters', () => { 27 | const cookieString = '(🤪)<>@,:\\"/[%1Y]?{}%=,\\%"; :=,\\%\\'; 28 | 29 | expect(Cookies.parse(cookieString)) 30 | .toStrictEqual([ 31 | { name: '(🤪)<>@,:\\"/[%1Y]?{}%', value: ',\\%"' }, 32 | { name: ':', value: ',\\%\\' }, 33 | ]); 34 | }); 35 | 36 | test('should skip cookies without separator', () => { 37 | const cookieString = [ 38 | '1.name=value', 39 | 'somestring', 40 | '2.name=value', 41 | ].join(';'); 42 | 43 | expect(Cookies.parse(cookieString)) 44 | .toStrictEqual([ 45 | { name: '1.name', value: 'value' }, 46 | { name: '2.name', value: 'value' }, 47 | ]); 48 | }); 49 | 50 | test('should return empty array when input parameter is null', () => { 51 | expect(Cookies.parse(null)).toStrictEqual([]); 52 | }); 53 | }); 54 | 55 | describe('serialize tests', () => { 56 | test('should correctly serialize cookie without attributes', () => { 57 | expect(Cookies.serialize('name', 'value')) 58 | .toStrictEqual('name=value'); 59 | }); 60 | 61 | test('should correctly serialize cookie with defined attributes', () => { 62 | const attributes: CookieAttributes = { 63 | domain: 'example.com', 64 | path: '/path/path', 65 | expires: new Date(0), 66 | maxAge: 1, 67 | secure: true, 68 | httpOnly: true, 69 | }; 70 | 71 | expect(Cookies.serialize('name', 'value', attributes)) 72 | .toStrictEqual('name=value; Domain=example.com; Path=/path/path; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=1; Secure; HttpOnly'); 73 | }); 74 | 75 | test('should skip undefined attributes on serialization', () => { 76 | const attributes: CookieAttributes = { 77 | domain: undefined, 78 | maxAge: 1, 79 | secure: true, 80 | httpOnly: true, 81 | }; 82 | 83 | expect(Cookies.serialize('name', 'value', attributes)) 84 | .toStrictEqual('name=value; Max-Age=1; Secure; HttpOnly'); 85 | }); 86 | 87 | test('should encode characters not compliant with RFC 6265 and correctly decode it on parse', () => { 88 | const name = '\t(%)<>@,;🤪:\\"/[]?={ключ} '; 89 | const value = ' ,<;>\t😉%=\\значение'; 90 | 91 | const serialized = Cookies.serialize(name, value); 92 | 93 | expect(serialized) 94 | .toStrictEqual('%09%28%25%29%3C%3E%40%2C%3B%F0%9F%A4%AA%3A%5C%22%2F%5B%5D%3F%3D%7B%D0%BA%D0%BB%D1%8E%D1%87%7D%20=%20%2C<%3B>%09%F0%9F%98%89%25=%5C%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5'); 95 | 96 | expect(Cookies.parse(serialized)) 97 | .toStrictEqual([{ name, value }]); 98 | }); 99 | 100 | test('should have correct SAME_SITE_VALUES', () => { 101 | expect(SAME_SITE_VALUES).toHaveLength(3); 102 | expect(SAME_SITE_VALUES).toEqual(['Strict', 'Lax', 'None']); 103 | }); 104 | }); 105 | 106 | describe('getCookieDomain', () => { 107 | it('should return cloudfront domain when disableCookieDomain is not set and cookieDomain is not set', () => { 108 | expect(getCookieDomain('example.aws.com', false)).toEqual('example.aws.com'); 109 | }); 110 | 111 | it('should return custom domain when cookieDomain is set', () => { 112 | expect(getCookieDomain('example.aws.com', false, 'aws.com')).toEqual('aws.com'); 113 | }); 114 | 115 | it('should return undefined when disableCookieDomain is set', () => { 116 | expect(getCookieDomain('example.aws.com', true)).toBeUndefined(); 117 | }); 118 | }); 119 | -------------------------------------------------------------------------------- /doc/architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/cognito-at-edge/49300c92707aab86e1e9eba60f9ae1b27da91c7c/doc/architecture.png -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | /** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */ 2 | module.exports = { 3 | preset: 'ts-jest', 4 | testEnvironment: 'node', 5 | globals: { 6 | 'ts-jest': { 7 | tsconfig: 'tsconfig.test.json', 8 | }, 9 | }, 10 | moduleNameMapper: { 11 | '^axios$': 'axios/dist/node/axios.cjs', 12 | }, 13 | }; -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cognito-at-edge", 3 | "version": "1.5.3", 4 | "repository": { 5 | "type": "git", 6 | "url": "https://github.com/awslabs/cognito-at-edge" 7 | }, 8 | "description": "Cognito authentication made easy to protect your website with CloudFront and Lambda@Edge.", 9 | "author": "AWS Builder Labs ", 10 | "license": "Apache-2.0", 11 | "main": "dist/index.js", 12 | "types": "dist/index.d.ts", 13 | "files": [ 14 | "/dist" 15 | ], 16 | "scripts": { 17 | "build": "tsc", 18 | "lint": "eslint .", 19 | "test": "jest --coverage" 20 | }, 21 | "dependencies": { 22 | "aws-jwt-verify": "^2.1.1", 23 | "axios": "^1.6.5", 24 | "pino": "^8.14.1" 25 | }, 26 | "devDependencies": { 27 | "@types/aws-lambda": "^8.10.89", 28 | "@types/jest": "^27.4.0", 29 | "@typescript-eslint/eslint-plugin": "^5.9.1", 30 | "@typescript-eslint/parser": "^5.9.1", 31 | "eslint": "^7.32.0", 32 | "jest": "^27.4.7", 33 | "ts-jest": "^27.1.2", 34 | "typescript": "^4.5.4" 35 | }, 36 | "engines": { 37 | "node": ">=10.0.0" 38 | }, 39 | "keywords": [ 40 | "aws", 41 | "cognito", 42 | "userpool", 43 | "cloudfront", 44 | "lambda", 45 | "edge", 46 | "private", 47 | "website" 48 | ] 49 | } 50 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { CognitoJwtVerifier } from 'aws-jwt-verify'; 2 | import type { CloudFrontRequest, CloudFrontRequestEvent, CloudFrontResultResponse } from 'aws-lambda'; 3 | import axios from 'axios'; 4 | import pino from 'pino'; 5 | import { parse, stringify } from 'querystring'; 6 | import { CookieAttributes, CookieSettingsOverrides, CookieType, Cookies, SAME_SITE_VALUES, SameSite, getCookieDomain } from './util/cookie'; 7 | import { CSRFTokens, NONCE_COOKIE_NAME_SUFFIX, NONCE_HMAC_COOKIE_NAME_SUFFIX, PKCE_COOKIE_NAME_SUFFIX, generateCSRFTokens, signNonce, urlSafe } from './util/csrf'; 8 | 9 | export interface AuthenticatorParams { 10 | region: string; 11 | userPoolId: string; 12 | userPoolAppId: string; 13 | userPoolAppSecret?: string; 14 | userPoolDomain: string; 15 | cookieExpirationDays?: number; 16 | disableCookieDomain?: boolean; 17 | httpOnly?: boolean; 18 | sameSite?: SameSite; 19 | logLevel?: 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'silent'; 20 | cookiePath?: string; 21 | cookieDomain?: string; 22 | cookieSettingsOverrides?: CookieSettingsOverrides; 23 | logoutConfiguration?: LogoutConfiguration; 24 | parseAuthPath?: string; 25 | csrfProtection?: { 26 | nonceSigningSecret: string; 27 | }, 28 | } 29 | 30 | interface LogoutConfiguration { 31 | logoutUri: string; 32 | logoutRedirectUri: string; 33 | } 34 | 35 | interface Tokens { 36 | accessToken?: string; 37 | idToken?: string; 38 | refreshToken?: string; 39 | } 40 | 41 | export class Authenticator { 42 | _region: string; 43 | _userPoolId: string; 44 | _userPoolAppId: string; 45 | _userPoolAppSecret: string | undefined; 46 | _userPoolDomain: string; 47 | _cookieExpirationDays: number; 48 | _disableCookieDomain: boolean; 49 | _httpOnly: boolean; 50 | _sameSite?: SameSite; 51 | _cookieBase: string; 52 | _cookiePath?: string; 53 | _cookieDomain?: string; 54 | _csrfProtection?: { 55 | nonceSigningSecret: string; 56 | }; 57 | _logoutConfiguration?: LogoutConfiguration; 58 | _parseAuthPath?: string; 59 | _cookieSettingsOverrides?: CookieSettingsOverrides; 60 | _logger; 61 | _jwtVerifier; 62 | 63 | constructor(params: AuthenticatorParams) { 64 | this._verifyParams(params); 65 | this._region = params.region; 66 | this._userPoolId = params.userPoolId; 67 | this._userPoolAppId = params.userPoolAppId; 68 | this._userPoolAppSecret = params.userPoolAppSecret; 69 | this._userPoolDomain = params.userPoolDomain; 70 | this._cookieExpirationDays = params.cookieExpirationDays || 365; 71 | this._disableCookieDomain = ('disableCookieDomain' in params && params.disableCookieDomain === true); 72 | this._cookieDomain = params.cookieDomain; 73 | this._httpOnly = ('httpOnly' in params && params.httpOnly === true); 74 | this._sameSite = params.sameSite; 75 | this._cookieBase = `CognitoIdentityServiceProvider.${params.userPoolAppId}`; 76 | this._cookiePath = params.cookiePath; 77 | this._cookieSettingsOverrides = params.cookieSettingsOverrides || {}; 78 | this._logger = pino({ 79 | level: params.logLevel || 'silent', // Default to silent 80 | base: null, //Remove pid, hostname and name logging as not usefull for Lambda 81 | }); 82 | this._jwtVerifier = CognitoJwtVerifier.create({ 83 | userPoolId: params.userPoolId, 84 | clientId: params.userPoolAppId, 85 | tokenUse: 'id', 86 | }); 87 | this._csrfProtection = params.csrfProtection; 88 | this._logoutConfiguration = params.logoutConfiguration; 89 | this._parseAuthPath = (params.parseAuthPath || '').replace(/^\//, ''); 90 | } 91 | 92 | /** 93 | * Verify that constructor parameters are corrects. 94 | * @param {object} params constructor params 95 | * @return {void} throw an exception if params are incorects. 96 | */ 97 | _verifyParams(params: AuthenticatorParams) { 98 | if (typeof params !== 'object') { 99 | throw new Error('Expected params to be an object'); 100 | } 101 | [ 'region', 'userPoolId', 'userPoolAppId', 'userPoolDomain' ].forEach(param => { 102 | if (typeof params[param as keyof AuthenticatorParams] !== 'string') { 103 | throw new Error(`Expected params.${param} to be a string`); 104 | } 105 | }); 106 | if (params.cookieExpirationDays && typeof params.cookieExpirationDays !== 'number') { 107 | throw new Error('Expected params.cookieExpirationDays to be a number'); 108 | } 109 | if ('disableCookieDomain' in params && typeof params.disableCookieDomain !== 'boolean') { 110 | throw new Error('Expected params.disableCookieDomain to be boolean'); 111 | } 112 | if ('cookieDomain' in params && typeof params.cookieDomain !== 'string') { 113 | throw new Error('Expected params.cookieDomain to be a string'); 114 | } 115 | if ('httpOnly' in params && typeof params.httpOnly !== 'boolean') { 116 | throw new Error('Expected params.httpOnly to be a boolean'); 117 | } 118 | if (params.sameSite !== undefined && !SAME_SITE_VALUES.includes(params.sameSite)) { 119 | throw new Error('Expected params.sameSite to be a Strict || Lax || None'); 120 | } 121 | if ('cookiePath' in params && typeof params.cookiePath !== 'string') { 122 | throw new Error('Expected params.cookiePath to be a string'); 123 | } 124 | if (params.logoutConfiguration && !/\/\w+/.test(params.logoutConfiguration.logoutUri)) { 125 | throw new Error('Expected params.logoutConfiguration.logoutUri to be a valid non-empty string starting with "/"'); 126 | } 127 | } 128 | 129 | /** 130 | * Exchange authorization code for tokens. 131 | * @param {String} redirectURI Redirection URI. 132 | * @param {String} code Authorization code. 133 | * @return {Promise} Authenticated user tokens. 134 | */ 135 | _fetchTokensFromCode(redirectURI: string, code: string): Promise { 136 | const authorization = this._getAuthorization(); 137 | const request = { 138 | url: `https://${this._userPoolDomain}/oauth2/token`, 139 | method: 'POST', 140 | headers: { 141 | 'Content-Type': 'application/x-www-form-urlencoded', 142 | ...(authorization && {'Authorization': `Basic ${authorization}`}), 143 | }, 144 | data: stringify({ 145 | client_id: this._userPoolAppId, 146 | code: code, 147 | grant_type: 'authorization_code', 148 | redirect_uri: redirectURI, 149 | }), 150 | } as const; 151 | this._logger.debug({ msg: 'Fetching tokens from grant code...', request, code }); 152 | return axios.request(request) 153 | .then(resp => { 154 | this._logger.debug({ msg: 'Fetched tokens', tokens: resp.data }); 155 | return { 156 | idToken: resp.data.id_token, 157 | accessToken: resp.data.access_token, 158 | refreshToken: resp.data.refresh_token, 159 | }; 160 | }) 161 | .catch(err => { 162 | this._logger.error({ msg: 'Unable to fetch tokens from grant code', request, code }); 163 | throw err; 164 | }); 165 | } 166 | 167 | /** 168 | * Fetch accessTokens from refreshToken. 169 | * @param {String} redirectURI Redirection URI. 170 | * @param {String} refreshToken Refresh token. 171 | * @return {Promise} Refreshed user tokens. 172 | */ 173 | _fetchTokensFromRefreshToken(redirectURI: string, refreshToken: string): Promise { 174 | const authorization = this._getAuthorization(); 175 | const request = { 176 | url: `https://${this._userPoolDomain}/oauth2/token`, 177 | method: 'POST', 178 | headers: { 179 | 'Content-Type': 'application/x-www-form-urlencoded', 180 | ...(authorization && {'Authorization': `Basic ${authorization}`}), 181 | }, 182 | data: stringify({ 183 | client_id: this._userPoolAppId, 184 | refresh_token: refreshToken, 185 | grant_type: 'refresh_token', 186 | redirect_uri: redirectURI, 187 | }), 188 | } as const; 189 | this._logger.debug({ msg: 'Fetching tokens from refreshToken...', request, refreshToken }); 190 | return axios.request(request) 191 | .then(resp => { 192 | this._logger.debug({ msg: 'Fetched tokens', tokens: resp.data }); 193 | return { 194 | idToken: resp.data.id_token, 195 | accessToken: resp.data.access_token, 196 | }; 197 | }) 198 | .catch(err => { 199 | this._logger.error({ msg: 'Unable to fetch tokens from refreshToken', request, refreshToken }); 200 | throw err; 201 | }); 202 | } 203 | 204 | _getAuthorization(): string | undefined { 205 | return this._userPoolAppSecret && Buffer.from(`${this._userPoolAppId}:${this._userPoolAppSecret}`).toString('base64'); 206 | } 207 | 208 | _validateCSRFCookies(request: CloudFrontRequest) { 209 | if (!this._csrfProtection) { 210 | throw new Error('_validateCSRFCookies should not be called if CSRF protection is disabled.'); 211 | } 212 | 213 | const requestParams = parse(request.querystring); 214 | const requestCookies = request.headers.cookie?.flatMap(h => Cookies.parse(h.value)) || []; 215 | this._logger.debug({ msg: 'Validating CSRF Cookies', requestCookies}); 216 | 217 | const parsedState = JSON.parse( 218 | Buffer.from(urlSafe.parse(requestParams.state as string), 'base64').toString() 219 | ); 220 | 221 | const {nonce: originalNonce, nonceHmac, pkce} = this._getCSRFTokensFromCookie(request.headers.cookie); 222 | 223 | if ( 224 | !parsedState.nonce || 225 | !originalNonce || 226 | parsedState.nonce !== originalNonce 227 | ) { 228 | if (!originalNonce) { 229 | throw new Error('Your browser didn\'t send the nonce cookie along, but it is required for security (prevent CSRF).'); 230 | } 231 | throw new Error('Nonce mismatch. This can happen if you start multiple authentication attempts in parallel (e.g. in separate tabs)'); 232 | } 233 | if (!pkce) { 234 | throw new Error('Your browser didn\'t send the pkce cookie along, but it is required for security (prevent CSRF).'); 235 | } 236 | 237 | const calculatedHmac = signNonce(parsedState.nonce, this._csrfProtection.nonceSigningSecret); 238 | 239 | if (calculatedHmac !== nonceHmac) { 240 | throw new Error(`Nonce signature mismatch! Expected ${calculatedHmac} but got ${nonceHmac}`); 241 | } 242 | } 243 | 244 | _getOverridenCookieAttributes(cookieAttributes: CookieAttributes = {}, cookieType: CookieType): CookieAttributes { 245 | const res = {...cookieAttributes}; 246 | 247 | const overrides = this._cookieSettingsOverrides?.[cookieType]; 248 | if (overrides) { 249 | if (overrides.httpOnly !== undefined) { 250 | res.httpOnly = overrides.httpOnly; 251 | } 252 | if (overrides.sameSite !== undefined) { 253 | res.sameSite = overrides.sameSite; 254 | } 255 | if (overrides.path !== undefined) { 256 | res.path = overrides.path; 257 | } 258 | if (overrides.expirationDays !== undefined) { 259 | res.expires = new Date(Date.now() + overrides.expirationDays * 864e+5); 260 | } 261 | } 262 | this._logger.debug({ 263 | msg: 'Cookie settings overriden', 264 | cookieAttributes, 265 | cookieType, 266 | cookieSettingsOverrides: this._cookieSettingsOverrides, 267 | }); 268 | return res; 269 | } 270 | 271 | /** 272 | * Create a Lambda@Edge redirection response to set the tokens on the user's browser cookies. 273 | * @param {Object} tokens Cognito User Pool tokens. 274 | * @param {String} domain Website domain. 275 | * @param {String} location Path to redirection. 276 | * @return Lambda@Edge response. 277 | */ 278 | async _getRedirectResponse(tokens: Tokens, domain: string, location: string): Promise { 279 | const decoded = await this._jwtVerifier.verify(tokens.idToken as string); 280 | const username = decoded['cognito:username'] as string; 281 | const usernameBase = `${this._cookieBase}.${username}`; 282 | const cookieDomain = getCookieDomain(domain, this._disableCookieDomain, this._cookieDomain); 283 | const cookieAttributes: CookieAttributes = { 284 | domain: cookieDomain, 285 | expires: new Date(Date.now() + this._cookieExpirationDays * 864e+5), 286 | secure: true, 287 | httpOnly: this._httpOnly, 288 | sameSite: this._sameSite, 289 | path: this._cookiePath, 290 | }; 291 | const cookies = [ 292 | Cookies.serialize(`${usernameBase}.accessToken`, tokens.accessToken as string, this._getOverridenCookieAttributes(cookieAttributes, 'accessToken')), 293 | Cookies.serialize(`${usernameBase}.idToken`, tokens.idToken as string, this._getOverridenCookieAttributes(cookieAttributes, 'idToken')), 294 | ...(tokens.refreshToken ? [Cookies.serialize(`${usernameBase}.refreshToken`, tokens.refreshToken, this._getOverridenCookieAttributes(cookieAttributes, 'refreshToken'))] : []), 295 | Cookies.serialize(`${usernameBase}.tokenScopesString`, 'phone email profile openid aws.cognito.signin.user.admin', cookieAttributes), 296 | Cookies.serialize(`${this._cookieBase}.LastAuthUser`, username, cookieAttributes), 297 | ]; 298 | 299 | // Clear CSRF Token Cookies 300 | if (this._csrfProtection) { 301 | // Domain attribute is always not set here as CSRF cookies are used 302 | // exclusively by the CF distribution 303 | const csrfCookieAttributes = {...cookieAttributes, domain: undefined, expires: new Date()}; 304 | cookies.push( 305 | Cookies.serialize(`${this._cookieBase}.${PKCE_COOKIE_NAME_SUFFIX}`, '', csrfCookieAttributes), 306 | Cookies.serialize(`${this._cookieBase}.${NONCE_COOKIE_NAME_SUFFIX}`, '', csrfCookieAttributes), 307 | Cookies.serialize(`${this._cookieBase}.${NONCE_HMAC_COOKIE_NAME_SUFFIX}`, '', csrfCookieAttributes), 308 | ); 309 | } 310 | 311 | const response: CloudFrontResultResponse = { 312 | status: '302' , 313 | headers: { 314 | 'location': [{ 315 | key: 'Location', 316 | value: location, 317 | }], 318 | 'cache-control': [{ 319 | key: 'Cache-Control', 320 | value: 'no-cache, no-store, max-age=0, must-revalidate', 321 | }], 322 | 'pragma': [{ 323 | key: 'Pragma', 324 | value: 'no-cache', 325 | }], 326 | 'set-cookie': cookies.map(c => ({ key: 'Set-Cookie', value: c })), 327 | }, 328 | }; 329 | 330 | this._logger.debug({ msg: 'Generated set-cookie response', response }); 331 | 332 | return response; 333 | } 334 | 335 | /** 336 | * Extract value of the authentication token from the request cookies. 337 | * @param {Array} cookieHeaders 'Cookie' request headers. 338 | * @return {Tokens} Extracted id token or access token. Null if not found. 339 | */ 340 | _getTokensFromCookie(cookieHeaders: Array<{ key?: string | undefined, value: string }> | undefined): Tokens { 341 | if (!cookieHeaders) { 342 | this._logger.debug("Cookies weren't present in the request"); 343 | throw new Error("Cookies weren't present in the request"); 344 | } 345 | 346 | this._logger.debug({ msg: 'Extracting authentication token from request cookie', cookieHeaders }); 347 | 348 | const cookies = cookieHeaders.flatMap(h => Cookies.parse(h.value)); 349 | 350 | const tokenCookieNamePrefix = `${this._cookieBase}.`; 351 | const idTokenCookieNamePostfix = '.idToken'; 352 | const refreshTokenCookieNamePostfix = '.refreshToken'; 353 | 354 | const tokens: Tokens = {}; 355 | for (const {name, value} of cookies){ 356 | if (name.startsWith(tokenCookieNamePrefix) && name.endsWith(idTokenCookieNamePostfix)) { 357 | tokens.idToken = value; 358 | } 359 | if (name.startsWith(tokenCookieNamePrefix) && name.endsWith(refreshTokenCookieNamePostfix)) { 360 | tokens.refreshToken = value; 361 | } 362 | } 363 | 364 | if (!tokens.idToken && !tokens.refreshToken) { 365 | this._logger.debug('Neither idToken, nor refreshToken was present in request cookies'); 366 | throw new Error('Neither idToken, nor refreshToken was present in request cookies'); 367 | } 368 | 369 | this._logger.debug({ msg: 'Found tokens in cookie', tokens }); 370 | return tokens; 371 | } 372 | 373 | /** 374 | * Extract values of the CSRF tokens from the request cookies. 375 | * @param {Array} cookieHeaders 'Cookie' request headers. 376 | * @return {CSRFTokens} Extracted CSRF Tokens from cookie. 377 | */ 378 | _getCSRFTokensFromCookie(cookieHeaders: Array<{ key?: string | undefined, value: string }> | undefined): CSRFTokens { 379 | if (!cookieHeaders) { 380 | this._logger.debug("Cookies weren't present in the request"); 381 | throw new Error("Cookies weren't present in the request"); 382 | } 383 | 384 | this._logger.debug({ msg: 'Extracting CSRF tokens from request cookie', cookieHeaders }); 385 | 386 | const cookies = cookieHeaders.flatMap(h => Cookies.parse(h.value)); 387 | const csrfTokens: CSRFTokens = cookies.reduce((tokens, {name, value}) => { 388 | if (name.startsWith(this._cookieBase)) { 389 | [ 390 | NONCE_COOKIE_NAME_SUFFIX, 391 | NONCE_HMAC_COOKIE_NAME_SUFFIX, 392 | PKCE_COOKIE_NAME_SUFFIX, 393 | ].forEach(key => { 394 | if (name.endsWith(`.${key}`)) { 395 | tokens[key] = value; 396 | } 397 | }); 398 | } 399 | return tokens; 400 | }, {} as CSRFTokens); 401 | 402 | this._logger.debug({ msg: 'Found CSRF tokens in cookie', csrfTokens }); 403 | return csrfTokens; 404 | } 405 | 406 | /** 407 | * Extracts the redirect uri from the state param. When CSRF protection is 408 | * enabled, redirect uri is encoded inside state along with other data. So, it 409 | * needs to be base64 decoded. When CSRF is not enabled, state can be used 410 | * directly. 411 | * @param {string} state 412 | * @returns {string} 413 | */ 414 | _getRedirectUriFromState(state: string): string { 415 | if (this._csrfProtection) { 416 | const parsedState = JSON.parse( 417 | Buffer.from(urlSafe.parse(state), 'base64').toString() 418 | ); 419 | this._logger.debug({ msg: 'Parsed state param to extract redirect uri', parsedState }); 420 | return parsedState.redirect_uri; 421 | } 422 | return state; 423 | } 424 | 425 | async _revokeTokens(tokens: Tokens) { 426 | const authorization = this._getAuthorization(); 427 | const revokeRequest = { 428 | url: `https://${this._userPoolDomain}/oauth2/revoke`, 429 | method: 'POST', 430 | headers: { 431 | 'Content-Type': 'application/x-www-form-urlencoded', 432 | ...(authorization && {'Authorization': `Basic ${authorization}`}), 433 | }, 434 | data: stringify({ 435 | client_id: this._userPoolAppId, 436 | token: tokens.refreshToken, 437 | }), 438 | } as const; 439 | this._logger.debug({ msg: 'Revoking refreshToken...', request: revokeRequest, refreshToken: tokens.refreshToken }); 440 | return axios.request(revokeRequest) 441 | .then(() => { 442 | this._logger.debug({ msg: 'Revoked refreshToken', refreshToken: tokens.refreshToken }); 443 | }) 444 | .catch(err => { 445 | this._logger.error({ msg: 'Unable to revoke refreshToken', request: revokeRequest, err: JSON.stringify(err) }); 446 | throw err; 447 | }); 448 | } 449 | 450 | async _clearCookies(event: CloudFrontRequestEvent, tokens: Tokens = {}): Promise { 451 | this._logger.info({ msg: 'Clearing cookies...', event, tokens }); 452 | const { request } = event.Records[0].cf; 453 | const cfDomain = request.headers.host[0].value; 454 | const requestParams = parse(request.querystring); 455 | const redirectURI = this._logoutConfiguration?.logoutRedirectUri || 456 | requestParams.redirect_uri as string || 457 | `https://${cfDomain}`; 458 | 459 | const cookieDomain = getCookieDomain(cfDomain, this._disableCookieDomain, this._cookieDomain); 460 | const cookieAttributes: CookieAttributes = { 461 | domain: cookieDomain, 462 | expires: new Date(), 463 | secure: true, 464 | httpOnly: this._httpOnly, 465 | sameSite: this._sameSite, 466 | path: this._cookiePath, 467 | }; 468 | 469 | let responseCookies: string[] = []; 470 | try { 471 | const decoded = await this._jwtVerifier.verify(tokens.idToken as string); 472 | const username = decoded['cognito:username'] as string; 473 | this._logger.info({ msg: 'Token verified. Clearing cookies...', idToken: tokens.idToken, username }); 474 | 475 | const usernameBase = `${this._cookieBase}.${username}`; 476 | responseCookies = [ 477 | Cookies.serialize(`${usernameBase}.accessToken`, '', cookieAttributes), 478 | Cookies.serialize(`${usernameBase}.idToken`, '', cookieAttributes), 479 | ...(tokens.refreshToken ? [Cookies.serialize(`${usernameBase}.refreshToken`, '', cookieAttributes)] : []), 480 | Cookies.serialize(`${usernameBase}.tokenScopesString`, '', cookieAttributes), 481 | Cookies.serialize(`${this._cookieBase}.LastAuthUser`, '', cookieAttributes), 482 | ]; 483 | } catch (err) { 484 | this._logger.info({ 485 | msg: 'Unable to verify token. Inferring data from request cookies and clearing them...', 486 | idToken: tokens.idToken, 487 | }); 488 | const requestCookies = request.headers.cookie?.flatMap(h => Cookies.parse(h.value)) || []; 489 | for (const { name } of requestCookies) { 490 | if (name.startsWith(this._cookieBase)) { 491 | responseCookies.push( 492 | Cookies.serialize(name, '', cookieAttributes), 493 | ); 494 | } 495 | } 496 | } 497 | 498 | const response: CloudFrontResultResponse = { 499 | status: '302' , 500 | headers: { 501 | 'location': [{ 502 | key: 'Location', 503 | value: redirectURI, 504 | }], 505 | 'cache-control': [{ 506 | key: 'Cache-Control', 507 | value: 'no-cache, no-store, max-age=0, must-revalidate', 508 | }], 509 | 'pragma': [{ 510 | key: 'Pragma', 511 | value: 'no-cache', 512 | }], 513 | 'set-cookie': responseCookies.map(c => ({ key: 'Set-Cookie', value: c })), 514 | }, 515 | }; 516 | 517 | this._logger.debug({ msg: 'Generated set-cookie response', response }); 518 | 519 | return response; 520 | } 521 | 522 | /** 523 | * Get redirect to cognito userpool response 524 | * @param {CloudFrontRequest} request The original request 525 | * @param {string} redirectURI Redirection URI. 526 | * @return {CloudFrontResultResponse} Redirect response. 527 | */ 528 | _getRedirectToCognitoUserPoolResponse(request: CloudFrontRequest, redirectURI: string): CloudFrontResultResponse { 529 | let redirectPath = request.uri; 530 | if (request.querystring && request.querystring !== '') { 531 | redirectPath += encodeURIComponent('?' + request.querystring); 532 | } 533 | 534 | let csrfTokens: CSRFTokens = {}; 535 | let state: string | undefined = redirectPath; 536 | if (this._csrfProtection) { 537 | csrfTokens = generateCSRFTokens(redirectURI, this._csrfProtection.nonceSigningSecret); 538 | state = csrfTokens.state; 539 | } 540 | 541 | const userPoolUrl = `https://${this._userPoolDomain}/authorize?redirect_uri=${redirectURI}&response_type=code&client_id=${this._userPoolAppId}&state=${state}`; 542 | 543 | this._logger.debug(`Redirecting user to Cognito User Pool URL ${userPoolUrl}`); 544 | 545 | let cookies: string[] | undefined; 546 | if (this._csrfProtection) { 547 | const cookieAttributes: CookieAttributes = { 548 | expires: new Date(Date.now() + 10 * 60 * 1000), 549 | secure: true, 550 | httpOnly: this._httpOnly, 551 | sameSite: this._sameSite, 552 | path: this._cookiePath, 553 | }; 554 | cookies = [ 555 | Cookies.serialize(`${this._cookieBase}.${PKCE_COOKIE_NAME_SUFFIX}`, csrfTokens.pkce || '', cookieAttributes), 556 | Cookies.serialize(`${this._cookieBase}.${NONCE_COOKIE_NAME_SUFFIX}`, csrfTokens.nonce || '', cookieAttributes), 557 | Cookies.serialize(`${this._cookieBase}.${NONCE_HMAC_COOKIE_NAME_SUFFIX}`, csrfTokens.nonceHmac || '', cookieAttributes), 558 | ]; 559 | } 560 | 561 | const response: CloudFrontResultResponse = { 562 | status: '302', 563 | headers: { 564 | 'location': [{ 565 | key: 'Location', 566 | value: userPoolUrl, 567 | }], 568 | 'cache-control': [{ 569 | key: 'Cache-Control', 570 | value: 'no-cache, no-store, max-age=0, must-revalidate', 571 | }], 572 | 'pragma': [{ 573 | key: 'Pragma', 574 | value: 'no-cache', 575 | }], 576 | ...(cookies 577 | ? { 'set-cookie': cookies && cookies.map(c => ({ key: 'Set-Cookie', value: c })) } 578 | : {}), 579 | }, 580 | }; 581 | 582 | return response; 583 | } 584 | 585 | /** 586 | * Handle Lambda@Edge event: 587 | * * if authentication cookie is present and valid: forward the request 588 | * * if authentication cookie is invalid, but refresh token is present: set cookies with refreshed tokens 589 | * * if ?code= is present: set cookies with new tokens 590 | * * else redirect to the Cognito UserPool to authenticate the user 591 | * @param {Object} event Lambda@Edge event. 592 | * @return {Promise} CloudFront response. 593 | */ 594 | async handle(event: CloudFrontRequestEvent): Promise { 595 | this._logger.debug({ msg: 'Handling Lambda@Edge event', event }); 596 | 597 | const { request } = event.Records[0].cf; 598 | const cfDomain = request.headers.host[0].value; 599 | const redirectURI = this._parseAuthPath ? `https://${cfDomain}/${this._parseAuthPath}` : `https://${cfDomain}`; 600 | 601 | try { 602 | const tokens = this._getTokensFromCookie(request.headers.cookie); 603 | if (this._logoutConfiguration && request.uri.startsWith(this._logoutConfiguration.logoutUri)) { 604 | this._logger.info({ msg: 'Revoking tokens', tokens }); 605 | await this._revokeTokens(tokens); 606 | 607 | this._logger.info({ msg: 'Revoked tokens. Clearing cookies', tokens }); 608 | return this._clearCookies(event, tokens); 609 | } 610 | try { 611 | this._logger.debug({ msg: 'Verifying token...', tokens }); 612 | const user = await this._jwtVerifier.verify(tokens.idToken as string); 613 | this._logger.info({ msg: 'Forwarding request', path: request.uri, user }); 614 | return request; 615 | } catch (err) { 616 | this._logger.info({ msg: 'Token verification failed', tokens, refreshToken: tokens.refreshToken }); 617 | if (tokens.refreshToken) { 618 | this._logger.debug({ msg: 'Verifying idToken failed, verifying refresh token instead...', tokens, err }); 619 | return await this._fetchTokensFromRefreshToken(redirectURI, tokens.refreshToken) 620 | .then(tokens => this._getRedirectResponse(tokens, cfDomain, request.uri)); 621 | } else { 622 | throw err; 623 | } 624 | } 625 | } catch (err) { 626 | if (this._logoutConfiguration && request.uri.startsWith(this._logoutConfiguration.logoutUri)) { 627 | this._logger.info({ msg: 'Clearing cookies', path: cfDomain }); 628 | return this._clearCookies(event); 629 | } 630 | this._logger.debug("User isn't authenticated: %s", err); 631 | 632 | const requestParams = parse(request.querystring); 633 | if (requestParams.code) { 634 | return this._fetchTokensFromCode(redirectURI, requestParams.code as string) 635 | .then(tokens => this._getRedirectResponse(tokens, cfDomain, this._getRedirectUriFromState(requestParams.state as string))); 636 | } else { 637 | return this._getRedirectToCognitoUserPoolResponse(request, redirectURI); 638 | } 639 | } 640 | } 641 | 642 | /** 643 | * 644 | * 1. If the token cookies are present in the request, send users to the redirect_uri 645 | * 2. If cookies are not present, initiate the authentication flow 646 | * 647 | * @param event Event that triggers this Lambda function 648 | * @returns Lambda response 649 | */ 650 | async handleSignIn(event: CloudFrontRequestEvent): Promise { 651 | this._logger.debug({ msg: 'Handling Lambda@Edge event', event }); 652 | 653 | const { request } = event.Records[0].cf; 654 | const requestParams = parse(request.querystring); 655 | const cfDomain = request.headers.host[0].value; 656 | const redirectURI = requestParams.redirect_uri as string || `https://${cfDomain}`; 657 | 658 | try { 659 | const tokens = this._getTokensFromCookie(request.headers.cookie); 660 | 661 | this._logger.debug({ msg: 'Verifying token...', tokens }); 662 | const user = await this._jwtVerifier.verify(tokens.idToken as string); 663 | 664 | this._logger.info({ msg: 'Redirecting user to', path: redirectURI, user }); 665 | return { 666 | status: '302', 667 | headers: { 668 | 'location': [{ 669 | key: 'Location', 670 | value: redirectURI, 671 | }], 672 | }, 673 | }; 674 | } catch (err) { 675 | this._logger.debug("User isn't authenticated: %s", err); 676 | return this._getRedirectToCognitoUserPoolResponse( 677 | request, this._parseAuthPath ? `https://${cfDomain}/${this._parseAuthPath}` : redirectURI, 678 | ); 679 | } 680 | } 681 | 682 | /** 683 | * 684 | * Handler that performs OAuth token exchange -- exchanges the authorization 685 | * code obtained from the query parameter from server for tokens -- and sets 686 | * tokens as cookies. This is done after performing CSRF checks, by verifying 687 | * that the information encoded in the state query parameter is related to the 688 | * one stored in the cookies. 689 | * 690 | * @param event Event that triggers this Lambda function 691 | * @returns Lambda response 692 | */ 693 | async handleParseAuth(event: CloudFrontRequestEvent): Promise { 694 | this._logger.debug({ msg: 'Handling Lambda@Edge event', event }); 695 | 696 | const { request } = event.Records[0].cf; 697 | const cfDomain = request.headers.host[0].value; 698 | const requestParams = parse(request.querystring); 699 | 700 | try { 701 | if (!this._parseAuthPath) { 702 | throw new Error('parseAuthPath is not set'); 703 | } 704 | const redirectURI = `https://${cfDomain}/${this._parseAuthPath}`; 705 | if (requestParams.code) { 706 | if (this._csrfProtection) { 707 | this._validateCSRFCookies(request); 708 | } 709 | const tokens = await this._fetchTokensFromCode(redirectURI, requestParams.code as string); 710 | const location = this._getRedirectUriFromState(requestParams.state as string); 711 | 712 | return this._getRedirectResponse(tokens, cfDomain, location); 713 | } else { 714 | this._logger.debug({msg: 'Code param not found', requestParams}); 715 | throw new Error('OAuth code parameter not found'); 716 | } 717 | } catch (err) { 718 | this._logger.debug({msg: 'Unable to exchange code for tokens', err}); 719 | return { 720 | status: '400', 721 | body: `${err}`, 722 | }; 723 | } 724 | } 725 | 726 | /** 727 | * 728 | * Uses the refreshToken present in the cookies to get a new set of tokens 729 | * from the authorization server. After fetching the tokens, they are sent 730 | * back to the client as cookies. 731 | * 732 | * @param event Event that triggers this Lambda function 733 | * @returns Lambda response 734 | */ 735 | async handleRefreshToken(event: CloudFrontRequestEvent): Promise { 736 | this._logger.debug({ msg: 'Handling Lambda@Edge event', event }); 737 | 738 | const { request } = event.Records[0].cf; 739 | const cfDomain = request.headers.host[0].value; 740 | const requestParams = parse(request.querystring); 741 | const redirectURI = requestParams.redirect_uri as string || `https://${cfDomain}`; 742 | 743 | try { 744 | let tokens = this._getTokensFromCookie(request.headers.cookie); 745 | 746 | this._logger.debug({ msg: 'Verifying token...', tokens }); 747 | const user = await this._jwtVerifier.verify(tokens.idToken as string); 748 | 749 | this._logger.debug({ msg: 'Refreshing tokens...', tokens, user }); 750 | tokens = await this._fetchTokensFromRefreshToken(redirectURI, tokens.refreshToken as string); 751 | 752 | this._logger.debug({ msg: 'Refreshed tokens...', tokens, user }); 753 | return this._getRedirectResponse(tokens, cfDomain, redirectURI); 754 | } catch (err) { 755 | this._logger.debug("User isn't authenticated: %s", err); 756 | return this._getRedirectToCognitoUserPoolResponse( 757 | request, this._parseAuthPath ? `https://${cfDomain}/${this._parseAuthPath}` : redirectURI, 758 | ); 759 | } 760 | } 761 | 762 | /** 763 | * 764 | * Revokes the refreshToken (which also invalidates the accessToken obtained 765 | * using that refreshToken) and clears the cookies. Even if the revoke 766 | * operation fails, clear cookies based on the cookie names present in the 767 | * request headers. 768 | * 769 | * @param event Event that triggers this Lambda function 770 | * @returns Lambda response 771 | */ 772 | async handleSignOut(event: CloudFrontRequestEvent): Promise { 773 | this._logger.debug({ msg: 'Handling Lambda@Edge event', event }); 774 | 775 | const { request } = event.Records[0].cf; 776 | const requestParams = parse(request.querystring); 777 | const cfDomain = request.headers.host[0].value; 778 | const redirectURI = requestParams.redirect_uri as string || `https://${cfDomain}`; 779 | 780 | try { 781 | const tokens = this._getTokensFromCookie(request.headers.cookie); 782 | 783 | this._logger.info({ msg: 'Revoking tokens', tokens }); 784 | await this._revokeTokens(tokens); 785 | 786 | this._logger.info({ msg: 'Revoked tokens. Clearing cookies...', tokens }); 787 | return this._clearCookies(event, tokens); 788 | } catch (err) { 789 | this._logger.info({ msg: 'Unable to revoke tokens. Clearing cookies...', path: redirectURI }); 790 | return this._clearCookies(event); 791 | } 792 | } 793 | } 794 | 795 | -------------------------------------------------------------------------------- /src/util/cookie.ts: -------------------------------------------------------------------------------- 1 | 2 | export interface Cookie { 3 | name: string; 4 | value: string; 5 | } 6 | 7 | export type SameSite = 'Strict' | 'Lax' | 'None'; 8 | export const SAME_SITE_VALUES: SameSite[] = ['Strict', 'Lax', 'None']; 9 | 10 | /** 11 | * Cookie attributes to be used inside 'Set-Cookie' header 12 | */ 13 | export interface CookieAttributes { 14 | /** 15 | * The Domain attribute specifies those hosts to which the cookie will be sent. 16 | * Refer to {@link https://www.rfc-editor.org/rfc/rfc6265#section-4.1.2.3 RFC 6265 section 4.1.2.3.} for more details. 17 | */ 18 | domain?: string; 19 | 20 | /** 21 | * The Expires attribute indicates the maximum lifetime of the cookie, represented as the date and time at which 22 | * the cookie expires. 23 | * Refer to {@link https://www.rfc-editor.org/rfc/rfc6265#section-4.1.2.1 RFC 6265 section 4.1.2.1.} for more details. 24 | */ 25 | expires?: Date; 26 | 27 | /** 28 | * The HttpOnly attribute limits the scope of the cookie to HTTP requests. 29 | * Refer to {@link https://www.rfc-editor.org/rfc/rfc6265#section-4.1.2.6 RFC 6265 section 4.1.2.6.} for more details. 30 | */ 31 | httpOnly?: boolean; 32 | 33 | /** 34 | * The SameSite attribute allows you to declare if your cookie should be restricted to a first-party or same-site context. 35 | * Refer to {@link https://httpwg.org/http-extensions/draft-ietf-httpbis-rfc6265bis.html#name-samesite-cookies RFC 6265 section 8.8.} for more details. 36 | */ 37 | sameSite?: SameSite; 38 | 39 | /** 40 | * The Max-Age attribute indicates the maximum lifetime of the cookie, represented as the number of seconds until 41 | * the cookie expires. 42 | * Refer to {@link https://www.rfc-editor.org/rfc/rfc6265#section-4.1.2.2 RFC 6265 section 4.1.2.2.} for more details. 43 | */ 44 | maxAge?: number; 45 | 46 | /** 47 | * The scope of each cookie is limited to a set of paths, controlled by the Path attribute. 48 | * Refer to {@link https://www.rfc-editor.org/rfc/rfc6265#section-4.1.2.4 RFC 6265 section 4.1.2.4.} for more details. 49 | */ 50 | path?: string; 51 | 52 | /** 53 | * The Secure attribute limits the scope of the cookie to "secure" channels (where "secure" is defined by the user agent). 54 | * Refer to {@link https://www.rfc-editor.org/rfc/rfc6265#section-4.1.2.5 RFC 6265 section 4.1.2.5.} for more details. 55 | */ 56 | secure?: boolean; 57 | } 58 | 59 | export type CookieType = 'idToken' | 'accessToken' | 'refreshToken'; 60 | 61 | export interface CookieSettings { 62 | /** 63 | * Indicates the maximum lifetime of the cookie. 64 | */ 65 | expirationDays?: number; 66 | 67 | /** 68 | * Indicates the path that must exist in the requested URL for the browser to 69 | * send the Cookie header. 70 | */ 71 | path?: string; 72 | 73 | /** 74 | * Controls whether the cookie can be accessed by JavaScript. 75 | */ 76 | httpOnly?: boolean; 77 | 78 | /** 79 | * Controls whether or not a cookie is sent with cross-site requests 80 | */ 81 | sameSite?: SameSite; 82 | } 83 | 84 | export interface CookieSettingsOverrides { 85 | idToken?: CookieSettings; 86 | accessToken?: CookieSettings; 87 | refreshToken?: CookieSettings; 88 | } 89 | 90 | export class Cookies { 91 | 92 | /** 93 | * Parse `Cookie` header string compliant with RFC 6265 and decode URI encoded characters. 94 | * 95 | * @param cookiesString 'Cookie' header value 96 | * @returns array of {@type Cookie} objects 97 | */ 98 | static parse(cookiesString: string): Cookie[] { 99 | const cookieStrArray = cookiesString ? cookiesString.split(';') : []; 100 | 101 | const cookies: Cookie[] = []; 102 | 103 | for (const cookieStr of cookieStrArray) { 104 | const separatorIndex = cookieStr.indexOf('='); 105 | 106 | if (separatorIndex < 0) { 107 | continue; 108 | } 109 | 110 | const name = this.decodeName(cookieStr.substring(0, separatorIndex).trim()); 111 | const value = this.decodeValue(cookieStr.substring(separatorIndex + 1).trim()); 112 | 113 | cookies.push({ name, value }); 114 | } 115 | 116 | return cookies; 117 | } 118 | 119 | /** 120 | * Serialize a cookie name-value pair into a `Set-Cookie` header string and URI encode characters that doesn't comply 121 | * with RFC 6265 122 | * 123 | * @param name cookie name 124 | * @param value cookie value 125 | * @param attributes cookie attributes 126 | * @returns string to be used as `Set-Cookie` header 127 | */ 128 | static serialize(name: string, value: string, attributes: CookieAttributes = {}): string { 129 | return [ 130 | `${this.encodeName(name)}=${this.encodeValue(value)}`, 131 | ...(attributes.domain ? [`Domain=${attributes.domain}`] : []), 132 | ...(attributes.path ? [`Path=${attributes.path}`] : []), 133 | ...(attributes.expires ? [`Expires=${attributes.expires.toUTCString()}`] : []), 134 | ...(attributes.maxAge ? [`Max-Age=${attributes.maxAge}`] : []), 135 | ...(attributes.secure ? ['Secure'] : []), 136 | ...(attributes.httpOnly ? ['HttpOnly'] : []), 137 | ...(attributes.sameSite ? [`SameSite=${attributes.sameSite}`] : []), 138 | ].join('; '); 139 | } 140 | 141 | /** 142 | * URI encodes all characters not compliant with RFC 6265 cookie-name syntax (namely, non-US-ASCII, 143 | * control characters and `()<>@,;:\"/[]?={} `) as well as `%` character to enable URI encoding support. 144 | * Refer to {@link https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1 RFC 6265 section 4.1.1.} for more details. 145 | */ 146 | private static encodeName = (str: string) => 147 | str.replace(/[^\x21\x23\x24\x26\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E-\x7A\x7C\x7E]+/g, encodeURIComponent) 148 | .replace(/[()]/g, (s) => `%${s.charCodeAt(0).toString(16).toUpperCase()}`); 149 | 150 | /** 151 | * Safely URI decodes cookie name. 152 | */ 153 | private static decodeName = (str: string) => 154 | str.replace(/(%[\dA-Fa-f]{2})+/g, decodeURIComponent); 155 | 156 | /** 157 | * URI encodes all characters not compliant with RFC 6265 cookie-octet syntax (namely, non-US-ASCII, 158 | * control characters, whitespace, double quote, comma, semicolon and backslash) as well as `%` character 159 | * to enable URI encoding support. 160 | * Refer to {@link https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1 RFC 6265 section 4.1.1.} for more details. 161 | */ 162 | private static encodeValue = (str: string) => 163 | str.replace(/[^\x21\x23\x24\x26-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+/g, encodeURIComponent); 164 | 165 | /** 166 | * Safely URI decodes cookie value. 167 | */ 168 | private static decodeValue = (str: string) => 169 | str.replace(/(%[\dA-Fa-f]{2})+/g, decodeURIComponent); 170 | 171 | } 172 | 173 | export function getCookieDomain(cfDomain: string, disableCookieDomain: boolean, customCookieDomain: string | undefined = undefined): string | undefined { 174 | if (disableCookieDomain) { 175 | return undefined; 176 | } 177 | if (customCookieDomain) { 178 | return customCookieDomain; 179 | } 180 | return cfDomain; 181 | } -------------------------------------------------------------------------------- /src/util/csrf.ts: -------------------------------------------------------------------------------- 1 | import { createHash, createHmac, randomInt } from 'crypto'; 2 | 3 | export interface CSRFTokens { 4 | nonce?: string; 5 | nonceHmac?: string; 6 | pkce?: string; 7 | pkceHash?: string; 8 | state?: string; 9 | } 10 | 11 | export const NONCE_COOKIE_NAME_SUFFIX: keyof CSRFTokens = 'nonce'; 12 | export const NONCE_HMAC_COOKIE_NAME_SUFFIX: keyof CSRFTokens = 'nonceHmac'; 13 | export const PKCE_COOKIE_NAME_SUFFIX: keyof CSRFTokens = 'pkce'; 14 | 15 | export const CSRF_CONFIG = { 16 | secretAllowedCharacters: 17 | 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~', 18 | pkceLength: 43, // Should be between 43 and 128 - per spec 19 | nonceLength: 16, 20 | nonceMaxAge: 60 * 60 * 24, 21 | }; 22 | 23 | export function generateNonce() { 24 | const randomString = generateSecret( 25 | CSRF_CONFIG.secretAllowedCharacters, 26 | CSRF_CONFIG.nonceLength 27 | ); 28 | return `${getCurrentTimestampInSeconds()}T${randomString}`; 29 | } 30 | 31 | export function generateCSRFTokens(redirectURI: string, signingSecret: string) { 32 | const nonce = generateNonce(); 33 | const nonceHmac = signNonce(nonce, signingSecret); 34 | 35 | const state = urlSafe.stringify( 36 | Buffer.from( 37 | JSON.stringify({ 38 | nonce, 39 | redirect_uri: redirectURI, 40 | }) 41 | ).toString('base64') 42 | ); 43 | 44 | return { 45 | nonce, 46 | nonceHmac, 47 | state, 48 | ...generatePkceVerifier(), 49 | }; 50 | } 51 | 52 | export function getCurrentTimestampInSeconds(): number { 53 | return (Date.now() / 1000) || 0; 54 | } 55 | 56 | export function generateSecret(allowedCharacters: string, secretLength: number) { 57 | return [...new Array(secretLength)] 58 | .map(() => allowedCharacters[randomInt(0, allowedCharacters.length)]) 59 | .join(''); 60 | } 61 | 62 | export function sign(stringToSign: string, secret: string, signatureLength: number): string { 63 | const digest = createHmac('sha256', secret) 64 | .update(stringToSign) 65 | .digest('base64') 66 | .slice(0, signatureLength); 67 | const signature = urlSafe.stringify(digest); 68 | return signature; 69 | } 70 | 71 | export function signNonce(nonce: string, signingSecret: string): string { 72 | return sign(nonce, signingSecret, CSRF_CONFIG.nonceLength); 73 | } 74 | 75 | export const urlSafe = { 76 | /* 77 | Functions to translate base64-encoded strings, so they can be used: 78 | - in URL's without needing additional encoding 79 | - in OAuth2 PKCE verifier 80 | - in cookies (to be on the safe side, as = + / are in fact valid characters in cookies) 81 | 82 | stringify: 83 | use this on a base64-encoded string to translate = + / into replacement characters 84 | 85 | parse: 86 | use this on a string that was previously urlSafe.stringify'ed to return it to 87 | its prior pure-base64 form. Note that trailing = are not added, but NodeJS does not care 88 | */ 89 | stringify: (b64encodedString: string) => 90 | b64encodedString.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'), 91 | parse: (b64encodedString: string) => 92 | b64encodedString.replace(/-/g, '+').replace(/_/g, '/'), 93 | }; 94 | 95 | export function generatePkceVerifier() { 96 | const pkce = generateSecret( 97 | CSRF_CONFIG.secretAllowedCharacters, 98 | CSRF_CONFIG.pkceLength 99 | ); 100 | const verifier = { 101 | pkce, 102 | pkceHash: urlSafe.stringify( 103 | createHash('sha256').update(pkce, 'utf8').digest('base64') 104 | ), 105 | }; 106 | return verifier; 107 | } -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "esnext", 5 | "declaration": true, 6 | "outDir": "./dist", 7 | "strict": true 8 | }, 9 | "include": [ 10 | "src/**/*" 11 | ], 12 | "exclude": [ 13 | "node_modules", 14 | ] 15 | } -------------------------------------------------------------------------------- /tsconfig.test.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "strict": false 5 | }, 6 | } --------------------------------------------------------------------------------