Repository: CVEProject/cve-services
Pull request #448 (2021-06-07 22:34:35)

Endpoint cleanup
* Removing deprecated unit tests, updating existent unit tests, and adding missing unit tests.
* Cleaning up the endpoints by optimizing code syntax, creating and applying functions for search aggregates (mongoDB) to reduce code duplication, removing redundant code, removing dead code, and parsing the request parameters when creating/updating orgs and users to avoid unexpected behavior.



Patch:
diff --git a/src/controller/cve-id.controller/cve-id.controller.js b/src/controller/cve-id.controller/cve-id.controller.js
index c2b5d2c6..aa63482e 100644
--- a/src/controller/cve-id.controller/cve-id.controller.js
+++ b/src/controller/cve-id.controller/cve-id.controller.js
@@ -13,10 +13,12 @@ async function getCveId (req, res, next) {
     const orgShortName = req.ctx.org
     const cveIdRepo = req.ctx.repositories.getCveIdRepository()
     const orgRepo = req.ctx.repositories.getOrgRepository()
-    const userRepo = req.ctx.repositories.getUserRepository()
 
-    const result = await cveIdRepo.findOneByCveId(id)
-    if (!result || result.state === 'AVAILABLE') { // result.state === 'AVAILABLE' check is dead code
+    const agt = setAggregateObj({ cve_id: id })
+    let result = await cveIdRepo.aggregate(agt)
+    result = result.length > 0 ? result[0] : null
+
+    if (!result || result.state === CONSTANTS.CVE_STATES.AVAILABLE) {
       return res.status(404).json(error.cveIdNotFound(id))
     }
 
@@ -24,38 +26,24 @@ async function getCveId (req, res, next) {
     const isSecretariat = await orgRepo.isSecretariatUUID(orgUUID)
 
     // the requester is not a user in the organization and is not the secretariat
-    if (orgUUID !== result.owning_cna && !isSecretariat) {
-      if (result.state === 'RESERVED') {
-        const cveId = JSON.parse(JSON.stringify(result)) // clone cve id returned from the db
-        delete cveId._id
-
-        logger.info({ uuid: req.ctx.uuid, message: id + ' is ' + result.state + '. A 404 status was sent to the requester.', cveId: cveId })
+    if (orgShortName !== result.owning_cna && !isSecretariat) {
+      if (result.state === CONSTANTS.CVE_STATES.RESERVED) {
+        logger.info({ uuid: req.ctx.uuid, message: id + ' is ' + result.state + '. A 404 status was sent to the requester.', cveId: result })
         return res.status(404).json(error.cveIdNotFound(id))
       }
 
-      const cveId = {
+      result = {
         cve_id: result.cve_id,
         cve_year: result.cve_year,
         state: result.state,
-        owning_cna: (await orgRepo.findOneByUUID(result.owning_cna)).short_name
+        owning_cna: result.owning_cna
       }
 
-      logger.info({ uuid: req.ctx.uuid, message: id + ' record was sent to the user.', cveId: cveId })
-      return res.status(200).json(cveId)
+      logger.info({ uuid: req.ctx.uuid, message: id + ' record was sent to the user.', cveId: result })
+      return res.status(200).json(result)
     } else {
-      // the requester is a user in the organization or is the secretariat
-      const cveId = JSON.parse(JSON.stringify(result)) // clone cve id returned from the db
-      cveId.owning_cna = (await orgRepo.findOneByUUID(result.owning_cna)).short_name
-      cveId.requested_by.cna = (await orgRepo.findOneByUUID(result.requested_by.cna)).short_name
-      cveId.requested_by.user = (await userRepo.findOneByUUID(result.requested_by.user)).username
-      delete cveId._id
-
-      if (cveId.__v !== undefined) {
-        delete cveId.__v
-      }
-
-      logger.info({ uuid: req.ctx.uuid, message: id + ' record was sent to the user.', cveId: cveId })
-      return res.status(200).json(cveId)
+      logger.info({ uuid: req.ctx.uuid, message: id + ' record was sent to the user.', cveId: result })
+      return res.status(200).json(result)
     }
   } catch (err) {
     next(err)
@@ -103,7 +91,7 @@ async function getFilteredCveId (req, res, next) {
     })
 
     const query = {
-      state: { $ne: 'AVAILABLE' }
+      state: { $ne: CONSTANTS.CVE_STATES.AVAILABLE }
     }
 
     if (!isSecretariat) {
@@ -115,10 +103,6 @@ async function getFilteredCveId (req, res, next) {
     }
 
     if (state) {
-      if (state === 'AVAILABLE') {
-        return res.status(200).json({ cve_ids: [] })
-      }
-
       query.state = state
     }
 
@@ -146,81 +130,7 @@ async function getFilteredCveId (req, res, next) {
       }
     }
 
-    const agt = [
-      {
-        $match: query
-      },
-      {
-        $lookup: {
-          from: 'Org',
-          localField: 'owning_cna',
-          foreignField: 'UUID',
-          as: 'ownerCna'
-        }
-      },
-      {
-        $unwind: '$ownerCna'
-      },
-      {
-        $project: {
-          _id: false,
-          cve_id: true,
-          cve_year: true,
-          state: true,
-          owning_cna: '$ownerCna.short_name',
-          requested_by: true,
-          reserved: true,
-          time: true
-        }
-      },
-      {
-        $lookup: {
-          from: 'User',
-          localField: 'requested_by.user',
-          foreignField: 'UUID',
-          as: 'result'
-        }
-      },
-      {
-        $unwind: '$result'
-      },
-      {
-        $project: {
-          cve_id: true,
-          cve_year: true,
-          state: true,
-          owning_cna: true,
-          'requested_by.cna': true,
-          'requested_by.user': '$result.username',
-          reserved: true,
-          time: true
-        }
-      },
-      {
-        $lookup: {
-          from: 'Org',
-          localField: 'requested_by.cna',
-          foreignField: 'UUID',
-          as: 'result'
-        }
-      },
-      {
-        $unwind: '$result'
-      },
-      {
-        $project: {
-          cve_id: true,
-          cve_year: true,
-          state: true,
-          owning_cna: true,
-          'requested_by.cna': '$result.short_name',
-          'requested_by.user': true,
-          reserved: true,
-          time: true
-        }
-      }
-    ]
-
+    const agt = setAggregateObj(query)
     const pg = await cveIdRepo.aggregatePaginate(agt, options)
     const payload = { cve_ids: pg.itemsList }
 
@@ -250,30 +160,15 @@ async function modifyCveId (req, res, next) {
     const cveIdRepo = req.ctx.repositories.getCveIdRepository()
     const userRepo = req.ctx.repositories.getUserRepository()
 
-    if (req.ctx.query.state) {
-      state = req.ctx.query.state
-    }
-
-    if (req.ctx.query.org) {
-      newOrgShortName = req.ctx.query.org
-    }
-
-    if (state) {
-      if (state === 'RESERVED') {
-        return res.status(400).json(error.invalidReservedState())
-      } else if (state !== 'PUBLIC' && state !== 'REJECT') { // dead code
-        return res.status(400).json(error.invalidState(state))
-      }
-    }
-
-    if (newOrgShortName) {
-      orgUUID = await orgRepo.getOrgUUID(newOrgShortName)
+    Object.keys(req.ctx.query).forEach(k => {
+      const key = k.toLowerCase()
 
-      if (!orgUUID) {
-        logger.info({ uuid: req.ctx.uuid, message: id + ' could not be reassigned to ' + newOrgShortName + ' in MongoDB because it does not exist.' })
-        return res.status(404).json(error.orgDne(newOrgShortName))
+      if (key === 'state') {
+        state = req.ctx.query.state
+      } else if (key === 'org') {
+        newOrgShortName = req.ctx.query.org
       }
-    }
+    })
 
     let result = await cveIdRepo.findOneByCveId(id)
     if (!result) {
@@ -285,27 +180,32 @@ async function modifyCveId (req, res, next) {
     delete updatedCveId.time
 
     if (state) {
+      if (state === CONSTANTS.CVE_STATES.RESERVED) {
+        return res.status(400).json(error.invalidReservedState())
+      }
+
       updatedCveId.state = state
     }
 
     if (newOrgShortName) {
-      updatedCveId.owning_cna = orgUUID
-    }
+      orgUUID = await orgRepo.getOrgUUID(newOrgShortName)
 
-    result = await cveIdRepo.findOneAndUpdate({ cve_id: id }, updatedCveId, { new: true }) // update cve id
-    const cveId = JSON.parse(JSON.stringify(result)) // clone cve id returned from the db
-    cveId.owning_cna = (await orgRepo.findOneByUUID(result.owning_cna)).short_name
-    cveId.requested_by.cna = (await orgRepo.findOneByUUID(result.requested_by.cna)).short_name
-    cveId.requested_by.user = (await userRepo.findOneByUUID(result.requested_by.user)).username
-    delete cveId._id
+      if (!orgUUID) {
+        logger.info({ uuid: req.ctx.uuid, message: id + ' could not be reassigned to ' + newOrgShortName + ' in MongoDB because it does not exist.' })
+        return res.status(404).json(error.orgDne(newOrgShortName))
+      }
 
-    if (cveId.__v !== undefined) {
-      delete cveId.__v
+      updatedCveId.owning_cna = orgUUID
     }
 
+    await cveIdRepo.findOneAndUpdate({ cve_id: id }, updatedCveId) // update cve id
+    const agt = setAggregateObj({ cve_id: id })
+    result = await cveIdRepo.aggregate(agt)
+    result = result.length > 0 ? result[0] : null
+
     const responseMessage = {
       message: id + ' was successfully updated.',
-      updated: cveId
+      updated: result
     }
 
     const payload = {
@@ -313,7 +213,7 @@ async function modifyCveId (req, res, next) {
       change: id + ' was successfully updated.',
       req_UUID: req.ctx.uuid,
       org_UUID: await orgRepo.getOrgUUID(req.ctx.org),
-      cve_id: cveId
+      cve_id: result
     }
     payload.user_UUID = await userRepo.getUserUUID(req.ctx.user, payload.org_UUID)
     logger.info(JSON.stringify(payload))
@@ -385,7 +285,6 @@ async function reserveCveId (req, res, next) {
     }
 
     hasLock = await orgRepo.findOneAndUpdate({ short_name: shortName, inUse: false }, { $set: { inUse: true } }, { new: true }) // set lock for org
-
     if (!hasLock) {
       return res.status(403).json(error.reservationInProgress())
     }
@@ -841,6 +740,83 @@ async function createCveIdRange (req, res, next) {
   }
 }
 
+function setAggregateObj (query) {
+  return [
+    {
+      $match: query
+    },
+    {
+      $lookup: {
+        from: 'Org',
+        localField: 'owning_cna',
+        foreignField: 'UUID',
+        as: 'ownerCna'
+      }
+    },
+    {
+      $unwind: '$ownerCna'
+    },
+    {
+      $project: {
+        _id: false,
+        cve_id: true,
+        cve_year: true,
+        state: true,
+        owning_cna: '$ownerCna.short_name',
+        requested_by: true,
+        reserved: true,
+        time: true
+      }
+    },
+    {
+      $lookup: {
+        from: 'User',
+        localField: 'requested_by.user',
+        foreignField: 'UUID',
+        as: 'result'
+      }
+    },
+    {
+      $unwind: '$result'
+    },
+    {
+      $project: {
+        cve_id: true,
+        cve_year: true,
+        state: true,
+        owning_cna: true,
+        'requested_by.cna': true,
+        'requested_by.user': '$result.username',
+        reserved: true,
+        time: true
+      }
+    },
+    {
+      $lookup: {
+        from: 'Org',
+        localField: 'requested_by.cna',
+        foreignField: 'UUID',
+        as: 'result'
+      }
+    },
+    {
+      $unwind: '$result'
+    },
+    {
+      $project: {
+        cve_id: true,
+        cve_year: true,
+        state: true,
+        owning_cna: true,
+        'requested_by.cna': '$result.short_name',
+        'requested_by.user': true,
+        reserved: true,
+        time: true
+      }
+    }
+  ]
+}
+
 module.exports = {
   CVEID_GET_SINGLE: getCveId,
   CVEID_RESERVE: reserveCveId,
diff --git a/src/controller/cve.controller/cve.controller.js b/src/controller/cve.controller/cve.controller.js
index 5e2b71e1..4f1af3be 100644
--- a/src/controller/cve.controller/cve.controller.js
+++ b/src/controller/cve.controller/cve.controller.js
@@ -119,10 +119,7 @@ async function submitCve (req, res, next) {
       return res.status(400).json(error.cveRecordExists())
     }
 
-    // update the cve id in MongoDB
     await cveIdRepo.updateByCveId(cveId, { state: state })
-
-    // create cve record in MongoDB if it doesn't exist
     await cveRepo.updateByCveId(cveId, newCve, { upsert: true })
 
     const responseMessage = {
@@ -149,14 +146,13 @@ async function submitCve (req, res, next) {
 // Updates a CVE if one exists for the specified CVE ID
 async function updateCve (req, res, next) {
   try {
-    const cve = req.ctx.body
-    const newCve = new Cve({ cve: cve })
+    const newCve = new Cve({ cve: req.ctx.body })
     const cveId = req.ctx.params.id
     const cveRepo = req.ctx.repositories.getCveRepository()
     const cveIdRepo = req.ctx.repositories.getCveIdRepository()
     const orgRepo = req.ctx.repositories.getOrgRepository()
 
-    if (cveId !== cve.CVE_data_meta.ID) {
+    if (cveId !== newCve.cve.CVE_data_meta.ID) {
       return res.status(400).json(error.cveIdMismatch())
     }
 
@@ -165,22 +161,19 @@ async function updateCve (req, res, next) {
     }
 
     let result = await cveIdRepo.findOneByCveId(cveId)
-
     if (!result) {
       logger.info(cveId + ' does not exist.')
       return res.status(403).json(error.cveDne())
     }
 
     result = await cveRepo.findOneByCveId(cveId)
-
     if (!result) {
       logger.info(cveId + ' does not exist.')
       return res.status(403).json(error.cveRecordDne())
     }
 
-    result = await cveRepo.updateByCveId(cveId, newCve)
-
-    result = await cveIdRepo.updateByCveId(cveId, { state: newCve.cve.CVE_data_meta.STATE })
+    await cveRepo.updateByCveId(cveId, newCve)
+    await cveIdRepo.updateByCveId(cveId, { state: newCve.cve.CVE_data_meta.STATE })
 
     const responseMessage = {
       message: cveId + ' record was successfully updated.',
diff --git a/src/controller/org.controller/org.controller.js b/src/controller/org.controller/org.controller.js
index 3fb060a5..249e01c5 100644
--- a/src/controller/org.controller/org.controller.js
+++ b/src/controller/org.controller/org.controller.js
@@ -172,7 +172,7 @@ async function getOrgIdQuota (req, res, next) {
 
     const query = {
       owning_cna: await repo.getOrgUUID(shortName),
-      state: 'RESERVED'
+      state: CONSTANTS.CVE_STATES.RESERVED
     }
     const cveIdRepo = req.ctx.repositories.getCveIdRepository()
     result = await cveIdRepo.countDocuments(query)
@@ -189,9 +189,29 @@ async function getOrgIdQuota (req, res, next) {
 // Creates a new org only if the org doesn't exist for the specified shortname. If the org exists, we do not update the org.
 async function createOrg (req, res, next) {
   try {
-    const newOrg = new Org(req.ctx.body)
+    const newOrg = new Org()
     const orgRepo = req.ctx.repositories.getOrgRepository()
 
+    Object.keys(req.ctx.body).forEach(k => {
+      const key = k.toLowerCase()
+
+      if (key === 'short_name') {
+        newOrg.short_name = req.ctx.body.short_name
+      } else if (key === 'name') {
+        newOrg.name = req.ctx.body.name
+      } else if (key === 'authority') {
+        if (req.ctx.body.authority.active_roles) {
+          newOrg.authority.active_roles = req.ctx.body.authority.active_roles
+        }
+      } else if (key === 'policies') {
+        if (req.ctx.body.policies.id_quota) {
+          newOrg.policies.id_quota = req.ctx.body.policies.id_quota
+        }
+      } else if (key === 'uuid') {
+        return res.status(400).json(error.uuidProvided())
+      }
+    })
+
     let result = await orgRepo.findOneByShortName(newOrg.short_name) // Find org in MongoDB
     if (result) {
       logger.info({ uuid: req.ctx.uuid, message: newOrg.short_name + ' organization was not created because it already exists.' })
@@ -199,18 +219,10 @@ async function createOrg (req, res, next) {
     }
 
     newOrg.inUse = false
-
-    // policies are undefined
-    if (newOrg.authority.active_roles.length === 0) {
-      newOrg.authority.active_roles = [CONSTANTS.AUTH_ROLE_ENUM.CNA] // default role
-    }
-
-    if (newOrg.UUID) {
-      return res.status(400).json(error.uuidProvided())
-    }
     newOrg.UUID = uuid.v4()
+    newOrg.authority.active_roles = [CONSTANTS.AUTH_ROLE_ENUM.CNA] // default role
 
-    if (newOrg.policies.id_quota === undefined || newOrg.policies.id_quota === null) {
+    if (!newOrg.policies.id_quota) {
       newOrg.policies.id_quota = CONSTANTS.DEFAULT_ID_QUOTA
     }
 
@@ -245,9 +257,6 @@ async function updateOrg (req, res, next) {
   try {
     const shortName = req.ctx.params.shortname
     const newOrg = new Org()
-    let quota
-    let name
-    let shortname
     const removeRoles = []
     const addRoles = []
     const orgRepo = req.ctx.repositories.getOrgRepository()
@@ -260,35 +269,34 @@ async function updateOrg (req, res, next) {
       return res.status(404).json(error.orgDneParam(shortName))
     }
 
-    // parsing query parameters
-    if ('id_quota' in req.ctx.query) {
-      quota = req.ctx.query.id_quota
-    }
-    if ('name' in req.ctx.query) {
-      name = req.ctx.query.name
-    }
-    if ('shortname' in req.ctx.query) {
-      shortname = req.ctx.query.shortname
-    }
-    if ('active_roles.add' in req.ctx.query) {
-      if (Array.isArray(req.ctx.query['active_roles.add'])) {
-        req.ctx.query['active_roles.add'].forEach(r => {
-          addRoles.push(r)
-        })
-      }
-    }
-    if ('active_roles.remove' in req.ctx.query) {
-      if (Array.isArray(req.ctx.query['active_roles.remove'])) {
-        req.ctx.query['active_roles.remove'].forEach(r => {
-          removeRoles.push(r)
-        })
+    Object.keys(req.ctx.query).forEach(k => {
+      const key = k.toLowerCase()
+
+      if (key === 'shortname') {
+        newOrg.short_name = req.ctx.query.shortname
+        agt = setAggregateOrgObj({ short_name: newOrg.short_name })
+      } else if (key === 'name') {
+        newOrg.name = req.ctx.query.name
+      } else if (key === 'id_quota') {
+        newOrg.policies.id_quota = req.ctx.query.id_quota
+      } else if (key === 'active_roles.add') {
+        if (Array.isArray(req.ctx.query['active_roles.add'])) {
+          req.ctx.query['active_roles.add'].forEach(r => {
+            addRoles.push(r)
+          })
+        }
+      } else if (key === 'active_roles.remove') {
+        if (Array.isArray(req.ctx.query['active_roles.remove'])) {
+          req.ctx.query['active_roles.remove'].forEach(r => {
+            removeRoles.push(r)
+          })
+        }
       }
-    }
+    })
 
     // updating the org's roles
     if (org) {
       const roles = org.authority.active_roles
-      newOrg.policies.id_quota = org.policies.id_quota
 
       // adding roles
       addRoles.forEach(role => {
@@ -309,20 +317,7 @@ async function updateOrg (req, res, next) {
       newOrg.authority.active_roles = roles
     }
 
-    // updating the org's quota
-    if (quota) {
-      newOrg.policies.id_quota = quota
-    }
-
-    // updating the org's name (the name field is never an empty string due to the stripping of the quotes and double quotes)
-    if (name) {
-      newOrg.name = name
-    }
-
-    // updating the org's shortname (the shortname field is never an empty string due to the stripping of the quotes and double quotes)
-    if (shortname) {
-      newOrg.short_name = shortname
-      agt = setAggregateOrgObj({ short_name: newOrg.short_name })
+    if (newOrg.short_name) {
       const result = await orgRepo.findOneByShortName(newOrg.short_name)
 
       if (result) {
@@ -365,11 +360,11 @@ async function updateOrg (req, res, next) {
 async function createUser (req, res, next) {
   try {
     const orgShortName = req.ctx.params.shortname
-    const newUser = new User(req.ctx.body)
     const requesterUsername = req.ctx.user
     const requesterShortName = req.ctx.org
     const orgRepo = req.ctx.repositories.getOrgRepository()
     const userRepo = req.ctx.repositories.getUserRepository()
+    const newUser = new User()
 
     const orgUUID = await orgRepo.getOrgUUID(orgShortName)
     if (!orgUUID) { // the org can only be non-existent if the requestor is the Secretariat
@@ -377,10 +372,37 @@ async function createUser (req, res, next) {
       return res.status(404).json(error.orgDneParam(orgShortName))
     }
 
-    if (newUser.org_UUID) {
-      return res.status(400).json(error.uuidProvided())
-    }
-    newUser.org_UUID = orgUUID
+    Object.keys(req.ctx.body).forEach(k => {
+      const key = k.toLowerCase()
+
+      if (key === 'username') {
+        newUser.username = req.ctx.body.username
+      } else if (key === 'authority') {
+        if (req.ctx.body.authority.active_roles) {
+          newUser.authority.active_roles = req.ctx.body.authority.active_roles
+        }
+      } else if (key === 'name') {
+        if (req.ctx.body.name.first) {
+          newUser.name.first = req.ctx.body.name.first
+        }
+        if (req.ctx.body.name.last) {
+          newUser.name.last = req.ctx.body.name.last
+        }
+        if (req.ctx.body.name.middle) {
+          newUser.name.middle = req.ctx.body.name.middle
+        }
+        if (req.ctx.body.name.suffix) {
+          newUser.name.suffix = req.ctx.body.name.suffix
+        }
+        if (req.ctx.body.name.surname) {
+          newUser.name.surname = req.ctx.body.name.surname
+        }
+      } else if (key === 'org_uuid') {
+        return res.status(400).json(error.uuidProvided())
+      } else if (key === 'uuid') {
+        return res.status(400).json(error.uuidProvided())
+      }
+    })
 
     const requesterOrgUUID = await orgRepo.getOrgUUID(requesterShortName)
     const isSecretariat = await orgRepo.isSecretariatUUID(requesterOrgUUID)
@@ -392,15 +414,12 @@ async function createUser (req, res, next) {
       }
     }
 
+    newUser.org_UUID = orgUUID
+    newUser.UUID = uuid.v4()
     newUser.active = true
     const randomKey = cryptoRandomString({ length: CONSTANTS.CRYPTO_RANDOM_STRING_LENGTH })
     newUser.secret = await argon2.hash(randomKey)
 
-    if (newUser.UUID) {
-      return res.status(400).json(error.uuidProvided())
-    }
-    newUser.UUID = uuid.v4()
-
     let result = await userRepo.findOneByUserNameAndOrgUUID(newUser.username, newUser.org_UUID) // Find user in MongoDB
     if (result) {
       logger.info({ uuid: req.ctx.uuid, message: newUser.username + ' was not created because it already exists.' })
@@ -444,27 +463,15 @@ async function updateUser (req, res, next) {
     const username = req.ctx.params.username
     const shortName = req.ctx.params.shortname
     const newUser = new User()
-    let nameChanged = false
-    let newUsername
     let newOrgShortName
-    let active
-    // Set variable to true if protected fields are being modified
-    let changesRequirePrivilegedRole
-    const name = {
-      first: null,
-      last: null,
-      middle: null,
-      surname: null,
-      suffix: null
-    }
+    let changesRequirePrivilegedRole // Set variable to true if protected fields are being modified
     const removeRoles = []
     const addRoles = []
     const userRepo = req.ctx.repositories.getUserRepository()
     const orgRepo = req.ctx.repositories.getOrgRepository()
     const orgUUID = await orgRepo.getOrgUUID(shortName)
     const isSecretariat = await orgRepo.isSecretariat(requesterShortName)
-    // Check if requester is Admin of the designated user's org
-    const isAdmin = await userRepo.isAdmin(requesterUsername, requesterShortName)
+    const isAdmin = await userRepo.isAdmin(requesterUsername, requesterShortName) // Check if requester is Admin of the designated user's org
 
     if (!orgUUID) {
       logger.info({ uuid: req.ctx.uuid, message: 'The user could not be updated because ' + shortName + ' organization does not exist.' })
@@ -486,58 +493,43 @@ async function updateUser (req, res, next) {
       }
     }
 
-    if ('new_username' in req.ctx.query) {
-      newUsername = req.ctx.query.new_username
-    }
-    if ('org_shortname' in req.ctx.query) {
-      newOrgShortName = req.ctx.query.org_shortname
-      changesRequirePrivilegedRole = true
-    }
-    if ('active' in req.ctx.query) {
-      active = req.ctx.query.active
-      changesRequirePrivilegedRole = true
-    }
-    if ('name.first' in req.ctx.query) {
-      name.first = req.ctx.query['name.first']
-      user.name.first = name.first
-      nameChanged = true
-    }
-    if ('name.last' in req.ctx.query) {
-      name.last = req.ctx.query['name.last']
-      user.name.last = name.last
-      nameChanged = true
-    }
-    if ('name.middle' in req.ctx.query) {
-      name.middle = req.ctx.query['name.middle']
-      user.name.middle = name.middle
-      nameChanged = true
-    }
-    if ('name.suffix' in req.ctx.query) {
-      name.suffix = req.ctx.query['name.suffix']
-      user.name.suffix = name.suffix
-      nameChanged = true
-    }
-    if ('name.surname' in req.ctx.query) {
-      name.surname = req.ctx.query['name.surname']
-      user.name.surname = name.surname
-      nameChanged = true
-    }
-    if ('active_roles.add' in req.ctx.query) {
-      if (Array.isArray(req.ctx.query['active_roles.add'])) {
-        req.ctx.query['active_roles.add'].forEach(r => {
-          addRoles.push(r)
-        })
+    Object.keys(req.ctx.query).forEach(k => {
+      const key = k.toLowerCase()
+
+      if (key === 'new_username') {
+        newUser.username = req.ctx.query.new_username
+      } else if (key === 'org_shortname') {
+        newOrgShortName = req.ctx.query.org_shortname
         changesRequirePrivilegedRole = true
-      }
-    }
-    if ('active_roles.remove' in req.ctx.query) {
-      if (Array.isArray(req.ctx.query['active_roles.remove'])) {
-        req.ctx.query['active_roles.remove'].forEach(r => {
-          removeRoles.push(r)
-        })
+      } else if (key === 'name.first') {
+        newUser.name.first = req.ctx.query['name.first']
+      } else if (key === 'name.last') {
+        newUser.name.last = req.ctx.query['name.last']
+      } else if (key === 'name.middle') {
+        newUser.name.middle = req.ctx.query['name.middle']
+      } else if (key === 'name.suffix') {
+        newUser.name.suffix = req.ctx.query['name.suffix']
+      } else if (key === 'name.surname') {
+        newUser.name.surname = req.ctx.query['name.surname']
+      } else if (key === 'active') {
+        newUser.active = req.ctx.query.active
         changesRequirePrivilegedRole = true
+      } else if (key === 'active_roles.add') {
+        if (Array.isArray(req.ctx.query['active_roles.add'])) {
+          req.ctx.query['active_roles.add'].forEach(r => {
+            addRoles.push(r)
+          })
+          changesRequirePrivilegedRole = true
+        }
+      } else if (key === 'active_roles.remove') {
+        if (Array.isArray(req.ctx.query['active_roles.remove'])) {
+          req.ctx.query['active_roles.remove'].forEach(r => {
+            removeRoles.push(r)
+          })
+          changesRequirePrivilegedRole = true
+        }
       }
-    }
+    })
 
     // updating user's roles and org_uuid is only allowed for secretariats and org admins
     if (changesRequirePrivilegedRole && !(isAdmin || isSecretariat)) {
@@ -545,20 +537,6 @@ async function updateUser (req, res, next) {
       return res.status(403).json(error.notOrgAdminOrSecretariat())
     }
 
-    // updating the user's username (the username field is never an empty string due to the stripping of the quotes and double quotes)
-    if (newUsername) {
-      newUser.username = newUsername
-    }
-
-    if (active) {
-      newUser.active = active
-    }
-
-    // only update the name sub fields that were changed
-    if (nameChanged) {
-      newUser.name = user.name
-    }
-
     // check if the new org exist
     if (newOrgShortName) {
       newUser.org_UUID = await orgRepo.getOrgUUID(newOrgShortName)
@@ -572,21 +550,21 @@ async function updateUser (req, res, next) {
     let agt = setAggregateUserObj({ username: username, org_UUID: orgUUID })
 
     // check if org has user of same username already
-    if (newUsername && newOrgShortName) {
+    if (newUser.username && newUser.org_UUID) {
       agt = setAggregateUserObj({ username: newUser.username, org_UUID: newUser.org_UUID })
       const duplicateUsers = await userRepo.find({ org_UUID: newUser.org_UUID, username: newUser.username })
       if (duplicateUsers.length) {
         logger.info({ uuid: req.ctx.uuid, message: 'The user could not be updated because ' + newOrgShortName + ' organization contains a user with the same username.' })
         return res.status(403).json(error.duplicateUsername(newOrgShortName, newUser.username))
       }
-    } else if (newUsername) {
+    } else if (newUser.username) {
       agt = setAggregateUserObj({ username: newUser.username, org_UUID: orgUUID })
       const duplicateUsers = await userRepo.find({ org_UUID: orgUUID, username: newUser.username })
       if (duplicateUsers.length) {
         logger.info({ uuid: req.ctx.uuid, message: 'The user could not be updated because ' + shortName + ' organization contains a user with the same username.' })
         return res.status(403).json(error.duplicateUsername(shortName, newUser.username))
       }
-    } else if (newOrgShortName) {
+    } else if (newUser.org_UUID) {
       agt = setAggregateUserObj({ username: username, org_UUID: newUser.org_UUID })
       const duplicateUsers = await userRepo.find({ org_UUID: newUser.org_UUID, username: username })
       if (duplicateUsers.length) {
@@ -615,8 +593,8 @@ async function updateUser (req, res, next) {
     })
 
     newUser.authority.active_roles = roles
-    let result = await userRepo.updateByUserNameAndOrgUUID(username, orgUUID, newUser)
 
+    let result = await userRepo.updateByUserNameAndOrgUUID(username, orgUUID, newUser)
     if (result.n === 0) {
       logger.info({ uuid: req.ctx.uuid, message: 'The user could not be updated because ' + username + ' does not exist for ' + shortName + ' organization.' })
       return res.status(404).json(error.userDne(username))
@@ -645,7 +623,6 @@ async function updateUser (req, res, next) {
   }
 }
 
-// Resets the user secret
 async function resetSecret (req, res, next) {
   try {
     const requesterShortName = req.ctx.org
diff --git a/src/middleware/middleware.js b/src/middleware/middleware.js
index f7e903be..e5c4b3c7 100644
--- a/src/middleware/middleware.js
+++ b/src/middleware/middleware.js
@@ -35,15 +35,15 @@ async function validateUser (req, res, next) {
   const orgRepo = req.ctx.repositories.getOrgRepository()
 
   try {
-    if (org === undefined) {
+    if (!org) {
       return res.status(400).json(error.badRequest(CONSTANTS.AUTH_HEADERS.ORG))
     }
 
-    if (user === undefined) {
+    if (!user) {
       return res.status(400).json(error.badRequest(CONSTANTS.AUTH_HEADERS.USER))
     }
 
-    if (key === undefined) {
+    if (!key) {
       return res.status(400).json(error.badRequest(CONSTANTS.AUTH_HEADERS.KEY))
     }
 


Test patch:
diff --git a/test/unit-tests/cve-id/cveIdGetAllTest.js b/test/unit-tests/cve-id/cveIdGetAllTest.js
index c43fa633..6b9d1b90 100644
--- a/test/unit-tests/cve-id/cveIdGetAllTest.js
+++ b/test/unit-tests/cve-id/cveIdGetAllTest.js
@@ -137,38 +137,6 @@ describe('Testing the GET /cve-id endpoint in CveId Controller', () => {
         })
     })
 
-    it('No available CVEs are returned', (done) => {
-      class CveIdGetCveIdNoAvailableCves {
-        async aggregate () {
-          return []
-        }
-      }
-
-      app.route('/cve-id-filtered-no-available-cves-returned')
-        .get((req, res, next) => {
-          const factory = {
-            getCveIdRepository: () => { return new CveIdGetCveIdNoAvailableCves() },
-            getOrgRepository: () => { return new OrgGetCveIdNoCveIdsWithParams() }
-          }
-          req.ctx.repositories = factory
-          next()
-        }, cveIdParams.parseGetParams, cveIdController.CVEID_GET_FILTER)
-
-      chai.request(app)
-        .get('/cve-id-filtered-no-available-cves-returned?state=AVAILABLE')
-        .set(cveIdFixtures.owningOrgHeader)
-        .end((err, res) => {
-          if (err) {
-            done(err)
-          }
-
-          expect(res).to.have.status(200)
-          expect(res).to.have.property('body').and.to.be.an('object')
-          expect(res.body).to.have.property('cve_ids').and.to.be.a('array').and.to.have.lengthOf(0)
-          done()
-        })
-    })
-
     it('The "cve_id_year" query parameter is provided', (done) => {
       class CveIdGetCveIdYearProvided {
         constructor () {
diff --git a/test/unit-tests/cve-id/cveIdGetSingleTest.js b/test/unit-tests/cve-id/cveIdGetSingleTest.js
index 409f9370..3bb48bd2 100644
--- a/test/unit-tests/cve-id/cveIdGetSingleTest.js
+++ b/test/unit-tests/cve-id/cveIdGetSingleTest.js
@@ -58,8 +58,8 @@ describe('Testing the GET /cve-id/:id endpoint in CveId Controller', () => {
   context('Negative Tests', () => {
     it('Cve does not exist', (done) => {
       class CveIdGetCveIdDoesntExist {
-        async findOneByCveId () {
-          return null
+        async aggregate () {
+          return []
         }
       }
 
@@ -93,8 +93,8 @@ describe('Testing the GET /cve-id/:id endpoint in CveId Controller', () => {
 
     it('Cve is available', (done) => {
       class CveIdGetCveIdAvailable {
-        async findOneByCveId () {
-          return cveIdFixtures.cveDummy5
+        async aggregate () {
+          return [cveIdFixtures.cveDummy5]
         }
       }
 
@@ -128,8 +128,8 @@ describe('Testing the GET /cve-id/:id endpoint in CveId Controller', () => {
 
     it('Requester is not a user of the same org or the secretariat and the cve is RESERVED', (done) => {
       class CveIdGetCveIdNotOwningOrg {
-        async findOneByCveId () {
-          return cveIdFixtures.cveReserved
+        async aggregate () {
+          return [cveIdFixtures.cveReserved]
         }
       }
 
@@ -175,8 +175,15 @@ describe('Testing the GET /cve-id/:id endpoint in CveId Controller', () => {
   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 {
-        async findOneByCveId () {
-          return cveIdFixtures.cveReject
+        constructor () {
+          this.testRes1 = JSON.parse(JSON.stringify(cveIdFixtures.cveReject))
+          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]
         }
       }
 
@@ -218,8 +225,15 @@ describe('Testing the GET /cve-id/:id endpoint in CveId Controller', () => {
 
     it('Requester is a user of the same org', async () => {
       class CveIdGetCveIdOwningOrg {
-        async findOneByCveId () {
-          return cveIdFixtures.cvePublic
+        constructor () {
+          this.testRes1 = JSON.parse(JSON.stringify(cveIdFixtures.cvePublic))
+          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]
         }
       }
 
@@ -269,8 +283,15 @@ describe('Testing the GET /cve-id/:id endpoint in CveId Controller', () => {
 
     it('Requester is the secretariat', (done) => {
       class CveIdGetCveIdOwningOrg {
-        async findOneByCveId () {
-          return cveIdFixtures.cvePublic
+        constructor () {
+          this.testRes1 = JSON.parse(JSON.stringify(cveIdFixtures.cvePublic))
+          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]
         }
       }
 
diff --git a/test/unit-tests/cve-id/cveIdUpdateTest.js b/test/unit-tests/cve-id/cveIdUpdateTest.js
index dc7e33e3..2eec29e6 100644
--- a/test/unit-tests/cve-id/cveIdUpdateTest.js
+++ b/test/unit-tests/cve-id/cveIdUpdateTest.js
@@ -32,12 +32,6 @@ class NullUserRepo {
   }
 }
 
-class NullCveIdRepo {
-  async countDocuments () {
-    return null
-  }
-}
-
 class NullOrgRepo {
   async findOneByShortName () {
     return null
@@ -61,10 +55,6 @@ class NullOrgRepo {
 }
 
 class UserModifyCveIdOrgAndStateModified {
-  async findOneByUUID () {
-    return cveIdFixtures.owningOrgUser
-  }
-
   async getUserUUID () {
     return cveIdFixtures.secretariatUser.UUID
   }
@@ -74,13 +64,26 @@ class OrgModifyCveIdOrgAndStateModified {
   async getOrgUUID () {
     return cveIdFixtures.org.UUID
   }
+}
 
-  async findOneByUUID (uuid) {
-    if (uuid === cveIdFixtures.org.UUID) {
-      return cveIdFixtures.org
-    } else {
-      return cveIdFixtures.owningOrg
-    }
+class CveIdModifyCveIdOrgAndStateModified {
+  constructor () {
+    this.testRes1 = JSON.parse(JSON.stringify(cveIdFixtures.cveReject))
+    this.testRes1.owning_cna = cveIdFixtures.org.short_name
+    this.testRes1.requested_by.cna = cveIdFixtures.owningOrg.short_name
+    this.testRes1.requested_by.user = cveIdFixtures.owningOrgUser.username
+  }
+
+  async findOneByCveId () {
+    return cveIdFixtures.cveReserved
+  }
+
+  async findOneAndUpdate () {
+    return null
+  }
+
+  async aggregate () {
+    return [this.testRes1]
   }
 }
 
@@ -137,7 +140,7 @@ describe('Testing the PUT /cve-id/:id endpoint in CveId Controller', () => {
       app.route('/cve-id-modify-org-doesnt-exist/:id')
         .put((req, res, next) => {
           const factory = {
-            getCveIdRepository: () => { return new NullCveIdRepo() },
+            getCveIdRepository: () => { return new CveIdModifyCveIdOrgAndStateModified() },
             getOrgRepository: () => { return new OrgModifyCveIdOrgDoesntExist() },
             getUserRepository: () => { return new NullUserRepo() }
           }
@@ -166,7 +169,7 @@ describe('Testing the PUT /cve-id/:id endpoint in CveId Controller', () => {
       app.route('/cve-id-modify-state-query-is-reserved/:id')
         .put((req, res, next) => {
           const factory = {
-            getCveIdRepository: () => { return new NullCveIdRepo() },
+            getCveIdRepository: () => { return new CveIdModifyCveIdOrgAndStateModified() },
             getOrgRepository: () => { return new NullOrgRepo() },
             getUserRepository: () => { return new NullUserRepo() }
           }
@@ -190,49 +193,10 @@ describe('Testing the PUT /cve-id/:id endpoint in CveId Controller', () => {
           done()
         })
     })
-
-    it('State query parameter is invalid', (done) => {
-      app.route('/cve-id-modify-state-query-is-invalid/:id')
-        .put((req, res, next) => {
-          const factory = {
-            getCveIdRepository: () => { return new NullCveIdRepo() },
-            getOrgRepository: () => { return new NullOrgRepo() },
-            getUserRepository: () => { return new NullUserRepo() }
-          }
-          req.ctx.repositories = factory
-          next()
-        }, cveIdParams.parsePostParams, cveIdController.CVEID_UPDATE_SINGLE)
-
-      chai.request(app)
-        .put(`/cve-id-modify-state-query-is-invalid/${cveIdFixtures.cveId}?state=PUBLISHED`)
-        .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.invalidState('PUBLISHED')
-          expect(res.body.error).to.equal(errObj.error)
-          expect(res.body.message).to.equal(errObj.message)
-          done()
-        })
-    })
   })
 
   context('Positive Tests', () => {
     it('Cve is reassigned to another org and state is modified', (done) => {
-      class CveIdModifyCveIdOrgAndStateModified {
-        async findOneByCveId () {
-          return cveIdFixtures.cveReserved
-        }
-
-        async findOneAndUpdate (query, updatedCveId) {
-          return updatedCveId
-        }
-      }
-
       app.route('/cve-id-modify-org-and-state-modified/:id')
         .put((req, res, next) => {
           const factory = {
@@ -268,16 +232,22 @@ describe('Testing the PUT /cve-id/:id endpoint in CveId Controller', () => {
     it('No query parameters are provided', (done) => {
       class CveIdModifyCveIdNoQuery {
         constructor () {
-          this.testRes1 = cveIdFixtures.cveReject
-          this.testRes1.owning_cna = cveIdFixtures.org.UUID
+          this.testRes1 = JSON.parse(JSON.stringify(cveIdFixtures.cveReject))
+          this.testRes1.owning_cna = cveIdFixtures.org.short_name
+          this.testRes1.requested_by.cna = cveIdFixtures.owningOrg.short_name
+          this.testRes1.requested_by.user = cveIdFixtures.owningOrgUser.username
         }
 
         async findOneByCveId () {
           return this.testRes1
         }
 
-        async findOneAndUpdate (query, updatedCveId) {
-          return updatedCveId
+        async findOneAndUpdate () {
+          return null
+        }
+
+        async aggregate () {
+          return [this.testRes1]
         }
       }
 
diff --git a/test/unit-tests/org/orgUpdateTest.js b/test/unit-tests/org/orgUpdateTest.js
index e2caf385..c5b6b9f3 100644
--- a/test/unit-tests/org/orgUpdateTest.js
+++ b/test/unit-tests/org/orgUpdateTest.js
@@ -10,6 +10,7 @@ app.use(express.urlencoded({ extended: false })) // Allows us to handle url enco
 const middleware = require('../../../src/middleware/middleware')
 app.use(middleware.createCtxAndReqUUID)
 
+const CONSTANTS = require('../../../src/constants')
 const errors = require('../../../src/controller/org.controller/error')
 const error = new errors.OrgControllerError()
 
@@ -31,6 +32,42 @@ class NullUserRepo {
   }
 }
 
+class OrgUpdatedAddingRole {
+  async findOneByShortName () {
+    return orgFixtures.owningOrg
+  }
+
+  async aggregate () {
+    return [orgFixtures.owningOrg]
+  }
+
+  async updateByOrgUUID () {
+    return { n: 1 }
+  }
+
+  async getOrgUUID () {
+    return null
+  }
+}
+
+class OrgUpdatedRemovingRole {
+  async findOneByShortName () {
+    return orgFixtures.owningOrg
+  }
+
+  async aggregate () {
+    return [orgFixtures.owningOrg]
+  }
+
+  async updateByOrgUUID () {
+    return { n: 1 }
+  }
+
+  async getOrgUUID () {
+    return null
+  }
+}
+
 describe('Testing the PUT /org/:shortname endpoint in Org Controller', () => {
   context('Negative Tests', () => {
     it('Org is not updated because it does not exists', async () => {
@@ -60,7 +97,7 @@ describe('Testing the PUT /org/:shortname endpoint in Org Controller', () => {
       expect(res.body.message).to.equal(errObj.message)
     })
 
-    it('Org is not updated because the shortname already exists', (done) => {
+    it('Org is not updated because the new shortname already exists', (done) => {
       class OrgNotUpdatedShortNameExists {
         async findOneByShortName () {
           return orgFixtures.existentOrg
@@ -95,6 +132,136 @@ describe('Testing the PUT /org/:shortname endpoint in Org Controller', () => {
   })
 
   context('Positive Tests', () => {
+    it('Org is updated: Adding a role', (done) => {
+      app.route('/org-updated-adding-role-1/:shortname')
+        .put((req, res, next) => {
+          const factory = {
+            getOrgRepository: () => { return new OrgUpdatedAddingRole() },
+            getUserRepository: () => { return new NullUserRepo() }
+          }
+          req.ctx.repositories = factory
+          next()
+        }, orgParams.parsePostParams, orgController.ORG_UPDATE_SINGLE)
+
+      chai.request(app)
+        .put(`/org-updated-adding-role-1/${orgFixtures.owningOrg.short_name}?active_roles.add=${CONSTANTS.AUTH_ROLE_ENUM.ROOT_CNA}&active_roles.add=${CONSTANTS.AUTH_ROLE_ENUM.ROOT_CNA}`)
+        .set(orgFixtures.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('updated').and.to.be.a('object')
+          expect(res.body.updated.authority.active_roles).to.have.lengthOf(2)
+          expect(res.body.updated.authority.active_roles[0]).to.equal(CONSTANTS.AUTH_ROLE_ENUM.CNA)
+          expect(res.body.updated.authority.active_roles[1]).to.equal(CONSTANTS.AUTH_ROLE_ENUM.ROOT_CNA)
+          expect(res.body.updated.short_name).to.equal(orgFixtures.owningOrg.short_name)
+          expect(res.body.updated.name).to.equal(orgFixtures.owningOrg.name)
+          expect(res.body.updated.UUID).to.equal(orgFixtures.owningOrg.UUID)
+          expect(res.body.updated.policies.id_quota).to.equal(orgFixtures.owningOrg.policies.id_quota)
+          done()
+        })
+    })
+
+    it('Org is unchanged: Adding a role that the org already have', (done) => {
+      app.route('/org-updated-adding-role-2/:shortname')
+        .put((req, res, next) => {
+          const factory = {
+            getOrgRepository: () => { return new OrgUpdatedAddingRole() },
+            getUserRepository: () => { return new NullUserRepo() }
+          }
+          req.ctx.repositories = factory
+          next()
+        }, orgParams.parsePostParams, orgController.ORG_UPDATE_SINGLE)
+
+      chai.request(app)
+        .put(`/org-updated-adding-role-2/${orgFixtures.owningOrg.short_name}?active_roles.add=${CONSTANTS.AUTH_ROLE_ENUM.ROOT_CNA}&active_roles.add=${CONSTANTS.AUTH_ROLE_ENUM.ROOT_CNA}`)
+        .set(orgFixtures.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('updated').and.to.be.a('object')
+          expect(res.body.updated.authority.active_roles).to.have.lengthOf(2)
+          expect(res.body.updated.authority.active_roles[0]).to.equal(CONSTANTS.AUTH_ROLE_ENUM.CNA)
+          expect(res.body.updated.authority.active_roles[1]).to.equal(CONSTANTS.AUTH_ROLE_ENUM.ROOT_CNA)
+          expect(res.body.updated.short_name).to.equal(orgFixtures.owningOrg.short_name)
+          expect(res.body.updated.name).to.equal(orgFixtures.owningOrg.name)
+          expect(res.body.updated.UUID).to.equal(orgFixtures.owningOrg.UUID)
+          expect(res.body.updated.policies.id_quota).to.equal(orgFixtures.owningOrg.policies.id_quota)
+          done()
+        })
+    })
+
+    it('Org is updated: Removing a role', (done) => {
+      app.route('/org-updated-removing-role-1/:shortname')
+        .put((req, res, next) => {
+          const factory = {
+            getOrgRepository: () => { return new OrgUpdatedRemovingRole() },
+            getUserRepository: () => { return new NullUserRepo() }
+          }
+          req.ctx.repositories = factory
+          next()
+        }, orgParams.parsePostParams, orgController.ORG_UPDATE_SINGLE)
+
+      chai.request(app)
+        .put(`/org-updated-removing-role-1/${orgFixtures.owningOrg.short_name}?active_roles.remove=${CONSTANTS.AUTH_ROLE_ENUM.ROOT_CNA}&active_roles.remove=${CONSTANTS.AUTH_ROLE_ENUM.ROOT_CNA}`)
+        .set(orgFixtures.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('updated').and.to.be.a('object')
+          expect(res.body.updated.authority.active_roles).to.have.lengthOf(1)
+          expect(res.body.updated.authority.active_roles[0]).to.equal(CONSTANTS.AUTH_ROLE_ENUM.CNA)
+          expect(res.body.updated.short_name).to.equal(orgFixtures.owningOrg.short_name)
+          expect(res.body.updated.name).to.equal(orgFixtures.owningOrg.name)
+          expect(res.body.updated.UUID).to.equal(orgFixtures.owningOrg.UUID)
+          expect(res.body.updated.policies.id_quota).to.equal(orgFixtures.owningOrg.policies.id_quota)
+          done()
+        })
+    })
+
+    it('Org is unchanged: Removing a role that the org does not have', (done) => {
+      app.route('/org-updated-removing-role-2/:shortname')
+        .put((req, res, next) => {
+          const factory = {
+            getOrgRepository: () => { return new OrgUpdatedRemovingRole() },
+            getUserRepository: () => { return new NullUserRepo() }
+          }
+          req.ctx.repositories = factory
+          next()
+        }, orgParams.parsePostParams, orgController.ORG_UPDATE_SINGLE)
+
+      chai.request(app)
+        .put(`/org-updated-removing-role-2/${orgFixtures.owningOrg.short_name}?active_roles.remove=${CONSTANTS.AUTH_ROLE_ENUM.ROOT_CNA}&active_roles.remove=${CONSTANTS.AUTH_ROLE_ENUM.ROOT_CNA}`)
+        .set(orgFixtures.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('updated').and.to.be.a('object')
+          expect(res.body.updated.authority.active_roles).to.have.lengthOf(1)
+          expect(res.body.updated.authority.active_roles[0]).to.equal(CONSTANTS.AUTH_ROLE_ENUM.CNA)
+          expect(res.body.updated.short_name).to.equal(orgFixtures.owningOrg.short_name)
+          expect(res.body.updated.name).to.equal(orgFixtures.owningOrg.name)
+          expect(res.body.updated.UUID).to.equal(orgFixtures.owningOrg.UUID)
+          expect(res.body.updated.policies.id_quota).to.equal(orgFixtures.owningOrg.policies.id_quota)
+          done()
+        })
+    })
+
     // check that the org is unchanged
     it('No query parameters are provided', async () => {
       class OrgNotUpdatedNoQueryParameters {
diff --git a/test/unit-tests/user/userCreateTest.js b/test/unit-tests/user/userCreateTest.js
index 91080417..38e5e57d 100644
--- a/test/unit-tests/user/userCreateTest.js
+++ b/test/unit-tests/user/userCreateTest.js
@@ -227,7 +227,7 @@ describe('Testing the POST /org/:shortname/user endpoint in Org Controller', ()
           next()
         }, orgParams.parsePostParams, orgController.USER_CREATE_SINGLE)
 
-      const testUser = JSON.parse(JSON.stringify(userFixtures.existentUser))
+      const testUser = Object.assign({}, userFixtures.existentUser)
       delete testUser.UUID
       delete testUser.org_UUID
 
@@ -288,7 +288,7 @@ describe('Testing the POST /org/:shortname/user endpoint in Org Controller', ()
           next()
         }, orgParams.parsePostParams, orgController.USER_CREATE_SINGLE)
 
-      const testUser = JSON.parse(JSON.stringify(userFixtures.userA))
+      const testUser = Object.assign({}, userFixtures.userA)
       delete testUser.UUID
       delete testUser.org_UUID
       testUser.authority = {
@@ -408,6 +408,7 @@ describe('Testing the POST /org/:shortname/user endpoint in Org Controller', ()
         }, orgParams.parsePostParams, orgController.USER_CREATE_SINGLE)
 
       userFixtures.userA.authority.active_roles = ['ADMIN']
+
       const testUser = JSON.parse(JSON.stringify(userFixtures.userC))
       delete testUser.UUID
       delete testUser.org_UUID