snyk
Version:
snyk library and cli utility
1,009 lines (968 loc) • 34.6 kB
JavaScript
;
exports.id = 617;
exports.ids = [617];
exports.modules = {
/***/ 33111:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.InvalidArgumentError = exports.isIacShareResultsOptions = exports.assertTerraformPlanModes = exports.assertIntegratedIaCOnlyOptions = exports.assertIaCOptionsFlags = exports.UnsupportedEntitlementCommandError = exports.UnsupportedEntitlementFlagError = exports.FlagValueError = exports.FeatureFlagError = exports.IntegratedFlagError = exports.FlagError = void 0;
const errors_1 = __webpack_require__(55191);
const args_1 = __webpack_require__(94765);
const error_utils_1 = __webpack_require__(36401);
const types_1 = __webpack_require__(94820);
const constants_1 = __webpack_require__(68620);
const keys = [
'org',
'debug',
'insecure',
'detectionDepth',
'severityThreshold',
'rules',
'json',
'sarif',
'json-file-output',
'sarif-file-output',
'v',
'version',
'h',
'help',
'q',
'quiet',
'scan',
'report',
// Tags and attributes
'tags',
'project-tags',
'project-environment',
'project-lifecycle',
'project-business-criticality',
'target-reference',
'var-file',
// PolicyOptions
'ignore-policy',
'policy-path',
// Report options
'remote-repo-url',
'target-name',
];
const integratedKeys = ['snyk-cloud-environment'];
const allowed = new Set(keys);
const integratedOnlyFlags = new Set(integratedKeys);
function camelcaseToDash(key) {
return key.replace(/[A-Z]/g, (m) => '-' + m.toLowerCase());
}
function getFlagName(key) {
const dashes = key.length === 1 ? '-' : '--';
const flag = camelcaseToDash(key);
return `${dashes}${flag}`;
}
class FlagError extends errors_1.CustomError {
constructor(key) {
const flag = getFlagName(key);
const msg = `Unsupported flag "${flag}" provided. Run snyk iac test --help for supported flags`;
super(msg);
this.code = types_1.IaCErrorCodes.FlagError;
this.strCode = (0, error_utils_1.getErrorStringCode)(this.code);
this.userMessage = msg;
}
}
exports.FlagError = FlagError;
class IntegratedFlagError extends errors_1.CustomError {
constructor(key, org) {
const flag = getFlagName(key);
const msg = `Flag "${flag}" is only supported when using ${constants_1.IacV2Name}. To enable it for your organisation "${org}", please contact Snyk support.`;
super(msg);
this.code = types_1.IaCErrorCodes.FlagError;
this.strCode = (0, error_utils_1.getErrorStringCode)(this.code);
this.userMessage = msg;
}
}
exports.IntegratedFlagError = IntegratedFlagError;
class FeatureFlagError extends errors_1.CustomError {
constructor(key, featureFlag, hasSnykPreview) {
const flag = getFlagName(key);
let msg;
if (hasSnykPreview) {
msg = `Flag "${flag}" is only supported if feature flag '${featureFlag}' is enabled. The feature flag can be enabled via Snyk Preview if you are on the Enterprise Plan`;
}
else {
msg = `Flag "${flag}" is only supported if feature flag "${featureFlag}" is enabled. To enable it, please contact Snyk support.`;
}
super(msg);
this.code = types_1.IaCErrorCodes.FeatureFlagError;
this.strCode = (0, error_utils_1.getErrorStringCode)(this.code);
this.userMessage = msg;
}
}
exports.FeatureFlagError = FeatureFlagError;
class FlagValueError extends errors_1.CustomError {
constructor(key, value, supportedValues) {
const flag = getFlagName(key);
const msg = `Unsupported value "${value}" provided to flag "${flag}".\nSupported values are: ${supportedValues}`;
super(msg);
this.code = types_1.IaCErrorCodes.FlagValueError;
this.strCode = (0, error_utils_1.getErrorStringCode)(this.code);
this.userMessage = msg;
}
}
exports.FlagValueError = FlagValueError;
class UnsupportedEntitlementFlagError extends errors_1.CustomError {
constructor(key, entitlementName) {
const flag = getFlagName(key);
super(`Unsupported flag: ${flag} - Missing the ${entitlementName} entitlement`);
this.code = types_1.IaCErrorCodes.UnsupportedEntitlementFlagError;
this.strCode = (0, error_utils_1.getErrorStringCode)(this.code);
this.userMessage = `Flag "${flag}" is currently not supported for this org. To enable it, please contact snyk support.`;
}
}
exports.UnsupportedEntitlementFlagError = UnsupportedEntitlementFlagError;
class UnsupportedEntitlementCommandError extends errors_1.CustomError {
constructor(key, entitlementName) {
super(`Unsupported command: ${key} - Missing the ${entitlementName} entitlement`);
this.code = types_1.IaCErrorCodes.UnsupportedEntitlementFlagError;
this.strCode = (0, error_utils_1.getErrorStringCode)(this.code);
this.userMessage = `Command "${key}" is currently not supported for this org. To enable it, please contact snyk support.`;
}
}
exports.UnsupportedEntitlementCommandError = UnsupportedEntitlementCommandError;
/**
* Validates the command line flags passed to the snyk iac test
* command. The current argument parsing is very permissive and
* allows unknown flags to be provided without validation.
*
* For snyk iac we need to explicitly validate the flags to avoid
* misconfigurations and typos. For example, if the --experimental
* flag were to be misspelled we would end up sending the client
* data to our backend rather than running it locally as intended.
* @param argv command line args passed to the process
*/
function assertIaCOptionsFlags(argv) {
// We process the process.argv so we don't get default values.
const parsed = (0, args_1.args)(argv);
for (const key of Object.keys(parsed.options)) {
// The _ property is a special case that contains non
// flag strings passed to the command line (usually files)
// and `iac` is the command provided.
if (key !== '_' && key !== 'iac' && !allowed.has(key)) {
throw new FlagError(key);
}
}
if (parsed.options.scan) {
assertTerraformPlanModes(parsed.options.scan);
}
}
exports.assertIaCOptionsFlags = assertIaCOptionsFlags;
/**
* Check that the flags used for the v1 flow do not contain any flag that are
* only usable with the new IaC+ flow
* @param settings organisation settings, used to get the org name
* @param argv command line args
*/
function assertIntegratedIaCOnlyOptions(settings, argv) {
// We process the process.argv so we don't get default values.
const parsed = (0, args_1.args)(argv);
for (const key of Object.keys(parsed.options)) {
// The _ property is a special case that contains non
// flag strings passed to the command line (usually files)
// and `iac` is the command provided.
if (key !== '_' && key !== 'iac' && integratedOnlyFlags.has(key)) {
throw new IntegratedFlagError(key, settings.meta.org);
}
}
}
exports.assertIntegratedIaCOnlyOptions = assertIntegratedIaCOnlyOptions;
const SUPPORTED_TF_PLAN_SCAN_MODES = [
types_1.TerraformPlanScanMode.DeltaScan,
types_1.TerraformPlanScanMode.FullScan,
];
function assertTerraformPlanModes(scanModeArgValue) {
if (!SUPPORTED_TF_PLAN_SCAN_MODES.includes(scanModeArgValue)) {
throw new FlagValueError('scan', scanModeArgValue, SUPPORTED_TF_PLAN_SCAN_MODES.join(', '));
}
}
exports.assertTerraformPlanModes = assertTerraformPlanModes;
function isIacShareResultsOptions(options) {
return options.iac && options.report;
}
exports.isIacShareResultsOptions = isIacShareResultsOptions;
class InvalidArgumentError extends errors_1.CustomError {
constructor(key) {
const flag = getFlagName(key);
const msg = `Invalid argument provided to flag "${flag}". Value must be a string`;
super(msg);
this.code = types_1.IaCErrorCodes.InvalidArgumentError;
this.strCode = (0, error_utils_1.getErrorStringCode)(this.code);
this.userMessage = msg;
}
}
exports.InvalidArgumentError = InvalidArgumentError;
/***/ }),
/***/ 36401:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getErrorStringCode = void 0;
const types_1 = __webpack_require__(94820);
function getErrorStringCode(code) {
const errorName = types_1.IaCErrorCodes[code];
if (!errorName) {
return 'INVALID_IAC_ERROR';
}
let result = errorName.replace(/([A-Z])/g, '_$1');
if (result.charAt(0) === '_') {
result = result.substring(1);
}
return result.toUpperCase();
}
exports.getErrorStringCode = getErrorStringCode;
/***/ }),
/***/ 11693:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.FailedToGetIacOrgSettingsError = exports.getIacOrgSettings = void 0;
const types_1 = __webpack_require__(94820);
const config_1 = __webpack_require__(25425);
const is_ci_1 = __webpack_require__(10090);
const api_token_1 = __webpack_require__(95181);
const request_1 = __webpack_require__(52050);
const errors_1 = __webpack_require__(55191);
const error_utils_1 = __webpack_require__(36401);
function getIacOrgSettings(publicOrgId) {
const payload = {
method: 'get',
url: config_1.default.API + '/iac-org-settings',
json: true,
qs: { org: publicOrgId },
headers: {
'x-is-ci': (0, is_ci_1.isCI)(),
authorization: (0, api_token_1.getAuthHeader)(),
},
};
return new Promise((resolve, reject) => {
(0, request_1.makeRequest)(payload, (error, res) => {
if (error) {
return reject(error);
}
if (res.statusCode < 200 || res.statusCode > 299) {
return reject(new FailedToGetIacOrgSettingsError());
}
resolve(res.body);
});
});
}
exports.getIacOrgSettings = getIacOrgSettings;
class FailedToGetIacOrgSettingsError extends errors_1.CustomError {
constructor(message) {
super(message || 'Failed to fetch IaC organization settings');
this.code = types_1.IaCErrorCodes.FailedToGetIacOrgSettingsError;
this.strCode = (0, error_utils_1.getErrorStringCode)(this.code);
this.userMessage =
'We failed to fetch your organization settings, including custom severity overrides for infrastructure-as-code policies. Please run the command again with the `-d` flag and contact support@snyk.io with the contents of the output.';
}
}
exports.FailedToGetIacOrgSettingsError = FailedToGetIacOrgSettingsError;
/***/ }),
/***/ 68620:
/***/ ((__unused_webpack_module, exports) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.IacV2ShortLink = exports.IacV2Name = exports.iacRemediationTypes = exports.TEST_SUPPORTED_IAC_PROJECTS = exports.IacProjectType = void 0;
var IacProjectType;
(function (IacProjectType) {
IacProjectType["K8S"] = "k8sconfig";
IacProjectType["TERRAFORM"] = "terraformconfig";
IacProjectType["CLOUDFORMATION"] = "cloudformationconfig";
IacProjectType["ARM"] = "armconfig";
IacProjectType["CUSTOM"] = "customconfig";
IacProjectType["MULTI_IAC"] = "multiiacconfig";
})(IacProjectType = exports.IacProjectType || (exports.IacProjectType = {}));
exports.TEST_SUPPORTED_IAC_PROJECTS = [
IacProjectType.K8S,
IacProjectType.TERRAFORM,
IacProjectType.CLOUDFORMATION,
IacProjectType.ARM,
IacProjectType.MULTI_IAC,
IacProjectType.CUSTOM,
];
exports.iacRemediationTypes = {
armconfig: 'arm',
cloudformationconfig: 'cloudformation',
k8sconfig: 'kubernetes',
terraformconfig: 'terraform',
};
exports.IacV2Name = 'IaC+';
exports.IacV2ShortLink = 'https://snyk.co/iac+';
/***/ }),
/***/ 3659:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
var _a;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.runDriftCTL = exports.translateExitCode = exports.generateArgs = exports.driftctlVersion = exports.DCTL_EXIT_CODES = void 0;
const config_1 = __webpack_require__(25425);
const exit_codes_1 = __webpack_require__(80079);
const env_paths_1 = __webpack_require__(21766);
const metrics_1 = __webpack_require__(32971);
const analytics = __webpack_require__(82744);
const spinner_1 = __webpack_require__(86766);
const service_mappings_1 = __webpack_require__(16228);
const debugLib = __webpack_require__(15158);
const request_1 = __webpack_require__(52050);
const child_process = __webpack_require__(32081);
const path = __webpack_require__(71017);
const fs = __webpack_require__(57147);
const os = __webpack_require__(22037);
const crypto = __webpack_require__(6113);
const file_utils_1 = __webpack_require__(52761);
const env_utils_1 = __webpack_require__(30470);
const debug = debugLib('driftctl');
const cachePath = (_a = config_1.default.CACHE_PATH) !== null && _a !== void 0 ? _a : (0, env_paths_1.default)('snyk').cache;
exports.DCTL_EXIT_CODES = {
EXIT_IN_SYNC: 0,
EXIT_NOT_IN_SYNC: 1,
EXIT_ERROR: 2,
};
exports.driftctlVersion = 'v0.40.0';
const driftctlChecksums = {
driftctl_darwin_amd64: '4eb86bd4a1e965c2552879795434143f1db974b2d795581b9ddb69d0bd8a245a',
'driftctl_windows_386.exe': 'a02f079cb128ba46396db9654bc8bb8066ebde0539ebbeb401a40a81dfc8f733',
driftctl_darwin_arm64: 'dfdee8138eb817cc066b8bf915c808fbd53536ee1757b34ca6e518e1c2ad1ba5',
driftctl_linux_arm64: '8816f1378138c2ce585c762e109b5fdd41b7144b915e97759ceae946db023540',
'driftctl_windows_arm.exe': '6217151b4168e93ffdd6e005cb1cf03768f371cd6b412f53605fde46343c08d1',
driftctl_linux_amd64: '84e2462454956a4df794a24e0f4d2351299212d772b8602fc5070e6174ac1324',
'driftctl_windows_amd64.exe': '1561fd04e3d428c39ae95f81214517bbf62e8333156bf538a2d385005e350c8b',
'driftctl_windows_arm64.exe': '76f939d836da64fa9dab63f0eeffd09a0de7e353b034296b8f1582cdff6f2a61',
driftctl_linux_arm: '7f669ca49e152779a09587ff0e58dedd3996229cc8ff3e5cdc371895eaa994f6',
driftctl_linux_386: 'e6bbdf341148e81511d30dd5afe2fa2ef08f3b0b75079bf0bde2b790d75beb8a',
};
const dctlBaseUrl = 'https://static.snyk.io/cli/driftctl/';
const driftctlPath = path.join(cachePath, 'driftctl_' + exports.driftctlVersion);
const driftctlDefaultOptions = ['--no-version-check'];
let isBinaryDownloaded = false;
const generateArgs = async (options, driftIgnore) => {
if (options.kind === 'describe') {
return await generateScanFlags(options, driftIgnore);
}
if (options.kind === 'fmt') {
return generateFmtFlags(options);
}
throw 'Unsupported command';
};
exports.generateArgs = generateArgs;
const generateFmtFlags = (options) => {
const args = ['fmt', ...driftctlDefaultOptions];
if (options.json) {
args.push('--output');
args.push('json://stdout');
}
if (options.html) {
args.push('--output');
args.push('html://stdout');
}
if (options['html-file-output']) {
args.push('--output');
args.push('html://' + options['html-file-output']);
}
return args;
};
const generateScanFlags = async (options, driftIgnore) => {
const args = ['scan', ...driftctlDefaultOptions];
if (options.quiet) {
args.push('--quiet');
}
if (options.filter) {
args.push('--filter');
args.push(options.filter);
}
args.push('--output');
args.push('json://stdout');
if (options['fetch-tfstate-headers']) {
args.push('--headers');
args.push(options['fetch-tfstate-headers']);
}
if (options['tfc-token']) {
args.push('--tfc-token');
args.push(options['tfc-token']);
}
if (options['tfc-endpoint']) {
args.push('--tfc-endpoint');
args.push(options['tfc-endpoint']);
}
if (options['tf-provider-version']) {
args.push('--tf-provider-version');
args.push(options['tf-provider-version']);
}
if (options.strict) {
args.push('--strict');
}
if (options['only-unmanaged']) {
args.push('--only-unmanaged');
}
if (options.driftignore) {
args.push('--driftignore');
args.push(options.driftignore);
}
if (options['tf-lockfile']) {
args.push('--tf-lockfile');
args.push(options['tf-lockfile']);
}
if (driftIgnore && driftIgnore.length > 0) {
args.push('--ignore');
args.push(driftIgnore.join(','));
}
let configDir = cachePath;
await (0, file_utils_1.createDirIfNotExists)(cachePath);
if (options['config-dir']) {
configDir = options['config-dir'];
}
args.push('--config-dir');
args.push(configDir);
if (options.from) {
const froms = options.from.split(',');
for (const f of froms) {
args.push('--from');
args.push(f);
}
}
let to = 'aws+tf';
if (options.to) {
to = options.to;
}
args.push('--to');
args.push(to);
if (options.service) {
const services = options.service.split(',');
(0, service_mappings_1.verifyServiceMappingExists)(services);
args.push('--ignore');
args.push((0, service_mappings_1.createIgnorePattern)(services));
}
debug(args);
return args;
};
function translateExitCode(exitCode) {
switch (exitCode) {
case exports.DCTL_EXIT_CODES.EXIT_IN_SYNC:
return 0;
case exports.DCTL_EXIT_CODES.EXIT_NOT_IN_SYNC:
return exit_codes_1.EXIT_CODES.VULNS_FOUND;
case exports.DCTL_EXIT_CODES.EXIT_ERROR:
return exit_codes_1.EXIT_CODES.ERROR;
default:
debug('driftctl returned %d', exitCode);
return exit_codes_1.EXIT_CODES.ERROR;
}
}
exports.translateExitCode = translateExitCode;
const runDriftCTL = async ({ options, driftIgnore, input, stdio, }) => {
const path = await findOrDownload();
const args = await (0, exports.generateArgs)(options, driftIgnore);
if (!stdio) {
stdio = ['pipe', 'pipe', 'inherit'];
}
debug('running driftctl %s ', args.join(' '));
const dctl_env = (0, env_utils_1.restoreEnvProxy)({
...process.env,
DCTL_IS_SNYK: 'true',
});
const p = child_process.spawn(path, args, {
stdio,
env: dctl_env,
});
let stdout = '';
return new Promise((resolve, reject) => {
var _a, _b, _c;
if (input) {
(_a = p.stdin) === null || _a === void 0 ? void 0 : _a.write(input);
(_b = p.stdin) === null || _b === void 0 ? void 0 : _b.end();
}
p.on('error', (error) => {
reject(error);
});
(_c = p.stdout) === null || _c === void 0 ? void 0 : _c.on('data', (data) => {
stdout += data;
});
p.on('exit', (code) => {
resolve({ code: translateExitCode(code), stdout });
});
});
};
exports.runDriftCTL = runDriftCTL;
async function findOrDownload() {
let dctl = await findDriftCtl();
if (isBinaryDownloaded) {
return dctl;
}
let downloadDuration = 0;
let binaryExist = true;
if (dctl === '') {
binaryExist = false;
try {
await (0, file_utils_1.createDirIfNotExists)(cachePath);
dctl = driftctlPath;
const duration = new metrics_1.TimerMetricInstance('driftctl_download');
duration.start();
await download(driftctlUrl(), dctl);
duration.stop();
downloadDuration = Math.round(duration.getValue() / 1000);
}
catch (err) {
return Promise.reject(err);
}
}
analytics.add('iac-drift-binary-already-exist', binaryExist);
analytics.add('iac-drift-binary-download-duration-seconds', downloadDuration);
isBinaryDownloaded = true;
return dctl;
}
async function findDriftCtl() {
// lookup in custom path contained in env var DRIFTCTL_PATH
let dctlPath = config_1.default.DRIFTCTL_PATH;
if (dctlPath != null) {
const exists = await (0, file_utils_1.isExe)(dctlPath);
if (exists) {
debug('Found driftctl in $DRIFTCTL_PATH: %s', dctlPath);
return dctlPath;
}
}
// lookup in app cache
dctlPath = driftctlPath;
const exists = await (0, file_utils_1.isExe)(dctlPath);
if (exists) {
debug('Found driftctl in cache: %s', dctlPath);
return dctlPath;
}
debug('driftctl not found');
return '';
}
async function download(url, destination) {
debug('downloading driftctl into %s', destination);
const payload = {
method: 'GET',
url: url,
output: destination,
follow: 3,
};
await (0, spinner_1.spinner)('Downloading...');
return new Promise((resolve, reject) => {
(0, request_1.makeRequest)(payload, function (err, res, body) {
try {
if (err) {
reject(new Error('Could not download driftctl from ' + url + ': ' + err));
return;
}
if (res.statusCode !== 200) {
reject(new Error('Could not download driftctl from ' + url + ': ' + res.statusCode));
return;
}
validateChecksum(body);
fs.writeFileSync(destination, body);
debug('File saved: ' + destination);
fs.chmodSync(destination, 0o744);
resolve(true);
}
finally {
spinner_1.spinner.clearAll();
}
});
});
}
function validateChecksum(body) {
// only validate if we downloaded the official driftctl binary
if (config_1.default.DRIFTCTL_URL || config_1.default.DRIFTCTL_PATH) {
return;
}
const computedHash = crypto
.createHash('sha256')
.update(body)
.digest('hex');
const givenHash = driftctlChecksums[driftctlFileName()];
if (computedHash != givenHash) {
throw new Error('Downloaded file has inconsistent checksum...');
}
}
function driftctlFileName() {
let platform = 'linux';
switch (os.platform()) {
case 'darwin':
platform = 'darwin';
break;
case 'win32':
platform = 'windows';
break;
}
let arch = 'amd64';
switch (os.arch()) {
case 'ia32':
case 'x32':
arch = '386';
break;
case 'arm':
arch = 'arm';
break;
case 'arm64':
arch = 'arm64';
break;
}
let ext = '';
switch (os.platform()) {
case 'win32':
ext = '.exe';
break;
}
return `driftctl_${platform}_${arch}${ext}`;
}
function driftctlUrl() {
if (config_1.default.DRIFTCTL_URL) {
return config_1.default.DRIFTCTL_URL;
}
return `${dctlBaseUrl}/${exports.driftctlVersion}/${driftctlFileName()}`;
}
/***/ }),
/***/ 30470:
/***/ ((__unused_webpack_module, exports) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.restoreEnvProxy = void 0;
function restoreEnvProxy(env) {
// WARN: We are restoring system en proxy because snyk cli override them but the proxy uses untrusted certs
if (process.env.SNYK_SYSTEM_HTTP_PROXY != undefined) {
env.HTTP_PROXY = process.env.SNYK_SYSTEM_HTTP_PROXY;
}
if (process.env.SNYK_SYSTEM_HTTPS_PROXY != undefined) {
env.HTTPS_PROXY = process.env.SNYK_SYSTEM_HTTPS_PROXY;
}
if (process.env.SNYK_SYSTEM_NO_PROXY != undefined) {
env.NO_PROXY = process.env.SNYK_SYSTEM_NO_PROXY;
}
return env;
}
exports.restoreEnvProxy = restoreEnvProxy;
/***/ }),
/***/ 52761:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.saveFile = exports.isArchive = exports.isFile = exports.createDirIfNotExists = exports.isExists = exports.isExe = void 0;
const tar = __webpack_require__(97998);
const fs_1 = __webpack_require__(57147);
const util_1 = __webpack_require__(73837);
async function isExe(path) {
try {
await fs_1.promises.access(path, fs_1.constants.X_OK);
return true;
}
catch (err) {
return false;
}
}
exports.isExe = isExe;
async function isExists(path) {
try {
await fs_1.promises.stat(path);
return true;
}
catch (err) {
return false;
}
}
exports.isExists = isExists;
async function createDirIfNotExists(path) {
const isDirExists = await isExists(path);
if (!isDirExists) {
fs_1.promises.mkdir(path, { recursive: true });
}
}
exports.createDirIfNotExists = createDirIfNotExists;
async function isFile(path) {
try {
return (await fs_1.promises.stat(path)).isFile();
}
catch (err) {
return false;
}
}
exports.isFile = isFile;
async function isArchive(path) {
try {
const tarList = (0, util_1.promisify)(tar.list);
await tarList({ file: path, strict: true });
return true;
}
catch (e) {
return false;
}
}
exports.isArchive = isArchive;
async function saveFile(dataBuffer, savePath) {
await fs_1.promises.writeFile(savePath, dataBuffer);
await fs_1.promises.chmod(savePath, 0o744);
}
exports.saveFile = saveFile;
/***/ }),
/***/ 16228:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.InvalidServiceError = exports.createIgnorePatternWithMap = exports.createIgnorePattern = exports.findServiceMappingForType = exports.verifyServiceMappingExists = exports.services2resources = void 0;
const errors_1 = __webpack_require__(55191);
const types_1 = __webpack_require__(94820);
const error_utils_1 = __webpack_require__(36401);
exports.services2resources = new Map([
// Amazon
[
'aws_s3',
[
'aws_s3_bucket',
'aws_s3_bucket_analytics_configuration',
'aws_s3_bucket_inventory',
'aws_s3_bucket_metric',
'aws_s3_bucket_notification',
'aws_s3_bucket_policy',
],
],
[
'aws_ec2',
[
'aws_instance',
'aws_key_pair',
'aws_ami',
'aws_ebs_snapshot',
'aws_ebs_volume',
'aws_eip',
'aws_eip_association',
'aws_volume_attachment',
'aws_launch_configuration',
'aws_launch_template',
],
],
['aws_lambda', ['aws_lambda_function', 'aws_lambda_event_source_mapping']],
[
'aws_rds',
[
'aws_db_instance',
'aws_db_subnet_group',
'aws_rds_cluster',
'aws_rds_cluster_endpoint',
'aws_rds_cluster_instance',
],
],
['aws_route53', ['aws_route53_record', 'aws_route53_zone']],
[
'aws_iam',
[
'aws_iam_access_key',
'aws_iam_policy',
'aws_iam_policy_attachment',
'aws_iam_role',
'aws_iam_role_policy',
'aws_iam_role_policy_attachment',
'aws_iam_user',
'aws_iam_user_policy',
'aws_iam_user_policy_attachment',
],
],
[
'aws_vpc',
[
'aws_security_group',
'aws_security_group_rule',
'aws_subnet',
'aws_default_vpc',
'aws_vpc',
'aws_default_security_group',
'aws_route_table',
'aws_default_route_table',
'aws_route',
'aws_route_table_association',
'aws_nat_gateway',
'aws_internet_gateway',
],
],
[
'aws_api_gateway',
[
'aws_api_gateway_resource',
'aws_api_gateway_rest_api',
'aws_api_gateway_account',
'aws_api_gateway_api_key',
'aws_api_gateway_authorizer',
'aws_api_gateway_base_path_mapping',
'aws_api_gateway_domain_name',
'aws_api_gateway_gateway_response',
'aws_api_gateway_integration',
'aws_api_gateway_integration_response',
'aws_api_gateway_method',
'aws_api_gateway_method_response',
'aws_api_gateway_method_settings',
'aws_api_gateway_model',
'aws_api_gateway_request_validator',
'aws_api_gateway_rest_api_policy',
'aws_api_gateway_stage',
'aws_api_gateway_vpc_link',
],
],
[
'aws_apigatewayv2',
[
'aws_apigatewayv2_api',
'aws_apigatewayv2_api_mapping',
'aws_apigatewayv2_authorizer',
'aws_apigatewayv2_deployment',
'aws_apigatewayv2_domain_name',
'aws_apigatewayv2_integration',
'aws_apigatewayv2_integration_response',
'aws_apigatewayv2_model',
'aws_apigatewayv2_route',
'aws_apigatewayv2_route_response',
'aws_apigatewayv2_stage',
'aws_apigatewayv2_vpc_link',
],
],
['aws_sqs', ['aws_sqs_queue', 'aws_sqs_queue_policy']],
[
'aws_sns',
['aws_sns_topic', 'aws_sns_topic_policy', 'aws_sns_topic_subscription'],
],
['aws_ecr', ['aws_ecr_repository']],
['aws_cloudfront', ['aws_cloudfront_distribution']],
['aws_kms', ['aws_kms_key', 'aws_kms_alias']],
['aws_dynamodb', ['aws_dynamodb_table']],
// Azure
['azure_base', ['azurerm_resource_group']],
['azure_compute', ['azurerm_image', 'azurerm_ssh_public_key']],
['azure_storage', ['azurerm_storage_account', 'azurerm_storage_container']],
[
'azure_network',
[
'azurerm_resource_group',
'azurerm_subnet',
'azurerm_public_ip',
'azurerm_firewall',
'azurerm_route',
'azurerm_route_table',
'azurerm_network_security_group',
],
],
['azure_container', ['azurerm_container_registry']],
[
'azure_database',
['azurerm_postgresql_server', 'azurerm_postgresql_database'],
],
['azure_loadbalancer', ['azurerm_lb', 'azurerm_lb_rule']],
[
'azure_private_dns',
[
'azurerm_private_dns_a_record',
'azurerm_private_dns_aaaa_record',
'azurerm_private_dns_cname_record',
'azurerm_private_dns_mx_record',
'azurerm_private_dns_ptr_record',
'azurerm_private_dns_srv_record',
'azurerm_private_dns_txt_record',
'azurerm_private_dns_zone',
],
],
// Google
[
'google_cloud_platform',
[
'google_project_iam_binding',
'google_project_iam_member',
'google_project_iam_policy',
],
],
[
'google_cloud_storage',
[
'google_storage_bucket',
'google_storage_bucket_iam_binding',
'google_storage_bucket_iam_member',
'google_storage_bucket_iam_policy',
],
],
[
'google_compute_engine',
[
'google_compute_address',
'google_compute_disk',
'google_compute_global_address',
'google_compute_firewall',
'google_compute_health_check',
'google_compute_image',
'google_compute_instance',
'google_compute_instance_group',
'google_compute_network',
'google_compute_node_group',
'google_compute_router',
'google_compute_subnetwork',
],
],
['google_cloud_dns', ['google_dns_managed_zone']],
[
'google_cloud_bigtable',
['google_bigtable_instance', 'google_bigtable_table'],
],
[
'google_cloud_bigquery',
['google_bigquery_table', 'google_bigquery_dataset'],
],
['google_cloud_functions', ['google_cloudfunctions_function']],
['google_cloud_sql', ['google_sql_database_instance']],
['google_cloud_run', ['google_cloud_run_service']],
]);
function verifyServiceMappingExists(services) {
if (services.length == 0) {
throw new InvalidServiceError('');
}
for (const s of services) {
if (!exports.services2resources.has(s)) {
throw new InvalidServiceError(`We were unable to match service "${s}". Please provide a valid service name: ${existingServiceNames()}`);
}
}
}
exports.verifyServiceMappingExists = verifyServiceMappingExists;
function findServiceMappingForType(type) {
var _a;
for (const service of exports.services2resources.keys()) {
if ((_a = exports.services2resources.get(service)) === null || _a === void 0 ? void 0 : _a.includes(type)) {
return service;
}
}
return '';
}
exports.findServiceMappingForType = findServiceMappingForType;
function existingServiceNames() {
let res = '';
for (const s of exports.services2resources.keys()) {
res += `${s},`;
}
return res.substring(0, res.length - 1);
}
function createIgnorePattern(services) {
return createIgnorePatternWithMap(services, exports.services2resources);
}
exports.createIgnorePattern = createIgnorePattern;
function createIgnorePatternWithMap(services, serviceMap) {
let res = '*';
const seenResources = new Set();
for (const s of services) {
const resourcePatterns = serviceMap.get(s);
for (const rp of resourcePatterns || []) {
// A resource might belong to multiple services, skip it if already processed
if (seenResources.has(rp)) {
continue;
}
res += `,!${rp}`;
seenResources.add(rp);
}
}
return res;
}
exports.createIgnorePatternWithMap = createIgnorePatternWithMap;
class InvalidServiceError extends errors_1.CustomError {
constructor(msg) {
super(msg);
this.code = types_1.IaCErrorCodes.InvalidServiceError;
this.strCode = (0, error_utils_1.getErrorStringCode)(this.code);
this.userMessage = msg;
}
}
exports.InvalidServiceError = InvalidServiceError;
/***/ })
};
;
//# sourceMappingURL=617.index.js.map