Thursday, 29 April 2021

AWS Secrets manager and setupProxy.js http-proxy-middleware

I need to pull in configs from secrets manager before wiring up my proxies

const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const { SecretsManagerClient, GetSecretValueCommand } = require('@aws-sdk/client-secrets-manager');
const pjson = require('../app/config');
const app = express();
async function getSecretsManager(){
    return secrets; // (this functions correctly, redacting for security)
}

const buildProxies = async (app) => {
    const proxies = pjson['nonprod-proxies'];
    const secrets = await getSecretsManager();
    let proxiesToMap = [];
    proxies.forEach(proxy => {
        console.log(`[PROXY SERVER] Creating proxy for: ${proxy['proxy-path']}`);
        let target, headers, options;
        const rewrite = `^${proxy['proxy-path']}`;
        if (proxy['internal'])
        {
            target = `https://${secrets['apiDomain']}`;
            headers = {'x-api-key': secrets['apiKey']};
            options = {
                target: target,
                changeOrigin: true,
                logLevel: 'debug',
                headers
            }
        } else {
            target = proxy['proxy-domain'];
            options = {
                target: `https://${target}`,
                changeOrigin: true,
                logLevel: 'debug',
                pathRewrite: {
                    [rewrite]: ''
                }
            }
        }
        proxiesToMap.push({'path': proxy['proxy-path'], 'options': options})
    });
    return proxiesToMap;
};

module.exports = function(app){
    buildProxies().then(proxies => {
        proxies.forEach(proxyVal => {
            console.log(`Proxy: ${proxyVal['path']} with options ${proxyVal['options']}`);
            app.use(proxyVal['path'], createProxyMiddleware(proxyVal['options']))
        });
    });
    console.log('=== SUCCESSFULY CREATED PROXY SERVER ===');
};

This results in localhost:3000 returning the boiler plate html cors response, however, when substituting the code for module.exports to be:

app.use('/internal/*', createProxyMiddleware({
    target: '<my aws secret url>',
    changeOrigin: true,
    logLevel: 'debug',
    headers: { 'x-api-key': '<my aws secret api key>' }
}));

The proxy works. Is there a way to do an asynchronous load of configs within setupProxy.js?



from AWS Secrets manager and setupProxy.js http-proxy-middleware

No comments:

Post a Comment