@axway/axway-central-cli
Version:
Manage APIs, services and publish to the Amplify Marketplace
294 lines (277 loc) • 13.9 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.testables = exports.askBundleType = exports.GitHubSaaSInstallMethods = void 0;
var _chalk = _interopRequireDefault(require("chalk"));
var _snooplogg = _interopRequireDefault(require("snooplogg"));
var _basicPrompts = require("../../common/basicPrompts");
var _types = require("../../common/types");
var helpers = _interopRequireWildcard(require("./helpers"));
var _crypto = _interopRequireDefault(require("crypto"));
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
const {
log
} = (0, _snooplogg.default)('engage: install: agents: saas');
class DataplaneConfig {
constructor(type) {
_defineProperty(this, "type", void 0);
this.type = type || "";
}
}
class GitHubDataplaneConfig extends DataplaneConfig {
constructor(name, ownerName, filter) {
super("GitHub");
_defineProperty(this, "name", void 0);
_defineProperty(this, "ownerName", void 0);
_defineProperty(this, "filter", void 0);
this.name = name;
this.ownerName = ownerName;
this.filter = filter;
}
}
class GitHubFilterConfig {
constructor(paths, branch, pattern) {
_defineProperty(this, "paths", void 0);
_defineProperty(this, "branch", void 0);
_defineProperty(this, "pattern", void 0);
this.paths = paths;
this.branch = branch;
this.pattern = pattern;
}
}
class SaasAgentValues {
constructor() {
_defineProperty(this, "frequencyDA", void 0);
_defineProperty(this, "queueDA", void 0);
_defineProperty(this, "frequencyTA", void 0);
_defineProperty(this, "dataplaneConfig", void 0);
_defineProperty(this, "centralConfig", void 0);
_defineProperty(this, "repositoryOwner", void 0);
_defineProperty(this, "repositoryName", void 0);
_defineProperty(this, "repositoryBranch", void 0);
_defineProperty(this, "filePaths", void 0);
_defineProperty(this, "filePatterns", void 0);
this.frequencyDA = '';
this.queueDA = false;
this.frequencyTA = '';
this.dataplaneConfig = new DataplaneConfig();
this.centralConfig = new _types.CentralAgentConfig();
this.repositoryOwner = '';
this.repositoryName = '';
this.repositoryBranch = '';
this.filePaths = [];
this.filePatterns = [];
}
}
class SaasGitHubAgentValues extends SaasAgentValues {
constructor() {
super();
_defineProperty(this, "accessToken", void 0);
this.accessToken = '';
}
getAccessData() {
let data = JSON.stringify({
accessToken: this.accessToken
});
return data;
}
}
// ConfigFiles - all the config file that are used in the setup
const ConfigFiles = {};
// GitHub SaaSPrompts - all GitHub Saas prompts to the user for input
const SaasPrompts = {
ACCESS_TOKEN: 'Enter the GitHub Access Token the agent will use',
REPOSITORY_OWNER: 'Enter the GitHub Repository Owner the agent will use',
REPOSITORY_NAME: 'Enter the Repository Name the agent will use',
REPOSITORY_BRANCH: 'Enter the Repository Branch the agent will use',
FILE_PATHS: 'Enter a File Path within the repository that the agent will use',
FILE_PATTERNS: 'Enter a File Pattern that the agent will use (Optional)',
DA_FREQUENCY: 'How often should the discovery run, leave blank for integrating in CI/CD process',
QUEUE: 'Do you want to discover immediately after installation',
ENTER_MORE_PATHS: 'Do you want to enter another file path ?',
ENTER_MORE_PATTERNS: 'Do you want to enter another file pattern ?'
};
const askBundleType = async () => {
//GitHub agent has only DA
return _types.BundleType.DISCOVERY;
};
exports.askBundleType = askBundleType;
const askConfigType = async () => {
return _types.AgentConfigTypes.HOSTED;
};
const askForGitHubCredentials = async hostedAgentValues => {
log("gathering access details for GitHub");
hostedAgentValues.accessToken = await (0, _basicPrompts.askInput)({
msg: SaasPrompts.ACCESS_TOKEN,
defaultValue: hostedAgentValues.accessToken !== '' ? hostedAgentValues.accessToken : undefined,
validate: (0, _basicPrompts.validateRegex)(helpers.GitHubRegexPatterns.gitHubAccessTokenRegex, helpers.invalidValueExampleErrMsg('AccessToken', 'ghp_testTokentestTokentestTokentestToken'))
});
return hostedAgentValues;
};
const validateFrequency = () => input => {
let val = (0, _basicPrompts.validateRegex)(helpers.frequencyRegex, helpers.invalidValueExampleErrMsg('frequency', '3d5h12m'))(input);
if (typeof val === "string") {
return val;
}
let r = input.toString().match(/^(\d*)m/);
if (r) {
// only minutes
let mins = r[1];
if (parseInt(mins, 10) < 30) {
return "Minimum frequency is 30m";
}
}
return true;
};
// @ts-ignore
const gatewayConnectivity = async installConfig => {
console.log('\nCONNECTION TO GitHub API GATEWAY:');
console.log(_chalk.default.gray("The Discovery Agent needs to connect to the GitHub API Gateway to discover API's for publishing to Amplify Engage"));
// DeploymentType
let hostedAgentValues = new SaasAgentValues();
if (installConfig.gatewayType === _types.SaaSGatewayTypes.GITHUB) {
// GitHub connection details
hostedAgentValues = new SaasGitHubAgentValues();
hostedAgentValues = await askForGitHubCredentials(hostedAgentValues);
}
// Ask to queue discovery now
log("getting the frequency and if the agent should run now");
console.log(_chalk.default.gray("\n00d00h00m format, where 30m = 30 minutes, 1h = 1 hour, 7d = 7 days, and 7d1h30m = 7 days 1 hour and 30 minutes. Minimum of 30m."));
hostedAgentValues.frequencyDA = await (0, _basicPrompts.askInput)({
msg: SaasPrompts.DA_FREQUENCY,
validate: validateFrequency(),
allowEmptyInput: true
});
hostedAgentValues.queueDA = (await (0, _basicPrompts.askList)({
msg: SaasPrompts.QUEUE,
default: _types.YesNo.No,
choices: _types.YesNoChoices
})) === _types.YesNo.Yes;
// get repository owner
hostedAgentValues.repositoryOwner = await (0, _basicPrompts.askInput)({
msg: SaasPrompts.REPOSITORY_OWNER,
defaultValue: hostedAgentValues.repositoryOwner !== '' ? hostedAgentValues.repositoryOwner : undefined,
validate: (0, _basicPrompts.validateRegex)(helpers.GitHubRegexPatterns.gitHubRepositoryOwnerRegex, helpers.invalidValueExampleErrMsg('Repository Owner', 'axway-github-owner'))
});
// get repository name
hostedAgentValues.repositoryName = await (0, _basicPrompts.askInput)({
msg: SaasPrompts.REPOSITORY_NAME,
defaultValue: hostedAgentValues.repositoryName !== '' ? hostedAgentValues.repositoryName : undefined,
validate: (0, _basicPrompts.validateRegex)(helpers.GitHubRegexPatterns.gitHubRepositoryNameRegex, helpers.invalidValueExampleErrMsg('Repository Name', 'axway-github-repo-name'))
});
// get repository branch
hostedAgentValues.repositoryBranch = await (0, _basicPrompts.askInput)({
msg: SaasPrompts.REPOSITORY_BRANCH,
defaultValue: hostedAgentValues.repositoryBranch !== '' ? hostedAgentValues.repositoryBranch : undefined
});
// get File Paths
let askFilePaths = true;
console.log(_chalk.default.gray("An array of paths within the repository that the agent will gather files for looking for specs"));
while (askFilePaths) {
const path = await (0, _basicPrompts.askInput)({
msg: SaasPrompts.FILE_PATHS,
allowEmptyInput: false,
validate: (0, _basicPrompts.validateRegex)(helpers.GitHubRegexPatterns.gitHubFilePathRegex, helpers.invalidValueExampleErrMsg('File Path', '/apis'))
});
hostedAgentValues.filePaths.push(path);
askFilePaths = (await (0, _basicPrompts.askList)({
msg: SaasPrompts.ENTER_MORE_PATHS,
default: _types.YesNo.No,
choices: _types.YesNoChoices
})) === _types.YesNo.Yes;
}
// get File Patterns
let askFilePatterns = true;
console.log(_chalk.default.gray("An array of regular expressions that a file name must match to be discovered"));
while (askFilePatterns) {
const pattern = await (0, _basicPrompts.askInput)({
msg: SaasPrompts.FILE_PATTERNS,
allowEmptyInput: true
});
if (pattern.trim() !== "") {
hostedAgentValues.filePatterns.push(pattern);
askFilePatterns = (await (0, _basicPrompts.askList)({
msg: SaasPrompts.ENTER_MORE_PATTERNS,
default: _types.YesNo.No,
choices: _types.YesNoChoices
})) === _types.YesNo.Yes;
} else {
askFilePatterns = false;
}
}
return hostedAgentValues;
};
const generateOutput = async installConfig => {
return `Install complete of hosted agent for ${installConfig.gatewayType} region`;
};
const createEncryptedAccessData = async (hostedAgentValues, dataplaneRes) => {
var _dataplaneRes$securit, _dataplaneRes$securit2;
// grab key from data plane resource
let key = ((_dataplaneRes$securit = dataplaneRes.security) === null || _dataplaneRes$securit === void 0 ? void 0 : _dataplaneRes$securit.encryptionKey) || "";
let hash = ((_dataplaneRes$securit2 = dataplaneRes.security) === null || _dataplaneRes$securit2 === void 0 ? void 0 : _dataplaneRes$securit2.encryptionHash) || "";
if (key === "" || hash === "") {
throw Error(`cannot encrypt access data as the encryption key info was incomplete`);
}
console.log(hostedAgentValues.getAccessData());
let encData = _crypto.default.publicEncrypt({
key: key,
padding: _crypto.default.constants.RSA_PKCS1_OAEP_PADDING,
oaepHash: hash
}, Buffer.from(hostedAgentValues.getAccessData()));
return encData.toString("base64");
};
const completeInstall = async (installConfig, apiServerClient, defsManager) => {
/**
* Create agent resources
*/
console.log("\n");
let gitHubAgentValues = installConfig.gatewayConfig;
// create the environment, if necessary
installConfig.centralConfig.environment = installConfig.centralConfig.ampcEnvInfo.isNew ? await helpers.createByResourceType(apiServerClient, defsManager, installConfig.centralConfig.ampcEnvInfo.name, 'Environment', 'env', {
axwayManaged: installConfig.centralConfig.axwayManaged,
production: installConfig.centralConfig.production
}) : installConfig.centralConfig.ampcEnvInfo.name;
if (installConfig.gatewayType === _types.SaaSGatewayTypes.GITHUB) {
gitHubAgentValues.dataplaneConfig = new GitHubDataplaneConfig(gitHubAgentValues.repositoryName, gitHubAgentValues.repositoryOwner, new GitHubFilterConfig(gitHubAgentValues.filePaths, gitHubAgentValues.repositoryBranch, gitHubAgentValues.filePatterns));
}
// create the data plane resource
let dataplaneRes = await helpers.createNewDataPlaneResource(apiServerClient, defsManager, installConfig.centralConfig.environment, _types.GatewayTypeToDataPlane[installConfig.gatewayType], gitHubAgentValues.dataplaneConfig);
// create data plane secret resource
try {
await helpers.createNewDataPlaneSecretResource(apiServerClient, defsManager, installConfig.centralConfig.environment, _types.GatewayTypeToDataPlane[installConfig.gatewayType], dataplaneRes.name, await createEncryptedAccessData(gitHubAgentValues, dataplaneRes));
} catch (error) {
console.log(_chalk.default.redBright("rolling back installation. Please check the credential data before re-running install"));
if (installConfig.centralConfig.ampcEnvInfo.isNew) {
await helpers.deleteByResourceType(apiServerClient, defsManager, installConfig.centralConfig.ampcEnvInfo.name, 'Environment', 'env');
} else {
await helpers.deleteByResourceType(apiServerClient, defsManager, dataplaneRes.name, "Dataplane", "dp", installConfig.centralConfig.environment);
}
return;
}
// create discovery agent resource
installConfig.centralConfig.daAgentName = await helpers.createNewAgentResource(apiServerClient, defsManager, installConfig.centralConfig.environment, _types.GatewayTypeToDataPlane[installConfig.gatewayType], _types.AgentResourceKind.da, _types.AgentTypes.da, installConfig.centralConfig.ampcTeamName, _types.GatewayTypeToDataPlane[installConfig.gatewayType] + " Discovery Agent", dataplaneRes.name, gitHubAgentValues.frequencyDA, gitHubAgentValues.queueDA);
console.log(await generateOutput(installConfig));
};
const GitHubSaaSInstallMethods = exports.GitHubSaaSInstallMethods = {
GetBundleType: askBundleType,
GetDeploymentType: askConfigType,
AskGatewayQuestions: gatewayConnectivity,
FinalizeGatewayInstall: completeInstall,
ConfigFiles: [],
AgentNameMap: {
[_types.AgentTypes.da]: _types.AgentNames.GITHUB_DA
},
GatewayDisplay: _types.SaaSGatewayTypes.GITHUB
};
// These are the items that are not exported, but need to be for testing
const testables = exports.testables = {
SaasAgentValues,
SaasGitHubAgentValues,
SaasPrompts,
ConfigFiles
};