diff --git a/.github/workflows/tests-release.yml b/.github/workflows/tests-release.yml index da006a27..2bd4e253 100644 --- a/.github/workflows/tests-release.yml +++ b/.github/workflows/tests-release.yml @@ -10,7 +10,6 @@ on: branches: - release-* # all release- branches - jobs: # STEP 1 - NPM Audit @@ -23,13 +22,13 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 - with: - node-version: 20 - # install to create local package-lock.json but don't cache the files - # also: no audit for dev dependencies - - run: npm i --package-lock-only && npm audit --production + - uses: actions/checkout@v3 + - uses: actions/setup-node@v3 + with: + node-version: 20 + # install to create local package-lock.json but don't cache the files + # also: no audit for dev dependencies + - run: npm i --package-lock-only && npm audit --production # STEP 2 - basic unit tests @@ -40,34 +39,34 @@ jobs: needs: [audit] strategy: matrix: - node: [14, 16, 18] + node: [16, 18, 20] steps: - - name: Checkout ${{ matrix.node }} - uses: actions/checkout@v3 - - - name: Setup node ${{ matrix.node }} - uses: actions/setup-node@v3 - with: - node-version: ${{ matrix.node }} - - - name: Cache dependencies ${{ matrix.node }} - uses: actions/cache@v3 - with: - path: ~/.npm - key: ${{ runner.os }}-node-${{ matrix.node }}-${{ hashFiles('**/package-lock.json') }} - restore-keys: | - ${{ runner.os }}-node-${{ matrix.node }} - # for this workflow we also require npm audit to pass - - run: npm i - - run: npm run test:coverage - - # with the following action we enforce PRs to have a high coverage - # and ensure, changes are tested well enough so that coverage won't fail - - name: check coverage - uses: VeryGoodOpenSource/very_good_coverage@v1.2.0 - with: - path: './coverage/lcov.info' - min_coverage: 95 + - name: Checkout ${{ matrix.node }} + uses: actions/checkout@v3 + + - name: Setup node ${{ matrix.node }} + uses: actions/setup-node@v3 + with: + node-version: ${{ matrix.node }} + + - name: Cache dependencies ${{ matrix.node }} + uses: actions/cache@v3 + with: + path: ~/.npm + key: ${{ runner.os }}-node-${{ matrix.node }}-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-node-${{ matrix.node }} + # for this workflow we also require npm audit to pass + - run: npm i + - run: npm run test:coverage + + # with the following action we enforce PRs to have a high coverage + # and ensure, changes are tested well enough so that coverage won't fail + - name: check coverage + uses: VeryGoodOpenSource/very_good_coverage@v1.2.0 + with: + path: './coverage/lcov.info' + min_coverage: 95 # STEP 3 - Integration tests @@ -80,41 +79,41 @@ jobs: needs: [unittest] strategy: matrix: - node: [14, 16, 18] # TODO get running for node 16+ + node: [16, 18, 20] # TODO get running for node 16+ steps: - # checkout this repo - - name: Checkout ${{ matrix.node }} - uses: actions/checkout@v3 - - # checkout express-adapter repo - - name: Checkout express-adapter ${{ matrix.node }} - uses: actions/checkout@v3 - with: - repository: node-oauth/express-oauth-server - path: github/testing/express - - - name: Setup node ${{ matrix.node }} - uses: actions/setup-node@v3 - with: - node-version: ${{ matrix.node }} - - - name: Cache dependencies ${{ matrix.node }} - uses: actions/cache@v3 - with: - path: ~/.npm - key: ${{ runner.os }}-node-${{ matrix.node }}-node-oauth/express-oauth-server-${{ hashFiles('github/testing/express/**/package-lock.json') }} - restore-keys: | - ${{ runner.os }}-node-${{ matrix.node }}-node-oauth/express-oauth-server - - # in order to test the adapter we need to use the current checkout - # and install it as local dependency - # we just cloned and install it as local dependency - # xxx: added bluebird as explicit dependency - - run: | - cd github/testing/express - npm i - npm install ../../../ - npm run test + # checkout this repo + - name: Checkout ${{ matrix.node }} + uses: actions/checkout@v3 + + # checkout express-adapter repo + - name: Checkout express-adapter ${{ matrix.node }} + uses: actions/checkout@v3 + with: + repository: node-oauth/express-oauth-server + path: github/testing/express + + - name: Setup node ${{ matrix.node }} + uses: actions/setup-node@v3 + with: + node-version: ${{ matrix.node }} + + - name: Cache dependencies ${{ matrix.node }} + uses: actions/cache@v3 + with: + path: ~/.npm + key: ${{ runner.os }}-node-${{ matrix.node }}-node-oauth/express-oauth-server-${{ hashFiles('github/testing/express/**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-node-${{ matrix.node }}-node-oauth/express-oauth-server + + # in order to test the adapter we need to use the current checkout + # and install it as local dependency + # we just cloned and install it as local dependency + # xxx: added bluebird as explicit dependency + - run: | + cd github/testing/express + npm i + npm install https://github.com/node-oauth/node-oauth2-server.git#${{ github.ref_name }} + npm run test # todo repeat with other adapters @@ -139,13 +138,13 @@ jobs: contents: read packages: write steps: - - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 - with: - # we always publish targeting the lowest supported node version - node-version: 16 - registry-url: $registry-url(npm) - - run: npm i - - run: npm publish --dry-run - env: - NODE_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}} \ No newline at end of file + - uses: actions/checkout@v3 + - uses: actions/setup-node@v3 + with: + # we always publish targeting the lowest supported node version + node-version: 16 + registry-url: $registry-url(npm) + - run: npm i + - run: npm publish --dry-run + env: + NODE_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}} diff --git a/.mocharc.yml b/.mocharc.yml index 83fda38c..1b4a955a 100644 --- a/.mocharc.yml +++ b/.mocharc.yml @@ -1,6 +1,6 @@ recursive: true reporter: "spec" -retries: 1 +retries: 0 slow: 20 timeout: 2000 ui: "bdd" diff --git a/.readthedocs.yml b/.readthedocs.yml index d9ee7902..bc2b3c65 100644 --- a/.readthedocs.yml +++ b/.readthedocs.yml @@ -17,6 +17,6 @@ sphinx: # We recommend specifying your dependencies to enable reproducible builds: # https://docs.readthedocs.io/en/stable/guides/reproducible-builds.html -# python: -# install: -# - requirements: docs/requirements.txt \ No newline at end of file +python: + install: + - requirements: docs/requirements.txt \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index f85f8456..79ef175d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,23 @@ ## Changelog +## 5.0.0 + +This release contains several breaking changes. +Please carefully consult the documentation while updating. + +- removed `bluebird` and `promisify-any` +- uses native Promises and `async/await` everywhere +- drop support for Node 14 (EOL), setting Node 16 as `engine` in `package.json` +- this is a breaking change, because **it removes callback support** for + `OAuthServer` and your model implementation. +- fixed missing await in calling generateAuthorizationCode in AuthorizeHandler +- fix scope validation bug +- revoke code before validating redirect URI +- improved Bearer token validation +- validate scope as an array of strings (breaking change) +- model support for retrieving user based on client +- more tests added; test coverage improved + ## 4.2.0 ### Fixed - fix(core): Bearer regular expression matching in authenticate handler #105 @@ -43,7 +61,7 @@ - Upgrades all code from ES5 to ES6, where possible. ## 4.1.0 -### Changed +### Changed * Bump dev dependencies to resolve vulnerabilities * Replaced jshint with eslint along with should and chai * Use sha256 when generating tokens diff --git a/README.md b/README.md index 1b14f038..5f01c4af 100644 --- a/README.md +++ b/README.md @@ -8,9 +8,9 @@ Complete, compliant and well tested module for implementing an OAuth2 server in [![Tests for Release](https://github.com/node-oauth/node-oauth2-server/actions/workflows/tests-release.yml/badge.svg)](https://github.com/node-oauth/node-oauth2-server/actions/workflows/tests-release.yml) [![Documentation Status](https://readthedocs.org/projects/node-oauthoauth2-server/badge/?version=latest)](https://node-oauthoauth2-server.readthedocs.io/en/latest/?badge=latest) [![Project Status: Active – The project has reached a stable, usable state and is being actively developed.](https://www.repostatus.org/badges/latest/active.svg)](https://www.repostatus.org/#active) -![npm Version](https://img.shields.io/npm/v/@node-oauth/oauth2-server?label=version) -![npm Downloads/Week](https://img.shields.io/npm/dw/@node-oauth/oauth2-server) -![GitHub License](https://img.shields.io/github/license/node-oauth/node-oauth2-server) +[![npm Version](https://img.shields.io/npm/v/@node-oauth/oauth2-server?label=version)](https://www.npmjs.com/package/@node-oauth/oauth2-server) +[![npm Downloads/Week](https://img.shields.io/npm/dw/@node-oauth/oauth2-server)](https://www.npmjs.com/package/@node-oauth/oauth2-server) +[![GitHub License](https://img.shields.io/github/license/node-oauth/node-oauth2-server)](https://github.com/node-oauth/node-oauth2-server/blob/master/LICENSE) NOTE: This project has been forked from [oauthjs/node-oauth2-server](https://github.com/oauthjs/node-oauth2-server) and is a continuation due to the project appearing to be abandoned. Please see [our issue board](https://github.com/node-oauth/node-oauth2-server/issues) to talk about next steps and the future of this project. @@ -27,7 +27,7 @@ If you're using one of those frameworks it is strongly recommended to use the re ## Features - Supports `authorization_code`, `client_credentials`, `refresh_token` and `password` grant, as well as *extension grants*, with scopes. -- Can be used with *promises*, *Node-style callbacks*, *ES6 generators* and *async*/*await* (using [Babel](https://babeljs.io)). +- Can be used with *promises*, *ES6 generators* and *async*/*await* (using [Babel](https://babeljs.io)). - Fully [RFC 6749](https://tools.ietf.org/html/rfc6749.html) and [RFC 6750](https://tools.ietf.org/html/rfc6750.html) compliant. - Implicitly supports any form of storage, e.g. *PostgreSQL*, *MySQL*, *MongoDB*, *Redis*, etc. - Support for PKCE @@ -35,16 +35,27 @@ If you're using one of those frameworks it is strongly recommended to use the re ## Documentation -[Documentation](https://node-oauthoauth2-server.readthedocs.io/en/latest/) is hosted on Read the Docs. +Documentation is hosted on Read the Docs. We have multiple versions of the docs available: + +- [stable](https://node-oauthoauth2-server.readthedocs.io/en/master/) (master branch) +- [development](https://node-oauthoauth2-server.readthedocs.io/en/development/) (development branch) + Please leave an issue if something is confusing or missing in the docs. ## Examples -Most users should refer to our [Express (active)](https://github.com/node-oauth/express-oauth-server) or +Most users should refer to our [Express (active)](https://github.com/node-oauth/express-oauth-server) or [Koa (not maintained by us)](https://github.com/oauthjs/koa-oauth-server/tree/master/examples) examples. More examples can be found here: https://github.com/14gasher/oauth-example +## Version 5 notes + +Beginning with version `5.x` we removed dual support for callbacks and promises. +With this version there is only support for Promises / async/await. + +With this version we also bumped the `engine` to Node 16 as 14 is now deprecated. + ## Migrating from OAuthJs and 3.x Version 4.x should not be hard-breaking, however, there were many improvements and fixes that may diff --git a/SECURITY.md b/SECURITY.md index f0cc8ef8..5bc4f6a9 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -5,11 +5,12 @@ Use this section to tell people about which versions of your project are currently being supported with security updates. -| Version | Supported | -| ------- | ------------------ | -| 4.x.x | :white_check_mark: | -| 3.x.x | :white_check_mark: but only very critical security issues | -| < 3 | :x: | +| Version | Supported | +|---------|--------------------------------------------------| +| 5.x.x | :white_check_mark: | +| 4.x.x | :white_check_mark: but only high severity issues | +| 3.x.x | :x: | +| < 3 | :x: | ## Reporting a Vulnerability diff --git a/docs/api/oauth2-server.rst b/docs/api/oauth2-server.rst index 38cf6bd1..2cb6cda4 100644 --- a/docs/api/oauth2-server.rst +++ b/docs/api/oauth2-server.rst @@ -57,7 +57,7 @@ Advanced example with additional options: .. _OAuth2Server#authenticate: -``authenticate(request, response, [options], [callback])`` +``authenticate(request, response, [options])`` ========================================================== Authenticates a request. @@ -73,7 +73,7 @@ Authenticates a request. +------------------------------------------------+-----------------+-----------------------------------------------------------------------+ | [options={}] | Object | Handler options. | +------------------------------------------------+-----------------+-----------------------------------------------------------------------+ -| [options.scope=undefined] | String | The scope(s) to authenticate. | +| [options.scope=undefined] | String[] | The scope(s) to authenticate. | +------------------------------------------------+-----------------+-----------------------------------------------------------------------+ | [options.addAcceptedScopesHeader=true] | Boolean | Set the ``X-Accepted-OAuth-Scopes`` HTTP header on response objects. | +------------------------------------------------+-----------------+-----------------------------------------------------------------------+ @@ -81,8 +81,6 @@ Authenticates a request. +------------------------------------------------+-----------------+-----------------------------------------------------------------------+ | [options.allowBearerTokensInQueryString=false] | Boolean | Allow clients to pass bearer tokens in the query string of a request. | +------------------------------------------------+-----------------+-----------------------------------------------------------------------+ -| [callback=undefined] | Function | Node-style callback to be used instead of the returned ``Promise``. | -+------------------------------------------------+-----------------+-----------------------------------------------------------------------+ **Return value:** @@ -94,8 +92,6 @@ Possible errors include but are not limited to: :doc:`/api/errors/unauthorized-request-error`: The protected resource request failed authentication. -**Versions <=4.x note:** The returned ``Promise`` **must** be ignored if ``callback`` is used. - **Remarks:** :: @@ -121,7 +117,7 @@ Possible errors include but are not limited to: .. _OAuth2Server#authorize: -``authorize(request, response, [options], [callback])`` +``authorize(request, response, [options])`` ======================================================= Authorizes a token request. @@ -139,14 +135,12 @@ Authorizes a token request. +-----------------------------------------+-----------------+-----------------------------------------------------------------------------+ | [options={}] | Object | Handler options. | +-----------------------------------------+-----------------+-----------------------------------------------------------------------------+ -| [options.authenticateHandler=undefined] | Object | The authenticate handler (see remarks section below). | +| [options.authenticateHandler=undefined] | Object | The authenticate handler (see remarks section). | +-----------------------------------------+-----------------+-----------------------------------------------------------------------------+ | [options.allowEmptyState=false] | Boolean | Allow clients to specify an empty ``state``. | +-----------------------------------------+-----------------+-----------------------------------------------------------------------------+ | [options.authorizationCodeLifetime=300] | Number | Lifetime of generated authorization codes in seconds (default = 5 minutes). | +-----------------------------------------+-----------------+-----------------------------------------------------------------------------+ -| [callback=undefined] | Function | Node-style callback to be used instead of the returned ``Promise``. | -+-----------------------------------------+-----------------+-----------------------------------------------------------------------------+ **Return value:** @@ -158,8 +152,6 @@ Possible errors include but are not limited to: :doc:`/api/errors/access-denied-error` The resource owner denied the access request (i.e. ``request.query.allow`` was ``'false'``). -**Versions <=4.x note:** The returned ``Promise`` **must** be ignored if ``callback`` is used. - **Remarks:** If ``request.query.allowed`` equals the string ``'false'`` the access request is denied and the returned promise is rejected with an :doc:`/api/errors/access-denied-error`. @@ -211,7 +203,7 @@ When working with a session-based login mechanism, the handler can simply look l .. _OAuth2Server#token: -``token(request, response, [options], [callback])`` +``token(request, response, [options])`` =================================================== Retrieves a new token for an authorized token request. @@ -239,8 +231,6 @@ Retrieves a new token for an authorized token request. +----------------------------------------------+-----------------+-------------------------------------------------------------------------------------------+ | [options.extendedGrantTypes={}] | Object | Additional supported grant types. | +----------------------------------------------+-----------------+-------------------------------------------------------------------------------------------+ -| [callback=undefined] | Function | Node-style callback to be used instead of the returned ``Promise``. | -+----------------------------------------------+-----------------+-------------------------------------------------------------------------------------------+ **Return value:** @@ -252,8 +242,6 @@ Possible errors include but are not limited to: :doc:`/api/errors/invalid-grant-error`: The access token request was invalid or not authorized. -**Versions <=4.x note:** The returned ``Promise`` **must** be ignored if ``callback`` is used. - **Remarks:** If ``options.allowExtendedTokenAttributes`` is ``true`` any additional properties set on the object returned from :ref:`Model#saveToken() ` are copied to the token response sent to the client. diff --git a/docs/conf.py b/docs/conf.py index a621e906..2abf9c3f 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -28,7 +28,7 @@ # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = ['sphinx.ext.intersphinx', 'sphinx.ext.ifconfig', 'sphinx.ext.todo'] +extensions = ['sphinx.ext.intersphinx', 'sphinx.ext.ifconfig', 'sphinx.ext.todo', 'sphinx_rtd_theme'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] @@ -94,7 +94,7 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. -html_theme = 'default' +html_theme = "sphinx_rtd_theme" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the diff --git a/docs/docs/adapters.rst b/docs/docs/adapters.rst index bec9ce6f..139995ee 100644 --- a/docs/docs/adapters.rst +++ b/docs/docs/adapters.rst @@ -2,12 +2,12 @@ Adapters ========== -The *oauth2-server* module is typically not used directly but through one of the available adapters, converting the interface to a suitable one for the HTTP server framework in use. +The *@node-oauth/oauth2-server* module is typically not used directly but through one of the available adapters, converting the interface to a suitable one for the HTTP server framework in use. -.. framework-agnostic but there are several officially supported adapters available for popular HTTP server frameworks such as Express_ and Koa_. +.. framework-agnostic but there are several officially supported adapters available for popular HTTP server frameworks such as Express_ and Koa_ (not maintained by us). - express-oauth-server_ for Express_ -- koa-oauth-server_ for Koa_ (outdated, maintainer wanted!) +- koa-oauth-server_ for Koa_ .. _express-oauth-server: https://www.npmjs.com/package/@node-oauth/express-oauth-server .. _Express: https://npmjs.org/package/express @@ -32,5 +32,5 @@ Adapters typically do the following: - Copy all fields from the :doc:`Response ` back to the framework-specific request object and send it. -Adapters should preserve functionality provided by *oauth2-server* but are free to add additional features that make sense for the respective HTTP server framework. +Adapters should preserve functionality provided by *@node-oauth/oauth2-server* but are free to add additional features that make sense for the respective HTTP server framework. diff --git a/docs/docs/getting-started.rst b/docs/docs/getting-started.rst index 1a55f18c..9d86c15b 100644 --- a/docs/docs/getting-started.rst +++ b/docs/docs/getting-started.rst @@ -16,7 +16,7 @@ oauth2-server_ is available via npm_. $ npm install @node-oauth/oauth2-server -.. note:: The *oauth2-server* module is framework-agnostic but there are several officially supported adapters available for popular HTTP server frameworks such as Express_ and Koa_ (maintainer wanted!). If you're using one of those frameworks it is strongly recommended to use the respective adapter module instead of rolling your own. +.. note:: The *@node-oauth/oauth2-server* module is framework-agnostic but there are several officially supported adapters available for popular HTTP server frameworks such as Express_ and Koa_. If you're using one of those frameworks it is strongly recommended to use the respective adapter module instead of rolling your own. .. _Express: https://www.npmjs.com/package/@node-oauth/express-oauth-server .. _Koa: https://npmjs.org/package/koa-oauth-server @@ -28,14 +28,11 @@ Features ======== - Supports :ref:`authorization code `, :ref:`client credentials `, :ref:`refresh token ` and :ref:`password ` grant, as well as :ref:`extension grants `, with scopes. -- Can be used with *promises*, *Node-style callbacks*, *ES6 generators* and *async*/*await* (using Babel_). -- From version 5.0.0 fully native async/await implemented +- Can be used with *promises*, *ES6 generators* and *async*/*await*. - Fully :rfc:`6749` and :rfc:`6750` compliant. -- Supports PKCE (:rfc:`7636`) - Implicitly supports any form of storage, e.g. *PostgreSQL*, *MySQL*, *MongoDB*, *Redis*, etc. - Complete `test suite`_. -.. _Babel: https://babeljs.io .. _test suite: https://github.com/node-oauth/node-oauth2-server/tree/master/test diff --git a/docs/index.rst b/docs/index.rst index f88c4b47..7c1ea417 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -45,25 +45,23 @@ Example Usage See the :doc:`/model/spec` of what is required from the model passed to :doc:`/api/oauth2-server`. +Contents +-------- .. toctree:: - :hidden: - Home .. toctree:: - :maxdepth: 2 + :maxdepth: 1 :caption: User Documentation - :hidden: docs/getting-started docs/adapters .. toctree:: - :maxdepth: 2 + :maxdepth: 1 :caption: API :includehidden: - :hidden: api/oauth2-server api/request @@ -71,19 +69,18 @@ See the :doc:`/model/spec` of what is required from the model passed to :doc:`/a api/errors/index .. toctree:: - :maxdepth: 3 + :maxdepth: 1 :caption: Model - :hidden: model/overview model/spec .. toctree:: - :maxdepth: 2 + :maxdepth: 1 :caption: Miscellaneous - :hidden: misc/extension-grants misc/pkce + misc/migrating-to-v5 misc/migrating-v2-to-v3 diff --git a/docs/misc/migrating-to-v5.rst b/docs/misc/migrating-to-v5.rst new file mode 100644 index 00000000..279c343b --- /dev/null +++ b/docs/misc/migrating-to-v5.rst @@ -0,0 +1,44 @@ +=========================== + Migrating to 5.x +=========================== + +This guide covers the most breaking changes, in case you updated from an earlier version. + +------------------- +Requires Node >= 16 +------------------- + +Due to Node 14 reaching end of life (EOL; which implies no security updates) this version requires at least Node 16. +Future versions of the 5.x major releases will update to a newer Node LTS, once the current one reaches EOL. + +Note, that we also won't regard any security patches to problems that are a direct consequence of +using a Node version that reached EOL. + +------------------------ +Removed callback support +------------------------ + +With beginning of release 5.0.0 this module dropped all callback support and uses `async/await` +for all asynchronous operations. + +This implies you either need to have a more recent Node.js environment that natively supports `async/await` +or your project uses tools to support at least Promises. + +----------------- +Update your model +----------------- + +The model functions is now expected to return a Promise (or being declared as `async function`), +since callback support is dropped. + +Note: Synchronous model functions are still supported. However, we recommend to use Promise or async, +if database operations (or other heavy operations) are part of a specific model function implementation. + +------------------ +Scope is now Array +------------------ + +In earlier versions we allowed `scope` to be strings with words, separated by empty space. +With beginning of 5.0.0 the scope parameter needs to be an Array of strings. + +This implies to requests, responses and model implementations where scope is included. diff --git a/docs/model/spec.rst b/docs/model/spec.rst index b0d23ccc..f18923f8 100644 --- a/docs/model/spec.rst +++ b/docs/model/spec.rst @@ -66,7 +66,7 @@ This model function is **optional**. If not implemented, a default handler is us +------------+----------+---------------------------------------------------------------------+ | user | Object | The user the access token is generated for. | +------------+----------+---------------------------------------------------------------------+ -| scope | String | The scopes associated with the access token. Can be ``null``. | +| scope | String[] | The scopes associated with the access token. Can be ``null``. | +------------+----------+---------------------------------------------------------------------+ **Return value:** @@ -107,7 +107,7 @@ This model function is **optional**. If not implemented, a default handler is us +------------+----------+---------------------------------------------------------------------+ | user | Object | The user the refresh token is generated for. | +------------+----------+---------------------------------------------------------------------+ -| scope | String | The scopes associated with the refresh token. Can be ``null``. | +| scope | String[] | The scopes associated with the refresh token. Can be ``null``. | +------------+----------+---------------------------------------------------------------------+ **Return value:** @@ -146,7 +146,7 @@ This model function is **optional**. If not implemented, a default handler is us +------------+----------+---------------------------------------------------------------------+ | user | Object | The user the authorization code is generated for. | +------------+----------+---------------------------------------------------------------------+ -| scope | String | The scopes associated with the authorization code. Can be ``null``. | +| scope | String[] | The scopes associated with the authorization code. Can be ``null``. | +------------+----------+---------------------------------------------------------------------+ **Return value:** @@ -182,23 +182,23 @@ This model function is **required** if :ref:`OAuth2Server#authenticate() VALID_SCOPES.indexOf(s) >= 0)) { + if (!scope.every(s => VALID_SCOPES.indexOf(s) >= 0)) { return false; } return scope; @@ -895,14 +893,9 @@ To accept partially valid scopes: const VALID_SCOPES = ['read', 'write']; function validateScope(user, client, scope) { - return scope - .split(' ') - .filter(s => VALID_SCOPES.indexOf(s) >= 0) - .join(' '); + return scope.filter(s => VALID_SCOPES.indexOf(s) >= 0); } -Note that the example above will still reject completely invalid scopes, since ``validateScope`` returns an empty string if all scopes are filtered out. - -------- .. _Model#verifyScope: @@ -930,7 +923,7 @@ but it's never called, if you provide your own ``authenticateHandler`` to the op +------------------------------+----------+---------------------------------------------------------------------+ | [token.accessTokenExpiresAt] | Date | The expiry time of the access token. | +------------------------------+----------+---------------------------------------------------------------------+ -| [token.scope] | String | The authorized scope of the access token. | +| [token.scope] | String[] | The authorized scope of the access token. | +------------------------------+----------+---------------------------------------------------------------------+ | token.client | Object | The client associated with the access token. | +------------------------------+----------+---------------------------------------------------------------------+ @@ -938,7 +931,7 @@ but it's never called, if you provide your own ``authenticateHandler`` to the op +------------------------------+----------+---------------------------------------------------------------------+ | token.user | Object | The user associated with the access token. | +------------------------------+----------+---------------------------------------------------------------------+ -| scope | String | The required scopes. | +| scope | String[] | The required scopes. | +------------------------------+----------+---------------------------------------------------------------------+ **Return value:** @@ -953,13 +946,12 @@ Returns ``true`` if the access token passes, ``false`` otherwise. :: - function verifyScope(token, scope) { + function verifyScope(token, requestedScopes) { if (!token.scope) { return false; } - let requestedScopes = scope.split(' '); - let authorizedScopes = token.scope.split(' '); - return requestedScopes.every(s => authorizedScopes.indexOf(s) >= 0); + let authorizedScopes = token.scope; + return requestedScopes.every(s => token.scope.includes(scope)); } -------- diff --git a/docs/requirements.txt b/docs/requirements.txt new file mode 100644 index 00000000..1ee13a2b --- /dev/null +++ b/docs/requirements.txt @@ -0,0 +1,4 @@ +# Defining the exact version will make sure things don't break +sphinx==5.3.0 +sphinx_rtd_theme==1.1.1 +readthedocs-sphinx-search==0.1.1 \ No newline at end of file diff --git a/index.d.ts b/index.d.ts index 777bda80..5cd73d9c 100644 --- a/index.d.ts +++ b/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Node OAuth2 Server 4.0 +// Type definitions for Node OAuth2 Server 5.0 // Definitions by: Robbie Van Gorkom , // Charles Irick , // Daniel Fischer , @@ -23,8 +23,7 @@ declare class OAuth2Server { authenticate( request: OAuth2Server.Request, response: OAuth2Server.Response, - options?: OAuth2Server.AuthenticateOptions, - callback?: OAuth2Server.Callback + options?: OAuth2Server.AuthenticateOptions ): Promise; /** @@ -33,8 +32,7 @@ declare class OAuth2Server { authorize( request: OAuth2Server.Request, response: OAuth2Server.Response, - options?: OAuth2Server.AuthorizeOptions, - callback?: OAuth2Server.Callback + options?: OAuth2Server.AuthorizeOptions ): Promise; /** @@ -43,8 +41,7 @@ declare class OAuth2Server { token( request: OAuth2Server.Request, response: OAuth2Server.Response, - options?: OAuth2Server.TokenOptions, - callback?: OAuth2Server.Callback + options?: OAuth2Server.TokenOptions ): Promise; } @@ -121,13 +118,13 @@ declare namespace OAuth2Server { * Generate access token. Calls Model#generateAccessToken() if implemented. * */ - generateAccessToken(client: Client, user: User, scope: string | string[]): Promise; + generateAccessToken(client: Client, user: User, scope: string[]): Promise; /** * Generate refresh token. Calls Model#generateRefreshToken() if implemented. * */ - generateRefreshToken(client: Client, user: User, scope: string | string[]): Promise; + generateRefreshToken(client: Client, user: User, scope: string[]): Promise; /** * Get access token expiration date. @@ -145,13 +142,13 @@ declare namespace OAuth2Server { * Get scope from the request body. * */ - getScope(request: Request): string; + getScope(request: Request): string[]; /** * Validate requested scope. Calls Model#validateScope() if implemented. * */ - validateScope(user: User, client: Client, scope: string | string[]): Promise; + validateScope(user: User, client: Client, scope: string[]): Promise; /** * Retrieve info from the request and client and return token @@ -171,7 +168,7 @@ declare namespace OAuth2Server { /** * The scope(s) to authenticate. */ - scope?: string | string[] | undefined; + scope?: string[] | undefined; /** * Set the X-Accepted-OAuth-Scopes HTTP header on response objects. @@ -238,11 +235,6 @@ declare namespace OAuth2Server { extendedGrantTypes?: { [key: string]: typeof AbstractGrantType } | undefined; } - /** - * Represents a generic callback structure for model callbacks - */ - type Callback = (err?: any, result?: T) => void; - /** * For returning falsey parameters in cases of failure */ @@ -253,19 +245,19 @@ declare namespace OAuth2Server { * Invoked to generate a new access token. * */ - generateAccessToken?(client: Client, user: User, scope: string | string[], callback?: Callback): Promise; + generateAccessToken?(client: Client, user: User, scope: string[]): Promise; /** * Invoked to retrieve a client using a client id or a client id/client secret combination, depending on the grant type. * */ - getClient(clientId: string, clientSecret: string, callback?: Callback): Promise; + getClient(clientId: string, clientSecret: string): Promise; /** * Invoked to save an access token and optionally a refresh token, depending on the grant type. * */ - saveToken(token: Token, client: Client, user: User, callback?: Callback): Promise; + saveToken(token: Token, client: Client, user: User): Promise; } interface RequestAuthenticationModel { @@ -273,13 +265,14 @@ declare namespace OAuth2Server { * Invoked to retrieve an existing access token previously saved through Model#saveToken(). * */ - getAccessToken(accessToken: string, callback?: Callback): Promise; + getAccessToken(accessToken: string): Promise; /** * Invoked during request authentication to check if the provided access token was authorized the requested scopes. + * Optional, if a custom authenticateHandler is used or if there is no scope part of the request. * */ - verifyScope(token: Token, scope: string | string[], callback?: Callback): Promise; + verifyScope?(token: Token, scope: string[]): Promise; } interface AuthorizationCodeModel extends BaseModel, RequestAuthenticationModel { @@ -287,19 +280,19 @@ declare namespace OAuth2Server { * Invoked to generate a new refresh token. * */ - generateRefreshToken?(client: Client, user: User, scope: string | string[], callback?: Callback): Promise; + generateRefreshToken?(client: Client, user: User, scope: string[]): Promise; /** * Invoked to generate a new authorization code. * */ - generateAuthorizationCode?(client: Client, user: User, scope: string | string[], callback?: Callback): Promise; + generateAuthorizationCode?(client: Client, user: User, scope: string[]): Promise; /** * Invoked to retrieve an existing authorization code previously saved through Model#saveAuthorizationCode(). * */ - getAuthorizationCode(authorizationCode: string, callback?: Callback): Promise; + getAuthorizationCode(authorizationCode: string): Promise; /** * Invoked to save an authorization code. @@ -308,21 +301,21 @@ declare namespace OAuth2Server { saveAuthorizationCode( code: Pick, client: Client, - user: User, - callback?: Callback): Promise; + user: User + ): Promise; /** * Invoked to revoke an authorization code. * */ - revokeAuthorizationCode(code: AuthorizationCode, callback?: Callback): Promise; + revokeAuthorizationCode(code: AuthorizationCode): Promise; /** * Invoked to check if the requested scope is valid for a particular client/user combination. * */ - validateScope?(user: User, client: Client, scope: string | string[], callback?: Callback): Promise; - + validateScope?(user: User, client: Client, scope: string[]): Promise; + /** * Invoked to check if the provided `redirectUri` is valid for a particular `client`. * @@ -335,19 +328,19 @@ declare namespace OAuth2Server { * Invoked to generate a new refresh token. * */ - generateRefreshToken?(client: Client, user: User, scope: string | string[], callback?: Callback): Promise; + generateRefreshToken?(client: Client, user: User, scope: string[]): Promise; /** * Invoked to retrieve a user using a username/password combination. * */ - getUser(username: string, password: string, callback?: Callback): Promise; + getUser(username: string, password: string, client: Client): Promise; /** * Invoked to check if the requested scope is valid for a particular client/user combination. * */ - validateScope?(user: User, client: Client, scope: string | string[], callback?: Callback): Promise; + validateScope?(user: User, client: Client, scope: string[]): Promise; } interface RefreshTokenModel extends BaseModel, RequestAuthenticationModel { @@ -355,19 +348,19 @@ declare namespace OAuth2Server { * Invoked to generate a new refresh token. * */ - generateRefreshToken?(client: Client, user: User, scope: string | string[], callback?: Callback): Promise; + generateRefreshToken?(client: Client, user: User, scope: string[]): Promise; /** * Invoked to retrieve an existing refresh token previously saved through Model#saveToken(). * */ - getRefreshToken(refreshToken: string, callback?: Callback): Promise; + getRefreshToken(refreshToken: string): Promise; /** * Invoked to revoke a refresh token. * */ - revokeToken(token: RefreshToken | Token, callback?: Callback): Promise; + revokeToken(token: RefreshToken): Promise; } interface ClientCredentialsModel extends BaseModel, RequestAuthenticationModel { @@ -375,13 +368,13 @@ declare namespace OAuth2Server { * Invoked to retrieve the user associated with the specified client. * */ - getUserFromClient(client: Client, callback?: Callback): Promise; + getUserFromClient(client: Client): Promise; /** * Invoked to check if the requested scope is valid for a particular client/user combination. * */ - validateScope?(user: User, client: Client, scope: string | string[], callback?: Callback): Promise; + validateScope?(user: User, client: Client, scope: string[]): Promise; } interface ExtensionModel extends BaseModel, RequestAuthenticationModel {} @@ -413,7 +406,7 @@ declare namespace OAuth2Server { authorizationCode: string; expiresAt: Date; redirectUri: string; - scope?: string | string[] | undefined; + scope?: string[] | undefined; client: Client; user: User; codeChallenge?: string; @@ -429,7 +422,7 @@ declare namespace OAuth2Server { accessTokenExpiresAt?: Date | undefined; refreshToken?: string | undefined; refreshTokenExpiresAt?: Date | undefined; - scope?: string | string[] | undefined; + scope?: string[] | undefined; client: Client; user: User; [key: string]: any; @@ -441,7 +434,7 @@ declare namespace OAuth2Server { interface RefreshToken { refreshToken: string; refreshTokenExpiresAt?: Date | undefined; - scope?: string | string[] | undefined; + scope?: string[] | undefined; client: Client; user: User; [key: string]: any; diff --git a/lib/errors/access-denied-error.js b/lib/errors/access-denied-error.js index ce5c0af4..614235c7 100644 --- a/lib/errors/access-denied-error.js +++ b/lib/errors/access-denied-error.js @@ -5,7 +5,6 @@ */ const OAuthError = require('./oauth-error'); -const util = require('util'); /** * Constructor. @@ -15,21 +14,18 @@ const util = require('util'); * @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 */ -function AccessDeniedError(message, properties) { - properties = Object.assign({ - code: 400, - name: 'access_denied' - }, properties); +class AccessDeniedError extends OAuthError { + constructor(message, properties) { + properties = { + code: 400, + name: 'access_denied', + ...properties + }; - OAuthError.call(this, message, properties); + super(message, properties); + } } -/** - * Inherit prototype. - */ - -util.inherits(AccessDeniedError, OAuthError); - /** * Export constructor. */ diff --git a/lib/errors/insufficient-scope-error.js b/lib/errors/insufficient-scope-error.js index a27ad681..3125c75e 100644 --- a/lib/errors/insufficient-scope-error.js +++ b/lib/errors/insufficient-scope-error.js @@ -5,7 +5,6 @@ */ const OAuthError = require('./oauth-error'); -const util = require('util'); /** * Constructor. @@ -15,21 +14,18 @@ const util = require('util'); * @see https://tools.ietf.org/html/rfc6750.html#section-3.1 */ -function InsufficientScopeError(message, properties) { - properties = Object.assign({ - code: 403, - name: 'insufficient_scope' - }, properties); +class InsufficientScopeError extends OAuthError { + constructor(message, properties) { + properties = { + code: 403, + name: 'insufficient_scope', + ...properties + }; - OAuthError.call(this, message, properties); + super(message, properties); + } } -/** - * Inherit prototype. - */ - -util.inherits(InsufficientScopeError, OAuthError); - /** * Export constructor. */ diff --git a/lib/errors/invalid-argument-error.js b/lib/errors/invalid-argument-error.js index 1958caa7..9c9cfc52 100644 --- a/lib/errors/invalid-argument-error.js +++ b/lib/errors/invalid-argument-error.js @@ -5,27 +5,23 @@ */ const OAuthError = require('./oauth-error'); -const util = require('util'); /** * Constructor. */ -function InvalidArgumentError(message, properties) { - properties = Object.assign({ - code: 500, - name: 'invalid_argument' - }, properties); +class InvalidArgumentError extends OAuthError { + constructor(message, properties) { + properties = { + code: 500, + name: 'invalid_argument', + ...properties + }; - OAuthError.call(this, message, properties); + super(message, properties); + } } -/** - * Inherit prototype. - */ - -util.inherits(InvalidArgumentError, OAuthError); - /** * Export constructor. */ diff --git a/lib/errors/invalid-client-error.js b/lib/errors/invalid-client-error.js index 1513d572..a1874d82 100644 --- a/lib/errors/invalid-client-error.js +++ b/lib/errors/invalid-client-error.js @@ -5,7 +5,6 @@ */ const OAuthError = require('./oauth-error'); -const util = require('util'); /** * Constructor. @@ -16,21 +15,18 @@ const util = require('util'); * @see https://tools.ietf.org/html/rfc6749#section-5.2 */ -function InvalidClientError(message, properties) { - properties = Object.assign({ - code: 400, - name: 'invalid_client' - }, properties); +class InvalidClientError extends OAuthError { + constructor(message, properties) { + properties = { + code: 400, + name: 'invalid_client', + ...properties + }; - OAuthError.call(this, message, properties); + super(message, properties); + } } -/** - * Inherit prototype. - */ - -util.inherits(InvalidClientError, OAuthError); - /** * Export constructor. */ diff --git a/lib/errors/invalid-grant-error.js b/lib/errors/invalid-grant-error.js index 2c6a568a..4beade93 100644 --- a/lib/errors/invalid-grant-error.js +++ b/lib/errors/invalid-grant-error.js @@ -5,7 +5,6 @@ */ const OAuthError = require('./oauth-error'); -const util = require('util'); /** * Constructor. @@ -17,21 +16,18 @@ const util = require('util'); * @see https://tools.ietf.org/html/rfc6749#section-5.2 */ -function InvalidGrantError(message, properties) { - properties = Object.assign({ - code: 400, - name: 'invalid_grant' - }, properties); +class InvalidGrantError extends OAuthError { + constructor(message, properties) { + properties = { + code: 400, + name: 'invalid_grant', + ...properties + }; - OAuthError.call(this, message, properties); + super(message, properties); + } } -/** - * Inherit prototype. - */ - -util.inherits(InvalidGrantError, OAuthError); - /** * Export constructor. */ diff --git a/lib/errors/invalid-request-error.js b/lib/errors/invalid-request-error.js index 56e997ec..0b861019 100644 --- a/lib/errors/invalid-request-error.js +++ b/lib/errors/invalid-request-error.js @@ -5,7 +5,6 @@ */ const OAuthError = require('./oauth-error'); -const util = require('util'); /** * Constructor. @@ -16,21 +15,18 @@ const util = require('util'); * @see https://tools.ietf.org/html/rfc6749#section-4.2.2.1 */ -function InvalidRequest(message, properties) { - properties = Object.assign({ - code: 400, - name: 'invalid_request' - }, properties); +class InvalidRequest extends OAuthError { + constructor(message, properties) { + properties = { + code: 400, + name: 'invalid_request', + ...properties + }; - OAuthError.call(this, message, properties); + super(message, properties); + } } -/** - * Inherit prototype. - */ - -util.inherits(InvalidRequest, OAuthError); - /** * Export constructor. */ diff --git a/lib/errors/invalid-scope-error.js b/lib/errors/invalid-scope-error.js index 2f5746d1..fec5d826 100644 --- a/lib/errors/invalid-scope-error.js +++ b/lib/errors/invalid-scope-error.js @@ -5,7 +5,6 @@ */ const OAuthError = require('./oauth-error'); -const util = require('util'); /** * Constructor. @@ -15,21 +14,18 @@ const util = require('util'); * @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 */ -function InvalidScopeError(message, properties) { - properties = Object.assign({ - code: 400, - name: 'invalid_scope' - }, properties); +class InvalidScopeError extends OAuthError { + constructor(message, properties) { + properties = { + code: 400, + name: 'invalid_scope', + ...properties + }; - OAuthError.call(this, message, properties); + super(message, properties); + } } -/** - * Inherit prototype. - */ - -util.inherits(InvalidScopeError, OAuthError); - /** * Export constructor. */ diff --git a/lib/errors/invalid-token-error.js b/lib/errors/invalid-token-error.js index e79d9261..481717be 100644 --- a/lib/errors/invalid-token-error.js +++ b/lib/errors/invalid-token-error.js @@ -5,7 +5,6 @@ */ const OAuthError = require('./oauth-error'); -const util = require('util'); /** * Constructor. @@ -15,21 +14,18 @@ const util = require('util'); * @see https://tools.ietf.org/html/rfc6750#section-3.1 */ -function InvalidTokenError(message, properties) { - properties = Object.assign({ - code: 401, - name: 'invalid_token' - }, properties); +class InvalidTokenError extends OAuthError { + constructor(message, properties) { + properties = { + code: 401, + name: 'invalid_token', + ...properties + }; - OAuthError.call(this, message, properties); + super(message, properties); + } } -/** - * Inherit prototype. - */ - -util.inherits(InvalidTokenError, OAuthError); - /** * Export constructor. */ diff --git a/lib/errors/oauth-error.js b/lib/errors/oauth-error.js index a96a41fe..fff9660f 100644 --- a/lib/errors/oauth-error.js +++ b/lib/errors/oauth-error.js @@ -3,39 +3,43 @@ /** * Module dependencies. */ -const util = require('util'); const http = require('http'); /** * Constructor. */ -function OAuthError(messageOrError, properties) { - let message = messageOrError instanceof Error ? messageOrError.message : messageOrError; - const error = messageOrError instanceof Error ? messageOrError : null; - if (properties == null || !Object.entries(properties).length ) { - properties = {}; - } +class OAuthError extends Error { + constructor(messageOrError, properties) { + super(messageOrError, properties); - properties = Object.assign({ code: 500 }, properties); + let message = messageOrError instanceof Error ? messageOrError.message : messageOrError; + const error = messageOrError instanceof Error ? messageOrError : null; - if (error) { - properties.inner = error; - } - if (!message || message.length === 0) { - message = http.STATUS_CODES[properties.code]; - } - this.code = this.status = this.statusCode = properties.code; - this.message = message; - for (const key in properties) { - if (key !== 'code') { - this[key] = properties[key]; + if (properties == null || !Object.entries(properties).length) { + properties = {}; + } + + properties = { code: 500, ...properties }; + + if (error) { + properties.inner = error; + } + + if (!message || message.length === 0) { + message = http.STATUS_CODES[properties.code]; + } + + this.code = this.status = this.statusCode = properties.code; + this.message = message; + + for (const key in properties) { + if (key !== 'code') { + this[key] = properties[key]; + } } } - Error.captureStackTrace(this, OAuthError); } -util.inherits(OAuthError, Error); - /** * Export constructor. */ diff --git a/lib/errors/server-error.js b/lib/errors/server-error.js index aee958b7..2b9fc8c7 100644 --- a/lib/errors/server-error.js +++ b/lib/errors/server-error.js @@ -5,7 +5,6 @@ */ const OAuthError = require('./oauth-error'); -const util = require('util'); /** * Constructor. @@ -15,21 +14,18 @@ const util = require('util'); * @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 */ -function ServerError(message, properties) { - properties = Object.assign({ - code: 503, - name: 'server_error' - }, properties); +class ServerError extends OAuthError { + constructor(message, properties) { + properties = { + code: 503, + name: 'server_error', + ...properties + }; - OAuthError.call(this, message, properties); + super(message, properties); + } } -/** - * Inherit prototype. - */ - -util.inherits(ServerError, OAuthError); - /** * Export constructor. */ diff --git a/lib/errors/unauthorized-client-error.js b/lib/errors/unauthorized-client-error.js index fde3cb5c..cf29c7c9 100644 --- a/lib/errors/unauthorized-client-error.js +++ b/lib/errors/unauthorized-client-error.js @@ -5,7 +5,6 @@ */ const OAuthError = require('./oauth-error'); -const util = require('util'); /** * Constructor. @@ -15,21 +14,18 @@ const util = require('util'); * @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 */ -function UnauthorizedClientError(message, properties) { - properties = Object.assign({ - code: 400, - name: 'unauthorized_client' - }, properties); +class UnauthorizedClientError extends OAuthError { + constructor(message, properties) { + properties = { + code: 400, + name: 'unauthorized_client', + ...properties + }; - OAuthError.call(this, message, properties); + super(message, properties); + } } -/** - * Inherit prototype. - */ - -util.inherits(UnauthorizedClientError, OAuthError); - /** * Export constructor. */ diff --git a/lib/errors/unauthorized-request-error.js b/lib/errors/unauthorized-request-error.js index e9604896..c861eab1 100644 --- a/lib/errors/unauthorized-request-error.js +++ b/lib/errors/unauthorized-request-error.js @@ -5,7 +5,6 @@ */ const OAuthError = require('./oauth-error'); -const util = require('util'); /** * Constructor. @@ -18,21 +17,18 @@ const util = require('util'); * @see https://tools.ietf.org/html/rfc6750#section-3.1 */ -function UnauthorizedRequestError(message, properties) { - properties = Object.assign({ - code: 401, - name: 'unauthorized_request' - }, properties); +class UnauthorizedRequestError extends OAuthError { + constructor(message, properties) { + properties = { + code: 401, + name: 'unauthorized_request', + ...properties + }; - OAuthError.call(this, message, properties); + super(message, properties); + } } -/** - * Inherit prototype. - */ - -util.inherits(UnauthorizedRequestError, OAuthError); - /** * Export constructor. */ diff --git a/lib/errors/unsupported-grant-type-error.js b/lib/errors/unsupported-grant-type-error.js index 586a743b..ac7a46c2 100644 --- a/lib/errors/unsupported-grant-type-error.js +++ b/lib/errors/unsupported-grant-type-error.js @@ -5,7 +5,6 @@ */ const OAuthError = require('./oauth-error'); -const util = require('util'); /** * Constructor. @@ -15,21 +14,18 @@ const util = require('util'); * @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 */ -function UnsupportedGrantTypeError(message, properties) { - properties = Object.assign({ - code: 400, - name: 'unsupported_grant_type' - }, properties); +class UnsupportedGrantTypeError extends OAuthError { + constructor(message, properties) { + properties = { + code: 400, + name: 'unsupported_grant_type', + ...properties + }; - OAuthError.call(this, message, properties); + super(message, properties); + } } -/** - * Inherit prototype. - */ - -util.inherits(UnsupportedGrantTypeError, OAuthError); - /** * Export constructor. */ diff --git a/lib/errors/unsupported-response-type-error.js b/lib/errors/unsupported-response-type-error.js index 539551ec..c480e50e 100644 --- a/lib/errors/unsupported-response-type-error.js +++ b/lib/errors/unsupported-response-type-error.js @@ -5,7 +5,6 @@ */ const OAuthError = require('./oauth-error'); -const util = require('util'); /** * Constructor. @@ -16,21 +15,18 @@ const util = require('util'); * @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 */ -function UnsupportedResponseTypeError(message, properties) { - properties = Object.assign({ - code: 400, - name: 'unsupported_response_type' - }, properties); +class UnsupportedResponseTypeError extends OAuthError { + constructor(message, properties) { + properties = { + code: 400, + name: 'unsupported_response_type', + ...properties + }; - OAuthError.call(this, message, properties); + super(message, properties); + } } -/** - * Inherit prototype. - */ - -util.inherits(UnsupportedResponseTypeError, OAuthError); - /** * Export constructor. */ diff --git a/lib/grant-types/abstract-grant-type.js b/lib/grant-types/abstract-grant-type.js index c09e6fb2..bce24ed8 100644 --- a/lib/grant-types/abstract-grant-type.js +++ b/lib/grant-types/abstract-grant-type.js @@ -6,107 +6,93 @@ const InvalidArgumentError = require('../errors/invalid-argument-error'); const InvalidScopeError = require('../errors/invalid-scope-error'); -const Promise = require('bluebird'); -const promisify = require('promisify-any').use(Promise); -const isFormat = require('@node-oauth/formats'); const tokenUtil = require('../utils/token-util'); +const { parseScope } = require('../utils/scope-util'); -/** - * Constructor. - */ +class AbstractGrantType { + constructor (options) { + options = options || {}; -function AbstractGrantType(options) { - options = options || {}; + if (!options.accessTokenLifetime) { + throw new InvalidArgumentError('Missing parameter: `accessTokenLifetime`'); + } - if (!options.accessTokenLifetime) { - throw new InvalidArgumentError('Missing parameter: `accessTokenLifetime`'); - } + if (!options.model) { + throw new InvalidArgumentError('Missing parameter: `model`'); + } - if (!options.model) { - throw new InvalidArgumentError('Missing parameter: `model`'); + this.accessTokenLifetime = options.accessTokenLifetime; + this.model = options.model; + this.refreshTokenLifetime = options.refreshTokenLifetime; + this.alwaysIssueNewRefreshToken = options.alwaysIssueNewRefreshToken; } - this.accessTokenLifetime = options.accessTokenLifetime; - this.model = options.model; - this.refreshTokenLifetime = options.refreshTokenLifetime; - this.alwaysIssueNewRefreshToken = options.alwaysIssueNewRefreshToken; -} - -/** - * Generate access token. - */ - -AbstractGrantType.prototype.generateAccessToken = function(client, user, scope) { - if (this.model.generateAccessToken) { - return promisify(this.model.generateAccessToken, 3).call(this.model, client, user, scope) - .then(function(accessToken) { - return accessToken || tokenUtil.generateRandomToken(); - }); + /** + * Generate access token. + */ + async generateAccessToken (client, user, scope) { + if (this.model.generateAccessToken) { + // We should not fall back to a random accessToken, if the model did not + // return a token, in order to prevent unintended token-issuing. + return this.model.generateAccessToken(client, user, scope); + } + + return tokenUtil.generateRandomToken(); } - return tokenUtil.generateRandomToken(); -}; - -/** + /** * Generate refresh token. */ - -AbstractGrantType.prototype.generateRefreshToken = function(client, user, scope) { - if (this.model.generateRefreshToken) { - return promisify(this.model.generateRefreshToken, 3).call(this.model, client, user, scope) - .then(function(refreshToken) { - return refreshToken || tokenUtil.generateRandomToken(); - }); + async generateRefreshToken (client, user, scope) { + if (this.model.generateRefreshToken) { + // We should not fall back to a random refreshToken, if the model did not + // return a token, in order to prevent unintended token-issuing. + return this.model.generateRefreshToken(client, user, scope); + } + + return tokenUtil.generateRandomToken(); } - return tokenUtil.generateRandomToken(); -}; - -/** + /** * Get access token expiration date. */ + getAccessTokenExpiresAt() { + return new Date(Date.now() + this.accessTokenLifetime * 1000); + } -AbstractGrantType.prototype.getAccessTokenExpiresAt = function() { - return new Date(Date.now() + this.accessTokenLifetime * 1000); -}; - -/** - * Get refresh token expiration date. - */ - -AbstractGrantType.prototype.getRefreshTokenExpiresAt = function() { - return new Date(Date.now() + this.refreshTokenLifetime * 1000); -}; -/** - * Get scope from the request body. - */ -AbstractGrantType.prototype.getScope = function(request) { - if (!isFormat.nqschar(request.body.scope)) { - throw new InvalidArgumentError('Invalid parameter: `scope`'); + /** + * Get refresh token expiration date. + */ + getRefreshTokenExpiresAt () { + return new Date(Date.now() + this.refreshTokenLifetime * 1000); } - return request.body.scope; -}; + /** + * Get scope from the request body. + */ + getScope (request) { + return parseScope(request.body.scope); + } -/** - * Validate requested scope. - */ -AbstractGrantType.prototype.validateScope = function(user, client, requestedScoped) { - if (this.model.validateScope) { - return promisify(this.model.validateScope, 3).call(this.model, user, client, requestedScoped) - .then(function (validatedScope) { - if (!validatedScope) { - throw new InvalidScopeError('Invalid scope: Requested scope is invalid'); - } - - return validatedScope; - }); - } else { - return requestedScoped; + /** + * Validate requested scope. + */ + async validateScope (user, client, scope) { + if (this.model.validateScope) { + const validatedScope = await this.model.validateScope(user, client, scope); + + if (!validatedScope) { + throw new InvalidScopeError('Invalid scope: Requested scope is invalid'); + } + + return validatedScope; + } else { + return scope; + } } -}; +} /** * Export constructor. diff --git a/lib/grant-types/authorization-code-grant-type.js b/lib/grant-types/authorization-code-grant-type.js index 802e45a7..766b947c 100644 --- a/lib/grant-types/authorization-code-grant-type.js +++ b/lib/grant-types/authorization-code-grant-type.js @@ -8,230 +8,204 @@ const AbstractGrantType = require('./abstract-grant-type'); const InvalidArgumentError = require('../errors/invalid-argument-error'); const InvalidGrantError = require('../errors/invalid-grant-error'); const InvalidRequestError = require('../errors/invalid-request-error'); -const Promise = require('bluebird'); -const promisify = require('promisify-any').use(Promise); const ServerError = require('../errors/server-error'); const isFormat = require('@node-oauth/formats'); -const util = require('util'); const pkce = require('../pkce/pkce'); /** * Constructor. */ -function AuthorizationCodeGrantType(options) { - options = options || {}; +class AuthorizationCodeGrantType extends AbstractGrantType { + constructor(options = {}) { + if (!options.model) { + throw new InvalidArgumentError('Missing parameter: `model`'); + } - if (!options.model) { - throw new InvalidArgumentError('Missing parameter: `model`'); - } + if (!options.model.getAuthorizationCode) { + throw new InvalidArgumentError('Invalid argument: model does not implement `getAuthorizationCode()`'); + } - if (!options.model.getAuthorizationCode) { - throw new InvalidArgumentError('Invalid argument: model does not implement `getAuthorizationCode()`'); - } + if (!options.model.revokeAuthorizationCode) { + throw new InvalidArgumentError('Invalid argument: model does not implement `revokeAuthorizationCode()`'); + } - if (!options.model.revokeAuthorizationCode) { - throw new InvalidArgumentError('Invalid argument: model does not implement `revokeAuthorizationCode()`'); - } + if (!options.model.saveToken) { + throw new InvalidArgumentError('Invalid argument: model does not implement `saveToken()`'); + } - if (!options.model.saveToken) { - throw new InvalidArgumentError('Invalid argument: model does not implement `saveToken()`'); + super(options); } - AbstractGrantType.call(this, options); -} + /** + * Handle authorization code grant. + * + * @see https://tools.ietf.org/html/rfc6749#section-4.1.3 + */ -/** - * Inherit prototype. - */ + async handle(request, client) { + if (!request) { + throw new InvalidArgumentError('Missing parameter: `request`'); + } -util.inherits(AuthorizationCodeGrantType, AbstractGrantType); + if (!client) { + throw new InvalidArgumentError('Missing parameter: `client`'); + } -/** - * Handle authorization code grant. - * - * @see https://tools.ietf.org/html/rfc6749#section-4.1.3 - */ + const code = await this.getAuthorizationCode(request, client); + await this.revokeAuthorizationCode(code); + await this.validateRedirectUri(request, code); -AuthorizationCodeGrantType.prototype.handle = function(request, client) { - if (!request) { - throw new InvalidArgumentError('Missing parameter: `request`'); + return this.saveToken(code.user, client, code.authorizationCode, code.scope); } - if (!client) { - throw new InvalidArgumentError('Missing parameter: `client`'); - } + /** + * Get the authorization code. + */ - return Promise.bind(this) - .then(function() { - return this.getAuthorizationCode(request, client); - }) - .tap(function(code) { - return this.revokeAuthorizationCode(code); - }) - .tap(function(code) { - return this.validateRedirectUri(request, code); - }) - .then(function(code) { - return this.saveToken(code.user, client, code.authorizationCode, code.scope); - }); -}; + async getAuthorizationCode(request, client) { + if (!request.body.code) { + throw new InvalidRequestError('Missing parameter: `code`'); + } -/** - * Get the authorization code. - */ + if (!isFormat.vschar(request.body.code)) { + throw new InvalidRequestError('Invalid parameter: `code`'); + } -AuthorizationCodeGrantType.prototype.getAuthorizationCode = function(request, client) { - if (!request.body.code) { - throw new InvalidRequestError('Missing parameter: `code`'); - } + const code = await this.model.getAuthorizationCode(request.body.code); - if (!isFormat.vschar(request.body.code)) { - throw new InvalidRequestError('Invalid parameter: `code`'); - } - return promisify(this.model.getAuthorizationCode, 1).call(this.model, request.body.code) - .then(function(code) { - if (!code) { - throw new InvalidGrantError('Invalid grant: authorization code is invalid'); - } + if (!code) { + throw new InvalidGrantError('Invalid grant: authorization code is invalid'); + } - if (!code.client) { - throw new ServerError('Server error: `getAuthorizationCode()` did not return a `client` object'); - } + if (!code.client) { + throw new ServerError('Server error: `getAuthorizationCode()` did not return a `client` object'); + } - if (!code.user) { - throw new ServerError('Server error: `getAuthorizationCode()` did not return a `user` object'); - } + if (!code.user) { + throw new ServerError('Server error: `getAuthorizationCode()` did not return a `user` object'); + } - if (code.client.id !== client.id) { - throw new InvalidGrantError('Invalid grant: authorization code is invalid'); - } + if (code.client.id !== client.id) { + throw new InvalidGrantError('Invalid grant: authorization code is invalid'); + } - if (!(code.expiresAt instanceof Date)) { - throw new ServerError('Server error: `expiresAt` must be a Date instance'); - } + if (!(code.expiresAt instanceof Date)) { + throw new ServerError('Server error: `expiresAt` must be a Date instance'); + } - if (code.expiresAt < new Date()) { - throw new InvalidGrantError('Invalid grant: authorization code has expired'); - } + if (code.expiresAt < new Date()) { + throw new InvalidGrantError('Invalid grant: authorization code has expired'); + } - if (code.redirectUri && !isFormat.uri(code.redirectUri)) { - throw new InvalidGrantError('Invalid grant: `redirect_uri` is not a valid URI'); - } + if (code.redirectUri && !isFormat.uri(code.redirectUri)) { + throw new InvalidGrantError('Invalid grant: `redirect_uri` is not a valid URI'); + } - // optional: PKCE code challenge + // optional: PKCE code challenge - if (code.codeChallenge) { - if (!request.body.code_verifier) { - throw new InvalidGrantError('Missing parameter: `code_verifier`'); - } + if (code.codeChallenge) { + if (!request.body.code_verifier) { + throw new InvalidGrantError('Missing parameter: `code_verifier`'); + } - const hash = pkce.getHashForCodeChallenge({ - method: code.codeChallengeMethod, - verifier: request.body.code_verifier - }); + const hash = pkce.getHashForCodeChallenge({ + method: code.codeChallengeMethod, + verifier: request.body.code_verifier + }); - if (!hash) { - // notice that we assume that codeChallengeMethod is already - // checked at an earlier stage when being read from - // request.body.code_challenge_method - throw new ServerError('Server error: `getAuthorizationCode()` did not return a valid `codeChallengeMethod` property'); - } + if (!hash) { + // notice that we assume that codeChallengeMethod is already + // checked at an earlier stage when being read from + // request.body.code_challenge_method + throw new ServerError('Server error: `getAuthorizationCode()` did not return a valid `codeChallengeMethod` property'); + } - if (code.codeChallenge !== hash) { - throw new InvalidGrantError('Invalid grant: code verifier is invalid'); - } + if (code.codeChallenge !== hash) { + throw new InvalidGrantError('Invalid grant: code verifier is invalid'); } - else { - if (request.body.code_verifier) { - // No code challenge but code_verifier was passed in. - throw new InvalidGrantError('Invalid grant: code verifier is invalid'); - } + } + else { + if (request.body.code_verifier) { + // No code challenge but code_verifier was passed in. + throw new InvalidGrantError('Invalid grant: code verifier is invalid'); } + } - return code; - }); -}; - -/** - * Validate the redirect URI. - * - * "The authorization server MUST ensure that the redirect_uri parameter is - * present if the redirect_uri parameter was included in the initial - * authorization request as described in Section 4.1.1, and if included - * ensure that their values are identical." - * - * @see https://tools.ietf.org/html/rfc6749#section-4.1.3 - */ + return code; + } -AuthorizationCodeGrantType.prototype.validateRedirectUri = function(request, code) { - if (!code.redirectUri) { - return; + /** + * Validate the redirect URI. + * + * "The authorization server MUST ensure that the redirect_uri parameter is + * present if the redirect_uri parameter was included in the initial + * authorization request as described in Section 4.1.1, and if included + * ensure that their values are identical." + * + * @see https://tools.ietf.org/html/rfc6749#section-4.1.3 + */ + + validateRedirectUri(request, code) { + if (!code.redirectUri) { + return; + } + + const redirectUri = request.body.redirect_uri || request.query.redirect_uri; + + if (!isFormat.uri(redirectUri)) { + throw new InvalidRequestError('Invalid request: `redirect_uri` is not a valid URI'); + } + + if (redirectUri !== code.redirectUri) { + throw new InvalidRequestError('Invalid request: `redirect_uri` is invalid'); + } } - const redirectUri = request.body.redirect_uri || request.query.redirect_uri; + /** + * Revoke the authorization code. + * + * "The authorization code MUST expire shortly after it is issued to mitigate + * the risk of leaks. [...] If an authorization code is used more than once, + * the authorization server MUST deny the request." + * + * @see https://tools.ietf.org/html/rfc6749#section-4.1.2 + */ - if (!isFormat.uri(redirectUri)) { - throw new InvalidRequestError('Invalid request: `redirect_uri` is not a valid URI'); - } + async revokeAuthorizationCode(code) { + const status = await this.model.revokeAuthorizationCode(code); - if (redirectUri !== code.redirectUri) { - throw new InvalidRequestError('Invalid request: `redirect_uri` is invalid'); + if (!status) { + throw new InvalidGrantError('Invalid grant: authorization code is invalid'); + } + + return code; } -}; -/** - * Revoke the authorization code. - * - * "The authorization code MUST expire shortly after it is issued to mitigate - * the risk of leaks. [...] If an authorization code is used more than once, - * the authorization server MUST deny the request." - * - * @see https://tools.ietf.org/html/rfc6749#section-4.1.2 - */ -AuthorizationCodeGrantType.prototype.revokeAuthorizationCode = function(code) { - return promisify(this.model.revokeAuthorizationCode, 1).call(this.model, code) - .then(function(status) { - if (!status) { - throw new InvalidGrantError('Invalid grant: authorization code is invalid'); - } + /** + * Save token. + */ - return code; - }); -}; + async saveToken(user, client, authorizationCode, requestedScope) { + const validatedScope = await this.validateScope(user, client, requestedScope); + const accessToken = await this.generateAccessToken(client, user, validatedScope); + const refreshToken = await this.generateRefreshToken(client, user, validatedScope); + const accessTokenExpiresAt = await this.getAccessTokenExpiresAt(); + const refreshTokenExpiresAt = await this.getRefreshTokenExpiresAt(); -/** - * Save token. - */ + const token = { + accessToken, + authorizationCode, + accessTokenExpiresAt, + refreshToken, + refreshTokenExpiresAt, + scope: validatedScope, + }; -AuthorizationCodeGrantType.prototype.saveToken = function(user, client, authorizationCode, requestedScope) { - return Promise.bind(this) - .then(function() { - return this.validateScope(user, client, requestedScope); - }) - .then(function(validatedScoped) { - return Promise.all([ - this.generateAccessToken(client, user, validatedScoped), - this.generateRefreshToken(client, user, validatedScoped), - this.getAccessTokenExpiresAt(), - this.getRefreshTokenExpiresAt() - ]) - .bind(this) - .spread(function(accessToken, refreshToken, accessTokenExpiresAt, refreshTokenExpiresAt) { - const token = { - accessToken: accessToken, - authorizationCode: authorizationCode, - accessTokenExpiresAt: accessTokenExpiresAt, - refreshToken: refreshToken, - refreshTokenExpiresAt: refreshTokenExpiresAt, - scope: validatedScoped - }; - - return promisify(this.model.saveToken, 3).call(this.model, token, client, user); - }); - }); -}; + return this.model.saveToken(token, client, user); + } +} /** * Export constructor. diff --git a/lib/grant-types/client-credentials-grant-type.js b/lib/grant-types/client-credentials-grant-type.js index 57e2a0e7..fa5cd27a 100644 --- a/lib/grant-types/client-credentials-grant-type.js +++ b/lib/grant-types/client-credentials-grant-type.js @@ -7,105 +7,80 @@ const AbstractGrantType = require('./abstract-grant-type'); const InvalidArgumentError = require('../errors/invalid-argument-error'); const InvalidGrantError = require('../errors/invalid-grant-error'); -const Promise = require('bluebird'); -const promisify = require('promisify-any').use(Promise); -const util = require('util'); /** * Constructor. */ -function ClientCredentialsGrantType(options) { - options = options || {}; +class ClientCredentialsGrantType extends AbstractGrantType { + constructor(options = {}) { + if (!options.model) { + throw new InvalidArgumentError('Missing parameter: `model`'); + } - if (!options.model) { - throw new InvalidArgumentError('Missing parameter: `model`'); - } + if (!options.model.getUserFromClient) { + throw new InvalidArgumentError('Invalid argument: model does not implement `getUserFromClient()`'); + } - if (!options.model.getUserFromClient) { - throw new InvalidArgumentError('Invalid argument: model does not implement `getUserFromClient()`'); - } + if (!options.model.saveToken) { + throw new InvalidArgumentError('Invalid argument: model does not implement `saveToken()`'); + } - if (!options.model.saveToken) { - throw new InvalidArgumentError('Invalid argument: model does not implement `saveToken()`'); + super(options); } - AbstractGrantType.call(this, options); -} + /** + * Handle client credentials grant. + * + * @see https://tools.ietf.org/html/rfc6749#section-4.4.2 + */ -/** - * Inherit prototype. - */ + async handle(request, client) { + if (!request) { + throw new InvalidArgumentError('Missing parameter: `request`'); + } -util.inherits(ClientCredentialsGrantType, AbstractGrantType); + if (!client) { + throw new InvalidArgumentError('Missing parameter: `client`'); + } -/** - * Handle client credentials grant. - * - * @see https://tools.ietf.org/html/rfc6749#section-4.4.2 - */ - -ClientCredentialsGrantType.prototype.handle = function(request, client) { - if (!request) { - throw new InvalidArgumentError('Missing parameter: `request`'); - } + const scope = this.getScope(request); + const user = await this.getUserFromClient(client); - if (!client) { - throw new InvalidArgumentError('Missing parameter: `client`'); + return this.saveToken(user, client, scope); } - const scope = this.getScope(request); + /** + * Retrieve the user using client credentials. + */ - return Promise.bind(this) - .then(function() { - return this.getUserFromClient(client); - }) - .then(function(user) { - return this.saveToken(user, client, scope); - }); -}; + async getUserFromClient(client) { + const user = await this.model.getUserFromClient(client); -/** - * Retrieve the user using client credentials. - */ - -ClientCredentialsGrantType.prototype.getUserFromClient = function(client) { - return promisify(this.model.getUserFromClient, 1).call(this.model, client) - .then(function(user) { - if (!user) { - throw new InvalidGrantError('Invalid grant: user credentials are invalid'); - } + if (!user) { + throw new InvalidGrantError('Invalid grant: user credentials are invalid'); + } - return user; - }); -}; - -/** - * Save token. - */ + return user; + } -ClientCredentialsGrantType.prototype.saveToken = function(user, client, requestedScope) { - return Promise.bind(this) - .then(function() { - return this.validateScope(user, client, requestedScope); - }) - .then(function(validatedScope) { - return Promise.all([ - this.generateAccessToken(client, user, validatedScope), - this.getAccessTokenExpiresAt(client, user, validatedScope) - ]) - .bind(this) - .spread(function(accessToken, accessTokenExpiresAt) { - const token = { - accessToken: accessToken, - accessTokenExpiresAt: accessTokenExpiresAt, - scope: validatedScope - }; - - return promisify(this.model.saveToken, 3).call(this.model, token, client, user); - }); - }); -}; + /** + * Save token. + */ + + async saveToken(user, client, requestedScope) { + const validatedScope = await this.validateScope(user, client, requestedScope); + const accessToken = await this.generateAccessToken(client, user, validatedScope); + const accessTokenExpiresAt = await this.getAccessTokenExpiresAt(client, user, validatedScope); + const token = { + accessToken, + accessTokenExpiresAt, + scope: validatedScope, + }; + + return this.model.saveToken(token, client, user); + } +} /** * Export constructor. diff --git a/lib/grant-types/password-grant-type.js b/lib/grant-types/password-grant-type.js index dc3462f2..b09e4993 100644 --- a/lib/grant-types/password-grant-type.js +++ b/lib/grant-types/password-grant-type.js @@ -8,126 +8,102 @@ const AbstractGrantType = require('./abstract-grant-type'); const InvalidArgumentError = require('../errors/invalid-argument-error'); const InvalidGrantError = require('../errors/invalid-grant-error'); const InvalidRequestError = require('../errors/invalid-request-error'); -const Promise = require('bluebird'); -const promisify = require('promisify-any').use(Promise); const isFormat = require('@node-oauth/formats'); -const util = require('util'); /** * Constructor. */ -function PasswordGrantType(options) { - options = options || {}; +class PasswordGrantType extends AbstractGrantType { + constructor(options = {}) { + if (!options.model) { + throw new InvalidArgumentError('Missing parameter: `model`'); + } - if (!options.model) { - throw new InvalidArgumentError('Missing parameter: `model`'); - } + if (!options.model.getUser) { + throw new InvalidArgumentError('Invalid argument: model does not implement `getUser()`'); + } - if (!options.model.getUser) { - throw new InvalidArgumentError('Invalid argument: model does not implement `getUser()`'); - } + if (!options.model.saveToken) { + throw new InvalidArgumentError('Invalid argument: model does not implement `saveToken()`'); + } - if (!options.model.saveToken) { - throw new InvalidArgumentError('Invalid argument: model does not implement `saveToken()`'); + super(options); } - AbstractGrantType.call(this, options); -} + /** + * Retrieve the user from the model using a username/password combination. + * + * @see https://tools.ietf.org/html/rfc6749#section-4.3.2 + */ -/** - * Inherit prototype. - */ + async handle(request, client) { + if (!request) { + throw new InvalidArgumentError('Missing parameter: `request`'); + } -util.inherits(PasswordGrantType, AbstractGrantType); + if (!client) { + throw new InvalidArgumentError('Missing parameter: `client`'); + } -/** - * Retrieve the user from the model using a username/password combination. - * - * @see https://tools.ietf.org/html/rfc6749#section-4.3.2 - */ + const scope = this.getScope(request); + const user = await this.getUser(request, client); -PasswordGrantType.prototype.handle = function(request, client) { - if (!request) { - throw new InvalidArgumentError('Missing parameter: `request`'); + return this.saveToken(user, client, scope); } - if (!client) { - throw new InvalidArgumentError('Missing parameter: `client`'); - } + /** + * Get user using a username/password combination. + */ - const scope = this.getScope(request); + async getUser(request, client) { + if (!request.body.username) { + throw new InvalidRequestError('Missing parameter: `username`'); + } - return Promise.bind(this) - .then(function() { - return this.getUser(request); - }) - .then(function(user) { - return this.saveToken(user, client, scope); - }); -}; + if (!request.body.password) { + throw new InvalidRequestError('Missing parameter: `password`'); + } -/** - * Get user using a username/password combination. - */ + if (!isFormat.uchar(request.body.username)) { + throw new InvalidRequestError('Invalid parameter: `username`'); + } -PasswordGrantType.prototype.getUser = function(request) { - if (!request.body.username) { - throw new InvalidRequestError('Missing parameter: `username`'); - } + if (!isFormat.uchar(request.body.password)) { + throw new InvalidRequestError('Invalid parameter: `password`'); + } - if (!request.body.password) { - throw new InvalidRequestError('Missing parameter: `password`'); - } + const user = await this.model.getUser(request.body.username, request.body.password, client); - if (!isFormat.uchar(request.body.username)) { - throw new InvalidRequestError('Invalid parameter: `username`'); - } + if (!user) { + throw new InvalidGrantError('Invalid grant: user credentials are invalid'); + } - if (!isFormat.uchar(request.body.password)) { - throw new InvalidRequestError('Invalid parameter: `password`'); + return user; } - return promisify(this.model.getUser, 2).call(this.model, request.body.username, request.body.password) - .then(function(user) { - if (!user) { - throw new InvalidGrantError('Invalid grant: user credentials are invalid'); - } - - return user; - }); -}; - -/** - * Save token. - */ - -PasswordGrantType.prototype.saveToken = function(user, client, requestedScope) { - return Promise.bind(this) - .then(function () { - return this.validateScope(user, client,requestedScope); - }) - .then(function(validatedScope) { - return Promise.all([ - this.generateAccessToken(client, user, validatedScope), - this.generateRefreshToken(client, user, validatedScope), - this.getAccessTokenExpiresAt(), - this.getRefreshTokenExpiresAt() - ]) - .bind(this) - .spread(function(accessToken, refreshToken, accessTokenExpiresAt, refreshTokenExpiresAt) { - const token = { - accessToken: accessToken, - accessTokenExpiresAt: accessTokenExpiresAt, - refreshToken: refreshToken, - refreshTokenExpiresAt: refreshTokenExpiresAt, - scope: validatedScope - }; - - return promisify(this.model.saveToken, 3).call(this.model, token, client, user); - }); - }); -}; + /** + * Save token. + */ + + async saveToken(user, client, requestedScope) { + const validatedScope = await this.validateScope(user, client, requestedScope); + const accessToken = await this.generateAccessToken(client, user, validatedScope); + const refreshToken = await this.generateRefreshToken(client, user, validatedScope); + const accessTokenExpiresAt = await this.getAccessTokenExpiresAt(); + const refreshTokenExpiresAt = await this.getRefreshTokenExpiresAt(); + + const token = { + accessToken, + accessTokenExpiresAt, + refreshToken, + refreshTokenExpiresAt, + scope: validatedScope, + }; + + return this.model.saveToken(token, client, user); + } +} /** * Export constructor. diff --git a/lib/grant-types/refresh-token-grant-type.js b/lib/grant-types/refresh-token-grant-type.js index 9787b084..45237dbc 100644 --- a/lib/grant-types/refresh-token-grant-type.js +++ b/lib/grant-types/refresh-token-grant-type.js @@ -8,170 +8,171 @@ const AbstractGrantType = require('./abstract-grant-type'); const InvalidArgumentError = require('../errors/invalid-argument-error'); const InvalidGrantError = require('../errors/invalid-grant-error'); const InvalidRequestError = require('../errors/invalid-request-error'); -const Promise = require('bluebird'); -const promisify = require('promisify-any').use(Promise); const ServerError = require('../errors/server-error'); const isFormat = require('@node-oauth/formats'); -const util = require('util'); +const InvalidScopeError = require('../errors/invalid-scope-error'); /** * Constructor. */ -function RefreshTokenGrantType(options) { - options = options || {}; +class RefreshTokenGrantType extends AbstractGrantType { + constructor(options = {}) { + if (!options.model) { + throw new InvalidArgumentError('Missing parameter: `model`'); + } - if (!options.model) { - throw new InvalidArgumentError('Missing parameter: `model`'); - } + if (!options.model.getRefreshToken) { + throw new InvalidArgumentError('Invalid argument: model does not implement `getRefreshToken()`'); + } - if (!options.model.getRefreshToken) { - throw new InvalidArgumentError('Invalid argument: model does not implement `getRefreshToken()`'); - } + if (!options.model.revokeToken) { + throw new InvalidArgumentError('Invalid argument: model does not implement `revokeToken()`'); + } - if (!options.model.revokeToken) { - throw new InvalidArgumentError('Invalid argument: model does not implement `revokeToken()`'); - } + if (!options.model.saveToken) { + throw new InvalidArgumentError('Invalid argument: model does not implement `saveToken()`'); + } - if (!options.model.saveToken) { - throw new InvalidArgumentError('Invalid argument: model does not implement `saveToken()`'); + super(options); } - AbstractGrantType.call(this, options); -} + /** + * Handle refresh token grant. + * + * @see https://tools.ietf.org/html/rfc6749#section-6 + */ -/** - * Inherit prototype. - */ + async handle(request, client) { + if (!request) { + throw new InvalidArgumentError('Missing parameter: `request`'); + } -util.inherits(RefreshTokenGrantType, AbstractGrantType); + if (!client) { + throw new InvalidArgumentError('Missing parameter: `client`'); + } -/** - * Handle refresh token grant. - * - * @see https://tools.ietf.org/html/rfc6749#section-6 - */ + let token; + token = await this.getRefreshToken(request, client); + token = await this.revokeToken(token); -RefreshTokenGrantType.prototype.handle = function(request, client) { - if (!request) { - throw new InvalidArgumentError('Missing parameter: `request`'); - } + const scope = this.getScope(request, token); - if (!client) { - throw new InvalidArgumentError('Missing parameter: `client`'); + return this.saveToken(token.user, client, scope); } - return Promise.bind(this) - .then(function() { - return this.getRefreshToken(request, client); - }) - .tap(function(token) { - return this.revokeToken(token); - }) - .then(function(token) { - return this.saveToken(token.user, client, token.scope); - }); -}; + /** + * Get refresh token. + */ -/** - * Get refresh token. - */ + async getRefreshToken(request, client) { + if (!request.body.refresh_token) { + throw new InvalidRequestError('Missing parameter: `refresh_token`'); + } -RefreshTokenGrantType.prototype.getRefreshToken = function(request, client) { - if (!request.body.refresh_token) { - throw new InvalidRequestError('Missing parameter: `refresh_token`'); - } + if (!isFormat.vschar(request.body.refresh_token)) { + throw new InvalidRequestError('Invalid parameter: `refresh_token`'); + } - if (!isFormat.vschar(request.body.refresh_token)) { - throw new InvalidRequestError('Invalid parameter: `refresh_token`'); - } + const token = await this.model.getRefreshToken(request.body.refresh_token); + + if (!token) { + throw new InvalidGrantError('Invalid grant: refresh token is invalid'); + } + + if (!token.client) { + throw new ServerError('Server error: `getRefreshToken()` did not return a `client` object'); + } - return promisify(this.model.getRefreshToken, 1).call(this.model, request.body.refresh_token) - .then(function(token) { - if (!token) { - throw new InvalidGrantError('Invalid grant: refresh token is invalid'); - } + if (!token.user) { + throw new ServerError('Server error: `getRefreshToken()` did not return a `user` object'); + } - if (!token.client) { - throw new ServerError('Server error: `getRefreshToken()` did not return a `client` object'); - } + if (token.client.id !== client.id) { + throw new InvalidGrantError('Invalid grant: refresh token was issued to another client'); + } - if (!token.user) { - throw new ServerError('Server error: `getRefreshToken()` did not return a `user` object'); - } + if (token.refreshTokenExpiresAt && !(token.refreshTokenExpiresAt instanceof Date)) { + throw new ServerError('Server error: `refreshTokenExpiresAt` must be a Date instance'); + } - if (token.client.id !== client.id) { - throw new InvalidGrantError('Invalid grant: refresh token was issued to another client'); - } + if (token.refreshTokenExpiresAt && token.refreshTokenExpiresAt < new Date()) { + throw new InvalidGrantError('Invalid grant: refresh token has expired'); + } - if (token.refreshTokenExpiresAt && !(token.refreshTokenExpiresAt instanceof Date)) { - throw new ServerError('Server error: `refreshTokenExpiresAt` must be a Date instance'); - } + return token; + } - if (token.refreshTokenExpiresAt && token.refreshTokenExpiresAt < new Date()) { - throw new InvalidGrantError('Invalid grant: refresh token has expired'); - } + /** + * Revoke the refresh token. + * + * @see https://tools.ietf.org/html/rfc6749#section-6 + */ + async revokeToken(token) { + if (this.alwaysIssueNewRefreshToken === false) { return token; - }); -}; + } -/** - * Revoke the refresh token. - * - * @see https://tools.ietf.org/html/rfc6749#section-6 - */ + const status = await this.model.revokeToken(token); -RefreshTokenGrantType.prototype.revokeToken = function(token) { - if (this.alwaysIssueNewRefreshToken === false) { - return Promise.resolve(token); + if (!status) { + throw new InvalidGrantError('Invalid grant: refresh token is invalid or could not be revoked'); + } + + return token; } - return promisify(this.model.revokeToken, 1).call(this.model, token) - .then(function(status) { - if (!status) { - throw new InvalidGrantError('Invalid grant: refresh token is invalid or could not be revoked'); - } + /** + * Save token. + */ + + async saveToken(user, client, scope) { + const accessToken = await this.generateAccessToken(client, user, scope); + const refreshToken = await this.generateRefreshToken(client, user, scope); + const accessTokenExpiresAt = await this.getAccessTokenExpiresAt(); + const refreshTokenExpiresAt = await this.getRefreshTokenExpiresAt(); + const token = { + accessToken, + accessTokenExpiresAt, + scope, + }; + + if (this.alwaysIssueNewRefreshToken !== false) { + token.refreshToken = refreshToken; + token.refreshTokenExpiresAt = refreshTokenExpiresAt; + } + + return this.model.saveToken(token, client, user); + } - return token; - }); -}; + getScope (request, token) { + const requestedScope = super.getScope(request); + const originalScope = token.scope; -/** - * Save token. - */ + if (!originalScope && !requestedScope) { + return; + } -RefreshTokenGrantType.prototype.saveToken = function(user, client, scope) { - const fns = [ - this.generateAccessToken(client, user, scope), - this.generateRefreshToken(client, user, scope), - this.getAccessTokenExpiresAt(), - this.getRefreshTokenExpiresAt() - ]; - - return Promise.all(fns) - .bind(this) - .spread(function(accessToken, refreshToken, accessTokenExpiresAt, refreshTokenExpiresAt) { - const token = { - accessToken: accessToken, - accessTokenExpiresAt: accessTokenExpiresAt, - scope: scope - }; - - if (this.alwaysIssueNewRefreshToken !== false) { - token.refreshToken = refreshToken; - token.refreshTokenExpiresAt = refreshTokenExpiresAt; - } + if (!originalScope && requestedScope) { + throw new InvalidScopeError('Invalid scope: Unable to add extra scopes'); + } - return token; - }) - .then(function(token) { - return promisify(this.model.saveToken, 3).call(this.model, token, client, user) - .then(function(savedToken) { - return savedToken; - }); + if (!requestedScope) { + return originalScope; + } + + const valid = requestedScope.every(scope => { + return originalScope.includes(scope); }); -}; + + if (!valid) { + throw new InvalidScopeError('Invalid scope: Unable to add extra scopes'); + } + + return requestedScope; + } +} /** * Export constructor. diff --git a/lib/handlers/authenticate-handler.js b/lib/handlers/authenticate-handler.js index 7724742b..32251758 100644 --- a/lib/handlers/authenticate-handler.js +++ b/lib/handlers/authenticate-handler.js @@ -9,8 +9,6 @@ const InvalidRequestError = require('../errors/invalid-request-error'); const InsufficientScopeError = require('../errors/insufficient-scope-error'); const InvalidTokenError = require('../errors/invalid-token-error'); const OAuthError = require('../errors/oauth-error'); -const Promise = require('bluebird'); -const promisify = require('promisify-any').use(Promise); const Request = require('../request'); const Response = require('../response'); const ServerError = require('../errors/server-error'); @@ -20,70 +18,65 @@ const UnauthorizedRequestError = require('../errors/unauthorized-request-error') * Constructor. */ -function AuthenticateHandler(options) { - options = options || {}; +class AuthenticateHandler { + constructor (options) { + options = options || {}; - if (!options.model) { - throw new InvalidArgumentError('Missing parameter: `model`'); - } + if (!options.model) { + throw new InvalidArgumentError('Missing parameter: `model`'); + } - if (!options.model.getAccessToken) { - throw new InvalidArgumentError('Invalid argument: model does not implement `getAccessToken()`'); - } + if (!options.model.getAccessToken) { + throw new InvalidArgumentError('Invalid argument: model does not implement `getAccessToken()`'); + } - if (options.scope && undefined === options.addAcceptedScopesHeader) { - throw new InvalidArgumentError('Missing parameter: `addAcceptedScopesHeader`'); - } + if (options.scope && undefined === options.addAcceptedScopesHeader) { + throw new InvalidArgumentError('Missing parameter: `addAcceptedScopesHeader`'); + } - if (options.scope && undefined === options.addAuthorizedScopesHeader) { - throw new InvalidArgumentError('Missing parameter: `addAuthorizedScopesHeader`'); - } + if (options.scope && undefined === options.addAuthorizedScopesHeader) { + throw new InvalidArgumentError('Missing parameter: `addAuthorizedScopesHeader`'); + } - if (options.scope && !options.model.verifyScope) { - throw new InvalidArgumentError('Invalid argument: model does not implement `verifyScope()`'); + if (options.scope && !options.model.verifyScope) { + throw new InvalidArgumentError('Invalid argument: model does not implement `verifyScope()`'); + } + + this.addAcceptedScopesHeader = options.addAcceptedScopesHeader; + this.addAuthorizedScopesHeader = options.addAuthorizedScopesHeader; + this.allowBearerTokensInQueryString = options.allowBearerTokensInQueryString; + this.model = options.model; + this.scope = options.scope; } - this.addAcceptedScopesHeader = options.addAcceptedScopesHeader; - this.addAuthorizedScopesHeader = options.addAuthorizedScopesHeader; - this.allowBearerTokensInQueryString = options.allowBearerTokensInQueryString; - this.model = options.model; - this.scope = options.scope; -} + /** + * Authenticate Handler. + */ -/** - * Authenticate Handler. - */ + async handle (request, response) { + if (!(request instanceof Request)) { + throw new InvalidArgumentError('Invalid argument: `request` must be an instance of Request'); + } -AuthenticateHandler.prototype.handle = function(request, response) { - if (!(request instanceof Request)) { - throw new InvalidArgumentError('Invalid argument: `request` must be an instance of Request'); - } + if (!(response instanceof Response)) { + throw new InvalidArgumentError('Invalid argument: `response` must be an instance of Response'); + } - if (!(response instanceof Response)) { - throw new InvalidArgumentError('Invalid argument: `response` must be an instance of Response'); - } + try { + const requestToken = await this.getTokenFromRequest(request); - return Promise.bind(this) - .then(function() { - return this.getTokenFromRequest(request); - }) - .then(function(token) { - return this.getAccessToken(token); - }) - .tap(function(token) { - return this.validateAccessToken(token); - }) - .tap(function(token) { - if (!this.scope) { - return; + let accessToken; + accessToken = await this.getAccessToken(requestToken); + accessToken = await this.validateAccessToken(accessToken); + + if (this.scope) { + await this.verifyScope(accessToken); } - return this.verifyScope(token); - }) - .tap(function(token) { - return this.updateResponse(response, token); - }) - .catch(function(e) { + this.updateResponse(response, accessToken); + + return accessToken; + } catch (e) { // Include the "WWW-Authenticate" response header field if the client // lacks any authentication information. // @@ -103,165 +96,165 @@ AuthenticateHandler.prototype.handle = function(request, response) { } throw e; - }); -}; - -/** - * Get the token from the header or body, depending on the request. - * - * "Clients MUST NOT use more than one method to transmit the token in each request." - * - * @see https://tools.ietf.org/html/rfc6750#section-2 - */ - -AuthenticateHandler.prototype.getTokenFromRequest = function(request) { - const headerToken = request.get('Authorization'); - const queryToken = request.query.access_token; - const bodyToken = request.body.access_token; - - if (!!headerToken + !!queryToken + !!bodyToken > 1) { - throw new InvalidRequestError('Invalid request: only one authentication method is allowed'); + } } - if (headerToken) { - return this.getTokenFromRequestHeader(request); - } + /** + * Get the token from the header or body, depending on the request. + * + * "Clients MUST NOT use more than one method to transmit the token in each request." + * + * @see https://tools.ietf.org/html/rfc6750#section-2 + */ - if (queryToken) { - return this.getTokenFromRequestQuery(request); - } + getTokenFromRequest (request) { + const headerToken = request.get('Authorization'); + const queryToken = request.query.access_token; + const bodyToken = request.body.access_token; - if (bodyToken) { - return this.getTokenFromRequestBody(request); - } + if (!!headerToken + !!queryToken + !!bodyToken > 1) { + throw new InvalidRequestError('Invalid request: only one authentication method is allowed'); + } - throw new UnauthorizedRequestError('Unauthorized request: no authentication given'); -}; + if (headerToken) { + return this.getTokenFromRequestHeader(request); + } -/** - * Get the token from the request header. - * - * @see http://tools.ietf.org/html/rfc6750#section-2.1 - */ + if (queryToken) { + return this.getTokenFromRequestQuery(request); + } -AuthenticateHandler.prototype.getTokenFromRequestHeader = function(request) { - const token = request.get('Authorization'); - const matches = token.match(/^Bearer\s(\S+)/); + if (bodyToken) { + return this.getTokenFromRequestBody(request); + } - if (!matches) { - throw new InvalidRequestError('Invalid request: malformed authorization header'); + throw new UnauthorizedRequestError('Unauthorized request: no authentication given'); } - return matches[1]; -}; + /** + * Get the token from the request header. + * + * @see http://tools.ietf.org/html/rfc6750#section-2.1 + */ -/** - * Get the token from the request query. - * - * "Don't pass bearer tokens in page URLs: Bearer tokens SHOULD NOT be passed in page - * URLs (for example, as query string parameters). Instead, bearer tokens SHOULD be - * passed in HTTP message headers or message bodies for which confidentiality measures - * are taken. Browsers, web servers, and other software may not adequately secure URLs - * in the browser history, web server logs, and other data structures. If bearer tokens - * are passed in page URLs, attackers might be able to steal them from the history data, - * logs, or other unsecured locations." - * - * @see http://tools.ietf.org/html/rfc6750#section-2.3 - */ + getTokenFromRequestHeader (request) { + const token = request.get('Authorization'); + const matches = token.match(/^Bearer ([0-9a-zA-Z-._~+/]+=*)$/); -AuthenticateHandler.prototype.getTokenFromRequestQuery = function(request) { - if (!this.allowBearerTokensInQueryString) { - throw new InvalidRequestError('Invalid request: do not send bearer tokens in query URLs'); - } - - return request.query.access_token; -}; + if (!matches) { + throw new InvalidRequestError('Invalid request: malformed authorization header'); + } -/** - * Get the token from the request body. - * - * "The HTTP request method is one for which the request-body has defined semantics. - * In particular, this means that the "GET" method MUST NOT be used." - * - * @see http://tools.ietf.org/html/rfc6750#section-2.2 - */ + return matches[1]; + } -AuthenticateHandler.prototype.getTokenFromRequestBody = function(request) { - if (request.method === 'GET') { - throw new InvalidRequestError('Invalid request: token may not be passed in the body when using the GET verb'); + /** + * Get the token from the request query. + * + * "Don't pass bearer tokens in page URLs: Bearer tokens SHOULD NOT be passed in page + * URLs (for example, as query string parameters). Instead, bearer tokens SHOULD be + * passed in HTTP message headers or message bodies for which confidentiality measures + * are taken. Browsers, web servers, and other software may not adequately secure URLs + * in the browser history, web server logs, and other data structures. If bearer tokens + * are passed in page URLs, attackers might be able to steal them from the history data, + * logs, or other unsecured locations." + * + * @see http://tools.ietf.org/html/rfc6750#section-2.3 + */ + + getTokenFromRequestQuery (request) { + if (!this.allowBearerTokensInQueryString) { + throw new InvalidRequestError('Invalid request: do not send bearer tokens in query URLs'); + } + + return request.query.access_token; } - if (!request.is('application/x-www-form-urlencoded')) { - throw new InvalidRequestError('Invalid request: content must be application/x-www-form-urlencoded'); + /** + * Get the token from the request body. + * + * "The HTTP request method is one for which the request-body has defined semantics. + * In particular, this means that the "GET" method MUST NOT be used." + * + * @see http://tools.ietf.org/html/rfc6750#section-2.2 + */ + + getTokenFromRequestBody (request) { + if (request.method === 'GET') { + throw new InvalidRequestError('Invalid request: token may not be passed in the body when using the GET verb'); + } + + if (!request.is('application/x-www-form-urlencoded')) { + throw new InvalidRequestError('Invalid request: content must be application/x-www-form-urlencoded'); + } + + return request.body.access_token; } - return request.body.access_token; -}; + /** + * Get the access token from the model. + */ -/** - * Get the access token from the model. - */ + async getAccessToken (token) { + const accessToken = await this.model.getAccessToken(token); -AuthenticateHandler.prototype.getAccessToken = function(token) { - return promisify(this.model.getAccessToken, 1).call(this.model, token) - .then(function(accessToken) { - if (!accessToken) { - throw new InvalidTokenError('Invalid token: access token is invalid'); - } + if (!accessToken) { + throw new InvalidTokenError('Invalid token: access token is invalid'); + } - if (!accessToken.user) { - throw new ServerError('Server error: `getAccessToken()` did not return a `user` object'); - } + if (!accessToken.user) { + throw new ServerError('Server error: `getAccessToken()` did not return a `user` object'); + } - return accessToken; - }); -}; + return accessToken; + } -/** - * Validate access token. - */ + /** + * Validate access token. + */ -AuthenticateHandler.prototype.validateAccessToken = function(accessToken) { - if (!(accessToken.accessTokenExpiresAt instanceof Date)) { - throw new ServerError('Server error: `accessTokenExpiresAt` must be a Date instance'); - } + validateAccessToken (accessToken) { + if (!(accessToken.accessTokenExpiresAt instanceof Date)) { + throw new ServerError('Server error: `accessTokenExpiresAt` must be a Date instance'); + } + + if (accessToken.accessTokenExpiresAt < new Date()) { + throw new InvalidTokenError('Invalid token: access token has expired'); + } - if (accessToken.accessTokenExpiresAt < new Date()) { - throw new InvalidTokenError('Invalid token: access token has expired'); + return accessToken; } - return accessToken; -}; + /** + * Verify scope. + */ -/** - * Verify scope. - */ + async verifyScope (accessToken) { + const scope = await this.model.verifyScope(accessToken, this.scope); -AuthenticateHandler.prototype.verifyScope = function(accessToken) { - return promisify(this.model.verifyScope, 2).call(this.model, accessToken, this.scope) - .then(function(scope) { - if (!scope) { - throw new InsufficientScopeError('Insufficient scope: authorized scope is insufficient'); - } + if (!scope) { + throw new InsufficientScopeError('Insufficient scope: authorized scope is insufficient'); + } + } - return scope; - }); -}; + /** + * Update response. + */ -/** - * Update response. - */ + updateResponse (response, accessToken) { + if (accessToken.scope == null) { + return; + } -AuthenticateHandler.prototype.updateResponse = function(response, accessToken) { - if (this.scope && this.addAcceptedScopesHeader) { - response.set('X-Accepted-OAuth-Scopes', this.scope); - } + if (this.scope && this.addAcceptedScopesHeader) { + response.set('X-Accepted-OAuth-Scopes', this.scope.join(' ')); + } - if (this.scope && this.addAuthorizedScopesHeader) { - response.set('X-OAuth-Scopes', accessToken.scope); + if (this.scope && this.addAuthorizedScopesHeader) { + response.set('X-OAuth-Scopes', accessToken.scope.join(' ')); + } } -}; - +} /** * Export constructor. */ diff --git a/lib/handlers/authorize-handler.js b/lib/handlers/authorize-handler.js index 57413e92..12ca72cf 100644 --- a/lib/handlers/authorize-handler.js +++ b/lib/handlers/authorize-handler.js @@ -12,8 +12,6 @@ const InvalidRequestError = require('../errors/invalid-request-error'); const InvalidScopeError = require('../errors/invalid-scope-error'); const UnsupportedResponseTypeError = require('../errors/unsupported-response-type-error'); const OAuthError = require('../errors/oauth-error'); -const Promise = require('bluebird'); -const promisify = require('promisify-any').use(Promise); const Request = require('../request'); const Response = require('../response'); const ServerError = require('../errors/server-error'); @@ -22,6 +20,7 @@ const isFormat = require('@node-oauth/formats'); const tokenUtil = require('../utils/token-util'); const url = require('url'); const pkce = require('../pkce/pkce'); +const { parseScope } = require('../utils/scope-util'); /** * Response types. @@ -36,365 +35,358 @@ const responseTypes = { * Constructor. */ -function AuthorizeHandler(options) { - options = options || {}; +class AuthorizeHandler { + constructor (options) { + options = options || {}; - if (options.authenticateHandler && !options.authenticateHandler.handle) { - throw new InvalidArgumentError('Invalid argument: authenticateHandler does not implement `handle()`'); - } + if (options.authenticateHandler && !options.authenticateHandler.handle) { + throw new InvalidArgumentError('Invalid argument: authenticateHandler does not implement `handle()`'); + } - if (!options.authorizationCodeLifetime) { - throw new InvalidArgumentError('Missing parameter: `authorizationCodeLifetime`'); - } + if (!options.authorizationCodeLifetime) { + throw new InvalidArgumentError('Missing parameter: `authorizationCodeLifetime`'); + } - if (!options.model) { - throw new InvalidArgumentError('Missing parameter: `model`'); - } + if (!options.model) { + throw new InvalidArgumentError('Missing parameter: `model`'); + } - if (!options.model.getClient) { - throw new InvalidArgumentError('Invalid argument: model does not implement `getClient()`'); - } + if (!options.model.getClient) { + throw new InvalidArgumentError('Invalid argument: model does not implement `getClient()`'); + } + + if (!options.model.saveAuthorizationCode) { + throw new InvalidArgumentError('Invalid argument: model does not implement `saveAuthorizationCode()`'); + } - if (!options.model.saveAuthorizationCode) { - throw new InvalidArgumentError('Invalid argument: model does not implement `saveAuthorizationCode()`'); + this.allowEmptyState = options.allowEmptyState; + this.authenticateHandler = options.authenticateHandler || new AuthenticateHandler(options); + this.authorizationCodeLifetime = options.authorizationCodeLifetime; + this.model = options.model; } - this.allowEmptyState = options.allowEmptyState; - this.authenticateHandler = options.authenticateHandler || new AuthenticateHandler(options); - this.authorizationCodeLifetime = options.authorizationCodeLifetime; - this.model = options.model; -} + /** + * Authorize Handler. + */ -/** - * Authorize Handler. - */ + async handle (request, response) { + if (!(request instanceof Request)) { + throw new InvalidArgumentError('Invalid argument: `request` must be an instance of Request'); + } -AuthorizeHandler.prototype.handle = function(request, response) { - if (!(request instanceof Request)) { - throw new InvalidArgumentError('Invalid argument: `request` must be an instance of Request'); + if (!(response instanceof Response)) { + throw new InvalidArgumentError('Invalid argument: `response` must be an instance of Response'); + } + + const expiresAt = await this.getAuthorizationCodeLifetime(); + const client = await this.getClient(request); + const user = await this.getUser(request, response); + + let uri; + let state; + + try { + uri = this.getRedirectUri(request, client); + state = this.getState(request); + + if (request.query.allowed === 'false' || request.body.allowed === 'false') { + throw new AccessDeniedError('Access denied: user denied access to application'); + } + + const requestedScope = await this.getScope(request); + const validScope = await this.validateScope(user, client, requestedScope); + const authorizationCode = await this.generateAuthorizationCode(client, user, validScope); + + const ResponseType = this.getResponseType(request); + const codeChallenge = this.getCodeChallenge(request); + const codeChallengeMethod = this.getCodeChallengeMethod(request); + const code = await this.saveAuthorizationCode( + authorizationCode, + expiresAt, + validScope, + client, + uri, + user, + codeChallenge, + codeChallengeMethod + ); + + const responseTypeInstance = new ResponseType(code.authorizationCode); + const redirectUri = this.buildSuccessRedirectUri(uri, responseTypeInstance); + + this.updateResponse(response, redirectUri, state); + + return code; + } catch (err) { + let e = err; + + if (!(e instanceof OAuthError)) { + e = new ServerError(e); + } + const redirectUri = this.buildErrorRedirectUri(uri, e); + this.updateResponse(response, redirectUri, state); + + throw e; + } } - if (!(response instanceof Response)) { - throw new InvalidArgumentError('Invalid argument: `response` must be an instance of Response'); + /** + * Generate authorization code. + */ + + async generateAuthorizationCode (client, user, scope) { + if (this.model.generateAuthorizationCode) { + return this.model.generateAuthorizationCode(client, user, scope); + } + return tokenUtil.generateRandomToken(); } - const fns = [ - this.getAuthorizationCodeLifetime(), - this.getClient(request), - this.getUser(request, response) - ]; - - return Promise.all(fns) - .bind(this) - .spread(function(expiresAt, client, user) { - const uri = this.getRedirectUri(request, client); - let scope; - let state; - let ResponseType; - - return Promise.bind(this) - .then(function() { - state = this.getState(request); - if (request.query.allowed === 'false' || request.body.allowed === 'false') { - throw new AccessDeniedError('Access denied: user denied access to application'); - } - }) - .then(function() { - const requestedScope = this.getScope(request); - - return this.validateScope(user, client, requestedScope); - }) - .then(function(validScope) { - scope = validScope; - - return this.generateAuthorizationCode(client, user, scope); - }) - .then(function(authorizationCode) { - ResponseType = this.getResponseType(request); - const codeChallenge = this.getCodeChallenge(request); - const codeChallengeMethod = this.getCodeChallengeMethod(request); - - return this.saveAuthorizationCode(authorizationCode, expiresAt, scope, client, uri, user, codeChallenge, codeChallengeMethod); - }) - .then(function(code) { - const responseType = new ResponseType(code.authorizationCode); - const redirectUri = this.buildSuccessRedirectUri(uri, responseType); - - this.updateResponse(response, redirectUri, state); - - return code; - }) - .catch(function(e) { - if (!(e instanceof OAuthError)) { - e = new ServerError(e); - } - const redirectUri = this.buildErrorRedirectUri(uri, e); - - this.updateResponse(response, redirectUri, state); - - throw e; - }); - }); -}; + /** + * Get authorization code lifetime. + */ -/** - * Generate authorization code. - */ + getAuthorizationCodeLifetime () { + const expires = new Date(); -AuthorizeHandler.prototype.generateAuthorizationCode = function(client, user, scope) { - if (this.model.generateAuthorizationCode) { - return promisify(this.model.generateAuthorizationCode, 3).call(this.model, client, user, scope); + expires.setSeconds(expires.getSeconds() + this.authorizationCodeLifetime); + return expires; } - return tokenUtil.generateRandomToken(); -}; -/** - * Get authorization code lifetime. - */ + /** + * Get the client from the model. + */ -AuthorizeHandler.prototype.getAuthorizationCodeLifetime = function() { - const expires = new Date(); + async getClient (request) { + const self = this; + const clientId = request.body.client_id || request.query.client_id; - expires.setSeconds(expires.getSeconds() + this.authorizationCodeLifetime); - return expires; -}; + if (!clientId) { + throw new InvalidRequestError('Missing parameter: `client_id`'); + } -/** - * Get the client from the model. - */ + if (!isFormat.vschar(clientId)) { + throw new InvalidRequestError('Invalid parameter: `client_id`'); + } -AuthorizeHandler.prototype.getClient = function(request) { - const self = this; - const clientId = request.body.client_id || request.query.client_id; + const redirectUri = request.body.redirect_uri || request.query.redirect_uri; - if (!clientId) { - throw new InvalidRequestError('Missing parameter: `client_id`'); - } + if (redirectUri && !isFormat.uri(redirectUri)) { + throw new InvalidRequestError('Invalid request: `redirect_uri` is not a valid URI'); + } - if (!isFormat.vschar(clientId)) { - throw new InvalidRequestError('Invalid parameter: `client_id`'); - } + const client = await this.model.getClient(clientId, null); - const redirectUri = request.body.redirect_uri || request.query.redirect_uri; + if (!client) { + throw new InvalidClientError('Invalid client: client credentials are invalid'); + } - if (redirectUri && !isFormat.uri(redirectUri)) { - throw new InvalidRequestError('Invalid request: `redirect_uri` is not a valid URI'); - } - return promisify(this.model.getClient, 2).call(this.model, clientId, null) - .then(function(client) { - if (!client) { - throw new InvalidClientError('Invalid client: client credentials are invalid'); - } + if (!client.grants) { + throw new InvalidClientError('Invalid client: missing client `grants`'); + } - if (!client.grants) { - throw new InvalidClientError('Invalid client: missing client `grants`'); - } + if (!Array.isArray(client.grants) || !client.grants.includes('authorization_code')) { + throw new UnauthorizedClientError('Unauthorized client: `grant_type` is invalid'); + } - if (!Array.isArray(client.grants) || !client.grants.includes('authorization_code')) { - throw new UnauthorizedClientError('Unauthorized client: `grant_type` is invalid'); - } + if (!client.redirectUris || 0 === client.redirectUris.length) { + throw new InvalidClientError('Invalid client: missing client `redirectUri`'); + } + + if (redirectUri) { + const valid = await self.validateRedirectUri(redirectUri, client); - if (!client.redirectUris || 0 === client.redirectUris.length) { - throw new InvalidClientError('Invalid client: missing client `redirectUri`'); + if (!valid) { + throw new InvalidClientError('Invalid client: `redirect_uri` does not match client value'); } + } + + return client; + } + + /** + * Validate requested scope. + */ + async validateScope (user, client, scope) { + if (this.model.validateScope) { + const validatedScope = await this.model.validateScope(user, client, scope); - if (redirectUri) { - return self.validateRedirectUri(redirectUri, client) - .then(function(valid) { - if (!valid) { - throw new InvalidClientError('Invalid client: `redirect_uri` does not match client value'); - } - return client; - }); - } else { - return client; + if (!validatedScope) { + throw new InvalidScopeError('Invalid scope: Requested scope is invalid'); } - }); -}; -/** - * Validate requested scope. - */ -AuthorizeHandler.prototype.validateScope = function(user, client, scope) { - if (this.model.validateScope) { - return promisify(this.model.validateScope, 3).call(this.model, user, client, scope) - .then(function (scope) { - if (!scope) { - throw new InvalidScopeError('Invalid scope: Requested scope is invalid'); - } - - return scope; - }); - } else { - return Promise.resolve(scope); + return validatedScope; + } + + return scope; } -}; -/** - * Get scope from the request. - */ + /** + * Get scope from the request. + */ -AuthorizeHandler.prototype.getScope = function(request) { - const scope = request.body.scope || request.query.scope; + getScope (request) { + const scope = request.body.scope || request.query.scope; - if (!isFormat.nqschar(scope)) { - throw new InvalidScopeError('Invalid parameter: `scope`'); + return parseScope(scope); } - return scope; -}; + /** + * Get state from the request. + */ -/** - * Get state from the request. - */ + getState (request) { + const state = request.body.state || request.query.state; + const stateExists = state && state.length > 0; + const stateIsValid = stateExists + ? isFormat.vschar(state) + : this.allowEmptyState; -AuthorizeHandler.prototype.getState = function(request) { - const state = request.body.state || request.query.state; - const stateExists = state && state.length > 0; - const stateIsValid = stateExists - ? isFormat.vschar(state) - : this.allowEmptyState; + if (!stateIsValid) { + const message = (!stateExists) ? 'Missing' : 'Invalid'; + throw new InvalidRequestError(`${message} parameter: \`state\``); + } - if (!stateIsValid) { - const message = (!stateExists) ? 'Missing' : 'Invalid'; - throw new InvalidRequestError(`${message} parameter: \`state\``); + return state; } - return state; -}; + /** + * Get user by calling the authenticate middleware. + */ -/** - * Get user by calling the authenticate middleware. - */ + async getUser (request, response) { + if (this.authenticateHandler instanceof AuthenticateHandler) { + const handled = await this.authenticateHandler.handle(request, response); + return handled + ? handled.user + : undefined; + } + + const user = await this.authenticateHandler.handle(request, response); -AuthorizeHandler.prototype.getUser = function(request, response) { - if (this.authenticateHandler instanceof AuthenticateHandler) { - return this.authenticateHandler.handle(request, response).get('user'); - } - return promisify(this.authenticateHandler.handle, 2)(request, response).then(function(user) { if (!user) { throw new ServerError('Server error: `handle()` did not return a `user` object'); } return user; - }); -}; + } -/** - * Get redirect URI. - */ + /** + * Get redirect URI. + */ -AuthorizeHandler.prototype.getRedirectUri = function(request, client) { - return request.body.redirect_uri || request.query.redirect_uri || client.redirectUris[0]; -}; + getRedirectUri (request, client) { + return request.body.redirect_uri || request.query.redirect_uri || client.redirectUris[0]; + } -/** - * Save authorization code. - */ + /** + * Save authorization code. + */ + + async saveAuthorizationCode (authorizationCode, expiresAt, scope, client, redirectUri, user, codeChallenge, codeChallengeMethod) { + let code = { + authorizationCode: authorizationCode, + expiresAt: expiresAt, + redirectUri: redirectUri, + scope: scope + }; + + if(codeChallenge && codeChallengeMethod){ + code = Object.assign({ + codeChallenge: codeChallenge, + codeChallengeMethod: codeChallengeMethod + }, code); + } -AuthorizeHandler.prototype.saveAuthorizationCode = function(authorizationCode, expiresAt, scope, client, redirectUri, user, codeChallenge, codeChallengeMethod) { - let code = { - authorizationCode: authorizationCode, - expiresAt: expiresAt, - redirectUri: redirectUri, - scope: scope - }; - - if(codeChallenge && codeChallengeMethod){ - code = Object.assign({ - codeChallenge: codeChallenge, - codeChallengeMethod: codeChallengeMethod - }, code); + return this.model.saveAuthorizationCode(code, client, user); } - return promisify(this.model.saveAuthorizationCode, 3).call(this.model, code, client, user); -}; -AuthorizeHandler.prototype.validateRedirectUri = function(redirectUri, client) { - if (this.model.validateRedirectUri) { - return promisify(this.model.validateRedirectUri, 2).call(this.model, redirectUri, client); + async validateRedirectUri (redirectUri, client) { + if (this.model.validateRedirectUri) { + return this.model.validateRedirectUri(redirectUri, client); + } + + return client.redirectUris.includes(redirectUri); } + /** + * Get response type. + */ - return Promise.resolve(client.redirectUris.includes(redirectUri)); -}; -/** - * Get response type. - */ + getResponseType (request) { + const responseType = request.body.response_type || request.query.response_type; -AuthorizeHandler.prototype.getResponseType = function(request) { - const responseType = request.body.response_type || request.query.response_type; + if (!responseType) { + throw new InvalidRequestError('Missing parameter: `response_type`'); + } - if (!responseType) { - throw new InvalidRequestError('Missing parameter: `response_type`'); - } + if (!Object.prototype.hasOwnProperty.call(responseTypes, responseType)) { + throw new UnsupportedResponseTypeError('Unsupported response type: `response_type` is not supported'); + } - if (!Object.prototype.hasOwnProperty.call(responseTypes, responseType)) { - throw new UnsupportedResponseTypeError('Unsupported response type: `response_type` is not supported'); + return responseTypes[responseType]; } - return responseTypes[responseType]; -}; + /** + * Build a successful response that redirects the user-agent to the client-provided url. + */ -/** - * Build a successful response that redirects the user-agent to the client-provided url. - */ + buildSuccessRedirectUri (redirectUri, responseType) { + return responseType.buildRedirectUri(redirectUri); + } -AuthorizeHandler.prototype.buildSuccessRedirectUri = function(redirectUri, responseType) { - return responseType.buildRedirectUri(redirectUri); -}; + /** + * Build an error response that redirects the user-agent to the client-provided url. + */ -/** - * Build an error response that redirects the user-agent to the client-provided url. - */ + buildErrorRedirectUri (redirectUri, error) { + const uri = url.parse(redirectUri); -AuthorizeHandler.prototype.buildErrorRedirectUri = function(redirectUri, error) { - const uri = url.parse(redirectUri); + uri.query = { + error: error.name + }; - uri.query = { - error: error.name - }; + if (error.message) { + uri.query.error_description = error.message; + } - if (error.message) { - uri.query.error_description = error.message; + return uri; } - return uri; -}; + /** + * Update response with the redirect uri and the state parameter, if available. + */ -/** - * Update response with the redirect uri and the state parameter, if available. - */ + updateResponse (response, redirectUri, state) { + redirectUri.query = redirectUri.query || {}; -AuthorizeHandler.prototype.updateResponse = function(response, redirectUri, state) { - redirectUri.query = redirectUri.query || {}; + if (state) { + redirectUri.query.state = state; + } - if (state) { - redirectUri.query.state = state; + response.redirect(url.format(redirectUri)); } - response.redirect(url.format(redirectUri)); -}; - -AuthorizeHandler.prototype.getCodeChallenge = function(request) { - return request.body.code_challenge; -}; + getCodeChallenge (request) { + return request.body.code_challenge || request.query.code_challenge; + } -/** - * Get code challenge method from request or defaults to plain. - * https://www.rfc-editor.org/rfc/rfc7636#section-4.3 - * - * @throws {InvalidRequestError} if request contains unsupported code_challenge_method - * (see https://www.rfc-editor.org/rfc/rfc7636#section-4.4) - */ -AuthorizeHandler.prototype.getCodeChallengeMethod = function(request) { - const algorithm = request.body.code_challenge_method; + /** + * Get code challenge method from request or defaults to plain. + * https://www.rfc-editor.org/rfc/rfc7636#section-4.3 + * + * @throws {InvalidRequestError} if request contains unsupported code_challenge_method + * (see https://www.rfc-editor.org/rfc/rfc7636#section-4.4) + */ + getCodeChallengeMethod (request) { + const algorithm = request.body.code_challenge_method || request.query.code_challenge_method; + + if (algorithm && !pkce.isValidMethod(algorithm)) { + throw new InvalidRequestError(`Invalid request: transform algorithm '${algorithm}' not supported`); + } - if (algorithm && !pkce.isValidMethod(algorithm)) { - throw new InvalidRequestError(`Invalid request: transform algorithm '${algorithm}' not supported`); + return algorithm || 'plain'; } - - return algorithm || 'plain'; -}; +} /** * Export constructor. diff --git a/lib/handlers/token-handler.js b/lib/handlers/token-handler.js index 0f0c57a2..6ce6c215 100644 --- a/lib/handlers/token-handler.js +++ b/lib/handlers/token-handler.js @@ -9,8 +9,6 @@ const InvalidArgumentError = require('../errors/invalid-argument-error'); const InvalidClientError = require('../errors/invalid-client-error'); const InvalidRequestError = require('../errors/invalid-request-error'); const OAuthError = require('../errors/oauth-error'); -const Promise = require('bluebird'); -const promisify = require('promisify-any').use(Promise); const Request = require('../request'); const Response = require('../response'); const ServerError = require('../errors/server-error'); @@ -36,106 +34,106 @@ const grantTypes = { * Constructor. */ -function TokenHandler(options) { - options = options || {}; +class TokenHandler { + constructor (options) { + options = options || {}; - if (!options.accessTokenLifetime) { - throw new InvalidArgumentError('Missing parameter: `accessTokenLifetime`'); - } + if (!options.accessTokenLifetime) { + throw new InvalidArgumentError('Missing parameter: `accessTokenLifetime`'); + } - if (!options.model) { - throw new InvalidArgumentError('Missing parameter: `model`'); - } + if (!options.model) { + throw new InvalidArgumentError('Missing parameter: `model`'); + } - if (!options.refreshTokenLifetime) { - throw new InvalidArgumentError('Missing parameter: `refreshTokenLifetime`'); - } + if (!options.refreshTokenLifetime) { + throw new InvalidArgumentError('Missing parameter: `refreshTokenLifetime`'); + } - if (!options.model.getClient) { - throw new InvalidArgumentError('Invalid argument: model does not implement `getClient()`'); - } + if (!options.model.getClient) { + throw new InvalidArgumentError('Invalid argument: model does not implement `getClient()`'); + } - this.accessTokenLifetime = options.accessTokenLifetime; - this.grantTypes = Object.assign({}, grantTypes, options.extendedGrantTypes); - this.model = options.model; - this.refreshTokenLifetime = options.refreshTokenLifetime; - this.allowExtendedTokenAttributes = options.allowExtendedTokenAttributes; - this.requireClientAuthentication = options.requireClientAuthentication || {}; - this.alwaysIssueNewRefreshToken = options.alwaysIssueNewRefreshToken !== false; -} + this.accessTokenLifetime = options.accessTokenLifetime; + this.grantTypes = Object.assign({}, grantTypes, options.extendedGrantTypes); + this.model = options.model; + this.refreshTokenLifetime = options.refreshTokenLifetime; + this.allowExtendedTokenAttributes = options.allowExtendedTokenAttributes; + this.requireClientAuthentication = options.requireClientAuthentication || {}; + this.alwaysIssueNewRefreshToken = options.alwaysIssueNewRefreshToken !== false; + } -/** - * Token Handler. - */ + /** + * Token Handler. + */ -TokenHandler.prototype.handle = function(request, response) { - if (!(request instanceof Request)) { - throw new InvalidArgumentError('Invalid argument: `request` must be an instance of Request'); - } + async handle (request, response) { + if (!(request instanceof Request)) { + throw new InvalidArgumentError('Invalid argument: `request` must be an instance of Request'); + } - if (!(response instanceof Response)) { - throw new InvalidArgumentError('Invalid argument: `response` must be an instance of Response'); - } + if (!(response instanceof Response)) { + throw new InvalidArgumentError('Invalid argument: `response` must be an instance of Response'); + } - if (request.method !== 'POST') { - return Promise.reject(new InvalidRequestError('Invalid request: method must be POST')); - } + if (request.method !== 'POST') { + throw new InvalidRequestError('Invalid request: method must be POST'); + } - if (!request.is('application/x-www-form-urlencoded')) { - return Promise.reject(new InvalidRequestError('Invalid request: content must be application/x-www-form-urlencoded')); - } + if (!request.is('application/x-www-form-urlencoded')) { + throw new InvalidRequestError('Invalid request: content must be application/x-www-form-urlencoded'); + } - return Promise.bind(this) - .then(function() { - return this.getClient(request, response); - }) - .then(function(client) { - return this.handleGrantType(request, client); - }) - .tap(function(data) { - const model = new TokenModel(data, {allowExtendedTokenAttributes: this.allowExtendedTokenAttributes}); + try { + const client = await this.getClient(request, response); + const data = await this.handleGrantType(request, client); + const model = new TokenModel(data, { allowExtendedTokenAttributes: this.allowExtendedTokenAttributes }); const tokenType = this.getTokenType(model); this.updateSuccessResponse(response, tokenType); - }).catch(function(e) { + + return data; + } catch (err) { + let e = err; + if (!(e instanceof OAuthError)) { e = new ServerError(e); } this.updateErrorResponse(response, e); - throw e; - }); -}; + } + } -/** - * Get the client from the model. - */ + /** + * Get the client from the model. + */ -TokenHandler.prototype.getClient = function(request, response) { - const credentials = this.getClientCredentials(request); - const grantType = request.body.grant_type; - const codeVerifier = request.body.code_verifier; - const isPkce = pkce.isPKCERequest({ grantType, codeVerifier }); + async getClient (request, response) { + const credentials = await this.getClientCredentials(request); + const grantType = request.body.grant_type; + const codeVerifier = request.body.code_verifier; + const isPkce = pkce.isPKCERequest({ grantType, codeVerifier }); - if (!credentials.clientId) { - throw new InvalidRequestError('Missing parameter: `client_id`'); - } + if (!credentials.clientId) { + throw new InvalidRequestError('Missing parameter: `client_id`'); + } - if (this.isClientAuthenticationRequired(grantType) && !credentials.clientSecret && !isPkce) { - throw new InvalidRequestError('Missing parameter: `client_secret`'); - } + if (this.isClientAuthenticationRequired(grantType) && !credentials.clientSecret && !isPkce) { + throw new InvalidRequestError('Missing parameter: `client_secret`'); + } - if (!isFormat.vschar(credentials.clientId)) { - throw new InvalidRequestError('Invalid parameter: `client_id`'); - } + if (!isFormat.vschar(credentials.clientId)) { + throw new InvalidRequestError('Invalid parameter: `client_id`'); + } - if (credentials.clientSecret && !isFormat.vschar(credentials.clientSecret)) { - throw new InvalidRequestError('Invalid parameter: `client_secret`'); - } + if (credentials.clientSecret && !isFormat.vschar(credentials.clientSecret)) { + throw new InvalidRequestError('Invalid parameter: `client_secret`'); + } + + try { + const client = await this.model.getClient(credentials.clientId, credentials.clientSecret); - return promisify(this.model.getClient, 2).call(this.model, credentials.clientId, credentials.clientSecret) - .then(function(client) { if (!client) { throw new InvalidClientError('Invalid client: client is invalid'); } @@ -149,155 +147,153 @@ TokenHandler.prototype.getClient = function(request, response) { } return client; - }) - .catch(function(e) { + } catch (e) { // Include the "WWW-Authenticate" response header field if the client // attempted to authenticate via the "Authorization" request header. // // @see https://tools.ietf.org/html/rfc6749#section-5.2. if ((e instanceof InvalidClientError) && request.get('authorization')) { response.set('WWW-Authenticate', 'Basic realm="Service"'); - throw new InvalidClientError(e, { code: 401 }); } throw e; - }); -}; - -/** - * Get client credentials. - * - * The client credentials may be sent using the HTTP Basic authentication scheme or, alternatively, - * the `client_id` and `client_secret` can be embedded in the body. - * - * @see https://tools.ietf.org/html/rfc6749#section-2.3.1 - */ - -TokenHandler.prototype.getClientCredentials = function(request) { - const credentials = auth(request); - const grantType = request.body.grant_type; - const codeVerifier = request.body.code_verifier; - - if (credentials) { - return { clientId: credentials.name, clientSecret: credentials.pass }; + } } - if (request.body.client_id && request.body.client_secret) { - return { clientId: request.body.client_id, clientSecret: request.body.client_secret }; - } + /** + * Get client credentials. + * + * The client credentials may be sent using the HTTP Basic authentication scheme or, alternatively, + * the `client_id` and `client_secret` can be embedded in the body. + * + * @see https://tools.ietf.org/html/rfc6749#section-2.3.1 + */ + + getClientCredentials (request) { + const credentials = auth(request); + const grantType = request.body.grant_type; + const codeVerifier = request.body.code_verifier; + + if (credentials) { + return { clientId: credentials.name, clientSecret: credentials.pass }; + } - if (pkce.isPKCERequest({ grantType, codeVerifier })) { - if(request.body.client_id) { - return { clientId: request.body.client_id }; + if (request.body.client_id && request.body.client_secret) { + return { clientId: request.body.client_id, clientSecret: request.body.client_secret }; } - } - if (!this.isClientAuthenticationRequired(grantType)) { - if(request.body.client_id) { - return { clientId: request.body.client_id }; + if (pkce.isPKCERequest({ grantType, codeVerifier })) { + if(request.body.client_id) { + return { clientId: request.body.client_id }; + } } - } - throw new InvalidClientError('Invalid client: cannot retrieve client credentials'); -}; + if (!this.isClientAuthenticationRequired(grantType)) { + if(request.body.client_id) { + return { clientId: request.body.client_id }; + } + } -/** - * Handle grant type. - */ + throw new InvalidClientError('Invalid client: cannot retrieve client credentials'); + } -TokenHandler.prototype.handleGrantType = function(request, client) { - const grantType = request.body.grant_type; + /** + * Handle grant type. + */ - if (!grantType) { - throw new InvalidRequestError('Missing parameter: `grant_type`'); - } + async handleGrantType (request, client) { + const grantType = request.body.grant_type; - if (!isFormat.nchar(grantType) && !isFormat.uri(grantType)) { - throw new InvalidRequestError('Invalid parameter: `grant_type`'); - } + if (!grantType) { + throw new InvalidRequestError('Missing parameter: `grant_type`'); + } - if (!Object.prototype.hasOwnProperty.call(this.grantTypes, grantType)) { - throw new UnsupportedGrantTypeError('Unsupported grant type: `grant_type` is invalid'); - } + if (!isFormat.nchar(grantType) && !isFormat.uri(grantType)) { + throw new InvalidRequestError('Invalid parameter: `grant_type`'); + } - if (!Array.isArray(client.grants) || !client.grants.includes(grantType)) { - throw new UnauthorizedClientError('Unauthorized client: `grant_type` is invalid'); - } + if (!Object.prototype.hasOwnProperty.call(this.grantTypes, grantType)) { + throw new UnsupportedGrantTypeError('Unsupported grant type: `grant_type` is invalid'); + } - const accessTokenLifetime = this.getAccessTokenLifetime(client); - const refreshTokenLifetime = this.getRefreshTokenLifetime(client); - const Type = this.grantTypes[grantType]; + if (!Array.isArray(client.grants) || !client.grants.includes(grantType)) { + throw new UnauthorizedClientError('Unauthorized client: `grant_type` is invalid'); + } - const options = { - accessTokenLifetime: accessTokenLifetime, - model: this.model, - refreshTokenLifetime: refreshTokenLifetime, - alwaysIssueNewRefreshToken: this.alwaysIssueNewRefreshToken - }; + const accessTokenLifetime = this.getAccessTokenLifetime(client); + const refreshTokenLifetime = this.getRefreshTokenLifetime(client); + const Type = this.grantTypes[grantType]; - return new Type(options) - .handle(request, client); -}; + const options = { + accessTokenLifetime: accessTokenLifetime, + model: this.model, + refreshTokenLifetime: refreshTokenLifetime, + alwaysIssueNewRefreshToken: this.alwaysIssueNewRefreshToken + }; -/** - * Get access token lifetime. - */ + return new Type(options).handle(request, client); + } -TokenHandler.prototype.getAccessTokenLifetime = function(client) { - return client.accessTokenLifetime || this.accessTokenLifetime; -}; + /** + * Get access token lifetime. + */ -/** - * Get refresh token lifetime. - */ + getAccessTokenLifetime (client) { + return client.accessTokenLifetime || this.accessTokenLifetime; + } -TokenHandler.prototype.getRefreshTokenLifetime = function(client) { - return client.refreshTokenLifetime || this.refreshTokenLifetime; -}; + /** + * Get refresh token lifetime. + */ -/** - * Get token type. - */ + getRefreshTokenLifetime (client) { + return client.refreshTokenLifetime || this.refreshTokenLifetime; + } -TokenHandler.prototype.getTokenType = function(model) { - return new BearerTokenType(model.accessToken, model.accessTokenLifetime, model.refreshToken, model.scope, model.customAttributes); -}; + /** + * Get token type. + */ -/** - * Update response when a token is generated. - */ + getTokenType (model) { + return new BearerTokenType(model.accessToken, model.accessTokenLifetime, model.refreshToken, model.scope, model.customAttributes); + } -TokenHandler.prototype.updateSuccessResponse = function(response, tokenType) { - response.body = tokenType.valueOf(); + /** + * Update response when a token is generated. + */ - response.set('Cache-Control', 'no-store'); - response.set('Pragma', 'no-cache'); -}; + updateSuccessResponse (response, tokenType) { + response.body = tokenType.valueOf(); -/** - * Update response when an error is thrown. - */ + response.set('Cache-Control', 'no-store'); + response.set('Pragma', 'no-cache'); + } -TokenHandler.prototype.updateErrorResponse = function(response, error) { - response.body = { - error: error.name, - error_description: error.message - }; + /** + * Update response when an error is thrown. + */ - response.status = error.code; -}; + updateErrorResponse (response, error) { + response.body = { + error: error.name, + error_description: error.message + }; -/** - * Given a grant type, check if client authentication is required - */ -TokenHandler.prototype.isClientAuthenticationRequired = function(grantType) { - if (Object.keys(this.requireClientAuthentication).length > 0) { - return (typeof this.requireClientAuthentication[grantType] !== 'undefined') ? this.requireClientAuthentication[grantType] : true; - } else { - return true; + response.status = error.code; } -}; + + /** + * Given a grant type, check if client authentication is required + */ + isClientAuthenticationRequired (grantType) { + if (Object.keys(this.requireClientAuthentication).length > 0) { + return (typeof this.requireClientAuthentication[grantType] !== 'undefined') ? this.requireClientAuthentication[grantType] : true; + } else { + return true; + } + } +} /** * Export constructor. diff --git a/lib/models/token-model.js b/lib/models/token-model.js index 473c7ace..40dee37c 100644 --- a/lib/models/token-model.js +++ b/lib/models/token-model.js @@ -3,63 +3,78 @@ /** * Module dependencies. */ - const InvalidArgumentError = require('../errors/invalid-argument-error'); +const { getLifetimeFromExpiresAt } = require('../utils/date-util'); /** - * Constructor. + * The core model attributes allowed when allowExtendedTokenAttributes is false. */ +const modelAttributes = new Set([ + 'accessToken', + 'accessTokenExpiresAt', + 'refreshToken', + 'refreshTokenExpiresAt', + 'scope', + 'client', + 'user' +]); + +class TokenModel { + constructor(data = {}, options = {}) { + const { + accessToken, + accessTokenExpiresAt, + refreshToken, + refreshTokenExpiresAt, + scope, + client, + user, + } = data; + + if (!accessToken) { + throw new InvalidArgumentError('Missing parameter: `accessToken`'); + } -const modelAttributes = ['accessToken', 'accessTokenExpiresAt', 'refreshToken', 'refreshTokenExpiresAt', 'scope', 'client', 'user']; - -function TokenModel(data, options) { - data = data || {}; + if (!client) { + throw new InvalidArgumentError('Missing parameter: `client`'); + } - if (!data.accessToken) { - throw new InvalidArgumentError('Missing parameter: `accessToken`'); - } + if (!user) { + throw new InvalidArgumentError('Missing parameter: `user`'); + } - if (!data.client) { - throw new InvalidArgumentError('Missing parameter: `client`'); - } + if (accessTokenExpiresAt && !(accessTokenExpiresAt instanceof Date)) { + throw new InvalidArgumentError('Invalid parameter: `accessTokenExpiresAt`'); + } - if (!data.user) { - throw new InvalidArgumentError('Missing parameter: `user`'); - } + if (refreshTokenExpiresAt && !(refreshTokenExpiresAt instanceof Date)) { + throw new InvalidArgumentError('Invalid parameter: `refreshTokenExpiresAt`'); + } - if (data.accessTokenExpiresAt && !(data.accessTokenExpiresAt instanceof Date)) { - throw new InvalidArgumentError('Invalid parameter: `accessTokenExpiresAt`'); - } + this.accessToken = accessToken; + this.accessTokenExpiresAt = accessTokenExpiresAt; + this.client = client; + this.refreshToken = refreshToken; + this.refreshTokenExpiresAt = refreshTokenExpiresAt; + this.scope = scope; + this.user = user; - if (data.refreshTokenExpiresAt && !(data.refreshTokenExpiresAt instanceof Date)) { - throw new InvalidArgumentError('Invalid parameter: `refreshTokenExpiresAt`'); - } + if (accessTokenExpiresAt) { + this.accessTokenLifetime = getLifetimeFromExpiresAt(accessTokenExpiresAt); + } - this.accessToken = data.accessToken; - this.accessTokenExpiresAt = data.accessTokenExpiresAt; - this.client = data.client; - this.refreshToken = data.refreshToken; - this.refreshTokenExpiresAt = data.refreshTokenExpiresAt; - this.scope = data.scope; - this.user = data.user; + const { allowExtendedTokenAttributes } = options; - if (options && options.allowExtendedTokenAttributes) { - this.customAttributes = {}; + if (allowExtendedTokenAttributes) { + this.customAttributes = {}; - for (const key in data) { - if ( Object.prototype.hasOwnProperty.call(data, key) && (modelAttributes.indexOf(key) < 0)) { - this.customAttributes[key] = data[key]; - } + Object.keys(data).forEach(key => { + if (!modelAttributes.has(key)) { + this.customAttributes[key] = data[key]; + } + }); } } - - if(this.accessTokenExpiresAt) { - this.accessTokenLifetime = Math.floor((this.accessTokenExpiresAt - new Date()) / 1000); - } } -/** - * Export constructor. - */ - module.exports = TokenModel; diff --git a/lib/pkce/pkce.js b/lib/pkce/pkce.js index 088b7521..e7603d98 100644 --- a/lib/pkce/pkce.js +++ b/lib/pkce/pkce.js @@ -19,7 +19,7 @@ const pkce = { * @return {String|undefined} */ getHashForCodeChallenge: function({ method, verifier }) { - // to prevent undesired side-effects when passing some weird values + // to prevent undesired side-effects when passing some wird values // to createHash or base64URLEncode we first check if the values are right if (pkce.isValidMethod(method) && typeof verifier === 'string' && verifier.length > 0) { if (method === 'plain') { diff --git a/lib/request.js b/lib/request.js index 560b29bc..7ac01a44 100644 --- a/lib/request.js +++ b/lib/request.js @@ -7,67 +7,53 @@ const InvalidArgumentError = require('./errors/invalid-argument-error'); const typeis = require('type-is'); -/** - * Constructor. - */ - -function Request(options) { - options = options || {}; +class Request { + constructor({ headers, method, query, body, ...otherOptions } = {}) { + if (!headers) { + throw new InvalidArgumentError('Missing parameter: `headers`'); + } - if (!options.headers) { - throw new InvalidArgumentError('Missing parameter: `headers`'); - } + if (!method) { + throw new InvalidArgumentError('Missing parameter: `method`'); + } - if (!options.method) { - throw new InvalidArgumentError('Missing parameter: `method`'); - } + if (!query) { + throw new InvalidArgumentError('Missing parameter: `query`'); + } - if (!options.query) { - throw new InvalidArgumentError('Missing parameter: `query`'); + this.body = body || {}; + this.headers = {}; + this.method = method; + this.query = query; + + // Store the headers in lower case. + Object.entries(headers).forEach(([header, value]) => { + this.headers[header.toLowerCase()] = value; + }); + + // Store additional properties of the request object passed in + Object.entries(otherOptions) + .filter(([property]) => !this[property]) + .forEach(([property, value]) => { + this[property] = value; + }); } - this.body = options.body || {}; - this.headers = {}; - this.method = options.method; - this.query = options.query; - - // Store the headers in lower case. - for (const field in options.headers) { - if (Object.prototype.hasOwnProperty.call(options.headers, field)) { - this.headers[field.toLowerCase()] = options.headers[field]; - } + /** + * Get a request header. + * @param {String} field + */ + get(field) { + return this.headers[field.toLowerCase()]; } - // Store additional properties of the request object passed in - for (const property in options) { - if (Object.prototype.hasOwnProperty.call(options, property) && !this[property]) { - this[property] = options[property]; - } + /** + * Check if the content-type matches any of the given mime types. + * @param {...String|Array} types + */ + is(...types) { + return typeis(this, types.flat()) || false; } } -/** - * Get a request header. - */ - -Request.prototype.get = function(field) { - return this.headers[field.toLowerCase()]; -}; - -/** - * Check if the content-type matches any of the given mime type. - */ - -Request.prototype.is = function(types) { - if (!Array.isArray(types)) { - types = [].slice.call(arguments); - } - - return typeis(this, types) || false; -}; - -/** - * Export constructor. - */ - module.exports = Request; diff --git a/lib/response-types/code-response-type.js b/lib/response-types/code-response-type.js index 8252248f..6311d22a 100644 --- a/lib/response-types/code-response-type.js +++ b/lib/response-types/code-response-type.js @@ -7,37 +7,27 @@ const InvalidArgumentError = require('../errors/invalid-argument-error'); const url = require('url'); -/** - * Constructor. - */ +class CodeResponseType { + constructor(code) { + if (!code) { + throw new InvalidArgumentError('Missing parameter: `code`'); + } -function CodeResponseType(code) { - if (!code) { - throw new InvalidArgumentError('Missing parameter: `code`'); + this.code = code; } - this.code = code; -} + buildRedirectUri(redirectUri) { + if (!redirectUri) { + throw new InvalidArgumentError('Missing parameter: `redirectUri`'); + } -/** - * Build redirect uri. - */ - -CodeResponseType.prototype.buildRedirectUri = function(redirectUri) { - if (!redirectUri) { - throw new InvalidArgumentError('Missing parameter: `redirectUri`'); - } + const uri = url.parse(redirectUri, true); - const uri = url.parse(redirectUri, true); + uri.query.code = this.code; + uri.search = null; - uri.query.code = this.code; - uri.search = null; - - return uri; -}; - -/** - * Export constructor. - */ + return uri; + } +} module.exports = CodeResponseType; diff --git a/lib/response-types/token-response-type.js b/lib/response-types/token-response-type.js index 29c32e70..cd6891b4 100644 --- a/lib/response-types/token-response-type.js +++ b/lib/response-types/token-response-type.js @@ -6,16 +6,10 @@ const ServerError = require('../errors/server-error'); -/** - * Constructor. - */ - -function TokenResponseType() { - throw new ServerError('Not implemented.'); +class TokenResponseType { + constructor() { + throw new ServerError('Not implemented.'); + } } -/** - * Export constructor. - */ - module.exports = TokenResponseType; diff --git a/lib/response.js b/lib/response.js index 29a2c517..23725963 100644 --- a/lib/response.js +++ b/lib/response.js @@ -1,58 +1,45 @@ 'use strict'; -/** - * Constructor. - */ - -function Response(options) { - options = options || {}; +class Response { + constructor({ headers = {}, body = {}, ...otherOptions } = {}) { + this.status = 200; + this.body = body; + this.headers = {}; + + // Store the headers in lower case. + Object.entries(headers).forEach(([header, value]) => { + this.headers[header.toLowerCase()] = value; + }); + + // Store additional properties of the response object passed in + Object.entries(otherOptions) + .filter(([property]) => !this[property]) + .forEach(([property, value]) => { + this[property] = value; + }); + } - this.body = options.body || {}; - this.headers = {}; - this.status = 200; + /** + * Get a response header. + */ + get(field) { + return this.headers[field.toLowerCase()]; + } - // Store the headers in lower case. - for (const field in options.headers) { - if (Object.prototype.hasOwnProperty.call(options.headers, field)) { - this.headers[field.toLowerCase()] = options.headers[field]; - } + /** + * Redirect response. + */ + redirect(url) { + this.set('Location', url); + this.status = 302; } - // Store additional properties of the response object passed in - for (const property in options) { - if (Object.prototype.hasOwnProperty.call(options, property) && !this[property]) { - this[property] = options[property]; - } + /** + * Set a response header. + */ + set(field, value) { + this.headers[field.toLowerCase()] = value; } } -/** - * Get a response header. - */ - -Response.prototype.get = function(field) { - return this.headers[field.toLowerCase()]; -}; - -/** - * Redirect response. - */ - -Response.prototype.redirect = function(url) { - this.set('Location', url); - this.status = 302; -}; - -/** - * Set a response header. - */ - -Response.prototype.set = function(field, value) { - this.headers[field.toLowerCase()] = value; -}; - -/** - * Export constructor. - */ - module.exports = Response; diff --git a/lib/server.js b/lib/server.js index 53bbd2aa..a2e31878 100644 --- a/lib/server.js +++ b/lib/server.js @@ -13,67 +13,59 @@ const TokenHandler = require('./handlers/token-handler'); * Constructor. */ -function OAuth2Server(options) { - options = options || {}; +class OAuth2Server { + constructor (options) { + options = options || {}; - if (!options.model) { - throw new InvalidArgumentError('Missing parameter: `model`'); - } + if (!options.model) { + throw new InvalidArgumentError('Missing parameter: `model`'); + } - this.options = options; -} + this.options = options; + } -/** + /** * Authenticate a token. */ -OAuth2Server.prototype.authenticate = function(request, response, options, callback) { - if (typeof options === 'string') { - options = {scope: options}; - } - - options = Object.assign({ - addAcceptedScopesHeader: true, - addAuthorizedScopesHeader: true, - allowBearerTokensInQueryString: false - }, this.options, options); + authenticate (request, response, options) { + options = Object.assign({ + addAcceptedScopesHeader: true, + addAuthorizedScopesHeader: true, + allowBearerTokensInQueryString: false + }, this.options, options); - return new AuthenticateHandler(options) - .handle(request, response) - .nodeify(callback); -}; + return new AuthenticateHandler(options).handle(request, response); + } -/** + /** * Authorize a request. */ -OAuth2Server.prototype.authorize = function(request, response, options, callback) { - options = Object.assign({ - allowEmptyState: false, - authorizationCodeLifetime: 5 * 60 // 5 minutes. - }, this.options, options); + authorize (request, response, options) { + options = Object.assign({ + allowEmptyState: false, + authorizationCodeLifetime: 5 * 60 // 5 minutes. + }, this.options, options); - return new AuthorizeHandler(options) - .handle(request, response) - .nodeify(callback); -}; + return new AuthorizeHandler(options).handle(request, response); + } -/** + /** * Create a token. */ -OAuth2Server.prototype.token = function(request, response, options, callback) { - options = Object.assign({ - accessTokenLifetime: 60 * 60, // 1 hour. - refreshTokenLifetime: 60 * 60 * 24 * 14, // 2 weeks. - allowExtendedTokenAttributes: false, - requireClientAuthentication: {} // defaults to true for all grant types - }, this.options, options); - - return new TokenHandler(options) - .handle(request, response) - .nodeify(callback); -}; + token (request, response, options) { + options = Object.assign({ + accessTokenLifetime: 60 * 60, // 1 hour. + refreshTokenLifetime: 60 * 60 * 24 * 14, // 2 weeks. + allowExtendedTokenAttributes: false, + requireClientAuthentication: {} // defaults to true for all grant types + }, this.options, options); + + return new TokenHandler(options).handle(request, response); + } +} /** * Export constructor. diff --git a/lib/token-types/bearer-token-type.js b/lib/token-types/bearer-token-type.js index 0bf526d0..02b73517 100644 --- a/lib/token-types/bearer-token-type.js +++ b/lib/token-types/bearer-token-type.js @@ -10,50 +10,52 @@ const InvalidArgumentError = require('../errors/invalid-argument-error'); * Constructor. */ -function BearerTokenType(accessToken, accessTokenLifetime, refreshToken, scope, customAttributes) { - if (!accessToken) { - throw new InvalidArgumentError('Missing parameter: `accessToken`'); - } +class BearerTokenType { + constructor(accessToken, accessTokenLifetime, refreshToken, scope, customAttributes) { + if (!accessToken) { + throw new InvalidArgumentError('Missing parameter: `accessToken`'); + } - this.accessToken = accessToken; - this.accessTokenLifetime = accessTokenLifetime; - this.refreshToken = refreshToken; - this.scope = scope; + this.accessToken = accessToken; + this.accessTokenLifetime = accessTokenLifetime; + this.refreshToken = refreshToken; + this.scope = scope; - if (customAttributes) { - this.customAttributes = customAttributes; + if (customAttributes) { + this.customAttributes = customAttributes; + } } -} -/** + /** * Retrieve the value representation. */ -BearerTokenType.prototype.valueOf = function() { - const object = { - access_token: this.accessToken, - token_type: 'Bearer' - }; + valueOf () { + const object = { + access_token: this.accessToken, + token_type: 'Bearer' + }; - if (this.accessTokenLifetime) { - object.expires_in = this.accessTokenLifetime; - } + if (this.accessTokenLifetime) { + object.expires_in = this.accessTokenLifetime; + } - if (this.refreshToken) { - object.refresh_token = this.refreshToken; - } + if (this.refreshToken) { + object.refresh_token = this.refreshToken; + } - if (this.scope) { - object.scope = this.scope; - } + if (this.scope) { + object.scope = this.scope; + } - for (const key in this.customAttributes) { - if ( Object.prototype.hasOwnProperty.call(this.customAttributes, key) ) { - object[key] = this.customAttributes[key]; + for (const key in this.customAttributes) { + if ( Object.prototype.hasOwnProperty.call(this.customAttributes, key) ) { + object[key] = this.customAttributes[key]; + } } + return object; } - return object; -}; +} /** * Export constructor. diff --git a/lib/token-types/mac-token-type.js b/lib/token-types/mac-token-type.js index a5dd240a..2d90fbe8 100644 --- a/lib/token-types/mac-token-type.js +++ b/lib/token-types/mac-token-type.js @@ -10,8 +10,10 @@ const ServerError = require('../errors/server-error'); * Constructor. */ -function MacTokenType() { - throw new ServerError('Not implemented.'); +class MacTokenType { + constructor() { + throw new ServerError('Not implemented.'); + } } /** diff --git a/lib/utils/date-util.js b/lib/utils/date-util.js new file mode 100644 index 00000000..4071a11f --- /dev/null +++ b/lib/utils/date-util.js @@ -0,0 +1,13 @@ +'use strict'; + +/** + * @param expiresAt {Date} The date at which something (e.g. a token) expires. + * @return {number} The number of seconds until the expiration date. + */ +function getLifetimeFromExpiresAt(expiresAt) { + return Math.floor((expiresAt - new Date()) / 1000); +} + +module.exports = { + getLifetimeFromExpiresAt, +}; diff --git a/lib/utils/scope-util.js b/lib/utils/scope-util.js new file mode 100644 index 00000000..61278587 --- /dev/null +++ b/lib/utils/scope-util.js @@ -0,0 +1,16 @@ +const isFormat = require('@node-oauth/formats'); +const InvalidScopeError = require('../errors/invalid-scope-error'); + +module.exports = { + parseScope: function (requestedScope) { + if (!isFormat.nqschar(requestedScope)) { + throw new InvalidScopeError('Invalid parameter: `scope`'); + } + + if (requestedScope == null) { + return undefined; + } + + return requestedScope.split(' '); + } +}; diff --git a/lib/utils/token-util.js b/lib/utils/token-util.js index 8626daca..a1d6937e 100644 --- a/lib/utils/token-util.js +++ b/lib/utils/token-util.js @@ -4,7 +4,7 @@ * Module dependencies. */ -const randomBytes = require('bluebird').promisify(require('crypto').randomBytes); +const randomBytes = require('crypto').randomBytes; const { createHash } = require('../utils/crypto-util'); /** @@ -17,10 +17,8 @@ module.exports = { * Generate random token. */ - generateRandomToken: function() { - return randomBytes(256).then(function(buffer) { - return createHash({ data: buffer, encoding: 'hex' }); - }); + generateRandomToken: async function() { + const buffer = randomBytes(256); + return createHash({ data: buffer, encoding: 'hex' }); } - }; diff --git a/package.json b/package.json index e95a0ce1..437c2476 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@node-oauth/oauth2-server", "description": "Complete, framework-agnostic, compliant and well tested module for implementing an OAuth2 Server in node.js", - "version": "4.3.0", + "version": "5.0.0", "keywords": [ "oauth", "oauth2" @@ -22,25 +22,24 @@ "files": [ "index.js", "index.d.ts", - "lib" + "lib", + "CHANGELOG.md" ], "dependencies": { "@node-oauth/formats": "1.0.0", "basic-auth": "2.0.1", - "bluebird": "3.7.2", - "promisify-any": "2.0.1", "type-is": "1.6.18" }, "devDependencies": { "chai": "4.3.7", - "eslint": "8.42.0", + "eslint": "8.46.0", "mocha": "10.2.0", "nyc": "15.1.0", - "sinon": "15.1.0" + "sinon": "15.2.0" }, "license": "MIT", "engines": { - "node": ">=14.0.0" + "node": ">=16.0.0" }, "scripts": { "pretest": "./node_modules/.bin/eslint lib test index.js", diff --git a/test/compliance/client-credential-workflow_test.js b/test/compliance/client-credential-workflow_test.js new file mode 100644 index 00000000..5e71d4ab --- /dev/null +++ b/test/compliance/client-credential-workflow_test.js @@ -0,0 +1,142 @@ +/** + * 4.4. Client Credentials Grant + * + * The client can request an access token using only its client + * credentials (or other supported means of authentication) when the + * client is requesting access to the protected resources under its + * control, or those of another resource owner that have been previously + * arranged with the authorization server (the method of which is beyond + * the scope of this specification). + * + * The client credentials grant type MUST only be used by confidential + * clients. + * + * @see https://www.rfc-editor.org/rfc/rfc6749#section-4.4 + */ + +const OAuth2Server = require('../..'); +const DB = require('../helpers/db'); +const createModel = require('../helpers/model'); +const createRequest = require('../helpers/request'); +const Response = require('../../lib/response'); + +require('chai').should(); + +const db = new DB(); +// this user represents requests in the name of an external server +// TODO: we should discuss, if we can make user optional for client credential workflows +// as it's not desired to have an extra fake-user representing a server just to pass validation +const userDoc = { id: 'machine2-123456789', name: 'machine2' }; +db.saveUser(userDoc); + +const oAuth2Server = new OAuth2Server({ + model: { + ...createModel(db), + getUserFromClient: async function (_client) { + // in a machine2machine setup we might not have a dedicated "user" + // but we need to return a truthy response to + const client = db.findClient(_client.id, _client.secret); + return client && { ...userDoc }; + } + } +}); + +const clientDoc = db.saveClient({ + id: 'client-credential-test-client', + secret: 'client-credential-test-secret', + grants: ['client_credentials'] +}); + +const enabledScope = 'read write'; + +describe('ClientCredentials Workflow Compliance (4.4)', function () { + describe('Access Token Request (4.4.1)', function () { + /** + * 4.4.2. Access Token Request + * + * The client makes a request to the token endpoint by adding the + * following parameters using the "application/x-www-form-urlencoded" + * format per Appendix B with a character encoding of UTF-8 in the HTTP + * request entity-body: + * + * grant_type + * REQUIRED. Value MUST be set to "client_credentials". + * + * scope + * OPTIONAL. The scope of the access request as described by + * Section 3.3. + * + * The client MUST authenticate with the authorization server as + * described in Section 3.2.1. + */ + it('authenticates the client with valid credentials', async function () { + const response = new Response(); + const request = createRequest({ + body: { + grant_type: 'client_credentials', + scope: enabledScope + }, + headers: { + 'authorization': 'Basic ' + Buffer.from(clientDoc.id + ':' + clientDoc.secret).toString('base64'), + 'content-type': 'application/x-www-form-urlencoded' + }, + method: 'POST', + }); + + const token = await oAuth2Server.token(request, response); + + response.status.should.equal(200); + response.headers.should.deep.equal( { 'cache-control': 'no-store', pragma: 'no-cache' }); + response.body.token_type.should.equal('Bearer'); + response.body.access_token.should.equal(token.accessToken); + response.body.expires_in.should.be.a('number'); + response.body.scope.should.eql(['read', 'write']); + ('refresh_token' in response.body).should.equal(false); + + token.accessToken.should.be.a('string'); + token.accessTokenExpiresAt.should.be.a('date'); + ('refreshToken' in token).should.equal(false); + ('refreshTokenExpiresAt' in token).should.equal(false); + token.scope.should.eql(['read', 'write']); + + db.accessTokens.has(token.accessToken).should.equal(true); + db.refreshTokens.has(token.refreshToken).should.equal(false); + }); + + /** + * 7. Accessing Protected Resources + * + * The client accesses protected resources by presenting the access + * token to the resource server. The resource server MUST validate the + * access token and ensure that it has not expired and that its scope + * covers the requested resource. The methods used by the resource + * server to validate the access token (as well as any error responses) + * are beyond the scope of this specification but generally involve an + * interaction or coordination between the resource server and the + * authorization server. + */ + it('enables an authenticated request using the access token', async function () { + const [accessToken] = [...db.accessTokens.entries()][0]; + const response = new Response(); + const request = createRequest({ + query: {}, + headers: { + 'authorization': `Bearer ${accessToken}` + }, + method: 'GET', + }); + + const token = await oAuth2Server.authenticate(request, response); + token.accessToken.should.equal(accessToken); + token.user.should.deep.equal(userDoc); + token.client.should.deep.equal(clientDoc); + token.scope.should.eql(['read', 'write']); + + response.status.should.equal(200); + // there should be no information in the response as it + // should only add information, if permission is denied + response.body.should.deep.equal({}); + response.headers.should.deep.equal({}); + }); + }); +}); diff --git a/test/compliance/password-grant-type_test.js b/test/compliance/password-grant-type_test.js index 7941d54f..c30e440d 100644 --- a/test/compliance/password-grant-type_test.js +++ b/test/compliance/password-grant-type_test.js @@ -101,13 +101,13 @@ describe('PasswordGrantType Compliance', function () { response.body.access_token.should.equal(token.accessToken); response.body.refresh_token.should.equal(token.refreshToken); response.body.expires_in.should.be.a('number'); - response.body.scope.should.equal(scope); + response.body.scope.should.eql(['read', 'write']); token.accessToken.should.be.a('string'); token.refreshToken.should.be.a('string'); token.accessTokenExpiresAt.should.be.a('date'); token.refreshTokenExpiresAt.should.be.a('date'); - token.scope.should.equal(scope); + token.scope.should.eql(['read', 'write']); db.accessTokens.has(token.accessToken).should.equal(true); db.refreshTokens.has(token.refreshToken).should.equal(true); @@ -134,7 +134,7 @@ describe('PasswordGrantType Compliance', function () { authenticationResponse, {}); - authenticated.scope.should.equal(scope); + authenticated.scope.should.eql(['read', 'write']); authenticated.user.should.be.an('object'); authenticated.client.should.be.an('object'); }); diff --git a/test/compliance/refresh-token-grant-type_test.js b/test/compliance/refresh-token-grant-type_test.js index b01fef3d..09427855 100644 --- a/test/compliance/refresh-token-grant-type_test.js +++ b/test/compliance/refresh-token-grant-type_test.js @@ -62,6 +62,7 @@ const DB = require('../helpers/db'); const createModel = require('../helpers/model'); const createRequest = require('../helpers/request'); const Response = require('../../lib/response'); +const should = require('chai').should(); require('chai').should(); @@ -123,13 +124,13 @@ describe('RefreshTokenGrantType Compliance', function () { refreshResponse.body.access_token.should.equal(token.accessToken); refreshResponse.body.refresh_token.should.equal(token.refreshToken); refreshResponse.body.expires_in.should.be.a('number'); - refreshResponse.body.scope.should.equal(scope); + refreshResponse.body.scope.should.eql(['read', 'write']); token.accessToken.should.be.a('string'); token.refreshToken.should.be.a('string'); token.accessTokenExpiresAt.should.be.a('date'); token.refreshTokenExpiresAt.should.be.a('date'); - token.scope.should.equal(scope); + token.scope.should.eql(['read', 'write']); db.accessTokens.has(token.accessToken).should.equal(true); db.refreshTokens.has(token.refreshToken).should.equal(true); @@ -147,27 +148,82 @@ describe('RefreshTokenGrantType Compliance', function () { }); }); - // TODO: test refresh token with different scopes - // https://github.com/node-oauth/node-oauth2-server/issues/104 + it('Should throw invalid_scope error', async function () { + const request = createLoginRequest(); + const response = new Response({}); - // it('Should throw invalid_scope error', async function () { - // const request = createLoginRequest(); - // const response = new Response({}); + const credentials = await auth.token(request, response, {}); - // const credentials = await auth.token(request, response, {}); + const refreshRequest = createRefreshRequest(credentials.refreshToken); + const refreshResponse = new Response({}); - // const refreshRequest = createRefreshRequest(credentials.refreshToken); - // const refreshResponse = new Response({}); + refreshRequest.body.scope = 'invalid'; - // refreshRequest.scope = 'invalid'; + await auth.token(refreshRequest, refreshResponse, {}) + .then(should.fail) + .catch(err => { + err.name.should.equal('invalid_scope'); + }); + }); + + it('Should throw error if requested scope is greater than original scope', async function () { + const request = createLoginRequest(); + const response = new Response({}); + + request.body.scope = 'read'; + + const credentials = await auth.token(request, response, {}); - // await auth.token(refreshRequest, refreshResponse, {}) - // .then(() => { - // throw Error('Should not reach this'); - // }) - // .catch(err => { - // err.name.should.equal('invalid_scope'); - // }); - // }); + const refreshRequest = createRefreshRequest(credentials.refreshToken); + const refreshResponse = new Response({}); + + refreshRequest.scope = 'read write'; + + await auth.token(refreshRequest, refreshResponse, {}) + .then(should.fail) + .catch(err => { + err.name.should.equal('invalid_scope'); + }); + }); + + it('Should throw error if a scope is requested without a previous scope', async function () { + const request = createLoginRequest(); + const response = new Response({}); + + delete request.body.scope; + + const credentials = await auth.token(request, response, {}); + + const refreshRequest = createRefreshRequest(credentials.refreshToken); + const refreshResponse = new Response({}); + + refreshRequest.scope = 'read write'; + + await auth.token(refreshRequest, refreshResponse, {}) + .then(should.fail) + .catch(err => { + err.name.should.equal('invalid_scope'); + }); + }); + + it('Should create refresh token with smaller scope', async function () { + const request = createLoginRequest(); + const response = new Response({}); + + const credentials = await auth.token(request, response, {}); + + const refreshRequest = createRefreshRequest(credentials.refreshToken); + const refreshResponse = new Response({}); + + refreshRequest.body.scope = 'read'; + + const token = await auth.token(refreshRequest, refreshResponse, {}); + + refreshResponse.body.token_type.should.equal('Bearer'); + refreshResponse.body.access_token.should.equal(token.accessToken); + refreshResponse.body.refresh_token.should.equal(token.refreshToken); + refreshResponse.body.expires_in.should.be.a('number'); + refreshResponse.body.scope.should.eql(['read']); + }); }); }); diff --git a/test/helpers/model.js b/test/helpers/model.js index 7a1893b1..6566f0cd 100644 --- a/test/helpers/model.js +++ b/test/helpers/model.js @@ -71,11 +71,7 @@ function createModel (db) { } async function verifyScope (token, scope) { - if (typeof scope === 'string') { - return scopes.includes(scope); - } else { - return scope.every(s => scopes.includes(s)); - } + return scope.every(s => scopes.includes(s)); } return { diff --git a/test/integration/grant-types/abstract-grant-type_test.js b/test/integration/grant-types/abstract-grant-type_test.js index a6c4d2be..d48c1ee0 100644 --- a/test/integration/grant-types/abstract-grant-type_test.js +++ b/test/integration/grant-types/abstract-grant-type_test.js @@ -6,8 +6,8 @@ const AbstractGrantType = require('../../../lib/grant-types/abstract-grant-type'); const InvalidArgumentError = require('../../../lib/errors/invalid-argument-error'); -const Promise = require('bluebird'); const Request = require('../../../lib/request'); +const InvalidScopeError = require('../../../lib/errors/invalid-scope-error'); const should = require('chai').should(); /** @@ -45,7 +45,7 @@ describe('AbstractGrantType integration', function() { }); it('should set the `model`', function() { - const model = {}; + const model = { async generateAccessToken () {} }; const grantType = new AbstractGrantType({ accessTokenLifetime: 123, model: model }); grantType.model.should.equal(model); @@ -59,70 +59,62 @@ describe('AbstractGrantType integration', function() { }); describe('generateAccessToken()', function() { - it('should return an access token', function() { + it('should return an access token', async function() { const handler = new AbstractGrantType({ accessTokenLifetime: 123, model: {}, refreshTokenLifetime: 456 }); - - return handler.generateAccessToken() - .then(function(data) { - data.should.be.a.sha256(); - }) - .catch(should.fail); + const accessToken = await handler.generateAccessToken(); + accessToken.should.be.a.sha256(); }); - it('should support promises', function() { + it('should support promises', async function() { const model = { - generateAccessToken: function() { - return Promise.resolve({}); + generateAccessToken: async function() { + return 'long-hash-foo-bar'; } }; const handler = new AbstractGrantType({ accessTokenLifetime: 123, model: model, refreshTokenLifetime: 456 }); - - handler.generateAccessToken().should.be.an.instanceOf(Promise); + const accessToken = await handler.generateAccessToken(); + accessToken.should.equal('long-hash-foo-bar'); }); - it('should support non-promises', function() { + it('should support non-promises', async function() { const model = { generateAccessToken: function() { - return {}; + return 'long-hash-foo-bar'; } }; const handler = new AbstractGrantType({ accessTokenLifetime: 123, model: model, refreshTokenLifetime: 456 }); - - handler.generateAccessToken().should.be.an.instanceOf(Promise); + const accessToken = await handler.generateAccessToken(); + accessToken.should.equal('long-hash-foo-bar'); }); }); describe('generateRefreshToken()', function() { - it('should return a refresh token', function() { + it('should return a refresh token', async function() { const handler = new AbstractGrantType({ accessTokenLifetime: 123, model: {}, refreshTokenLifetime: 456 }); - - return handler.generateRefreshToken() - .then(function(data) { - data.should.be.a.sha256(); - }) - .catch(should.fail); + const refreshToken = await handler.generateRefreshToken(); + refreshToken.should.be.a.sha256(); }); - it('should support promises', function() { + it('should support promises', async function() { const model = { - generateRefreshToken: function() { - return Promise.resolve({}); + generateRefreshToken: async function() { + return 'long-hash-foo-bar'; } }; const handler = new AbstractGrantType({ accessTokenLifetime: 123, model: model, refreshTokenLifetime: 456 }); - - handler.generateRefreshToken().should.be.an.instanceOf(Promise); + const refreshToken = await handler.generateRefreshToken(); + refreshToken.should.equal('long-hash-foo-bar'); }); - it('should support non-promises', function() { + it('should support non-promises', async function() { const model = { generateRefreshToken: function() { - return {}; + return 'long-hash-foo-bar'; } }; const handler = new AbstractGrantType({ accessTokenLifetime: 123, model: model, refreshTokenLifetime: 456 }); - - handler.generateRefreshToken().should.be.an.instanceOf(Promise); + const refreshToken = await handler.generateRefreshToken(); + refreshToken.should.equal('long-hash-foo-bar'); }); }); @@ -152,7 +144,7 @@ describe('AbstractGrantType integration', function() { should.fail(); } catch (e) { - e.should.be.an.instanceOf(InvalidArgumentError); + e.should.be.an.instanceOf(InvalidScopeError); e.message.should.equal('Invalid parameter: `scope`'); } }); @@ -168,7 +160,67 @@ describe('AbstractGrantType integration', function() { const handler = new AbstractGrantType({ accessTokenLifetime: 123, model: {}, refreshTokenLifetime: 456 }); const request = new Request({ body: { scope: 'foo' }, headers: {}, method: {}, query: {} }); - handler.getScope(request).should.equal('foo'); + handler.getScope(request).should.eql(['foo']); + }); + }); + + describe('validateScope()', function () { + it('accepts the scope, if the model does not implement it', async function () { + const scope = ['some,scope,this,that']; + const user = { id: 123 }; + const client = { id: 456 }; + const handler = new AbstractGrantType({ accessTokenLifetime: 123, model: {}, refreshTokenLifetime: 456 }); + const validated = await handler.validateScope(user, client, scope); + validated.should.eql(scope); + }); + + it('accepts the scope, if the model accepts it', async function () { + const scope = ['some,scope,this,that']; + const user = { id: 123 }; + const client = { id: 456 }; + + const model = { + async validateScope (_user, _client, _scope) { + // make sure the model received the correct args + _user.should.deep.equal(user); + _client.should.deep.equal(_client); + _scope.should.eql(scope); + + return scope; + } + }; + const handler = new AbstractGrantType({ accessTokenLifetime: 123, model, refreshTokenLifetime: 456 }); + const validated = await handler.validateScope(user, client, scope); + validated.should.eql(scope); + }); + + it('throws if the model rejects the scope', async function () { + const scope = ['some,scope,this,that']; + const user = { id: 123 }; + const client = { id: 456 }; + const returnTypes = [undefined, null, false, 0, '']; + + for (const type of returnTypes) { + const model = { + async validateScope (_user, _client, _scope) { + // make sure the model received the correct args + _user.should.deep.equal(user); + _client.should.deep.equal(_client); + _scope.should.eql(scope); + + return type; + } + }; + const handler = new AbstractGrantType({ accessTokenLifetime: 123, model, refreshTokenLifetime: 456 }); + + try { + await handler.validateScope(user, client, scope); + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(InvalidScopeError); + e.message.should.equal('Invalid scope: Requested scope is invalid'); + } + } }); }); }); diff --git a/test/integration/grant-types/authorization-code-grant-type_test.js b/test/integration/grant-types/authorization-code-grant-type_test.js index 6cddd53f..d705f397 100644 --- a/test/integration/grant-types/authorization-code-grant-type_test.js +++ b/test/integration/grant-types/authorization-code-grant-type_test.js @@ -8,7 +8,6 @@ const AuthorizationCodeGrantType = require('../../../lib/grant-types/authorizati const InvalidArgumentError = require('../../../lib/errors/invalid-argument-error'); const InvalidGrantError = require('../../../lib/errors/invalid-grant-error'); const InvalidRequestError = require('../../../lib/errors/invalid-request-error'); -const Promise = require('bluebird'); const Request = require('../../../lib/request'); const ServerError = require('../../../lib/errors/server-error'); const should = require('chai').should(); @@ -74,48 +73,49 @@ describe('AuthorizationCodeGrantType integration', function() { }); describe('handle()', function() { - it('should throw an error if `request` is missing', function() { + it('should throw an error if `request` is missing', async function() { const model = { - getAuthorizationCode: function() {}, - revokeAuthorizationCode: function() {}, - saveToken: function() {} + getAuthorizationCode: () => should.fail(), + revokeAuthorizationCode: () => should.fail(), + saveToken: () => should.fail() }; const grantType = new AuthorizationCodeGrantType({ accessTokenLifetime: 123, model: model }); try { - grantType.handle(); - - should.fail(); + await grantType.handle(); } catch (e) { e.should.be.an.instanceOf(InvalidArgumentError); e.message.should.equal('Missing parameter: `request`'); } }); - - it('should throw an error if `client` is invalid', function() { - const client = {}; + + it('should throw an error if `client` is invalid (not in code)', async function() { + const client = { id: 1234 }; const model = { - getAuthorizationCode: function() { return { authorizationCode: 12345, expiresAt: new Date(new Date() * 2), user: {} }; }, - revokeAuthorizationCode: function() {}, - saveToken: function() {} + getAuthorizationCode: function(code) { + code.should.equal(123456789); + return { authorizationCode: 12345, expiresAt: new Date(new Date() * 2), user: {} }; + }, + revokeAuthorizationCode: () => should.fail(), + saveToken: () => should.fail() }; const grantType = new AuthorizationCodeGrantType({ accessTokenLifetime: 123, model: model }); - const request = new Request({ body: { code: 12345 }, headers: {}, method: {}, query: {} }); + const request = new Request({ body: { code: 123456789 }, headers: {}, method: {}, query: {} }); - return grantType.handle(request, client) - .then(should.fail) - .catch(function(e) { - e.should.be.an.instanceOf(ServerError); - e.message.should.equal('Server error: `getAuthorizationCode()` did not return a `client` object'); - }); + try { + await grantType.handle(request, client); + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(ServerError); + e.message.should.equal('Server error: `getAuthorizationCode()` did not return a `client` object'); + } }); it('should throw an error if `client` is missing', function() { - const model = { - getAuthorizationCode: function() { return { authorizationCode: 12345, expiresAt: new Date(new Date() * 2), user: {} }; }, - revokeAuthorizationCode: function() {}, - saveToken: function() {} + getAuthorizationCode: () => should.fail(), + revokeAuthorizationCode: () => should.fail(), + saveToken: () => should.fail() }; const grantType = new AuthorizationCodeGrantType({ accessTokenLifetime: 123, model: model }); const request = new Request({ body: { code: 12345 }, headers: {}, method: {}, query: {} }); @@ -129,29 +129,72 @@ describe('AuthorizationCodeGrantType integration', function() { } }); - it('should return a token', function() { + it('should return a token', async function() { const client = { id: 'foobar' }; - const token = {}; + const scope = ['fooscope']; + const user = { name: 'foouser' }; + const codeDoc = { + authorizationCode: 12345, + expiresAt: new Date(new Date() * 2), + client, + user, + scope + }; const model = { - getAuthorizationCode: function() { return { authorizationCode: 12345, client: { id: 'foobar' }, expiresAt: new Date(new Date() * 2), user: {} }; }, - revokeAuthorizationCode: function() { return true; }, - saveToken: function() { return token; }, - validateScope: function() { return 'foo'; } + getAuthorizationCode: async function (code) { + code.should.equal('code-1234'); + + return codeDoc; + }, + revokeAuthorizationCode: async function (_codeDoc) { + _codeDoc.should.deep.equal(codeDoc); + return true; + }, + validateScope: async function (_user, _client, _scope) { + _user.should.deep.equal(user); + _client.should.deep.equal(client); + _scope.should.eql(scope); + return scope; + }, + generateAccessToken: async function (_client, _user, _scope) { + _user.should.deep.equal(user); + _client.should.deep.equal(client); + _scope.should.eql(scope); + return 'long-access-token-hash'; + }, + generateRefreshToken: async function (_client, _user, _scope) { + _user.should.deep.equal(user); + _client.should.deep.equal(client); + _scope.should.eql(scope); + return 'long-refresh-token-hash'; + }, + saveToken: async function (_token, _client, _user) { + _user.should.deep.equal(user); + _client.should.deep.equal(client); + _token.accessToken.should.equal('long-access-token-hash'); + _token.refreshToken.should.equal('long-refresh-token-hash'); + _token.authorizationCode.should.equal(codeDoc.authorizationCode); + _token.accessTokenExpiresAt.should.be.instanceOf(Date); + _token.refreshTokenExpiresAt.should.be.instanceOf(Date); + return _token; + }, }; + const grantType = new AuthorizationCodeGrantType({ accessTokenLifetime: 123, model: model }); - const request = new Request({ body: { code: 12345 }, headers: {}, method: {}, query: {} }); + const request = new Request({ body: { code: 'code-1234' }, headers: {}, method: {}, query: {} }); - return grantType.handle(request, client) - .then(function(data) { - data.should.equal(token); - }) - .catch(should.fail); + const token = await grantType.handle(request, client); + token.accessToken.should.equal('long-access-token-hash'); + token.refreshToken.should.equal('long-refresh-token-hash'); + token.authorizationCode.should.equal(codeDoc.authorizationCode); + token.accessTokenExpiresAt.should.be.instanceOf(Date); + token.refreshTokenExpiresAt.should.be.instanceOf(Date); }); it('should support promises', function() { const client = { id: 'foobar' }; const model = { - getAuthorizationCode: function() { return Promise.resolve({ authorizationCode: 12345, client: { id: 'foobar' }, expiresAt: new Date(new Date() * 2), user: {} }); }, + getAuthorizationCode: function() { return { authorizationCode: 12345, client: { id: 'foobar' }, expiresAt: new Date(new Date() * 2), user: {} }; }, revokeAuthorizationCode: function() { return true; }, saveToken: function() {} }; @@ -173,55 +216,39 @@ describe('AuthorizationCodeGrantType integration', function() { grantType.handle(request, client).should.be.an.instanceOf(Promise); }); - - it('should support callbacks', function() { - const client = { id: 'foobar' }; - const model = { - getAuthorizationCode: function(code, callback) { callback(null, { authorizationCode: 12345, client: { id: 'foobar' }, expiresAt: new Date(new Date() * 2), user: {} }); }, - revokeAuthorizationCode: function(code, callback) { callback(null, { authorizationCode: 12345, client: { id: 'foobar' }, expiresAt: new Date(new Date() / 2), user: {} }); }, - saveToken: function(tokenToSave, client, user, callback) { callback(null, tokenToSave); } - }; - const grantType = new AuthorizationCodeGrantType({ accessTokenLifetime: 123, model: model }); - const request = new Request({ body: { code: 12345 }, headers: {}, method: {}, query: {} }); - - grantType.handle(request, client).should.be.an.instanceOf(Promise); - }); }); describe('getAuthorizationCode()', function() { - it('should throw an error if the request body does not contain `code`', function() { + it('should throw an error if the request body does not contain `code`', async function() { const client = {}; const model = { - getAuthorizationCode: function() {}, - revokeAuthorizationCode: function() {}, - saveToken: function() {} + getAuthorizationCode: () => should.fail(), + revokeAuthorizationCode: () => should.fail(), + saveToken: () => should.fail() }; const grantType = new AuthorizationCodeGrantType({ accessTokenLifetime: 123, model: model }); const request = new Request({ body: {}, headers: {}, method: {}, query: {} }); try { - grantType.getAuthorizationCode(request, client); - - should.fail(); + await grantType.getAuthorizationCode(request, client); } catch (e) { e.should.be.an.instanceOf(InvalidRequestError); e.message.should.equal('Missing parameter: `code`'); } }); - it('should throw an error if `code` is invalid', function() { + it('should throw an error if `code` is invalid', async function() { const client = {}; const model = { - getAuthorizationCode: function() {}, - revokeAuthorizationCode: function() {}, - saveToken: function() {} + getAuthorizationCode: () => should.fail(), + revokeAuthorizationCode: () => should.fail(), + saveToken: () => should.fail() }; const grantType = new AuthorizationCodeGrantType({ accessTokenLifetime: 123, model: model }); const request = new Request({ body: { code: 'øå€£‰' }, headers: {}, method: {}, query: {} }); try { - grantType.getAuthorizationCode(request, client); - + await grantType.getAuthorizationCode(request, client); should.fail(); } catch (e) { e.should.be.an.instanceOf(InvalidRequestError); @@ -229,161 +256,176 @@ describe('AuthorizationCodeGrantType integration', function() { } }); - it('should throw an error if `authorizationCode` is missing', function() { + it('should throw an error if `authorizationCode` is missing', async function() { const client = {}; const model = { - getAuthorizationCode: function() {}, - revokeAuthorizationCode: function() {}, - saveToken: function() {} + getAuthorizationCode: async function() {}, + revokeAuthorizationCode: () => should.fail(), + saveToken: () => should.fail() }; const grantType = new AuthorizationCodeGrantType({ accessTokenLifetime: 123, model: model }); const request = new Request({ body: { code: 12345 }, headers: {}, method: {}, query: {} }); - return grantType.getAuthorizationCode(request, client) - .then(should.fail) - .catch(function(e) { - e.should.be.an.instanceOf(InvalidGrantError); - e.message.should.equal('Invalid grant: authorization code is invalid'); - }); + try { + await grantType.getAuthorizationCode(request, client); + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(InvalidGrantError); + e.message.should.equal('Invalid grant: authorization code is invalid'); + } }); - it('should throw an error if `authorizationCode.client` is missing', function() { + it('should throw an error if `authorizationCode.client` is missing', async function() { const client = {}; const model = { - getAuthorizationCode: function() { return { authorizationCode: 12345 }; }, - revokeAuthorizationCode: function() {}, - saveToken: function() {} + getAuthorizationCode: async function() { return { authorizationCode: 12345 }; }, + revokeAuthorizationCode: () => should.fail(), + saveToken: () => should.fail() }; const grantType = new AuthorizationCodeGrantType({ accessTokenLifetime: 123, model: model }); const request = new Request({ body: { code: 12345 }, headers: {}, method: {}, query: {} }); - return grantType.getAuthorizationCode(request, client) - .then(should.fail) - .catch(function(e) { - e.should.be.an.instanceOf(ServerError); - e.message.should.equal('Server error: `getAuthorizationCode()` did not return a `client` object'); - }); + try { + await grantType.getAuthorizationCode(request, client); + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(ServerError); + e.message.should.equal('Server error: `getAuthorizationCode()` did not return a `client` object'); + } }); - it('should throw an error if `authorizationCode.expiresAt` is missing', function() { + it('should throw an error if `authorizationCode.expiresAt` is missing', async function() { const client = {}; const model = { - getAuthorizationCode: function() { return { authorizationCode: 12345, client: {}, user: {} }; }, - revokeAuthorizationCode: function() {}, - saveToken: function() {} + getAuthorizationCode: async function() { + return { authorizationCode: 12345, client: {}, user: {} }; + }, + revokeAuthorizationCode: () => should.fail(), + saveToken: () => should.fail() }; const grantType = new AuthorizationCodeGrantType({ accessTokenLifetime: 123, model: model }); const request = new Request({ body: { code: 12345 }, headers: {}, method: {}, query: {} }); - return grantType.getAuthorizationCode(request, client) - .then(should.fail) - .catch(function(e) { - e.should.be.an.instanceOf(ServerError); - e.message.should.equal('Server error: `expiresAt` must be a Date instance'); - }); + try { + await grantType.getAuthorizationCode(request, client); + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(ServerError); + e.message.should.equal('Server error: `expiresAt` must be a Date instance'); + } }); - it('should throw an error if `authorizationCode.user` is missing', function() { + it('should throw an error if `authorizationCode.user` is missing', async function() { const client = {}; const model = { - getAuthorizationCode: function() { return { authorizationCode: 12345, client: {}, expiresAt: new Date() }; }, - revokeAuthorizationCode: function() {}, - saveToken: function() {} + getAuthorizationCode: async function() { + return { authorizationCode: 12345, client: {}, expiresAt: new Date() }; + }, + revokeAuthorizationCode: () => should.fail(), + saveToken: () => should.fail() }; const grantType = new AuthorizationCodeGrantType({ accessTokenLifetime: 123, model: model }); const request = new Request({ body: { code: 12345 }, headers: {}, method: {}, query: {} }); - return grantType.getAuthorizationCode(request, client) - .then(should.fail) - .catch(function(e) { - e.should.be.an.instanceOf(ServerError); - e.message.should.equal('Server error: `getAuthorizationCode()` did not return a `user` object'); - }); + try { + await grantType.getAuthorizationCode(request, client); + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(ServerError); + e.message.should.equal('Server error: `getAuthorizationCode()` did not return a `user` object'); + } }); - it('should throw an error if the client id does not match', function() { + it('should throw an error if the client id does not match', async function() { const client = { id: 123 }; const model = { - getAuthorizationCode: function() { + getAuthorizationCode: async function() { return { authorizationCode: 12345, expiresAt: new Date(), client: { id: 456 }, user: {} }; }, - revokeAuthorizationCode: function() {}, - saveToken: function() {} + revokeAuthorizationCode: () => should.fail(), + saveToken: () => should.fail() }; const grantType = new AuthorizationCodeGrantType({ accessTokenLifetime: 123, model: model }); const request = new Request({ body: { code: 12345 }, headers: {}, method: {}, query: {} }); - return grantType.getAuthorizationCode(request, client) - .then(should.fail) - .catch(function(e) { - e.should.be.an.instanceOf(InvalidGrantError); - e.message.should.equal('Invalid grant: authorization code is invalid'); - }); + try { + await grantType.getAuthorizationCode(request, client); + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(InvalidGrantError); + e.message.should.equal('Invalid grant: authorization code is invalid'); + } }); - it('should throw an error if the auth code is expired', function() { + it('should throw an error if the auth code is expired', async function() { const client = { id: 123 }; const date = new Date(new Date() / 2); const model = { - getAuthorizationCode: function() { + getAuthorizationCode: async function() { return { authorizationCode: 12345, client: { id: 123 }, expiresAt: date, user: {} }; }, - revokeAuthorizationCode: function() {}, - saveToken: function() {} + revokeAuthorizationCode: () => should.fail(), + saveToken: () => should.fail() }; const grantType = new AuthorizationCodeGrantType({ accessTokenLifetime: 123, model: model }); const request = new Request({ body: { code: 12345 }, headers: {}, method: {}, query: {} }); - return grantType.getAuthorizationCode(request, client) - .then(should.fail) - .catch(function(e) { - e.should.be.an.instanceOf(InvalidGrantError); - e.message.should.equal('Invalid grant: authorization code has expired'); - }); + try { + await grantType.getAuthorizationCode(request, client); + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(InvalidGrantError); + e.message.should.equal('Invalid grant: authorization code has expired'); + } }); - it('should throw an error if the `redirectUri` is invalid', function() { + it('should throw an error if the `redirectUri` is invalid (format)', async function() { const authorizationCode = { authorizationCode: 12345, client: { id: 'foobar' }, expiresAt: new Date(new Date() * 2), redirectUri: 'foobar', user: {} }; const client = { id: 'foobar' }; const model = { - getAuthorizationCode: function() { return authorizationCode; }, - revokeAuthorizationCode: function() {}, - saveToken: function() {} + getAuthorizationCode: async function() { return authorizationCode; }, + revokeAuthorizationCode: () => should.fail(), + saveToken: () => should.fail() }; const grantType = new AuthorizationCodeGrantType({ accessTokenLifetime: 123, model: model }); const request = new Request({ body: { code: 12345 }, headers: {}, method: {}, query: {} }); - return grantType.getAuthorizationCode(request, client) - .then(should.fail) - .catch(function(e) { - e.should.be.an.instanceOf(InvalidGrantError); - e.message.should.equal('Invalid grant: `redirect_uri` is not a valid URI'); - }); + try { + await grantType.getAuthorizationCode(request, client); + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(InvalidGrantError); + e.message.should.equal('Invalid grant: `redirect_uri` is not a valid URI'); + } }); - it('should return an auth code', function() { - const authorizationCode = { authorizationCode: 12345, client: { id: 'foobar' }, expiresAt: new Date(new Date() * 2), user: {} }; + it('should return an auth code', async function() { + const authorizationCode = { + authorizationCode: 1234567, + client: { id: 'foobar' }, + expiresAt: new Date(new Date() * 2), user: {} + }; const client = { id: 'foobar' }; const model = { - getAuthorizationCode: function() { return authorizationCode; }, - revokeAuthorizationCode: function() {}, - saveToken: function() {} + getAuthorizationCode: async function(_code) { + _code.should.equal(12345); + return authorizationCode; + }, + revokeAuthorizationCode: () => should.fail(), + saveToken: () => should.fail() }; const grantType = new AuthorizationCodeGrantType({ accessTokenLifetime: 123, model: model }); const request = new Request({ body: { code: 12345 }, headers: {}, method: {}, query: {} }); - return grantType.getAuthorizationCode(request, client) - .then(function(data) { - data.should.equal(authorizationCode); - }) - .catch(should.fail); + const code = await grantType.getAuthorizationCode(request, client); + code.should.deep.equal(authorizationCode); }); it('should support promises', function() { const authorizationCode = { authorizationCode: 12345, client: { id: 'foobar' }, expiresAt: new Date(new Date() * 2), user: {} }; const client = { id: 'foobar' }; const model = { - getAuthorizationCode: function() { return Promise.resolve(authorizationCode); }, + getAuthorizationCode: async function() { return authorizationCode; }, revokeAuthorizationCode: function() {}, saveToken: function() {} }; @@ -406,20 +448,6 @@ describe('AuthorizationCodeGrantType integration', function() { grantType.getAuthorizationCode(request, client).should.be.an.instanceOf(Promise); }); - - it('should support callbacks', function() { - const authorizationCode = { authorizationCode: 12345, client: { id: 'foobar' }, expiresAt: new Date(new Date() * 2), user: {} }; - const client = { id: 'foobar' }; - const model = { - getAuthorizationCode: function(code, callback) { callback(null, authorizationCode); }, - revokeAuthorizationCode: function() {}, - saveToken: function() {} - }; - const grantType = new AuthorizationCodeGrantType({ accessTokenLifetime: 123, model: model }); - const request = new Request({ body: { code: 12345 }, headers: {}, method: {}, query: {} }); - - grantType.getAuthorizationCode(request, client).should.be.an.instanceOf(Promise); - }); }); describe('validateRedirectUri()', function() { @@ -462,97 +490,113 @@ describe('AuthorizationCodeGrantType integration', function() { e.message.should.equal('Invalid request: `redirect_uri` is invalid'); } }); - }); - - describe('revokeAuthorizationCode()', function() { - it('should revoke the auth code', function() { - const authorizationCode = { authorizationCode: 12345, client: {}, expiresAt: new Date(new Date() / 2), user: {} }; + it('returns undefined and does not throw if `redirectUri` is valid', async function () { + const authorizationCode = { authorizationCode: 12345, client: {}, expiresAt: new Date(new Date() / 2), redirectUri: 'http://foo.bar', user: {} }; const model = { getAuthorizationCode: function() {}, revokeAuthorizationCode: function() { return true; }, saveToken: function() {} }; const grantType = new AuthorizationCodeGrantType({ accessTokenLifetime: 123, model: model }); - - return grantType.revokeAuthorizationCode(authorizationCode) - .then(function(data) { - data.should.equal(authorizationCode); - }) - .catch(should.fail); + const request = new Request({ body: { code: 12345, redirect_uri: 'http://foo.bar' }, headers: {}, method: {}, query: {} }); + const value = grantType.validateRedirectUri(request, authorizationCode); + const isUndefined = value === undefined; + isUndefined.should.equal(true); }); + }); - it('should throw an error when the auth code is invalid', function() { + describe('revokeAuthorizationCode()', function() { + it('should revoke the auth code', async function() { const authorizationCode = { authorizationCode: 12345, client: {}, expiresAt: new Date(new Date() / 2), user: {} }; const model = { - getAuthorizationCode: function() {}, - revokeAuthorizationCode: function() { return false; }, - saveToken: function() {} + getAuthorizationCode: () => should.fail(), + revokeAuthorizationCode: async function(_code) { + _code.should.equal(authorizationCode); + return true; + }, + saveToken: () => should.fail() }; const grantType = new AuthorizationCodeGrantType({ accessTokenLifetime: 123, model: model }); - return grantType.revokeAuthorizationCode(authorizationCode) - .then(function(data) { - data.should.equal(authorizationCode); - }) - .catch(function(e) { + const data = await grantType.revokeAuthorizationCode(authorizationCode); + data.should.deep.equal(authorizationCode); + }); + + it('should throw an error when the auth code is invalid', async function() { + const authorizationCode = { authorizationCode: 12345, client: {}, expiresAt: new Date(new Date() / 2), user: {} }; + const returnTypes = [false, null, undefined, 0, '']; + + for (const type of returnTypes) { + const model = { + getAuthorizationCode: () => should.fail(), + revokeAuthorizationCode: async function(_code) { + _code.should.equal(authorizationCode); + return type; + }, + saveToken: () => should.fail() + }; + const grantType = new AuthorizationCodeGrantType({ accessTokenLifetime: 123, model: model }); + + try { + await grantType.revokeAuthorizationCode(authorizationCode); + should.fail(); + } catch (e) { e.should.be.an.instanceOf(InvalidGrantError); e.message.should.equal('Invalid grant: authorization code is invalid'); - }); + } + } }); it('should support promises', function() { const authorizationCode = { authorizationCode: 12345, client: {}, expiresAt: new Date(new Date() / 2), user: {} }; const model = { - getAuthorizationCode: function() {}, - revokeAuthorizationCode: function() { return Promise.resolve(true); }, - saveToken: function() {} + getAuthorizationCode: () => should.fail(), + revokeAuthorizationCode: async function() { return true; }, + saveToken: () => should.fail() }; const grantType = new AuthorizationCodeGrantType({ accessTokenLifetime: 123, model: model }); - grantType.revokeAuthorizationCode(authorizationCode).should.be.an.instanceOf(Promise); }); it('should support non-promises', function() { const authorizationCode = { authorizationCode: 12345, client: {}, expiresAt: new Date(new Date() / 2), user: {} }; const model = { - getAuthorizationCode: function() {}, + getAuthorizationCode: () => should.fail(), revokeAuthorizationCode: function() { return authorizationCode; }, - saveToken: function() {} - }; - const grantType = new AuthorizationCodeGrantType({ accessTokenLifetime: 123, model: model }); - - grantType.revokeAuthorizationCode(authorizationCode).should.be.an.instanceOf(Promise); - }); - - it('should support callbacks', function() { - const authorizationCode = { authorizationCode: 12345, client: {}, expiresAt: new Date(new Date() / 2), user: {} }; - const model = { - getAuthorizationCode: function() {}, - revokeAuthorizationCode: function(code, callback) { callback(null, authorizationCode); }, - saveToken: function() {} + saveToken: () => should.fail() }; const grantType = new AuthorizationCodeGrantType({ accessTokenLifetime: 123, model: model }); - grantType.revokeAuthorizationCode(authorizationCode).should.be.an.instanceOf(Promise); }); }); describe('saveToken()', function() { - it('should save the token', function() { - const token = {}; + it('should save the token', async function() { + const token = { foo: 'bar' }; const model = { - getAuthorizationCode: function() {}, - revokeAuthorizationCode: function() {}, - saveToken: function() { return token; }, - validateScope: function() { return 'foo'; } + getAuthorizationCode: () => should.fail(), + revokeAuthorizationCode: () => should.fail(), + saveToken: function(_token, _client= 'fallback', _user= 'fallback') { + _token.accessToken.should.be.a.sha256(); + _token.accessTokenExpiresAt.should.be.instanceOf(Date); + _token.refreshTokenExpiresAt.should.be.instanceOf(Date); + _token.refreshToken.should.be.a.sha256(); + _token.scope.should.eql(['foo']); + (_token.authorizationCode === undefined).should.equal(true); + _user.should.equal('fallback'); + _client.should.equal('fallback'); + return token; + }, + validateScope: function(_user= 'fallback', _client= 'fallback', _scope = ['fallback']) { + _user.should.equal('fallback'); + _client.should.equal('fallback'); + _scope.should.eql(['fallback']); + return ['foo']; + } }; const grantType = new AuthorizationCodeGrantType({ accessTokenLifetime: 123, model: model }); - - return grantType.saveToken(token) - .then(function(data) { - data.should.equal(token); - }) - .catch(should.fail); + const data = await grantType.saveToken(); + data.should.equal(token); }); it('should support promises', function() { @@ -560,7 +604,7 @@ describe('AuthorizationCodeGrantType integration', function() { const model = { getAuthorizationCode: function() {}, revokeAuthorizationCode: function() {}, - saveToken: function() { return Promise.resolve(token); } + saveToken: async function() { return token; } }; const grantType = new AuthorizationCodeGrantType({ accessTokenLifetime: 123, model: model }); @@ -578,17 +622,5 @@ describe('AuthorizationCodeGrantType integration', function() { grantType.saveToken(token).should.be.an.instanceOf(Promise); }); - - it('should support callbacks', function() { - const token = {}; - const model = { - getAuthorizationCode: function() {}, - revokeAuthorizationCode: function() {}, - saveToken: function(tokenToSave, client, user, callback) { callback(null, token); } - }; - const grantType = new AuthorizationCodeGrantType({ accessTokenLifetime: 123, model: model }); - - grantType.saveToken(token).should.be.an.instanceOf(Promise); - }); }); }); diff --git a/test/integration/grant-types/client-credentials-grant-type_test.js b/test/integration/grant-types/client-credentials-grant-type_test.js index b13df086..97d10055 100644 --- a/test/integration/grant-types/client-credentials-grant-type_test.js +++ b/test/integration/grant-types/client-credentials-grant-type_test.js @@ -7,7 +7,6 @@ const ClientCredentialsGrantType = require('../../../lib/grant-types/client-credentials-grant-type'); const InvalidArgumentError = require('../../../lib/errors/invalid-argument-error'); const InvalidGrantError = require('../../../lib/errors/invalid-grant-error'); -const Promise = require('bluebird'); const Request = require('../../../lib/request'); const should = require('chai').should(); @@ -56,7 +55,7 @@ describe('ClientCredentialsGrantType integration', function() { }); describe('handle()', function() { - it('should throw an error if `request` is missing', function() { + it('should throw an error if `request` is missing', async function() { const model = { getUserFromClient: function() {}, saveToken: function() {} @@ -64,7 +63,7 @@ describe('ClientCredentialsGrantType integration', function() { const grantType = new ClientCredentialsGrantType({ accessTokenLifetime: 120, model: model }); try { - grantType.handle(); + await grantType.handle(); should.fail(); } catch (e) { @@ -73,7 +72,7 @@ describe('ClientCredentialsGrantType integration', function() { } }); - it('should throw an error if `client` is missing', function() { + it('should throw an error if `client` is missing', async function() { const model = { getUserFromClient: function() {}, saveToken: function() {} @@ -82,7 +81,7 @@ describe('ClientCredentialsGrantType integration', function() { const request = new Request({ body: {}, headers: {}, method: {}, query: {} }); try { - grantType.handle(request); + await grantType.handle(request); should.fail(); } catch (e) { @@ -91,28 +90,50 @@ describe('ClientCredentialsGrantType integration', function() { } }); - it('should return a token', function() { + it('should return a token', async function() { const token = {}; + const client = { foo: 'bar' }; + const user = { name: 'foo' }; + const scope = ['fooscope']; + const model = { - getUserFromClient: function() { return {}; }, - saveToken: function() { return token; }, - validateScope: function() { return 'foo'; } + getUserFromClient: async function(_client) { + _client.should.deep.equal(client); + return { ...user }; + }, + saveToken: async function(_token, _client, _user) { + _client.should.deep.equal(client); + _user.should.deep.equal(user); + _token.accessToken.should.equal('long-access-token-hash'); + _token.accessTokenExpiresAt.should.be.instanceOf(Date); + _token.scope.should.eql(scope); + return token; + }, + validateScope: async function (_user, _client, _scope) { + _user.should.deep.equal(user); + _client.should.deep.equal(client); + _scope.should.eql(scope); + return scope; + }, + generateAccessToken: async function (_client, _user, _scope) { + _user.should.deep.equal(user); + _client.should.deep.equal(client); + _scope.should.eql(scope); + return 'long-access-token-hash'; + } }; const grantType = new ClientCredentialsGrantType({ accessTokenLifetime: 120, model: model }); - const request = new Request({ body: {}, headers: {}, method: {}, query: {} }); + const request = new Request({ body: { scope: scope.join(' ') }, headers: {}, method: {}, query: {} }); - return grantType.handle(request, {}) - .then(function(data) { - data.should.equal(token); - }) - .catch(should.fail); + const data = await grantType.handle(request, client); + data.should.equal(token); }); it('should support promises', function() { const token = {}; const model = { - getUserFromClient: function() { return {}; }, - saveToken: function() { return token; } + getUserFromClient: async function() { return {}; }, + saveToken: async function() { return token; } }; const grantType = new ClientCredentialsGrantType({ accessTokenLifetime: 120, model: model }); const request = new Request({ body: {}, headers: {}, method: {}, query: {} }); @@ -137,7 +158,7 @@ describe('ClientCredentialsGrantType integration', function() { it('should throw an error if `user` is missing', function() { const model = { getUserFromClient: function() {}, - saveToken: function() {} + saveToken: () => should.fail() }; const grantType = new ClientCredentialsGrantType({ accessTokenLifetime: 120, model: model }); const request = new Request({ body: {}, headers: {}, method: {}, query: {} }); @@ -154,7 +175,7 @@ describe('ClientCredentialsGrantType integration', function() { const user = { email: 'foo@bar.com' }; const model = { getUserFromClient: function() { return user; }, - saveToken: function() {} + saveToken: () => should.fail() }; const grantType = new ClientCredentialsGrantType({ accessTokenLifetime: 120, model: model }); const request = new Request({ body: {}, headers: {}, method: {}, query: {} }); @@ -169,8 +190,8 @@ describe('ClientCredentialsGrantType integration', function() { it('should support promises', function() { const user = { email: 'foo@bar.com' }; const model = { - getUserFromClient: function() { return Promise.resolve(user); }, - saveToken: function() {} + getUserFromClient: async function() { return user; }, + saveToken: () => should.fail() }; const grantType = new ClientCredentialsGrantType({ accessTokenLifetime: 120, model: model }); const request = new Request({ body: {}, headers: {}, method: {}, query: {} }); @@ -182,19 +203,7 @@ describe('ClientCredentialsGrantType integration', function() { const user = { email: 'foo@bar.com' }; const model = { getUserFromClient: function() {return user; }, - saveToken: function() {} - }; - const grantType = new ClientCredentialsGrantType({ accessTokenLifetime: 120, model: model }); - const request = new Request({ body: {}, headers: {}, method: {}, query: {} }); - - grantType.getUserFromClient(request, {}).should.be.an.instanceOf(Promise); - }); - - it('should support callbacks', function() { - const user = { email: 'foo@bar.com' }; - const model = { - getUserFromClient: function(userId, callback) { callback(null, user); }, - saveToken: function() {} + saveToken: () => should.fail() }; const grantType = new ClientCredentialsGrantType({ accessTokenLifetime: 120, model: model }); const request = new Request({ body: {}, headers: {}, method: {}, query: {} }); @@ -204,27 +213,23 @@ describe('ClientCredentialsGrantType integration', function() { }); describe('saveToken()', function() { - it('should save the token', function() { + it('should save the token', async function() { const token = {}; const model = { - getUserFromClient: function() {}, + getUserFromClient: () => should.fail(), saveToken: function() { return token; }, - validateScope: function() { return 'foo'; } + validateScope: function() { return ['foo']; } }; const grantType = new ClientCredentialsGrantType({ accessTokenLifetime: 123, model: model }); - - return grantType.saveToken(token) - .then(function(data) { - data.should.equal(token); - }) - .catch(should.fail); + const data = await grantType.saveToken(token); + data.should.equal(token); }); it('should support promises', function() { const token = {}; const model = { - getUserFromClient: function() {}, - saveToken: function() { return Promise.resolve(token); } + getUserFromClient:() => should.fail(), + saveToken: async function() { return token; } }; const grantType = new ClientCredentialsGrantType({ accessTokenLifetime: 123, model: model }); @@ -234,23 +239,12 @@ describe('ClientCredentialsGrantType integration', function() { it('should support non-promises', function() { const token = {}; const model = { - getUserFromClient: function() {}, + getUserFromClient: () => should.fail(), saveToken: function() { return token; } }; const grantType = new ClientCredentialsGrantType({ accessTokenLifetime: 123, model: model }); grantType.saveToken(token).should.be.an.instanceOf(Promise); }); - - it('should support callbacks', function() { - const token = {}; - const model = { - getUserFromClient: function() {}, - saveToken: function(tokenToSave, client, user, callback) { callback(null, token); } - }; - const grantType = new ClientCredentialsGrantType({ accessTokenLifetime: 123, model: model }); - - grantType.saveToken(token).should.be.an.instanceOf(Promise); - }); }); }); diff --git a/test/integration/grant-types/password-grant-type_test.js b/test/integration/grant-types/password-grant-type_test.js index a8c4cdaa..ef9b2f16 100644 --- a/test/integration/grant-types/password-grant-type_test.js +++ b/test/integration/grant-types/password-grant-type_test.js @@ -8,7 +8,6 @@ const InvalidArgumentError = require('../../../lib/errors/invalid-argument-error const InvalidGrantError = require('../../../lib/errors/invalid-grant-error'); const InvalidRequestError = require('../../../lib/errors/invalid-request-error'); const PasswordGrantType = require('../../../lib/grant-types/password-grant-type'); -const Promise = require('bluebird'); const Request = require('../../../lib/request'); const should = require('chai').should(); @@ -46,7 +45,7 @@ describe('PasswordGrantType integration', function() { getUser: function() {} }; - new PasswordGrantType({ model: model }); + new PasswordGrantType({ model }); should.fail(); } catch (e) { @@ -57,15 +56,15 @@ describe('PasswordGrantType integration', function() { }); describe('handle()', function() { - it('should throw an error if `request` is missing', function() { + it('should throw an error if `request` is missing', async function() { const model = { - getUser: function() {}, - saveToken: function() {} + getUser: () => should.fail(), + saveToken: () => should.fail() }; - const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model: model }); + const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model }); try { - grantType.handle(); + await grantType.handle(); should.fail(); } catch (e) { @@ -74,15 +73,15 @@ describe('PasswordGrantType integration', function() { } }); - it('should throw an error if `client` is missing', function() { + it('should throw an error if `client` is missing', async function() { const model = { - getUser: function() {}, - saveToken: function() {} + getUser: () => should.fail(), + saveToken: () => should.fail() }; - const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model: model }); + const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model }); try { - grantType.handle({}); + await grantType.handle({}); should.fail(); } catch (e) { @@ -91,75 +90,99 @@ describe('PasswordGrantType integration', function() { } }); - it('should return a token', function() { + it('should return a token', async function() { const client = { id: 'foobar' }; + const scope = ['baz']; const token = {}; + const user = { + id: 123456, + username: 'foo', + email: 'foo@example.com' + }; + const model = { - getUser: function() { return {}; }, - saveToken: function() { return token; }, - validateScope: function() { return 'baz'; } + getUser: async function(username, password) { + username.should.equal('foo'); + password.should.equal('bar'); + return user; + }, + validateScope: async function(_user, _client, _scope) { + _client.should.equal(client); + _user.should.equal(user); + _scope.should.eql(scope); + return scope; + }, + generateAccessToken: async function (_client, _user, _scope) { + _client.should.equal(client); + _user.should.equal(user); + _scope.should.eql(scope); + return 'long-access-token-hash'; + }, + generateRefreshToken: async function (_client, _user, _scope) { + _client.should.equal(client); + _user.should.equal(user); + _scope.should.eql(scope); + return 'long-refresh-token-hash'; + }, + saveToken: async function(_token, _client, _user) { + _client.should.equal(client); + _user.should.equal(user); + _token.accessToken.should.equal('long-access-token-hash'); + _token.refreshToken.should.equal('long-refresh-token-hash'); + _token.accessTokenExpiresAt.should.be.instanceOf(Date); + _token.refreshTokenExpiresAt.should.be.instanceOf(Date); + return token; + } }; - const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model: model }); + + const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model }); const request = new Request({ body: { username: 'foo', password: 'bar', scope: 'baz' }, headers: {}, method: {}, query: {} }); - return grantType.handle(request, client) - .then(function(data) { - data.should.equal(token); - }) - .catch(should.fail); + const data = await grantType.handle(request, client); + data.should.equal(token); }); - it('should support promises', function() { + it('should support promises', async function() { const client = { id: 'foobar' }; const token = {}; const model = { - getUser: function() { return {}; }, - saveToken: function() { return Promise.resolve(token); } + getUser: async function() { return {}; }, + saveToken: async function() { return token; } }; - const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model: model }); + const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model }); const request = new Request({ body: { username: 'foo', password: 'bar' }, headers: {}, method: {}, query: {} }); - grantType.handle(request, client).should.be.an.instanceOf(Promise); + const result = await grantType.handle(request, client); + result.should.deep.equal({}); }); - it('should support non-promises', function() { + it('should support non-promises', async function() { const client = { id: 'foobar' }; const token = {}; const model = { getUser: function() { return {}; }, saveToken: function() { return token; } }; - const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model: model }); + const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model }); const request = new Request({ body: { username: 'foo', password: 'bar' }, headers: {}, method: {}, query: {} }); - grantType.handle(request, client).should.be.an.instanceOf(Promise); - }); - - it('should support callbacks', function() { - const client = { id: 'foobar' }; - const token = {}; - const model = { - getUser: function(username, password, callback) { callback(null, {}); }, - saveToken: function(tokenToSave, client, user, callback) { callback(null, token); } - }; - const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model: model }); - const request = new Request({ body: { username: 'foo', password: 'bar' }, headers: {}, method: {}, query: {} }); - - grantType.handle(request, client).should.be.an.instanceOf(Promise); + const result = await grantType.handle(request, client); + result.should.deep.equal({}); }); }); describe('getUser()', function() { - it('should throw an error if the request body does not contain `username`', function() { + it('should throw an error if the request body does not contain `username`', async function() { const model = { - getUser: function() {}, - saveToken: function() {} + getUser: () => should.fail(), + saveToken: () => should.fail() }; - const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model: model }); + const client = { id: 'foobar' }; + const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model }); const request = new Request({ body: {}, headers: {}, method: {}, query: {} }); try { - grantType.getUser(request); + await grantType.getUser(request, client); should.fail(); } catch (e) { @@ -168,16 +191,17 @@ describe('PasswordGrantType integration', function() { } }); - it('should throw an error if the request body does not contain `password`', function() { + it('should throw an error if the request body does not contain `password`', async function() { const model = { - getUser: function() {}, - saveToken: function() {} + getUser: () => should.fail(), + saveToken: () => should.fail() }; - const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model: model }); + const client = { id: 'foobar' }; + const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model }); const request = new Request({ body: { username: 'foo' }, headers: {}, method: {}, query: {} }); try { - grantType.getUser(request); + await grantType.getUser(request, client); should.fail(); } catch (e) { @@ -186,16 +210,17 @@ describe('PasswordGrantType integration', function() { } }); - it('should throw an error if `username` is invalid', function() { + it('should throw an error if `username` is invalid', async function() { const model = { - getUser: function() {}, - saveToken: function() {} + getUser: () => should.fail(), + saveToken: () => should.fail() }; - const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model: model }); + const client = { id: 'foobar' }; + const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model }); const request = new Request({ body: { username: '\r\n', password: 'foobar' }, headers: {}, method: {}, query: {} }); try { - grantType.getUser(request); + await grantType.getUser(request, client); should.fail(); } catch (e) { @@ -204,16 +229,17 @@ describe('PasswordGrantType integration', function() { } }); - it('should throw an error if `password` is invalid', function() { + it('should throw an error if `password` is invalid', async function() { const model = { - getUser: function() {}, - saveToken: function() {} + getUser: () => should.fail(), + saveToken: () => should.fail() }; - const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model: model }); + const client = { id: 'foobar' }; + const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model }); const request = new Request({ body: { username: 'foobar', password: '\r\n' }, headers: {}, method: {}, query: {} }); try { - grantType.getUser(request); + await grantType.getUser(request, client); should.fail(); } catch (e) { @@ -222,99 +248,102 @@ describe('PasswordGrantType integration', function() { } }); - it('should throw an error if `user` is missing', function() { + it('should throw an error if `user` is missing', async function() { const model = { - getUser: function() {}, - saveToken: function() {} + getUser: async () => undefined, + saveToken: () => should.fail() }; - const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model: model }); + const client = { id: 'foobar' }; + const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model }); const request = new Request({ body: { username: 'foo', password: 'bar' }, headers: {}, method: {}, query: {} }); - return grantType.getUser(request) - .then(should.fail) - .catch(function(e) { - e.should.be.an.instanceOf(InvalidGrantError); - e.message.should.equal('Invalid grant: user credentials are invalid'); - }); + try { + await grantType.getUser(request, client); + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(InvalidGrantError); + e.message.should.equal('Invalid grant: user credentials are invalid'); + } }); - it('should return a user', function() { + it('should return a user', async function() { const user = { email: 'foo@bar.com' }; + const client = { id: 'foobar' }; const model = { - getUser: function() { return user; }, - saveToken: function() {} + getUser: function(username, password) { + username.should.equal('foo'); + password.should.equal('bar'); + return user; + }, + saveToken: () => should.fail() }; - const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model: model }); + const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model }); const request = new Request({ body: { username: 'foo', password: 'bar' }, headers: {}, method: {}, query: {} }); - return grantType.getUser(request) - .then(function(data) { - data.should.equal(user); - }) - .catch(should.fail); + const data = await grantType.getUser(request, client); + data.should.equal(user); }); it('should support promises', function() { const user = { email: 'foo@bar.com' }; + const client = { id: 'foobar' }; const model = { - getUser: function() { return Promise.resolve(user); }, - saveToken: function() {} + getUser: async function() { return user; }, + saveToken: () => should.fail() }; - const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model: model }); + const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model }); const request = new Request({ body: { username: 'foo', password: 'bar' }, headers: {}, method: {}, query: {} }); - grantType.getUser(request).should.be.an.instanceOf(Promise); + grantType.getUser(request, client).should.be.an.instanceOf(Promise); }); it('should support non-promises', function() { const user = { email: 'foo@bar.com' }; + const client = { id: 'foobar' }; const model = { getUser: function() { return user; }, - saveToken: function() {} + saveToken: () => should.fail() }; - const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model: model }); + const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model }); const request = new Request({ body: { username: 'foo', password: 'bar' }, headers: {}, method: {}, query: {} }); - grantType.getUser(request).should.be.an.instanceOf(Promise); - }); - - it('should support callbacks', function() { - const user = { email: 'foo@bar.com' }; - const model = { - getUser: function(username, password, callback) { callback(null, user); }, - saveToken: function() {} - }; - const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model: model }); - const request = new Request({ body: { username: 'foo', password: 'bar' }, headers: {}, method: {}, query: {} }); - - grantType.getUser(request).should.be.an.instanceOf(Promise); + grantType.getUser(request, client).should.be.an.instanceOf(Promise); }); }); describe('saveToken()', function() { - it('should save the token', function() { + it('should save the token', async function() { const token = {}; const model = { - getUser: function() {}, - saveToken: function() { return token; }, - validateScope: function() { return 'foo'; } + getUser: () => should.fail(), + saveToken: async function(_token, _client = 'fallback', _user = 'fallback') { + _token.accessToken.should.be.a.sha256(); + _token.accessTokenExpiresAt.should.be.instanceOf(Date); + _token.refreshTokenExpiresAt.should.be.instanceOf(Date); + _token.refreshToken.should.be.a.sha256(); + _token.scope.should.eql(['foo']); + _client.should.equal('fallback'); + _user.should.equal('fallback'); + return token; + }, + validateScope: async function(_scope = ['fallback']) { + _scope.should.eql(['fallback']); + return ['foo']; + } }; - const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model: model }); + const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model }); - return grantType.saveToken(token) - .then(function(data) { - data.should.equal(token); - }) - .catch(should.fail); + const data = await grantType.saveToken(); + data.should.equal(token); }); it('should support promises', function() { const token = {}; const model = { - getUser: function() {}, - saveToken: function() { return Promise.resolve(token); } + getUser: () => should.fail(), + saveToken: async function() { return token; } }; - const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model: model }); + const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model }); grantType.saveToken(token).should.be.an.instanceOf(Promise); }); @@ -322,21 +351,10 @@ describe('PasswordGrantType integration', function() { it('should support non-promises', function() { const token = {}; const model = { - getUser: function() {}, + getUser: () => should.fail(), saveToken: function() { return token; } }; - const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model: model }); - - grantType.saveToken(token).should.be.an.instanceOf(Promise); - }); - - it('should support callbacks', function() { - const token = {}; - const model = { - getUser: function() {}, - saveToken: function(tokenToSave, client, user, callback) { callback(null, token); } - }; - const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model: model }); + const grantType = new PasswordGrantType({ accessTokenLifetime: 123, model }); grantType.saveToken(token).should.be.an.instanceOf(Promise); }); diff --git a/test/integration/grant-types/refresh-token-grant-type_test.js b/test/integration/grant-types/refresh-token-grant-type_test.js index 83c7489f..0619fefd 100644 --- a/test/integration/grant-types/refresh-token-grant-type_test.js +++ b/test/integration/grant-types/refresh-token-grant-type_test.js @@ -7,7 +7,6 @@ const InvalidArgumentError = require('../../../lib/errors/invalid-argument-error'); const InvalidGrantError = require('../../../lib/errors/invalid-grant-error'); const InvalidRequestError = require('../../../lib/errors/invalid-request-error'); -const Promise = require('bluebird'); const RefreshTokenGrantType = require('../../../lib/grant-types/refresh-token-grant-type'); const Request = require('../../../lib/request'); const ServerError = require('../../../lib/errors/server-error'); @@ -44,10 +43,10 @@ describe('RefreshTokenGrantType integration', function() { it('should throw an error if the model does not implement `revokeToken()`', function() { try { const model = { - getRefreshToken: function() {} + getRefreshToken: () => should.fail() }; - new RefreshTokenGrantType({ model: model }); + new RefreshTokenGrantType({ model }); should.fail(); } catch (e) { @@ -59,11 +58,11 @@ describe('RefreshTokenGrantType integration', function() { it('should throw an error if the model does not implement `saveToken()`', function() { try { const model = { - getRefreshToken: function() {}, - revokeToken: function() {} + getRefreshToken: () => should.fail(), + revokeToken: () => should.fail() }; - new RefreshTokenGrantType({ model: model }); + new RefreshTokenGrantType({ model }); should.fail(); } catch (e) { @@ -74,16 +73,16 @@ describe('RefreshTokenGrantType integration', function() { }); describe('handle()', function() { - it('should throw an error if `request` is missing', function() { + it('should throw an error if `request` is missing', async function() { const model = { - getRefreshToken: function() {}, - revokeToken: function() {}, - saveToken: function() {} + getRefreshToken: () => should.fail(), + revokeToken: () => should.fail(), + saveToken: () => should.fail() }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 120, model: model }); + const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 120, model }); try { - grantType.handle(); + await grantType.handle(); should.fail(); } catch (e) { @@ -92,17 +91,17 @@ describe('RefreshTokenGrantType integration', function() { } }); - it('should throw an error if `client` is missing', function() { + it('should throw an error if `client` is missing', async function() { const model = { - getRefreshToken: function() {}, - revokeToken: function() {}, - saveToken: function() {} + getRefreshToken: () => should.fail(), + revokeToken: () => should.fail(), + saveToken: () => should.fail() }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 120, model: model }); + const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 120, model }); const request = new Request({ body: {}, headers: {}, method: {}, query: {} }); try { - grantType.handle(request); + await grantType.handle(request); should.fail(); } catch (e) { @@ -111,32 +110,61 @@ describe('RefreshTokenGrantType integration', function() { } }); - it('should return a token', function() { + it('should return a token', async function() { const client = { id: 123 }; - const token = { accessToken: 'foo', client: { id: 123 }, user: {} }; + const token = { + accessToken: 'foo', + client: { id: 123 }, + user: { name: 'foo' }, + scope: ['read', 'write'], + refreshTokenExpiresAt: new Date( new Date() * 2) + }; const model = { - getRefreshToken: function() { return token; }, - revokeToken: function() { return { accessToken: 'foo', client: { id: 123 }, refreshTokenExpiresAt: new Date(new Date() / 2), user: {} }; }, - saveToken: function() { return token; } + getRefreshToken: async function(_refreshToken) { + _refreshToken.should.equal('foobar_refresh'); + return token; + }, + revokeToken: async function(_token) { + _token.should.deep.equal(token); + return true; + }, + generateAccessToken: async function (_client, _user, _scope) { + _user.should.deep.equal({ name: 'foo' }); + _client.should.deep.equal({ id: 123 }); + _scope.should.eql(['read', 'write']); + return 'new-access-token'; + }, + generateRefreshToken: async function (_client, _user, _scope) { + _user.should.deep.equal({ name: 'foo' }); + _client.should.deep.equal({ id: 123 }); + _scope.should.eql(['read', 'write']); + return 'new-refresh-token'; + }, + saveToken: async function(_token, _client, _user) { + _user.should.deep.equal({ name: 'foo' }); + _client.should.deep.equal({ id: 123 }); + _token.accessToken.should.equal('new-access-token'); + _token.refreshToken.should.equal('new-refresh-token'); + _token.accessTokenExpiresAt.should.be.instanceOf(Date); + _token.refreshTokenExpiresAt.should.be.instanceOf(Date); + return token; + } }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model: model }); - const request = new Request({ body: { refresh_token: 'foobar' }, headers: {}, method: {}, query: {} }); - return grantType.handle(request, client) - .then(function(data) { - data.should.equal(token); - }) - .catch(should.fail); + const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model }); + const request = new Request({ body: { refresh_token: 'foobar_refresh' }, headers: {}, method: {}, query: {} }); + const data = await grantType.handle(request, client); + data.should.equal(token); }); it('should support promises', function() { const client = { id: 123 }; const model = { - getRefreshToken: function() { return Promise.resolve({ accessToken: 'foo', client: { id: 123 }, user: {} }); }, - revokeToken: function() { return Promise.resolve({ accessToken: 'foo', client: {}, refreshTokenExpiresAt: new Date(new Date() / 2), user: {} }); }, - saveToken: function() { return Promise.resolve({ accessToken: 'foo', client: {}, user: {} }); } + getRefreshToken: async function() { return { accessToken: 'foo', client: { id: 123 }, user: {} }; }, + revokeToken: async function() { return { accessToken: 'foo', client: {}, refreshTokenExpiresAt: new Date(new Date() / 2), user: {} }; }, + saveToken: async function() { return { accessToken: 'foo', client: {}, user: {} }; } }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model: model }); + const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model }); const request = new Request({ body: { refresh_token: 'foobar' }, headers: {}, method: {}, query: {} }); grantType.handle(request, client).should.be.an.instanceOf(Promise); @@ -145,24 +173,11 @@ describe('RefreshTokenGrantType integration', function() { it('should support non-promises', function() { const client = { id: 123 }; const model = { - getRefreshToken: function() { return { accessToken: 'foo', client: { id: 123 }, user: {} }; }, - revokeToken: function() { return { accessToken: 'foo', client: {}, refreshTokenExpiresAt: new Date(new Date() / 2), user: {} }; }, - saveToken: function() { return { accessToken: 'foo', client: {}, user: {} }; } - }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model: model }); - const request = new Request({ body: { refresh_token: 'foobar' }, headers: {}, method: {}, query: {} }); - - grantType.handle(request, client).should.be.an.instanceOf(Promise); - }); - - it('should support callbacks', function() { - const client = { id: 123 }; - const model = { - getRefreshToken: function(refreshToken, callback) { callback(null, { accessToken: 'foo', client: { id: 123 }, user: {} }); }, - revokeToken: function(refreshToken, callback) { callback(null, { accessToken: 'foo', client: {}, refreshTokenExpiresAt: new Date(new Date() / 2), user: {} }); }, - saveToken: function(tokenToSave, client, user, callback) { callback(null,{ accessToken: 'foo', client: {}, user: {} }); } + getRefreshToken: async function() { return { accessToken: 'foo', client: { id: 123 }, user: {} }; }, + revokeToken: async function() { return { accessToken: 'foo', client: {}, refreshTokenExpiresAt: new Date(new Date() / 2), user: {} }; }, + saveToken: async function() { return { accessToken: 'foo', client: {}, user: {} }; } }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model: model }); + const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model }); const request = new Request({ body: { refresh_token: 'foobar' }, headers: {}, method: {}, query: {} }); grantType.handle(request, client).should.be.an.instanceOf(Promise); @@ -170,18 +185,18 @@ describe('RefreshTokenGrantType integration', function() { }); describe('getRefreshToken()', function() { - it('should throw an error if the `refreshToken` parameter is missing from the request body', function() { + it('should throw an error if the `refreshToken` parameter is missing from the request body', async function() { const client = {}; const model = { - getRefreshToken: function() {}, - revokeToken: function() {}, - saveToken: function() {} + getRefreshToken: () => should.fail(), + revokeToken: () => should.fail(), + saveToken: () => should.fail() }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 120, model: model }); + const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 120, model }); const request = new Request({ body: {}, headers: {}, method: {}, query: {} }); try { - grantType.getRefreshToken(request, client); + await grantType.getRefreshToken(request, client); should.fail(); } catch (e) { @@ -190,96 +205,104 @@ describe('RefreshTokenGrantType integration', function() { } }); - it('should throw an error if `refreshToken` is not found', function() { + it('should throw an error if `refreshToken` is not found', async function() { const client = { id: 123 }; const model = { - getRefreshToken: function() { return; }, - revokeToken: function() {}, - saveToken: function() {} + getRefreshToken: async function() {} , + revokeToken: () => should.fail(), + saveToken: () => should.fail() }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 120, model: model }); + const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 120, model }); const request = new Request({ body: { refresh_token: '12345' }, headers: {}, method: {}, query: {} }); - return grantType.getRefreshToken(request, client) - .then(should.fail) - .catch(function(e) { - e.should.be.an.instanceOf(InvalidGrantError); - e.message.should.equal('Invalid grant: refresh token is invalid'); - }); + try { + await grantType.getRefreshToken(request, client); + + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(InvalidGrantError); + e.message.should.equal('Invalid grant: refresh token is invalid'); + } }); - it('should throw an error if `refreshToken.client` is missing', function() { + it('should throw an error if `refreshToken.client` is missing', async function() { const client = {}; const model = { - getRefreshToken: function() { return {}; }, - revokeToken: function() {}, - saveToken: function() {} + getRefreshToken: async function() { return {}; }, + revokeToken: () => should.fail(), + saveToken: () => should.fail() }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 120, model: model }); + const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 120, model }); const request = new Request({ body: { refresh_token: 12345 }, headers: {}, method: {}, query: {} }); - return grantType.getRefreshToken(request, client) - .then(should.fail) - .catch(function(e) { - e.should.be.an.instanceOf(ServerError); - e.message.should.equal('Server error: `getRefreshToken()` did not return a `client` object'); - }); + try { + await grantType.getRefreshToken(request, client); + + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(ServerError); + e.message.should.equal('Server error: `getRefreshToken()` did not return a `client` object'); + } }); - it('should throw an error if `refreshToken.user` is missing', function() { + it('should throw an error if `refreshToken.user` is missing', async function() { const client = {}; const model = { - getRefreshToken: function() { + getRefreshToken: async function() { return { accessToken: 'foo', client: {} }; }, - revokeToken: function() {}, - saveToken: function() {} + revokeToken: () => should.fail(), + saveToken: () => should.fail() }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 120, model: model }); + const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 120, model }); const request = new Request({ body: { refresh_token: 12345 }, headers: {}, method: {}, query: {} }); - return grantType.getRefreshToken(request, client) - .then(should.fail) - .catch(function(e) { - e.should.be.an.instanceOf(ServerError); - e.message.should.equal('Server error: `getRefreshToken()` did not return a `user` object'); - }); + try { + await grantType.getRefreshToken(request, client); + + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(ServerError); + e.message.should.equal('Server error: `getRefreshToken()` did not return a `user` object'); + } }); - it('should throw an error if the client id does not match', function() { + it('should throw an error if the client id does not match', async function() { const client = { id: 123 }; const model = { - getRefreshToken: function() { + getRefreshToken: async function() { return { accessToken: 'foo', client: { id: 456 }, user: {} }; }, - revokeToken: function() {}, - saveToken: function() {} + revokeToken: () => should.fail(), + saveToken: () => should.fail() }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 120, model: model }); + const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 120, model }); const request = new Request({ body: { refresh_token: 12345 }, headers: {}, method: {}, query: {} }); - return grantType.getRefreshToken(request, client) - .then(should.fail) - .catch(function(e) { - e.should.be.an.instanceOf(InvalidGrantError); - e.message.should.equal('Invalid grant: refresh token was issued to another client'); - }); + try { + await grantType.getRefreshToken(request, client); + + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(InvalidGrantError); + e.message.should.equal('Invalid grant: refresh token was issued to another client'); + } }); - it('should throw an error if `refresh_token` contains invalid characters', function() { + it('should throw an error if `refresh_token` contains invalid characters', async function() { const client = {}; const model = { - getRefreshToken: function() { + getRefreshToken: async function() { return { client: { id: 456 }, user: {} }; }, - revokeToken: function() {}, - saveToken: function() {} + revokeToken: () => should.fail(), + saveToken: () => should.fail() }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 120, model: model }); + const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 120, model }); const request = new Request({ body: { refresh_token: 'øå€£‰' }, headers: {}, method: {}, query: {} }); try { - grantType.getRefreshToken(request, client); + await grantType.getRefreshToken(request, client); should.fail(); } catch (e) { @@ -288,94 +311,111 @@ describe('RefreshTokenGrantType integration', function() { } }); - it('should throw an error if `refresh_token` is missing', function() { + it('should throw an error if `refresh_token` is missing', async function() { const client = {}; const model = { - getRefreshToken: function() { + getRefreshToken: async function() { return { accessToken: 'foo', client: { id: 456 }, user: {} }; }, - revokeToken: function() {}, - saveToken: function() {} + revokeToken: () => should.fail(), + saveToken: () => should.fail() }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 120, model: model }); + const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 120, model }); const request = new Request({ body: { refresh_token: 12345 }, headers: {}, method: {}, query: {} }); - return grantType.getRefreshToken(request, client) - .then(should.fail) - .catch(function(e) { - e.should.be.an.instanceOf(InvalidGrantError); - e.message.should.equal('Invalid grant: refresh token was issued to another client'); - }); + try { + await grantType.getRefreshToken(request, client); + + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(InvalidGrantError); + e.message.should.equal('Invalid grant: refresh token was issued to another client'); + } }); - it('should throw an error if `refresh_token` is expired', function() { + it('should throw an error if `refresh_token` is expired', async function() { const client = { id: 123 }; const date = new Date(new Date() / 2); const model = { - getRefreshToken: function() { + getRefreshToken: async function() { return { accessToken: 'foo', client: { id: 123 }, refreshTokenExpiresAt: date, user: {} }; }, - revokeToken: function() {}, - saveToken: function() {} + revokeToken: () => should.fail(), + saveToken: () => should.fail() }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 120, model: model }); + const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 120, model }); const request = new Request({ body: { refresh_token: 12345 }, headers: {}, method: {}, query: {} }); - return grantType.getRefreshToken(request, client) - .then(should.fail) - .catch(function(e) { - e.should.be.an.instanceOf(InvalidGrantError); - e.message.should.equal('Invalid grant: refresh token has expired'); - }); + try { + await grantType.getRefreshToken(request, client); + + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(InvalidGrantError); + e.message.should.equal('Invalid grant: refresh token has expired'); + } }); - it('should throw an error if `refreshTokenExpiresAt` is not a date value', function() { + it('should throw an error if `refreshTokenExpiresAt` is not a date value', async function() { const client = { id: 123 }; const model = { - getRefreshToken: function() { + getRefreshToken: async function() { return { accessToken: 'foo', client: { id: 123 }, refreshTokenExpiresAt: 'stringvalue', user: {} }; }, - revokeToken: function() {}, - saveToken: function() {} + revokeToken: () => should.fail(), + saveToken: () => should.fail() }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 120, model: model }); + const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 120, model }); const request = new Request({ body: { refresh_token: 12345 }, headers: {}, method: {}, query: {} }); - return grantType.getRefreshToken(request, client) - .then(should.fail) - .catch(function(e) { - e.should.be.an.instanceOf(ServerError); - e.message.should.equal('Server error: `refreshTokenExpiresAt` must be a Date instance'); - }); + try { + await grantType.getRefreshToken(request, client); + + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(ServerError); + e.message.should.equal('Server error: `refreshTokenExpiresAt` must be a Date instance'); + } }); - it('should return a token', function() { + it('should return a token', async function() { const client = { id: 123 }; - const token = { accessToken: 'foo', client: { id: 123 }, user: {} }; + const token = { accessToken: 'foo', client: { id: 123 }, user: { name: 'foobar' } }; const model = { - getRefreshToken: function() { return token; }, - revokeToken: function() {}, - saveToken: function() {} + getRefreshToken: async function(_refreshToken) { + _refreshToken.should.equal('foobar_refresh'); + return token; + }, + revokeToken: async function(_token) { + _token.should.deep.equal(token); + return true; + }, + saveToken: async function(_token, _client, _user) { + _user.should.deep.equal(token.user); + _client.should.deep.equal(client); + _token.accessToken.should.be.a.sha256(); + _token.refreshToken.should.be.a.sha256(); + _token.accessTokenExpiresAt.should.be.instanceOf(Date); + _token.refreshTokenExpiresAt.should.be.instanceOf(Date); + return token; + } }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model: model }); - const request = new Request({ body: { refresh_token: 'foobar' }, headers: {}, method: {}, query: {} }); + const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model }); + const request = new Request({ body: { refresh_token: 'foobar_refresh' }, headers: {}, method: {}, query: {} }); - return grantType.getRefreshToken(request, client) - .then(function(data) { - data.should.equal(token); - }) - .catch(should.fail); + const data = await grantType.getRefreshToken(request, client); + data.should.equal(token); }); it('should support promises', function() { const client = { id: 123 }; const token = { accessToken: 'foo', client: { id: 123 }, user: {} }; const model = { - getRefreshToken: function() { return Promise.resolve(token); }, - revokeToken: function() {}, - saveToken: function() {} + getRefreshToken: async function() { return token; }, + revokeToken: async function() {}, + saveToken: async function() {} }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model: model }); + const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model }); const request = new Request({ body: { refresh_token: 'foobar' }, headers: {}, method: {}, query: {} }); grantType.getRefreshToken(request, client).should.be.an.instanceOf(Promise); @@ -385,25 +425,11 @@ describe('RefreshTokenGrantType integration', function() { const client = { id: 123 }; const token = { accessToken: 'foo', client: { id: 123 }, user: {} }; const model = { - getRefreshToken: function() { return token; }, - revokeToken: function() {}, - saveToken: function() {} + getRefreshToken: async function() { return token; }, + revokeToken: async function() {}, + saveToken: async function() {} }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model: model }); - const request = new Request({ body: { refresh_token: 'foobar' }, headers: {}, method: {}, query: {} }); - - grantType.getRefreshToken(request, client).should.be.an.instanceOf(Promise); - }); - - it('should support callbacks', function() { - const client = { id: 123 }; - const token = { accessToken: 'foo', client: { id: 123 }, user: {} }; - const model = { - getRefreshToken: function(refreshToken, callback) { callback(null, token); }, - revokeToken: function() {}, - saveToken: function() {} - }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model: model }); + const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model }); const request = new Request({ body: { refresh_token: 'foobar' }, headers: {}, method: {}, query: {} }); grantType.getRefreshToken(request, client).should.be.an.instanceOf(Promise); @@ -411,46 +437,47 @@ describe('RefreshTokenGrantType integration', function() { }); describe('revokeToken()', function() { - it('should throw an error if the `token` is invalid', function() { + it('should throw an error if the `token` is invalid', async function() { const model = { - getRefreshToken: function() {}, - revokeToken: function() {}, - saveToken: function() {} + getRefreshToken: () => should.fail(), + revokeToken: async () => {}, + saveToken: () => should.fail() }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 120, model: model }); - - grantType.revokeToken({}) - .then(should.fail) - .catch(function (e) { - e.should.be.an.instanceOf(InvalidGrantError); - e.message.should.equal('Invalid grant: refresh token is invalid'); - }); + const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 120, model }); + + try { + await grantType.revokeToken({}); + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(InvalidGrantError); + e.message.should.equal('Invalid grant: refresh token is invalid or could not be revoked'); + } }); - it('should revoke the token', function() { + it('should revoke the token', async function() { const token = { accessToken: 'foo', client: {}, refreshTokenExpiresAt: new Date(new Date() / 2), user: {} }; const model = { - getRefreshToken: function() {}, - revokeToken: function() { return token; }, - saveToken: function() {} + getRefreshToken: () => should.fail(), + revokeToken: async function(_token) { + _token.should.deep.equal(token); + return token; + }, + saveToken: () => should.fail() }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model: model }); + const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model }); - return grantType.revokeToken(token) - .then(function(data) { - data.should.equal(token); - }) - .catch(should.fail); + const data = await grantType.revokeToken(token); + data.should.equal(token); }); it('should support promises', function() { const token = { accessToken: 'foo', client: {}, refreshTokenExpiresAt: new Date(new Date() / 2), user: {} }; const model = { - getRefreshToken: function() {}, - revokeToken: function() { return Promise.resolve(token); }, - saveToken: function() {} + getRefreshToken: () => should.fail(), + revokeToken: async function() { return token; }, + saveToken: () => should.fail() }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model: model }); + const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model }); grantType.revokeToken(token).should.be.an.instanceOf(Promise); }); @@ -458,53 +485,53 @@ describe('RefreshTokenGrantType integration', function() { it('should support non-promises', function() { const token = { accessToken: 'foo', client: {}, refreshTokenExpiresAt: new Date(new Date() / 2), user: {} }; const model = { - getRefreshToken: function() {}, + getRefreshToken: () => should.fail(), revokeToken: function() { return token; }, - saveToken: function() {} + saveToken: () => should.fail() }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model: model }); - - grantType.revokeToken(token).should.be.an.instanceOf(Promise); - }); - - it('should support callbacks', function() { - const token = { accessToken: 'foo', client: {}, refreshTokenExpiresAt: new Date(new Date() / 2), user: {} }; - const model = { - getRefreshToken: function() {}, - revokeToken: function(refreshToken, callback) { callback(null, token); }, - saveToken: function() {} - }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model: model }); + const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model }); grantType.revokeToken(token).should.be.an.instanceOf(Promise); }); }); describe('saveToken()', function() { - it('should save the token', function() { - const token = {}; + it('should save the token', async function() { + const user = { name: 'foo' }; + const client = { id: 123465 }; + const scope = ['foo', 'bar']; const model = { - getRefreshToken: function() {}, - revokeToken: function() {}, - saveToken: function() { return token; } + getRefreshToken: () => should.fail(), + revokeToken: () => should.fail(), + saveToken: async function(_token, _client, _user) { + _user.should.deep.equal(user); + _client.should.deep.equal(client); + _token.scope.should.deep.eql(scope); + _token.accessToken.should.be.a.sha256(); + _token.refreshToken.should.be.a.sha256(); + _token.accessTokenExpiresAt.should.be.instanceOf(Date); + _token.refreshTokenExpiresAt.should.be.instanceOf(Date); + return { ..._token }; + } }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model: model }); + const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model }); - return grantType.saveToken(token) - .then(function(data) { - data.should.equal(token); - }) - .catch(should.fail); + const data = await grantType.saveToken(user, client, scope); + data.accessToken.should.be.a.sha256(); + data.refreshToken.should.be.a.sha256(); + data.accessTokenExpiresAt.should.be.instanceOf(Date); + data.refreshTokenExpiresAt.should.be.instanceOf(Date); + data.scope.should.deep.equal(scope); }); it('should support promises', function() { const token = {}; const model = { - getRefreshToken: function() {}, - revokeToken: function() {}, - saveToken: function() { return Promise.resolve(token); } + getRefreshToken: () => should.fail(), + revokeToken: () => should.fail(), + saveToken: async function() { return token; } }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model: model }); + const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model }); grantType.saveToken(token).should.be.an.instanceOf(Promise); }); @@ -512,23 +539,11 @@ describe('RefreshTokenGrantType integration', function() { it('should support non-promises', function() { const token = {}; const model = { - getRefreshToken: function() {}, - revokeToken: function() {}, + getRefreshToken: () => should.fail(), + revokeToken: () => should.fail(), saveToken: function() { return token; } }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model: model }); - - grantType.saveToken(token).should.be.an.instanceOf(Promise); - }); - - it('should support callbacks', function() { - const token = {}; - const model = { - getRefreshToken: function() {}, - revokeToken: function() {}, - saveToken: function(tokenToSave, client, user, callback) { callback(null, token); } - }; - const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model: model }); + const grantType = new RefreshTokenGrantType({ accessTokenLifetime: 123, model }); grantType.saveToken(token).should.be.an.instanceOf(Promise); }); diff --git a/test/integration/handlers/authenticate-handler_test.js b/test/integration/handlers/authenticate-handler_test.js index 151ada32..52355550 100644 --- a/test/integration/handlers/authenticate-handler_test.js +++ b/test/integration/handlers/authenticate-handler_test.js @@ -10,7 +10,6 @@ const InvalidArgumentError = require('../../../lib/errors/invalid-argument-error const InvalidRequestError = require('../../../lib/errors/invalid-request-error'); const InsufficientScopeError = require('../../../lib/errors/insufficient-scope-error'); const InvalidTokenError = require('../../../lib/errors/invalid-token-error'); -const Promise = require('bluebird'); const Request = require('../../../lib/request'); const Response = require('../../../lib/response'); const ServerError = require('../../../lib/errors/server-error'); @@ -47,7 +46,7 @@ describe('AuthenticateHandler integration', function() { it('should throw an error if `scope` was given and `addAcceptedScopesHeader()` is missing', function() { try { - new AuthenticateHandler({ model: { getAccessToken: function() {} }, scope: 'foobar' }); + new AuthenticateHandler({ model: { getAccessToken: function() {} }, scope: ['foobar'] }); should.fail(); } catch (e) { @@ -58,7 +57,7 @@ describe('AuthenticateHandler integration', function() { it('should throw an error if `scope` was given and `addAuthorizedScopesHeader()` is missing', function() { try { - new AuthenticateHandler({ addAcceptedScopesHeader: true, model: { getAccessToken: function() {} }, scope: 'foobar' }); + new AuthenticateHandler({ addAcceptedScopesHeader: true, model: { getAccessToken: function() {} }, scope: ['foobar'] }); should.fail(); } catch (e) { @@ -69,7 +68,7 @@ describe('AuthenticateHandler integration', function() { it('should throw an error if `scope` was given and the model does not implement `verifyScope()`', function() { try { - new AuthenticateHandler({ addAcceptedScopesHeader: true, addAuthorizedScopesHeader: true, model: { getAccessToken: function() {} }, scope: 'foobar' }); + new AuthenticateHandler({ addAcceptedScopesHeader: true, addAuthorizedScopesHeader: true, model: { getAccessToken: function() {} }, scope: ['foobar'] }); should.fail(); } catch (e) { @@ -94,28 +93,50 @@ describe('AuthenticateHandler integration', function() { addAcceptedScopesHeader: true, addAuthorizedScopesHeader: true, model: model, - scope: 'foobar' + scope: ['foobar'] }); - grantType.scope.should.equal('foobar'); + grantType.scope.should.eql(['foobar']); }); }); describe('handle()', function() { - it('should throw an error if `request` is missing', function() { - const handler = new AuthenticateHandler({ model: { getAccessToken: function() {} } }); + it('should throw an error if `request` is missing or not a Request instance', async function() { + class Request {} // intentionally fake + const values = [undefined, null, {}, [], new Date(), new Request()]; + for (const request of values) { + const handler = new AuthenticateHandler({ model: { getAccessToken: function() {} } }); + + try { + await handler.handle(request); + + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(InvalidArgumentError); + e.message.should.equal('Invalid argument: `request` must be an instance of Request'); + } + } + }); - try { - handler.handle(); + it('should throw an error if `response` is missing or not a Response instance', async function() { + class Response {} // intentionally fake + const values = [undefined, null, {}, [], new Date(), new Response()]; + const request = new Request({ body: {}, headers: { 'Authorization': 'Bearer foo' }, method: {}, query: {} }); - should.fail(); - } catch (e) { - e.should.be.an.instanceOf(InvalidArgumentError); - e.message.should.equal('Invalid argument: `request` must be an instance of Request'); + for (const response of values) { + const handler = new AuthenticateHandler({ model: { getAccessToken: function() {} } }); + try { + await handler.handle(request, response); + + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(InvalidArgumentError); + e.message.should.equal('Invalid argument: `response` must be an instance of Response'); + } } }); - it('should set the `WWW-Authenticate` header if an unauthorized request error is thrown', function() { + it('should set the `WWW-Authenticate` header if an unauthorized request error is thrown', async function() { const model = { getAccessToken: function() { throw new UnauthorizedRequestError(); @@ -125,11 +146,12 @@ describe('AuthenticateHandler integration', function() { const request = new Request({ body: {}, headers: { 'Authorization': 'Bearer foo' }, method: {}, query: {} }); const response = new Response({ body: {}, headers: {} }); - return handler.handle(request, response) - .then(should.fail) - .catch(function() { - response.get('WWW-Authenticate').should.equal('Bearer realm="Service"'); - }); + try { + await handler.handle(request, response); + should.fail(); + } catch (e) { + response.get('WWW-Authenticate').should.equal('Bearer realm="Service"'); + } }); it('should set the `WWW-Authenticate` header if an InvalidRequestError is thrown', function() { @@ -232,7 +254,7 @@ describe('AuthenticateHandler integration', function() { return true; } }; - const handler = new AuthenticateHandler({ addAcceptedScopesHeader: true, addAuthorizedScopesHeader: true, model: model, scope: 'foo' }); + const handler = new AuthenticateHandler({ addAcceptedScopesHeader: true, addAuthorizedScopesHeader: true, model: model, scope: ['foo'] }); const request = new Request({ body: {}, headers: { 'Authorization': 'Bearer foo' }, @@ -250,7 +272,7 @@ describe('AuthenticateHandler integration', function() { }); describe('getTokenFromRequest()', function() { - it('should throw an error if more than one authentication method is used', function() { + it('should throw an error if more than one authentication method is used', async function() { const handler = new AuthenticateHandler({ model: { getAccessToken: function() {} } }); const request = new Request({ body: {}, @@ -260,7 +282,7 @@ describe('AuthenticateHandler integration', function() { }); try { - handler.getTokenFromRequest(request); + await handler.getTokenFromRequest(request); should.fail(); } catch (e) { @@ -269,12 +291,12 @@ describe('AuthenticateHandler integration', function() { } }); - it('should throw an error if `accessToken` is missing', function() { + it('should throw an error if `accessToken` is missing', async function() { const handler = new AuthenticateHandler({ model: { getAccessToken: function() {} } }); const request = new Request({ body: {}, headers: {}, method: {}, query: {} }); try { - handler.getTokenFromRequest(request); + await handler.getTokenFromRequest(request); should.fail(); } catch (e) { @@ -285,7 +307,7 @@ describe('AuthenticateHandler integration', function() { }); describe('getTokenFromRequestHeader()', function() { - it('should throw an error if the token is malformed', function() { + it('should throw an error if the token is malformed', async function() { const handler = new AuthenticateHandler({ model: { getAccessToken: function() {} } }); const request = new Request({ body: {}, @@ -297,7 +319,7 @@ describe('AuthenticateHandler integration', function() { }); try { - handler.getTokenFromRequestHeader(request); + await handler.getTokenFromRequestHeader(request); should.fail(); } catch (e) { @@ -324,11 +346,11 @@ describe('AuthenticateHandler integration', function() { }); describe('getTokenFromRequestQuery()', function() { - it('should throw an error if the query contains a token', function() { + it('should throw an error if the query contains a token', async function() { const handler = new AuthenticateHandler({ model: { getAccessToken: function() {} } }); try { - handler.getTokenFromRequestQuery(); + await handler.getTokenFromRequestQuery(); should.fail(); } catch (e) { @@ -345,7 +367,7 @@ describe('AuthenticateHandler integration', function() { }); describe('getTokenFromRequestBody()', function() { - it('should throw an error if the method is `GET`', function() { + it('should throw an error if the method is `GET`', async function() { const handler = new AuthenticateHandler({ model: { getAccessToken: function() {} } }); const request = new Request({ body: { access_token: 'foo' }, @@ -355,7 +377,7 @@ describe('AuthenticateHandler integration', function() { }); try { - handler.getTokenFromRequestBody(request); + await handler.getTokenFromRequestBody(request); should.fail(); } catch (e) { @@ -364,7 +386,7 @@ describe('AuthenticateHandler integration', function() { } }); - it('should throw an error if the media type is not `application/x-www-form-urlencoded`', function() { + it('should throw an error if the media type is not `application/x-www-form-urlencoded`', async function() { const handler = new AuthenticateHandler({ model: { getAccessToken: function() {} } }); const request = new Request({ body: { access_token: 'foo' }, @@ -374,7 +396,7 @@ describe('AuthenticateHandler integration', function() { }); try { - handler.getTokenFromRequestBody(request); + await handler.getTokenFromRequestBody(request); should.fail(); } catch (e) { @@ -445,8 +467,8 @@ describe('AuthenticateHandler integration', function() { it('should support promises', function() { const model = { - getAccessToken: function() { - return Promise.resolve({ user: {} }); + getAccessToken: async function() { + return { user: {} }; } }; const handler = new AuthenticateHandler({ model: model }); @@ -464,26 +486,15 @@ describe('AuthenticateHandler integration', function() { handler.getAccessToken('foo').should.be.an.instanceOf(Promise); }); - - it('should support callbacks', function() { - const model = { - getAccessToken: function(token, callback) { - callback(null, { user: {} }); - } - }; - const handler = new AuthenticateHandler({ model: model }); - - handler.getAccessToken('foo').should.be.an.instanceOf(Promise); - }); }); describe('validateAccessToken()', function() { - it('should throw an error if `accessToken` is expired', function() { + it('should throw an error if `accessToken` is expired', async function() { const accessToken = { accessTokenExpiresAt: new Date(new Date() / 2) }; const handler = new AuthenticateHandler({ model: { getAccessToken: function() {} } }); try { - handler.validateAccessToken(accessToken); + await handler.validateAccessToken(accessToken); should.fail(); } catch (e) { @@ -511,9 +522,9 @@ describe('AuthenticateHandler integration', function() { return false; } }; - const handler = new AuthenticateHandler({ addAcceptedScopesHeader: true, addAuthorizedScopesHeader: true, model: model, scope: 'foo' }); + const handler = new AuthenticateHandler({ addAcceptedScopesHeader: true, addAuthorizedScopesHeader: true, model: model, scope: ['foo'] }); - return handler.verifyScope('foo') + return handler.verifyScope(['foo']) .then(should.fail) .catch(function(e) { e.should.be.an.instanceOf(InsufficientScopeError); @@ -528,9 +539,9 @@ describe('AuthenticateHandler integration', function() { return true; } }; - const handler = new AuthenticateHandler({ addAcceptedScopesHeader: true, addAuthorizedScopesHeader: true, model: model, scope: 'foo' }); + const handler = new AuthenticateHandler({ addAcceptedScopesHeader: true, addAuthorizedScopesHeader: true, model: model, scope: ['foo'] }); - handler.verifyScope('foo').should.be.an.instanceOf(Promise); + handler.verifyScope(['foo']).should.be.an.instanceOf(Promise); }); it('should support non-promises', function() { @@ -540,21 +551,9 @@ describe('AuthenticateHandler integration', function() { return true; } }; - const handler = new AuthenticateHandler({ addAcceptedScopesHeader: true, addAuthorizedScopesHeader: true, model: model, scope: 'foo' }); - - handler.verifyScope('foo').should.be.an.instanceOf(Promise); - }); - - it('should support callbacks', function() { - const model = { - getAccessToken: function() {}, - verifyScope: function(token, scope, callback) { - callback(null, true); - } - }; - const handler = new AuthenticateHandler({ addAcceptedScopesHeader: true, addAuthorizedScopesHeader: true, model: model, scope: 'foo' }); + const handler = new AuthenticateHandler({ addAcceptedScopesHeader: true, addAuthorizedScopesHeader: true, model: model, scope: ['foo'] }); - handler.verifyScope('foo').should.be.an.instanceOf(Promise); + handler.verifyScope(['foo']).should.be.an.instanceOf(Promise); }); }); @@ -567,7 +566,7 @@ describe('AuthenticateHandler integration', function() { const handler = new AuthenticateHandler({ addAcceptedScopesHeader: true, addAuthorizedScopesHeader: false, model: model }); const response = new Response({ body: {}, headers: {} }); - handler.updateResponse(response, { scope: 'foo biz' }); + handler.updateResponse(response, { scope: ['foo', 'biz'] }); response.headers.should.not.have.property('x-accepted-oauth-scopes'); }); @@ -577,10 +576,10 @@ describe('AuthenticateHandler integration', function() { getAccessToken: function() {}, verifyScope: function() {} }; - const handler = new AuthenticateHandler({ addAcceptedScopesHeader: true, addAuthorizedScopesHeader: false, model: model, scope: 'foo bar' }); + const handler = new AuthenticateHandler({ addAcceptedScopesHeader: true, addAuthorizedScopesHeader: false, model: model, scope: ['foo', 'bar'] }); const response = new Response({ body: {}, headers: {} }); - handler.updateResponse(response, { scope: 'foo biz' }); + handler.updateResponse(response, { scope: ['foo', 'biz'] }); response.get('X-Accepted-OAuth-Scopes').should.equal('foo bar'); }); @@ -593,7 +592,7 @@ describe('AuthenticateHandler integration', function() { const handler = new AuthenticateHandler({ addAcceptedScopesHeader: false, addAuthorizedScopesHeader: true, model: model }); const response = new Response({ body: {}, headers: {} }); - handler.updateResponse(response, { scope: 'foo biz' }); + handler.updateResponse(response, { scope: ['foo', 'biz'] }); response.headers.should.not.have.property('x-oauth-scopes'); }); @@ -603,10 +602,10 @@ describe('AuthenticateHandler integration', function() { getAccessToken: function() {}, verifyScope: function() {} }; - const handler = new AuthenticateHandler({ addAcceptedScopesHeader: false, addAuthorizedScopesHeader: true, model: model, scope: 'foo bar' }); + const handler = new AuthenticateHandler({ addAcceptedScopesHeader: false, addAuthorizedScopesHeader: true, model: model, scope: ['foo', 'bar'] }); const response = new Response({ body: {}, headers: {} }); - handler.updateResponse(response, { scope: 'foo biz' }); + handler.updateResponse(response, { scope: ['foo', 'biz'] }); response.get('X-OAuth-Scopes').should.equal('foo biz'); }); diff --git a/test/integration/handlers/authorize-handler_test.js b/test/integration/handlers/authorize-handler_test.js index b91408a1..8bc3ae09 100644 --- a/test/integration/handlers/authorize-handler_test.js +++ b/test/integration/handlers/authorize-handler_test.js @@ -13,7 +13,6 @@ const InvalidClientError = require('../../../lib/errors/invalid-client-error'); const InvalidRequestError = require('../../../lib/errors/invalid-request-error'); const InvalidScopeError = require('../../../lib/errors/invalid-scope-error'); const UnsupportedResponseTypeError = require('../../../lib/errors/unsupported-response-type-error'); -const Promise = require('bluebird'); const Request = require('../../../lib/request'); const Response = require('../../../lib/response'); const ServerError = require('../../../lib/errors/server-error'); @@ -21,6 +20,15 @@ const UnauthorizedClientError = require('../../../lib/errors/unauthorized-client const should = require('chai').should(); const url = require('url'); +const createModel = (model = {}) => { + return { + getAccessToken: () => should.fail(), + getClient: () => should.fail(), + saveAuthorizationCode: () => should.fail(), + ...model + }; +}; + /** * Test `AuthorizeHandler` integration. */ @@ -30,7 +38,6 @@ describe('AuthorizeHandler integration', function() { it('should throw an error if `options.authorizationCodeLifetime` is missing', function() { try { new AuthorizeHandler(); - should.fail(); } catch (e) { e.should.be.an.instanceOf(InvalidArgumentError); @@ -41,7 +48,6 @@ describe('AuthorizeHandler integration', function() { it('should throw an error if `options.model` is missing', function() { try { new AuthorizeHandler({ authorizationCodeLifetime: 120 }); - should.fail(); } catch (e) { e.should.be.an.instanceOf(InvalidArgumentError); @@ -52,7 +58,6 @@ describe('AuthorizeHandler integration', function() { it('should throw an error if the model does not implement `getClient()`', function() { try { new AuthorizeHandler({ authorizationCodeLifetime: 120, model: {} }); - should.fail(); } catch (e) { e.should.be.an.instanceOf(InvalidArgumentError); @@ -62,8 +67,7 @@ describe('AuthorizeHandler integration', function() { it('should throw an error if the model does not implement `saveAuthorizationCode()`', function() { try { - new AuthorizeHandler({ authorizationCodeLifetime: 120, model: { getClient: function() {} } }); - + new AuthorizeHandler({ authorizationCodeLifetime: 120, model: { getClient: () => should.fail() } }); should.fail(); } catch (e) { e.should.be.an.instanceOf(InvalidArgumentError); @@ -73,12 +77,12 @@ describe('AuthorizeHandler integration', function() { it('should throw an error if the model does not implement `getAccessToken()`', function() { const model = { - getClient: function() {}, - saveAuthorizationCode: function() {} + getClient: () => should.fail(), + saveAuthorizationCode: () => should.fail() }; try { - new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); should.fail(); } catch (e) { @@ -88,51 +92,58 @@ describe('AuthorizeHandler integration', function() { }); it('should set the `authorizationCodeLifetime`', function() { - const model = { - getAccessToken: function() {}, - getClient: function() {}, - saveAuthorizationCode: function() {} - }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const model = createModel(); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); handler.authorizationCodeLifetime.should.equal(120); }); - it('should set the `authenticateHandler`', function() { - const model = { - getAccessToken: function() {}, - getClient: function() {}, - saveAuthorizationCode: function() {} - }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + it('should throw if the custom `authenticateHandler` does not implement a `handle` method', function () { + const model = createModel(); + const authenticateHandler = {}; // misses handle() method + + try { + new AuthorizeHandler({ authenticateHandler, authorizationCodeLifetime: 120, model }); + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(InvalidArgumentError); + e.message.should.equal('Invalid argument: authenticateHandler does not implement `handle()`'); + } + }); + it('should set the default `authenticateHandler`, if no custom one is passed', function() { + const model = createModel(); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); handler.authenticateHandler.should.be.an.instanceOf(AuthenticateHandler); }); - it('should set the `model`', function() { - const model = { - getAccessToken: function() {}, - getClient: function() {}, - saveAuthorizationCode: function() {} - }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + it('should set the custom `authenticateHandler`, if valid', function () { + const model = createModel(); + + class CustomAuthenticateHandler { + async handle () {} + } + const authenticateHandler = new CustomAuthenticateHandler(); + const handler = new AuthorizeHandler({ authenticateHandler, authorizationCodeLifetime: 120, model }); + handler.authenticateHandler.should.be.an.instanceOf(CustomAuthenticateHandler); + handler.authenticateHandler.should.not.be.an.instanceOf(AuthenticateHandler); + }); + + it('should set the `model`', function() { + const model = createModel(); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); handler.model.should.equal(model); }); }); describe('handle()', function() { - it('should throw an error if `request` is missing', function() { - const model = { - getAccessToken: function() {}, - getClient: function() {}, - saveAuthorizationCode: function() {} - }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + it('should throw an error if `request` is missing', async function() { + const model = createModel(); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); try { - handler.handle(); - + await handler.handle(); should.fail(); } catch (e) { e.should.be.an.instanceOf(InvalidArgumentError); @@ -140,18 +151,13 @@ describe('AuthorizeHandler integration', function() { } }); - it('should throw an error if `response` is missing', function() { - const model = { - getAccessToken: function() {}, - getClient: function() {}, - saveAuthorizationCode: function() {} - }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + it('should throw an error if `response` is missing', async function() { + const model = createModel(); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: {}, headers: {}, method: {}, query: {} }); try { - handler.handle(request); - + await handler.handle(request); should.fail(); } catch (e) { e.should.be.an.instanceOf(InvalidArgumentError); @@ -159,28 +165,35 @@ describe('AuthorizeHandler integration', function() { } }); - it('should redirect to an error response if user denied access', function() { - const model = { - getAccessToken: function() { + it('should redirect to an error response if user denied access', async function() { + const client = { + id: 'client-12345', + grants: ['authorization_code'], + redirectUris: ['http://example.com/cb'] + }; + const model = createModel({ + getAccessToken: async function(_token) { + _token.should.equal('foobarbazmootoken'); return { user: {}, accessTokenExpiresAt: new Date(new Date().getTime() + 10000) }; }, - getClient: function() { - return { grants: ['authorization_code'], redirectUris: ['http://example.com/cb'] }; - }, - saveAuthorizationCode: function() {} - }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + getClient: async function(clientId, clientSecret) { + clientId.should.equal(client.id); + (clientSecret === null).should.equal(true); + return { ...client }; + } + }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: { - client_id: 12345, + client_id: client.id, response_type: 'code' }, method: {}, headers: { - 'Authorization': 'Bearer foo' + 'Authorization': 'Bearer foobarbazmootoken' }, query: { state: 'foobar', @@ -189,29 +202,39 @@ describe('AuthorizeHandler integration', function() { }); const response = new Response({ body: {}, headers: {} }); - return handler.handle(request, response) - .then(should.fail) - .catch(function() { - response.get('location').should.equal('http://example.com/cb?error=access_denied&error_description=Access%20denied%3A%20user%20denied%20access%20to%20application&state=foobar'); - }); + try { + await handler.handle(request, response); + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(AccessDeniedError); + e.message.should.equal('Access denied: user denied access to application'); + response + .get('location') + .should + .equal('http://example.com/cb?error=access_denied&error_description=Access%20denied%3A%20user%20denied%20access%20to%20application&state=foobar'); + } }); - it('should redirect to an error response if a non-oauth error is thrown', function() { - const model = { - getAccessToken: function() { + it('should redirect to an error response if a non-oauth error is thrown', async function() { + const model = createModel({ + getAccessToken: async function() { return { user: {}, accessTokenExpiresAt: new Date(new Date().getTime() + 10000) }; }, - getClient: function() { - return { grants: ['authorization_code'], redirectUris: ['http://example.com/cb'] }; + getClient: async function() { + return { + grants: ['authorization_code'], + redirectUris: ['http://example.com/cb'] + }; }, - saveAuthorizationCode: function() { - throw new Error('Unhandled exception'); + saveAuthorizationCode: async function() { + throw new CustomError('Unhandled exception'); } - }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + }); + class CustomError extends Error {} + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: { client_id: 12345, @@ -227,29 +250,35 @@ describe('AuthorizeHandler integration', function() { }); const response = new Response({ body: {}, headers: {} }); - return handler.handle(request, response) - .then(should.fail) - .catch(function() { - response.get('location').should.equal('http://example.com/cb?error=server_error&error_description=Unhandled%20exception&state=foobar'); - }); + try { + await handler.handle(request, response); + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(ServerError); // non-oauth-errors are converted to ServerError + e.message.should.equal('Unhandled exception'); + response + .get('location') + .should + .equal('http://example.com/cb?error=server_error&error_description=Unhandled%20exception&state=foobar'); + } }); - it('should redirect to an error response if an oauth error is thrown', function() { - const model = { - getAccessToken: function() { + it('should redirect to an error response if an oauth error is thrown', async function() { + const model = createModel({ + getAccessToken: async function() { return { user: {}, accessTokenExpiresAt: new Date(new Date().getTime() + 10000) }; }, - getClient: function() { + getClient: async function() { return { grants: ['authorization_code'], redirectUris: ['http://example.com/cb'] }; }, - saveAuthorizationCode: function() { + saveAuthorizationCode: async function() { throw new AccessDeniedError('Cannot request this auth code'); } - }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: { client_id: 12345, @@ -265,69 +294,87 @@ describe('AuthorizeHandler integration', function() { }); const response = new Response({ body: {}, headers: {} }); - return handler.handle(request, response) - .then(should.fail) - .catch(function() { - response.get('location').should.equal('http://example.com/cb?error=access_denied&error_description=Cannot%20request%20this%20auth%20code&state=foobar'); - }); + try { + await handler.handle(request, response); + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(AccessDeniedError); + e.message.should.equal('Cannot request this auth code'); + response + .get('location') + .should + .equal('http://example.com/cb?error=access_denied&error_description=Cannot%20request%20this%20auth%20code&state=foobar'); + } }); - it('should redirect to a successful response with `code` and `state` if successful', function() { - const client = { grants: ['authorization_code'], redirectUris: ['http://example.com/cb'] }; - const model = { - getAccessToken: function() { + it('should redirect to a successful response with `code` and `state` if successful', async function() { + const client = { + id: 'client-12343434', + grants: ['authorization_code'], + redirectUris: ['http://example.com/cb'] + }; + const model = createModel({ + getAccessToken: async function(_token) { + _token.should.equal('foobarbaztokenmoo'); return { - client: client, + client, user: {}, accessTokenExpiresAt: new Date(new Date().getTime() + 10000) }; }, - getClient: function() { - return client; + getClient: async function(clientId, clientSecret) { + clientId.should.equal(client.id); + (clientSecret === null).should.equal(true); + return { ...client }; }, - saveAuthorizationCode: function() { - return { authorizationCode: 12345, client: client }; + saveAuthorizationCode: async function() { + return { + authorizationCode: 'fooobar-long-authzcode-?', + client + }; } - }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: { - client_id: 12345, + client_id: client.id, response_type: 'code' }, headers: { - 'Authorization': 'Bearer foo' + 'Authorization': 'Bearer foobarbaztokenmoo' }, method: {}, query: { - state: 'foobar' + state: 'foobarbazstatemoo' } }); const response = new Response({ body: {}, headers: {} }); - - return handler.handle(request, response) - .then(function() { - response.get('location').should.equal('http://example.com/cb?code=12345&state=foobar'); - }) - .catch(should.fail); - }); - - it('should redirect to an error response if `scope` is invalid', function() { - const model = { - getAccessToken: function() { + const data = await handler.handle(request, response); + data.authorizationCode.should.equal('fooobar-long-authzcode-?'); + data.client.should.deep.equal(client); + response.status.should.equal(302); + response + .get('location') + .should + .equal('http://example.com/cb?code=fooobar-long-authzcode-%3F&state=foobarbazstatemoo'); + }); + + it('should redirect to an error response if `scope` is invalid', async function() { + const model = createModel({ + getAccessToken: async function() { return { user: {}, accessTokenExpiresAt: new Date(new Date().getTime() + 10000) }; }, - getClient: function() { + getClient: async function() { return { grants: ['authorization_code'], redirectUris: ['http://example.com/cb'] }; }, - saveAuthorizationCode: function() { + saveAuthorizationCode: async function() { return {}; } - }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: { client_id: 12345, @@ -344,14 +391,18 @@ describe('AuthorizeHandler integration', function() { }); const response = new Response({ body: {}, headers: {} }); - return handler.handle(request, response) - .then(should.fail) - .catch(function() { - response.get('location').should.equal('http://example.com/cb?error=invalid_scope&error_description=Invalid%20parameter%3A%20%60scope%60&state=foobar'); - }); + try { + await handler.handle(request, response); + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(InvalidScopeError); + e.message.should.equal('Invalid parameter: `scope`'); + response.status.should.equal(302); + response.get('location').should.equal('http://example.com/cb?error=invalid_scope&error_description=Invalid%20parameter%3A%20%60scope%60&state=foobar'); + } }); - it('should redirect to a successful response if `model.validateScope` is not defined', function() { + it('should redirect to a successful response if `model.validateScope` is not defined', async function() { const client = { grants: ['authorization_code'], redirectUris: ['http://example.com/cb'] }; const model = { getAccessToken: function() { @@ -365,10 +416,10 @@ describe('AuthorizeHandler integration', function() { return client; }, saveAuthorizationCode: function() { - return { authorizationCode: 12345, client: client }; + return { authorizationCode: 'fooobar-long-authzcode-?', client }; } }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: { client_id: 12345, @@ -380,42 +431,44 @@ describe('AuthorizeHandler integration', function() { method: {}, query: { scope: 'read', - state: 'foobar' + state: 'foobarbazstatemoo' } }); const response = new Response({ body: {}, headers: {} }); - - return handler.handle(request, response) - .then(function(data) { - data.should.eql({ - authorizationCode: 12345, - client: client - }); - }) - .catch(should.fail); + const data = await handler.handle(request, response); + data.should.deep.equal({ + authorizationCode: 'fooobar-long-authzcode-?', + client: client + }); + response.status.should.equal(302); + response + .get('location') + .should + .equal('http://example.com/cb?code=fooobar-long-authzcode-%3F&state=foobarbazstatemoo'); }); - it('should redirect to an error response if `scope` is insufficient', function() { - const client = { grants: ['authorization_code'], redirectUris: ['http://example.com/cb'] }; + it('should redirect to an error response if `scope` is insufficient (validateScope)', async function() { + const client = { id: 12345, grants: ['authorization_code'], redirectUris: ['http://example.com/cb'] }; const model = { - getAccessToken: function() { + getAccessToken: async function() { return { client: client, - user: {}, + user: { name: 'foouser' }, accessTokenExpiresAt: new Date(new Date().getTime() + 10000) }; }, - getClient: function() { + getClient: async function() { return client; }, - saveAuthorizationCode: function() { - return { authorizationCode: 12345, client: client }; + saveAuthorizationCode: async function() { + return { authorizationCode: 12345, client }; }, - validateScope: function() { + validateScope: async function(_user, _client, _scope) { + _scope.should.eql(['read']); return false; } }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: { client_id: 12345, @@ -432,29 +485,36 @@ describe('AuthorizeHandler integration', function() { }); const response = new Response({ body: {}, headers: {} }); - return handler.handle(request, response) - .then(should.fail) - .catch(function() { - response.get('location').should.equal('http://example.com/cb?error=invalid_scope&error_description=Invalid%20scope%3A%20Requested%20scope%20is%20invalid&state=foobar'); - }); + try { + await handler.handle(request, response); + should.fail(); + } catch(e) { + e.should.be.an.instanceOf(InvalidScopeError); + e.message.should.equal('Invalid scope: Requested scope is invalid'); + response.status.should.equal(302); + response + .get('location') + .should + .equal('http://example.com/cb?error=invalid_scope&error_description=Invalid%20scope%3A%20Requested%20scope%20is%20invalid&state=foobar'); + } }); - it('should redirect to an error response if `state` is missing', function() { - const model = { - getAccessToken: function() { + it('should redirect to an error response if `state` is missing', async function() { + const model = createModel({ + getAccessToken: async function() { return { user: {}, accessTokenExpiresAt: new Date(new Date().getTime() + 10000) }; }, - getClient: function() { + getClient: async function() { return { grants: ['authorization_code'], redirectUris: ['http://example.com/cb'] }; }, - saveAuthorizationCode: function() { + saveAuthorizationCode: async function() { throw new AccessDeniedError('Cannot request this auth code'); } - }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: { client_id: 12345, @@ -468,29 +528,34 @@ describe('AuthorizeHandler integration', function() { }); const response = new Response({ body: {}, headers: {} }); - return handler.handle(request, response) - .then(should.fail) - .catch(function() { - response.get('location').should.equal('http://example.com/cb?error=invalid_request&error_description=Missing%20parameter%3A%20%60state%60'); - }); + try { + await handler.handle(request, response); + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(InvalidRequestError); + e.message.should.equal('Missing parameter: `state`'); + response.status.should.equal(302); + response + .get('location') + .should + .equal('http://example.com/cb?error=invalid_request&error_description=Missing%20parameter%3A%20%60state%60'); + } }); - it('should redirect to an error response if `response_type` is invalid', function() { + it('should redirect to an error response if `response_type` is invalid', async function() { const model = { - getAccessToken: function() { + getAccessToken: async function() { return { user: {}, accessTokenExpiresAt: new Date(new Date().getTime() + 10000) }; }, - getClient: function() { + getClient: async function() { return { grants: ['authorization_code'], redirectUris: ['http://example.com/cb'] }; }, - saveAuthorizationCode: function() { - return { authorizationCode: 12345, client: {} }; - } + saveAuthorizationCode: () => should.fail() // should fail before call }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: { client_id: 12345, @@ -506,33 +571,43 @@ describe('AuthorizeHandler integration', function() { }); const response = new Response({ body: {}, headers: {} }); - return handler.handle(request, response) - .then(should.fail) - .catch(function() { - response.get('location').should.equal('http://example.com/cb?error=unsupported_response_type&error_description=Unsupported%20response%20type%3A%20%60response_type%60%20is%20not%20supported&state=foobar'); - }); + try { + await handler.handle(request, response); + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(UnsupportedResponseTypeError); + e.message.should.equal('Unsupported response type: `response_type` is not supported'); + response.status.should.equal(302); + response + .get('location') + .should + .equal('http://example.com/cb?error=unsupported_response_type&error_description=Unsupported%20response%20type%3A%20%60response_type%60%20is%20not%20supported&state=foobar'); + } }); - it('should fail on invalid `response_type` before calling model.saveAuthorizationCode()', function() { + it('should return the `code` if successful', async function() { + const client = { grants: ['authorization_code'], redirectUris: ['http://example.com/cb'] }; const model = { - getAccessToken: function() { + getAccessToken: async function() { return { + client: client, user: {}, accessTokenExpiresAt: new Date(new Date().getTime() + 10000) }; }, - getClient: function() { - return { grants: ['authorization_code'], redirectUris: ['http://example.com/cb'] }; + getClient: async function() { + return client; }, - saveAuthorizationCode: function() { - throw new Error('must not be reached'); + generateAuthorizationCode: async () => 'some-code', + saveAuthorizationCode: async function(code) { + return { authorizationCode: code.authorizationCode, client: client }; } }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: { client_id: 12345, - response_type: 'test' + response_type: 'code' }, headers: { 'Authorization': 'Bearer foo' @@ -544,31 +619,119 @@ describe('AuthorizeHandler integration', function() { }); const response = new Response({ body: {}, headers: {} }); - return handler.handle(request, response) - .then(should.fail) - .catch(function() { - response.get('location').should.equal('http://example.com/cb?error=unsupported_response_type&error_description=Unsupported%20response%20type%3A%20%60response_type%60%20is%20not%20supported&state=foobar'); - }); + const data = await handler.handle(request, response); + data.should.eql({ + authorizationCode: 'some-code', + client: client + }); }); - it('should return the `code` if successful', function() { + it('should return the `code` if successful (full model implementation)', async function () { + const user = { name: 'fooUser' }; + const state = 'fooobarstatebaz'; + const scope = ['read']; + const client = { + id: 'client-1322132131', + grants: ['authorization_code'], + redirectUris: ['http://example.com/cb'] + }; + const authorizationCode = 'long-authz-code'; + const accessTokenDoc = { + accessToken: 'some-access-token-code', + client, + user, + scope, + accessTokenExpiresAt: new Date(new Date().getTime() + 10000) + }; + const model = { + getClient: async function (clientId, clientSecret) { + clientId.should.equal(client.id); + (clientSecret === null).should.equal(true); + return { ...client }; + }, + getAccessToken: async function (_token) { + _token.should.equal(accessTokenDoc.accessToken); + return { ...accessTokenDoc }; + }, + verifyScope: async function (_tokenDoc, _scope) { + _tokenDoc.should.equal(accessTokenDoc); + _scope.should.eql(accessTokenDoc.scope); + return true; + }, + validateScope: async function (_user, _client, _scope) { + _user.should.deep.equal(user); + _client.should.deep.equal(client); + _scope.should.eql(scope); + return _scope; + }, + generateAuthorizationCode: async function (_client, _user, _scope) { + _user.should.deep.equal(user); + _client.should.deep.equal(client); + _scope.should.eql(scope); + return authorizationCode; + }, + saveAuthorizationCode: async function (code, _client, _user) { + code.authorizationCode.should.equal(authorizationCode); + code.expiresAt.should.be.instanceOf(Date); + _user.should.deep.equal(user); + _client.should.deep.equal(client); + return { ...code, client, user }; + } + }; + + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); + const request = new Request({ + body: { + client_id: client.id, + response_type: 'code' + }, + headers: { + 'Authorization': `Bearer ${accessTokenDoc.accessToken}` + }, + method: {}, + query: { state, scope: scope.join(' ') } + }); + + const response = new Response({ body: {}, headers: {} }); + const data = await handler.handle(request, response); + data.scope.should.eql(scope); + data.client.should.deep.equal(client); + data.user.should.deep.equal(user); + data.expiresAt.should.be.instanceOf(Date); + data.redirectUri.should.equal(client.redirectUris[0]); + response.status.should.equal(302); + response + .get('location') + .should + .equal('http://example.com/cb?code=long-authz-code&state=fooobarstatebaz'); + }); + + it('should support a custom `authenticateHandler`', async function () { + const user = { name: 'user1' }; + const authenticateHandler = { + handle: async function () { + // all good + return { ...user }; + } + }; const client = { grants: ['authorization_code'], redirectUris: ['http://example.com/cb'] }; const model = { - getAccessToken: function() { + getAccessToken: async function() { return { client: client, user: {}, accessTokenExpiresAt: new Date(new Date().getTime() + 10000) }; }, - getClient: function() { + getClient: async function() { return client; }, - saveAuthorizationCode: function() { - return { authorizationCode: 12345, client: client }; + generateAuthorizationCode: async () => 'some-code', + saveAuthorizationCode: async function(code) { + return { authorizationCode: code.authorizationCode, client: client }; } }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model, authenticateHandler }); const request = new Request({ body: { client_id: 12345, @@ -584,14 +747,11 @@ describe('AuthorizeHandler integration', function() { }); const response = new Response({ body: {}, headers: {} }); - return handler.handle(request, response) - .then(function(data) { - data.should.eql({ - authorizationCode: 12345, - client: client - }); - }) - .catch(should.fail); + const data = await handler.handle(request, response); + data.should.eql({ + authorizationCode: 'some-code', + client: client + }); }); }); @@ -602,7 +762,7 @@ describe('AuthorizeHandler integration', function() { getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); return handler.generateAuthorizationCode() .then(function(data) { @@ -613,14 +773,14 @@ describe('AuthorizeHandler integration', function() { it('should support promises', function() { const model = { - generateAuthorizationCode: function() { - return Promise.resolve({}); + generateAuthorizationCode: async function() { + return {}; }, getAccessToken: function() {}, getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); handler.generateAuthorizationCode().should.be.an.instanceOf(Promise); }); @@ -634,7 +794,7 @@ describe('AuthorizeHandler integration', function() { getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); handler.generateAuthorizationCode().should.be.an.instanceOf(Promise); }); @@ -647,7 +807,7 @@ describe('AuthorizeHandler integration', function() { getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); handler.getAuthorizationCodeLifetime().should.be.an.instanceOf(Date); }); @@ -661,7 +821,7 @@ describe('AuthorizeHandler integration', function() { saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); handler.validateRedirectUri('http://example.com/a', { redirectUris: ['http://example.com/a'] }).should.be.an.instanceOf(Promise); }); @@ -671,12 +831,12 @@ describe('AuthorizeHandler integration', function() { getAccessToken: function() {}, getClient: function() {}, saveAuthorizationCode: function() {}, - validateRedirectUri: function() { - return Promise.resolve(true); + validateRedirectUri: async function() { + return true; } }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); handler.validateRedirectUri('http://example.com/a', { }).should.be.an.instanceOf(Promise); }); @@ -691,39 +851,24 @@ describe('AuthorizeHandler integration', function() { } }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); - - handler.validateRedirectUri('http://example.com/a', { }).should.be.an.instanceOf(Promise); - }); - - it('should support callbacks', function() { - const model = { - getAccessToken: function() {}, - getClient: function() {}, - saveAuthorizationCode: function() {}, - validateRedirectUri: function(redirectUri, client, callback) { - callback(null, false); - } - }; - - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); handler.validateRedirectUri('http://example.com/a', { }).should.be.an.instanceOf(Promise); }); }); describe('getClient()', function() { - it('should throw an error if `client_id` is missing', function() { + it('should throw an error if `client_id` is missing', async function() { const model = { getAccessToken: function() {}, getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: { response_type: 'code' }, headers: {}, method: {}, query: {} }); try { - handler.getClient(request); + await handler.getClient(request); should.fail(); } catch (e) { @@ -732,17 +877,17 @@ describe('AuthorizeHandler integration', function() { } }); - it('should throw an error if `client_id` is invalid', function() { + it('should throw an error if `client_id` is invalid', async function() { const model = { getAccessToken: function() {}, getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: { client_id: 'øå€£‰', response_type: 'code' }, headers: {}, method: {}, query: {} }); try { - handler.getClient(request); + await handler.getClient(request); should.fail(); } catch (e) { @@ -751,17 +896,17 @@ describe('AuthorizeHandler integration', function() { } }); - it('should throw an error if `client.redirectUri` is invalid', function() { + it('should throw an error if `client.redirectUri` is invalid', async function() { const model = { getAccessToken: function() {}, getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: { client_id: 12345, response_type: 'code', redirect_uri: 'foobar' }, headers: {}, method: {}, query: {} }); try { - handler.getClient(request); + await handler.getClient(request); should.fail(); } catch (e) { @@ -776,7 +921,7 @@ describe('AuthorizeHandler integration', function() { getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: { client_id: 12345, response_type: 'code' }, headers: {}, method: {}, query: {} }); return handler.getClient(request) @@ -795,7 +940,7 @@ describe('AuthorizeHandler integration', function() { }, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: { client_id: 12345, response_type: 'code' }, headers: {}, method: {}, query: {} }); return handler.getClient(request) @@ -814,7 +959,7 @@ describe('AuthorizeHandler integration', function() { }, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: { client_id: 12345, response_type: 'code' }, headers: {}, method: {}, query: {} }); return handler.getClient(request) @@ -831,7 +976,7 @@ describe('AuthorizeHandler integration', function() { getClient: function() { return { grants: ['authorization_code'] }; }, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: { client_id: 12345, response_type: 'code' }, headers: {}, method: {}, query: {} }); return handler.getClient(request) @@ -850,7 +995,7 @@ describe('AuthorizeHandler integration', function() { }, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: { client_id: 12345, response_type: 'code', redirect_uri: 'https://foobar.com' }, headers: {}, method: {}, query: {} }); return handler.getClient(request) @@ -864,12 +1009,12 @@ describe('AuthorizeHandler integration', function() { it('should support promises', function() { const model = { getAccessToken: function() {}, - getClient: function() { - return Promise.resolve({ grants: ['authorization_code'], redirectUris: ['http://example.com/cb'] }); + getClient: async function() { + return { grants: ['authorization_code'], redirectUris: ['http://example.com/cb'] }; }, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: { client_id: 12345 }, headers: {}, @@ -888,27 +1033,7 @@ describe('AuthorizeHandler integration', function() { }, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); - const request = new Request({ - body: { client_id: 12345 }, - headers: {}, - method: {}, - query: {} - }); - - handler.getClient(request).should.be.an.instanceOf(Promise); - }); - - it('should support callbacks', function() { - const model = { - getAccessToken: function() {}, - getClient: function(clientId, clientSecret, callback) { - should.equal(clientSecret, null); - callback(null, { grants: ['authorization_code'], redirectUris: ['http://example.com/cb'] }); - }, - saveAuthorizationCode: function() {} - }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: { client_id: 12345 }, headers: {}, @@ -929,7 +1054,7 @@ describe('AuthorizeHandler integration', function() { }, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: { response_type: 'code' }, headers: {}, method: {}, query: { client_id: 12345 } }); return handler.getClient(request) @@ -942,17 +1067,17 @@ describe('AuthorizeHandler integration', function() { }); describe('getScope()', function() { - it('should throw an error if `scope` is invalid', function() { + it('should throw an error if `scope` is invalid', async function() { const model = { getAccessToken: function() {}, getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: { scope: 'øå€£‰' }, headers: {}, method: {}, query: {} }); try { - handler.getScope(request); + await handler.getScope(request); should.fail(); } catch (e) { @@ -968,10 +1093,10 @@ describe('AuthorizeHandler integration', function() { getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: { scope: 'foo' }, headers: {}, method: {}, query: {} }); - handler.getScope(request).should.equal('foo'); + handler.getScope(request).should.eql(['foo']); }); }); @@ -982,26 +1107,26 @@ describe('AuthorizeHandler integration', function() { getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: {}, headers: {}, method: {}, query: { scope: 'foo' } }); - handler.getScope(request).should.equal('foo'); + handler.getScope(request).should.eql(['foo']); }); }); }); describe('getState()', function() { - it('should throw an error if `allowEmptyState` is false and `state` is missing', function() { + it('should throw an error if `allowEmptyState` is false and `state` is missing', async function() { const model = { getAccessToken: function() {}, getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ allowEmptyState: false, authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ allowEmptyState: false, authorizationCodeLifetime: 120, model }); const request = new Request({ body: {}, headers: {}, method: {}, query: {} }); try { - handler.getState(request); + await handler.getState(request); should.fail(); } catch (e) { @@ -1016,23 +1141,23 @@ describe('AuthorizeHandler integration', function() { getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ allowEmptyState: true, authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ allowEmptyState: true, authorizationCodeLifetime: 120, model }); const request = new Request({ body: {}, headers: {}, method: {}, query: {} }); const state = handler.getState(request); should.equal(state, undefined); }); - it('should throw an error if `state` is invalid', function() { + it('should throw an error if `state` is invalid', async function() { const model = { getAccessToken: function() {}, getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: {}, headers: {}, method: {}, query: { state: 'øå€£‰' } }); try { - handler.getState(request); + await handler.getState(request); should.fail(); } catch (e) { @@ -1048,7 +1173,7 @@ describe('AuthorizeHandler integration', function() { getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: { state: 'foobar' }, headers: {}, method: {}, query: {} }); handler.getState(request).should.equal('foobar'); @@ -1062,7 +1187,7 @@ describe('AuthorizeHandler integration', function() { getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: {}, headers: {}, method: {}, query: { state: 'foobar' } }); handler.getState(request).should.equal('foobar'); @@ -1077,7 +1202,7 @@ describe('AuthorizeHandler integration', function() { getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authenticateHandler: authenticateHandler, authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authenticateHandler: authenticateHandler, authorizationCodeLifetime: 120, model }); const request = new Request({ body: {}, headers: {}, method: {}, query: {} }); const response = new Response(); @@ -1101,7 +1226,7 @@ describe('AuthorizeHandler integration', function() { getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: {}, headers: { 'Authorization': 'Bearer foo' }, method: {}, query: {} }); const response = new Response({ body: {}, headers: {} }); @@ -1123,7 +1248,7 @@ describe('AuthorizeHandler integration', function() { return authorizationCode; } }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); return handler.saveAuthorizationCode('foo', 'bar', 'biz', 'baz') .then(function(data) { @@ -1136,11 +1261,11 @@ describe('AuthorizeHandler integration', function() { const model = { getAccessToken: function() {}, getClient: function() {}, - saveAuthorizationCode: function() { - return Promise.resolve({}); + saveAuthorizationCode: async function() { + return {}; } }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); handler.saveAuthorizationCode('foo', 'bar', 'biz', 'baz').should.be.an.instanceOf(Promise); }); @@ -1153,37 +1278,24 @@ describe('AuthorizeHandler integration', function() { return {}; } }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); - - handler.saveAuthorizationCode('foo', 'bar', 'biz', 'baz').should.be.an.instanceOf(Promise); - }); - - it('should support callbacks when calling `model.saveAuthorizationCode()`', function() { - const model = { - getAccessToken: function() {}, - getClient: function() {}, - saveAuthorizationCode: function(code, client, user, callback) { - return callback(null, true); - } - }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); handler.saveAuthorizationCode('foo', 'bar', 'biz', 'baz').should.be.an.instanceOf(Promise); }); }); describe('getResponseType()', function() { - it('should throw an error if `response_type` is missing', function() { + it('should throw an error if `response_type` is missing', async function() { const model = { getAccessToken: function() {}, getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: {}, headers: {}, method: {}, query: {} }); try { - handler.getResponseType(request); + await handler.getResponseType(request); should.fail(); } catch (e) { @@ -1192,17 +1304,17 @@ describe('AuthorizeHandler integration', function() { } }); - it('should throw an error if `response_type` is not `code`', function() { + it('should throw an error if `response_type` is not `code`', async function() { const model = { getAccessToken: function() {}, getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: { response_type: 'foobar' }, headers: {}, method: {}, query: {} }); try { - handler.getResponseType(request); + await handler.getResponseType(request); should.fail(); } catch (e) { @@ -1218,7 +1330,7 @@ describe('AuthorizeHandler integration', function() { getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: { response_type: 'code' }, headers: {}, method: {}, query: {} }); const ResponseType = handler.getResponseType(request); @@ -1233,7 +1345,7 @@ describe('AuthorizeHandler integration', function() { getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: {}, headers: {}, method: {}, query: { response_type: 'code' } }); const ResponseType = handler.getResponseType(request); @@ -1249,7 +1361,7 @@ describe('AuthorizeHandler integration', function() { getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const responseType = new CodeResponseType(12345); const redirectUri = handler.buildSuccessRedirectUri('http://example.com/cb', responseType); @@ -1265,7 +1377,7 @@ describe('AuthorizeHandler integration', function() { getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const redirectUri = handler.buildErrorRedirectUri('http://example.com/cb', error); url.format(redirectUri).should.equal('http://example.com/cb?error=invalid_client&error_description=foo%20bar'); @@ -1278,7 +1390,7 @@ describe('AuthorizeHandler integration', function() { getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const redirectUri = handler.buildErrorRedirectUri('http://example.com/cb', error); url.format(redirectUri).should.equal('http://example.com/cb?error=invalid_client&error_description=Bad%20Request'); @@ -1292,7 +1404,7 @@ describe('AuthorizeHandler integration', function() { getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const response = new Response({ body: {}, headers: {} }); const uri = url.parse('http://example.com/cb'); @@ -1309,7 +1421,7 @@ describe('AuthorizeHandler integration', function() { getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: {code_challenge_method: 'S256'}, headers: {}, method: {}, query: {} }); const codeChallengeMethod = handler.getCodeChallengeMethod(request); @@ -1322,11 +1434,11 @@ describe('AuthorizeHandler integration', function() { getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: {code_challenge_method: 'foo'}, headers: {}, method: {}, query: {} }); try { - handler.getCodeChallengeMethod(request); + await handler.getCodeChallengeMethod(request); should.fail(); } catch (e) { @@ -1342,7 +1454,7 @@ describe('AuthorizeHandler integration', function() { getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: {}, headers: {}, method: {}, query: {} }); const codeChallengeMethod = handler.getCodeChallengeMethod(request); @@ -1357,7 +1469,7 @@ describe('AuthorizeHandler integration', function() { getClient: function() {}, saveAuthorizationCode: function() {} }; - const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); + const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model }); const request = new Request({ body: {code_challenge: 'challenge'}, headers: {}, method: {}, query: {} }); const codeChallengeMethod = handler.getCodeChallenge(request); diff --git a/test/integration/handlers/token-handler_test.js b/test/integration/handlers/token-handler_test.js index 0cb60c39..1c2db3b4 100644 --- a/test/integration/handlers/token-handler_test.js +++ b/test/integration/handlers/token-handler_test.js @@ -11,7 +11,6 @@ const InvalidClientError = require('../../../lib/errors/invalid-client-error'); const InvalidGrantError = require('../../../lib/errors/invalid-grant-error'); const InvalidRequestError = require('../../../lib/errors/invalid-request-error'); const PasswordGrantType = require('../../../lib/grant-types/password-grant-type'); -const Promise = require('bluebird'); const Request = require('../../../lib/request'); const Response = require('../../../lib/response'); const ServerError = require('../../../lib/errors/server-error'); @@ -149,7 +148,7 @@ describe('TokenHandler integration', function() { }); describe('handle()', function() { - it('should throw an error if `request` is missing', function() { + it('should throw an error if `request` is missing', async function() { const model = { getClient: function() {}, saveToken: function() {} @@ -157,7 +156,7 @@ describe('TokenHandler integration', function() { const handler = new TokenHandler({ accessTokenLifetime: 120, model: model, refreshTokenLifetime: 120 }); try { - handler.handle(); + await handler.handle(); should.fail(); } catch (e) { @@ -166,7 +165,7 @@ describe('TokenHandler integration', function() { } }); - it('should throw an error if `response` is missing', function() { + it('should throw an error if `response` is missing', async function() { const model = { getClient: function() {}, saveToken: function() {} @@ -175,7 +174,7 @@ describe('TokenHandler integration', function() { const request = new Request({ body: {}, headers: {}, method: {}, query: {} }); try { - handler.handle(request); + await handler.handle(request); should.fail(); } catch (e) { @@ -299,12 +298,12 @@ describe('TokenHandler integration', function() { }); it('should return a bearer token if successful', function() { - const token = { accessToken: 'foo', client: {}, refreshToken: 'bar', scope: 'foobar', user: {} }; + const token = { accessToken: 'foo', client: {}, refreshToken: 'bar', scope: ['foobar'], user: {} }; const model = { getClient: function() { return { grants: ['password'] }; }, getUser: function() { return {}; }, saveToken: function() { return token; }, - validateScope: function() { return 'baz'; } + validateScope: function() { return ['baz']; } }; const handler = new TokenHandler({ accessTokenLifetime: 120, model: model, refreshTokenLifetime: 120 }); const request = new Request({ @@ -330,12 +329,12 @@ describe('TokenHandler integration', function() { }); it('should not return custom attributes in a bearer token if the allowExtendedTokenAttributes is not set', function() { - const token = { accessToken: 'foo', client: {}, refreshToken: 'bar', scope: 'foobar', user: {}, foo: 'bar' }; + const token = { accessToken: 'foo', client: {}, refreshToken: 'bar', scope: ['foobar'], user: {}, foo: 'bar' }; const model = { getClient: function() { return { grants: ['password'] }; }, getUser: function() { return {}; }, saveToken: function() { return token; }, - validateScope: function() { return 'baz'; } + validateScope: function() { return ['baz']; } }; const handler = new TokenHandler({ accessTokenLifetime: 120, model: model, refreshTokenLifetime: 120 }); const request = new Request({ @@ -365,12 +364,12 @@ describe('TokenHandler integration', function() { }); it('should return custom attributes in a bearer token if the allowExtendedTokenAttributes is set', function() { - const token = { accessToken: 'foo', client: {}, refreshToken: 'bar', scope: 'foobar', user: {}, foo: 'bar' }; + const token = { accessToken: 'foo', client: {}, refreshToken: 'bar', scope: ['foobar'], user: {}, foo: 'bar' }; const model = { getClient: function() { return { grants: ['password'] }; }, getUser: function() { return {}; }, saveToken: function() { return token; }, - validateScope: function() { return 'baz'; } + validateScope: function() { return ['baz']; } }; const handler = new TokenHandler({ accessTokenLifetime: 120, model: model, refreshTokenLifetime: 120, allowExtendedTokenAttributes: true }); const request = new Request({ @@ -402,7 +401,7 @@ describe('TokenHandler integration', function() { describe('getClient()', function() { - it('should throw an error if `clientId` is invalid', function() { + it('should throw an error if `clientId` is invalid', async function() { const model = { getClient: function() {}, saveToken: function() {} @@ -411,7 +410,7 @@ describe('TokenHandler integration', function() { const request = new Request({ body: { client_id: 'øå€£‰', client_secret: 'foo' }, headers: {}, method: {}, query: {} }); try { - handler.getClient(request); + await handler.getClient(request); should.fail(); } catch (e) { @@ -420,7 +419,7 @@ describe('TokenHandler integration', function() { } }); - it('should throw an error if `clientSecret` is invalid', function() { + it('should throw an error if `clientSecret` is invalid', async function() { const model = { getClient: function() {}, saveToken: function() {} @@ -429,7 +428,7 @@ describe('TokenHandler integration', function() { const request = new Request({ body: { client_id: 'foo', client_secret: 'øå€£‰' }, headers: {}, method: {}, query: {} }); try { - handler.getClient(request); + await handler.getClient(request); should.fail(); } catch (e) { @@ -588,7 +587,7 @@ describe('TokenHandler integration', function() { it('should support promises', function() { const model = { - getClient: function() { return Promise.resolve({ grants: [] }); }, + getClient: async function() { return { grants: [] }; }, saveToken: function() {} }; const handler = new TokenHandler({ accessTokenLifetime: 120, model: model, refreshTokenLifetime: 120 }); @@ -607,21 +606,10 @@ describe('TokenHandler integration', function() { handler.getClient(request).should.be.an.instanceOf(Promise); }); - - it('should support callbacks', function() { - const model = { - getClient: function(clientId, clientSecret, callback) { callback(null, { grants: [] }); }, - saveToken: function() {} - }; - const handler = new TokenHandler({ accessTokenLifetime: 120, model: model, refreshTokenLifetime: 120 }); - const request = new Request({ body: { client_id: 12345, client_secret: 'secret' }, headers: {}, method: {}, query: {} }); - - handler.getClient(request).should.be.an.instanceOf(Promise); - }); }); describe('getClientCredentials()', function() { - it('should throw an error if `client_id` is missing', function() { + it('should throw an error if `client_id` is missing', async function() { const model = { getClient: function() {}, saveToken: function() {} @@ -630,7 +618,7 @@ describe('TokenHandler integration', function() { const request = new Request({ body: { client_secret: 'foo' }, headers: {}, method: {}, query: {} }); try { - handler.getClientCredentials(request); + await handler.getClientCredentials(request); should.fail(); } catch (e) { @@ -639,7 +627,7 @@ describe('TokenHandler integration', function() { } }); - it('should throw an error if `client_secret` is missing', function() { + it('should throw an error if `client_secret` is missing', async function() { const model = { getClient: function() {}, saveToken: function() {} @@ -648,7 +636,7 @@ describe('TokenHandler integration', function() { const request = new Request({ body: { client_id: 'foo' }, headers: {}, method: {}, query: {} }); try { - handler.getClientCredentials(request); + await handler.getClientCredentials(request); should.fail(); } catch (e) { @@ -708,7 +696,7 @@ describe('TokenHandler integration', function() { }); describe('handleGrantType()', function() { - it('should throw an error if `grant_type` is missing', function() { + it('should throw an error if `grant_type` is missing', async function() { const model = { getClient: function() {}, saveToken: function() {} @@ -717,7 +705,7 @@ describe('TokenHandler integration', function() { const request = new Request({ body: {}, headers: {}, method: {}, query: {} }); try { - handler.handleGrantType(request); + await handler.handleGrantType(request); should.fail(); } catch (e) { @@ -726,7 +714,7 @@ describe('TokenHandler integration', function() { } }); - it('should throw an error if `grant_type` is invalid', function() { + it('should throw an error if `grant_type` is invalid', async function() { const model = { getClient: function() {}, saveToken: function() {} @@ -735,7 +723,7 @@ describe('TokenHandler integration', function() { const request = new Request({ body: { grant_type: '~foo~' }, headers: {}, method: {}, query: {} }); try { - handler.handleGrantType(request); + await handler.handleGrantType(request); should.fail(); } catch (e) { @@ -744,7 +732,7 @@ describe('TokenHandler integration', function() { } }); - it('should throw an error if `grant_type` is unsupported', function() { + it('should throw an error if `grant_type` is unsupported', async function() { const model = { getClient: function() {}, saveToken: function() {} @@ -753,7 +741,7 @@ describe('TokenHandler integration', function() { const request = new Request({ body: { grant_type: 'foobar' }, headers: {}, method: {}, query: {} }); try { - handler.handleGrantType(request); + await handler.handleGrantType(request); should.fail(); } catch (e) { @@ -762,7 +750,7 @@ describe('TokenHandler integration', function() { } }); - it('should throw an error if `grant_type` is unauthorized', function() { + it('should throw an error if `grant_type` is unauthorized', async function() { const client = { grants: ['client_credentials'] }; const model = { getClient: function() {}, @@ -772,7 +760,7 @@ describe('TokenHandler integration', function() { const request = new Request({ body: { grant_type: 'password' }, headers: {}, method: {}, query: {} }); try { - handler.handleGrantType(request, client); + await handler.handleGrantType(request, client); should.fail(); } catch (e) { @@ -784,8 +772,8 @@ describe('TokenHandler integration', function() { it('should throw an invalid grant error if a non-oauth error is thrown', function() { const client = { grants: ['password'] }; const model = { - getClient: function(clientId, password, callback) { callback(null, client); }, - getUser: function(uid, pwd, callback) { callback(); }, + getClient: function(clientId, password) { return client; }, + getUser: function(uid, pwd) {}, saveToken: function() {} }; const handler = new TokenHandler({ accessTokenLifetime: 120, model: model, refreshTokenLifetime: 120 }); @@ -807,7 +795,7 @@ describe('TokenHandler integration', function() { getAuthorizationCode: function() { return { authorizationCode: 12345, client: { id: 'foobar' }, expiresAt: new Date(new Date() * 2), user: {} }; }, getClient: function() {}, saveToken: function() { return token; }, - validateScope: function() { return 'foo'; }, + validateScope: function() { return ['foo']; }, revokeAuthorizationCode: function() { return { authorizationCode: 12345, client: { id: 'foobar' }, expiresAt: new Date(new Date() / 2), user: {} }; } }; const handler = new TokenHandler({ accessTokenLifetime: 120, model: model, refreshTokenLifetime: 120 }); @@ -846,7 +834,7 @@ describe('TokenHandler integration', function() { getAuthorizationCode: function() { return authorizationCode; }, getClient: function() {}, saveToken: function() { return token; }, - validateScope: function() { return 'foo'; }, + validateScope: function() { return ['foo']; }, revokeAuthorizationCode: function() { return authorizationCode; } }; const handler = new TokenHandler({ accessTokenLifetime: 120, model: model, refreshTokenLifetime: 120 }); @@ -884,7 +872,7 @@ describe('TokenHandler integration', function() { getAuthorizationCode: function() { return authorizationCode; }, getClient: function() {}, saveToken: function() { return token; }, - validateScope: function() { return 'foo'; }, + validateScope: function() { return ['foo']; }, revokeAuthorizationCode: function() { return authorizationCode; } }; const handler = new TokenHandler({ accessTokenLifetime: 120, model: model, refreshTokenLifetime: 120 }); @@ -922,7 +910,7 @@ describe('TokenHandler integration', function() { getAuthorizationCode: function() { return authorizationCode; }, getClient: function() {}, saveToken: function() { return token; }, - validateScope: function() { return 'foo'; }, + validateScope: function() { return ['foo']; }, revokeAuthorizationCode: function() { return authorizationCode; } }; const handler = new TokenHandler({ accessTokenLifetime: 120, model: model, refreshTokenLifetime: 120 }); @@ -961,7 +949,7 @@ describe('TokenHandler integration', function() { getAuthorizationCode: function() { return authorizationCode; }, getClient: function() {}, saveToken: function() { return token; }, - validateScope: function() { return 'foo'; }, + validateScope: function() { return ['foo']; }, revokeAuthorizationCode: function() { return authorizationCode; } }; const handler = new TokenHandler({ accessTokenLifetime: 120, model: model, refreshTokenLifetime: 120 }); @@ -996,7 +984,7 @@ describe('TokenHandler integration', function() { getAuthorizationCode: function() { return authorizationCode; }, getClient: function() {}, saveToken: function() { return token; }, - validateScope: function() { return 'foo'; }, + validateScope: function() { return ['foo']; }, revokeAuthorizationCode: function() { return authorizationCode; } }; const handler = new TokenHandler({ accessTokenLifetime: 120, model: model, refreshTokenLifetime: 120 }); @@ -1028,7 +1016,7 @@ describe('TokenHandler integration', function() { getClient: function() {}, getUserFromClient: function() { return {}; }, saveToken: function() { return token; }, - validateScope: function() { return 'foo'; } + validateScope: function() { return ['foo']; } }; const handler = new TokenHandler({ accessTokenLifetime: 120, model: model, refreshTokenLifetime: 120 }); const request = new Request({ @@ -1057,7 +1045,7 @@ describe('TokenHandler integration', function() { getClient: function() {}, getUser: function() { return {}; }, saveToken: function() { return token; }, - validateScope: function() { return 'baz'; } + validateScope: function() { return ['baz']; } }; const handler = new TokenHandler({ accessTokenLifetime: 120, model: model, refreshTokenLifetime: 120 }); const request = new Request({ @@ -1119,7 +1107,7 @@ describe('TokenHandler integration', function() { getClient: function() {}, getUser: function() { return {}; }, saveToken: function() { return token; }, - validateScope: function() { return 'foo'; } + validateScope: function() { return ['foo']; } }; const handler = new TokenHandler({ accessTokenLifetime: 120, model: model, refreshTokenLifetime: 120, extendedGrantTypes: { 'urn:ietf:params:oauth:grant-type:saml2-bearer': PasswordGrantType } }); const request = new Request({ body: { grant_type: 'urn:ietf:params:oauth:grant-type:saml2-bearer', username: 'foo', password: 'bar' }, headers: {}, method: {}, query: {} }); @@ -1188,8 +1176,8 @@ describe('TokenHandler integration', function() { saveToken: function() {} }; const handler = new TokenHandler({ accessTokenLifetime: 120, model: model, refreshTokenLifetime: 120 }); - const tokenType = handler.getTokenType({ accessToken: 'foo', refreshToken: 'bar', scope: 'foobar' }); - tokenType.should.deep.include({ accessToken: 'foo', accessTokenLifetime: undefined, refreshToken: 'bar', scope: 'foobar' }); + const tokenType = handler.getTokenType({ accessToken: 'foo', refreshToken: 'bar', scope: ['foobar'] }); + tokenType.should.deep.include({ accessToken: 'foo', accessTokenLifetime: undefined, refreshToken: 'bar', scope: ['foobar'] }); }); }); diff --git a/test/integration/server_test.js b/test/integration/server_test.js index db105444..7732bdc2 100644 --- a/test/integration/server_test.js +++ b/test/integration/server_test.js @@ -5,7 +5,6 @@ */ const InvalidArgumentError = require('../../lib/errors/invalid-argument-error'); -const Promise = require('bluebird'); const Request = require('../../lib/request'); const Response = require('../../lib/response'); const Server = require('../../lib/server'); @@ -18,14 +17,16 @@ const should = require('chai').should(); describe('Server integration', function() { describe('constructor()', function() { it('should throw an error if `model` is missing', function() { - try { - new Server({}); - - should.fail(); - } catch (e) { - e.should.be.an.instanceOf(InvalidArgumentError); - e.message.should.equal('Missing parameter: `model`'); - } + [null, undefined, {}].forEach(options => { + try { + new Server(options); + + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(InvalidArgumentError); + e.message.should.equal('Missing parameter: `model`'); + } + }); }); it('should set the `model`', function() { @@ -37,7 +38,7 @@ describe('Server integration', function() { }); describe('authenticate()', function() { - it('should set the default `options`', function() { + it('should set the default `options`', async function() { const model = { getAccessToken: function() { return { @@ -50,35 +51,19 @@ describe('Server integration', function() { const request = new Request({ body: {}, headers: { 'Authorization': 'Bearer foo' }, method: {}, query: {} }); const response = new Response({ body: {}, headers: {} }); - return server.authenticate(request, response) - .then(function() { - this.addAcceptedScopesHeader.should.be.true; - this.addAuthorizedScopesHeader.should.be.true; - this.allowBearerTokensInQueryString.should.be.false; - }) - .catch(should.fail); + try { + await server.authenticate(request, response); + } catch (e) { + server.addAcceptedScopesHeader.should.be.true; + server.addAuthorizedScopesHeader.should.be.true; + server.allowBearerTokensInQueryString.should.be.false; + should.fail(); + } }); it('should return a promise', function() { const model = { - getAccessToken: function(token, callback) { - callback(null, { - user: {}, - accessTokenExpiresAt: new Date(new Date().getTime() + 10000) - }); - } - }; - const server = new Server({ model: model }); - const request = new Request({ body: {}, headers: { 'Authorization': 'Bearer foo' }, method: {}, query: {} }); - const response = new Response({ body: {}, headers: {} }); - const handler = server.authenticate(request, response); - - handler.should.be.an.instanceOf(Promise); - }); - - it('should support callbacks', function(next) { - const model = { - getAccessToken: function() { + getAccessToken: async function(token) { return { user: {}, accessTokenExpiresAt: new Date(new Date().getTime() + 10000) @@ -88,13 +73,14 @@ describe('Server integration', function() { const server = new Server({ model: model }); const request = new Request({ body: {}, headers: { 'Authorization': 'Bearer foo' }, method: {}, query: {} }); const response = new Response({ body: {}, headers: {} }); + const handler = server.authenticate(request, response); - server.authenticate(request, response, null, next); + handler.should.be.an.instanceOf(Promise); }); }); describe('authorize()', function() { - it('should set the default `options`', function() { + it('should set the default `options`', async function() { const model = { getAccessToken: function() { return { @@ -113,12 +99,13 @@ describe('Server integration', function() { const request = new Request({ body: { client_id: 1234, client_secret: 'secret', response_type: 'code' }, headers: { 'Authorization': 'Bearer foo' }, method: {}, query: { state: 'foobar' } }); const response = new Response({ body: {}, headers: {} }); - return server.authorize(request, response) - .then(function() { - this.allowEmptyState.should.be.false; - this.authorizationCodeLifetime.should.equal(300); - }) - .catch(should.fail); + try { + await server.authorize(request, response); + } catch (e) { + server.allowEmptyState.should.be.false; + server.authorizationCodeLifetime.should.equal(300); + should.fail(); + } }); it('should return a promise', function() { @@ -143,32 +130,10 @@ describe('Server integration', function() { handler.should.be.an.instanceOf(Promise); }); - - it('should support callbacks', function(next) { - const model = { - getAccessToken: function() { - return { - user: {}, - accessTokenExpiresAt: new Date(new Date().getTime() + 10000) - }; - }, - getClient: function() { - return { grants: ['authorization_code'], redirectUris: ['http://example.com/cb'] }; - }, - saveAuthorizationCode: function() { - return { authorizationCode: 123 }; - } - }; - const server = new Server({ model: model }); - const request = new Request({ body: { client_id: 1234, client_secret: 'secret', response_type: 'code' }, headers: { 'Authorization': 'Bearer foo' }, method: {}, query: { state: 'foobar' } }); - const response = new Response({ body: {}, headers: {} }); - - server.authorize(request, response, null, next); - }); }); describe('token()', function() { - it('should set the default `options`', function() { + it('should set the default `options`', async function() { const model = { getClient: function() { return { grants: ['password'] }; @@ -179,18 +144,19 @@ describe('Server integration', function() { saveToken: function() { return { accessToken: 1234, client: {}, user: {} }; }, - validateScope: function() { return 'foo'; } + validateScope: function() { return ['foo']; } }; const server = new Server({ model: model }); const request = new Request({ body: { client_id: 1234, client_secret: 'secret', grant_type: 'password', username: 'foo', password: 'pass', scope: 'foo' }, headers: { 'content-type': 'application/x-www-form-urlencoded', 'transfer-encoding': 'chunked' }, method: 'POST', query: {} }); const response = new Response({ body: {}, headers: {} }); - return server.token(request, response) - .then(function() { - this.accessTokenLifetime.should.equal(3600); - this.refreshTokenLifetime.should.equal(1209600); - }) - .catch(should.fail); + try { + await server.token(request, response); + } catch (e) { + server.accessTokenLifetime.should.equal(3600); + server.refreshTokenLifetime.should.equal(1209600); + should.fail(); + } }); it('should return a promise', function() { @@ -212,27 +178,5 @@ describe('Server integration', function() { handler.should.be.an.instanceOf(Promise); }); - - it('should support callbacks', function(next) { - const model = { - getClient: function() { - return { grants: ['password'] }; - }, - getUser: function() { - return {}; - }, - saveToken: function() { - return { accessToken: 1234, client: {}, user: {} }; - }, - validateScope: function() { - return 'foo'; - } - }; - const server = new Server({ model: model }); - const request = new Request({ body: { client_id: 1234, client_secret: 'secret', grant_type: 'password', username: 'foo', password: 'pass', scope: 'foo' }, headers: { 'content-type': 'application/x-www-form-urlencoded', 'transfer-encoding': 'chunked' }, method: 'POST', query: {} }); - const response = new Response({ body: {}, headers: {} }); - - server.token(request, response, null, next); - }); }); }); diff --git a/test/integration/utils/token-util_test.js b/test/integration/utils/token-util_test.js index d4f368ea..edf9c7e9 100644 --- a/test/integration/utils/token-util_test.js +++ b/test/integration/utils/token-util_test.js @@ -5,7 +5,6 @@ */ const TokenUtil = require('../../../lib/utils/token-util'); -const should = require('chai').should(); /** * Test `TokenUtil` integration. @@ -13,12 +12,9 @@ const should = require('chai').should(); describe('TokenUtil integration', function() { describe('generateRandomToken()', function() { - it('should return a sha-256 token', function() { - return TokenUtil.generateRandomToken() - .then(function(token) { - token.should.be.a.sha256(); - }) - .catch(should.fail); + it('should return a sha-256 token', async function() { + const token = await TokenUtil.generateRandomToken(); + token.should.be.a.sha256(); }); }); }); diff --git a/test/unit/errors/oauth-error_test.js b/test/unit/errors/oauth-error_test.js new file mode 100644 index 00000000..6d68a299 --- /dev/null +++ b/test/unit/errors/oauth-error_test.js @@ -0,0 +1,58 @@ +'use strict'; + +/** + * Module dependencies. + */ + +const { describe, it } = require('mocha'); +const should = require('chai').should(); +const OAuthError = require('../../../lib/errors/oauth-error'); + +/** + * Test `OAuthError`. + */ + +describe('OAuthError', function() { + describe('constructor()', function() { + it('should get `captureStackTrace`', function() { + + const errorFn = function () { throw new OAuthError('test', {name: 'test_error', foo: 'bar'}); }; + + try { + errorFn(); + + should.fail(); + } catch (e) { + + e.should.be.an.instanceOf(OAuthError); + e.name.should.equal('test_error'); + e.foo.should.equal('bar'); + e.message.should.equal('test'); + e.code.should.equal(500); + e.stack.should.not.be.null; + e.stack.should.not.be.undefined; + e.stack.should.include('oauth-error_test.js'); + e.stack.should.include('19'); //error lineNUmber + } + }); + }); + it('supports undefined properties', function () { + const errorFn = function () { throw new OAuthError('test'); }; + + try { + errorFn(); + + should.fail(); + } catch (e) { + + e.should.be.an.instanceOf(OAuthError); + e.name.should.equal('Error'); + e.message.should.equal('test'); + e.code.should.equal(500); + e.stack.should.not.be.null; + e.stack.should.not.be.undefined; + e.stack.should.include('oauth-error_test.js'); + e.stack.should.include('40'); //error lineNUmber + } + }); +}); diff --git a/test/unit/grant-types/authorization-code-grant-type_test.js b/test/unit/grant-types/authorization-code-grant-type_test.js index 7672ed48..3ffe46ad 100644 --- a/test/unit/grant-types/authorization-code-grant-type_test.js +++ b/test/unit/grant-types/authorization-code-grant-type_test.js @@ -7,7 +7,6 @@ const AuthorizationCodeGrantType = require('../../../lib/grant-types/authorization-code-grant-type'); const InvalidGrantError = require('../../../lib/errors/invalid-grant-error'); const ServerError = require('../../../lib/errors/server-error'); -const Promise = require('bluebird'); const Request = require('../../../lib/request'); const sinon = require('sinon'); const should = require('chai').should(); @@ -73,17 +72,17 @@ describe('AuthorizationCodeGrantType', function() { }; const handler = new AuthorizationCodeGrantType({ accessTokenLifetime: 120, model: model }); - sinon.stub(handler, 'validateScope').returns('foobiz'); + sinon.stub(handler, 'validateScope').returns(['foobiz']); sinon.stub(handler, 'generateAccessToken').returns(Promise.resolve('foo')); sinon.stub(handler, 'generateRefreshToken').returns(Promise.resolve('bar')); sinon.stub(handler, 'getAccessTokenExpiresAt').returns(Promise.resolve('biz')); sinon.stub(handler, 'getRefreshTokenExpiresAt').returns(Promise.resolve('baz')); - return handler.saveToken(user, client, 'foobar', 'foobiz') + return handler.saveToken(user, client, 'foobar', ['foobiz']) .then(function() { model.saveToken.callCount.should.equal(1); model.saveToken.firstCall.args.should.have.length(3); - model.saveToken.firstCall.args[0].should.eql({ accessToken: 'foo', authorizationCode: 'foobar', accessTokenExpiresAt: 'biz', refreshToken: 'bar', refreshTokenExpiresAt: 'baz', scope: 'foobiz' }); + model.saveToken.firstCall.args[0].should.eql({ accessToken: 'foo', authorizationCode: 'foobar', accessTokenExpiresAt: 'biz', refreshToken: 'bar', refreshTokenExpiresAt: 'baz', scope: ['foobiz'] }); model.saveToken.firstCall.args[1].should.equal(client); model.saveToken.firstCall.args[2].should.equal(user); model.saveToken.firstCall.thisValue.should.equal(model); diff --git a/test/unit/grant-types/client-credentials-grant-type_test.js b/test/unit/grant-types/client-credentials-grant-type_test.js index 3997823b..5e012b43 100644 --- a/test/unit/grant-types/client-credentials-grant-type_test.js +++ b/test/unit/grant-types/client-credentials-grant-type_test.js @@ -43,15 +43,15 @@ describe('ClientCredentialsGrantType', function() { }; const handler = new ClientCredentialsGrantType({ accessTokenLifetime: 120, model: model }); - sinon.stub(handler, 'validateScope').returns('foobar'); + sinon.stub(handler, 'validateScope').returns(['foobar']); sinon.stub(handler, 'generateAccessToken').returns('foo'); sinon.stub(handler, 'getAccessTokenExpiresAt').returns('biz'); - return handler.saveToken(user, client, 'foobar') + return handler.saveToken(user, client, ['foobar']) .then(function() { model.saveToken.callCount.should.equal(1); model.saveToken.firstCall.args.should.have.length(3); - model.saveToken.firstCall.args[0].should.eql({ accessToken: 'foo', accessTokenExpiresAt: 'biz', scope: 'foobar' }); + model.saveToken.firstCall.args[0].should.eql({ accessToken: 'foo', accessTokenExpiresAt: 'biz', scope: ['foobar'] }); model.saveToken.firstCall.args[1].should.equal(client); model.saveToken.firstCall.args[2].should.equal(user); model.saveToken.firstCall.thisValue.should.equal(model); diff --git a/test/unit/grant-types/password-grant-type_test.js b/test/unit/grant-types/password-grant-type_test.js index ceb2ad9d..63f43933 100644 --- a/test/unit/grant-types/password-grant-type_test.js +++ b/test/unit/grant-types/password-grant-type_test.js @@ -20,13 +20,14 @@ describe('PasswordGrantType', function() { getUser: sinon.stub().returns(true), saveToken: function() {} }; + const client = { id: 'foobar' }; const handler = new PasswordGrantType({ accessTokenLifetime: 120, model: model }); const request = new Request({ body: { username: 'foo', password: 'bar' }, headers: {}, method: {}, query: {} }); - return handler.getUser(request) + return handler.getUser(request, client) .then(function() { model.getUser.callCount.should.equal(1); - model.getUser.firstCall.args.should.have.length(2); + model.getUser.firstCall.args.should.have.length(3); model.getUser.firstCall.args[0].should.equal('foo'); model.getUser.firstCall.args[1].should.equal('bar'); model.getUser.firstCall.thisValue.should.equal(model); @@ -45,17 +46,17 @@ describe('PasswordGrantType', function() { }; const handler = new PasswordGrantType({ accessTokenLifetime: 120, model: model }); - sinon.stub(handler, 'validateScope').returns('foobar'); + sinon.stub(handler, 'validateScope').returns(['foobar']); sinon.stub(handler, 'generateAccessToken').returns('foo'); sinon.stub(handler, 'generateRefreshToken').returns('bar'); sinon.stub(handler, 'getAccessTokenExpiresAt').returns('biz'); sinon.stub(handler, 'getRefreshTokenExpiresAt').returns('baz'); - return handler.saveToken(user, client, 'foobar') + return handler.saveToken(user, client, ['foobar']) .then(function() { model.saveToken.callCount.should.equal(1); model.saveToken.firstCall.args.should.have.length(3); - model.saveToken.firstCall.args[0].should.eql({ accessToken: 'foo', accessTokenExpiresAt: 'biz', refreshToken: 'bar', refreshTokenExpiresAt: 'baz', scope: 'foobar' }); + model.saveToken.firstCall.args[0].should.eql({ accessToken: 'foo', accessTokenExpiresAt: 'biz', refreshToken: 'bar', refreshTokenExpiresAt: 'baz', scope: ['foobar'] }); model.saveToken.firstCall.args[1].should.equal(client); model.saveToken.firstCall.args[2].should.equal(user); model.saveToken.firstCall.thisValue.should.equal(model); diff --git a/test/unit/grant-types/refresh-token-grant-type_test.js b/test/unit/grant-types/refresh-token-grant-type_test.js index c91a37ed..8d2faee6 100644 --- a/test/unit/grant-types/refresh-token-grant-type_test.js +++ b/test/unit/grant-types/refresh-token-grant-type_test.js @@ -131,11 +131,11 @@ describe('RefreshTokenGrantType', function() { sinon.stub(handler, 'getAccessTokenExpiresAt').returns('biz'); sinon.stub(handler, 'getRefreshTokenExpiresAt').returns('baz'); - return handler.saveToken(user, client, 'foobar') + return handler.saveToken(user, client, ['foobar']) .then(function() { model.saveToken.callCount.should.equal(1); model.saveToken.firstCall.args.should.have.length(3); - model.saveToken.firstCall.args[0].should.eql({ accessToken: 'foo', accessTokenExpiresAt: 'biz', refreshToken: 'bar', refreshTokenExpiresAt: 'baz', scope: 'foobar' }); + model.saveToken.firstCall.args[0].should.eql({ accessToken: 'foo', accessTokenExpiresAt: 'biz', refreshToken: 'bar', refreshTokenExpiresAt: 'baz', scope: ['foobar'] }); model.saveToken.firstCall.args[1].should.equal(client); model.saveToken.firstCall.args[2].should.equal(user); model.saveToken.firstCall.thisValue.should.equal(model); @@ -158,11 +158,11 @@ describe('RefreshTokenGrantType', function() { sinon.stub(handler, 'getAccessTokenExpiresAt').returns('biz'); sinon.stub(handler, 'getRefreshTokenExpiresAt').returns('baz'); - return handler.saveToken(user, client, 'foobar') + return handler.saveToken(user, client, ['foobar']) .then(function() { model.saveToken.callCount.should.equal(1); model.saveToken.firstCall.args.should.have.length(3); - model.saveToken.firstCall.args[0].should.eql({ accessToken: 'foo', accessTokenExpiresAt: 'biz', scope: 'foobar' }); + model.saveToken.firstCall.args[0].should.eql({ accessToken: 'foo', accessTokenExpiresAt: 'biz', scope: ['foobar'] }); model.saveToken.firstCall.args[1].should.equal(client); model.saveToken.firstCall.args[2].should.equal(user); model.saveToken.firstCall.thisValue.should.equal(model); @@ -185,11 +185,11 @@ describe('RefreshTokenGrantType', function() { sinon.stub(handler, 'getAccessTokenExpiresAt').returns('biz'); sinon.stub(handler, 'getRefreshTokenExpiresAt').returns('baz'); - return handler.saveToken(user, client, 'foobar') + return handler.saveToken(user, client, ['foobar']) .then(function() { model.saveToken.callCount.should.equal(1); model.saveToken.firstCall.args.should.have.length(3); - model.saveToken.firstCall.args[0].should.eql({ accessToken: 'foo', accessTokenExpiresAt: 'biz', refreshToken: 'bar', refreshTokenExpiresAt: 'baz', scope: 'foobar' }); + model.saveToken.firstCall.args[0].should.eql({ accessToken: 'foo', accessTokenExpiresAt: 'biz', refreshToken: 'bar', refreshTokenExpiresAt: 'baz', scope: ['foobar'] }); model.saveToken.firstCall.args[1].should.equal(client); model.saveToken.firstCall.args[2].should.equal(user); model.saveToken.firstCall.thisValue.should.equal(model); diff --git a/test/unit/handlers/authenticate-handler_test.js b/test/unit/handlers/authenticate-handler_test.js index ff0a924d..c8433057 100644 --- a/test/unit/handlers/authenticate-handler_test.js +++ b/test/unit/handlers/authenticate-handler_test.js @@ -166,13 +166,13 @@ describe('AuthenticateHandler', function() { getAccessToken: function() {}, verifyScope: sinon.stub().returns(true) }; - const handler = new AuthenticateHandler({ addAcceptedScopesHeader: true, addAuthorizedScopesHeader: true, model: model, scope: 'bar' }); + const handler = new AuthenticateHandler({ addAcceptedScopesHeader: true, addAuthorizedScopesHeader: true, model: model, scope: ['bar'] }); - return handler.verifyScope('foo') + return handler.verifyScope(['foo']) .then(function() { model.verifyScope.callCount.should.equal(1); model.verifyScope.firstCall.args.should.have.length(2); - model.verifyScope.firstCall.args[0].should.equal('foo', 'bar'); + model.verifyScope.firstCall.args[0].should.eql(['foo'], ['bar']); model.verifyScope.firstCall.thisValue.should.equal(model); }) .catch(should.fail); diff --git a/test/unit/handlers/authorize-handler_test.js b/test/unit/handlers/authorize-handler_test.js index 0038c7c4..078f82f8 100644 --- a/test/unit/handlers/authorize-handler_test.js +++ b/test/unit/handlers/authorize-handler_test.js @@ -7,7 +7,6 @@ const AuthorizeHandler = require('../../../lib/handlers/authorize-handler'); const Request = require('../../../lib/request'); const Response = require('../../../lib/response'); -const Promise = require('bluebird'); const sinon = require('sinon'); const should = require('chai').should(); @@ -87,11 +86,11 @@ describe('AuthorizeHandler', function() { }; const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); - return handler.saveAuthorizationCode('foo', 'bar', 'qux', 'biz', 'baz', 'boz') + return handler.saveAuthorizationCode('foo', 'bar', ['qux'], 'biz', 'baz', 'boz') .then(function() { model.saveAuthorizationCode.callCount.should.equal(1); model.saveAuthorizationCode.firstCall.args.should.have.length(3); - model.saveAuthorizationCode.firstCall.args[0].should.eql({ authorizationCode: 'foo', expiresAt: 'bar', redirectUri: 'baz', scope: 'qux' }); + model.saveAuthorizationCode.firstCall.args[0].should.eql({ authorizationCode: 'foo', expiresAt: 'bar', redirectUri: 'baz', scope: ['qux'] }); model.saveAuthorizationCode.firstCall.args[1].should.equal('biz'); model.saveAuthorizationCode.firstCall.args[2].should.equal('boz'); model.saveAuthorizationCode.firstCall.thisValue.should.equal(model); @@ -107,11 +106,11 @@ describe('AuthorizeHandler', function() { }; const handler = new AuthorizeHandler({ authorizationCodeLifetime: 120, model: model }); - return handler.saveAuthorizationCode('foo', 'bar', 'qux', 'biz', 'baz', 'boz', 'codeChallenge', 'codeChallengeMethod') + return handler.saveAuthorizationCode('foo', 'bar', ['qux'], 'biz', 'baz', 'boz', 'codeChallenge', 'codeChallengeMethod') .then(function() { model.saveAuthorizationCode.callCount.should.equal(1); model.saveAuthorizationCode.firstCall.args.should.have.length(3); - model.saveAuthorizationCode.firstCall.args[0].should.eql({ authorizationCode: 'foo', expiresAt: 'bar', redirectUri: 'baz', scope: 'qux', codeChallenge: 'codeChallenge', codeChallengeMethod: 'codeChallengeMethod' }); + model.saveAuthorizationCode.firstCall.args[0].should.eql({ authorizationCode: 'foo', expiresAt: 'bar', redirectUri: 'baz', scope: ['qux'], codeChallenge: 'codeChallenge', codeChallengeMethod: 'codeChallengeMethod' }); model.saveAuthorizationCode.firstCall.args[1].should.equal('biz'); model.saveAuthorizationCode.firstCall.args[2].should.equal('boz'); model.saveAuthorizationCode.firstCall.thisValue.should.equal(model); diff --git a/test/unit/models/token-model_test.js b/test/unit/models/token-model_test.js index 7dcac615..3f2688df 100644 --- a/test/unit/models/token-model_test.js +++ b/test/unit/models/token-model_test.js @@ -1,4 +1,5 @@ const TokenModel = require('../../../lib/models/token-model'); +const InvalidArgumentError = require('../../../lib/errors/invalid-argument-error'); const should = require('chai').should(); /** * Test `Server`. @@ -6,6 +7,101 @@ const should = require('chai').should(); describe('Model', function() { describe('constructor()', function() { + it('throws, if data is empty', function () { + try { + new TokenModel(); + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(InvalidArgumentError); + e.message.should.equal('Missing parameter: `accessToken`'); + } + }); + it('throws, if `accessToken` is missing', function () { + const atExpiresAt = new Date(); + atExpiresAt.setHours(new Date().getHours() + 1); + + const data = { + client: 'bar', + user: 'tar', + accessTokenExpiresAt: atExpiresAt + }; + + try { + new TokenModel(data); + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(InvalidArgumentError); + e.message.should.equal('Missing parameter: `accessToken`'); + } + }); + it('throws, if `client` is missing', function () { + const atExpiresAt = new Date(); + atExpiresAt.setHours(new Date().getHours() + 1); + + const data = { + accessToken: 'foo', + user: 'tar', + accessTokenExpiresAt: atExpiresAt + }; + + try { + new TokenModel(data); + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(InvalidArgumentError); + e.message.should.equal('Missing parameter: `client`'); + } + }); + it('throws, if `user` is missing', function () { + const atExpiresAt = new Date(); + atExpiresAt.setHours(new Date().getHours() + 1); + + const data = { + accessToken: 'foo', + client: 'bar', + accessTokenExpiresAt: atExpiresAt + }; + + try { + new TokenModel(data); + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(InvalidArgumentError); + e.message.should.equal('Missing parameter: `user`'); + } + }); + it('throws, if `accessTokenExpiresAt` is not a Date', function () { + const data = { + accessToken: 'foo', + client: 'bar', + user: 'tar', + accessTokenExpiresAt: '11/10/2023' + }; + + try { + new TokenModel(data); + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(InvalidArgumentError); + e.message.should.equal('Invalid parameter: `accessTokenExpiresAt`'); + } + }); + it('throws, if `refreshTokenExpiresAt` is not a Date', function () { + const data = { + accessToken: 'foo', + client: 'bar', + user: 'tar', + refreshTokenExpiresAt: '11/10/2023' + }; + + try { + new TokenModel(data); + should.fail(); + } catch (e) { + e.should.be.an.instanceOf(InvalidArgumentError); + e.message.should.equal('Invalid parameter: `refreshTokenExpiresAt`'); + } + }); it('should calculate `accessTokenLifetime` if `accessTokenExpiresAt` is set', function() { const atExpiresAt = new Date(); atExpiresAt.setHours(new Date().getHours() + 1); @@ -22,5 +118,38 @@ describe('Model', function() { model.accessTokenLifetime.should.a('number'); model.accessTokenLifetime.should.be.approximately(3600, 2); }); + + it('should throw if the required arguments are not provided', () => { + should.throw(() => { + new TokenModel({}); + }); + }); + + it('should ignore custom attributes if allowExtendedTokenAttributes is not specified as true', () => { + const model = new TokenModel({ + accessToken: 'token', + client: 'client', + user: 'user', + myCustomAttribute: 'myCustomValue' + }); + + should.not.exist(model['myCustomAttribute']); + should.not.exist(model['customAttributes']); + }); + + it('should set custom attributes on the customAttributes field if allowExtendedTokenAttributes is specified as true', () => { + const model = new TokenModel({ + accessToken: 'token', + client: 'client', + user: 'user', + myCustomAttribute: 'myCustomValue' + }, { + allowExtendedTokenAttributes: true + }); + + should.not.exist(model['myCustomAttribute']); + model['customAttributes'].should.be.an('object'); + model['customAttributes']['myCustomAttribute'].should.equal('myCustomValue'); + }); }); }); diff --git a/test/unit/request_test.js b/test/unit/request_test.js index f292e2b4..ee5a2761 100644 --- a/test/unit/request_test.js +++ b/test/unit/request_test.js @@ -5,6 +5,7 @@ */ const Request = require('../../lib/request'); +const InvalidArgumentError = require('../../lib/errors/invalid-argument-error'); const should = require('chai').should(); /** @@ -27,6 +28,24 @@ function generateBaseRequest() { } describe('Request', function() { + it('should throw on missing args', function () { + const args = [ + [undefined, InvalidArgumentError, 'Missing parameter: `headers`'], + [null, TypeError, 'Cannot destructure property \'headers\''], + [{}, InvalidArgumentError, 'Missing parameter: `headers`'], + [{ headers: { }}, InvalidArgumentError, 'Missing parameter: `method`'], + [{ headers: {}, method: 'GET' }, InvalidArgumentError, 'Missing parameter: `query`'], + ]; + + args.forEach(([value, error, message]) => { + try { + new Request(value); + } catch (e) { + e.should.be.instanceOf(error); + e.message.should.include(message); + } + }); + }); it('should instantiate with a basic request', function() { const originalRequest = generateBaseRequest(); @@ -127,6 +146,22 @@ describe('Request', function() { request.custom2.should.eql(originalRequest.custom2); }); + it('should not allow overwriting methods on the Request prototype via custom properties', () => { + const request = new Request({ + query: {}, + method: 'GET', + headers: { + 'content-type': 'application/json' + }, + get() { + // malicious attempt to override the 'get' method + return 'text/html'; + } + }); + + request.get('content-type').should.equal('application/json'); + }); + it('should allow getting of headers using `request.get`', function() { const originalRequest = generateBaseRequest(); diff --git a/test/unit/response_test.js b/test/unit/response_test.js index 8d4897c9..af505ba9 100644 --- a/test/unit/response_test.js +++ b/test/unit/response_test.js @@ -83,6 +83,20 @@ describe('Request', function() { response.custom2.should.eql(originalResponse.custom2); }); + it('should not allow overwriting methods on the Response prototype via custom properties', () => { + const response = new Response({ + headers: { + 'content-type': 'application/json' + }, + get() { + // malicious attempt to override the 'get' method + return 'text/html'; + } + }); + + response.get('content-type').should.equal('application/json'); + }); + it('should allow getting of headers using `response.get`', function() { const originalResponse = generateBaseResponse(); diff --git a/test/unit/server_test.js b/test/unit/server_test.js index 3987df77..fd7bd391 100644 --- a/test/unit/server_test.js +++ b/test/unit/server_test.js @@ -6,7 +6,6 @@ const AuthenticateHandler = require('../../lib/handlers/authenticate-handler'); const AuthorizeHandler = require('../../lib/handlers/authorize-handler'); -const Promise = require('bluebird'); const Server = require('../../lib/server'); const TokenHandler = require('../../lib/handlers/token-handler'); const sinon = require('sinon'); @@ -31,24 +30,6 @@ describe('Server', function() { AuthenticateHandler.prototype.handle.firstCall.args[0].should.equal('foo'); AuthenticateHandler.prototype.handle.restore(); }); - - it('should map string passed as `options` to `options.scope`', function() { - const model = { - getAccessToken: function() {}, - verifyScope: function() {} - }; - const server = new Server({ model: model }); - - sinon.stub(AuthenticateHandler.prototype, 'handle').returns(Promise.resolve()); - - server.authenticate('foo', 'bar', 'test'); - - AuthenticateHandler.prototype.handle.callCount.should.equal(1); - AuthenticateHandler.prototype.handle.firstCall.args[0].should.equal('foo'); - AuthenticateHandler.prototype.handle.firstCall.args[1].should.equal('bar'); - AuthenticateHandler.prototype.handle.firstCall.thisValue.should.have.property('scope', 'test'); - AuthenticateHandler.prototype.handle.restore(); - }); }); describe('authorize()', function() { diff --git a/test/unit/utils/crypto-util_test.js b/test/unit/utils/crypto-util_test.js new file mode 100644 index 00000000..7c3057e0 --- /dev/null +++ b/test/unit/utils/crypto-util_test.js @@ -0,0 +1,18 @@ +const cryptoUtil = require('../../../lib/utils/crypto-util'); +require('chai').should(); + +describe(cryptoUtil.createHash.name, function () { + it('creates a hash by given algorithm', function () { + const data = 'client-credentials-grant'; + const hash = cryptoUtil.createHash({ data, encoding: 'hex' }); + hash.should.equal('072726830f0aadd2d91f86f53e3a7ef40018c2626438152dd576e272bf2b8e60'); + }); + it('should throw if data is missing', function () { + try { + cryptoUtil.createHash({}); + } catch (e) { + e.should.be.instanceOf(TypeError); + e.message.should.include('he "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView.'); + } + }); +}); diff --git a/test/unit/utils/date-util__test.js b/test/unit/utils/date-util__test.js new file mode 100644 index 00000000..47b8e7d5 --- /dev/null +++ b/test/unit/utils/date-util__test.js @@ -0,0 +1,26 @@ +const dateUtil = require('../../../lib/utils/date-util'); + +const sinon = require('sinon'); +require('chai').should(); + +describe('DateUtil', function() { + describe('getLifetimeFromExpiresAt', () => { + const now = new Date('2023-01-01T00:00:00.000Z'); + + beforeEach(() => { + sinon.useFakeTimers(now); + }); + + it('should convert a valid expiration date into seconds from now', () => { + const expiresAt = new Date('2023-01-01T00:00:10.000Z'); + const lifetime = dateUtil.getLifetimeFromExpiresAt(expiresAt); + + lifetime.should.be.a('number'); + lifetime.should.be.approximately(10, 2); + }); + + afterEach(() => { + sinon.restore(); + }); + }); +});