Skip to content

Commit

Permalink
Merge pull request #327 from friggframework/FRI-460_Move-SecretsToEnv…
Browse files Browse the repository at this point in the history
…-to-frigg-core-add-to-createHandler
  • Loading branch information
seanspeaks authored Aug 9, 2024
2 parents 3c2bb94 + 7aba4e4 commit 50b2fde
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
10 changes: 10 additions & 0 deletions packages/core/core/create-handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ require('source-map-support').install();

const { connectToDatabase } = require('../database/mongo');
const { initDebugLog, flushDebugLog } = require('../logs');
const { secretsToEnv } = require('./secrets-to-env');

const createHandler = (optionByName = {}) => {
const {
Expand All @@ -20,6 +21,15 @@ const createHandler = (optionByName = {}) => {
try {
initDebugLog(eventName, event);

const requestMethod = event.httpMethod;
const requestPath = event.path;
if (requestMethod && requestPath) {
console.info(`${requestMethod} ${requestPath}`);
}

// If enabled (i.e. if SECRET_ARN is set in process.env) Fetch secrets from AWS Secrets Manager, and set them as environment variables.
await secretsToEnv();

// Helps mongoose reuse the connection. Lowers response times.
context.callbackWaitsForEmptyEventLoop = false;

Expand Down
61 changes: 61 additions & 0 deletions packages/core/core/secrets-to-env.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
const getSecretValue = async () => {
console.log('Fetching secrets...');

const httpPort = process.env.PARAMETERS_SECRETS_EXTENSION_HTTP_PORT || 2773;
const url = `http://localhost:${httpPort}/secretsmanager/get?secretId=${encodeURIComponent(
process.env.SECRET_ARN
)}`;
const options = {
headers: {
'X-Aws-Parameters-Secrets-Token': process.env.AWS_SESSION_TOKEN,
},
method: 'GET',
};

const response = await fetch(url, options);

if (!response.ok) {
const json = await response.json().catch((err) => err.message);
console.error('Invalid response - response:', JSON.stringify(response));
console.error('Invalid response - json:', json);
throw new Error(`Invalid ${response.status} response`);
}

const result = await response.json();

if (!result) {
throw new Error('Error getting secret', result);
}

return JSON.parse(result.SecretString);
};

const transformSecrets = (secrets) => {
Object.keys(secrets).forEach((key) => {
process.env[key] = secrets[key];
});
};

/**
* Middleware that gets the secrets from Lambda layer and transform into environment variables.
*
*/
const secretsToEnv = async () => {
if (!process.env.SECRET_ARN) {
return;
}
console.log('Secrets to env');

try {
const secrets = await getSecretValue();
transformSecrets(secrets);

return secrets;
} catch (err) {
throw err;
}
};

module.exports = {
secretsToEnv,
};

0 comments on commit 50b2fde

Please sign in to comment.