/**
 * Minified by jsDelivr using Terser v5.39.0.
 * Original file: /npm/@cloudgraph/cg-provider-aws@0.90.0/dist/services/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,s,r){void 0===r&&(r=s),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[s]}})}:function(e,t,s,r){void 0===r&&(r=s),e[r]=t[s]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var s in e)"default"!==s&&Object.prototype.hasOwnProperty.call(e,s)&&__createBinding(t,e,s);return __setModuleDefault(t,e),t},__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.enums=void 0;const sdk_1=__importStar(require("@cloudgraph/sdk")),load_files_1=require("@graphql-tools/load-files"),merge_1=require("@graphql-tools/merge"),aws_sdk_1=__importDefault(require("aws-sdk")),shared_ini_file_loader_1=require("@aws-sdk/shared-ini-file-loader"),credential_providers_1=require("@aws-sdk/credential-providers"),chalk_1=__importDefault(require("chalk")),sts_1=__importDefault(require("aws-sdk/clients/sts")),lodash_1=require("lodash"),path_1=__importDefault(require("path")),regions_1=__importDefault(require("../enums/regions")),resources_1=__importDefault(require("../enums/resources")),services_1=__importDefault(require("../enums/services")),serviceMap_1=__importDefault(require("../enums/serviceMap")),schemasMap_1=__importDefault(require("../enums/schemasMap")),relations_1=__importDefault(require("../enums/relations")),format_1=require("../utils/format"),utils_1=require("../utils"),enhancers_1=__importDefault(require("./base/enhancers")),errorLog_1=__importDefault(require("../utils/errorLog")),DEFAULT_REGION="us-east-1",DEFAULT_RESOURCES=Object.values(services_1.default).join(","),ENV_VAR_CREDS_LOG="Using ENV variable credentials";exports.enums={services:services_1.default,regions:regions_1.default,resources:resources_1.default,schemasMap:schemasMap_1.default};class Provider extends sdk_1.default.Client{constructor(e){super(e),this.properties=exports.enums}logSelectedAccessRegionsAndResources(e,t,s){this.logger.info(`Profiles and role ARNs configured: ${chalk_1.default.green(e.join(", "))}`),this.logger.info(`Regions configured: ${chalk_1.default.green(t.replace(/,/g,", "))}`),this.logger.info(`Resources configured: ${chalk_1.default.green(s.replace(/,/g,", "))}`)}async configure(){const{flags:e={},cloudGraphConfig:t,...s}=this.config,r={...s};let i;try{i=await this.getProfilesFromSharedConfig()}catch(e){this.logger.warn("No AWS profiles found")}const a=[];for(;;){if(a.length>0){const{addAccount:e}=await this.interface.prompt([{type:"confirm",message:"Configure another AWS account?",name:"addAccount",default:!0}]);if(!e)break}let t="",s="",r="";if(!e["use-roles"]&&i&&i.length){const{profile:e}=await this.interface.prompt([{type:"list",message:"Please select AWS identity",name:"profile",loop:!1,choices:i.map((e=>({name:e})))}]);t=e}else this.logger.info('** NOTE: if you want to use the "built in" (metadata) credentials for ec2/ecs, leave the roleArn blank for that account.');const{addRoleArn:n}=await this.interface.prompt([{type:"confirm",message:"Do you want to provide a role ARN for this identity to assume?",name:"addRoleArn",default:!1}]);if(n){const{role:e,externalId:t}=await this.interface.prompt([{type:"input",message:"Enter role ARN for identity to assume",name:"role"},{type:"input",message:"Enter ExternalID for role OR press ENTER for none",name:"externalId"}]);s=e,r=t}a.push({profile:t,roleArn:s,externalId:r})}a.length||a.push({profile:"",roleArn:"",externalId:""}),r.accounts=a;const{regions:n}=await this.interface.prompt([{type:"checkbox",message:"Select regions to scan",loop:!1,name:"regions",choices:regions_1.default.map((e=>({name:e})))}]);if(this.logger.debug(`Regions selected: ${n}`),n.length?r.regions=n.join(","):(this.logger.info(`No Regions selected, using default region: ${chalk_1.default.green("us-east-1")}`),r.regions="us-east-1"),e.resources){const{resources:e}=await this.interface.prompt([{type:"checkbox",message:"Select services to scan",loop:!1,name:"resources",choices:Object.values(services_1.default).map((e=>({name:e})))}]);this.logger.debug(e),e.length>0?r.resources=e.join(","):r.resources=DEFAULT_RESOURCES}else r.resources=DEFAULT_RESOURCES;const o=String.fromCodePoint(127882);return this.logger.success(`${o} ${chalk_1.default.green("AWS")} configuration successfully completed ${o}`),this.logSelectedAccessRegionsAndResources(r.accounts.map((e=>e.roleArn??e.profile)),r.regions,r.resources),r}async getIdentity(e){try{const t=await this.getAwsConfig(e);return new Promise(((e,s)=>new sts_1.default(t).getCallerIdentity(((t,r)=>t?s(t):e({accountId:r.Account})))))}catch(e){return this.logger.error("There was an error in function getIdentity"),this.logger.debug(e),{accountId:""}}}unsetAwsCredentials(){this.credentials=void 0}getAwsConfig({profile:e,roleArn:t,externalId:s,accessKeyId:r,secretAccessKey:i}){const{cloudGraphConfig:{ignorePrompts:a,ignoreEnvVariables:n}={ignorePrompts:!1,ignoreEnvVariables:!1}}=this.config;let o;return new Promise((async(c,l)=>{if(r&&i){const e={accessKeyId:r,secretAccessKey:i};return this.credentials||(this.logger.warn("Using hard coded accessKeyId and secretAccessKey, it is not advised to save these in config"),this.logger.success(`accessKeyId: ${chalk_1.default.underline.green(format_1.obfuscateSensitiveString(r))}`),this.logger.success(`secretAccessKey: ${chalk_1.default.underline.green(format_1.obfuscateSensitiveString(i))}`)),this.credentials=e,o={...aws_sdk_1.default.config,credentials:this.credentials},c(o)}if(this.credentials&&(this.profile===e||this.role===t))return o={...aws_sdk_1.default.config,credentials:this.credentials},c(o);switch(this.logger.info("Searching for AWS credentials..."),!0){case t&&""!==t:{let r=new aws_sdk_1.default.STS;await new Promise((async i=>{if(e&&"default"!==e){let t;const s=credential_providers_1.fromIni({profile:e,mfaCodeProvider:async()=>{this.logger.debug("MFA token needed, requesting...");const{mfaToken:t=""}=await this.interface.prompt([{type:"input",message:`Please enter the MFA token for ${e}`,name:"mfaToken"}]);return t}});t&&(r=new aws_sdk_1.default.STS({credentials:await s()}))}const a={RoleSessionName:"CloudGraph",RoleArn:t,...s&&{ExternalId:s}};r.assumeRole(a,((s,r)=>{if(s)this.logger.error(`No valid credentials found for roleARN: ${t}`),this.logger.debug(s),i();else{const{AccessKeyId:t,SecretAccessKey:s,SessionToken:a}=r.Credentials,n={accessKeyId:t,secretAccessKey:s,sessionToken:a};this.credentials=n,o={...aws_sdk_1.default.config,credentials:n},this.profile=e,i()}}))}));break}case e&&"default"!==e:try{const t=this.getSharedIniFileCredentials(e);t&&(this.credentials=t,o={...aws_sdk_1.default.config,credentials:t},this.profile=e);break}catch(e){break}default:this.unsetAwsCredentials(),await new Promise((t=>aws_sdk_1.default.config.getCredentials((s=>{s||(this.credentials=aws_sdk_1.default.config.credentials,o={...aws_sdk_1.default.config,credentials:this.credentials},this.profile=e),t()}))))}if(!this.credentials&&!a){this.logger.info("No AWS Credentials found for scan, please enter them manually");const t=this.logger.stopSpinner(),s=await this.interface.prompt([{type:"input",message:"Please input a valid accessKeyId",name:"accessKeyId"},{type:"input",message:"Please input a valid secretAccessKey",name:"secretAccessKey"}]);if(!s?.accessKeyId||!s?.secretAccessKey){const e="Cannot scan AWS without credentials";return this.logger.error(e),l(new Error(e))}this.credentials=s,this.profile=e,o={...aws_sdk_1.default.config,credentials:this.credentials},this.logger.startSpinner(t)}const d=e||"default",u=!!process.env.AWS_ACCESS_KEY_ID&&!n;if(!this.credentials)return l(new Error("No Credentials found for AWS"));u?this.logger.success("Using credentials set by ENV variables"):(this.logger.success("Found and using the following AWS credentials"),this.logger.success(`${t?"roleARN":"profile"}: ${chalk_1.default.underline.green(t||d)}`)),this.logger.success(`accessKeyId: ${chalk_1.default.underline.green(format_1.obfuscateSensitiveString(this.credentials.accessKeyId))}`),this.logger.success(`secretAccessKey: ${chalk_1.default.underline.green(format_1.obfuscateSensitiveString(this.credentials.secretAccessKey))}`),c(o)}))}getSchema(){const e=load_files_1.loadFilesSync(path_1.default.join(__dirname),{recursive:!0,extensions:["graphql"]});return merge_1.mergeTypeDefs(e)}getService(e){if(serviceMap_1.default[e])return new serviceMap_1.default[e](this)}getSharedIniFileCredentials(e){let t;try{t=new aws_sdk_1.default.SharedIniFileCredentials({profile:e,callback:t=>{t&&this.logger.error(`No credentials found for profile ${e}`)}})}catch(e){this.logger.debug(e)}return t}async getProfilesFromSharedConfig(){const e=[];try{const t=await shared_ini_file_loader_1.loadSharedConfigFiles(),s=Object.keys(t);for(const r of s){const s=Object.keys(t[r]);s&&s.length>0&&e.push(...s)}}catch(e){this.logger.warn("Unable to read AWS shared credential file"),this.logger.debug(e)}return e}mergeRawData(e,t){if(lodash_1.isEmpty(e))return t;const s=[];for(const r of e)try{const{className:e,name:i,data:a}=r,n=t.find((({name:e})=>i===e)).data||{};if(n){let t={};if(lodash_1.isEmpty(a))t=n;else for(const e in a)n[e]?(this.logger.debug(`Found additional data for ${i} in ${e}, merging`),t[e]=[...a[e]??[],...n[e]]):t[e]=a[e];s.push({className:e,name:i,data:t})}else s.push({className:e,name:i,data:a})}catch(e){this.logger.debug(e),this.logger.error("There was an error merging raw data for AWS")}return s}async getRawData(e,t){let{regions:s,resources:r}=this.config;const i=[];s=s?[...new Set(s.split(","))].join(","):this.properties.regions.join(","),r||(r=Object.values(this.properties.services).join(","));const a=sdk_1.sortResourcesDependencies(relations_1.default,[...new Set(r.split(","))]),n=await this.getAwsConfig(e),{accountId:o}=await this.getIdentity(e);for(const e of a){const r=this.getService(e);if(r&&r.getData)try{const a=await r.getData({regions:s,config:n,opts:t,account:o,rawData:i});i.push({className:r.constructor.name,name:e,accountId:o,data:a}),this.logger.success(`${e} scan completed`)}catch(t){this.logger.error(`There was an error scanning AWS sdk data for ${e} resource`),this.logger.debug(t)}else this.logger.warn(`Skipping service ${e} as there was an issue getting data for it. Is it currently supported?`)}return this.logger.success(`Account: ${o} scan completed`),i}enhanceData({data:e,...t}){let s={entities:e.entities,connections:e.connections};for(const{name:e,enhancer:r}of enhancers_1.default)try{s=r({...t,data:s})}catch(t){return this.logger.error(`There was an error enriching AWS data with ${e} data`),this.logger.debug(t),s}return s}async getData({opts:e}){const t={entities:[],connections:{}};let{regions:s,resources:r}=this.config;const{accounts:i,cloudGraphConfig:{ignoreEnvVariables:a}={ignoreEnvVariables:!1}}=this.config;s=s?[...new Set(s.split(","))].join(","):this.properties.regions.join(","),r||(r=Object.values(this.properties.services).join(","));const n=!!process.env.AWS_ACCESS_KEY_ID&&!a;this.logSelectedAccessRegionsAndResources(n?[ENV_VAR_CREDS_LOG]:i.map((e=>e.roleArn||e.profile)),s,r);let o=[],c=[];const l="aws-global",d={className:"Tag",name:"tag",data:{[l]:[]}},u={className:"AwsAccount",name:"account",data:{[l]:[]}};if(n)o=await this.getRawData({profile:"default",roleArn:void 0,externalId:void 0},e);else{const t=[];for(const r of i){const{profile:i,roleArn:a}=r;if(i){if(!(await this.getProfilesFromSharedConfig()).includes(i)){this.logger.warn(`Profile: ${i} not found in shared credentials file. Skipping...`);continue}}const{accountId:n}=await this.getIdentity(r);if(u.data[l].push({id:n,regions:s.split(",")}),t.find((e=>e===n)))this.logger.warn(`${i?"profile":"roleARN"}: ${i??a} returned accountId ${n} which has already been crawled, skipping...`);else{t.push(n);const s=await this.getRawData(r,e);c=this.mergeRawData(c,s),o=[...o,...s]}this.unsetAwsCredentials()}}try{for(const{data:e}of o)for(const t of Object.keys(e)){(e[t]??[]).forEach((e=>{if(!lodash_1.isEmpty(e.Tags))for(const[t,s]of Object.entries(e.Tags))d.data[l].find((({id:e})=>e===`${t}:${s}`))||d.data[l].push({id:`${t}:${s}`,key:t,value:s})}))}o.push(u);const e=o.findIndex((({name:e})=>"tag"===e));e>-1?o[e]=d:o.push(d)}catch(e){this.logger.error("There was an error aggregating AWS tags"),this.logger.debug(e)}for(const e of o)try{const r=this.getService(e.name),i=[];for(const a of Object.keys(e.data)){await new Promise((e=>setTimeout(e,10)));const n=e.data[a];lodash_1.isEmpty(n)||n.forEach((n=>{const o=r.format({service:n,region:a,account:e.accountId});if(i.push(o),"function"==typeof r.getConnections){let i={};for(const t of s.split(",")){const s=r.getConnections({service:n,region:t,account:e.accountId,data:c});i=utils_1.checkAndMergeConnections(i,s)}Object.assign(t.connections,i)}}))}const a=t.entities.findIndex((({name:t})=>t===e.name));if(a>-1){const s=t.entities[a].data;for(const e of i){const t=s.findIndex((({id:t})=>t===e.id));if(t>-1){const r=s[t];s.splice(t,1);const a=i.findIndex((({id:t})=>t===e.id));i[a]=lodash_1.merge(r,e)}}t.entities[a]={className:r.constructor.name,name:e.name,mutation:r.mutation,data:[...s,...i]}}else t.entities.push({className:r.constructor.name,name:e.name,mutation:r.mutation,data:i})}catch(t){this.logger.error(`There was an error formatting/connecting service ${e.name} `),this.logger.debug(t)}return{...this.enhanceData({accounts:u.data[l],configuredRegions:s,rawData:c,data:t}),errors:errorLog_1.default.errorsHistory}}}exports.default=Provider;
//# sourceMappingURL=/sm/05791e192412f0deaa4cabef2970a5ee6226765369d06edee5832bf1d24c9825.map