Skip to content

Commit

Permalink
Update ApiBuilder.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
tcaiger committed Oct 21, 2024
1 parent 357d29f commit fa85c49
Showing 1 changed file with 33 additions and 9 deletions.
42 changes: 33 additions & 9 deletions packages/server-boilerplate/src/orchestrator/api/ApiBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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: () =>
Expand Down

0 comments on commit fa85c49

Please sign in to comment.