Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: introduce new package @commercetools-backend/express with utilities for working with Custom Applications #1447

Merged
merged 6 commits into from
Apr 20, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
_translations/
dist/
build/
node_modules/*
**/node_modules/*
packages/application-shell/test-utils/index.js
Expand Down
1 change: 1 addition & 0 deletions .vscode/spellright.dict
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ npm
linting
serverless
Node.js
Express.js
Webpack
Transifex
graphql
Expand Down
3 changes: 2 additions & 1 deletion jest.test.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ module.exports = {
moduleDirectories: [
'application-templates',
'packages',
'packages-backend',
'playground',
'node_modules',
],
modulePathIgnorePatterns: ['examples'],
transformIgnorePatterns: [
// Transpile also our local packages as they are only symlinked.
'node_modules/(?!(@commercetools-frontend)/)',
'node_modules/(?!(@commercetools-[frontend|backend]+)/)',
],
testEnvironment: 'jest-environment-jsdom-sixteen',
};
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
"packages": [
"application-templates/*",
"packages/*",
"packages-backend/*",
"playground",
"visual-testing-app",
"website",
Expand Down
1 change: 1 addition & 0 deletions packages-backend/express/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
build
21 changes: 21 additions & 0 deletions packages-backend/express/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 commercetools GmbH

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
45 changes: 45 additions & 0 deletions packages-backend/express/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# @commercetools-backend/express

<p align="center">
<a href="https://www.npmjs.com/package/@commercetools-backend/express"><img src="https://badgen.net/npm/v/@commercetools-backend/express" alt="Latest release (latest dist-tag)" /></a> <a href="https://www.npmjs.com/package/@commercetools-backend/express"><img src="https://badgen.net/npm/v/@commercetools-backend/express/next" alt="Latest release (next dist-tag)" /></a> <a href="https://bundlephobia.com/result?p=@commercetools-backend/express"><img src="https://badgen.net/bundlephobia/minzip/@commercetools-backend/express" alt="Minified + GZipped size" /></a> <a href="https://github.com/commercetools/merchant-center-application-kit/blob/master/LICENSE"><img src="https://badgen.net/github/license/commercetools/merchant-center-application-kit" alt="GitHub license" /></a>
</p>

Zero-config HTTP server as Express.js to facilitate development.

This package is primarily built for HTTP servers used by Custom Applications and it provides a set of components to facilitate the development of the HTTP server.

## Install

```bash
$ npm install --save @commercetools-backend/express
```

## Session middleware

This middleware should be used to handle the authentication exchange between the server and the `/proxy/forward-to` endpoint of the Merchant Center API Gateway.

> You can read more about the "Proxy to External API" concepts [here](https://docs.commercetools.com/custom-applications/main-concepts/proxy-to-external-api).

```js
const {
createSessionMiddleware,
CLOUD_IDENTIFIERS,
} = require('@commercetools-backend/express');

app.use(createSessionMiddleware({ mcApiUrl: CLOUD_IDENTIFIERS.GCP_EU }));
app.use((request, response, next) => {
// `request.session` contains the useful information
});
```

### Middleware options

- `issuer` (_string_): either a cloud identifier or a valid URL to the Merchant Center API Gateway. The cloud identifier maps to the Merchant Center API URL of the related [cloud region](https://docs.commercetools.com/custom-applications/main-concepts/api-gateway#cloud-regions).

- `gcp-au`: `https://mc-api.australia-southeast1.gcp.commercetools.com`
- `gcp-eu`: `https://mc-api.europe-west1.gcp.commercetools.com`
- `gcp-us`: `https://mc-api.us-central1.gcp.commercetools.com`
- `aws-fra`: `https://mc-api.eu-central-1.aws.commercetools.com`
- `aws-ohio`: `https://mc-api.us-east-2.aws.commercetools.com`

- `inferIssuer` (_boolean_): determines whether the issuer should be inferred from the custom request HTTP header `x-mc-api-cloud-identifier` which is sent by the Merchant Center API Gateway when forwarding the request. This might be useful in case the server is used in multiple regions.
48 changes: 48 additions & 0 deletions packages-backend/express/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
{
"name": "@commercetools-backend/express",
"version": "16.5.3",
"description": "Zero-config HTTP server as Express.js to facilitate development",
"bugs": "https://github.com/commercetools/merchant-center-application-kit/issues",
"repository": {
"type": "git",
"url": "https://github.com/commercetools/merchant-center-application-kit.git",
"directory": "packages-backend/express"
},
"homepage": "https://docs.commercetools.com/custom-applications",
"keywords": [
"javascript",
"nodejs",
"express",
"http",
"server",
"toolkit"
],
"license": "MIT",
"private": false,
"publishConfig": {
"access": "public"
},
"main": "./build/index.js",
"typings": "./build/index.d.ts",
"types": "./build/index.d.ts",
"files": [
"build",
"package.json",
"LICENSE",
"README.md"
],
"scripts": {
"prebuild": "rimraf build/**",
"build": "tsc -p tsconfig.build.json"
},
"dependencies": {
"@types/node": "12.12.29",
"express": "4.17.1",
"express-jwt": "5.3.3",
"jwks-rsa": "1.7.0"
},
"devDependencies": {
"@panva/jose": "1.9.3",
"nock": "12.0.3"
}
}
15 changes: 15 additions & 0 deletions packages-backend/express/src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export const CLOUD_IDENTIFIERS = {
GCP_AU: 'gcp-au',
GCP_EU: 'gcp-eu',
GCP_US: 'gcp-us',
AWS_FRA: 'aws-fra',
AWS_OHIO: 'aws-ohio',
} as const;

export const MC_API_URLS = {
GCP_AU: 'https://mc-api.australia-southeast1.gcp.commercetools.com',
GCP_EU: 'https://mc-api.europe-west1.gcp.commercetools.com',
GCP_US: 'https://mc-api.us-central1.gcp.commercetools.com',
AWS_FRA: 'https://mc-api.eu-central-1.aws.commercetools.com',
AWS_OHIO: 'https://mc-api.us-east-2.aws.commercetools.com',
} as const;
2 changes: 2 additions & 0 deletions packages-backend/express/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './constants';
export { default as createSessionMiddleware } from './middlewares/session-middleware';
19 changes: 19 additions & 0 deletions packages-backend/express/src/middlewares/fixtures/jwt-token.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { JWT, JWK, JWKS } from '@panva/jose';

const keyRS256 = JWK.generateSync('RSA', 2048, { use: 'sig', alg: 'RS256' });

const jwksStore = new JWKS.KeyStore([keyRS256]);

const createToken = (options: { issuer: string; audience: string }) =>
JWT.sign(
{
sub: 'user-id',
iss: options.issuer,
aud: options.audience,
[`${options.issuer}/claims/project_key`]: 'project-key',
},
keyRS256,
{ algorithm: 'RS256' }
);

export { jwksStore, createToken };
111 changes: 111 additions & 0 deletions packages-backend/express/src/middlewares/session-middleware.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import nock from 'nock';
import createSessionMiddleware from './session-middleware';
import * as fixtureJWTToken from './fixtures/jwt-token';

describe.each`
cloudIdentifier | issuer
${'https://mc-api.ct-test.com'} | ${'https://mc-api.ct-test.com'}
${'gcp-au'} | ${'https://mc-api.australia-southeast1.gcp.commercetools.com'}
${'gcp-eu'} | ${'https://mc-api.europe-west1.gcp.commercetools.com'}
${'gcp-us'} | ${'https://mc-api.us-central1.gcp.commercetools.com'}
${'aws-fra'} | ${'https://mc-api.eu-central-1.aws.commercetools.com'}
${'aws-ohio'} | ${'https://mc-api.us-east-2.aws.commercetools.com'}
`(
'when the middleware uses as "issuer": "$cloudIdentifier"',
({ cloudIdentifier, issuer }) => {
beforeEach(() => {
nock(issuer)
.get('/.well-known/jwks.json')
.reply(200, fixtureJWTToken.jwksStore.toJWKS());
});
it('should verify the token and attach the session info to the request', async () => {
const sessionMiddleware = createSessionMiddleware({
issuer: cloudIdentifier,
});
const fakeRequest = {
method: 'GET',
header: jest.fn((key) => {
switch (key) {
case 'x-mc-api-cloud-identifier':
return cloudIdentifier;
default:
return undefined;
}
}),
headers: {
authorization: `Bearer ${fixtureJWTToken.createToken({
issuer,
audience: 'http://test-server/foo/bar',
})}`,
},
hostname: 'http://test-server',
originalUrl: '/foo/bar',
};
const fakeResponse = {};
await new Promise((resolve, reject) => {
// @ts-ignore
sessionMiddleware(fakeRequest, fakeResponse, (error) => {
if (error) reject(error);
else resolve();
});
});

expect(fakeRequest).toHaveProperty('session', {
userId: 'user-id',
projectKey: 'project-key',
});
expect(fakeRequest).not.toHaveProperty('decoded_token');
});
if (!cloudIdentifier.startsWith('http')) {
it('should infer cloud identifier from custom HTTP header instead of given "mcApiUrl"', async () => {
const sessionMiddleware = createSessionMiddleware({
issuer: 'https://mc-api.another-ct-test.com', // This value should not matter
inferIssuer: true,
});
const fakeRequest = {
method: 'GET',
header: jest.fn((key) => {
switch (key) {
case 'x-mc-api-cloud-identifier':
return cloudIdentifier;
default:
return undefined;
}
}),
headers: {
authorization: `Bearer ${fixtureJWTToken.createToken({
issuer,
audience: 'http://test-server/foo/bar',
})}`,
},
hostname: 'http://test-server',
originalUrl: '/foo/bar',
};
const fakeResponse = {};
await new Promise((resolve, reject) => {
// @ts-ignore
sessionMiddleware(fakeRequest, fakeResponse, (error) => {
if (error) reject(error);
else resolve();
});
});

expect(fakeRequest).toHaveProperty('session', {
userId: 'user-id',
projectKey: 'project-key',
});
expect(fakeRequest).not.toHaveProperty('decoded_token');
});
}
}
);

describe('when issuer is not a valid URL', () => {
it('should throw a validation error', () => {
expect(() =>
createSessionMiddleware({
issuer: 'invalid url',
})
).toThrowError('Invalid issuer URL');
});
});
Loading