Skip to content

Commit

Permalink
fix(security): upgrade express-jwt to v8.4.1
Browse files Browse the repository at this point in the history
Fixes/changes that needed to be done in order to make the upgrade work:
1. The HTTP verbs for exempted endpoints are now specified both as
lowercase and uppercase meaning that if a specific endpoint is configured
to be exempt from JWT authorization then it's method will be specified
twice, once as 'POST' and once as 'post' because the underlying library
(which is called express-unless) does not have the ability to handle
verbs in a case insensitive way.

2. In the registerWebServiceEndpoint function, the configuration of the
express-jwt-authz library had to be changed because the scope enforcement
was broken due to express-jwt changing the default request property
where it places the decoded JWT payload from `"user"` to `"auth"` and
this made it incompatible by default with the behavior of express-jwt-authz
Luckily there is a parameter to set the request property name and that is
now being specified explicitly as `"auth"` so that they are playing nice
with each other once again and the authorization's scope based access
control works just fine.

Fixes #2231

Signed-off-by: Peter Somogyvari <peter.somogyvari@accenture.com>
  • Loading branch information
petermetz committed Apr 5, 2023
1 parent 495a3c5 commit e251168
Show file tree
Hide file tree
Showing 18 changed files with 1,552 additions and 157 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,6 @@
},
"devDependencies": {
"@types/express": "4.17.13",
"@types/express-jwt": "6.0.2",
"@types/fs-extra": "9.0.12",
"@types/uuid": "8.3.1",
"hardhat": "2.6.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
} from "@hyperledger/cactus-cmd-api-server";

import {
IJoseFittingJwtParams,
LoggerProvider,
LogLevelDesc,
Servers,
Expand Down Expand Up @@ -56,7 +57,7 @@ test("BEFORE " + testCase, async (t: Test) => {
test.skip(testCase, async (t: Test) => {
const jwtKeyPair = await generateKeyPair("RS256", { modulusLength: 4096 });
const jwtPublicKey = await exportSPKI(jwtKeyPair.publicKey);
const expressJwtOptions: expressJwt.Options = {
const expressJwtOptions: expressJwt.Params & IJoseFittingJwtParams = {
algorithms: ["RS256"],
secret: jwtPublicKey,
audience: "carbon-accounting-tool-servers-hostname-here",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
Logger,
LoggerProvider,
Servers,
IJoseFittingJwtParams,
} from "@hyperledger/cactus-common";

import {
Expand Down Expand Up @@ -162,7 +163,7 @@ export class SupplyChainApp {
async createAuthorizationConfig(): Promise<void> {
const jwtKeyPair = await generateKeyPair("RS256", { modulusLength: 4096 });
const jwtPrivateKeyPem = await exportPKCS8(jwtKeyPair.privateKey);
const expressJwtOptions: expressJwt.Options = {
const expressJwtOptions: expressJwt.Params & IJoseFittingJwtParams = {
algorithms: ["RS256"],
secret: jwtPrivateKeyPem,
audience: uuidv4(),
Expand Down
3 changes: 1 addition & 2 deletions packages/cactus-cmd-api-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@
"cors": "2.8.5",
"express": "4.17.3",
"express-http-proxy": "1.6.2",
"express-jwt": "6.0.0",
"express-jwt": "8.4.1",
"express-openapi-validator": "4.12.12",
"express-rate-limit": "6.7.0",
"fs-extra": "10.0.0",
Expand All @@ -97,7 +97,6 @@
"@types/cors": "2.8.12",
"@types/express": "4.17.13",
"@types/express-http-proxy": "1.6.2",
"@types/express-jwt": "6.0.2",
"@types/google-protobuf": "3.15.5",
"@types/jsonwebtoken": "8.5.4",
"@types/multer": "1.4.7",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { RequestHandler } from "express";
import expressJwt from "express-jwt";
import { expressjwt, Params as ExpressJwtOptions } from "express-jwt";
import { Optional } from "typescript-optional";

import {
Expand Down Expand Up @@ -83,13 +83,23 @@ export class AuthorizerFactory {
throw new Error(`${fnTag}: ${E_BAD_EXPRESS_JWT_OPTIONS}`);
}

const options: expressJwt.Options = {
const options: ExpressJwtOptions & { [key: string]: unknown } = {
audience: "org.hyperledger.cactus", // default that can be overridden
...expressJwtOptions,
};
const unprotectedEndpoints = this.unprotectedEndpoints.map((e) => {
const verbLowerCase = e.getVerbLowerCase();

// including both cases of the HTTP verbs because upgrading the
// express-unless dependency (through the upgrade of express-jwt)
// broke the test cases that were verifying if the exemptions are
// enforced correctly.
// This test breakage was traced back to express-unless not realizing
// that there is a match of verbs if they are differently cased.
const methods = [verbLowerCase.toUpperCase(), verbLowerCase];

// type pathFilter = string | RegExp | { url: string | RegExp, methods?: string[], method?: string | string[] };
return { url: e.getPath(), method: e.getVerbLowerCase() };
return { url: e.getPath(), methods };
});
if (socketIoPath) {
log.info("SocketIO path configuration detected: %o", socketIoPath);
Expand All @@ -99,7 +109,7 @@ export class AuthorizerFactory {
"Exempted SocketIO path from express-jwt authorization. Using @thream/socketio-jwt instead)",
);
}
return expressJwt(options).unless({ path: unprotectedEndpoints });
return expressjwt(options).unless({ path: unprotectedEndpoints });
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import type { Options as ExpressJwtOptions } from "express-jwt";
import type { AuthorizeOptions as SocketIoJwtOptions } from "@thream/socketio-jwt";

export interface IAuthorizationConfig {
expressJwtOptions: ExpressJwtOptions;
expressJwtOptions: Record<string, unknown>;
socketIoJwtOptions: SocketIoJwtOptions;
unprotectedEndpointExemptions: Array<string>;
socketIoPath?: string;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Strings } from "@hyperledger/cactus-common";
import { Options } from "express-jwt";
import { Params } from "express-jwt";

export function isExpressJwtOptions(x: unknown): x is Options {
export function isExpressJwtOptions(x: unknown): x is Params {
return (
!!x &&
typeof x === "object" &&
Array.isArray((x as Options).algorithms) &&
Strings.isString((x as Options).secret)
Array.isArray((x as Params).algorithms) &&
Strings.isString((x as Params).secret)
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
GeneralSign,
generalVerify,
} from "jose";
import type { Options as ExpressJwtOptions } from "express-jwt";
import type { Params as ExpressJwtOptions } from "express-jwt";
import jsonStableStringify from "json-stable-stringify";
import {
LoggerProvider,
Expand Down Expand Up @@ -592,7 +592,7 @@ export class ConfigService {

const jwtSecret = uuidV4();

const expressJwtOptions: ExpressJwtOptions = {
const expressJwtOptions: ExpressJwtOptions & { [key: string]: unknown } = {
secret: jwtSecret,
algorithms: ["RS256"],
audience: "org.hyperledger.cactus.jwt.audience",
Expand Down Expand Up @@ -664,7 +664,6 @@ export class ConfigService {
const schema: Schema<ICactusApiServerOptions> = ConfigService.getConfigSchema();
ConfigService.config = (convict as any)(schema, options);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
if (ConfigService.config.get("configFile")) {
const configFilePath = ConfigService.config.get("configFile");
ConfigService.config.loadFile(configFilePath);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,17 @@ import {
import expressJwt from "express-jwt";
import "jest-extended";

import { LoggerProvider, LogLevelDesc } from "@hyperledger/cactus-common";
import { IJoseFittingJwtParams } from "@hyperledger/cactus-common";
import { Configuration } from "@hyperledger/cactus-core-api";

import {
ApiServer,
ConfigService,
ICactusApiServerOptions,
isHealthcheckResponse,
} from "../../../main/typescript/public-api";
import { DefaultApi as ApiServerApi } from "../../../main/typescript/public-api";
import { LoggerProvider, LogLevelDesc } from "@hyperledger/cactus-common";
import { Configuration } from "@hyperledger/cactus-core-api";
import { AuthorizationProtocol } from "../../../main/typescript/config/authorization-protocol";
import { IAuthorizationConfig } from "../../../main/typescript/authzn/i-authorization-config";

Expand All @@ -30,7 +32,7 @@ const log = LoggerProvider.getOrCreate({

describe(testCase, () => {
let apiServer: ApiServer,
expressJwtOptions: expressJwt.Options,
expressJwtOptions: expressJwt.Params & IJoseFittingJwtParams,
jwtKeyPair: GenerateKeyPairResult,
apiSrvOpts: ICactusApiServerOptions;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import expressJwt from "express-jwt";
import axios, { Method } from "axios";

import { LogLevelDesc } from "@hyperledger/cactus-common";
import { IJoseFittingJwtParams } from "@hyperledger/cactus-common";
import { PluginRegistry } from "@hyperledger/cactus-core";

import {
Expand Down Expand Up @@ -35,7 +36,7 @@ describe(testCase, () => {
modulusLength: 4096,
});
const jwtPublicKey = await exportSPKI(jwtKeyPair.publicKey);
const expressJwtOptions: expressJwt.Options = {
const expressJwtOptions: expressJwt.Params & IJoseFittingJwtParams = {
algorithms: ["RS256"],
secret: jwtPublicKey,
audience: uuidv4(),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import test, { Test } from "tape-promise/tape";
import { v4 as uuidv4 } from "uuid";
import { generateKeyPair, exportSPKI, SignJWT } from "jose";
import type { Options as ExpressJwtOptions } from "express-jwt";
import type { Params as ExpressJwtOptions } from "express-jwt";
import type { AuthorizeOptions as SocketIoJwtOptions } from "@thream/socketio-jwt";

import { Constants } from "@hyperledger/cactus-core-api";
import { LoggerProvider, LogLevelDesc } from "@hyperledger/cactus-common";
import { IJoseFittingJwtParams } from "@hyperledger/cactus-common";

import {
ApiServer,
ConfigService,
Expand All @@ -13,7 +16,6 @@ import {
} from "../../../main/typescript/public-api";
import { ApiServerApiClient } from "../../../main/typescript/public-api";
import { ApiServerApiClientConfiguration } from "../../../main/typescript/public-api";
import { LoggerProvider, LogLevelDesc } from "@hyperledger/cactus-common";
import { AuthorizationProtocol } from "../../../main/typescript/config/authorization-protocol";
import { IAuthorizationConfig } from "../../../main/typescript/authzn/i-authorization-config";

Expand All @@ -28,7 +30,7 @@ test(testCase, async (t: Test) => {
try {
const jwtKeyPair = await generateKeyPair("RS256", { modulusLength: 4096 });
const jwtPublicKey = await exportSPKI(jwtKeyPair.publicKey);
const expressJwtOptions: ExpressJwtOptions = {
const expressJwtOptions: ExpressJwtOptions & IJoseFittingJwtParams = {
algorithms: ["RS256"],
secret: jwtPublicKey,
audience: uuidv4(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ test(testCase, async () => {
try {
const jwtKeyPair = await generateKeyPair("RS256", { modulusLength: 4096 });
const jwtPublicKey = await exportSPKI(jwtKeyPair.publicKey);
const expressJwtOptions: expressJwt.Options = {
const expressJwtOptions: expressJwt.Params & { [key: string]: unknown } = {
algorithms: ["RS256"],
secret: jwtPublicKey,
audience: uuidv4(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import axios, { Method } from "axios";
import { StatusCodes } from "http-status-codes";

import { LoggerProvider, LogLevelDesc } from "@hyperledger/cactus-common";
import { IJoseFittingJwtParams } from "@hyperledger/cactus-common";
import { PluginRegistry } from "@hyperledger/cactus-core";

import {
Expand Down Expand Up @@ -39,7 +40,7 @@ describe(testCase, () => {
modulusLength: 4096,
});
const jwtPublicKey = await exportSPKI(jwtKeyPair.publicKey);
const expressJwtOptions: expressJwt.Options = {
const expressJwtOptions: expressJwt.Params & IJoseFittingJwtParams = {
algorithms: ["RS256"],
secret: jwtPublicKey,
audience: uuidv4(),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* This interface is defined as the lowest common denominator between
* two different types that libraries use that are related to each other.
* The libraries are: `jose` and `express-jwt`.
*
* Why though?
* We need this because when we are using `jose` to sign a JWT payload,
* we are extracting the parameters from a `Params` typed object (which
* is defined as a type by `express-jwt`) and the two have certain
* incompatibilities by default that would either force us to do
* unsafe casts or (the better solution) to do runtime checks. Said
* runtime checks is what this interface is powering through a user-
* defined type-guard.
*
* The list of properties on this interface is incomplete, but that is
* by design because we just want to use it to check whether objects
* are compliant or not with the expectations of the `jose` library for
* JWT signing.
*
* @link https://www.npmjs.com/package/express-jwt
* @link https://www.npmjs.com/package/jose
* @link https://www.rfc-editor.org/rfc/rfc7519
*/
export interface IJoseFittingJwtParams {
[key: string]: unknown;
readonly issuer: string;
readonly audience: string;
}

/**
* User defined type-guard to check/enforce at runtime if an object has
* the shape it needs to for it to be used by the `jose` library for
* parameters to a JWT signing operation.
*
* @param x Literally anything, ideally a IJoseFittingJwtParams shaped
* object.
* @returns Whether x is conformant (at runtime) to the expected type.
*/
export function isIJoseFittingJwtParams(
x: unknown,
): x is IJoseFittingJwtParams {
return true;
}
5 changes: 5 additions & 0 deletions packages/cactus-common/src/main/typescript/public-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,8 @@ export { Secp256k1Keys } from "./secp256k1-keys";
export { KeyFormat, KeyConverter } from "./key-converter";
export { IAsyncProvider } from "./i-async-provider";
export { Http405NotAllowedError } from "./http/http-status-code-errors";

export {
IJoseFittingJwtParams,
isIJoseFittingJwtParams,
} from "./authzn/i-jose-fitting-jwt-params";
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import expressJwtAuthz from "express-jwt-authz";
import expressJwtAuthz, { AuthzOptions } from "express-jwt-authz";
import { Express } from "express";

import { IWebServiceEndpoint } from "@hyperledger/cactus-core-api";
Expand Down Expand Up @@ -29,7 +29,13 @@ export async function registerWebServiceEndpoint(
const registrationMethod = webAppCasted[httpVerb].bind(webApp);
try {
if (isProtected) {
const scopeCheckMiddleware = expressJwtAuthz(requiredRoles);
const opts: AuthzOptions = {
failWithError: true,
customScopeKey: "scope",
customUserKey: "auth",
checkAllScopes: true,
};
const scopeCheckMiddleware = expressJwtAuthz(requiredRoles, opts);
registrationMethod(httpPath, scopeCheckMiddleware, requestHandler);
} else {
registrationMethod(httpPath, requestHandler);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,6 @@ describe(testCase, () => {
addressInfo = httpServer?.address() as AddressInfo;

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
protocol = config.get("apiTlsEnabled") ? "https:" : "http:";
basePath = `${protocol}//${addressInfo.address}:${addressInfo.port}`;
configuration = new Configuration({ basePath });
Expand Down
Loading

0 comments on commit e251168

Please sign in to comment.