text:
const express = require('express')
const app = express()
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-http'))

// Body Parser Middleware
app.use(express.json()) // Allows us to handle raw JSON data
app.use(express.urlencoded({ extended: false })) // Allows us to handle url encoded data
const middleware = require('../../../src/middleware/middleware')
app.use(middleware.createCtxAndReqUUID)

const nonExistentCveId = 'CVE-2020-1425'
const cveIdPublished5 = 'CVE-2017-4024'
const cveIdReserved = 'CVE-2017-5835'
const url = process.env.NODE_ENV === 'staging' ? 'https://test.cve.org/' : 'https://cve.org/' // Used in submitCna response messages
const cveCnaContainerFail = require('../../schemas/cna-container/cna-container_fail.json')
const cveCnaContainerPass = require('../../schemas/cna-container/cna-container_pass.json')
const errors = require('../../../src/controller/cve.controller/error')
const error = new errors.CveControllerError()

const cveFixtures = require('./mockObjects.cve')
const cveController = require('../../../src/controller/cve.controller/cve.controller')
const cveParams = require('../../../src/controller/cve.controller/cve.middleware')

class MyOrg {
  async getOrgUUID (shortName) {
    if (shortName === cveFixtures.regularOrg.short_name) {
      return cveFixtures.regularOrg.UUID
    } else if (shortName === cveFixtures.secretariatOrg.short_name) {
      return cveFixtures.secretariatOrg.UUID
    }
    return null
  }

  async isSecretariat (org) {
    if (org === cveFixtures.secretariatHeader['CVE-API-ORG']) {
      return true
    }
    return null
  }

  async findOneByUUID () {
    return cveFixtures.secretariatOrg
  }
}

class MyUser {
  async getUserUUID () {
    return null
  }
}

class MyCveIdNegativeTests {
  async findOneByCveId (id) {
    if (id === cveIdPublished5) {
      const fixture = cveFixtures.cvePublished5
      fixture.owning_cna = 'random'
      return fixture
    }
    if (id === cveIdReserved) {
      const fixture = cveFixtures.cveRejected5
      fixture.reserved = new Date()
      return fixture
    }
    return null
  }

  async updateByCveId () {
    return null
  }
}

class MyCveNegativeTests {
  async findOneByCveId (id) {
    if (id === cveIdPublished5) {
      return true
    }
    return null
  }

  async updateByCveId () {
    return null
  }
}

class MyCveIdPositiveTests {
  async findOneByCveId (id) {
    if (id === cveIdPublished5) {
      return cveFixtures.cvePublished5
    }
    if (id === cveIdReserved) {
      const cveId = Object.assign({}, cveFixtures.cveRejected5)
      cveId.owning_cna = cveFixtures.regularOrg.UUID
      return cveId
    }
    return cveFixtures.cveRejected5
  }

  async updateByCveId (id, cveId) {
    return null
  }
}

class MyCvePositiveTests {
  async findOneByCveId () {
    return null
  }

  async updateByCveId () {
    return null
  }
}

app.route('/cve-cna-negative-tests/:id')
  .post((req, res, next) => {
    const factory = {
      getCveIdRepository: () => { return new MyCveIdNegativeTests() },
      getCveRepository: () => { return new MyCveNegativeTests() },
      getOrgRepository: () => { return new MyOrg() },
      getUserRepository: () => { return new MyUser() }
    }
    req.ctx.repositories = factory
    next()
  }, cveParams.parsePostParams, cveController.CVE_SUBMIT_CNA)

app.route('/cve-cna-positive-tests/:id')
  .post((req, res, next) => {
    const factory = {
      getCveIdRepository: () => { return new MyCveIdPositiveTests() },
      getCveRepository: () => { return new MyCvePositiveTests() },
      getOrgRepository: () => { return new MyOrg() },
      getUserRepository: () => { return new MyUser() }
    }
    req.ctx.repositories = factory
    next()
  }, cveParams.parsePostParams, cveController.CVE_SUBMIT_CNA)

describe('Testing the POST /cve/:id/cna endpoint in Cve Controller', () => {
  context('Negative Tests', () => {
    it('should return 400 when cveId does not exist', (done) => {
      chai.request(app)
        .post(`/cve-cna-negative-tests/${nonExistentCveId}`)
        .set(cveFixtures.secretariatHeader)
        .send(cveCnaContainerFail)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(400)
          expect(res).to.have.property('body').and.to.be.a('object')
          const errObj = error.cveDne()
          expect(res.body.error).to.equal(errObj.error)
          expect(res.body.message).to.equal(errObj.message)
          done()
        })
    })

    it('should return 403 when cveId does not belong to cveId owning org', (done) => {
      const headers = Object.assign({}, cveFixtures.secretariatHeader)
      headers['CVE-API-ORG'] = 'cisco'
      chai.request(app)
        .post(`/cve-cna-negative-tests/${cveIdPublished5}`)
        .set(headers)
        .send(cveCnaContainerFail)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(403)
          expect(res).to.have.property('body').and.to.be.a('object')
          const errObj = error.owningOrgDoesNotMatch()
          expect(res.body.error).to.equal(errObj.error)
          expect(res.body.message).to.equal(errObj.message)
          done()
        })
    })

    it('should return 403 when cve record does exist', (done) => {
      chai.request(app)
        .post(`/cve-cna-negative-tests/${cveIdPublished5}`)
        .set(cveFixtures.secretariatHeader)
        .send(cveCnaContainerFail)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(403)
          expect(res).to.have.property('body').and.to.be.a('object')
          const errObj = error.cveRecordExists()
          expect(res.body.error).to.equal(errObj.error)
          expect(res.body.message).to.equal(errObj.message)
          done()
        })
    })

    it('should return 400 when cve record is not valid', (done) => {
      chai.request(app)
        .post(`/cve-cna-negative-tests/${cveIdReserved}`)
        .set(cveFixtures.secretariatHeader)
        .send(cveCnaContainerFail)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(400)
          expect(res).to.have.property('body').and.to.be.a('object')
          const errObj = error.invalidCnaContainerJsonSchema()
          expect(res.body.error).to.equal(errObj.error)
          expect(res.body.message).to.equal(errObj.message)
          done()
        })
    })
  })

  context('Positive Tests', () => {
    it('Post cna container as secretariat', (done) => {
      chai.request(app)
        .post(`/cve-cna-positive-tests/${cveIdReserved}`)
        .set(cveFixtures.secretariatHeader)
        .send(cveCnaContainerPass)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(200)
          expect(res).to.have.property('body').and.to.be.a('object')
          expect(res.body.message).to.equal(`${cveIdReserved} record was successfully created. This submission should appear on ${url} within 15 minutes.`)
          done()
        })
    })

    it('Post cna container as user', (done) => {
      const headers = Object.assign({}, cveFixtures.secretariatHeader)
      headers['CVE-API-ORG'] = cveFixtures.regularOrg.short_name
      headers['CVE-API-USER'] = cveFixtures.regularUser.username
      chai.request(app)
        .post(`/cve-cna-positive-tests/${cveIdReserved}`)
        .set(headers)
        .send(cveCnaContainerPass)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(200)
          expect(res).to.have.property('body').and.to.be.a('object')
          expect(res.body.message).to.equal(`${cveIdReserved} record was successfully created. This submission should appear on ${url} within 15 minutes.`)
          done()
        })
    })
  })
})


text:
const express = require('express')
const app = express()
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-http'))

// Body Parser Middleware
app.use(express.json()) // Allows us to handle raw JSON data
app.use(express.urlencoded({ extended: false })) // Allows us to handle url encoded data
const middleware = require('../../../src/middleware/middleware')
app.use(middleware.createCtxAndReqUUID)

const getConstants = require('../../../src/constants').getConstants
const nonExistentCveId = 'CVE-2020-1425'
const cveIdPublished5 = 'CVE-2017-4024'
const cveIdReserved5 = 'CVE-2017-5833'
const cveIdAvailable5 = 'CVE-2017-5834'
const cveIdRejected5 = 'CVE-2017-5835'
const cvePublishedPass5 = require('../../schemas/5.0/' + cveIdPublished5 + '_published.json')
const cveReservedPass5 = require('../../schemas/5.0/' + cveIdReserved5 + '_reserved.json')
const cveRejectedPass5 = require('../../schemas/5.0/' + cveIdRejected5 + '_rejected.json')
const errors = require('../../../src/controller/cve.controller/error')
const error = new errors.CveControllerError()

const cveFixtures = require('./mockObjects.cve')
const cveController = require('../../../src/controller/cve.controller/cve.controller')
const cveParams = require('../../../src/controller/cve.controller/cve.middleware')

class MyOrg {
  async getOrgUUID () {
    return null
  }
}

class MyUser {
  async getUserUUID () {
    return null
  }
}

class MyCveIdNegativeTests {
  async findOneByCveId (id) {
    if (id === cveIdAvailable5) {
      return cveFixtures.cveAvailable5
    } else if (id === cveIdPublished5) {
      return cveFixtures.cvePublished5
    }

    return null
  }

  async updateByCveId () {
    return null
  }
}

class MyCveNegativeTests {
  async findOneByCveId (id) {
    if (id === cveIdPublished5) {
      return cvePublishedPass5
    }

    return null
  }

  async updateByCveId () {
    return null
  }
}

class MyCveIdPositiveTests {
  constructor () {
    this.publishedDoc = cveFixtures.cvePublished5
    this.rejectedDoc = cveFixtures.cveRejected5
  }

  getCveIdPublished () {
    return this.publishedDoc
  }

  getCveIdRejected () {
    return this.rejectedDoc
  }

  async findOneByCveId (id) {
    if (id === cveIdPublished5) {
      return cveFixtures.cvePublished5
    }

    return cveFixtures.cveRejected5
  }

  async updateByCveId (id, cveId) {
    if (id === cveIdPublished5) {
      this.publishedDoc.state = cveId.state
    } else {
      this.rejectedDoc.state = cveId.state
    }

    return null
  }
}

class MyCvePositiveTests {
  async findOneByCveId () {
    return null
  }

  async updateByCveId () {
    return null
  }
}

app.route('/cve-create-record-negative-tests/:id')
  .post((req, res, next) => {
    const factory = {
      getCveRepository: () => { return new MyCveNegativeTests() },
      getCveIdRepository: () => { return new MyCveIdNegativeTests() },
      getOrgRepository: () => { return new MyOrg() },
      getUserRepository: () => { return new MyUser() }
    }
    req.ctx.repositories = factory
    next()
  }, cveParams.parsePostParams, cveController.CVE_SUBMIT)

app.route('/cve-create-record-positive-tests/:id')
  .post((req, res, next) => {
    const factory = {
      getCveRepository: () => { return new MyCvePositiveTests() },
      getCveIdRepository: () => { return new MyCveIdPositiveTests() },
      getOrgRepository: () => { return new MyOrg() },
      getUserRepository: () => { return new MyUser() }
    }
    req.ctx.repositories = factory
    next()
  }, cveParams.parsePostParams, cveController.CVE_SUBMIT)

describe('Testing the POST /cve/:id endpoint in Cve Controller', () => {
  context('Negative Tests', () => {
    it('should return 400 bad request because the cve id in the parameter does not match the cve id in the JSON body', (done) => {
      chai.request(app)
        .post(`/cve-create-record-negative-tests/${nonExistentCveId}`)
        .set(cveFixtures.secretariatHeader)
        .send(cvePublishedPass5)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(400)
          expect(res).to.have.property('body').and.to.be.a('object')
          const errObj = error.cveIdMismatch()
          expect(res.body.error).to.equal(errObj.error)
          expect(res.body.message).to.equal(errObj.message)
          done()
        })
    })

    it('should return 400 bad request because the cve record cannot be created in the RESERVED state', (done) => {
      const CONSTANTS = getConstants()

      chai.request(app)
        .post(`/cve-create-record-negative-tests/${cveIdReserved5}`)
        .set(cveFixtures.secretariatHeader)
        .send(cveReservedPass5)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(400)
          expect(res).to.have.property('body').and.to.be.a('object')
          const errObj = error.cveCreateUnsupportedState(CONSTANTS.CVE_STATES.RESERVED)
          expect(res.body.error).to.equal(errObj.error)
          expect(res.body.message).to.equal(errObj.message)
          done()
        })
    })

    it('should return 403 forbidden because the cve id does not exist', (done) => {
      const nonExistentCve = JSON.parse(JSON.stringify(cvePublishedPass5))
      nonExistentCve.cveMetadata.cveId = nonExistentCveId

      chai.request(app)
        .post(`/cve-create-record-negative-tests/${nonExistentCveId}`)
        .set(cveFixtures.secretariatHeader)
        .send(nonExistentCve)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(403)
          expect(res).to.have.property('body').and.to.be.a('object')
          const errObj = error.cveDne()
          expect(res.body.error).to.equal(errObj.error)
          expect(res.body.message).to.equal(errObj.message)
          done()
        })
    })

    it('should return 403 forbidden because the cve id has state AVAILABLE', (done) => {
      const testCve = JSON.parse(JSON.stringify(cvePublishedPass5))
      testCve.cveMetadata.cveId = cveIdAvailable5

      chai.request(app)
        .post(`/cve-create-record-negative-tests/${cveIdAvailable5}`)
        .set(cveFixtures.secretariatHeader)
        .send(testCve)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(403)
          expect(res).to.have.property('body').and.to.be.a('object')
          const errObj = error.cveDne()
          expect(res.body.error).to.equal(errObj.error)
          expect(res.body.message).to.equal(errObj.message)
          done()
        })
    })

    it('should return 400 bad request because the cve record already exist', (done) => {
      chai.request(app)
        .post(`/cve-create-record-negative-tests/${cveIdPublished5}`)
        .set(cveFixtures.secretariatHeader)
        .send(cvePublishedPass5)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(400)
          expect(res).to.have.property('body').and.to.be.a('object')
          const errObj = error.cveRecordExists()
          expect(res.body.error).to.equal(errObj.error)
          expect(res.body.message).to.equal(errObj.message)
          done()
        })
    })
  })

  context('Positive Tests', () => {
    it('State PUBLISHED: should return the cve record because the cve record was created', (done) => {
      const CONSTANTS = getConstants()
      const cveIdTestRepo = new MyCveIdPositiveTests()
      const doc = cveIdTestRepo.getCveIdPublished() // get internal state of cveId document
      expect(doc).to.have.property('cve_id').and.to.equal(cveIdPublished5)
      expect(doc).to.have.property('state').and.to.equal(CONSTANTS.CVE_STATES.RESERVED)

      chai.request(app)
        .post(`/cve-create-record-positive-tests/${cveIdPublished5}`)
        .set(cveFixtures.secretariatHeader)
        .send(cvePublishedPass5)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(200)
          expect(res).to.have.property('body').and.to.be.a('object')
          expect(res.body).to.have.property('created').and.to.be.a('object')
          expect(res.body.created).to.have.nested.property('cveMetadata.cveId').and.to.equal(cveIdPublished5)
          expect(res.body.created).to.have.nested.property('cveMetadata.state').and.to.equal(CONSTANTS.CVE_STATES.PUBLISHED)
          expect(doc).to.have.property('cve_id').and.to.equal(cveIdPublished5)
          expect(doc).to.have.property('state').and.to.equal(CONSTANTS.CVE_STATES.PUBLISHED)
          done()
        })
    })

    it('STATE REJECTED: should return the cve record because the cve record was created', (done) => {
      const CONSTANTS = getConstants()
      const cveIdTestRepo = new MyCveIdPositiveTests()
      const doc = cveIdTestRepo.getCveIdRejected() // get internal state of cveId document
      expect(doc).to.have.property('cve_id').and.to.equal(cveIdRejected5)
      expect(doc).to.have.property('state').and.to.equal(CONSTANTS.CVE_STATES.RESERVED)

      chai.request(app)
        .post(`/cve-create-record-positive-tests/${cveIdRejected5}`)
        .set(cveFixtures.secretariatHeader)
        .send(cveRejectedPass5)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(200)
          expect(res).to.have.property('body').and.to.be.a('object')
          expect(res.body).to.have.property('created').and.to.be.a('object')
          expect(res.body.created).to.have.nested.property('cveMetadata.cveId').and.to.equal(cveIdRejected5)
          expect(res.body.created).to.have.nested.property('cveMetadata.state').and.to.equal(CONSTANTS.CVE_STATES.REJECTED)
          expect(doc).to.have.property('cve_id').and.to.equal(cveIdRejected5)
          expect(doc).to.have.property('state').and.to.equal(CONSTANTS.CVE_STATES.REJECTED)
          done()
        })
    })
  })
})

repo_name: CVEProject/cve-services

repo_language: JavaScript

file_name: Dockerfile

mime_type: text/plain


text:
const chai = require('chai')
const sinon = require('sinon')
const { faker } = require('@faker-js/faker')
const _ = require('lodash')
const expect = chai.expect
const cveIdPublished5 = 'CVE-2017-4024'
const cveRecordPublished = require('../../schemas/5.0/CVE-2017-4024_published.json')
const adpContainer = require('../../schemas/5.0/adpContainerExample.json').adpContainer
const { CVE_INSERT_ADP } = require('../../../src/controller/cve.controller/cve.controller.js')
const errors = require('../../../src/controller/cve.controller/error.js')
const error = new errors.CveControllerError()

const OrgRepository = require('../../../src/repositories/orgRepository.js')
const CveIdRepository = require('../../../src/repositories/cveIdRepository.js')
const CveRepository = require('../../../src/repositories/cveRepository.js')
const UserRepository = require('../../../src/repositories/userRepository.js')

const adpUUID = faker.datatype.uuid()

const stubAdpOrg = {
  short_name: 'adpOrg',
  name: 'test_adp',
  UUID: adpUUID,
  authority: {
    active_roles: [
      'ADP'
    ]
  }
}

const stubAdpUser = {
  username: 'testAdpUser',
  org_UUID: adpUUID,
  UUID: faker.datatype.uuid()
}

const stubCveId = {
  requested_by: {
    cna: 'mitre',
    user: 'test_secretariat_0@mitre.org'
  },
  cve_id: 'CVE-2017-4024',
  cve_year: '2017',
  state: 'PUBLISHED',
  owning_cna: 'mitre',
  reserved: '2023-05-17T16:57:35.698Z'
}

describe('Testing insertAdp function', () => {
  let status, json, res, next, getOrgRepository,
    orgRepo, getCveRepository, cveRepo, getCveIdRepository,
    cveIdRepo, getUserRepository, userRepo, adpContainerCopy,
    cveCopy, req

  // Stub out functions called in insertAdp and reset them for each test
  beforeEach(() => {
    status = sinon.stub()
    json = sinon.spy()
    res = { json, status }
    next = sinon.spy()
    status.returns(res)
    orgRepo = new OrgRepository()
    getOrgRepository = sinon.stub()
    getOrgRepository.returns(orgRepo)

    userRepo = new UserRepository()
    getUserRepository = sinon.stub()
    getUserRepository.returns(userRepo)

    cveRepo = new CveRepository()
    getCveRepository = sinon.stub()
    getCveRepository.returns(cveRepo)

    cveIdRepo = new CveIdRepository()
    getCveIdRepository = sinon.stub()
    getCveIdRepository.returns(cveIdRepo)

    // Deep copy because adpContainer and cveRecordPublished are directly modified in inserAdp call
    adpContainerCopy = _.cloneDeep(adpContainer)
    cveCopy = _.cloneDeep(cveRecordPublished)

    sinon.stub(cveIdRepo, 'findOneByCveId').returns(stubCveId)
    sinon.stub(orgRepo, 'getOrgUUID').returns(stubAdpOrg.UUID)
    sinon.stub(userRepo, 'getUserUUID').returns(stubAdpUser.UUID)
    sinon.stub(cveRepo, 'findOneByCveId').returns({ cve: cveCopy })
    sinon.stub(cveRepo, 'updateByCveId').returns(true)

    req = {
      ctx: {
        org: stubAdpOrg.short_name,
        uuid: stubAdpOrg.UUID,
        params: {
          id: cveIdPublished5
        },
        repositories: {
          getOrgRepository,
          getUserRepository,
          getCveRepository,
          getCveIdRepository
        },
        body: {
          adpContainer
        }
      }
    }
  })
  context('Negative Tests', () => {
    it('Should return 400 when ADP json body is the wrong format', async () => {
      req.ctx.body = {
        adpContainerCopy // insertAdp requires the body to have adpContainer property
      }

      await CVE_INSERT_ADP(req, res, next)

      expect(status.args[0][0]).to.equal(400)
      expect(res.json.args[0][0].message).to.equal(error.badAdpFormat().message)
      expect(res.json.args[0][0].error).to.equal(error.badAdpFormat().error)
    })

    it('Should return 400 when ADP fails to validate', async () => {
      adpContainerCopy.affected = {} // affected must be an array per the schema
      req.ctx.body = {
        adpContainer: adpContainerCopy
      }

      await CVE_INSERT_ADP(req, res, next)

      expect(status.args[0][0]).to.equal(400)
      expect(res.json.args[0][0].message).to.equal(error.badAdpJson().message)
      expect(res.json.args[0][0].error).to.equal(error.badAdpJson().error)
    })
  })

  context('Positive Tests', () => {
    it('Should add an ADP container to an existing CVE record', async () => {
      const adpCount = cveCopy.containers.adp.length

      const resMessage = cveIdPublished5 + ' record had new ADP container for org ' + stubAdpOrg.short_name + ' successfully inserted'
      await CVE_INSERT_ADP(req, res, next)

      expect(status.args[0][0]).to.equal(200)
      expect(res.json.args[0][0].message).to.include(resMessage)
      expect(res.json.args[0][0].updated.containers.adp[adpCount].providerMetadata.orgId).to.equal(stubAdpOrg.UUID)
      expect(res.json.args[0][0].updated.containers.adp[adpCount].providerMetadata.shortName).to.equal(stubAdpOrg.short_name)

      // Set providerMetadata on copy, since that field is generated, then compare objects
      adpContainerCopy.providerMetadata = res.json.args[0][0].updated.containers.adp[adpCount].providerMetadata
      expect(res.json.args[0][0].updated.containers.adp[adpCount]).to.deep.equal(adpContainerCopy)
    })

    it('Should update an existing ADP container on an existing CVE record', async () => {
      const adpCopy2 = _.cloneDeep(adpContainer)
      adpCopy2.providerMetadata = {
        orgId: stubAdpOrg.UUID,
        shortName: stubAdpOrg.short_name,
        dateUpdated: faker.date.past()
      }

      // Create adpContainer to modify and add it to record
      cveCopy.containers.adp.push(adpCopy2)

      adpContainerCopy.providerMetadata = {
        orgId: stubAdpOrg.UUID,
        shortName: stubAdpOrg.short_name,
        dateUpdated: faker.date.past()
      }

      // Modify container to test for changes
      adpContainerCopy.affected[0].vendor = 'test'
      req.ctx.body = {
        adpContainer: adpContainerCopy
      }

      const adpCount = cveCopy.containers.adp.length
      const resMessage = cveIdPublished5 + ' record had replacement ADP container for org ' + stubAdpOrg.short_name + ' successfully inserted'
      await CVE_INSERT_ADP(req, res, next)

      expect(status.args[0][0]).to.equal(200)
      expect(res.json.args[0][0].message).to.include(resMessage)
      expect(res.json.args[0][0].updated.containers.adp[adpCount - 1].providerMetadata.orgId).to.equal(stubAdpOrg.UUID)
      expect(res.json.args[0][0].updated.containers.adp[adpCount - 1].providerMetadata.shortName).to.equal(stubAdpOrg.short_name)
      expect(res.json.args[0][0].updated.containers.adp[adpCount - 1].affected[0].vendor).to.equal('test')
      expect(res.json.args[0][0].updated.containers.adp[adpCount - 1]).to.not.deep.equal(adpCopy2)
    })
  })
})


text:
const express = require('express')
const app = express()
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-http'))

// Body Parser Middleware
app.use(express.json()) // Allows us to handle raw JSON data
app.use(express.urlencoded({ extended: false })) // Allows us to handle url encoded data
const middleware = require('../../../src/middleware/middleware')
const cveMiddleware = require('../../../src/controller/cve.controller/cve.middleware')
app.use(middleware.createCtxAndReqUUID)

const mwCnaFixtures = require('./cnaMustOwnId.fixtures')
const errors = require('../../../src/middleware/error')
const error = new errors.MiddlewareError()

describe('Test cna must own Id middleware', () => {
  context('Positive Tests', function () {
    it('Requester Owns CVE ID, is a CNA and is not a Secretariat', function (done) {
      class RequesterOrg {
        async findOneByShortName () {
          return mwCnaFixtures.owningOrg
        }

        async isSecretariat () {
          return false
        }
      }
      class RequesterCveId {
        async findOneByCveId () {
          return mwCnaFixtures.cveDummy1
        }
      }

      app.route('/requester-owns-cveid-and-is-a-cna')
        .post((req, res, next) => {
          const factory = {
            getOrgRepository: () => { return new RequesterOrg() },
            getCveIdRepository: () => { return new RequesterCveId() }
          }
          req.ctx.repositories = factory
          next()
        }, cveMiddleware.parsePostParams, middleware.cnaMustOwnID, (req, res) => {
          return res.status(200).json({ message: 'Success! You have reached the target endpoint.' })
        })

      chai.request(app)
        .post('/requester-owns-cveid-and-is-a-cna')
        .set(mwCnaFixtures.owningOrgHeader)
        .send()
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(200)
          expect(res).to.have.property('body').and.to.be.a('object')
          expect(res.body).to.have.property('message').and.to.be.a('string')
          expect(res.body.message).to.equal('Success! You have reached the target endpoint.')
          done()
        })
    })
  })

  context('Negative Tests', function () {
    it('Requester does not own CVE ID', function (done) {
      class RequesterOrg {
        async findOneByShortName () {
          return mwCnaFixtures.owningOrg
        }

        async isSecretariat () {
          return false
        }
      }
      class RequesterCveId {
        async findOneByCveId () {
          return mwCnaFixtures.cveDummy2
        }
      }

      app.route('/requester-does-not-own-cve-id')
        .post((req, res, next) => {
          const factory = {
            getOrgRepository: () => { return new RequesterOrg() },
            getCveIdRepository: () => { return new RequesterCveId() }
          }
          req.ctx.repositories = factory
          next()
        }, cveMiddleware.parsePostParams, middleware.cnaMustOwnID, (req, res) => {
          return res.status(200).json({ message: 'Success! You have reached the target endpoint.' })
        })

      chai.request(app)
        .post('/requester-does-not-own-cve-id')
        .set(mwCnaFixtures.owningOrg)
        .send()
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(403)
          expect(res).to.have.property('body').and.to.be.a('object')
          const errObj = error.orgDoesNotOwnId()
          expect(res.body.error).to.equal(errObj.error)
          expect(res.body.message).to.equal(errObj.message)
          done()
        })
    })

    it('Requester did not provide a CVE ID', function (done) {
      class RequesterOrg {
        async findOneByShortName () {
          return mwCnaFixtures.owningOrg
        }

        async isSecretariat () {
          return false
        }
      }
      class RequesterCveId {
        async findOneByCveId () {
          return null
        }
      }

      app.route('/requester-did-not-provide-a-cve-id')
        .post((req, res, next) => {
          const factory = {
            getOrgRepository: () => { return new RequesterOrg() },
            getCveIdRepository: () => { return new RequesterCveId() }
          }
          req.ctx.repositories = factory
          next()
        }, cveMiddleware.parsePostParams, middleware.cnaMustOwnID, (req, res) => {
          return res.status(200).json({ message: 'Success! You have reached the target endpoint.' })
        })

      chai.request(app)
        .post('/requester-did-not-provide-a-cve-id')
        .set(mwCnaFixtures.owningOrg)
        .send()
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(403)
          expect(res).to.have.property('body').and.to.be.a('object')
          const errObj = error.orgDoesNotOwnId()
          expect(res.body.error).to.equal(errObj.error)
          expect(res.body.message).to.equal(errObj.message)
          done()
        })
    })
  })
})


text:
/* eslint-disable no-unused-expressions */

const chai = require('chai')
const sinon = require('sinon')
const { faker } = require('@faker-js/faker')
const expect = chai.expect

const OrgRepository = require('../../../src/repositories/orgRepository.js')
const { onlyAdps } = require('../../../src/middleware/middleware.js')
const errors = require('../../../src/middleware/error.js')
const error = new errors.MiddlewareError()

const stubAdpOrg = {
  short_name: 'adpOrg',
  name: 'test_adp',
  UUID: faker.datatype.uuid(),
  authority: {
    active_roles: [
      'ADP'
    ]
  }
}

const stubCnaOrg = {
  short_name: 'cnaOrg',
  name: 'test_cna',
  UUID: faker.datatype.uuid(),
  authority: {
    active_roles: [
      'CNA'
    ]
  }
}

const stubSecretariat = {
  short_name: 'secOrg',
  name: 'test_sec',
  UUID: faker.datatype.uuid(),
  authority: {
    active_roles: [
      'SECRETARIAT'
    ]
  }
}

describe('Testing onlyAdps middleware', () => {
  let status, json, res, next, getOrgRepository, orgRepo
  beforeEach(() => {
    status = sinon.stub()
    json = sinon.spy()
    res = { json, status }
    next = sinon.spy()
    status.returns(res)
    orgRepo = new OrgRepository()
    getOrgRepository = sinon.stub()
    getOrgRepository.returns(orgRepo)
  })
  context('Negative Tests', () => {
    it('Should return 403 for users from orgs without the ADP role ', async () => {
      const req = {
        ctx: {
          org: stubCnaOrg.short_name,
          uuid: stubCnaOrg.UUID,
          repositories: {
            getOrgRepository
          }
        }
      }
      const stub = sinon.stub(orgRepo, 'findOneByShortName').returns(stubCnaOrg)

      await onlyAdps(req, res, next)
      expect(stub.calledOnce).to.be.true
      expect(status.calledOnce).to.be.true
      expect(status.args[0][0]).to.equal(403)
      expect(res.json.args[0][0].error).to.equal(error.adpOnly().error)
    })

    it('Should return 404 if the requester org does not exist', async () => {
      const req = {
        ctx: {
          org: stubCnaOrg.short_name,
          uuid: stubCnaOrg.UUID,
          repositories: {
            getOrgRepository
          }
        }
      }
      const stub = sinon.stub(orgRepo, 'findOneByShortName').returns(null)

      await onlyAdps(req, res, next)
      expect(stub.calledOnce).to.be.true
      expect(status.calledOnce).to.be.true
      expect(status.args[0][0]).to.equal(404)
      expect(res.json.args[0][0].error).to.equal(error.adpDoesNotExist(stubCnaOrg.short_name).error)
    })
  })

  context('Positive Tests', () => {
    it('Should allow orgs with ADP role through by calling next()  ', async () => {
      const req = {
        ctx: {
          org: stubAdpOrg.short_name,
          uuid: stubAdpOrg.UUID,
          repositories: {
            getOrgRepository
          }
        }
      }
      const stub = sinon.stub(orgRepo, 'findOneByShortName').returns(stubAdpOrg)

      await onlyAdps(req, res, next)
      expect(stub.calledOnce).to.be.true
      expect(status.calledOnce).to.be.false
      expect(next.calledOnce).to.be.true
    })
    it('Should allow orgs with Secretariat role through by calling next()  ', async () => {
      const req = {
        ctx: {
          org: stubSecretariat.short_name,
          uuid: stubSecretariat.UUID,
          repositories: {
            getOrgRepository
          }
        }
      }
      const stub = sinon.stub(orgRepo, 'findOneByShortName').returns(stubSecretariat)

      await onlyAdps(req, res, next)
      expect(stub.calledOnce).to.be.true
      expect(status.calledOnce).to.be.false
      expect(next.calledOnce).to.be.true
    })
  })
})


text:
const express = require('express')
const app = express()
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-http'))

// Body Parser Middleware
app.use(express.json()) // Allows us to handle raw JSON data
app.use(express.urlencoded({ extended: false })) // Allows us to handle url encoded data
const middleware = require('../../../src/middleware/middleware')
app.use(middleware.createCtxAndReqUUID)

const mwSecretariatOrAdminFixtures = require('./onlySecretariatOrAdmin.fixtures')
const errors = require('../../../src/middleware/error')
const error = new errors.MiddlewareError()

class OrgOnlySecretariatOrAdmin {
  async isSecretariat (shortname) {
    if (shortname === mwSecretariatOrAdminFixtures.secretariatOrg.short_name) {
      return true
    }

    return false
  }
}

class UserOnlySecretariatOrAdmin {
  async isAdmin (username, shortname) {
    if (username === mwSecretariatOrAdminFixtures.secretariatUser.username && shortname === mwSecretariatOrAdminFixtures.secretariatOrg.short_name) {
      return false
    } else if (username === mwSecretariatOrAdminFixtures.regularUser.username && shortname === mwSecretariatOrAdminFixtures.notSecretariatOrg.short_name) {
      return false
    }

    return true
  }
}

app.route('/only-secretariat-or-admin-pass')
  .post((req, res, next) => {
    const factory = {
      getOrgRepository: () => { return new OrgOnlySecretariatOrAdmin() },
      getUserRepository: () => { return new UserOnlySecretariatOrAdmin() }
    }
    req.ctx.repositories = factory
    next()
  }, middleware.onlySecretariatOrAdmin, (req, res) => {
    return res.status(200).json({ message: 'Success! You have reached the target endpoint.' })
  })

describe('Test only Secretariat or Org Admin user middleware', () => {
  context('Positive Tests', function () {
    it('User is a secretariat', function (done) {
      chai.request(app)
        .post('/only-secretariat-or-admin-pass')
        .set(mwSecretariatOrAdminFixtures.secretariatHeaders)
        .send()
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(200)
          expect(res).to.have.property('body').and.to.be.a('object')
          expect(res.body).to.have.property('message').and.to.be.a('string')
          expect(res.body.message).to.equal('Success! You have reached the target endpoint.')
          done()
        })
    })

    it('User is an admin user', function (done) {
      chai.request(app)
        .post('/only-secretariat-or-admin-pass')
        .set(mwSecretariatOrAdminFixtures.adminHeaders)
        .send()
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(200)
          expect(res).to.have.property('body').and.to.be.a('object')
          expect(res.body).to.have.property('message').and.to.be.a('string')
          expect(res.body.message).to.equal('Success! You have reached the target endpoint.')
          done()
        })
    })

    it('User is a secretariat and an admin user', function (done) {
      chai.request(app)
        .post('/only-secretariat-or-admin-pass')
        .set(mwSecretariatOrAdminFixtures.secretariatAndAdminHeaders)
        .send()
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(200)
          expect(res).to.have.property('body').and.to.be.a('object')
          expect(res.body).to.have.property('message').and.to.be.a('string')
          expect(res.body.message).to.equal('Success! You have reached the target endpoint.')
          done()
        })
    })
  })

  context('Negative Tests', function () {
    it('User is not a secretariat or an admin user', function (done) {
      app.route('/only-secretariat-or-admin-reject')
        .post((req, res, next) => {
          const factory = {
            getOrgRepository: () => { return new OrgOnlySecretariatOrAdmin() },
            getUserRepository: () => { return new UserOnlySecretariatOrAdmin() }
          }
          req.ctx.repositories = factory
          next()
        }, middleware.onlySecretariatOrAdmin, (req, res) => {
          return res.status(200).json({ message: 'Success! You have reached the target endpoint.' })
        })

      chai.request(app)
        .post('/only-secretariat-or-admin-reject')
        .set(mwSecretariatOrAdminFixtures.regHeaders)
        .send()
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(403)
          expect(res).to.have.property('body').and.to.be.a('object')
          const errObj = error.notOrgAdminOrSecretariat()
          expect(res.body.error).to.equal(errObj.error)
          expect(res.body.message).to.equal(errObj.message)
          done()
        })
    })
  })
})


text:
/* eslint-disable no-unused-expressions */

const chai = require('chai')
const sinon = require('sinon')
const { faker } = require('@faker-js/faker')
const expect = chai.expect

const OrgRepository = require('../../../src/repositories/orgRepository.js')
const { onlyOrgWithPartnerRole } = require('../../../src/middleware/middleware.js')
const errors = require('../../../src/middleware/error.js')
const error = new errors.MiddlewareError()

const stubAdpOrg = {
  short_name: 'adpOrg',
  name: 'test_adp',
  UUID: faker.datatype.uuid(),
  authority: {
    active_roles: [
      'ADP'
    ]
  }
}

const stubCnaOrg = {
  short_name: 'cnaOrg',
  name: 'test_cna',
  UUID: faker.datatype.uuid(),
  authority: {
    active_roles: [
      'CNA'
    ]
  }
}

const stubBulkDownloadOrg = {
  short_name: 'bdOrg',
  name: 'test_bd',
  UUID: faker.datatype.uuid(),
  authority: {
    active_roles: [
      'BULK_DOWNLOAD'
    ]
  }
}

const stubOrgNoRole = {
  short_name: 'NoRole',
  name: 'test_org',
  UUID: faker.datatype.uuid(),
  authority: {
    active_roles: []
  }
}

const stubSecretariat = {
  short_name: 'secOrg',
  name: 'test_sec',
  UUID: faker.datatype.uuid(),
  authority: {
    active_roles: [
      'SECRETARIAT'
    ]
  }
}

describe('Testing onlyOrgWithPartnerRole middleware', () => {
  let status, json, res, next, getOrgRepository, orgRepo
  beforeEach(() => {
    status = sinon.stub()
    json = sinon.spy()
    res = { json, status }
    next = sinon.spy()
    status.returns(res)
    orgRepo = new OrgRepository()
    getOrgRepository = sinon.stub()
    getOrgRepository.returns(orgRepo)
  })
  context('Negative Tests', () => {
    it('Should return 403 for users from orgs without a partner role ', async () => {
      const req = {
        ctx: {
          org: stubBulkDownloadOrg.short_name,
          uuid: stubBulkDownloadOrg.UUID,
          repositories: {
            getOrgRepository
          }
        }
      }
      const stub = sinon.stub(orgRepo, 'findOneByShortName').returns(stubBulkDownloadOrg)

      await onlyOrgWithPartnerRole(req, res, next)
      expect(stub.calledOnce).to.be.true
      expect(status.calledOnce).to.be.true
      expect(status.args[0][0]).to.equal(403)
      expect(res.json.args[0][0].error).to.equal(error.orgHasNoPartnerRole().error)
    })
    it('Should return 403 for users from orgs without a role ', async () => {
      const req = {
        ctx: {
          org: stubOrgNoRole.short_name,
          uuid: stubOrgNoRole.UUID,
          repositories: {
            getOrgRepository
          }
        }
      }
      const stub = sinon.stub(orgRepo, 'findOneByShortName').returns(stubOrgNoRole)

      await onlyOrgWithPartnerRole(req, res, next)
      expect(stub.calledOnce).to.be.true
      expect(status.calledOnce).to.be.true
      expect(status.args[0][0]).to.equal(403)
      expect(res.json.args[0][0].error).to.equal(error.orgHasNoPartnerRole().error)
    })

    it('Should return 404 if the requester org does not exist', async () => {
      const req = {
        ctx: {
          org: stubCnaOrg.short_name,
          uuid: stubCnaOrg.UUID,
          repositories: {
            getOrgRepository
          }
        }
      }
      const stub = sinon.stub(orgRepo, 'findOneByShortName').returns(null)

      await onlyOrgWithPartnerRole(req, res, next)
      expect(stub.calledOnce).to.be.true
      expect(status.calledOnce).to.be.true
      expect(status.args[0][0]).to.equal(404)
      expect(res.json.args[0][0].error).to.equal(error.orgDoesNotExist(stubCnaOrg.short_name).error)
    })
  })

  context('Positive Tests', () => {
    it('Should allow orgs with ADP partner role through by calling next()  ', async () => {
      const req = {
        ctx: {
          org: stubAdpOrg.short_name,
          uuid: stubAdpOrg.UUID,
          repositories: {
            getOrgRepository
          }
        }
      }
      const stub = sinon.stub(orgRepo, 'findOneByShortName').returns(stubAdpOrg)

      await onlyOrgWithPartnerRole(req, res, next)
      expect(stub.calledOnce).to.be.true
      expect(status.calledOnce).to.be.false
      expect(next.calledOnce).to.be.true
    })
    it('Should allow orgs with CNA partner role through by calling next()  ', async () => {
      const req = {
        ctx: {
          org: stubCnaOrg.short_name,
          uuid: stubCnaOrg.UUID,
          repositories: {
            getOrgRepository
          }
        }
      }
      const stub = sinon.stub(orgRepo, 'findOneByShortName').returns(stubCnaOrg)

      await onlyOrgWithPartnerRole(req, res, next)
      expect(stub.calledOnce).to.be.true
      expect(status.calledOnce).to.be.false
      expect(next.calledOnce).to.be.true
    })
    it('Should allow orgs with Secretariat role through by calling next()  ', async () => {
      const req = {
        ctx: {
          org: stubSecretariat.short_name,
          uuid: stubSecretariat.UUID,
          repositories: {
            getOrgRepository
          }
        }
      }
      const stub = sinon.stub(orgRepo, 'findOneByShortName').returns(stubSecretariat)

      await onlyOrgWithPartnerRole(req, res, next)
      expect(stub.calledOnce).to.be.true
      expect(status.calledOnce).to.be.false
      expect(next.calledOnce).to.be.true
    })
  })
})


text:
const getConstants = require('../../../src/constants').getConstants
const CONSTANTS = getConstants()

const owningOrgHeader = {
  'content-type': 'application/json',
  'CVE-API-ORG': 'cisco',
  'CVE-API-USER': 'alopez',
  'CVE-API-KEY': 'SVXPHM9-1VXM0A8-QMG8WN0-29MASSE'
}

const secretariatHeader = {
  'content-type': 'application/json',
  'CVE-API-ORG': 'mitre',
  'CVE-API-USER': 'cpadro',
  'CVE-API-KEY': 'S96E4QT-SMT4YE3-KX03X6K-4615CED'
}

const owningOrg = {
  UUID: '88c02595-c8f7-4864-a0e7-e09b3e1da691',
  authority: {
    active_roles: [CONSTANTS.AUTH_ROLE_ENUM.CNA]
  },
  name: 'Cisco',
  policies: {
    id_quota: 1000
  },
  short_name: 'cisco',
  inUse: false
}

const org = {
  UUID: 'c0a1d017-faa5-4608-92ff-5c938da17eff',
  authority: {
    active_roles: [CONSTANTS.AUTH_ROLE_ENUM.CNA]
  },
  name: 'Siemens',
  policies: {
    id_quota: 500
  },
  short_name: 'siemens',
  inUse: false
}

const cveDummy1 = {
  _id: 1,
  cve_id: 'CVE-2019-5012',
  cve_year: '2019',
  state: CONSTANTS.CVE_STATES.RESERVED,
  owning_cna: owningOrg.UUID,
  requested_by: {}
}

const cveDummy2 = {
  _id: 1,
  cve_id: 'CVE-2018-5111',
  cve_year: '2018',
  state: CONSTANTS.CVE_STATES.REJECTED,
  owning_cna: org.UUID,
  requested_by: {}
}

const secretariatOrg = {
  UUID: '15fd129f-af00-4d8c-8f7b-e19b0587223f',
  authority: {
    active_roles: [CONSTANTS.AUTH_ROLE_ENUM.CNA, CONSTANTS.AUTH_ROLE_ENUM.SECRETARIAT]
  },
  name: 'The MITRE Corporation',
  policies: {
    id_quota: 1000
  },
  short_name: 'mitre',
  inUse: false
}

const secretariatUser = {
  UUID: 'e13186d5-ce3d-4fd9-aecd-8698c26897f2',
  org_UUID: secretariatOrg.UUID,
  name: {
    first: 'Cristina',
    last: 'Padro'
  },
  authority: {
    active_roles: []
  },
  secret: '$argon2i$v=19$m=4096,t=3,p=1$+qGHEfH5h4/tk404iWBxFw$xV96/b4NvQVvlZIq57wTS8s7gfKzsfMXRiOyf3ffgcw',
  username: 'cpadro',
  active: true
}

module.exports = {
  owningOrgHeader,
  owningOrg,
  cveDummy1,
  cveDummy2,
  org,
  secretariatHeader,
  secretariatOrg,
  secretariatUser
}


text:
const getConstants = require('../../../src/constants').getConstants
const CONSTANTS = getConstants()

const secretariatHeaders = {
  'content-type': 'application/json',
  'CVE-API-ORG': 'mitre',
  'CVE-API-USER': 'cpadro',
  'CVE-API-KEY': 'S96E4QT-SMT4YE3-KX03X6K-4615CED',
  'PAGINATOR-PAGE': CONSTANTS.PAGINATOR_PAGE
}

const existentOrg = {
  UUID: '15fd129f-af00-4d8c-8f7b-e19b0587223f',
  authority: {
    active_roles: [CONSTANTS.AUTH_ROLE_ENUM.CNA, CONSTANTS.AUTH_ROLE_ENUM.SECRETARIAT]
  },
  name: 'The MITRE Corporation',
  policies: {
    id_quota: 5
  },
  short_name: 'mitre',
  active: true
}

const existentUser = {
  UUID: 'e13186d5-ce3d-4fd9-aecd-8698c26897f2',
  org_UUID: existentOrg.UUID,
  name: {
    first: 'Cristina',
    last: 'Padro'
  },
  authority: {
    active_roles: []
  },
  secret: '$argon2i$v=19$m=4096,t=3,p=1$+qGHEfH5h4/tk404iWBxFw$xV96/b4NvQVvlZIq57wTS8s7gfKzsfMXRiOyf3ffgcw',
  username: 'cpadro',
  active: true
}

const deactivatedUser = {
  UUID: 'a32386d5-ce3d-4fd9-aecd-8698c26897f2',
  org_UUID: existentOrg.UUID,
  name: {
    first: 'First',
    last: 'Last'
  },
  authority: {
    active_roles: []
  },
  secret: '$argon2i$v=19$m=4096,t=3,p=1$+qGHEfH5h4/tk404iWBxFw$xV96/b4NvQVvlZIq57wTS8s7gfKzsfMXRiOyf3ffgcw',
  username: 'flast',
  active: false
}

module.exports = {
  secretariatHeaders,
  existentOrg,
  existentUser,
  deactivatedUser
}


text:
const getConstants = require('../../../src/constants').getConstants
const CONSTANTS = getConstants()

const secretariatHeaders = {
  'content-type': 'application/json',
  'CVE-API-ORG': 'secretariat',
  'CVE-API-USER': 'secretariat_user',
  'CVE-API-KEY': 'S96E4QT-SMT4YE3-KX03X6K-4615CED'
}

const secretariatOrg = {
  UUID: '11kd129f-af00-4d8c-8f7b-e19b0587223f',
  authority: {
    active_roles: [CONSTANTS.AUTH_ROLE_ENUM.SECRETARIAT]
  },
  name: 'The Sec',
  policies: {
    id_quota: 5
  },
  short_name: 'secretariat'
}

const secretariatUser = {
  UUID: 'b34186d5-ce3d-4fd9-aecd-8698c26897f2',
  org_UUID: secretariatOrg.UUID,
  name: {
    first: 'Secretariat',
    last: 'User'
  },
  authority: {
    active_roles: []
  },
  secret: '$argon2i$v=19$m=4096,t=3,p=1$+qGHEfH5h4/tk404iWBxFw$xV96/b4NvQVvlZIq57wTS8s7gfKzsfMXRiOyf3ffgcw',
  username: 'secretariat_user',
  active: true
}

const secretariatAndCnaHeaders = {
  'content-type': 'application/json',
  'CVE-API-ORG': 'secretariatAndCna',
  'CVE-API-USER': 'secretariatAndCna_user',
  'CVE-API-KEY': 'S96E4QT-SMT4YE3-KX03X6K-4615CED'
}

const secretariatAndCnaOrg = {
  UUID: '15fd129f-af00-4d8c-8f7b-e19b0587223f',
  authority: {
    active_roles: [CONSTANTS.AUTH_ROLE_ENUM.CNA, CONSTANTS.AUTH_ROLE_ENUM.SECRETARIAT]
  },
  name: 'The Sec and CNA',
  policies: {
    id_quota: 5
  },
  short_name: 'secretariatAndCna'
}

const secretariatAndCnaUser = {
  UUID: 'h34186d5-ce3d-4fd9-aecd-8698c26897f2',
  org_UUID: secretariatAndCnaOrg.UUID,
  name: {
    first: 'SecretariatAndCna',
    last: 'User'
  },
  authority: {
    active_roles: []
  },
  secret: '$argon2i$v=19$m=4096,t=3,p=1$+qGHEfH5h4/tk404iWBxFw$xV96/b4NvQVvlZIq57wTS8s7gfKzsfMXRiOyf3ffgcw',
  username: 'secretariatAndCna_user',
  active: true
}

const notCnaHeaders = {
  'content-type': 'application/json',
  'CVE-API-ORG': 'not_CNA',
  'CVE-API-USER': 'not_cna_user',
  'CVE-API-KEY': 'S96E4QT-SMT4YE3-KX03X6K-4615CED'
}

const notCnaOrg = {
  UUID: '25bd129f-af00-4d8c-8f7b-e19b0587223f',
  authority: {
    active_roles: ['']
  },
  name: 'Not a CNA',
  policies: {
    id_quota: 5
  },
  short_name: 'not_CNA'
}

const notCnaUser = {
  UUID: 'z13186d5-ce3d-4fd9-aecd-8698c26897f2',
  org_UUID: notCnaOrg.UUID,
  name: {
    first: 'Not',
    last: 'CNA_User'
  },
  authority: {
    active_roles: []
  },
  secret: '$argon2i$v=19$m=4096,t=3,p=1$+qGHEfH5h4/tk404iWBxFw$xV96/b4NvQVvlZIq57wTS8s7gfKzsfMXRiOyf3ffgcw',
  username: 'not_cna_user',
  active: true
}

const cnaHeaders = {
  'content-type': 'application/json',
  'CVE-API-ORG': 'CNA',
  'CVE-API-USER': 'cna_user',
  'CVE-API-KEY': 'S96E4QT-SMT4YE3-KX03X6K-4615CED'
}

const cnaOrg = {
  UUID: '87yd129f-af00-4d8c-8f7b-e19b0587223f',
  authority: {
    active_roles: [CONSTANTS.AUTH_ROLE_ENUM.CNA]
  },
  name: 'CNA',
  policies: {
    id_quota: 5
  },
  short_name: 'CNA'
}

const cnaUser = {
  UUID: 'f98186d5-ce3d-4fd9-aecd-8698c26897f2',
  org_UUID: cnaOrg.UUID,
  name: {
    first: 'CNA',
    last: 'User'
  },
  authority: {
    active_roles: []
  },
  secret: '$argon2i$v=19$m=4096,t=3,p=1$+qGHEfH5h4/tk404iWBxFw$xV96/b4NvQVvlZIq57wTS8s7gfKzsfMXRiOyf3ffgcw',
  username: 'cna_user',
  active: true
}

module.exports = {
  secretariatHeaders,
  secretariatUser,
  secretariatOrg,
  secretariatAndCnaHeaders,
  secretariatAndCnaUser,
  secretariatAndCnaOrg,
  notCnaHeaders,
  notCnaUser,
  notCnaOrg,
  cnaHeaders,
  cnaUser,
  cnaOrg
}


text:
const getConstants = require('../../../src/constants').getConstants
const CONSTANTS = getConstants()

const secretariatHeaders = {
  'content-type': 'application/json',
  'CVE-API-ORG': 'secretariat',
  'CVE-API-USER': 'secretariat_user',
  'CVE-API-KEY': 'S96E4QT-SMT4YE3-KX03X6K-4615CED'
}

const adminHeaders = {
  'content-type': 'application/json',
  'CVE-API-ORG': 'not_secretariat',
  'CVE-API-USER': 'admin_user',
  'CVE-API-KEY': 'S96E4QT-SMT4YE3-KX03X6K-4615CED'
}

const secretariatAndAdminHeaders = {
  'content-type': 'application/json',
  'CVE-API-ORG': 'secretariat',
  'CVE-API-USER': 'sec_and_admin_user',
  'CVE-API-KEY': 'S96E4QT-SMT4YE3-KX03X6K-4615CED'
}

const regHeaders = {
  'content-type': 'application/json',
  'CVE-API-ORG': 'not_secretariat',
  'CVE-API-USER': 'regular_user',
  'CVE-API-KEY': 'S96E4QT-SMT4YE3-KX03X6K-4615CED'
}

const secretariatOrg = {
  UUID: '15fd129f-af00-4d8c-8f7b-e19b0587223f',
  authority: {
    active_roles: [CONSTANTS.AUTH_ROLE_ENUM.SECRETARIAT]
  },
  name: 'The Sec',
  policies: {
    id_quota: 5
  },
  short_name: 'secretariat'
}

const notSecretariatOrg = {
  UUID: '24ad129f-af00-4d8c-8f7b-e19b0587223f',
  authority: {
    active_roles: [CONSTANTS.AUTH_ROLE_ENUM.CNA]
  },
  name: 'Not a Secretariat',
  policies: {
    id_quota: 5
  },
  short_name: 'not_secretariat'
}

const secretariatUser = {
  UUID: 'h34186d5-ce3d-4fd9-aecd-8698c26897f2',
  org_UUID: secretariatOrg.UUID,
  name: {
    first: 'Secretariat',
    last: 'User'
  },
  authority: {
    active_roles: []
  },
  secret: '$argon2i$v=19$m=4096,t=3,p=1$+qGHEfH5h4/tk404iWBxFw$xV96/b4NvQVvlZIq57wTS8s7gfKzsfMXRiOyf3ffgcw',
  username: 'secretariat_user',
  active: true
}

const adminUser = {
  UUID: 'a11186d5-ce3d-4fd9-aecd-8698c26897f2',
  org_UUID: notSecretariatOrg.UUID,
  name: {
    first: 'Not',
    last: 'Secretariat_User'
  },
  authority: {
    active_roles: [CONSTANTS.USER_ROLE_ENUM.ADMIN]
  },
  secret: '$argon2i$v=19$m=4096,t=3,p=1$+qGHEfH5h4/tk404iWBxFw$xV96/b4NvQVvlZIq57wTS8s7gfKzsfMXRiOyf3ffgcw',
  username: 'admin_user',
  active: true
}

const secretariatAndAdminUser = {
  UUID: 'a11186d5-ce3d-4fd9-aecd-8698c26897f2',
  org_UUID: secretariatOrg.UUID,
  name: {
    first: 'Secretariat and Admin',
    last: 'User'
  },
  authority: {
    active_roles: [CONSTANTS.USER_ROLE_ENUM.ADMIN]
  },
  secret: '$argon2i$v=19$m=4096,t=3,p=1$+qGHEfH5h4/tk404iWBxFw$xV96/b4NvQVvlZIq57wTS8s7gfKzsfMXRiOyf3ffgcw',
  username: 'sec_and_admin_user',
  active: true
}

const regularUser = {
  UUID: 'a11186d5-ce3d-4fd9-aecd-8698c26897f2',
  org_UUID: notSecretariatOrg.UUID,
  name: {
    first: 'Regular',
    last: 'User'
  },
  authority: {
    active_roles: []
  },
  secret: '$argon2i$v=19$m=4096,t=3,p=1$+qGHEfH5h4/tk404iWBxFw$xV96/b4NvQVvlZIq57wTS8s7gfKzsfMXRiOyf3ffgcw',
  username: 'regular_user',
  active: true
}

module.exports = {
  secretariatHeaders,
  adminHeaders,
  secretariatAndAdminHeaders,
  regHeaders,
  secretariatUser,
  secretariatOrg,
  adminUser,
  notSecretariatOrg,
  secretariatAndAdminUser,
  regularUser
}


text:
const express = require('express')
const app = express()
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-http'))

// Body Parser Middleware
app.use(express.json()) // Allows us to handle raw JSON data
app.use(express.urlencoded({ extended: false })) // Allows us to handle url encoded data
const middleware = require('../../../src/middleware/middleware')
app.use(middleware.createCtxAndReqUUID)

const mwFixtures = require('./mockObjects.middleware')
const cveId5 = 'CVE-2017-4024'
const cvePass5 = require('../../schemas/5.0/' + cveId5 + '_published.json')
const cveFail5 = require('../../schemas/5.0/' + cveId5 + '_fail.json')
const cveMetadataFail5 = require('../../schemas/5.0/' + cveId5 + '_fail_cveMetadata.json')
const cveRejectedFail5 = require('../../schemas/5.0/' + cveId5 + '_rejected_fail.json')
const cveReservedFail5 = require('../../schemas/5.0/' + cveId5 + '_reserved_fail.json')
const cvePublishedFail5 = require('../../schemas/5.0/' + cveId5 + '_published_fail.json')
const cveVersionFail5 = require('../../schemas/5.0/' + cveId5 + '_version_fail.json')

app.route('/api/test/mw/schema5')
  .post(middleware.validateCveJsonSchema, (req, res) => {
    return res.status(200).json({ message: 'Success! You have reached the target endpoint.' })
  })

describe('Test the JSON schema 5.0 validation middleware', () => {
  context('Negative Tests', () => {
    it('Json validator fails because the STATE is invalid', (done) => {
      chai.request(app)
        .post('/api/test/mw/schema5')
        .set(mwFixtures.secretariatHeaders)
        .send(cveFail5)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(400)
          expect(res).to.have.property('body').and.to.be.a('object')
          expect(res.body).to.have.property('message').and.to.be.a('string')
          expect(res.body.message).to.equal('CVE JSON schema validation FAILED.')
          expect(res.body.details).to.have.property('errors').and.to.be.an('array')
          expect(res.body.details.errors[0]).to.have.string('cveMetadata.state is not one of enum values')
          done()
        })
    })

    it('Json validator fails when cveMetadata is not present', (done) => {
      chai.request(app)
        .post('/api/test/mw/schema5')
        .set(mwFixtures.secretariatHeaders)
        .send(cveMetadataFail5)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(400)
          expect(res).to.have.property('body').and.to.be.a('object')
          expect(res.body).to.have.property('message').and.to.be.a('string')
          expect(res.body.message).to.equal('CVE JSON schema validation FAILED.')
          expect(res.body.details).to.have.property('errors').and.to.be.an('array')
          expect(res.body.details.errors[0]).to.have.string('instance.cveMetadata is not defined')
          done()
        })
    })

    it('Json validator fails in REJECTED state', (done) => {
      chai.request(app)
        .post('/api/test/mw/schema5')
        .set(mwFixtures.secretariatHeaders)
        .send(cveRejectedFail5)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.property('status', 400)
          expect(res).to.have.property('body').and.to.be.a('object')
          expect(res.body).to.have.property('message').and.to.be.a('string')
          expect(res.body.message).to.equal('CVE JSON schema validation FAILED.')
          expect(res.body.details).to.have.property('errors').to.be.an('array')
          done()
        })
    })

    it('Json validator fails in RESERVED state', (done) => {
      chai.request(app)
        .post('/api/test/mw/schema5')
        .set(mwFixtures.secretariatHeaders)
        .send(cveReservedFail5)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.property('status', 400)
          expect(res).to.have.property('body').and.to.be.a('object')
          expect(res.body).to.have.property('message').and.to.be.a('string')
          expect(res.body.message).to.equal('CVE JSON schema validation FAILED.')
          done()
        })
    })

    it('Json validator fails in PUBLISHED state', (done) => {
      chai.request(app)
        .post('/api/test/mw/schema5')
        .set(mwFixtures.secretariatHeaders)
        .send(cvePublishedFail5)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(400)
          expect(res).to.have.property('body').and.to.be.a('object')
          expect(res.body).to.have.property('message').and.to.be.a('string')
          expect(res.body.message).to.equal('CVE JSON schema validation FAILED.')
          expect(res.body.details).to.have.property('errors').and.to.be.an('array')
          expect(res.body.details.errors[0].message).to.have.string('must be string')
          expect(res.body.details.errors[0].instancePath).to.have.string('/containers/cna/providerMetadata/orgId')
          done()
        })
    })

    it('Json validator fails because invalid data version', (done) => {
      chai.request(app)
        .post('/api/test/mw/schema5')
        .set(mwFixtures.secretariatHeaders)
        .send(cveVersionFail5)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(400)
          expect(res).to.have.property('body').and.to.be.a('object')
          expect(res.body).to.have.property('message').and.to.be.a('string')
          expect(res.body.message).to.equal('CVE JSON schema validation FAILED.')
          expect(res.body.details).to.have.property('errors').and.to.be.an('array')
          expect(res.body.details.errors[0]).to.have.string('instance.dataVersion is not one of enum values')
          done()
        })
    })
  })

  context('Positive Tests', () => {
    it('Json validator pass', (done) => {
      chai.request(app)
        .post('/api/test/mw/schema5')
        .set(mwFixtures.secretariatHeaders)
        .send(cvePass5)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(200)
          expect(res).to.have.property('body').and.to.be.a('object')
          expect(res.body).to.have.property('message').and.to.be.a('string')
          expect(res.body.message).to.equal('Success! You have reached the target endpoint.')
          done()
        })
    })
  })
})


text:
const express = require('express')
const app = express()
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-http'))

// Body Parser Middleware
app.use(express.json()) // Allows us to handle raw JSON data
app.use(express.urlencoded({ extended: false })) // Allows us to handle url encoded data
const middleware = require('../../../src/middleware/middleware')
app.use(middleware.createCtxAndReqUUID)

const getConstants = require('../../../src/constants').getConstants
const errors = require('../../../src/middleware/error')
const error = new errors.MiddlewareError()

const mwFixtures = require('./mockObjects.middleware')
const cveId5 = 'CVE-2017-4024'
const cvePass5 = require('../../schemas/5.0/' + cveId5 + '_published.json')

class OrgValidateUserSuccess {
  async getOrgUUID () {
    return mwFixtures.existentOrg.UUID
  }
}

class UserValidateUserSuccess {
  async findOneByUserNameAndOrgUUID () {
    return mwFixtures.existentUser
  }
}

class NullOrgRepo {
  async findOneByShortName () {
    return null
  }

  async updateByOrgUUID () {
    return null
  }

  async getOrgUUID () {
    return null
  }

  async isSecretariat () {
    return null
  }

  async isSecretariatUUID () {
    return null
  }
}

class NullUserRepo {
  async getUserUUID () {
    return null
  }

  async findOneByUserNameAndOrgUUID () {
    return null
  }

  async isAdmin () {
    return null
  }
}

describe('Testing the user validation middleware', () => {
  context('Negative Tests', () => {
    it('Org does not exist', (done) => {
      app.route('/validate-user-org-doesnt-exist')
        .post((req, res, next) => {
          const factory = {
            getOrgRepository: () => { return new NullOrgRepo() },
            getUserRepository: () => { return new NullUserRepo() }
          }
          req.ctx.repositories = factory
          next()
        }, middleware.validateUser, (req, res) => {
          return res.status(200).json({ message: 'Success! You have reached the target endpoint.' })
        })

      const CONSTANTS = getConstants()
      const testHeaders = Object.assign({}, mwFixtures.secretariatHeaders)
      testHeaders[CONSTANTS.AUTH_HEADERS.ORG] = 'jpmorgan'

      chai.request(app)
        .post('/validate-user-org-doesnt-exist')
        .set(testHeaders)
        .send(cvePass5)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(401)
          expect(res).to.have.property('body').and.to.be.a('object')
          const errObj = error.unauthorized()
          expect(res.body.error).to.equal(errObj.error)
          expect(res.body.message).to.equal(errObj.message)
          done()
        })
    })

    it('User is not found', (done) => {
      app.route('/validate-user-user-not-found')
        .post((req, res, next) => {
          const factory = {
            getOrgRepository: () => { return new NullOrgRepo() },
            getUserRepository: () => { return new NullUserRepo() }
          }
          req.ctx.repositories = factory
          next()
        }, middleware.validateUser, (req, res) => {
          return res.status(200).json({ message: 'Success! You have reached the target endpoint.' })
        })

      const CONSTANTS = getConstants()
      const testHeaders = Object.assign({}, mwFixtures.secretariatHeaders)
      testHeaders[CONSTANTS.AUTH_HEADERS.USER] = 'morgan'

      chai.request(app)
        .post('/validate-user-user-not-found')
        .set(testHeaders)
        .send(cvePass5)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(401)
          expect(res).to.have.property('body').and.to.be.a('object')
          const errObj = error.unauthorized()
          expect(res.body.error).to.equal(errObj.error)
          expect(res.body.message).to.equal(errObj.message)
          done()
        })
    })

    it('Secret apikey is incorrect', (done) => {
      app.route('/validate-user-key-incorrect')
        .post((req, res, next) => {
          const factory = {
            getOrgRepository: () => { return new OrgValidateUserSuccess() },
            getUserRepository: () => { return new UserValidateUserSuccess() }
          }
          req.ctx.repositories = factory
          next()
        }, middleware.validateUser, (req, res) => {
          return res.status(200).json({ message: 'Success! You have reached the target endpoint.' })
        })

      const CONSTANTS = getConstants()
      const testHeaders = Object.assign({}, mwFixtures.secretariatHeaders)
      testHeaders[CONSTANTS.AUTH_HEADERS.KEY] = 'wrong secret'

      chai.request(app)
        .post('/validate-user-key-incorrect')
        .set(testHeaders)
        .send(cvePass5)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(401)
          expect(res).to.have.property('body').and.to.be.a('object')
          const errObj = error.unauthorized()
          expect(res.body.error).to.equal(errObj.error)
          expect(res.body.message).to.equal(errObj.message)
          done()
        })
    })

    it('User is deactivated', (done) => {
      class UserValidateUserDeactivated {
        async findOneByUserNameAndOrgUUID () {
          return mwFixtures.deactivatedUser
        }
      }

      app.route('/validate-user-deactivated')
        .post((req, res, next) => {
          const factory = {
            getOrgRepository: () => { return new OrgValidateUserSuccess() },
            getUserRepository: () => { return new UserValidateUserDeactivated() }
          }
          req.ctx.repositories = factory
          next()
        }, middleware.validateUser, (req, res) => {
          return res.status(200).json({ message: 'Success! You have reached the target endpoint.' })
        })

      const CONSTANTS = getConstants()
      const deactivatedHeaders = {}
      deactivatedHeaders[CONSTANTS.AUTH_HEADERS.ORG] = 'mitre'
      deactivatedHeaders[CONSTANTS.AUTH_HEADERS.KEY] = 'S96E4QT-SMT4YE3-KX03X6K-4615CED'
      deactivatedHeaders[CONSTANTS.AUTH_HEADERS.USER] = 'flast'
      deactivatedHeaders['content-type'] = 'application/json'

      chai.request(app)
        .post('/validate-user-deactivated')
        .set(deactivatedHeaders)
        .send()
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(401)
          expect(res).to.have.property('body').and.to.be.a('object')
          const errObj = error.unauthorized()
          expect(res.body.error).to.equal(errObj.error)
          expect(res.body.message).to.equal(errObj.message)
          done()
        })
    })

    it('Org is undefined', (done) => {
      app.route('/validate-user-org-undefined')
        .post((req, res, next) => {
          const factory = {
            getOrgRepository: () => { return new NullOrgRepo() },
            getUserRepository: () => { return new NullUserRepo() }
          }
          req.ctx.repositories = factory
          next()
        }, middleware.validateUser, (req, res) => {
          return res.status(200).json({ message: 'Success! You have reached the target endpoint.' })
        })

      const CONSTANTS = getConstants()
      const testHeaders = Object.assign({}, mwFixtures.secretariatHeaders)
      delete testHeaders[CONSTANTS.AUTH_HEADERS.ORG]

      chai.request(app)
        .post('/validate-user-org-undefined')
        .set(testHeaders)
        .send(cvePass5)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(400)
          expect(res).to.have.property('body').and.to.be.a('object')
          const errObj = error.badRequest(CONSTANTS.AUTH_HEADERS.ORG)
          expect(res.body.error).to.equal(errObj.error)
          expect(res.body.message).to.equal(errObj.message)
          done()
        })
    })

    it('Requester is undefined', (done) => {
      app.route('/validate-user-submitter-undefined')
        .post((req, res, next) => {
          const factory = {
            getOrgRepository: () => { return new NullOrgRepo() },
            getUserRepository: () => { return new NullUserRepo() }
          }
          req.ctx.repositories = factory
          next()
        }, middleware.validateUser, (req, res) => {
          return res.status(200).json({ message: 'Success! You have reached the target endpoint.' })
        })

      const CONSTANTS = getConstants()
      const testHeaders = Object.assign({}, mwFixtures.secretariatHeaders)
      delete testHeaders[CONSTANTS.AUTH_HEADERS.USER]

      chai.request(app)
        .post('/validate-user-submitter-undefined')
        .set(testHeaders)
        .send(cvePass5)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(400)
          expect(res).to.have.property('body').and.to.be.a('object')
          const errObj = error.badRequest(CONSTANTS.AUTH_HEADERS.USER)
          expect(res.body.error).to.equal(errObj.error)
          expect(res.body.message).to.equal(errObj.message)
          done()
        })
    })

    it('Secret apikey is undefined', (done) => {
      app.route('/validate-user-secret-undefined')
        .post((req, res, next) => {
          const factory = {
            getOrgRepository: () => { return new NullOrgRepo() },
            getUserRepository: () => { return new NullUserRepo() }
          }
          req.ctx.repositories = factory
          next()
        }, middleware.validateUser, (req, res) => {
          return res.status(200).json({ message: 'Success! You have reached the target endpoint.' })
        })

      const CONSTANTS = getConstants()
      const testHeaders = Object.assign({}, mwFixtures.secretariatHeaders)
      delete testHeaders[CONSTANTS.AUTH_HEADERS.KEY]

      chai.request(app)
        .post('/validate-user-secret-undefined')
        .set(testHeaders)
        .send(cvePass5)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(400)
          expect(res).to.have.property('body').and.to.be.a('object')
          const errObj = error.badRequest(CONSTANTS.AUTH_HEADERS.KEY)
          expect(res.body.error).to.equal(errObj.error)
          expect(res.body.message).to.equal(errObj.message)
          done()
        })
    })
  })

  context('Positive Tests', () => {
    it('User is successfully validated', (done) => {
      app.route('/validate-user-successful')
        .post((req, res, next) => {
          const factory = {
            getOrgRepository: () => { return new OrgValidateUserSuccess() },
            getUserRepository: () => { return new UserValidateUserSuccess() }
          }
          req.ctx.repositories = factory
          next()
        }, middleware.validateUser, (req, res) => {
          return res.status(200).json({ message: 'Success! You have reached the target endpoint.' })
        })

      chai.request(app)
        .post('/validate-user-successful')
        .set(mwFixtures.secretariatHeaders)
        .send(cvePass5)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(200)
          expect(res).to.have.property('body').and.to.be.a('object')
          expect(res.body).to.have.property('message').and.to.be.a('string')
          expect(res.body.message).to.equal('Success! You have reached the target endpoint.')
          done()
        })
    })
  })
})


text:
const getConstants = require('../../../src/constants').getConstants
const CONSTANTS = getConstants()

const secretariatHeaders = {
  'content-type': 'application/json',
  'CVE-API-ORG': 'secretariat',
  'CVE-API-USER': 'secretariat_user',
  'CVE-API-KEY': 'S96E4QT-SMT4YE3-KX03X6K-4615CED'
}

const secretariatOrg = {
  UUID: '15fd129f-af00-4d8c-8f7b-e19b0587223f',
  authority: {
    active_roles: [CONSTANTS.AUTH_ROLE_ENUM.SECRETARIAT]
  },
  name: 'The Sec',
  policies: {
    id_quota: 5
  },
  short_name: 'secretariat'
}

const secretariatUser = {
  UUID: 'h34186d5-ce3d-4fd9-aecd-8698c26897f2',
  org_UUID: secretariatOrg.UUID,
  name: {
    first: 'Secretariat',
    last: 'User'
  },
  authority: {
    active_roles: []
  },
  secret: '$argon2i$v=19$m=4096,t=3,p=1$+qGHEfH5h4/tk404iWBxFw$xV96/b4NvQVvlZIq57wTS8s7gfKzsfMXRiOyf3ffgcw',
  username: 'secretariat_user',
  active: true
}

const notSecretariatOrg = {
  UUID: '24ad129f-af00-4d8c-8f7b-e19b0587223f',
  authority: {
    active_roles: [CONSTANTS.AUTH_ROLE_ENUM.CNA]
  },
  name: 'Not a Secretariat',
  policies: {
    id_quota: 5
  },
  short_name: 'not_secretariat'
}

const notSecretariatUser = {
  UUID: 'a11186d5-ce3d-4fd9-aecd-8698c26897f2',
  org_UUID: notSecretariatOrg.UUID,
  name: {
    first: 'Not',
    last: 'Secretariat_User'
  },
  authority: {
    active_roles: []
  },
  secret: '$argon2i$v=19$m=4096,t=3,p=1$+qGHEfH5h4/tk404iWBxFw$xV96/b4NvQVvlZIq57wTS8s7gfKzsfMXRiOyf3ffgcw',
  username: 'not_secretariat_user',
  active: true
}

module.exports = {
  secretariatHeaders,
  secretariatUser,
  secretariatOrg,
  notSecretariatUser,
  notSecretariatOrg
}


text:
const express = require('express')
const app = express()
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-http'))

// Body Parser Middleware
app.use(express.json()) // Allows us to handle raw JSON data
app.use(express.urlencoded({ extended: false })) // Allows us to handle url encoded data
const middleware = require('../../../src/middleware/middleware')
app.use(middleware.createCtxAndReqUUID)

const mwFixtures = require('./onlySecretariat.fixtures')
const getConstants = require('../../../src/constants').getConstants
const errors = require('../../../src/middleware/error')
const error = new errors.MiddlewareError()

describe('Test only Secretariat middleware', () => {
  context('Positive Tests', function () {
    it('User is a secretariat', function (done) {
      class OrgOnlySecretariatPass {
        async isSecretariat () {
          return true
        }
      }

      app.route('/only-secretariat-pass')
        .post((req, res, next) => {
          const factory = {
            getOrgRepository: () => { return new OrgOnlySecretariatPass() }
          }
          req.ctx.repositories = factory
          next()
        }, middleware.onlySecretariat, (req, res) => {
          return res.status(200).json({ message: 'Success! You have reached the target endpoint.' })
        })

      chai.request(app)
        .post('/only-secretariat-pass')
        .set(mwFixtures.secretariatHeaders)
        .send()
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(200)
          expect(res).to.have.property('body').and.to.be.a('object')
          expect(res.body).to.have.property('message').and.to.be.a('string')
          expect(res.body.message).to.equal('Success! You have reached the target endpoint.')
          done()
        })
    })
  })

  context('Negative Tests', function () {
    it('User is not a secretariat', function (done) {
      class OrgOnlySecretariatReject {
        async isSecretariat () {
          return false
        }
      }

      app.route('/only-secretariat-reject')
        .post((req, res, next) => {
          const factory = {
            getOrgRepository: () => { return new OrgOnlySecretariatReject() }
          }
          req.ctx.repositories = factory
          next()
        }, middleware.onlySecretariat, (req, res) => {
          return res.status(200).json({ message: 'Success! You have reached the target endpoint.' })
        })

      const testHeaders = Object.assign({}, mwFixtures.secretariatHeaders)
      const CONSTANTS = getConstants()

      testHeaders[CONSTANTS.AUTH_HEADERS.USER] = mwFixtures.notSecretariatUser.username
      testHeaders[CONSTANTS.AUTH_HEADERS.ORG] = mwFixtures.notSecretariatOrg.short_name

      chai.request(app)
        .post('/only-secretariat-reject')
        .set(testHeaders)
        .send()
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(403)
          expect(res).to.have.property('body').and.to.be.a('object')
          const errObj = error.secretariatOnly()
          expect(res.body.error).to.equal(errObj.error)
          expect(res.body.message).to.equal(errObj.message)
          done()
        })
    })
  })
})


text:
const express = require('express')
const app = express()
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-http'))

// Body Parser Middleware
app.use(express.json()) // Allows us to handle raw JSON data
app.use(express.urlencoded({ extended: false })) // Allows us to handle url encoded data
const middleware = require('../../../src/middleware/middleware')
app.use(middleware.createCtxAndReqUUID)

const mwCnaFixtures = require('./onlyCnas.fixtures')
const errors = require('../../../src/middleware/error')
const error = new errors.MiddlewareError()

describe('Test only CNA middleware', () => {
  context('Positive Tests', function () {
    it('Requester is a CNA', function (done) {
      class OrgOnlyCnasOrgCnaPass {
        async findOneByShortName () {
          return mwCnaFixtures.cnaOrg
        }
      }

      app.route('/only-cnas-org-cna-passes')
        .post((req, res, next) => {
          const factory = {
            getOrgRepository: () => { return new OrgOnlyCnasOrgCnaPass() }
          }
          req.ctx.repositories = factory
          next()
        }, middleware.onlyCnas, (req, res) => {
          return res.status(200).json({ message: 'Success! You have reached the target endpoint.' })
        })

      chai.request(app)
        .post('/only-cnas-org-cna-passes')
        .set(mwCnaFixtures.cnaHeaders)
        .send()
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(200)
          expect(res).to.have.property('body').and.to.be.a('object')
          expect(res.body).to.have.property('message').and.to.be.a('string')
          expect(res.body.message).to.equal('Success! You have reached the target endpoint.')
          done()
        })
    })

    it('Requester is a CNA and a secretariat', function (done) {
      class OrgOnlyCnasOrgCnaSecretariatPass {
        async findOneByShortName () {
          return mwCnaFixtures.secretariatAndCnaOrg
        }
      }

      app.route('/only-cnas-org-cna-and-secretariat-passes')
        .post((req, res, next) => {
          const factory = {
            getOrgRepository: () => { return new OrgOnlyCnasOrgCnaSecretariatPass() }
          }
          req.ctx.repositories = factory
          next()
        }, middleware.onlyCnas, (req, res) => {
          return res.status(200).json({ message: 'Success! You have reached the target endpoint.' })
        })

      chai.request(app)
        .post('/only-cnas-org-cna-and-secretariat-passes')
        .set(mwCnaFixtures.secretariatAndCnaHeaders)
        .send()
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(200)
          expect(res).to.have.property('body').and.to.be.a('object')
          expect(res.body).to.have.property('message').and.to.be.a('string')
          expect(res.body.message).to.equal('Success! You have reached the target endpoint.')
          done()
        })
    })

    // This test will change with the implementation of Root CNAs, as the burden of reserving IDs
    // on behalf of other organizations transfers to Roots. Secretariat will then step back.
    it('Requester is a secretariat but not a CNA', function (done) {
      class OrgOnlyCnasOrgSecretariatPass {
        async findOneByShortName () {
          return mwCnaFixtures.secretariatOrg
        }
      }

      app.route('/only-cnas-org-secretariat-passes')
        .post((req, res, next) => {
          const factory = {
            getOrgRepository: () => { return new OrgOnlyCnasOrgSecretariatPass() }
          }
          req.ctx.repositories = factory
          next()
        }, middleware.onlyCnas, (req, res) => {
          return res.status(200).json({ message: 'Success! You have reached the target endpoint.' })
        })

      chai.request(app)
        .post('/only-cnas-org-secretariat-passes')
        .set(mwCnaFixtures.secretariatHeaders)
        .send()
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(200)
          expect(res).to.have.property('body').and.to.be.a('object')
          expect(res.body).to.have.property('message').and.to.be.a('string')
          expect(res.body.message).to.equal('Success! You have reached the target endpoint.')
          done()
        })
    })
  })

  context('Negative Tests', function () {
    it('Requester is not a CNA or a secretariat', function (done) {
      class OrgOnlyCnasOrgNotCnaReject {
        async findOneByShortName () {
          return mwCnaFixtures.notCnaOrg
        }
      }

      app.route('/only-cnas-org-not-cna-rejected')
        .post((req, res, next) => {
          const factory = {
            getOrgRepository: () => { return new OrgOnlyCnasOrgNotCnaReject() }
          }
          req.ctx.repositories = factory
          next()
        }, middleware.onlyCnas, (req, res) => {
          return res.status(200).json({ message: 'Success! You have reached the target endpoint.' })
        })

      chai.request(app)
        .post('/only-cnas-org-not-cna-rejected')
        .set(mwCnaFixtures.notCnaHeaders)
        .send()
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(403)
          expect(res).to.have.property('body').and.to.be.a('object')
          const errObj = error.cnaOnly()
          expect(res.body.error).to.equal(errObj.error)
          expect(res.body.message).to.equal(errObj.message)
          done()
        })
    })

    it('Requester organization shortname is not valid', function (done) {
      class OrgOnlyCnasOrgNull {
        async findOneByShortName () {
          return null
        }
      }

      app.route('/only-cnas-org-equals-null')
        .post((req, res, next) => {
          const factory = {
            getOrgRepository: () => { return new OrgOnlyCnasOrgNull() }
          }
          req.ctx.repositories = factory
          next()
        }, middleware.onlyCnas, (req, res) => {
          return res.status(200).json({ message: 'Success! You have reached the target endpoint.' })
        })

      chai.request(app)
        .post('/only-cnas-org-equals-null')
        .set(mwCnaFixtures.notCnaHeaders)
        .send()
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(404)
          expect(res).to.have.property('body').and.to.be.a('object')
          const errObj = error.cnaDoesNotExist(mwCnaFixtures.notCnaHeaders['CVE-API-ORG'])
          expect(res.body.error).to.equal(errObj.error)
          expect(res.body.message).to.equal(errObj.message)
          done()
        })
    })
  })
})


text:
const express = require('express')
const app = express()
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-http'))

// Body Parser Middleware
app.use(express.json()) // Allows us to handle raw JSON data
app.use(express.urlencoded({ extended: false })) // Allows us to handle url encoded data
const middleware = require('../../../src/middleware/middleware')
app.use(middleware.createCtxAndReqUUID)

const nonExistentCveId = 'CVE-2017-35437'
const errors = require('../../../src/controller/cve-id.controller/error')
const error = new errors.CveIdControllerError()

const cveIdFixtures = require('./mockObjects.cve-id')
const cveIdController = require('../../../src/controller/cve-id.controller/cve-id.controller')
const cveIdParams = require('../../../src/controller/cve-id.controller/cve-id.middleware')

class NullUserRepo {
  async getUserUUID () {
    return null
  }

  async findOneByUserNameAndOrgUUID () {
    return null
  }

  async isAdmin () {
    return null
  }
}

class NullOrgRepo {
  async findOneByShortName () {
    return null
  }

  async updateByOrgUUID () {
    return null
  }

  async getOrgUUID () {
    return null
  }

  async isSecretariat () {
    return null
  }

  async isSecretariatUUID () {
    return null
  }
}

describe('Testing the GET /cve-id/:id endpoint in CveId Controller', () => {
  context('Negative Tests', () => {
    it('Cve does not exist', (done) => {
      class CveIdGetCveIdDoesntExist {
        async aggregate () {
          return []
        }
      }

      app.route('/cve-id-doesnt-exist/:id')
        .get((req, res, next) => {
          const factory = {
            getCveIdRepository: () => { return new CveIdGetCveIdDoesntExist() },
            getUserRepository: () => { return new NullUserRepo() },
            getOrgRepository: () => { return new NullOrgRepo() }
          }
          req.ctx.repositories = factory
          next()
        }, cveIdParams.parseGetParams, cveIdController.CVEID_GET_SINGLE)

      chai.request(app)
        .get(`/cve-id-doesnt-exist/${nonExistentCveId}`)
        .set(cveIdFixtures.secretariatHeader)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(404)
          expect(res).to.have.property('body').and.to.be.a('object')
          const errObj = error.cveIdNotFound(nonExistentCveId)
          expect(res.body.error).to.equal(errObj.error)
          expect(res.body.message).to.equal(errObj.message)
          done()
        })
    })

    it('Cve is available', (done) => {
      class CveIdGetCveIdAvailable {
        async aggregate () {
          return [cveIdFixtures.cveDummy5]
        }
      }

      app.route('/cve-id-available/:id')
        .get((req, res, next) => {
          const factory = {
            getCveIdRepository: () => { return new CveIdGetCveIdAvailable() },
            getUserRepository: () => { return new NullUserRepo() },
            getOrgRepository: () => { return new NullOrgRepo() }
          }
          req.ctx.repositories = factory
          next()
        }, cveIdParams.parseGetParams, cveIdController.CVEID_GET_SINGLE)

      chai.request(app)
        .get(`/cve-id-available/${cveIdFixtures.cveDummy5.cve_id}`)
        .set(cveIdFixtures.secretariatHeader)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(404)
          expect(res).to.have.property('body').and.to.be.a('object')
          const errObj = error.cveIdNotFound(cveIdFixtures.cveDummy5.cve_id)
          expect(res.body.error).to.equal(errObj.error)
          expect(res.body.message).to.equal(errObj.message)
          done()
        })
    })

    it('Requester is not a user of the same org or the secretariat and the cve is RESERVED', (done) => {
      class CveIdGetCveIdNotOwningOrg {
        async aggregate () {
          return [cveIdFixtures.cveReserved]
        }
      }

      class OrgGetCveIdNotOwnerOrgReserved {
        async getOrgUUID () {
          return cveIdFixtures.org.UUID
        }

        async isSecretariatUUID () {
          return false
        }
      }

      app.route('/cve-id-not-owning-org-reserved/:id')
        .get((req, res, next) => {
          const factory = {
            getCveIdRepository: () => { return new CveIdGetCveIdNotOwningOrg() },
            getUserRepository: () => { return new NullUserRepo() },
            getOrgRepository: () => { return new OrgGetCveIdNotOwnerOrgReserved() }
          }
          req.ctx.repositories = factory
          next()
        }, cveIdParams.parseGetParams, cveIdController.CVEID_GET_SINGLE)

      chai.request(app)
        .get(`/cve-id-not-owning-org-reserved/${cveIdFixtures.cveId}`)
        .set(cveIdFixtures.orgHeader) // not the owning org or secretariat
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(200)
          expect(res).to.have.property('body').and.to.be.a('object')
          expect(res.body).to.have.property('cve_id').and.to.equal(cveIdFixtures.cveId)
          expect(res.body).to.have.property('state').and.to.equal('RESERVED')
          expect(res.body).to.have.property('owning_cna').and.to.equal('[REDACTED]')
          done()
        })
    })
  })

  context('Positive Tests', () => {
    it('Requester is not a user of the same org or the secretariat and the cve is not RESERVED', async () => {
      class CveIdGetCveIdNotOwningOrgNotReserved {
        constructor () {
          this.testRes1 = JSON.parse(JSON.stringify(cveIdFixtures.cveRejected))
          this.testRes1.owning_cna = cveIdFixtures.owningOrg.short_name
          this.testRes1.requested_by.cna = cveIdFixtures.owningOrg.short_name
          this.testRes1.requested_by.user = cveIdFixtures.owningOrgUser.username
        }

        async aggregate () {
          return [this.testRes1]
        }
      }

      class OrgGetCveIdNotOwnerOrgNotReserved {
        async getOrgUUID () {
          return cveIdFixtures.org.UUID
        }

        async isSecretariatUUID () {
          return false
        }

        async findOneByUUID () {
          return cveIdFixtures.owningOrg
        }
      }

      app.route('/cve-id-not-owning-org-not-reserved/:id')
        .get((req, res, next) => {
          const factory = {
            getCveIdRepository: () => { return new CveIdGetCveIdNotOwningOrgNotReserved() },
            getUserRepository: () => { return new NullUserRepo() },
            getOrgRepository: () => { return new OrgGetCveIdNotOwnerOrgNotReserved() }
          }
          req.ctx.repositories = factory
          next()
        }, cveIdParams.parseGetParams, cveIdController.CVEID_GET_SINGLE)

      const res = await chai.request(app)
        .get(`/cve-id-not-owning-org-not-reserved/${cveIdFixtures.cveId}`)
        .set(cveIdFixtures.orgHeader) // not the owning cna or secretariat

      expect(res).to.have.status(200)
      expect(res).to.have.property('body').and.to.be.a('object')
      expect(res.body).to.have.property('cve_id').and.to.equal(cveIdFixtures.cveId)
      expect(res.body).to.have.property('state').and.to.equal('REJECTED')
      expect(res.body).to.have.property('owning_cna').and.to.equal(cveIdFixtures.owningOrg.short_name)
    })

    it('Requester is a user of the same org', async () => {
      class CveIdGetCveIdOwningOrg {
        constructor () {
          this.testRes1 = JSON.parse(JSON.stringify(cveIdFixtures.cvePublished))
          this.testRes1.owning_cna = cveIdFixtures.owningOrg.short_name
          this.testRes1.requested_by.cna = cveIdFixtures.owningOrg.short_name
          this.testRes1.requested_by.user = cveIdFixtures.owningOrgUser.username
        }

        async aggregate () {
          return [this.testRes1]
        }
      }

      class UserGetCveIdOwningOrg {
        async findOneByUUID () {
          return cveIdFixtures.owningOrgUser
        }
      }

      class OrgGetCveIdOwningOrg {
        async getOrgUUID () {
          return cveIdFixtures.owningOrg.UUID
        }

        async isSecretariatUUID () {
          return false
        }

        async findOneByUUID () {
          return cveIdFixtures.owningOrg
        }
      }

      app.route('/cve-id-owning-org/:id')
        .get((req, res, next) => {
          const factory = {
            getCveIdRepository: () => { return new CveIdGetCveIdOwningOrg() },
            getUserRepository: () => { return new UserGetCveIdOwningOrg() },
            getOrgRepository: () => { return new OrgGetCveIdOwningOrg() }
          }
          req.ctx.repositories = factory
          req.ctx.authenticated = true
          next()
        }, cveIdParams.parseGetParams, cveIdController.CVEID_GET_SINGLE)

      const res = await chai.request(app)
        .get(`/cve-id-owning-org/${cveIdFixtures.cveId}`)
        .set(cveIdFixtures.owningOrgHeader)

      expect(res).to.have.status(200)
      expect(res).to.have.property('body').and.to.be.a('object')
      expect(res.body).to.have.property('cve_id').and.to.equal(cveIdFixtures.cveId)
      expect(res.body).to.have.property('state').and.to.equal('PUBLISHED')
      expect(res.body).to.have.property('owning_cna').and.to.equal(cveIdFixtures.owningOrg.short_name)
      expect(res.body).to.have.nested.property('requested_by.cna').and.to.equal(cveIdFixtures.owningOrg.short_name)
      expect(res.body).to.have.nested.property('requested_by.user').and.to.equal(cveIdFixtures.owningOrgUser.username)
    })

    it('Requester is the secretariat', (done) => {
      class CveIdGetCveIdOwningOrg {
        constructor () {
          this.testRes1 = JSON.parse(JSON.stringify(cveIdFixtures.cvePublished))
          this.testRes1.owning_cna = cveIdFixtures.owningOrg.short_name
          this.testRes1.requested_by.cna = cveIdFixtures.owningOrg.short_name
          this.testRes1.requested_by.user = cveIdFixtures.owningOrgUser.username
        }

        async aggregate () {
          return [this.testRes1]
        }
      }

      class UserGetCveIdRequestorSecretariat {
        async findOneByUUID (uuid) {
          if (uuid === cveIdFixtures.secretariatUser.UUID) {
            return cveIdFixtures.secretariatUser
          } else {
            return cveIdFixtures.owningOrgUser
          }
        }
      }

      class OrgGetCveIdRequestorSecretariat {
        async getOrgUUID () {
          return cveIdFixtures.secretariatOrg.UUID
        }

        async isSecretariatUUID () {
          return true
        }

        async findOneByUUID (uuid) {
          if (uuid === cveIdFixtures.secretariatOrg.UUID) {
            return cveIdFixtures.secretariatOrg
          } else {
            return cveIdFixtures.owningOrg
          }
        }
      }

      app.route('/cve-id-is-secretariat/:id')
        .get((req, res, next) => {
          const factory = {
            getCveIdRepository: () => { return new CveIdGetCveIdOwningOrg() },
            getUserRepository: () => { return new UserGetCveIdRequestorSecretariat() },
            getOrgRepository: () => { return new OrgGetCveIdRequestorSecretariat() }
          }
          req.ctx.repositories = factory
          req.ctx.authenticated = true
          next()
        }, cveIdParams.parseGetParams, cveIdController.CVEID_GET_SINGLE)

      chai.request(app)
        .get(`/cve-id-is-secretariat/${cveIdFixtures.cveId}`)
        .set(cveIdFixtures.secretariatHeader)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(200)
          expect(res).to.have.property('body').and.to.be.a('object')
          expect(res.body).to.have.property('cve_id').and.to.equal(cveIdFixtures.cveId)
          expect(res.body).to.have.property('state').and.to.equal('PUBLISHED')
          expect(res.body).to.have.property('owning_cna').and.to.equal(cveIdFixtures.owningOrg.short_name)
          expect(res.body).to.have.nested.property('requested_by.cna').and.to.equal(cveIdFixtures.owningOrg.short_name)
          expect(res.body).to.have.nested.property('requested_by.user').and.to.equal(cveIdFixtures.owningOrgUser.username)
          done()
        })
    })
  })
})


text:
const express = require('express')
const app = express()
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-http'))

// Body Parser Middleware
app.use(express.json()) // Allows us to handle raw JSON data
app.use(express.urlencoded({ extended: false })) // Allows us to handle url encoded data
const middleware = require('../../../src/middleware/middleware')
app.use(middleware.createCtxAndReqUUID)

const getConstants = require('../../../src/constants').getConstants
const year22 = 2022
const errors = require('../../../src/controller/cve-id.controller/error')
const error = new errors.CveIdControllerError()

const cveIdFixtures = require('./mockObjects.cve-id')
const cveIdController = require('../../../src/controller/cve-id.controller/cve-id.controller')
const cveIdParams = require('../../../src/controller/cve-id.controller/cve-id.middleware')

class NullUserRepo {
  async getUserUUID () {
    return null
  }

  async findOneByUserNameAndOrgUUID () {
    return null
  }

  async isAdmin () {
    return null
  }
}

class NullOrgRepo {
  async findOneByShortName () {
    return null
  }

  async updateByOrgUUID () {
    return null
  }

  async getOrgUUID () {
    return null
  }

  async isSecretariat () {
    return null
  }

  async isSecretariatUUID () {
    return null
  }
}

describe('Testing the POST /cve-id-range/:year endpoint in CveId Controller', () => {
  context('Negative Tests', () => {
    it(`CveId Range already exists for year ${year22}`, (done) => {
      class CveIdRange2022Exists {
        constructor () {
          const CONSTANTS = getConstants()
          this.cveIdRange = Object.assign({}, CONSTANTS.DEFAULT_CVE_ID_RANGE)
          this.cveIdRange.cve_year = '2022'
        }

        async findOne () {
          return this.cveIdRange
        }
      }

      app.route('/cve-id-range-2022-already-exists/:year')
        .post((req, res, next) => {
          const factory = {
            getCveIdRangeRepository: () => { return new CveIdRange2022Exists() },
            getUserRepository: () => { return new NullUserRepo() },
            getOrgRepository: () => { return new NullOrgRepo() }
          }
          req.ctx.repositories = factory
          next()
        }, cveIdParams.parsePostParams, cveIdController.CVEID_RANGE_CREATE)

      chai.request(app)
        .post(`/cve-id-range-2022-already-exists/${year22}`)
        .set(cveIdFixtures.secretariatHeader)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(400)
          expect(res).to.have.property('body').and.to.be.a('object')
          const errObj = error.yearRangeExists(year22)
          expect(res.body.error).to.equal(errObj.error)
          expect(res.body.message).to.equal(errObj.message)
          done()
        })
    })
  })

  context('Positive Tests', () => {
    it(`CveId Range is created for year ${year22}`, (done) => {
      class CveIdRange2022NotExists {
        async findOne () {
          return null
        }

        async findOneAndUpdate () {
          return null
        }
      }

      app.route('/cve-id-range-2022/:year')
        .post((req, res, next) => {
          const factory = {
            getCveIdRangeRepository: () => { return new CveIdRange2022NotExists() },
            getUserRepository: () => { return new NullUserRepo() },
            getOrgRepository: () => { return new NullOrgRepo() }
          }
          req.ctx.repositories = factory
          next()
        }, cveIdParams.parsePostParams, cveIdController.CVEID_RANGE_CREATE)

      chai.request(app)
        .post(`/cve-id-range-2022/${year22}`)
        .set(cveIdFixtures.secretariatHeader)
        .end((err, res) => {
          if (err) {
            done(err)
          }

          expect(res).to.have.status(200)
          done()
        })
    })
  })
})