├── .cargo-ok ├── .gitignore ├── .prettierrc ├── LICENSE ├── README.md ├── jestconfig.json ├── package-lock.json ├── package.json ├── src ├── AuthorizationServerError.ts ├── bindings.d.ts ├── configuration.ts ├── cookieDecrypter.ts ├── handler.ts └── index.ts ├── test ├── handler.test.ts └── valueEncrypter.ts ├── tsconfig.json ├── webpack.config.js └── wrangler.toml /.cargo-ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/curityio/cloudflare-oauth-proxy-worker/bea62a28e903524071dcfa5037d980429a59103c/.cargo-ok -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | dist 2 | node_modules 3 | transpiled 4 | /.idea/ 5 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "semi": false, 4 | "trailingComma": "all", 5 | "tabWidth": 2, 6 | "printWidth": 80 7 | } 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OAuth Proxy module worker 2 | 3 | [![Quality](https://img.shields.io/badge/quality-experiment-red)](https://curity.io/resources/code-examples/status/) 4 | [![Availability](https://img.shields.io/badge/availability-source-blue)](https://curity.io/resources/code-examples/status/) 5 | 6 | An Oauth Proxy module is part of a [Token Handler](https://curity.io/resources/learn/the-token-handler-pattern/) component, a lightweight backend component designed to securely deal with tokens in Single Page Applications. This repository provides a Cloudflare worker implementation of the module using Typescript. The module is responsible for obtaining an access token from an encrypted cookie and forwards the request to the upstream API with the token put in the `Authorization` header. If opaque (phantom) tokens are used, the worker performs token introspection to exchange the opaque token for a JWT. 7 | 8 | ## Getting Started 9 | 10 | You need [Wrangler](https://github.com/cloudflare/wrangler) at least in version 1.17. to work with this code. If you are not already familiar with the tool, then have a look at the [documentation](https://developers.cloudflare.com/workers/tooling/wrangler/). 11 | 12 | ### Running the Dev Environment 13 | 14 | First make sure that proper configuration values are entered in the `wrangler.toml` file, then run `wrangler dev` to start the worker in the dev environment. Have a look at the [SPA and Token Handler's Deployment](https://github.com/curityio/spa-using-token-handler) to learn how to set up the rest of the environment used by the Token Handler. That tutorial uses an nginx API gateway and must be tweaked to work with this worker. 15 | 16 | ### Testing 17 | 18 | `npm test` will run the test suite. Tests are written using [Jest](https://jestjs.io/). 19 | 20 | ## Configuration 21 | 22 | The worker uses the following environment variables for configuration. These can be set in the `wrangler.toml` file or directly from the Cloudflare workers UI. 23 | 24 | - `TRUSTED_WEB_ORIGINS` - a comma-separated list of trusted web origins. Requests coming from other origins will be rejected by the Proxy. 25 | - `COOKIE_NAME_PREFIX` - the name prefix of the cookies used by the proxy. 26 | - `ENCRYPTION_KEY` - a 256-bit encryption key represented as a 64-character hex string. The key is used to decrypt cookie values. You can use the following command to generate a secure key: `openssl rand 32 | xxd -p -c 64` 27 | - `USE_PHANTOM_TOKEN` - a boolean informing the worker whether a phantom token is used. If true, then the worker will perform token introspection before calling the API. 28 | - `INTROSPECTION_URL` - the URL of the introspection endpoint of the Authorization Server. 29 | - `CLIENT_ID` - the ID of the client used to perform the introspection call. 30 | - `CLIENT_SECRET` - the secret of the client used to perform the introspection call. 31 | 32 | ## More Information 33 | 34 | Please visit [curity.io](https://curity.io/) for more information about the Token Handler and the Curity Identity Server. 35 | -------------------------------------------------------------------------------- /jestconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "transform": { 3 | "^.+\\.(t|j)sx?$": "ts-jest" 4 | }, 5 | "testRegex": "/test/.*\\.test\\.ts$", 6 | "collectCoverageFrom": ["src/**/*.{ts,js}"] 7 | } 8 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "oauth-proxy-worker", 3 | "version": "1.0.0", 4 | "description": "An Oauth Proxy module for the Token Handler pattern", 5 | "main": "dist/worker.js", 6 | "scripts": { 7 | "build": "webpack", 8 | "login": "wrangler login", 9 | "start": "wrangler dev", 10 | "publish": "wrangler publish", 11 | "format": "prettier --write '*.{json,js}' 'src/**/*.{js,ts}' 'test/**/*.{js,ts}'", 12 | "lint": "eslint --max-warnings=0 src && prettier --check '*.{json,js}' 'src/**/*.{js,ts}' 'test/**/*.{js,ts}'", 13 | "test": "jest --config jestconfig.json --verbose" 14 | }, 15 | "author": "Curity AB", 16 | "license": "Apache-2.0", 17 | "eslintConfig": { 18 | "root": true, 19 | "extends": [ 20 | "typescript", 21 | "prettier" 22 | ] 23 | }, 24 | "devDependencies": { 25 | "@cloudflare/workers-types": "^3.0.0", 26 | "@cloudflare/wrangler": "^1.19", 27 | "@types/cookie": "^0.4.1", 28 | "@types/jest": "^26.0.23", 29 | "@types/node": "^16.11.7", 30 | "@types/service-worker-mock": "^2.0.1", 31 | "@typescript-eslint/eslint-plugin": "^4.16.1", 32 | "@typescript-eslint/parser": "^4.16.1", 33 | "eslint": "^7.21.0", 34 | "eslint-config-prettier": "^8.1.0", 35 | "eslint-config-typescript": "^3.0.0", 36 | "jest": "^27.0.1", 37 | "prettier": "^2.3.0", 38 | "service-worker-mock": "^2.0.5", 39 | "ts-jest": "^27.0.1", 40 | "ts-loader": "^9.2.2", 41 | "typescript": "^4.3.2", 42 | "webpack": "^5.38.1", 43 | "webpack-cli": "^4.7.0" 44 | }, 45 | "dependencies": { 46 | "cookie": "^0.4.1" 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/AuthorizationServerError.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 Curity AB 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export default class AuthorizationServerError extends Error { 18 | statusCode: number 19 | responseBodyPromise: Promise 20 | constructor(statusCode: number, responseBodyPromise: Promise) { 21 | super('Error returned from the Authorization Server') 22 | 23 | this.statusCode = statusCode 24 | this.responseBodyPromise = responseBodyPromise 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/bindings.d.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 Curity AB 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export {} 18 | 19 | declare global { 20 | const TRUSTED_WEB_ORIGINS: string 21 | const COOKIE_NAME_PREFIX: string 22 | const ENCRYPTION_KEY: string 23 | const USE_PHANTOM_TOKEN: boolean 24 | const INTROSPECTION_URL: string 25 | const CLIENT_ID: string 26 | const CLIENT_SECRET: string 27 | } 28 | -------------------------------------------------------------------------------- /src/configuration.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 Curity AB 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export default class Configuration { 18 | private readonly _trustedOrigins: string[] 19 | private readonly _trustedOriginsString: string 20 | private readonly _cookieNamePrefix: string 21 | private readonly _encryptionKey: string 22 | private readonly _phantomToken: boolean 23 | private readonly _introspectionURL: string 24 | private readonly _clientID: string 25 | private readonly _clientSecret: string 26 | 27 | constructor( 28 | trustedOrigins: string, 29 | cookieNamePrefix: string, 30 | encryptionKey: string, 31 | phantomToken: boolean, 32 | introspectionURL: string, 33 | clientID: string, 34 | clientSecret: string, 35 | ) { 36 | this._trustedOriginsString = trustedOrigins 37 | this._trustedOrigins = trustedOrigins.split(',') 38 | this._cookieNamePrefix = cookieNamePrefix 39 | this._encryptionKey = encryptionKey 40 | this._phantomToken = phantomToken 41 | this._introspectionURL = introspectionURL 42 | this._clientID = clientID 43 | this._clientSecret = clientSecret 44 | } 45 | 46 | get trustedOrigins(): string[] { 47 | return this._trustedOrigins 48 | } 49 | 50 | get trustedOriginsString(): string { 51 | return this._trustedOriginsString 52 | } 53 | 54 | get cookieNamePrefix(): string { 55 | return this._cookieNamePrefix 56 | } 57 | 58 | get encryptionKey(): string { 59 | return this._encryptionKey 60 | } 61 | 62 | get phantomToken(): boolean { 63 | return this._phantomToken 64 | } 65 | 66 | get introspectionURL(): string { 67 | return this._introspectionURL 68 | } 69 | 70 | get clientID(): string { 71 | return this._clientID 72 | } 73 | 74 | get clientSecret(): string { 75 | return this._clientSecret 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/cookieDecrypter.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 Curity AB 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | const VERSION_SIZE = 1; 18 | const GCM_IV_SIZE = 12; 19 | const GCM_TAG_SIZE = 16; 20 | const CURRENT_VERSION = 1; 21 | 22 | export default async function decryptCookie( 23 | payloadBase64UrlEncoded: string, 24 | encryptionKeyHex: string, 25 | ): Promise { 26 | const payloadBytes = base64DecodeURL(payloadBase64UrlEncoded) 27 | 28 | const minSize = (VERSION_SIZE + GCM_IV_SIZE + 1 + GCM_TAG_SIZE) 29 | if (payloadBytes.length < minSize) { 30 | throw new Error('The received payload is invalid and cannot be parsed') 31 | } 32 | 33 | const version = payloadBytes[0] 34 | if (version !== CURRENT_VERSION) { 35 | throw new Error('The received cookie has an invalid format') 36 | } 37 | 38 | let offset = VERSION_SIZE 39 | 40 | const ivBytes = payloadBytes.slice(offset, offset + GCM_IV_SIZE) 41 | offset += GCM_IV_SIZE 42 | const ciphertextAndTagBytes = payloadBytes.slice(offset) 43 | 44 | const aesKey = await crypto.subtle.importKey( 45 | 'raw', 46 | hexToBytes(encryptionKeyHex), 47 | 'AES-GCM', 48 | true, 49 | ['decrypt'], 50 | ) 51 | 52 | const decrypted = await crypto.subtle.decrypt( 53 | { 54 | name: 'AES-GCM', 55 | iv: ivBytes, 56 | tagLength: GCM_TAG_SIZE * 8, // length in bits 57 | }, 58 | aesKey, 59 | ciphertextAndTagBytes, 60 | ) 61 | 62 | const decoder = new TextDecoder() 63 | return decoder.decode(decrypted) 64 | } 65 | 66 | function hexToBytes(hex: string): Uint8Array { 67 | const bytes = new Uint8Array(hex.length / 2) 68 | for (let i = 0; i !== bytes.length; i++) { 69 | bytes[i] = parseInt(hex.substr(i * 2, 2), 16) 70 | } 71 | return bytes 72 | } 73 | 74 | function base64DecodeURL(b64urlstring: string): Uint8Array { 75 | return new Uint8Array(atob(b64urlstring.replace(/-/g, '+').replace(/_/g, '/')).split('').map(val => { 76 | return val.charCodeAt(0); 77 | })); 78 | } 79 | -------------------------------------------------------------------------------- /src/handler.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 Curity AB 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import Configuration from './configuration' 18 | import decryptCookie from './cookieDecrypter' 19 | import { parse } from 'cookie' 20 | import AuthorizationServerError from './AuthorizationServerError' 21 | 22 | export async function handleRequest( 23 | request: Request, 24 | config: Configuration, 25 | fetch: (request: Request) => Promise, 26 | ): Promise { 27 | // Ignore pre-flight requests from browser clients 28 | if (request.method == 'OPTIONS') { 29 | return fetch(request) 30 | } 31 | 32 | // If there is already a bearer token, eg for mobile clients, return immediately 33 | // Note that the target API must always digitally verify the JWT access token 34 | const authorizationHeader = request.headers.get('Authorization') 35 | if (authorizationHeader && authorizationHeader.startsWith('Bearer ')) { 36 | return fetch(request) 37 | } 38 | 39 | // For cookie requests, verify the web origin in line with OWASP CSRF best practices 40 | const originFromHeader = request.headers.get('Origin') || '' 41 | 42 | if (config.trustedOrigins.length) { 43 | if (!config.trustedOrigins.includes(originFromHeader)) { 44 | console.warn( 45 | `The ${request.method} request to ${request.url} was from an untrusted web origin: ${originFromHeader}. Trusted origins: ${config.trustedOriginsString}`, 46 | ) 47 | return new Response( 48 | JSON.stringify({ 49 | message: 'The request failed cookie authorization', 50 | code: 'unauthorized', 51 | }), 52 | { 53 | status: 401, 54 | statusText: 'Unauthorized', 55 | }, 56 | ) 57 | } 58 | } 59 | 60 | const cookies = parse(request.headers.get('Cookie') || '') 61 | const dataChangingMethods = ['POST', 'PUT', 'DELETE', 'PATCH'] 62 | 63 | // For data changing requests do double submit cookie verification in line with OWASP CSRF best practices 64 | if (dataChangingMethods.includes(request.method)) { 65 | const csrfCookieName = config.cookieNamePrefix + '-csrf' 66 | const csrfEncryptedCookie = cookies[csrfCookieName] 67 | 68 | if (!csrfEncryptedCookie) { 69 | console.warn( 70 | `No CSRF cookie was sent with the ${request.method} request to ${request.url}`, 71 | ) 72 | return unauthorizedResponse(config.trustedOrigins, originFromHeader) 73 | } 74 | 75 | let csrfTokenFromCookie = '' 76 | 77 | try { 78 | csrfTokenFromCookie = await decryptCookie( 79 | csrfEncryptedCookie, 80 | config.encryptionKey, 81 | ) 82 | } catch (error) { 83 | console.warn( 84 | `Error decrypting CSRF cookie ${csrfEncryptedCookie} during ${request.method} request to ${request.url}.`, 85 | error.message, 86 | ) 87 | return unauthorizedResponse(config.trustedOrigins, originFromHeader) 88 | } 89 | 90 | const csrfTokenFromHeader = request.headers.get('x-' + csrfCookieName) 91 | if (csrfTokenFromHeader !== csrfTokenFromCookie) { 92 | console.warn( 93 | `Invalid or missing CSRF request header ${csrfTokenFromHeader} during ${request.method} request to ${request.url}. CSRF token from cookie: ${csrfTokenFromCookie}`, 94 | ) 95 | return unauthorizedResponse(config.trustedOrigins, originFromHeader) 96 | } 97 | } 98 | 99 | // Next verify that the main cookie was received and get the access token 100 | const accessTokenEncryptedCookie = cookies[config.cookieNamePrefix + '-at'] 101 | if (!accessTokenEncryptedCookie) { 102 | console.warn( 103 | `No access token cookie was sent with the ${request.method} request to ${request.url}`, 104 | ) 105 | return unauthorizedResponse(config.trustedOrigins, originFromHeader) 106 | } 107 | 108 | // Decrypt the access token cookie, which is encrypted using AES256 109 | let requestToForward = null 110 | let accessToken: string | null 111 | 112 | try { 113 | accessToken = await decryptCookie( 114 | accessTokenEncryptedCookie, 115 | config.encryptionKey, 116 | ) 117 | } catch (error) { 118 | console.warn( 119 | `Error decrypting access token cookie ${accessTokenEncryptedCookie} during ${request.method} request to ${request.url}`, 120 | ) 121 | return unauthorizedResponse(config.trustedOrigins, originFromHeader) 122 | } 123 | 124 | if (config.phantomToken) { 125 | // Exchange phantom token for a JWT 126 | try { 127 | accessToken = await exchangePhantomToken(accessToken, config, fetch) 128 | } catch (error) { 129 | if (error instanceof AuthorizationServerError) { 130 | console.warn( 131 | `Error response from the Authorization Server when trying to exchange the Phantom Token during ${ 132 | request.method 133 | } request to ${request.url}. 134 | Access token from cookie: ${accessToken}. Response code: ${ 135 | error.statusCode 136 | }. Response body from server: ${await error.responseBodyPromise}`, 137 | error.message, 138 | ) 139 | } else { 140 | console.warn( 141 | `Error encountered when trying to exchange the Phantom Token during ${request.method} request to ${request.url}. Access token from cookie: ${accessToken}`, 142 | error.message, 143 | ) 144 | } 145 | return badGatewayResponse(config.trustedOrigins, originFromHeader) 146 | } 147 | } 148 | 149 | if (!accessToken) { 150 | return unauthorizedResponse(config.trustedOrigins, originFromHeader) 151 | } 152 | 153 | // Prepare a request with a new token 154 | requestToForward = new Request(request) 155 | requestToForward.headers.set('Authorization', 'Bearer ' + accessToken) 156 | 157 | // Forward the access token to the target API 158 | if (requestToForward) { 159 | return fetch(requestToForward) 160 | } 161 | 162 | return unauthorizedResponse(config.trustedOrigins, originFromHeader) 163 | } 164 | 165 | const errorResponse = ( 166 | statusCode: number, 167 | code: string, 168 | message: string, 169 | trustedOrigins: string[], 170 | originHeader: string, 171 | ) => { 172 | const headers = new Headers({ 173 | 'Content-Type': 'application/json', 174 | }) 175 | 176 | if (trustedOrigins.length) { 177 | if (trustedOrigins.includes(originHeader)) { 178 | headers.set('Access-Control-Allow-Origin', originHeader) 179 | headers.set('Access-Control-Allow-Credentials', 'true') 180 | } 181 | } 182 | return new Response(JSON.stringify({ message, code }), { 183 | status: statusCode, 184 | headers, 185 | }) 186 | } 187 | 188 | const unauthorizedResponse = (trustedOrigins: string[], originHeader: string) => 189 | errorResponse( 190 | 401, 191 | 'unauthorized', 192 | 'The request failed cookie authorization', 193 | trustedOrigins, 194 | originHeader, 195 | ) 196 | 197 | const badGatewayResponse = (trustedOrigins: string[], originHeader: string) => 198 | errorResponse( 199 | 503, 200 | 'Bad Gateway', 201 | 'Introspection request failed', 202 | trustedOrigins, 203 | originHeader, 204 | ) 205 | 206 | const exchangePhantomToken = async ( 207 | accessToken: string, 208 | configuration: Configuration, 209 | fetch: (request: Request) => Promise, 210 | ): Promise => { 211 | const credentials = configuration.clientID + ':' + configuration.clientSecret 212 | const base64Credentials = btoa(credentials) 213 | .replace(/=/g, '') 214 | .replace(/\+/g, '-') 215 | .replace(/\//g, '_') 216 | const introspectionRequest = new Request(configuration.introspectionURL, { 217 | method: 'POST', 218 | headers: { 219 | 'Content-Type': 'application/x-www-form-urlencoded', 220 | Accept: 'application/jwt', 221 | Authorization: 'Basic ' + base64Credentials, 222 | }, 223 | body: 'token=' + accessToken, 224 | }) 225 | 226 | const introspectionResponse = await fetch(introspectionRequest) 227 | 228 | if (introspectionResponse.status == 204) { 229 | return null 230 | } 231 | 232 | if (introspectionResponse.status != 200) { 233 | throw new AuthorizationServerError( 234 | introspectionResponse.status, 235 | introspectionResponse.text(), 236 | ) 237 | } 238 | 239 | return introspectionResponse.text() 240 | } 241 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 Curity AB 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { handleRequest } from './handler' 18 | import Configuration from './configuration' 19 | 20 | addEventListener('fetch', (event) => { 21 | const config = new Configuration( 22 | TRUSTED_WEB_ORIGINS, 23 | COOKIE_NAME_PREFIX, 24 | ENCRYPTION_KEY, 25 | USE_PHANTOM_TOKEN, 26 | INTROSPECTION_URL, 27 | CLIENT_ID, 28 | CLIENT_SECRET, 29 | ) 30 | event.respondWith(handleRequest(event.request, config, fetch)) 31 | }) 32 | -------------------------------------------------------------------------------- /test/handler.test.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 Curity AB 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { handleRequest } from '../src/handler' 18 | import makeServiceWorkerEnv from 'service-worker-mock' 19 | import Configuration from '../src/configuration' 20 | import encryptValue from './valueEncrypter' 21 | import { serialize } from 'cookie' 22 | import nodecrypto from 'crypto' 23 | 24 | declare let global: never 25 | 26 | // Workers use browser API, tests use node API. We need these two so that tests can run. 27 | Object.assign(global, { 28 | btoa: (credentials: string) => Buffer.from(credentials).toString('base64'), 29 | atob: (base64: string) => Buffer.from(base64, 'base64').toString('binary'), 30 | crypto: nodecrypto.webcrypto, 31 | }) 32 | 33 | describe('OAuth Proxy tests', () => { 34 | const configuration = new Configuration( 35 | 'https://example.com', 36 | 'example', 37 | 'cc26d51be30dd69f11369c6a7af214ef5fce70a6f6ef19f02ab55d4cff4bce5d', 38 | false, 39 | 'https://login.example.com/token', 40 | 'client', 41 | 'secret', 42 | ) 43 | 44 | const configWithPhantomTokenEnabled = new Configuration( 45 | configuration.trustedOriginsString, 46 | configuration.cookieNamePrefix, 47 | configuration.encryptionKey, 48 | true, 49 | configuration.introspectionURL, 50 | configuration.clientID, 51 | configuration.clientSecret, 52 | ) 53 | 54 | const fetchOk = () => Promise.resolve(new Response('', { status: 200 })) 55 | 56 | beforeEach(() => { 57 | Object.assign(global, makeServiceWorkerEnv()) 58 | jest.resetModules() 59 | }) 60 | 61 | test('should pass OPTIONS without any checks', async () => { 62 | const result = await handleRequest( 63 | request('OPTIONS'), 64 | configuration, 65 | fetchOk, 66 | ) 67 | expect(result.status).toEqual(200) 68 | }) 69 | 70 | test('should pass requests with Bearer token without any modifications', async () => { 71 | const result = await handleRequest( 72 | request('GET', { Authorization: 'Bearer access_token' }), 73 | configuration, 74 | fetchOk, 75 | ) 76 | expect(result.status).toEqual(200) 77 | }) 78 | 79 | test('request from untrusted origin should return a 401 response', async () => { 80 | const result = await handleRequest( 81 | request('GET', { Origin: 'https://malicious.site' }), 82 | configuration, 83 | fetchOk, 84 | ) 85 | expect(result.status).toEqual(401) 86 | }) 87 | 88 | const dataChangingMethods = ['POST', 'PUT', 'PATCH', 'DELETE'] 89 | 90 | test.each(dataChangingMethods)( 91 | 'Data changing %p request without CSRF cookie should return 401 response', 92 | async (method) => { 93 | const result = await handleRequest( 94 | trustedOriginRequest(method), 95 | configuration, 96 | fetchOk, 97 | ) 98 | expect(result.status).toEqual(401) 99 | }, 100 | ) 101 | 102 | test.each(dataChangingMethods)( 103 | 'Data changing %p request with invalid CSRF cookie should return 401 response', 104 | async (method) => { 105 | const result = await handleRequest( 106 | trustedOriginRequest(method, { Cookie: csrfCookie('invalid') }), 107 | configuration, 108 | fetchOk, 109 | ) 110 | expect(result.status).toEqual(401) 111 | }, 112 | ) 113 | 114 | test.each(dataChangingMethods)( 115 | 'Data changing %p request with a a valid CSRF cookie should return a 200 response', 116 | async (method) => { 117 | const csrfToken = 'abcdef' 118 | const csrfEncryptedToken = encryptValue( 119 | csrfToken, 120 | configuration.encryptionKey, 121 | ) 122 | const csrfHeaderName = 'x-' + configuration.cookieNamePrefix + '-csrf' 123 | 124 | const result = await handleRequest( 125 | trustedOriginRequest(method, { 126 | Cookie: [ 127 | csrfCookie(csrfEncryptedToken), 128 | accessTokenCookie( 129 | encryptValue('token', configuration.encryptionKey), 130 | ), 131 | ].join('; '), 132 | [csrfHeaderName]: csrfToken, 133 | }), 134 | configuration, 135 | fetchOk, 136 | ) 137 | expect(result.status).toEqual(200) 138 | }, 139 | ) 140 | 141 | test('Request without an access token cookie should return a 401 response', async () => { 142 | const result = await handleRequest( 143 | trustedOriginRequest('GET'), 144 | configuration, 145 | fetchOk, 146 | ) 147 | 148 | expect(result.status).toEqual(401) 149 | }) 150 | 151 | test('Request with invalid access token cookie should return a 401 response', async () => { 152 | const result = await handleRequest( 153 | trustedOriginRequest('GET', { Cookie: accessTokenCookie('invalid') }), 154 | configuration, 155 | fetchOk, 156 | ) 157 | 158 | expect(result.status).toEqual(401) 159 | }) 160 | 161 | test('Request with a valid access token cookie should return a 200 and forward the token to the API', async () => { 162 | const accessToken = 'access_token' 163 | const fetch = (request: Request) => { 164 | const authorizationHeader = request.headers.get('Authorization') 165 | expect(authorizationHeader).toEqual('Bearer ' + accessToken) 166 | return Promise.resolve(new Response('', { status: 200 })) 167 | } 168 | 169 | const result = await handleRequest( 170 | requestWithValidAccessToken(accessToken), 171 | configuration, 172 | fetch, 173 | ) 174 | 175 | expect(result.status).toEqual(200) 176 | }) 177 | 178 | test('When phantom-token option enabled, should return 503 when Authorization Server call returns a 5xx error', async () => { 179 | const fetch = () => Promise.resolve(new Response('', { status: 500 })) 180 | 181 | const result = await handleRequest( 182 | requestWithValidAccessToken(), 183 | configWithPhantomTokenEnabled, 184 | fetch, 185 | ) 186 | 187 | expect(result.status).toEqual(503) 188 | }) 189 | 190 | test('When phantom-token option enabled, should return 503 when Authorization Server call fails', async () => { 191 | const fetch = () => { 192 | throw new Error('Connection to Authorization Server failed') 193 | } 194 | 195 | const result = await handleRequest( 196 | requestWithValidAccessToken(), 197 | configWithPhantomTokenEnabled, 198 | fetch, 199 | ) 200 | 201 | expect(result.status).toEqual(503) 202 | }) 203 | 204 | test('When phantom-token option enabled, should return 401 when token expired', async () => { 205 | const fetch = () => Promise.resolve(new Response('', { status: 204 })) 206 | 207 | const result = await handleRequest( 208 | requestWithValidAccessToken(), 209 | configWithPhantomTokenEnabled, 210 | fetch, 211 | ) 212 | 213 | expect(result.status).toEqual(401) 214 | }) 215 | 216 | test('When phantom-token option enabled, an introspection request should be performed', async () => { 217 | const fetch = (request: Request) => { 218 | if (request.url.endsWith('/token')) { 219 | const acceptHeader = request.headers.get('Accept') 220 | expect(acceptHeader).toEqual('application/jwt') 221 | return Promise.resolve(new Response('jwtToken', { status: 200 })) 222 | } else { 223 | const authorizationHeader = request.headers.get('Authorization') 224 | expect(authorizationHeader).toEqual('Bearer jwtToken') 225 | return Promise.resolve(new Response('', { status: 200 })) 226 | } 227 | } 228 | 229 | const result = await handleRequest( 230 | requestWithValidAccessToken('access_token'), 231 | configWithPhantomTokenEnabled, 232 | fetch, 233 | ) 234 | 235 | expect(result.status).toEqual(200) 236 | }) 237 | 238 | const request = ( 239 | method: string, 240 | headers: HeadersInitializer | undefined = undefined, 241 | ): Request => { 242 | if (headers) { 243 | return new Request('/', { method: method, headers }) 244 | } else { 245 | return new Request('/', { method: method }) 246 | } 247 | } 248 | 249 | const trustedOriginRequest = ( 250 | method: string, 251 | additionalHeaders: HeadersInitializer | undefined = undefined, 252 | ): Request => { 253 | let headers = { Origin: configuration.trustedOrigins[0] } 254 | 255 | if (additionalHeaders !== undefined) { 256 | headers = { 257 | ...additionalHeaders, 258 | ...headers, 259 | } 260 | } 261 | 262 | return request(method, headers) 263 | } 264 | 265 | const requestWithValidAccessToken = (token = 'access_token') => 266 | trustedOriginRequest('GET', { 267 | Cookie: accessTokenCookie( 268 | encryptValue(token, configuration.encryptionKey), 269 | ), 270 | }) 271 | 272 | const csrfCookie = (token: string) => 273 | serialize(configuration.cookieNamePrefix + '-csrf', token) 274 | const accessTokenCookie = (token: string) => 275 | serialize(configuration.cookieNamePrefix + '-at', token) 276 | }) 277 | -------------------------------------------------------------------------------- /test/valueEncrypter.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 Curity AB 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import crypto, { CipherKey } from 'crypto' 18 | 19 | export default function encryptValue( 20 | value: string, 21 | encryptionKeyHex: string, 22 | ): string { 23 | const ivBytes = crypto.randomBytes(12) 24 | const encryptionKeyBytes = Buffer.from(encryptionKeyHex, 'hex') 25 | 26 | return encrypt(value, encryptionKeyBytes, ivBytes) 27 | } 28 | 29 | function encrypt( 30 | payloadText: string, 31 | encryptionKeyBytes: CipherKey, 32 | ivBytes: Buffer, 33 | ) { 34 | const cipher = crypto.createCipheriv('aes-256-gcm', encryptionKeyBytes, ivBytes); 35 | 36 | const versionBytes = Buffer.from(new Uint8Array([1])) 37 | const plaintextBytes = Buffer.from(payloadText) 38 | 39 | const encryptedBytes = cipher.update(plaintextBytes) 40 | const finalBytes = cipher.final() 41 | 42 | const ciphertextBytes = Buffer.concat([encryptedBytes, finalBytes]) 43 | const tagBytes = cipher.getAuthTag() 44 | 45 | const allBytes = Buffer.concat([versionBytes, ivBytes, ciphertextBytes, tagBytes]) 46 | 47 | return allBytes.toString("base64") 48 | .replace(/=/g, "") 49 | .replace(/\+/g, "-") 50 | .replace(/\//g, "_") 51 | } 52 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "./dist", 4 | "module": "commonjs", 5 | "target": "esnext", 6 | "lib": ["esnext"], 7 | "alwaysStrict": true, 8 | "strict": true, 9 | "preserveConstEnums": true, 10 | "moduleResolution": "node", 11 | "sourceMap": true, 12 | "esModuleInterop": true, 13 | "types": [ 14 | "@cloudflare/workers-types", 15 | "@types/jest", 16 | "@types/service-worker-mock", 17 | "@types/node" 18 | ] 19 | }, 20 | "include": ["src"], 21 | "exclude": ["node_modules", "dist", "test"] 22 | } 23 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path') 2 | 3 | module.exports = { 4 | entry: './src/index.ts', 5 | output: { 6 | filename: 'worker.js', 7 | path: path.join(__dirname, 'dist'), 8 | }, 9 | // devtool: 'cheap-module-source-map', 10 | // mode: 'development', 11 | mode: 'production', 12 | resolve: { 13 | extensions: ['.ts', '.tsx', '.js'], 14 | fallback: {}, 15 | }, 16 | module: { 17 | rules: [ 18 | { 19 | test: /\.tsx?$/, 20 | loader: 'ts-loader', 21 | options: { 22 | // transpileOnly is useful to skip typescript checks occasionally: 23 | // transpileOnly: true, 24 | }, 25 | }, 26 | ], 27 | }, 28 | } 29 | -------------------------------------------------------------------------------- /wrangler.toml: -------------------------------------------------------------------------------- 1 | name = "oauth-proxy" 2 | type = "javascript" 3 | zone_id = "" 4 | account_id = "" 5 | route = "" 6 | workers_dev = true 7 | compatibility_date = "2022-01-11" 8 | 9 | [build] 10 | command = "npm install && npm run build" 11 | [build.upload] 12 | format = "service-worker" 13 | 14 | [vars] 15 | ENCRYPTION_KEY = "cc26d51be30dd69f11369c6a7af214ef5fce70a6f6ef19f02ab55d4cff4bce5d" 16 | COOKIE_NAME_PREFIX = "example" 17 | TRUSTED_WEB_ORIGINS = "https://www.example.com" 18 | USE_PHANTOM_TOKEN = true 19 | INTROSPECTION_URL = "https://login.example.com:8443/oauth/v2/oauth-token" 20 | CLIENT_ID = "gateway-client" 21 | CLIENT_SECRET = "Password1" 22 | --------------------------------------------------------------------------------