diff --git a/app/controllers/software-controller.js b/app/controllers/software-controller.js index c1c641e3..da22f886 100644 --- a/app/controllers/software-controller.js +++ b/app/controllers/software-controller.js @@ -2,8 +2,9 @@ const softwareService = require('../services/software-service'); const logger = require('../lib/logger'); +const { DuplicateIdError, BadlyFormattedParameterError, InvalidQueryStringParameterError, PropertyNotAllowedError } = require('../exceptions'); -exports.retrieveAll = function(req, res) { +exports.retrieveAll = async function(req, res) { const options = { offset: req.query.offset || 0, limit: req.query.limit || 0, @@ -16,165 +17,172 @@ exports.retrieveAll = function(req, res) { lastUpdatedBy: req.query.lastUpdatedBy, includePagination: req.query.includePagination } - - softwareService.retrieveAll(options, function(err, results) { - if (err) { - logger.error('Failed with error: ' + err); - return res.status(500).send('Unable to get software. Server error.'); + try { + const results = await softwareService.retrieveAll(options); + if (options.includePagination) { + logger.debug(`Success: Retrieved ${ results.data.length } of ${ results.pagination.total } total software`); } else { - if (options.includePagination) { - logger.debug(`Success: Retrieved ${ results.data.length } of ${ results.pagination.total } total software`); - } - else { - logger.debug(`Success: Retrieved ${ results.length } software`); - } - return res.status(200).send(results); - } - }); + logger.debug(`Success: Retrieved ${ results.length } software`); + } + return res.status(200).send(results); + } catch (err) { + console.log("retrieve all error"); + console.log(err); + logger.error('Failed with error: ' + err); + return res.status(500).send('Unable to get software. Server error.'); + } }; -exports.retrieveById = function(req, res) { +exports.retrieveById = async function(req, res) { const options = { versions: req.query.versions || 'latest' } - - softwareService.retrieveById(req.params.stixId, options, function (err, software) { - if (err) { - if (err.message === softwareService.errors.badlyFormattedParameter) { - logger.warn('Badly formatted stix id: ' + req.params.stixId); - return res.status(400).send('Stix id is badly formatted.'); - } - else if (err.message === softwareService.errors.invalidQueryStringParameter) { - logger.warn('Invalid query string: versions=' + req.query.versions); - return res.status(400).send('Query string parameter versions is invalid.'); - } - else { - logger.error('Failed with error: ' + err); - return res.status(500).send('Unable to get software. Server error.'); - } + try { + const software = await softwareService.retrieveById(req.params.stixId, options); + if (software.length === 0) { + return res.status(404).send('Software not found.'); + } + else { + logger.debug(`Success: Retrieved ${ software.length } software with id ${ req.params.stixId }`); + return res.status(200).send(software); + } + + } catch (err) { + if (err instanceof BadlyFormattedParameterError) { + logger.warn('Badly formatted stix id: ' + req.params.stixId); + return res.status(400).send('Stix id is badly formatted.'); + } + else if (err instanceof InvalidQueryStringParameterError) { + logger.warn('Invalid query string: versions=' + req.query.versions); + return res.status(400).send('Query string parameter versions is invalid.'); } else { - if (software.length === 0) { - return res.status(404).send('Software not found.'); - } - else { - logger.debug(`Success: Retrieved ${ software.length } software with id ${ req.params.stixId }`); - return res.status(200).send(software); - } - } - }); + console.log("retrieve by id error"); + console.log(err); + logger.error('Failed with error: ' + err); + return res.status(500).send('Unable to get software. Server error.'); + } + } + }; -exports.retrieveVersionById = function(req, res) { - softwareService.retrieveVersionById(req.params.stixId, req.params.modified, function (err, software) { - if (err) { - if (err.message === softwareService.errors.badlyFormattedParameter) { - logger.warn('Badly formatted stix id: ' + req.params.stixId); - return res.status(400).send('Stix id is badly formatted.'); - } - else { - logger.error('Failed with error: ' + err); - return res.status(500).send('Unable to get software. Server error.'); - } - } else { - if (!software) { - return res.status(404).send('Software not found.'); - } - else { - logger.debug(`Success: Retrieved software with id ${software.id}`); - return res.status(200).send(software); - } - } - }); +exports.retrieveVersionById = async function(req, res) { + try { + const software = await softwareService.retrieveVersionById(req.params.stixId, req.params.modified); + + if (!software) { + return res.status(404).send('Software not found.'); + } + else { + logger.debug(`Success: Retrieved software with id ${software.id}`); + return res.status(200).send(software); + } + } catch (err) { + + if (err instanceof BadlyFormattedParameterError) { + logger.warn('Badly formatted stix id: ' + req.params.stixId); + return res.status(400).send('Stix id is badly formatted.'); + } + else { + console.log("retrieve version by id error"); + console.log(err); + logger.error('Failed with error: ' + err); + return res.status(500).send('Unable to get software. Server error.'); + } + } + }; exports.create = async function(req, res) { // Get the data from the request const softwareData = req.body; + const options = { + import: false, + userAccountId: req.user?.userAccountId + }; + // Create the software try { - const options = { - import: false, - userAccountId: req.user?.userAccountId - }; - const software = await softwareService.create(softwareData, options); + const software = await await softwareService.create(softwareData, options); logger.debug("Success: Created software with id " + software.stix.id); return res.status(201).send(software); - } - catch(err) { - if (err.message === softwareService.errors.duplicateId) { + } catch(err) { + if (err instanceof DuplicateIdError) { logger.warn("Duplicate stix.id and stix.modified"); return res.status(409).send('Unable to create software. Duplicate stix.id and stix.modified properties.'); } - else if (err.message === softwareService.errors.missingProperty) { - logger.warn(`Unable to create software, missing property ${ err.propertyName }`); - return res.status(400).send(`Unable to create software, missing property ${ err.propertyName }`); - } - else if (err.message === softwareService.errors.propertyNotAllowed) { + else if (err instanceof PropertyNotAllowedError) { logger.warn(`Unable to create software, property ${ err.propertyName } is not allowed`); return res.status(400).send(`Unable to create software, property ${ err.propertyName } is not allowed`); } else { + console.log("create error"); + console.log(err); logger.error("Failed with error: " + err); return res.status(500).send("Unable to create software. Server error."); } } }; -exports.updateFull = function(req, res) { +exports.updateFull = async function(req, res) { // Get the data from the request const softwareData = req.body; - // Create the software - softwareService.updateFull(req.params.stixId, req.params.modified, softwareData, function(err, software) { - if (err) { - logger.error("Failed with error: " + err); - return res.status(500).send("Unable to update software. Server error."); + try { + // Create the software + const software = await softwareService.updateFull(req.params.stixId, req.params.modified, softwareData); + + if (!software) { + return res.status(404).send('Software not found.'); + } else { + logger.debug("Success: Updated software with id " + software.stix.id); + return res.status(200).send(software); } - else { - if (!software) { - return res.status(404).send('Software not found.'); - } else { - logger.debug("Success: Updated software with id " + software.stix.id); - return res.status(200).send(software); - } - } - }); + } catch (err) { + console.log("update full error"); + console.log(err); + logger.error("Failed with error: " + err); + return res.status(500).send("Unable to update software. Server error."); + } }; -exports.deleteVersionById = function(req, res) { - softwareService.deleteVersionById(req.params.stixId, req.params.modified, function (err, software) { - if (err) { - logger.error('Delete software failed. ' + err); - return res.status(500).send('Unable to delete software. Server error.'); +exports.deleteVersionById = async function(req, res) { + try { + const software = await softwareService.deleteVersionById(req.params.stixId, req.params.modified); + + if (!software) { + return res.status(404).send('Software not found.'); + } else { + logger.debug("Success: Deleted software with id " + software.stix.id); + return res.status(204).end(); } - else { - if (!software) { - return res.status(404).send('Software not found.'); - } else { - logger.debug("Success: Deleted software with id " + software.stix.id); - return res.status(204).end(); - } - } - }); + + } catch (err) { + console.log("delete version by id error"); + console.log(err); + logger.error('Delete software failed. ' + err); + return res.status(500).send('Unable to delete software. Server error.'); + } }; -exports.deleteById = function(req, res) { - softwareService.deleteById(req.params.stixId, function (err, softwares) { - if (err) { - logger.error('Delete software failed. ' + err); - return res.status(500).send('Unable to delete software. Server error.'); +exports.deleteById = async function(req, res) { + try { + const softwares = await softwareService.deleteById(req.params.stixId); + + if (softwares.deletedCount === 0) { + return res.status(404).send('Software not found.'); } else { - if (softwares.deletedCount === 0) { - return res.status(404).send('Software not found.'); - } - else { - logger.debug(`Success: Deleted software with id ${ req.params.stixId }`); - return res.status(204).end(); - } - } - }); + logger.debug(`Success: Deleted software with id ${ req.params.stixId }`); + return res.status(204).end(); + } + + } catch (err) { + console.log("delete by id error"); + console.log(err); + logger.error('Delete software failed. ' + err); + return res.status(500).send('Unable to delete software. Server error.'); + } }; diff --git a/app/exceptions/index.js b/app/exceptions/index.js index a228f196..13476470 100644 --- a/app/exceptions/index.js +++ b/app/exceptions/index.js @@ -87,6 +87,12 @@ class NotImplementedError extends CustomError { } } +class PropertyNotAllowedError extends CustomError { + constructor(propertyName, options) { + super(`Unable to create software, property ${propertyName} is not allowed`, options); + } +} + class InvalidTypeError extends CustomError { constructor(options) { super('Invalid stix.type', options); @@ -114,5 +120,7 @@ module.exports = { IdentityServiceError, TechniquesServiceError, TacticsServiceError, + PropertyNotAllowedError, + InvalidTypeError, }; diff --git a/app/repository/software-repository.js b/app/repository/software-repository.js new file mode 100644 index 00000000..a1aeb200 --- /dev/null +++ b/app/repository/software-repository.js @@ -0,0 +1,8 @@ +'use strict'; + +const BaseRepository = require('./_base.repository'); +const Software = require('../models/software-model'); + +class SoftwareRepository extends BaseRepository { } + +module.exports = new SoftwareRepository(Software); \ No newline at end of file diff --git a/app/services/software-service.js b/app/services/software-service.js index a9711124..18899a6e 100644 --- a/app/services/software-service.js +++ b/app/services/software-service.js @@ -1,400 +1,88 @@ 'use strict'; const uuid = require('uuid'); -const Software = require('../models/software-model'); const systemConfigurationService = require('./system-configuration-service'); -const identitiesService = require('./identities-service'); const attackObjectsService = require('./attack-objects-service'); const config = require('../config/config'); -const regexValidator = require('../lib/regex'); -const {lastUpdatedByQueryHelper} = require('../lib/request-parameter-helper'); -const errors = { - missingParameter: 'Missing required parameter', - missingProperty: 'Missing required property', - propertyNotAllowed: 'Includes property that is not allowed', - badlyFormattedParameter: 'Badly formatted parameter', - duplicateId: 'Duplicate id', - notFound: 'Document not found', - invalidQueryStringParameter: 'Invalid query string parameter' -}; -exports.errors = errors; +const { PropertyNotAllowedError, InvalidTypeError } = require('../exceptions'); -exports.retrieveAll = function(options, callback) { - // Build the query - const query = {}; - if (!options.includeRevoked) { - query['stix.revoked'] = { $in: [null, false] }; - } - if (!options.includeDeprecated) { - query['stix.x_mitre_deprecated'] = { $in: [null, false] }; - } - if (typeof options.state !== 'undefined') { - if (Array.isArray(options.state)) { - query['workspace.workflow.state'] = { $in: options.state }; - } - else { - query['workspace.workflow.state'] = options.state; - } - } - if (typeof options.domain !== 'undefined') { - if (Array.isArray(options.domain)) { - query['stix.x_mitre_domains'] = { $in: options.domain }; - } - else { - query['stix.x_mitre_domains'] = options.domain; - } - } - if (typeof options.platform !== 'undefined') { - if (Array.isArray(options.platform)) { - query['stix.x_mitre_platforms'] = { $in: options.platform }; - } - else { - query['stix.x_mitre_platforms'] = options.platform; - } - } - if (typeof options.lastUpdatedBy !== 'undefined') { - query['workspace.workflow.created_by_user_account'] = lastUpdatedByQueryHelper(options.lastUpdatedBy); - } +const BaseService = require('./_base.service'); +const softwareRepository = require('../repository/software-repository'); - // Build the aggregation - // - Group the documents by stix.id, sorted by stix.modified - // - Use the first document in each group (according to the value of stix.modified) - // - Then apply query, skip and limit options - const aggregation = [ - { $sort: { 'stix.id': 1, 'stix.modified': -1 } }, - { $group: { _id: '$stix.id', document: { $first: '$$ROOT' }}}, - { $replaceRoot: { newRoot: '$document' }}, - { $sort: { 'stix.id': 1 }}, - { $match: query } - ]; - - if (typeof options.search !== 'undefined') { - options.search = regexValidator.sanitizeRegex(options.search); - const match = { $match: { $or: [ - { 'stix.name': { '$regex': options.search, '$options': 'i' }}, - { 'stix.description': { '$regex': options.search, '$options': 'i' }}, - { 'workspace.attack_id': { '$regex': options.search, '$options': 'i' }} - ]}}; - aggregation.push(match); - } - - const facet = { - $facet: { - totalCount: [ { $count: 'totalCount' }], - documents: [ ] - } - }; - if (options.offset) { - facet.$facet.documents.push({ $skip: options.offset }); - } - else { - facet.$facet.documents.push({ $skip: 0 }); - } - if (options.limit) { - facet.$facet.documents.push({ $limit: options.limit }); - } - aggregation.push(facet); - - // Retrieve the documents - Software.aggregate(aggregation, function(err, results) { - if (err) { - return callback(err); - } - else { - identitiesService.addCreatedByAndModifiedByIdentitiesToAll(results[0].documents) - .then(function() { - if (options.includePagination) { - let derivedTotalCount = 0; - if (results[0].totalCount.length > 0) { - derivedTotalCount = results[0].totalCount[0].totalCount; - } - const returnValue = { - pagination: { - total: derivedTotalCount, - offset: options.offset, - limit: options.limit - }, - data: results[0].documents - }; - return callback(null, returnValue); - } - else { - return callback(null, results[0].documents); - } - }); - } - }); -}; +class SoftwareService extends BaseService { + async create(data, options, callback) { + // This function handles two use cases: + // 1. This is a completely new object. Create a new object and generate the stix.id if not already + // provided. Set both stix.created_by_ref and stix.x_mitre_modified_by_ref to the organization identity. + // 2. This is a new version of an existing object. Create a new object with the specified id. + // Set stix.x_mitre_modified_by_ref to the organization identity. -exports.retrieveById = function(stixId, options, callback) { - // versions=all Retrieve all software with the stixId - // versions=latest Retrieve the software with the latest modified date for this stixId - - if (!stixId) { - const error = new Error(errors.missingParameter); - error.parameterName = 'stixId'; - return callback(error); - } - - if (options.versions === 'all') { - Software.find({'stix.id': stixId}) - .lean() - .exec(function (err, software) { - if (err) { - if (err.name === 'CastError') { - const error = new Error(errors.badlyFormattedParameter); - error.parameterName = 'stixId'; - return callback(error); - } else { - return callback(err); - } - } else { - identitiesService.addCreatedByAndModifiedByIdentitiesToAll(software) - .then(() => callback(null, software)); - } - }); - } - else if (options.versions === 'latest') { - Software.findOne({ 'stix.id': stixId }) - .sort('-stix.modified') - .lean() - .exec(function(err, software) { - if (err) { - if (err.name === 'CastError') { - const error = new Error(errors.badlyFormattedParameter); - error.parameterName = 'stixId'; - return callback(error); - } - else { - return callback(err); - } - } - else { - // Note: document is null if not found - if (software) { - identitiesService.addCreatedByAndModifiedByIdentities(software) - .then(() => callback(null, [ software ])); - } - else { - return callback(null, []); - } - } - }); - } - else { - const error = new Error(errors.invalidQueryStringParameter); - error.parameterName = 'versions'; - return callback(error); - } -}; - -exports.retrieveVersionById = function(stixId, modified, callback) { - // Retrieve the versions of the software with the matching stixId and modified date - - if (!stixId) { - const error = new Error(errors.missingParameter); - error.parameterName = 'stixId'; - return callback(error); - } - - if (!modified) { - const error = new Error(errors.missingParameter); - error.parameterName = 'modified'; - return callback(error); - } - - Software.findOne({ 'stix.id': stixId, 'stix.modified': modified }, function(err, software) { - if (err) { - if (err.name === 'CastError') { - const error = new Error(errors.badlyFormattedParameter); - error.parameterName = 'stixId'; - return callback(error); - } - else { - return callback(err); + // is_family defaults to true for malware, not allowed for tools + try { + if (data?.stix?.type !== 'malware' && data?.stix?.type !== 'tool') { + throw new InvalidTypeError(); } - } - else { - // Note: document is null if not found - if (software) { - identitiesService.addCreatedByAndModifiedByIdentities(software) - .then(() => callback(null, software)); + + if (data.stix && data.stix.type === 'malware' && typeof data.stix.is_family !== 'boolean') { + data.stix.is_family = true; } - else { - return callback(); + else if (data.stix && data.stix.type === 'tool' && data.stix.is_family !== undefined) { + throw new PropertyNotAllowedError(); } - } - }); -}; - -exports.createIsAsync = true; -exports.create = async function(data, options) { - // This function handles two use cases: - // 1. This is a completely new object. Create a new object and generate the stix.id if not already - // provided. Set both stix.created_by_ref and stix.x_mitre_modified_by_ref to the organization identity. - // 2. This is a new version of an existing object. Create a new object with the specified id. - // Set stix.x_mitre_modified_by_ref to the organization identity. - - // is_family defaults to true for malware, not allowed for tools - if (data.stix && data.stix.type === 'malware' && typeof data.stix.is_family !== 'boolean') { - data.stix.is_family = true; - } - else if (data.stix && data.stix.type === 'tool' && data.stix.is_family !== undefined) { - const err = new Error(errors.propertyNotAllowed); - err.propertyName = 'stix.is_family'; - throw err; - } - // Create the document - const software = new Software(data); + options = options || {}; + if (!options.import) { + // Set the ATT&CK Spec Version + data.stix.x_mitre_attack_spec_version = data.stix.x_mitre_attack_spec_version ?? config.app.attackSpecVersion; - options = options || {}; - if (!options.import) { - // Set the ATT&CK Spec Version - software.stix.x_mitre_attack_spec_version = software.stix.x_mitre_attack_spec_version ?? config.app.attackSpecVersion; + // Record the user account that created the object + if (options.userAccountId) { + data.workspace.workflow.created_by_user_account = options.userAccountId; + } - // Record the user account that created the object - if (options.userAccountId) { - software.workspace.workflow.created_by_user_account = options.userAccountId; - } + // Set the default marking definitions + await attackObjectsService.setDefaultMarkingDefinitions(data); - // Set the default marking definitions - await attackObjectsService.setDefaultMarkingDefinitions(software); + // Get the organization identity + const organizationIdentityRef = await systemConfigurationService.retrieveOrganizationIdentityRef(); - // Get the organization identity - const organizationIdentityRef = await systemConfigurationService.retrieveOrganizationIdentityRef(); + // Check for an existing object + let existingObject; + if (data.stix.id) { + existingObject = await this.repository.retrieveOneById(data.stix.id); + } - // Check for an existing object - let existingObject; - if (software.stix.id) { - existingObject = await Software.findOne({ 'stix.id': software.stix.id }); - } + if (existingObject) { + // New version of an existing object + // Only set the x_mitre_modified_by_ref property + data.stix.x_mitre_modified_by_ref = organizationIdentityRef; + } + else { + // New object + // Assign a new STIX id if not already provided + if (!data.stix.id) { + // const stixIdPrefix = getStixIdPrefixFromModel(this.model.modelName, data.stix.type); + data.stix.id = `${data.stix.type}--${uuid.v4()}`; + } - if (existingObject) { - // New version of an existing object - // Only set the x_mitre_modified_by_ref property - software.stix.x_mitre_modified_by_ref = organizationIdentityRef; - } - else { - // New object - // Assign a new STIX id if not already provided - if (software.stix.type === 'tool') { - software.stix.id = software.stix.id || `tool--${uuid.v4()}`; + // Set the created_by_ref and x_mitre_modified_by_ref properties + data.stix.created_by_ref = organizationIdentityRef; + data.stix.x_mitre_modified_by_ref = organizationIdentityRef; + } } - else { - software.stix.id = software.stix.id || `malware--${uuid.v4()}`; + const res = await this.repository.save(data); + if (callback) { + return callback(null, res); } - - // Set the created_by_ref and x_mitre_modified_by_ref properties - software.stix.created_by_ref = organizationIdentityRef; - software.stix.x_mitre_modified_by_ref = organizationIdentityRef; - } - } - - // Save the document in the database - try { - const savedSoftware = await software.save(); - return savedSoftware; - } - catch(err) { - if (err.name === 'MongoServerError' && err.code === 11000) { - // 11000 = Duplicate index - const error = new Error(errors.duplicateId); - throw error; - } - else { - throw err; - } - } -}; - -exports.updateFull = function(stixId, stixModified, data, callback) { - if (!stixId) { - const error = new Error(errors.missingParameter); - error.parameterName = 'stixId'; - return callback(error); - } - - if (!stixModified) { - const error = new Error(errors.missingParameter); - error.parameterName = 'modified'; - return callback(error); - } - - Software.findOne({ 'stix.id': stixId, 'stix.modified': stixModified }, function(err, document) { - if (err) { - if (err.name === 'CastError') { - var error = new Error(errors.badlyFormattedParameter); - error.parameterName = 'stixId'; - return callback(error); - } - else { + return res; + } catch (err) { + if (callback) { return callback(err); } + throw err; } - else if (!document) { - // document not found - return callback(null); - } - else { - // Copy data to found document and save - Object.assign(document, data); - document.save(function(err, savedDocument) { - if (err) { - if (err.name === 'MongoServerError' && err.code === 11000) { - // 11000 = Duplicate index - var error = new Error(errors.duplicateId); - return callback(error); - } - else { - return callback(err); - } - } - else { - return callback(null, savedDocument); - } - }); - } - }); -}; - -exports.deleteVersionById = function (stixId, stixModified, callback) { - if (!stixId) { - const error = new Error(errors.missingParameter); - error.parameterName = 'stixId'; - return callback(error); - } - - if (!stixModified) { - const error = new Error(errors.missingParameter); - error.parameterName = 'modified'; - return callback(error); - } - - Software.findOneAndRemove({ 'stix.id': stixId, 'stix.modified': stixModified }, function (err, software) { - if (err) { - return callback(err); - } else { - //Note: software is null if not found - return callback(null, software); - } - }); -}; - -exports.deleteById = function (stixId, callback) { - if (!stixId) { - const error = new Error(errors.missingParameter); - error.parameterName = 'stixId'; - return callback(error); } +} - Software.deleteMany({ 'stix.id': stixId }, function (err, software) { - if (err) { - return callback(err); - } else { - //Note: software is null if not found - return callback(null, software); - } - }); -}; +module.exports = new SoftwareService(null, softwareRepository); \ No newline at end of file diff --git a/app/tests/api/software/software.spec.js b/app/tests/api/software/software.spec.js index 908ba20d..16f1f77d 100644 --- a/app/tests/api/software/software.spec.js +++ b/app/tests/api/software/software.spec.js @@ -78,245 +78,172 @@ describe('Software API', function () { passportCookie = await login.loginAnonymous(app); }); - it('GET /api/software returns an empty array of software', function (done) { - request(app) + it('GET /api/software returns an empty array of software', async function () { + const res = await request(app) .get('/api/software') .set('Accept', 'application/json') .set('Cookie', `${ login.passportCookieName }=${ passportCookie.value }`) .expect(200) - .expect('Content-Type', /json/) - .end(function(err, res) { - if (err) { - done(err); - } - else { - // We expect to get an empty array - const software = res.body; - expect(software).toBeDefined(); - expect(Array.isArray(software)).toBe(true); - expect(software.length).toBe(0); - done(); - } - }); + .expect('Content-Type', /json/); + + // We expect to get an empty array + const software = res.body; + expect(software).toBeDefined(); + expect(Array.isArray(software)).toBe(true); + expect(software.length).toBe(0); }); - it('POST /api/software does not create an empty software', function (done) { + it('POST /api/software does not create an empty software', async function () { const body = { }; - request(app) + await request(app) .post('/api/software') .send(body) .set('Accept', 'application/json') .set('Cookie', `${ login.passportCookieName }=${ passportCookie.value }`) - .expect(400) - .end(function(err, res) { - if (err) { - done(err); - } - else { - done(); - } - }); + .expect(400); }); - it('POST /api/software does not create a software missing the name property', function (done) { + it('POST /api/software does not create a software missing the name property', async function () { const timestamp = new Date().toISOString(); invalidMissingName.stix.created = timestamp; invalidMissingName.stix.modified = timestamp; const body = invalidMissingName; - request(app) + await request(app) .post('/api/software') .send(body) .set('Accept', 'application/json') .set('Cookie', `${ login.passportCookieName }=${ passportCookie.value }`) - .expect(400) - .end(function(err, res) { - if (err) { - done(err); - } - else { - done(); - } - }); + .expect(400); }); - it('POST /api/software does not create a software (tool) with the is_family property', function (done) { + it('POST /api/software does not create a software (tool) with the is_family property', async function () { const timestamp = new Date().toISOString(); invalidToolIncludesIsFamily.stix.created = timestamp; invalidToolIncludesIsFamily.stix.modified = timestamp; const body = invalidToolIncludesIsFamily; - request(app) + await request(app) .post('/api/software') .send(body) .set('Accept', 'application/json') .set('Cookie', `${ login.passportCookieName }=${ passportCookie.value }`) - .expect(400) - .end(function(err, res) { - if (err) { - done(err); - } - else { - done(); - } - }); + .expect(400); }); let software1; - it('POST /api/software creates a software', function (done) { + it('POST /api/software creates a software', async function () { const timestamp = new Date().toISOString(); initialObjectData.stix.created = timestamp; initialObjectData.stix.modified = timestamp; const body = initialObjectData; - request(app) + const res = await request(app) .post('/api/software') .send(body) .set('Accept', 'application/json') .set('Cookie', `${ login.passportCookieName }=${ passportCookie.value }`) .expect(201) - .expect('Content-Type', /json/) - .end(function(err, res) { - if (err) { - done(err); - } - else { - // We expect to get the created software - software1 = res.body; - expect(software1).toBeDefined(); - expect(software1.stix).toBeDefined(); - expect(software1.stix.id).toBeDefined(); - expect(software1.stix.created).toBeDefined(); - expect(software1.stix.modified).toBeDefined(); - expect(software1.stix.x_mitre_attack_spec_version).toBe(config.app.attackSpecVersion); - - done(); - } - }); + .expect('Content-Type', /json/); + + // We expect to get the created software + software1 = res.body; + expect(software1).toBeDefined(); + expect(software1.stix).toBeDefined(); + expect(software1.stix.id).toBeDefined(); + expect(software1.stix.created).toBeDefined(); + expect(software1.stix.modified).toBeDefined(); + expect(software1.stix.x_mitre_attack_spec_version).toBe(config.app.attackSpecVersion); + }); - it('GET /api/software returns the added software', function (done) { - request(app) + it('GET /api/software returns the added software', async function () { + const res = await request(app) .get('/api/software') .set('Accept', 'application/json') .set('Cookie', `${ login.passportCookieName }=${ passportCookie.value }`) .expect(200) - .expect('Content-Type', /json/) - .end(function(err, res) { - if (err) { - done(err); - } - else { - // We expect to get one software in an array - const software = res.body; - expect(software).toBeDefined(); - expect(Array.isArray(software)).toBe(true); - expect(software.length).toBe(1); - done(); - } - }); + .expect('Content-Type', /json/); + + // We expect to get one software in an array + const software = res.body; + expect(software).toBeDefined(); + expect(Array.isArray(software)).toBe(true); + expect(software.length).toBe(1); }); - it('GET /api/software/:id should not return a software when the id cannot be found', function (done) { - request(app) + it('GET /api/software/:id should not return a software when the id cannot be found', async function () { + await request(app) .get('/api/software/not-an-id') .set('Accept', 'application/json') .set('Cookie', `${ login.passportCookieName }=${ passportCookie.value }`) - .expect(404) - .end(function (err, res) { - if (err) { - done(err); - } else { - done(); - } - }); + .expect(404); }); - it('GET /api/software/:id returns the added software', function (done) { - request(app) + it('GET /api/software/:id returns the added software', async function () { + const res = await request(app) .get('/api/software/' + software1.stix.id) .set('Accept', 'application/json') .set('Cookie', `${ login.passportCookieName }=${ passportCookie.value }`) .expect(200) - .expect('Content-Type', /json/) - .end(function(err, res) { - if (err) { - done(err); - } - else { - // We expect to get one software in an array - const softwareObjects = res.body; - expect(softwareObjects).toBeDefined(); - expect(Array.isArray(softwareObjects)).toBe(true); - expect(softwareObjects.length).toBe(1); - - const software= softwareObjects[0]; - expect(software).toBeDefined(); - expect(software.stix).toBeDefined(); - expect(software.stix.id).toBe(software1.stix.id); - expect(software.stix.type).toBe(software1.stix.type); - expect(software.stix.name).toBe(software1.stix.name); - expect(software.stix.description).toBe(software1.stix.description); - expect(software.stix.is_family).toBe(software1.stix.is_family); - expect(software.stix.spec_version).toBe(software1.stix.spec_version); - expect(software.stix.object_marking_refs).toEqual(expect.arrayContaining(software1.stix.object_marking_refs)); - expect(software.stix.created_by_ref).toBe(software1.stix.created_by_ref); - expect(software.stix.x_mitre_version).toBe(software1.stix.x_mitre_version); - expect(software.stix.x_mitre_aliases).toEqual(expect.arrayContaining(software1.stix.x_mitre_aliases)); - expect(software.stix.x_mitre_platforms).toEqual(expect.arrayContaining(software1.stix.x_mitre_platforms)); - expect(software.stix.x_mitre_contributors).toEqual(expect.arrayContaining(software1.stix.x_mitre_contributors)); - expect(software.stix.x_mitre_attack_spec_version).toBe(software1.stix.x_mitre_attack_spec_version); - - done(); - } - }); + .expect('Content-Type', /json/); + + // We expect to get one software in an array + const softwareObjects = res.body; + expect(softwareObjects).toBeDefined(); + expect(Array.isArray(softwareObjects)).toBe(true); + expect(softwareObjects.length).toBe(1); + + const software= softwareObjects[0]; + expect(software).toBeDefined(); + expect(software.stix).toBeDefined(); + expect(software.stix.id).toBe(software1.stix.id); + expect(software.stix.type).toBe(software1.stix.type); + expect(software.stix.name).toBe(software1.stix.name); + expect(software.stix.description).toBe(software1.stix.description); + expect(software.stix.is_family).toBe(software1.stix.is_family); + expect(software.stix.spec_version).toBe(software1.stix.spec_version); + expect(software.stix.object_marking_refs).toEqual(expect.arrayContaining(software1.stix.object_marking_refs)); + expect(software.stix.created_by_ref).toBe(software1.stix.created_by_ref); + expect(software.stix.x_mitre_version).toBe(software1.stix.x_mitre_version); + expect(software.stix.x_mitre_aliases).toEqual(expect.arrayContaining(software1.stix.x_mitre_aliases)); + expect(software.stix.x_mitre_platforms).toEqual(expect.arrayContaining(software1.stix.x_mitre_platforms)); + expect(software.stix.x_mitre_contributors).toEqual(expect.arrayContaining(software1.stix.x_mitre_contributors)); + expect(software.stix.x_mitre_attack_spec_version).toBe(software1.stix.x_mitre_attack_spec_version); + }); - it('PUT /api/software updates a software', function (done) { + it('PUT /api/software updates a software', async function () { const originalModified = software1.stix.modified; const timestamp = new Date().toISOString(); software1.stix.modified = timestamp; software1.stix.description = 'This is an updated software.' const body = software1; - request(app) + const res = await request(app) .put('/api/software/' + software1.stix.id + '/modified/' + originalModified) .send(body) .set('Accept', 'application/json') .set('Cookie', `${ login.passportCookieName }=${ passportCookie.value }`) .expect(200) - .expect('Content-Type', /json/) - .end(function(err, res) { - if (err) { - done(err); - } - else { - // We expect to get the updated software - const software = res.body; - expect(software).toBeDefined(); - expect(software.stix.id).toBe(software1.stix.id); - expect(software.stix.modified).toBe(software1.stix.modified); - done(); - } - }); + .expect('Content-Type', /json/); + + // We expect to get the updated software + const software = res.body; + expect(software).toBeDefined(); + expect(software.stix.id).toBe(software1.stix.id); + expect(software.stix.modified).toBe(software1.stix.modified); + }); - it('POST /api/software does not create a software with the same id and modified date', function (done) { + it('POST /api/software does not create a software with the same id and modified date', async function () { const body = software1; - request(app) + await request(app) .post('/api/software') .send(body) .set('Accept', 'application/json') .set('Cookie', `${ login.passportCookieName }=${ passportCookie.value }`) - .expect(409) - .end(function(err, res) { - if (err) { - done(err); - } - else { - done(); - } - }); + .expect(409); }); let software2; - it('POST /api/software should create a new version of a software with a duplicate stix.id but different stix.modified date', function (done) { + it('POST /api/software should create a new version of a software with a duplicate stix.id but different stix.modified date', async function () { software2 = _.cloneDeep(software1); software2._id = undefined; software2.__t = undefined; @@ -324,121 +251,90 @@ describe('Software API', function () { const timestamp = new Date().toISOString(); software2.stix.modified = timestamp; const body = software2; - request(app) + const res = await request(app) .post('/api/software') .send(body) .set('Accept', 'application/json') .set('Cookie', `${ login.passportCookieName }=${ passportCookie.value }`) .expect(201) - .expect('Content-Type', /json/) - .end(function(err, res) { - if (err) { - done(err); - } - else { - // We expect to get the created software - const software = res.body; - expect(software).toBeDefined(); - done(); - } - }); + .expect('Content-Type', /json/); + + // We expect to get the created software + const software = res.body; + expect(software).toBeDefined(); + }); - it('GET /api/software returns the latest added software', function (done) { - request(app) + it('GET /api/software returns the latest added software', async function () { + const res = await request(app) .get('/api/software/' + software2.stix.id) .set('Accept', 'application/json') .set('Cookie', `${ login.passportCookieName }=${ passportCookie.value }`) .expect(200) - .expect('Content-Type', /json/) - .end(function(err, res) { - if (err) { - done(err); - } - else { - // We expect to get one software in an array - const software = res.body; - expect(software).toBeDefined(); - expect(Array.isArray(software)).toBe(true); - expect(software.length).toBe(1); - const softwre = software[0]; - expect(softwre.stix.id).toBe(software2.stix.id); - expect(softwre.stix.modified).toBe(software2.stix.modified); - done(); - } - }); + .expect('Content-Type', /json/); + + // We expect to get one software in an array + const software = res.body; + expect(software).toBeDefined(); + expect(Array.isArray(software)).toBe(true); + expect(software.length).toBe(1); + const softwre = software[0]; + expect(softwre.stix.id).toBe(software2.stix.id); + expect(softwre.stix.modified).toBe(software2.stix.modified); }); - it('GET /api/software returns all added software', function (done) { - request(app) + it('GET /api/software returns all added software', async function () { + const res = await request(app) .get('/api/software/' + software1.stix.id + '?versions=all') .set('Accept', 'application/json') .set('Cookie', `${ login.passportCookieName }=${ passportCookie.value }`) .expect(200) - .expect('Content-Type', /json/) - .end(function(err, res) { - if (err) { - done(err); - } - else { - // We expect to get two software in an array - const software = res.body; - expect(software).toBeDefined(); - expect(Array.isArray(software)).toBe(true); - expect(software.length).toBe(2); - done(); - } - }); + .expect('Content-Type', /json/); + + // We expect to get two software in an array + const software = res.body; + expect(software).toBeDefined(); + expect(Array.isArray(software)).toBe(true); + expect(software.length).toBe(2); + }); - it('GET /api/software/:id/modified/:modified returns the first added software', function (done) { - request(app) + it('GET /api/software/:id/modified/:modified returns the first added software', async function () { + const res = await request(app) .get('/api/software/' + software1.stix.id + '/modified/' + software1.stix.modified) .set('Accept', 'application/json') .set('Cookie', `${ login.passportCookieName }=${ passportCookie.value }`) .expect(200) - .expect('Content-Type', /json/) - .end(function(err, res) { - if (err) { - done(err); - } - else { - // We expect to get one software in an array - const software = res.body; - expect(software).toBeDefined(); - expect(software.stix).toBeDefined(); - expect(software.stix.id).toBe(software1.stix.id); - expect(software.stix.modified).toBe(software1.stix.modified); - done(); - } - }); + .expect('Content-Type', /json/); + + // We expect to get one software in an array + const software = res.body; + expect(software).toBeDefined(); + expect(software.stix).toBeDefined(); + expect(software.stix.id).toBe(software1.stix.id); + expect(software.stix.modified).toBe(software1.stix.modified); + }); - it('GET /api/software/:id/modified/:modified returns the second added software', function (done) { - request(app) + it('GET /api/software/:id/modified/:modified returns the second added software', async function () { + const res = await request(app) .get('/api/software/' + software2.stix.id + '/modified/' + software2.stix.modified) .set('Accept', 'application/json') .set('Cookie', `${ login.passportCookieName }=${ passportCookie.value }`) .expect(200) - .expect('Content-Type', /json/) - .end(function(err, res) { - if (err) { - done(err); - } - else { - // We expect to get one software in an array - const software = res.body; - expect(software).toBeDefined(); - expect(software.stix).toBeDefined(); - expect(software.stix.id).toBe(software2.stix.id); - expect(software.stix.modified).toBe(software2.stix.modified); - done(); - } - }); + .expect('Content-Type', /json/); + + // We expect to get one software in an array + const software = res.body; + expect(software).toBeDefined(); + expect(software.stix).toBeDefined(); + expect(software.stix.id).toBe(software2.stix.id); + expect(software.stix.modified).toBe(software2.stix.modified); + }); let software3; - it('POST /api/software should create a new version of a software with a duplicate stix.id but different stix.modified date', function (done) { + it('POST /api/software should create a new version of a software with a duplicate stix.id but different stix.modified date', async function () { software3 = _.cloneDeep(software1); software3._id = undefined; software3.__t = undefined; @@ -446,122 +342,80 @@ describe('Software API', function () { const timestamp = new Date().toISOString(); software3.stix.modified = timestamp; const body = software3; - request(app) + const res = await request(app) .post('/api/software') .send(body) .set('Accept', 'application/json') .set('Cookie', `${ login.passportCookieName }=${ passportCookie.value }`) .expect(201) - .expect('Content-Type', /json/) - .end(function(err, res) { - if (err) { - done(err); - } - else { - // We expect to get the created software - const software = res.body; - expect(software).toBeDefined(); - done(); - } - }); + .expect('Content-Type', /json/); + + // We expect to get the created software + const software = res.body; + expect(software).toBeDefined(); + }); - it('DELETE /api/software/:id should not delete a software when the id cannot be found', function (done) { - request(app) + it('DELETE /api/software/:id should not delete a software when the id cannot be found', async function () { + await request(app) .delete('/api/software/not-an-id') .set('Cookie', `${ login.passportCookieName }=${ passportCookie.value }`) - .expect(404) - .end(function(err, res) { - if (err) { - done(err); - } - else { - done(); - } - }); + .expect(404); }); - it('DELETE /api/software/:id/modified/:modified deletes a software', function (done) { - request(app) + it('DELETE /api/software/:id/modified/:modified deletes a software', async function () { + await request(app) .delete('/api/software/' + software1.stix.id + '/modified/' + software1.stix.modified) .set('Cookie', `${ login.passportCookieName }=${ passportCookie.value }`) - .expect(204) - .end(function(err, res) { - if (err) { - done(err); - } - else { - done(); - } - }); + .expect(204); }); - it('DELETE /api/software/:id should delete all the software with the same stix id', function (done) { - request(app) + it('DELETE /api/software/:id should delete all the software with the same stix id', async function () { + await request(app) .delete('/api/software/' + software2.stix.id) .set('Cookie', `${ login.passportCookieName }=${ passportCookie.value }`) - .expect(204) - .end(function(err, res) { - if (err) { - done(err); - } - else { - done(); - } - }); + .expect(204); }); - it('GET /api/software returns an empty array of software', function (done) { - request(app) + it('GET /api/software returns an empty array of software', async function () { + const res = await request(app) .get('/api/software') .set('Accept', 'application/json') .set('Cookie', `${ login.passportCookieName }=${ passportCookie.value }`) .expect(200) - .expect('Content-Type', /json/) - .end(function(err, res) { - if (err) { - done(err); - } - else { - // We expect to get an empty array - const software = res.body; - expect(software).toBeDefined(); - expect(Array.isArray(software)).toBe(true); - expect(software.length).toBe(0); - done(); - } - }); + .expect('Content-Type', /json/); + + // We expect to get an empty array + const software = res.body; + expect(software).toBeDefined(); + expect(Array.isArray(software)).toBe(true); + expect(software.length).toBe(0); + }); - it('POST /api/software creates a software (malware) missing the is_family property using a default value', function (done) { + it('POST /api/software creates a software (malware) missing the is_family property using a default value', async function () { const timestamp = new Date().toISOString(); invalidMalwareMissingIsFamily.stix.created = timestamp; invalidMalwareMissingIsFamily.stix.modified = timestamp; const body = invalidMalwareMissingIsFamily; - request(app) + const res = await request(app) .post('/api/software') .send(body) .set('Accept', 'application/json') .set('Cookie', `${ login.passportCookieName }=${ passportCookie.value }`) .expect(201) - .expect('Content-Type', /json/) - .end(function(err, res) { - if (err) { - done(err); - } - else { - // We expect to get the created software - const malware = res.body; - expect(malware).toBeDefined(); - expect(malware.stix).toBeDefined(); - expect(malware.stix.id).toBeDefined(); - expect(malware.stix.created).toBeDefined(); - expect(malware.stix.modified).toBeDefined(); - expect(typeof malware.stix.is_family).toBe('boolean'); - expect(malware.stix.is_family).toBe(true); - done(); - } - }); + .expect('Content-Type', /json/); + + // We expect to get the created software + const malware = res.body; + expect(malware).toBeDefined(); + expect(malware.stix).toBeDefined(); + expect(malware.stix.id).toBeDefined(); + expect(malware.stix.created).toBeDefined(); + expect(malware.stix.modified).toBeDefined(); + expect(typeof malware.stix.is_family).toBe('boolean'); + expect(malware.stix.is_family).toBe(true); + }); after(async function() {