@goldstack/infra-aws
Version:
Utilities to work with AWS infrastructure via the cli.
179 lines • 8.3 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAWSUserFromEnvironmentVariables = getAWSUserFromEnvironmentVariables;
exports.getAWSUserFromContainerEnvironment = getAWSUserFromContainerEnvironment;
exports.getAWSUserFromDefaultLocalProfile = getAWSUserFromDefaultLocalProfile;
exports.getAWSUserFromGoldstackConfig = getAWSUserFromGoldstackConfig;
const assert_1 = __importDefault(require("assert"));
const client_sts_1 = require("@aws-sdk/client-sts");
const credential_providers_1 = require("@aws-sdk/credential-providers");
const awsAuthUtils_1 = require("./awsAuthUtils");
const utils_log_1 = require("@goldstack/utils-log");
async function getAWSUserFromEnvironmentVariables() {
(0, assert_1.default)(process.env.AWS_ACCESS_KEY_ID, 'AWS_ACCESS_KEY_ID not defined.');
(0, assert_1.default)(process.env.AWS_SECRET_ACCESS_KEY, 'AWS_SECRET_ACCESS_KEY not defined');
const credentials = (0, credential_providers_1.fromEnv)();
(0, awsAuthUtils_1.injectCredentials)(credentials, {
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
});
return credentials;
}
/**
* Obtains AWS user credentials from container environment variables for ECS containers.
*/
async function getAWSUserFromContainerEnvironment() {
const ecsCredentials = (0, credential_providers_1.fromContainerMetadata)({
timeout: 5000,
maxRetries: 10, // retry 10 times
});
if (!process.env.AWS_REGION) {
throw new Error('AWS region environment variable ("AWS_REGION") not defined for ECS task.');
}
return ecsCredentials;
}
async function validateCredentials(credentials) {
if ((0, awsAuthUtils_1.hasInjectedCredentials)(credentials)) {
return true;
}
const client = new client_sts_1.STSClient({
credentials,
});
const input = {};
const command = new client_sts_1.GetCallerIdentityCommand(input);
try {
const response = await client.send(command);
if (!response.Account) {
return false;
}
}
catch (e) {
return false;
}
return true;
}
async function getAWSUserFromDefaultLocalProfile() {
let credentials = (0, credential_providers_1.fromIni)();
const envVarValues = {
AWS_SDK_LOAD_CONFIG: process.env.AWS_SDK_LOAD_CONFIG,
};
if (!(await validateCredentials(credentials))) {
(0, utils_log_1.warn)('Cannot load credentials from INI file. Trying process credentials instead.');
// if no access key is found, try loading process_credentials
// see https://github.com/aws/aws-sdk-js/pull/1391
process.env.AWS_SDK_LOAD_CONFIG = '1';
credentials = (0, credential_providers_1.fromProcess)();
}
resetEnvironmentVariables(envVarValues);
return credentials;
}
async function getAWSUserFromGoldstackConfig(config, userName) {
const user = config.users.find((user) => user.name === userName);
if (!user) {
throw new Error(`User '${userName}' does not exist in AWS configuration.`);
}
if (user.type === 'profile') {
const userConfig = user.config;
if (process.env.AWS_SHARED_CREDENTIALS_FILE) {
(0, utils_log_1.warn)(`Using AWS_SHARED_CREDENTIALS_FILE environment variable: '${process.env.AWS_SHARED_CREDENTIALS_FILE}'. awsCredentialsFileName in configuration will be ignored.`);
}
const envVarValues = {
AWS_SDK_LOAD_CONFIG: process.env.AWS_SDK_LOAD_CONFIG,
AWS_SHARED_CREDENTIALS_FILE: process.env.AWS_SHARED_CREDENTIALS_FILE,
AWS_CONFIG_FILE: process.env.AWS_CONFIG_FILE,
};
if (userConfig.awsConfigFileName) {
// support loading from both `config` and `credentials` files, see https://github.com/goldstack/goldstack/issues/17#issuecomment-1044811805 https://github.com/aws/aws-sdk-js/pull/1391
process.env.AWS_SDK_LOAD_CONFIG = '1';
// filename property is ignored if AWS_SDK_LOAD_CONFIG is set; thus need to set AWS_SHARED_CREDENTIALS_FILE.
process.env.AWS_SHARED_CREDENTIALS_FILE = userConfig.awsCredentialsFileName;
process.env.AWS_CONFIG_FILE = userConfig.awsConfigFileName;
}
let credentials;
let filename;
if (!process.env.SHARE_CREDENTIALS_FILE) {
filename = userConfig.awsCredentialsFileName;
}
if (userConfig.credentialsSource !== 'process') {
credentials = (0, credential_providers_1.fromIni)({
profile: userConfig.profile,
filepath: filename,
});
}
else {
// Allow `AWS.ProcessCredentials` to search the default config location `~/.aws/config` in addition to `credentials`
// This matches most other CLI / SDK implementations (including AWS JS SDK v3) and the behaviour of most `credential_process` helper tools
// With this enabled, `AWS_CONFIG_FILE` must not contains an invalid path, but `AWS_SHARED_CREDENTIALS_FILE` can be missing.
if (!userConfig.awsCredentialsFileName) {
process.env.AWS_SDK_LOAD_CONFIG = '1';
}
credentials = (0, credential_providers_1.fromProcess)({
profile: userConfig.profile,
filepath: filename,
});
}
resetEnvironmentVariables(envVarValues);
// if (!(await validateCredentials(credentials))) {
// throw new Error(
// 'Cannot load profile ' +
// userConfig.profile +
// ' from AWS configuration for user ' +
// user.name +
// '. Please perform `aws login` for the profile using the AWS CLI.'
// );
// }
return credentials;
}
if (user.type === 'apiKey') {
const config = user.config;
if (!config.awsAccessKeyId || !config.awsSecretAccessKey) {
throw new Error(`AWS Access credentials not defined for user ${userName}. Define them in infra/aws/config.json.`);
}
process.env.AWS_ACCESS_KEY_ID = config.awsAccessKeyId;
process.env.AWS_SECRET_ACCESS_KEY = config.awsSecretAccessKey;
const credentials = (0, credential_providers_1.fromEnv)();
(0, awsAuthUtils_1.injectCredentials)(credentials, {
accessKeyId: config.awsAccessKeyId,
secretAccessKey: config.awsSecretAccessKey,
});
return credentials;
}
if (user.type === 'environmentVariables') {
const userConfig = user.config;
const awsAccessKeyId = process.env[userConfig.awsAccessKeyIdVariableName];
if (!awsAccessKeyId) {
throw new Error(`Environment variable expected but not found: ${userConfig.awsAccessKeyIdVariableName}`);
}
const awsSecretAccessKey = process.env[userConfig.awsSecretAccessKeyVariableName];
if (!awsSecretAccessKey) {
throw new Error(`Environment variable expected but not found: ${userConfig.awsSecretAccessKeyVariableName}`);
}
const awsDefaultRegion = process.env[userConfig.awsDefaultRegionVariableName];
if (!awsDefaultRegion) {
throw new Error(`Environment variable expected but not found: ${userConfig.awsDefaultRegionVariableName}`);
}
process.env.AWS_ACCESS_KEY_ID = awsAccessKeyId;
process.env.AWS_SECRET_ACCESS_KEY = awsSecretAccessKey;
const credentials = (0, credential_providers_1.fromEnv)();
(0, awsAuthUtils_1.injectCredentials)(credentials, {
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
});
return credentials;
}
throw new Error(`Unknown user config type ${user.type}`);
}
function resetEnvironmentVariables(envVarValues) {
Object.entries(envVarValues).forEach(([key, value]) => {
if (process.env[key] === undefined) {
delete process.env[key];
}
else {
process.env[key] = value;
}
});
}
//# sourceMappingURL=awsUserUtils.js.map