Skip to content

Commit

Permalink
feat: introduce new package server-express with utilities for working…
Browse files Browse the repository at this point in the history
… with Custom Applications
  • Loading branch information
emmenko committed Apr 17, 2020
1 parent 99287af commit e4c41b0
Show file tree
Hide file tree
Showing 15 changed files with 562 additions and 9 deletions.
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 packages/server-express/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
build
21 changes: 21 additions & 0 deletions packages/server-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/server-express/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# @commercetools-frontend/server-express

<p align="center">
<a href="https://www.npmjs.com/package/@commercetools-frontend/server-express"><img src="https://badgen.net/npm/v/@commercetools-frontend/server-express" alt="Latest release (latest dist-tag)" /></a> <a href="https://www.npmjs.com/package/@commercetools-frontend/server-express"><img src="https://badgen.net/npm/v/@commercetools-frontend/server-express/next" alt="Latest release (next dist-tag)" /></a> <a href="https://bundlephobia.com/result?p=@commercetools-frontend/server-express"><img src="https://badgen.net/bundlephobia/minzip/@commercetools-frontend/server-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 for working with Merchant Center Custom Applications

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-frontend/server-express
```

## Session middleware

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

> 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-frontend/server-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 URL. The cloud identifier maps to the MC 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`

- `inferIssuerFromCustomHeader` (_boolean_): determines whether the issuer should be inferred from the custom request HTTP header `x-mc-api-cloud-identifier` which is sent by the MC API when forwarding the request. This might be useful in case the server is used in multiple regions.
48 changes: 48 additions & 0 deletions packages/server-express/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
{
"name": "@commercetools-frontend/server-express",
"version": "16.5.3",
"description": "Zero-config HTTP server as Express.js for working with Merchant Center Custom Applications",
"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/server-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"
}
}
7 changes: 7 additions & 0 deletions packages/server-express/src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
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;
2 changes: 2 additions & 0 deletions packages/server-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';
17 changes: 17 additions & 0 deletions packages/server-express/src/middlewares/fixtures/jwt-token.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { JWT, JWK, JWKS } from '@panva/jose';

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

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

export 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' }
);
101 changes: 101 additions & 0 deletions packages/server-express/src/middlewares/session-middleware.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
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: 'this-value-should-not-matter',
inferIssuerFromCustomHeader: 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');
});
}
}
);
92 changes: 92 additions & 0 deletions packages/server-express/src/middlewares/session-middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import type { TSessionMiddlewareOptions } from '../types';
import type { Request, Response, NextFunction } from 'express';

import { CLOUD_IDENTIFIERS } from '../constants';
import expressJwtMiddleware from 'express-jwt';
import jwksRsa from 'jwks-rsa';

const decodedTokenKey = 'decoded_token';

const mapCloudIdentifierToUrl = (
issuer: TSessionMiddlewareOptions['issuer']
) => {
switch (issuer) {
case CLOUD_IDENTIFIERS['gcp-au']:
return 'https://mc-api.australia-southeast1.gcp.commercetools.com';
case CLOUD_IDENTIFIERS['gcp-eu']: {
return 'https://mc-api.europe-west1.gcp.commercetools.com';
}
case CLOUD_IDENTIFIERS['gcp-us']: {
return 'https://mc-api.us-central1.gcp.commercetools.com';
}
case CLOUD_IDENTIFIERS['aws-fra']:
return 'https://mc-api.eu-central-1.aws.commercetools.com';
case CLOUD_IDENTIFIERS['aws-ohio']:
return 'https://mc-api.us-east-2.aws.commercetools.com';
default:
return undefined;
}
};

type TDecodedJWT = {
sub: string;
iss: string;
[property: string]: string;
};

const writeSessionContext = (
request: Request & { decoded_token: TDecodedJWT }
) => {
const decodedToken = request[decodedTokenKey];
const publicClaimForProjectKey = `${decodedToken.iss}/claims/project_key`;

// @ts-ignore
request.session = {
userId: decodedToken.sub,
projectKey: decodedToken[publicClaimForProjectKey],
};

delete request.decoded_token;
};

function createSessionMiddleware(options: TSessionMiddlewareOptions) {
const configuredIssuer =
mapCloudIdentifierToUrl(options.issuer) ?? options.issuer;

// Return the middleware
return (request: Request, response: Response, next: NextFunction) => {
let issuer = configuredIssuer;
if (options.inferIssuerFromCustomHeader) {
// Attempt to infer the
const cloudIdentifierHeader = request.header('x-mc-api-cloud-identifier');
if (cloudIdentifierHeader) {
issuer = mapCloudIdentifierToUrl(cloudIdentifierHeader) ?? issuer;
}
}
const audience = `${request.hostname}${request.originalUrl}`;
return expressJwtMiddleware({
// Dynamically provide a signing key based on the kid in the header
// and the singing keys provided by the JWKS endpoint
secret: jwksRsa.expressJwtSecret({
cache: options.jwksUseCache ?? true,
rateLimit: options.jwksUseRateLimit ?? true,
jwksRequestsPerMinute: options.jwksRequestsPerMinute ?? 5,
jwksUri: `${issuer}/.well-known/jwks.json`,
}),
requestProperty: decodedTokenKey,
// Validate the audience and the issuer.
audience,
issuer,
algorithms: ['RS256'],
})(request, response, (error) => {
if (error) {
return next(error);
}
// @ts-ignore
writeSessionContext(request);
next();
});
};
}

export default createSessionMiddleware;
29 changes: 29 additions & 0 deletions packages/server-express/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import type { Request } from 'express';

import { CLOUD_IDENTIFIERS } from './constants';

export type TCloudIdentifier = typeof CLOUD_IDENTIFIERS[keyof typeof CLOUD_IDENTIFIERS];

export type TSessionMiddlewareOptions = {
// The cloud identifier (see `CLOUD_IDENTIFIERS`) that maps to the MC API URL
// of the related cloud region or the MC API URL.
issuer: TCloudIdentifier | string;
// Determines whether the issuer should be inferred from the custom request
// HTTP header `x-mc-api-cloud-identifier` which is sent by the MC API when
// forwarding the request.
// This might be useful in case the server is used in multiple regions.
inferIssuerFromCustomHeader?: boolean;

/* Options for the `jwksRsa.expressJwtSecret` */

jwksUseCache?: boolean;
jwksUseRateLimit?: boolean;
jwksRequestsPerMinute?: number;
};

export type TSession = {
userId: string;
projectKey: string;
};

export type TRequestWithSession = Request & { session: TSession };
11 changes: 11 additions & 0 deletions packages/server-express/tsconfig.build.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"declaration": true,
"declarationDir": "build"
},
"exclude": [
"**/fixtures/**",
"**/*.spec.ts"
],
}
Loading

0 comments on commit e4c41b0

Please sign in to comment.