diff --git a/packages/server-boilerplate/src/orchestrator/api/ApiBuilder.ts b/packages/server-boilerplate/src/orchestrator/api/ApiBuilder.ts index feccb525e8..5324074093 100644 --- a/packages/server-boilerplate/src/orchestrator/api/ApiBuilder.ts +++ b/packages/server-boilerplate/src/orchestrator/api/ApiBuilder.ts @@ -34,6 +34,8 @@ import { AccessPolicyBuilder } from '@tupaia/auth'; // eslint-disable-next-line @typescript-eslint/no-var-requires const i18n = require('i18n'); +const TRUSTED_PROXIES_INTERVAL = 60000; // 1 minute + export class ApiBuilder { private readonly app: Express; private readonly database: TupaiaDatabase; @@ -64,15 +66,10 @@ export class ApiBuilder { this.verifyAuthMiddleware = emptyMiddleware; // Do nothing by default this.attachAccessPolicy = buildAttachAccessPolicy(new AccessPolicyBuilder(this.models)); - // Dynamically set trusted proxy so that we can trust the IP address of the client - publicIp - .v4() - .then(publicIp => { - this.app.set('trust proxy', ['loopback', process.env.AWS_TRUSTED_PROXY_IP, publicIp]); - }) - .catch(err => { - console.error('Error fetching public IP:', err); - }); + /** + * Set trusted proxies + */ + this.startTrustedProxiesInterval(); /** * Access logs @@ -213,6 +210,33 @@ export class ApiBuilder { return this; } + /** + * Call the setTrustedProxies function periodically to update the trusted proxies + * because it's possible for the server's IP address to change while server is running + */ + private startTrustedProxiesInterval = () => { + this.setTrustedProxies(); // Call it once immediately + setInterval(this.setTrustedProxies, TRUSTED_PROXIES_INTERVAL); + }; + + /** + * Dynamically set trusted proxy so that we can trust the IP address of the client + */ + private setTrustedProxies = () => { + const trustedProxyIPs = process.env.TRUSTED_PROXY_IPS + ? process.env.TRUSTED_PROXY_IPS.split(',').map(ip => ip.trim()) + : []; + + publicIp + .v4() + .then(publicIp => { + this.app.set('trust proxy', ['loopback', ...trustedProxyIPs, publicIp]); + }) + .catch(err => { + console.error('Error fetching public IP:', err); + }); + }; + public use(path: string, ...middleware: RequestHandler[]) { this.handlers.push({ add: () =>