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

PIN-5682 - Reverting #1131 to fix JWKS timeout #1206

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
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
5 changes: 1 addition & 4 deletions packages/agreement-process/src/app.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {
authenticationMiddleware,
buildJwksClients,
contextMiddleware,
loggerMiddleware,
zodiosCtx,
Expand All @@ -13,15 +12,13 @@ const serviceName = "agreement-process";

const app = zodiosCtx.app();

const jwksClients = buildJwksClients(config);

// Disable the "X-Powered-By: Express" HTTP header for security reasons.
// See https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Headers_Cheat_Sheet.html#recommendation_16
app.disable("x-powered-by");

app.use(healthRouter);
app.use(contextMiddleware(serviceName));
app.use(authenticationMiddleware(config, jwksClients));
app.use(authenticationMiddleware(config));
app.use(loggerMiddleware(serviceName));
app.use(agreementRouter(zodiosCtx));

Expand Down
5 changes: 1 addition & 4 deletions packages/api-gateway/src/app.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {
authenticationMiddleware,
buildJwksClients,
contextMiddleware,
initRedisRateLimiter,
loggerMiddleware,
Expand All @@ -18,8 +17,6 @@ const clients = getInteropBeClients();

const app = zodiosCtx.app();

const jwksClients = buildJwksClients(config);

const redisRateLimiter = await initRedisRateLimiter({
limiterGroup: "API_GW",
maxRequests: config.rateLimiterMaxRequests,
Expand All @@ -40,7 +37,7 @@ app.use(
`/api-gateway/${config.apiGatewayInterfaceVersion}`,
healthRouter,
contextMiddleware(serviceName, false),
authenticationMiddleware(config, jwksClients),
authenticationMiddleware(config),
// Authenticated routes - rate limiter relies on auth data to work
rateLimiterMiddleware(redisRateLimiter),
apiGatewayRouter(zodiosCtx, clients)
Expand Down
5 changes: 1 addition & 4 deletions packages/attribute-registry-process/src/app.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {
authenticationMiddleware,
buildJwksClients,
contextMiddleware,
loggerMiddleware,
zodiosCtx,
Expand All @@ -13,15 +12,13 @@ const serviceName = "attribute-registry-process";

const app = zodiosCtx.app();

const jwksClients = buildJwksClients(config);

// Disable the "X-Powered-By: Express" HTTP header for security reasons.
// See https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Headers_Cheat_Sheet.html#recommendation_16
app.disable("x-powered-by");

app.use(healthRouter);
app.use(contextMiddleware(serviceName));
app.use(authenticationMiddleware(config, jwksClients));
app.use(authenticationMiddleware(config));
app.use(loggerMiddleware(serviceName));
app.use(attributeRouter(zodiosCtx));

Expand Down
5 changes: 1 addition & 4 deletions packages/authorization-process/src/app.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {
authenticationMiddleware,
buildJwksClients,
contextMiddleware,
zodiosCtx,
} from "pagopa-interop-commons";
Expand All @@ -12,15 +11,13 @@ const serviceName = "authorization-process";

const app = zodiosCtx.app();

const jwksClients = buildJwksClients(config);

// Disable the "X-Powered-By: Express" HTTP header for security reasons.
// See https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Headers_Cheat_Sheet.html#recommendation_16
app.disable("x-powered-by");

app.use(healthRouter);
app.use(contextMiddleware(serviceName));
app.use(authenticationMiddleware(config, jwksClients));
app.use(authenticationMiddleware(config));
app.use(authorizationRouter(zodiosCtx));

export default app;
15 changes: 3 additions & 12 deletions packages/backend-for-frontend/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {
zodiosCtx,
initRedisRateLimiter,
rateLimiterMiddleware,
buildJwksClients,
} from "pagopa-interop-commons";
import express from "express";
import { config } from "./config/config.js";
Expand Down Expand Up @@ -40,8 +39,6 @@ const clients = getInteropBeClients();

const app = zodiosCtx.app();

const jwksClients = buildJwksClients(config);

const redisRateLimiter = await initRedisRateLimiter({
limiterGroup: "BFF",
maxRequests: config.rateLimiterMaxRequests,
Expand Down Expand Up @@ -71,22 +68,16 @@ app.use(
`/backend-for-frontend/${config.backendForFrontendInterfaceVersion}`,
healthRouter,
contextMiddleware(serviceName, false),
authorizationRouter(
zodiosCtx,
clients,
allowList,
redisRateLimiter,
jwksClients
),
authenticationMiddleware(config, jwksClients),
authorizationRouter(zodiosCtx, clients, allowList, redisRateLimiter),
authenticationMiddleware(config),
// Authenticated routes - rate limiter relies on auth data to work
rateLimiterMiddleware(redisRateLimiter),
catalogRouter(zodiosCtx, clients, fileManager),
attributeRouter(zodiosCtx, clients),
purposeRouter(zodiosCtx, clients),
agreementRouter(zodiosCtx, clients, fileManager),
selfcareRouter(clients, zodiosCtx),
supportRouter(zodiosCtx, clients, redisRateLimiter, jwksClients),
supportRouter(zodiosCtx, clients, redisRateLimiter),
toolRouter(zodiosCtx, clients),
tenantRouter(zodiosCtx, clients),
clientRouter(zodiosCtx, clients),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {
zodiosValidationErrorToApiProblem,
RateLimiter,
rateLimiterHeadersFromStatus,
buildJwksClients,
} from "pagopa-interop-commons";
import { tooManyRequestsError } from "pagopa-interop-models";
import { makeApiProblem } from "../model/errors.js";
Expand All @@ -22,8 +21,7 @@ const authorizationRouter = (
ctx: ZodiosContext,
{ tenantProcessClient }: PagoPAInteropBeClients,
allowList: string[],
rateLimiter: RateLimiter,
jwksClients: ReturnType<typeof buildJwksClients>
rateLimiter: RateLimiter
): ZodiosRouter<ZodiosEndpointDefinitions, ExpressContext> => {
const authorizationRouter = ctx.router(bffApi.authorizationApi.api, {
validationErrorHandler: zodiosValidationErrorToApiProblem,
Expand All @@ -34,8 +32,7 @@ const authorizationRouter = (
interopTokenGenerator,
tenantProcessClient,
allowList,
rateLimiter,
jwksClients
rateLimiter
);

authorizationRouter
Expand Down
7 changes: 2 additions & 5 deletions packages/backend-for-frontend/src/routers/supportRouter.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { ZodiosEndpointDefinitions } from "@zodios/core";
import { ZodiosRouter } from "@zodios/express";
import {
buildJwksClients,
ExpressContext,
InteropTokenGenerator,
RateLimiter,
Expand All @@ -20,8 +19,7 @@ import { fromBffAppContext } from "../utilities/context.js";
const supportRouter = (
ctx: ZodiosContext,
{ tenantProcessClient }: PagoPAInteropBeClients,
rateLimiter: RateLimiter,
jwksClients: ReturnType<typeof buildJwksClients>
rateLimiter: RateLimiter
): ZodiosRouter<ZodiosEndpointDefinitions, ExpressContext> => {
const supportRouter = ctx.router(bffApi.supportApi.api, {
validationErrorHandler: zodiosValidationErrorToApiProblem,
Expand All @@ -32,8 +30,7 @@ const supportRouter = (
interopTokenGenerator,
tenantProcessClient,
config.tenantAllowedOrigins,
rateLimiter,
jwksClients
rateLimiter
);

supportRouter.post("/session/saml2/tokens", async (req, res) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import {
USER_ROLES,
WithLogger,
decodeJwtToken,
buildJwksClients,
userRoles,
verifyJwtToken,
} from "pagopa-interop-commons";
Expand Down Expand Up @@ -52,8 +51,7 @@ export function authorizationServiceBuilder(
interopTokenGenerator: InteropTokenGenerator,
tenantProcessClient: PagoPAInteropBeClients["tenantProcessClient"],
allowList: string[],
rateLimiter: RateLimiter,
jwksClients: ReturnType<typeof buildJwksClients>
rateLimiter: RateLimiter
) {
const readJwt = async (
identityToken: string,
Expand All @@ -63,12 +61,7 @@ export function authorizationServiceBuilder(
sessionClaims: SessionClaims;
selfcareId: string;
}> => {
const verified = await verifyJwtToken(
identityToken,
jwksClients,
config,
logger
);
const verified = await verifyJwtToken(identityToken, config, logger);
if (!verified) {
throw tokenVerificationFailed();
}
Expand Down
5 changes: 1 addition & 4 deletions packages/catalog-process/src/app.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {
authenticationMiddleware,
buildJwksClients,
contextMiddleware,
loggerMiddleware,
zodiosCtx,
Expand All @@ -13,15 +12,13 @@ const serviceName = "catalog-process";

const app = zodiosCtx.app();

const jwksClients = buildJwksClients(config);

// Disable the "X-Powered-By: Express" HTTP header for security reasons.
// See https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Headers_Cheat_Sheet.html#recommendation_16
app.disable("x-powered-by");

app.use(healthRouter);
app.use(contextMiddleware(serviceName));
app.use(authenticationMiddleware(config, jwksClients));
app.use(authenticationMiddleware(config));
app.use(loggerMiddleware(serviceName));
app.use(eservicesRouter(zodiosCtx));

Expand Down
13 changes: 3 additions & 10 deletions packages/commons/src/auth/authenticationMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
unauthorizedError,
} from "pagopa-interop-models";
import { match } from "ts-pattern";
import { JwksClient } from "jwks-rsa";
import {
ExpressContext,
fromAppContext,
Expand All @@ -18,23 +17,17 @@ import { readAuthDataFromJwtToken, verifyJwtToken } from "./jwt.js";
const makeApiProblem = makeApiProblemBuilder({});

export const authenticationMiddleware: (
config: JWTConfig,
jwksClients: JwksClient[]
config: JWTConfig
) => ZodiosRouterContextRequestHandler<ExpressContext> =
(config: JWTConfig, jwksClients: JwksClient[]) =>
(config: JWTConfig) =>
async (req, res, next): Promise<unknown> => {
// We assume that:
// - contextMiddleware already set ctx.serviceName and ctx.correlationId
const ctx = fromAppContext(req.ctx);

try {
const jwtToken = jwtFromAuthHeader(req, ctx.logger);
const valid = await verifyJwtToken(
jwtToken,
jwksClients,
config,
ctx.logger
);
const valid = await verifyJwtToken(jwtToken, config, ctx.logger);
if (!valid) {
throw unauthorizedError("Invalid token");
}
Expand Down
10 changes: 7 additions & 3 deletions packages/commons/src/auth/jwk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,13 +70,17 @@ export function sortJWK(jwk: JsonWebKey): JsonWebKey {
export function buildJwksClients(config: JWTConfig): JwksClient[] {
return config.wellKnownUrls.map((url) =>
jwksClient({
cache: true,
rateLimit: true,
jwksUri: url,
/* If JWKS_CACHE_MAX_AGE_MILLIS not provided using 10 minutes as default value:
https://github.com/auth0/node-jwks-rsa/blob/master/EXAMPLES.md#configuration
*/
cacheMaxAge: config.jwksCacheMaxAge ?? 600000,

// Caching is not being leveraged at the moment since we are building
// a new client for each request.
// Building clients only once at startup caused https://pagopa.atlassian.net/browse/PIN-5682
// cache: true,
// rateLimit: true,
// cacheMaxAge: config.jwksCacheMaxAge ?? 600000,
})
);
}
4 changes: 2 additions & 2 deletions packages/commons/src/auth/jwt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
jwtDecodingError,
jwksSigningKeyError,
} from "pagopa-interop-models";
import { JWTConfig, Logger } from "../index.js";
import { buildJwksClients, JWTConfig, Logger } from "../index.js";
import { AuthData, AuthToken, getAuthDataFromToken } from "./authData.js";

export const decodeJwtToken = (
Expand Down Expand Up @@ -68,7 +68,6 @@ const getKey = async (

export const verifyJwtToken = async (
jwtToken: string,
jwksClients: jwksClient.JwksClient[],
config: JWTConfig,
logger: Logger
): Promise<boolean> => {
Expand All @@ -81,6 +80,7 @@ export const verifyJwtToken = async (
return Promise.resolve(false);
}

const jwksClients = buildJwksClients(config);
const secret: Secret = await getKey(jwksClients, jwtHeader.kid, logger);

return new Promise((resolve) => {
Expand Down
5 changes: 1 addition & 4 deletions packages/delegation-process/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import {
contextMiddleware,
loggerMiddleware,
zodiosCtx,
buildJwksClients,
} from "pagopa-interop-commons";

import healthRouter from "./routers/HealthRouter.js";
Expand All @@ -15,15 +14,13 @@ const serviceName = "delegation-process";

const app = zodiosCtx.app();

const jwksClients = buildJwksClients(config);

// Disable the "X-Powered-By: Express" HTTP header for security reasons.
// See https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Headers_Cheat_Sheet.html#recommendation_16
app.disable("x-powered-by");

app.use(healthRouter);
app.use(contextMiddleware(serviceName));
app.use(authenticationMiddleware(config, jwksClients));
app.use(authenticationMiddleware(config));
app.use(loggerMiddleware(serviceName));
app.use(delegationRouter(zodiosCtx));
app.use(delegationProducerRouter(zodiosCtx));
Expand Down
5 changes: 1 addition & 4 deletions packages/purpose-process/src/app.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {
authenticationMiddleware,
buildJwksClients,
contextMiddleware,
loggerMiddleware,
zodiosCtx,
Expand All @@ -13,15 +12,13 @@ const serviceName = "purpose-process";

const app = zodiosCtx.app();

const jwksClients = buildJwksClients(config);

// Disable the "X-Powered-By: Express" HTTP header for security reasons.
// See https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Headers_Cheat_Sheet.html#recommendation_16
app.disable("x-powered-by");

app.use(healthRouter);
app.use(contextMiddleware(serviceName));
app.use(authenticationMiddleware(config, jwksClients));
app.use(authenticationMiddleware(config));
app.use(loggerMiddleware(serviceName));
app.use(purposeRouter(zodiosCtx));

Expand Down
Loading