From 82f5a0c82bfc4d43dfdd73e39e51e3232d0b518c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Francisco=20L=C3=B3pez?= Date: Wed, 28 May 2025 15:28:18 +0200 Subject: [PATCH] refactor: implement caching for public key retrieval in JwtHttpStrategy --- .../src/common/guards/strategy/jwt.http.ts | 39 ++++++++++++++----- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/packages/apps/fortune/exchange-oracle/server/src/common/guards/strategy/jwt.http.ts b/packages/apps/fortune/exchange-oracle/server/src/common/guards/strategy/jwt.http.ts index b7df3e905d..7f948fddc8 100644 --- a/packages/apps/fortune/exchange-oracle/server/src/common/guards/strategy/jwt.http.ts +++ b/packages/apps/fortune/exchange-oracle/server/src/common/guards/strategy/jwt.http.ts @@ -14,6 +14,11 @@ import { AuthError, ValidationError } from '../../errors'; @Injectable() export class JwtHttpStrategy extends PassportStrategy(Strategy, 'jwt-http') { + // In-memory cache for public keys with expiration + private publicKeyCache: Map = + new Map(); + private cacheTTL = 24 * 60 * 60 * 1000; // 1 day + constructor(private readonly web3Service: Web3Service) { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), @@ -26,15 +31,31 @@ export class JwtHttpStrategy extends PassportStrategy(Strategy, 'jwt-http') { try { const payload = jwt.decode(rawJwtToken); const chainId = this.web3Service.getValidChains()[0]; - const signer = this.web3Service.getSigner(chainId); - - const url = await this.getFileUrlAndVerifyHash( - signer, - chainId, - (payload as any).reputation_network, - JWT_KVSTORE_KEY, - ); - const publicKey = await StorageClient.downloadFileFromUrl(url); + const address = (payload as any).reputation_network; + const cacheKey = `${chainId}-${address}`; + + const cached = this.publicKeyCache.get(cacheKey); + + let publicKey: string | undefined; + if (cached && cached.expires > Date.now()) { + publicKey = cached.value; + } else { + const signer = this.web3Service.getSigner(chainId); + const url = await this.getFileUrlAndVerifyHash( + signer, + chainId, + address, + JWT_KVSTORE_KEY, + ); + publicKey = (await StorageClient.downloadFileFromUrl( + url, + )) as string; + + this.publicKeyCache.set(cacheKey, { + value: publicKey, + expires: Date.now() + this.cacheTTL, + }); + } done(null, publicKey); } catch (error) {