Best JavaScript code snippet using jest
glueS3EncryptionEnabled.js
Source: glueS3EncryptionEnabled.js
1var async = require('async');2var helpers = require('../../../helpers/aws');3module.exports = {4 title: 'AWS Glue S3 Encryption Enabled',5 category: 'Glue',6 description: 'Ensures that encryption at-rest is enabled when writing AWS Glue data to Amazon S3.',7 more_info: 'AWS Glue should have encryption at-rest enabled for Amazon S3 to ensure security of data at rest and to prevent unauthorized access.',8 recommended_action: 'Recreate AWS Glue Security Configuration to enable Amazon S3 encryption at-rest',9 link: 'https://docs.aws.amazon.com/glue/latest/dg/console-security-configurations.html',10 apis: ['Glue:getSecurityConfigurations', 'STS:getCallerIdentity', 'KMS:listKeys', 'KMS:describeKey'],11 settings: {12 glue_s3_encryption_level: {13 name: 'Glue S3 Encryption Level',14 description: 'In order (lowest to highest) sse=S3 Server-Side; awskms=AWS-managed KMS; awscmk=Customer managed KMS;',15 regex: '^(sse|awskms|awscmk)$',16 default: 'awscmk',17 }18 },19 run: function(cache, settings, callback) {20 var results = [];21 var source = {};22 var regions = helpers.regions(settings);23 var config = {24 glue_s3_encryption_level: settings.glue_s3_encryption_level || this.settings.glue_s3_encryption_level.default,25 };26 var desiredEncryptionLevel = helpers.ENCRYPTION_LEVELS.indexOf(config.glue_s3_encryption_level);27 var currentEncryptionLevel;28 var acctRegion = helpers.defaultRegion(settings);29 var awsOrGov = helpers.defaultPartition(settings);30 var accountId = helpers.addSource(cache, source, ['sts', 'getCallerIdentity', acctRegion, 'data']);31 async.each(regions.glue, function(region, rcb){32 var getSecurityConfigurations = helpers.addSource(cache, source,33 ['glue', 'getSecurityConfigurations', region]);34 if (!getSecurityConfigurations) return rcb();35 if (getSecurityConfigurations.err || !getSecurityConfigurations.data) {36 helpers.addResult(results, 3,37 `Unable to query for AWS Glue security configurations: ${helpers.addError(getSecurityConfigurations)}`, region);38 return rcb();39 }40 if (!getSecurityConfigurations.data.length) {41 helpers.addResult(results, 0,42 'No AWS Glue security configurations found', region);43 return rcb();44 }45 async.each(getSecurityConfigurations.data, function(configuration, cb) {46 if (!configuration.Name) return cb();47 var resource = `arn:${awsOrGov}:glue:${region}:${accountId}:/securityConfiguration/${configuration.Name}`;48 var encryptionEnabled = false;49 if (configuration && configuration.EncryptionConfiguration &&50 configuration.EncryptionConfiguration.S3Encryption &&51 configuration.EncryptionConfiguration.S3Encryption.length) {52 for (var encryptionConfig of configuration.EncryptionConfiguration.S3Encryption) {53 if (encryptionConfig.S3EncryptionMode && encryptionConfig.S3EncryptionMode.toUpperCase() !== 'DISABLED') {54 encryptionEnabled = true;55 if (encryptionConfig.S3EncryptionMode.toUpperCase() === 'SSE-S3') {56 currentEncryptionLevel = helpers.ENCRYPTION_LEVELS.indexOf('sse');57 } else {58 if (encryptionConfig.KmsKeyArn) {59 var keyId = encryptionConfig.KmsKeyArn.split('/')[1];60 var describeKey = helpers.addSource(cache, source,61 ['kms', 'describeKey', region, keyId]);62 if (!describeKey || describeKey.err || !describeKey.data || !describeKey.data.KeyMetadata) {63 helpers.addResult(results, 3, `Unable to query associated KMS Key for configuration "${configuration.Name}": ${helpers.addError(describeKey)}`,64 region, resource);65 return cb();66 }67 currentEncryptionLevel = helpers.getEncryptionLevel(describeKey.data.KeyMetadata, helpers.ENCRYPTION_LEVELS);68 } else {69 helpers.addResult(results, 3, 'Unable to find associated KMS key for security configuration',70 region, resource);71 return cb();72 }73 }74 break;75 }76 }77 }78 var currentEncryptionLevelString = helpers.ENCRYPTION_LEVELS[currentEncryptionLevel];79 if (encryptionEnabled) {80 if (currentEncryptionLevel >= desiredEncryptionLevel) {81 helpers.addResult(results, 0,82 `Glue security configuration "${configuration.Name}" has S3 encryption enabled at encryption level ${currentEncryptionLevelString} which is greater than or equal to target level ${config.glue_s3_encryption_level}`,83 region, resource); 84 } else {85 helpers.addResult(results, 2,86 `Glue security configuration "${configuration.Name}" has S3 encryption enabled at encryption level ${currentEncryptionLevelString} which is less than target level ${config.glue_s3_encryption_level}`,87 region, resource);88 }89 } else {90 helpers.addResult(results, 2,91 `Glue security configuration "${configuration.Name}" does not have S3 encryption enabled`,92 region, resource);93 }94 cb();95 }, function(){96 rcb();97 });98 }, function(){99 callback(null, results, source);100 });101 }...
dataCatalogCmkEncrypted.spec.js
Source: dataCatalogCmkEncrypted.spec.js
1var expect = require('chai').expect;2var dataCatalogCmkEncrypted = require('./dataCatalogCmkEncrypted');3const getDataCatalogEncryptionSettings = [4 {5 "EncryptionAtRest": {6 "CatalogEncryptionMode": "SSE-KMS",7 "SseAwsKmsKeyId": "arn:aws:kms:us-east-1:111122223333:key/75e9285f-ae6b-4c36-9405-06e67bcc7ef1"8 },9 "ConnectionPasswordEncryption": {10 "ReturnConnectionPasswordEncrypted": false11 }12 },13 {14 "EncryptionAtRest": {15 "CatalogEncryptionMode": "DISABLED"16 },17 "ConnectionPasswordEncryption": {18 "ReturnConnectionPasswordEncrypted": false19 }20 }21];22const describeKey = [23 {24 "KeyMetadata": {25 "AWSAccountId": "111122223333",26 "KeyId": "75e9285f-ae6b-4c36-9405-06e67bcc7ef1",27 "Arn": "arn:aws:kms:us-east-1:111122223333:key/75e9285f-ae6b-4c36-9405-06e67bcc7ef1",28 "CreationDate": "2020-12-15T01:16:53.045000+05:00",29 "Enabled": true,30 "Description": "Default master key that protects my Glue data when no other key is defined",31 "KeyUsage": "ENCRYPT_DECRYPT",32 "KeyState": "Enabled",33 "Origin": "AWS_KMS",34 "KeyManager": "CUSTOMER",35 "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT",36 "EncryptionAlgorithms": [37 "SYMMETRIC_DEFAULT"38 ]39 }40 },41 {42 "KeyMetadata": {43 "AWSAccountId": "111122223333",44 "KeyId": "75e9285f-ae6b-4c36-9405-06e67bcc7ef1",45 "Arn": "arn:aws:kms:us-east-1:111122223333:key/75e9285f-ae6b-4c36-9405-06e67bcc7ef1",46 "CreationDate": "2020-12-15T01:16:53.045000+05:00",47 "Enabled": true,48 "Description": "Default master key that protects my Glue data when no other key is defined",49 "KeyUsage": "ENCRYPT_DECRYPT",50 "KeyState": "Enabled",51 "Origin": "AWS_KMS",52 "KeyManager": "AWS",53 "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT",54 "EncryptionAlgorithms": [55 "SYMMETRIC_DEFAULT"56 ]57 }58 }59]60const createCache = (configurations, describeKey, configurationsErr, describeKeyErr) => {61 var keyId = (configurations && configurations.EncryptionAtRest && configurations.EncryptionAtRest.SseAwsKmsKeyId) ? configurations.EncryptionAtRest.SseAwsKmsKeyId.split('/')[1] : null;62 return {63 glue: {64 getDataCatalogEncryptionSettings: {65 'us-east-1': {66 err: configurationsErr,67 data: configurations68 },69 },70 },71 kms: {72 describeKey: {73 'us-east-1': {74 [keyId]: {75 err: describeKeyErr,76 data: describeKey77 },78 },79 },80 },81 };82};83const createNullCache = () => {84 return {85 glue: {86 getDataCatalogEncryptionSettings: {87 'us-east-1': null88 }89 },90 kms: {91 describeKey: {92 'us-east-1': null93 }94 },95 };96};97describe('dataCatalogCmkEncrypted', function () {98 describe('run', function () {99 it('should PASS if Glue data catalog has encryption at-rest enabled for metadata using Customer Master Key', function (done) {100 const cache = createCache(getDataCatalogEncryptionSettings[0], describeKey[0]);101 dataCatalogCmkEncrypted.run(cache, {}, (err, results) => {102 expect(results.length).to.equal(1);103 expect(results[0].status).to.equal(0);104 done();105 });106 });107 it('should FAIL if Glue data catalog has encryption at-rest enabled for metadata using AWS-managed key', function (done) {108 const cache = createCache(getDataCatalogEncryptionSettings[0], describeKey[1]);109 dataCatalogCmkEncrypted.run(cache, {}, (err, results) => {110 expect(results.length).to.equal(1);111 expect(results[0].status).to.equal(2);112 done();113 });114 });115 it('should FAIL if Glue data catalog does not have encryption at-rest enabled for metadata', function (done) {116 const cache = createCache(getDataCatalogEncryptionSettings[1]);117 dataCatalogCmkEncrypted.run(cache, {}, (err, results) => {118 expect(results.length).to.equal(1);119 expect(results[0].status).to.equal(2);120 done();121 });122 });123 it('should UNKNOWN if unable to get AWS Glue data catalog encryption settings', function (done) {124 const cache = createCache(null, null, { message: "Unable to get AWS Glue data catalog encryption settings" });125 dataCatalogCmkEncrypted.run(cache, {}, (err, results) => {126 expect(results.length).to.equal(1);127 expect(results[0].status).to.equal(3);128 done();129 });130 });131 it('should UNKNOWN if unable to describe KMS key', function (done) {132 const cache = createCache(getDataCatalogEncryptionSettings[0], describeKey[0], null, { message: "Unable to describe KMS key" });133 dataCatalogCmkEncrypted.run(cache, {}, (err, results) => {134 expect(results.length).to.equal(1);135 expect(results[0].status).to.equal(3);136 done();137 });138 });139 it('should not return anything if get datalog encryption settings response not found', function (done) {140 const cache = createNullCache();141 dataCatalogCmkEncrypted.run(cache, {}, (err, results) => {142 expect(results.length).to.equal(0);143 done();144 });145 });146 });...
ebsDefaultEncryptionEnabled.js
Source: ebsDefaultEncryptionEnabled.js
1var async = require('async');2var helpers = require('../../../helpers/aws');3module.exports = {4 title: 'EBS Encryption Enabled By Default',5 category: 'EC2',6 description: 'Ensure the setting for encryption by default is enabled',7 more_info: 'AWS account should be configured to enable encryption for new EBS volumes and snapshots for all regions.',8 link: 'https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-by-default',9 recommended_action: 'Enable EBS Encryption by Default',10 apis: ['EC2:getEbsEncryptionByDefault', 'EC2:getEbsDefaultKmsKeyId', 'KMS:describeKey', 'KMS:listKeys', 'KMS:listAliases'],11 settings: {12 ebs_encryption_level: {13 name: 'EBS Minimum Encryption Level',14 description: 'In order (lowest to highest) none=no encryption; awskms=AWS-managed KMS; awscmk=Customer managed KMS; externalcmk=Customer managed externally sourced KMS; cloudhsm=Customer managed CloudHSM sourced KMS',15 regex: '^(none|awskms|awscmk|externalcmk|cloudhsm)$',16 default: 'awskms',17 },18 },19 run: function(cache, settings, callback) {20 var results = [];21 var source = {};22 var regions = helpers.regions(settings);23 var ebs_encryption_level = settings.ebs_encryption_level || this.settings.ebs_encryption_level.default;24 var targetEncryptionLevel = helpers.ENCRYPTION_LEVELS.indexOf(ebs_encryption_level);25 async.each(regions.ec2, function(region, rcb){26 var getEbsEncryptionByDefault = helpers.addSource(cache, source,27 ['ec2', 'getEbsEncryptionByDefault', region]);28 if (!getEbsEncryptionByDefault) return rcb();29 if (getEbsEncryptionByDefault.err) {30 helpers.addResult(results, 3,31 'Unable to query for ebs encryption by default: ' + helpers.addError(getEbsEncryptionByDefault), region);32 return rcb();33 }34 if (!getEbsEncryptionByDefault.data) {35 helpers.addResult(results, 2,36 'EBS default encryption is disabled', region);37 return rcb();38 }39 var getEbsDefaultKmsKeyId = helpers.addSource(cache, source,40 ['ec2', 'getEbsDefaultKmsKeyId', region]);41 if (!getEbsDefaultKmsKeyId || getEbsDefaultKmsKeyId.err || !getEbsDefaultKmsKeyId.data) {42 helpers.addResult(results, 3,43 'Unable to query for ebs default kms key id: ' + helpers.addError(getEbsDefaultKmsKeyId), region);44 return rcb();45 }46 var kmsKeyId = '';47 var isPredefinedAlias = false;48 if (getEbsDefaultKmsKeyId.data.split('/')[0] === 'alias') {49 var listAliases = helpers.addSource(cache, source, ['kms', 'listAliases', region]);50 if (!listAliases || listAliases.err || !listAliases.data) {51 helpers.addResult(results, 3, 'Unable to query for list aliases: ' + helpers.addError(listAliases), region);52 return rcb();53 }54 listAliases.data.forEach(function(alias){55 if (alias.AliasName === getEbsDefaultKmsKeyId.data) {56 if (alias.TargetKeyId) {57 kmsKeyId = alias.TargetKeyId;58 }59 else {60 isPredefinedAlias = true;61 }62 }63 });64 } else {65 kmsKeyId = getEbsDefaultKmsKeyId.data.split('/')[1];66 }67 var encryptionLevel;68 if (!isPredefinedAlias) {69 var describeKey = helpers.addSource(cache, source, ['kms', 'describeKey', region, kmsKeyId]);70 71 if (!describeKey || describeKey.err || !describeKey.data || !describeKey.data.KeyMetadata) {72 helpers.addResult(results, 3,73 'Unable to query kms key: ' + helpers.addError(describeKey), region);74 return rcb();75 }76 encryptionLevel = helpers.getEncryptionLevel(describeKey.data.KeyMetadata, helpers.ENCRYPTION_LEVELS);77 } else {78 encryptionLevel = 2; //awskms79 }80 if (encryptionLevel < targetEncryptionLevel) {81 helpers.addResult(results, 2,82 `EBS default encryption is enabled but current encryption level ${helpers.ENCRYPTION_LEVELS[encryptionLevel]} is less than the target level ${helpers.ENCRYPTION_LEVELS[targetEncryptionLevel]}`, region);83 } else {84 helpers.addResult(results, 0,85 `EBS default encryption is enabled and current encryption level ${helpers.ENCRYPTION_LEVELS[encryptionLevel]} is greater than or equal to the target level ${helpers.ENCRYPTION_LEVELS[targetEncryptionLevel]}`, region);86 }87 rcb();88 }, function(){89 callback(null, results, source);90 });91 }...
index.js
Source: index.js
1const heightInput = document.getElementById('height');2const weightInput = document.getElementById('weight');3var bmiData;4//樣æ¿å串5const template = {6 result: (BMI, DescribeKey, describe) => {7 return `<div class="result ${DescribeKey}">8 <div class="result-circle">9 <div class="bmi-wrapper">10 <span class="result-num">${BMI}</span>11 <span class="bmi-text">BMI</span>12 </div>13 <button id="reset" class="reset-btn" onclick="reset()">14 <img src="static/img/icon/icons_loop.png" alt="reset" />15 </button>16 </div>17 <div class="result-text">${describe}</div>18 </div>`;19 },20 submitBtn: () => {21 return `<button id="submit" class="submit-btn" onclick="submit()">ççµæ</button>`;22 },23 recordList: ({ height, weight, BMI, describe, DescribeKey }, dateString) => {24 return `<li class="record-li ${DescribeKey}">25 <span class="main-text">${describe}</span>26 <span>27 <span class="label">BMI</span>28 <span class="main-text">${BMI}</span>29 </span>30 <span>31 <span class="label">weight</span>32 <span class="main-text">${weight}kg</span>33 </span>34 <span>35 <span class="label">height</span>36 <span class="main-text">${height}cm</span>37 </span>38 <span class="date">${dateString}</span>39 </li>`;40 }41};42//init rendering43renderData();44//èçæ交è¡çº45function submit() {46 const calcWrapper = document.getElementById('calc-wrapper');47 const height = heightInput.value;48 const weight = weightInput.value;49 if (!inputValidate(height, weight)) {50 return;51 }52 const { BMI, describe, DescribeKey } = calcBMI(height, weight);53 if (BMI > 99 || BMI < 1) {54 alert('è«è¼¸å
¥åçæ¸å¼');55 return;56 }57 const timestamp = new Date().getTime();58 const storedData = { height, weight, BMI, describe, DescribeKey, timestamp };59 const newUuid = _uuid();60 bmiData[newUuid] = storedData;61 localStorage.setItem('bmiData', JSON.stringify(bmiData));62 renderData();63 calcWrapper.innerHTML = template.result(BMI, DescribeKey, describe);64}65//èçéç½®è¡çº66function reset() {67 const calcWrapper = document.getElementById('calc-wrapper');68 calcWrapper.innerHTML = template.submitBtn();69 //reset value of inputs70 heightInput.value = null;71 weightInput.value = null;72}73//é©è身é«åé«éæ¯å¦å¤§æ¼074function inputValidate(height, weight) {75 if (height > 0 && weight > 0) {76 return true;77 } else {78 alert('è«è¼¸å
¥èº«é«åé«é');79 return false;80 }81}82//è¨ç®BMIå¼83function calcBMI(height, weight) {84 const BMI = weight / Math.pow(height / 100, 2);85 const { DescribeKey, describe } = analysis(BMI);86 return { BMI: BMI.toFixed(2), DescribeKey, describe };87}88//解æBMIå¼çµæ89function analysis(BMI) {90 if (BMI < 18.5) {91 return { DescribeKey: 'underWeight', describe: 'éè¼' };92 } else if (BMI >= 18.5 && BMI < 24) {93 return { DescribeKey: 'ideal', describe: 'çæ³' };94 } else if (BMI >= 24 && BMI < 27) {95 return { DescribeKey: 'overWeight', describe: 'éé' };96 } else if (BMI >= 27 && BMI < 30) {97 return { DescribeKey: 'mildObesity', describe: 'è¼åº¦è¥è' };98 } else if (BMI >= 30 && BMI < 35) {99 return { DescribeKey: 'moderateObesity', describe: 'ä¸åº¦è¥è' };100 } else if (BMI >= 35) {101 return { DescribeKey: 'severeObesity', describe: 'é度è¥è' };102 }103}104//å°è³ærenderé²DOMå
ç´ 105function renderData() {106 bmiData = JSON.parse(localStorage.getItem('bmiData')) || {};107 const recordUl = document.getElementById('recordUl');108 const listArray = [];109 recordUl.innerHTML = '';110 for (var key in bmiData) {111 const date = new Date(bmiData[key].timestamp);112 const dateString = `${date.getMonth() + 1}-${date.getDate()}-${date.getFullYear()}`;113 const listItem = template.recordList(bmiData[key], dateString);114 listArray.push(listItem);115 }116 recordUl.innerHTML = listArray.reverse().join('');117}118//ç¢çuuid119function _uuid() {120 var d = Date.now();121 if (typeof performance !== 'undefined' && typeof performance.now === 'function') {122 d += performance.now(); //use high-precision timer if available123 }124 return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {125 var r = (d + Math.random() * 16) % 16 | 0;126 d = Math.floor(d / 16);127 return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);128 });...
kmsKeyRotation.js
Source: kmsKeyRotation.js
1var async = require('async');2var helpers = require('../../../helpers/aws');3module.exports = {4 title: 'KMS Key Rotation',5 category: 'KMS',6 description: 'Ensures KMS keys are set to rotate on a regular schedule',7 more_info: 'All KMS keys should have key rotation enabled. AWS will handle the rotation of the encryption key itself, as well as storage of previous keys, so previous data does not need to be re-encrypted before the rotation occurs.',8 recommended_action: 'Enable yearly rotation for the KMS key',9 link: 'http://docs.aws.amazon.com/kms/latest/developerguide/rotate-keys.html',10 apis: ['KMS:listKeys', 'KMS:describeKey', 'KMS:getKeyRotationStatus'],11 compliance: {12 pci: 'PCI has strict requirements regarding the use of encryption keys ' +13 'to protect cardholder data. These requirements include rotating ' +14 'the key periodically. KMS provides key rotation capabilities that ' +15 'should be enabled.'16 },17 run: function(cache, settings, callback) {18 var results = [];19 var source = {};20 var regions = helpers.regions(settings);21 async.each(regions.kms, function(region, rcb){22 23 var listKeys = helpers.addSource(cache, source,24 ['kms', 'listKeys', region]);25 if (!listKeys) return rcb();26 if (listKeys.err || !listKeys.data) {27 helpers.addResult(results, 3,28 'Unable to list KMS keys: ' + helpers.addError(listKeys), region);29 return rcb();30 }31 if (!listKeys.data.length) {32 helpers.addResult(results, 0, 'No KMS keys found', region);33 return rcb(); 34 }35 async.each(listKeys.data, function(kmsKey, kcb){36 var describeKey = helpers.addSource(cache, source,37 ['kms', 'describeKey', region, kmsKey.KeyId]);38 var getKeyRotationStatus = helpers.addSource(cache, source,39 ['kms', 'getKeyRotationStatus', region, kmsKey.KeyId]);40 if (!describeKey || describeKey.err || !describeKey.data) {41 helpers.addResult(results, 3,42 'Unable to describe key: ' + helpers.addError(describeKey),43 region, kmsKey.KeyArn);44 return kcb();45 }46 var describeKeyData = describeKey.data;47 // AWS-generated keys for CodeCommit, ACM, etc. should be skipped.48 // The only way to distinguish these keys is the default description used by AWS.49 // Also skip keys that are being deleted50 if (describeKeyData.KeyMetadata &&51 (describeKeyData.KeyMetadata.Description && describeKeyData.KeyMetadata.Description.indexOf('Default master key that protects my') === 0) ||52 (describeKeyData.KeyMetadata.KeyState && describeKeyData.KeyMetadata.KeyState == 'PendingDeletion')) {53 return kcb();54 }55 // Skip keys that are imported into KMS56 if (describeKeyData.KeyMetadata &&57 describeKeyData.KeyMetadata.Origin &&58 describeKeyData.KeyMetadata.Origin !== 'AWS_KMS') {59 return kcb();60 }61 var keyRotationStatusData = getKeyRotationStatus.data;62 if (!getKeyRotationStatus || getKeyRotationStatus.err || !getKeyRotationStatus.data) {63 helpers.addResult(results, 3,64 'Unable to get key rotation status: ' + helpers.addError(getKeyRotationStatus),65 region, kmsKey.KeyArn);66 return kcb();67 }68 if (keyRotationStatusData.KeyRotationEnabled) {69 helpers.addResult(results, 0, 'Key rotation is enabled', region, kmsKey.KeyArn);70 } else {71 helpers.addResult(results, 2, 'Key rotation is not enabled', region, kmsKey.KeyArn);72 }73 kcb();74 }, function(){75 rcb();76 });77 }, function(){78 callback(null, results, source);79 });80 }...
secretsManagerEncrypted.js
Source: secretsManagerEncrypted.js
1var async = require('async');2var helpers = require('../../../helpers/aws');3module.exports = {4 title: 'Secrets Manager Encrypted Secrets',5 category: 'Secrets Manager',6 domain: 'Identity and Access Management',7 description: 'Ensures Secrets Manager Secrets are encrypted',8 more_info: 'Secrets Manager Secrets should be encrypted. This allows their values to be used by approved systems, while restricting access to other users of the account.',9 recommended_action: 'Encrypt Secrets Manager Secrets',10 apis: ['SecretsManager:listSecrets', 'KMS:listKeys', 'KMS:describeKey'],11 link: 'https://docs.aws.amazon.com/secretsmanager/latest/userguide/data-protection.html',12 compliance: {13 hipaa: 'HIPAA requires that all data is encrypted, including data at rest',14 pci: 'PCI requires proper encryption of cardholder data at rest. Secrets Manager ' +15 'encryption should be enabled for all Secrets storing this type ' +16 'of data.'17 },18 settings: {19 secretsmanager_minimum_encryption_level: {20 name: 'Secrets Manager Secret Minimum Encryption Level',21 description: 'In order (lowest to highest) \22 awskms=AWS-managed KMS; \23 awscmk=Customer managed KMS; \24 externalcmk=Customer managed externally sourced KMS; \25 cloudhsm=Customer managed CloudHSM sourced KMS',26 regex: '^(awskms|awscmk|externalcmk|cloudhsm)$',27 default: 'awskms',28 }29 },30 run: function(cache, settings, callback) {31 var results = [];32 var source = {};33 var regions = helpers.regions(settings);34 var desiredEncryptionLevelString = settings.secretsmanager_minimum_encryption_level || this.settings.secretsmanager_minimum_encryption_level.default;35 var desiredEncryptionLevel = helpers.ENCRYPTION_LEVELS.indexOf(desiredEncryptionLevelString);36 async.each(regions.secretsmanager, (region, rcb) => {37 var listSecrets = helpers.addSource(cache, source, ['secretsmanager', 'listSecrets', region]);38 if (!listSecrets) return rcb();39 if (!listSecrets.data || listSecrets.err) {40 helpers.addResult(results, 3, `Unable to query for secrets: ${helpers.addError(listSecrets)}`, region);41 return rcb();42 }43 if (!listSecrets.data.length) {44 helpers.addResult(results, 0, 'No secrets found', region);45 return rcb();46 }47 for (let secret of listSecrets.data) {48 let encryptionLevel;49 let encryptionLevelString;50 if (!secret.KmsKeyId) encryptionLevel = 2; //awskms51 else {52 const keyId = secret.KmsKeyId.startsWith('arn:aws:kms')53 ? secret.KmsKeyId.split('/')[1]54 : secret.KmsKeyId;55 const describeKey = helpers.addSource(cache, source, ['kms', 'describeKey', region, keyId]);56 if (!describeKey || describeKey.err || !describeKey.data || !describeKey.data.KeyMetadata) {57 helpers.addResult(results, 3, `Unable to query for KMS Key: ${helpers.addError(describeKey)}`, region, keyId);58 continue;59 }60 encryptionLevel = helpers.getEncryptionLevel(describeKey.data.KeyMetadata, helpers.ENCRYPTION_LEVELS);61 }62 encryptionLevelString = helpers.ENCRYPTION_LEVELS[encryptionLevel];63 if (encryptionLevel < desiredEncryptionLevel) {64 helpers.addResult(results, 2, `Secret configured to use ${encryptionLevelString} instead of ${desiredEncryptionLevelString}`, region, secret.ARN);65 } else {66 helpers.addResult(results, 0, `Secret configured to use desired encryption ${encryptionLevelString}`, region, secret.ARN);67 }68 }69 rcb();70 }, function(){71 callback(null, results, source);72 });73 }...
dataCatalogCmkEncrypted.js
Source: dataCatalogCmkEncrypted.js
1var async = require('async');2var helpers = require('../../../helpers/aws');3module.exports = {4 title: 'AWS Glue Data Catalog CMK Encrypted',5 category: 'Glue',6 description: 'Ensures that AWS Glue has data catalog encryption enabled with KMS Customer Master Key (CMK).',7 more_info: 'AWS Glue should have data catalog encryption enabled with KMS Customer Master Key (CMK) instead of AWS-managed Key in order to gain more granular control over encryption/decryption process.',8 recommended_action: 'Modify Glue data catalog to use CMK instead of AWS-managed Key to encrypt Metadata',9 link: 'https://docs.aws.amazon.com/glue/latest/dg/encrypt-glue-data-catalog.html',10 apis: ['Glue:getDataCatalogEncryptionSettings', 'KMS:listKeys', 'KMS:describeKey'],11 run: function(cache, settings, callback) {12 var results = [];13 var source = {};14 var regions = helpers.regions(settings);15 async.each(regions.glue, function(region, rcb){16 var getDataCatalogEncryptionSettings = helpers.addSource(cache, source,17 ['glue', 'getDataCatalogEncryptionSettings', region]);18 if (!getDataCatalogEncryptionSettings) return rcb();19 if (getDataCatalogEncryptionSettings.err || !getDataCatalogEncryptionSettings.data) {20 helpers.addResult(results, 3,21 `Unable to query Glue data catalog encryption settings: ${helpers.addError(getDataCatalogEncryptionSettings)}`, region);22 return rcb();23 }24 var encryptionSettings = getDataCatalogEncryptionSettings.data;25 if (encryptionSettings && encryptionSettings.EncryptionAtRest &&26 encryptionSettings.EncryptionAtRest.CatalogEncryptionMode &&27 encryptionSettings.EncryptionAtRest.SseAwsKmsKeyId &&28 encryptionSettings.EncryptionAtRest.CatalogEncryptionMode.toUpperCase() !== 'DISABLED') {29 var kmsKeyId = encryptionSettings.EncryptionAtRest.SseAwsKmsKeyId.split('/')[1];30 var describeKey = helpers.addSource(cache, source,31 ['kms', 'describeKey', region, kmsKeyId]);32 if (!describeKey || describeKey.err || !describeKey.data ||33 !describeKey.data.KeyMetadata || !describeKey.data.KeyMetadata) {34 helpers.addResult(results, 3,35 `Unable to query KMS key: ${helpers.addError(describeKey)}`,36 region, kmsKeyId);37 return rcb();38 }39 if (helpers.getEncryptionLevel(describeKey.data.KeyMetadata, helpers.ENCRYPTION_LEVELS) == 3) {40 helpers.addResult(results, 0,41 'Glue data catalog has encryption at-rest enabled for metadata using Customer Master Key',42 region);43 } else {44 helpers.addResult(results, 2,45 'Glue data catalog has encryption at-rest enabled for metadata using AWS-managed key',46 region);47 }48 } else {49 helpers.addResult(results, 2,50 'Glue data catalog does not have encryption at-rest enabled for metadata',51 region);52 }53 rcb();54 }, function(){55 callback(null, results, source);56 });57 }...
kmsScheduledDeletion.js
Source: kmsScheduledDeletion.js
1var async = require('async');2var helpers = require('../../../helpers/aws');3module.exports = {4 title: 'KMS Scheduled Deletion',5 category: 'KMS',6 description: 'Detects KMS keys that are scheduled for deletion',7 more_info: 'Deleting a KMS key will permanently prevent all data encrypted using that key from being decrypted. Avoid deleting keys unless no encrypted data is in use.',8 recommended_action: 'Disable the key deletion before the scheduled deletion time.',9 link: 'http://docs.aws.amazon.com/kms/latest/developerguide/deleting-keys.html',10 apis: ['KMS:listKeys', 'KMS:describeKey'],11 asl: {12 conditions: [13 {14 service: 'kms',15 api: 'describeKey',16 property: 'KeyMetadata.KeyState',17 transform: 'STRING',18 op: 'EQ',19 value: 'PendingDeletion'20 }21 ]22 },23 run: function(cache, settings, callback) {24 var results = [];25 var source = {};26 var regions = helpers.regions(settings);27 async.each(regions.kms, function(region, rcb){28 29 var listKeys = helpers.addSource(cache, source,30 ['kms', 'listKeys', region]);31 if (!listKeys) return rcb();32 if (listKeys.err || !listKeys.data) {33 helpers.addResult(results, 3,34 'Unable to list KMS keys: ' + helpers.addError(listKeys), region);35 return rcb();36 }37 if (!listKeys.data.length) {38 helpers.addResult(results, 0, 'No KMS keys found', region);39 return rcb(); 40 }41 async.each(listKeys.data, function(kmsKey, kcb){42 var describeKey = helpers.addSource(cache, source,43 ['kms', 'describeKey', region, kmsKey.KeyId]);44 if (!describeKey || describeKey.err || !describeKey.data) {45 helpers.addResult(results, 3,46 'Unable to describe key: ' + helpers.addError(describeKey),47 region, kmsKey.KeyArn);48 return kcb();49 }50 var describeKeyData = describeKey.data;51 // AWS-generated keys for CodeCommit, ACM, etc. should be skipped.52 // The only way to distinguish these keys is the default description used by AWS.53 if (describeKeyData.KeyMetadata &&54 (describeKeyData.KeyMetadata.Description && describeKeyData.KeyMetadata.Description.indexOf('Default master key that protects my') === 0)) {55 return kcb();56 }57 if (describeKeyData && describeKeyData.KeyMetadata &&58 describeKeyData.KeyMetadata.KeyState &&59 describeKeyData.KeyMetadata.KeyState == 'PendingDeletion') {60 helpers.addResult(results, 1, 'Key is scheduled for deletion', region, kmsKey.KeyArn);61 } else {62 helpers.addResult(results, 0, 'Key is not scheduled for deletion', region, kmsKey.KeyArn);63 }64 kcb();65 }, function(){66 rcb();67 });68 }, function(){69 callback(null, results, source);70 });71 }...
How to test if a method returns an array of a class in Jest
How do node_modules packages read config files in the project root?
Jest: how to mock console when it is used by a third-party-library?
ERESOLVE unable to resolve dependency tree while installing a pacakge
Testing arguments with toBeCalledWith() in Jest
Is there assertCountEqual equivalent in javascript unittests jest library?
NodeJS: NOT able to set PERCY_TOKEN via package script with start-server-and-test
Jest: How to consume result of jest.genMockFromModule
How To Reset Manual Mocks In Jest
How to move '__mocks__' folder in Jest to /test?
Since Jest tests are runtime tests, they only have access to runtime information. You're trying to use a type, which is compile-time information. TypeScript should already be doing the type aspect of this for you. (More on that in a moment.)
The fact the tests only have access to runtime information has a couple of ramifications:
If it's valid for getAll
to return an empty array (because there aren't any entities to get), the test cannot tell you whether the array would have had Entity
elements in it if it hadn't been empty. All it can tell you is it got an array.
In the non-empty case, you have to check every element of the array to see if it's an Entity
. You've said Entity
is a class, not just a type, so that's possible. I'm not a user of Jest (I should be), but it doesn't seem to have a test specifically for this; it does have toBeTruthy
, though, and we can use every
to tell us if every element is an Entity
:
it('should return an array of Entity class', async () => {
const all = await service.getAll()
expect(all.every(e => e instanceof Entity)).toBeTruthy();
});
Beware, though, that all calls to every
on an empty array return true
, so again, that empty array issue raises its head.
If your Jest tests are written in TypeScript, you can improve on that by ensuring TypeScript tests the compile-time type of getAll
's return value:
it('should return an array of Entity class', async () => {
const all: Entity[] = await service.getAll()
// ^^^^^^^^^^
expect(all.every(e => e instanceof Entity)).toBeTruthy();
});
TypeScript will complain about that assignment at compile time if it's not valid, and Jest will complain at runtime if it sees an array containing a non-Entity
object.
But jonrsharpe has a good point: This test may not be useful vs. testing for specific values that should be there.
Check out the latest blogs from LambdaTest on this topic:
Node js has become one of the most popular frameworks in JavaScript today. Used by millions of developers, to develop thousands of project, node js is being extensively used. The more you develop, the better the testing you require to have a smooth, seamless application. This article shares the best practices for the testing node.in 2019, to deliver a robust web application or website.
Storybook offers a clean-room setting for isolating component testing. No matter how complex a component is, stories make it simple to explore it in all of its permutations. Before we discuss the Storybook testing in any browser, let us try and understand the fundamentals related to the Storybook framework and how it simplifies how we build UI components.
Quality Assurance (QA) is at the point of inflection and it is an exciting time to be in the field of QA as advanced digital technologies are influencing QA practices. As per a press release by Gartner, The encouraging part is that IT and automation will play a major role in transformation as the IT industry will spend close to $3.87 trillion in 2020, up from $3.76 trillion in 2019.
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on WebDriverIO Tutorial and Selenium JavaScript Tutorial.
Having a strategy or plan can be the key to unlocking many successes, this is true to most contexts in life whether that be sport, business, education, and much more. The same is true for any company or organisation that delivers software/application solutions to their end users/customers. If you narrow that down even further from Engineering to Agile and then even to Testing or Quality Engineering, then strategy and planning is key at every level.
LambdaTest’s Jest Testing Tutorial covers step-by-step guides around Jest with code examples to help you be proficient with the Jest framework. The Jest tutorial has chapters to help you learn right from the basics of Jest framework to code-based tutorials around testing react apps with Jest, perform snapshot testing, import ES modules and more.
|<p>it('check_object_of_Car', () => {</p><p>
expect(newCar()).toBeInstanceOf(Car);</p><p>
});</p>|
| :- |
Get 100 minutes of automation test minutes FREE!!