UNPKG

reshuffle-aws-connectors

Version:
263 lines 12.2 kB
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; exports.__esModule = true; exports.BaseAWSConnector = exports.validateURL = exports.validateSecretAccessKey = exports.validateS3URL = exports.validateRegion = exports.validateBucket = exports.validateAccesKeyId = exports.AWS = void 0; var aws_sdk_1 = __importDefault(require("aws-sdk")); exports.AWS = aws_sdk_1["default"]; var crypto_1 = __importDefault(require("crypto")); var object_hash_1 = __importDefault(require("object-hash")); var CoreConnector_1 = require("./CoreConnector"); aws_sdk_1["default"].config.signatureVersion = 'v4'; function validateAccesKeyId(accessKeyId) { if (!/^AK[A-Z0-9]{18}$/.test(accessKeyId)) { throw new Error("Invalid accessKeyId: " + accessKeyId); } return accessKeyId; } exports.validateAccesKeyId = validateAccesKeyId; function validateBucket(bucket) { if (!bucket || !/(?=^.{3,63}$)(?!^(\d+\.)+\d+$)(^(([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])\.)*([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])$)/.test(bucket)) { throw new Error("Invalid bucket: " + bucket); } return bucket; } exports.validateBucket = validateBucket; function validateRegion(region) { if (!/^(af|ap|ca|cn|eu|me|sa|us|us-gov)-(central|east|north|northeast|northwest|south|southeast|southwest|west)-\d$/.test(region)) { throw new Error("Invalid region: " + region); } return region; } exports.validateRegion = validateRegion; function validateS3URL(url) { var match = url.match(/^s3:\/\/([^\/]+)\/(([^\/]+\/)*)([^\/]+)$/); try { validateBucket(match[1]); } catch (_a) { throw new Error("Invalid bucket in S3 URL: " + url); } return url; } exports.validateS3URL = validateS3URL; function validateSecretAccessKey(secretAccessKey) { if (!/^[A-Za-z0-9\/\+=]{40}$/.test(secretAccessKey)) { throw new Error("Invalid secretAccessKey: " + secretAccessKey); } return secretAccessKey; } exports.validateSecretAccessKey = validateSecretAccessKey; function validateURL(url) { if (!/^https?:\/\/([^:]+(:[^@]+)?@)?[0-9a-zA-Z_-]+(\.[0-9a-zA-Z_-]+)*(\/[\.0-9a-zA-Z_-]+)*\/?$/.test(url)) { throw new Error("Invalid URL: " + url); } return url; } exports.validateURL = validateURL; var AWSAccount = /** @class */ (function () { function AWSAccount(options) { this.options = options; this.clients = {}; validateAccesKeyId(options.accessKeyId); validateSecretAccessKey(options.secretAccessKey); if (options.region) { validateRegion(options.region); } } AWSAccount.prototype.getClient = function (service, options) { if (options === void 0) { options = {}; } var opts = __assign(__assign({}, this.options), options); var hash = object_hash_1["default"]({ service: service, opts: opts }); if (!this.clients[hash]) { var constructor = aws_sdk_1["default"][service]; this.clients[hash] = new constructor(opts); } return this.clients[hash]; }; AWSAccount.prototype.getCredentials = function () { if (!this.options) { throw new Error('Credentials must be specified in connector options'); } return { accessKeyId: this.options.accessKeyId, secretAccessKey: this.options.secretAccessKey }; }; return AWSAccount; }()); var AWSIdentity = /** @class */ (function () { function AWSIdentity(account) { this.account = account; } AWSIdentity.prototype.createPolicy = function (statements) { var sts = Array.isArray(statements) ? statements : [statements]; return { Version: '2012-10-17', Statement: sts.map(function (st) { return ({ Effect: st.effect, Action: st.action, Resource: st.resource }); }) }; }; AWSIdentity.prototype.createSimplePolicy = function (resource, action, effect) { if (effect === void 0) { effect = 'Allow'; } return this.createPolicy({ effect: effect, resource: resource, action: action }); }; AWSIdentity.prototype.getOrCreateServiceRole = function (roleName, service, policies) { return __awaiter(this, void 0, void 0, function () { var iam, res, e_1, res, policiesArray, _i, policiesArray_1, policy; return __generator(this, function (_a) { switch (_a.label) { case 0: iam = this.account.getClient('IAM'); _a.label = 1; case 1: _a.trys.push([1, 3, , 12]); return [4 /*yield*/, iam.getRole({ RoleName: roleName }).promise()]; case 2: res = _a.sent(); return [2 /*return*/, res.Role]; case 3: e_1 = _a.sent(); if (e_1.code !== 'NoSuchEntity') { throw e_1; } console.log("Creating IAM role for service " + service + ": " + roleName); return [4 /*yield*/, iam .createRole({ RoleName: roleName, AssumeRolePolicyDocument: JSON.stringify({ Version: '2012-10-17', Statement: [ { Effect: 'Allow', Principal: { Service: service }, Action: 'sts:AssumeRole' }, ] }) }) .promise()]; case 4: res = _a.sent(); policiesArray = policies === undefined ? [] : Array.isArray(policies) ? policies : [policies]; _i = 0, policiesArray_1 = policiesArray; _a.label = 5; case 5: if (!(_i < policiesArray_1.length)) return [3 /*break*/, 10]; policy = policiesArray_1[_i]; if (!(typeof policy === 'string')) return [3 /*break*/, 7]; return [4 /*yield*/, iam .attachRolePolicy({ RoleName: roleName, PolicyArn: policy }) .promise()]; case 6: _a.sent(); return [3 /*break*/, 9]; case 7: return [4 /*yield*/, iam .putRolePolicy({ PolicyDocument: JSON.stringify(policy), PolicyName: "policy_" + roleName + "_" + crypto_1["default"].randomBytes(4).toString('hex'), RoleName: roleName }) .promise()]; case 8: _a.sent(); _a.label = 9; case 9: _i++; return [3 /*break*/, 5]; case 10: // It takes a while for a service role to become assumable return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, 10000); })]; case 11: // It takes a while for a service role to become assumable _a.sent(); return [2 /*return*/, res.Role]; case 12: return [2 /*return*/]; } }); }); }; return AWSIdentity; }()); var BaseAWSConnector = /** @class */ (function (_super) { __extends(BaseAWSConnector, _super); function BaseAWSConnector(app, options, id) { var _this = _super.call(this, app, options, id) || this; _this.account = new AWSAccount(options); _this.identity = new AWSIdentity(_this.account); return _this; } return BaseAWSConnector; }(CoreConnector_1.CoreConnector)); exports.BaseAWSConnector = BaseAWSConnector; //# sourceMappingURL=BaseAWSConnector.js.map