From 72eb6b69dc758cfbad2a8ea77dc3cd45542ecf02 Mon Sep 17 00:00:00 2001
From: David T Rocca User must belong to an organization with the Secretariat role. The organization identified by shortname must have ROOT authority. The organization identified by shortname2 will report to it. If shortname2 already reported to a different ROOT. It will be removed from that and both will receive an audit entry. User must belong to an organization with the Secretariat role. The organization identified by shortname must have ROOT authority. The organization identified by shortname2 will report to it. If shortname2 already reported to a different ROOT, it will be removed from that Root. Audit entries capture the final relationship state for changed parents and any organizations whose derived top_level_root or _hierarchy changes. User must belong to an organization with the Secretariat role. The organization identified by shortname must have ROOT authority. The organization identified by shortname2 will
- report to it. If shortname2 already reported to a different ROOT. It will be removed from that and both will receive an audit entry.Access Control
Expected Behavior
Access Control
Expected Behavior
Expected Behavior
CVE data is to be in the JSON 5.2 CVE Record format. Details of the JSON 5.2 schema are located here.
Contact the CVE Services team", "contact": { diff --git a/package-lock.json b/package-lock.json index 17bf2d03a..2c66c90d2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "cve-services", - "version": "2.9.3", + "version": "2.9.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "cve-services", - "version": "2.9.3", + "version": "2.9.4", "license": "(CC0)", "dependencies": { "@cveproject/cve-validation-library": "github:CVEProject/cve-validation-library#v1.2.0", diff --git a/package.json b/package.json index 85d83d5fd..0de5a20f0 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "cve-services", "author": "Automation Working Group", - "version": "2.9.3", + "version": "2.9.4", "license": "(CC0)", "devDependencies": { "@faker-js/faker": "^10.5.0", From e0721dbe9d217a2ef4c190f67b007bd0005293b9 Mon Sep 17 00:00:00 2001 From: David T RoccaRelated legacy endpoint: PUT /org/{shortname}. This endpoint accepts a JSON request body and allows organization admins to request changes, with joint approval for designated fields. The legacy endpoint uses query parameters and requires Secretariat access.
User must belong to an organization with the Secretariat role or be an Admin of the requested organization.
With Joint Approval required for the following fields:
Secretariat: Updates any organization's information
Users cannot remove SECRETARIAT authority from their own organization. Another Secretariat organization must perform the demotion. Self-demotion returns 403 SECRETARIAT_CANNOT_SELF_DEMOTE.
Organization Admin: Requests changes to its organization's information
Organizations whose only role is ROOT have an ID quota of zero. An approved change to ROOT resets the quota to zero, even when the request omits it.
Related legacy endpoint: PUT /org/{shortname}. This endpoint accepts a JSON request body and allows organization admins to request changes, with joint approval for designated fields. The legacy endpoint uses query parameters and requires Secretariat access.
User must belong to an organization with the Secretariat role or be an Admin of the requested organization.
With Joint Approval required for the following fields:
Secretariat: Updates any organization's information
Partial joint approval: Secretariat users may supply x_unresolved_keys, an array of unique pending field paths such as ["industry", "contact_info.emails"]. The full organization body is still required. Listed fields retain their published values and original proposed values remain in the same pending review. Other fields use the submitted values, so denied fields must contain their published values. The response retains the existing message/updated envelope and reports that joint approval is still required.
Omitting this metadata or supplying an empty array retains existing whole-review approval/rejection behavior. Nonempty lists require a pending review and actual proposed changes. Arrays resolve as a whole; use short_name for a deferred rename, including when new_short_name is supplied. Unsupported, unchanged, or overlapping paths return 400. Resolve dependent role and quota changes together; updates that cannot preserve an unresolved value return 400 and roll back. Relationship fields reports_to, oversees, and top_level_root are excluded. Any supplied metadata from a non-Secretariat user returns 403.
Users cannot remove SECRETARIAT authority from their own organization. Another Secretariat organization must perform the demotion. Self-demotion returns 403 SECRETARIAT_CANNOT_SELF_DEMOTE.
Organization Admin: Requests changes to its organization's information
Organizations whose only role is ROOT have an ID quota of zero. An approved change to ROOT resets the quota to zero, even when the request omits it.
Secretariat: Updates any organization's information
+Partial joint approval: Secretariat users may supply x_unresolved_keys, an array of unique pending field paths such as ["industry", "contact_info.emails"]. The full organization body is still required. Listed fields retain their published values and original proposed values remain in the same pending review. Other fields use the submitted values, so denied fields must contain their published values. The response retains the existing message/updated envelope and reports that joint approval is still required.
Omitting this metadata or supplying an empty array retains existing whole-review approval/rejection behavior. Nonempty lists require a pending review and actual proposed changes. Arrays resolve as a whole; use short_name for a deferred rename, including when new_short_name is supplied. Unsupported, unchanged, or overlapping paths return 400. Resolve dependent role and quota changes together; updates that cannot preserve an unresolved value return 400 and roll back. Relationship fields reports_to, oversees, and top_level_root are excluded. Any supplied metadata from a non-Secretariat user returns 403.
Users cannot remove SECRETARIAT authority from their own organization. Another Secretariat organization must perform the demotion. Self-demotion returns 403 SECRETARIAT_CANNOT_SELF_DEMOTE.
Organization Admin: Requests changes to its organization's information
Organizations whose only role is ROOT have an ID quota of zero. An approved change to ROOT resets the quota to zero, even when the request omits it.
@@ -878,6 +880,7 @@ router.put('/registry/org/:shortname', mw.useRegistry(), mw.validateUser, // mw.onlySecretariat, + body('x_unresolved_keys').optional().custom(value => Array.isArray(value) && value.every(path => typeof path === 'string' && path.length > 0) && new Set(value).size === value.length).withMessage('x_unresolved_keys must be an array of unique nonempty field paths.'), body('user_quota').optional().custom(value => Number.isSafeInteger(value) && value >= 0).withMessage('user_quota must be a nonnegative safe integer.'), parseError, parsePutParams, diff --git a/src/controller/registry.controller/org.registry.controller.js b/src/controller/registry.controller/org.registry.controller.js index 84767895c..4a0d1b0e1 100644 --- a/src/controller/registry.controller/org.registry.controller.js +++ b/src/controller/registry.controller/org.registry.controller.js @@ -13,6 +13,8 @@ const { DisabledSecretariatError } = require('../../utils/orgDisabled') const { SecretariatSelfDemotionError } = require('../../utils/orgAuthority') const { REGISTRY_FORMAT } = require('../format.constants') const { getUserQuotaUsage } = require('../../utils/userQuota') +const { deepRemoveEmpty } = require('../../utils/utils') +const { normalizeOrgCveWebsiteUpdateDate } = require('../../utils/dateOnly') function addUUIDsToSet (uuidSet, values) { if (!Array.isArray(values)) return @@ -553,6 +555,18 @@ async function validateRequestedShortName (req, repo, body, shortName, session) return { requestedShortName } } +// Preserve path presence and replace arrays wholesale in both published and proposed data. +function copyReviewFields (target, source, paths) { + for (const path of paths) { + if (_.has(source, path)) { + _.set(target, path, _.cloneDeep(_.get(source, path))) + } else { + _.unset(target, path) + } + } + return target +} + /** * Updates an existing registry organization. * @@ -572,12 +586,14 @@ async function updateOrg (req, res, next) { const repo = req.ctx.repositories.getBaseOrgRepository() const userRepo = req.ctx.repositories.getBaseUserRepository() const conversationRepo = req.ctx.repositories.getConversationRepository() - const { conversation, ...body } = req.ctx.body + const { conversation, x_unresolved_keys: unresolvedKeys, ...orgBody } = req.ctx.body + let body = orgBody // oversees is managed exclusively by the dedicated reports-to endpoints. // Ignore it during standard organization updates. delete body.oversees let updatedOrg let jointApprovalRequired + let partialReview try { session.startTransaction({ readPreference: 'primary' }) @@ -585,7 +601,8 @@ async function updateOrg (req, res, next) { const isSecretariat = requester.isSecretariat const isAdmin = requester.isAdmin const requestingUser = requester.user - const org = await repo.findOneByShortName(shortName, { session }) + // Partial decisions need stored path presence, without hydrated array defaults. + const org = await repo.findOneByShortName(shortName, unresolvedKeys?.length ? { session, lean: true } : { session }) const requesterSameOrg = org ? await authContext.isRequesterSameOrg(req, repo, org, { session }) : await authContext.isRequesterSameOrg(req, repo, shortName, { session }) @@ -603,6 +620,10 @@ async function updateOrg (req, res, next) { } if (!isSecretariat) { + if (unresolvedKeys !== undefined) { + await session.abortTransaction() + return res.status(403).json(error.secretariatOnlyEditing(['x_unresolved_keys'])) + } const secretariatOnlyFields = getConstants().SECRETARIAT_ONLY_FIELDS const restrictedFieldsSent = secretariatOnlyFields.filter(field => _.has(body, field)) if (restrictedFieldsSent.length > 0) { @@ -671,6 +692,52 @@ async function updateOrg (req, res, next) { } } + if (unresolvedKeys?.length) { + const reviewRepo = req.ctx.repositories.getReviewObjectRepository() + partialReview = await reviewRepo.getOrgReviewObjectByOrgUUID(org.UUID, isSecretariat, { session }) + const allowedPaths = [ + ...getConstants().JOINT_APPROVAL_FIELDS.filter(path => !['oversees', 'top_level_root'].includes(path)), + 'contact_info.emails', 'contact_info.websites' + ] + let invalidReason + if (!partialReview) { + invalidReason = 'A pending organization review is required for unresolved fields.' + } else if (unresolvedKeys.some(path => !allowedPaths.includes(path))) { + invalidReason = 'Unresolved fields must be supported joint approval paths; relationship fields are not supported.' + } else if (unresolvedKeys.some(path => unresolvedKeys.some(other => other.startsWith(path + '.')))) { + invalidReason = 'Unresolved fields must not contain overlapping paths.' + } else { + const published = JSON.parse(JSON.stringify(org)) + const proposed = JSON.parse(JSON.stringify(partialReview.new_review_data)) + normalizeOrgCveWebsiteUpdateDate(published, { output: true }) + normalizeOrgCveWebsiteUpdateDate(proposed, { output: true }) + if (unresolvedKeys.some(path => _.has(published, path) === _.has(proposed, path) && _.isEqual(_.get(published, path), _.get(proposed, path)))) { + invalidReason = 'Each unresolved field must have a pending change.' + } + } + if (invalidReason) { + await session.abortTransaction() + return res.status(400).json({ message: 'Parameters were invalid', errors: [{ instancePath: '/x_unresolved_keys', message: invalidReason }] }) + } + + // Keep the established conflicting-name error even when the rename is deferred. + if (body.new_short_name && body.short_name !== shortName && body.short_name !== body.new_short_name) { + const validation = await validateRequestedShortName(req, repo, body, shortName, session) + await session.abortTransaction() + return res.status(validation.status).json(validation.response) + } + body = copyReviewFields(_.cloneDeep(body), org, unresolvedKeys) + if (unresolvedKeys.includes('short_name')) delete body.new_short_name + + // Stored optional nulls and Dates must survive the write. Validate a wire-format + // copy, including dependencies such as a deferred CNA authority requiring a quota. + const effectiveValidation = repo.validateOrg(deepRemoveEmpty(JSON.parse(JSON.stringify(body)))) + if (!effectiveValidation.isValid) { + await session.abortTransaction() + return res.status(400).json({ message: 'Parameters were invalid', errors: effectiveValidation.errors }) + } + } + const shortNameValidation = await validateRequestedShortName(req, repo, body, shortName, session) if (shortNameValidation.status) { await session.abortTransaction() @@ -678,7 +745,7 @@ async function updateOrg (req, res, next) { } // Handle secretariat "stomping" of pending review objects - if (isSecretariat) { + if (isSecretariat && !partialReview) { const reviewRepo = req.ctx.repositories.getReviewObjectRepository() const pendingReview = await reviewRepo.getOrgReviewObjectByOrgShortname(shortName, isSecretariat, { session }) @@ -715,7 +782,23 @@ async function updateOrg (req, res, next) { isSecretariat, requester.orgUUID ) - jointApprovalRequired = _.get(updatedOrg, 'joint_approval_required', false) + if (partialReview) { + // Use the saved raw state so a later approval cannot restore denied proposals, + // stale resolved values, or values removed by full replacement or role changes. + const savedOrg = await repo.findOneByUUID(org.UUID, { session, lean: true }) + if (unresolvedKeys.some(path => _.has(org, path) !== _.has(savedOrg, path) || !_.isEqual(_.get(org, path), _.get(savedOrg, path)))) { + await session.abortTransaction() + return res.status(400).json({ + message: 'Parameters were invalid', + errors: [{ instancePath: '/x_unresolved_keys', message: 'The update would change an unresolved field. Resolve dependent changes together.' }] + }) + } + const remainingProposal = copyReviewFields(savedOrg, partialReview.new_review_data, unresolvedKeys) + const reviewRepo = req.ctx.repositories.getReviewObjectRepository() + const savedReview = await reviewRepo.updateReviewOrgObject(remainingProposal, partialReview.uuid, { session }) + if (!savedReview) throw new Error('Pending organization review could not be updated.') + } + jointApprovalRequired = Boolean(partialReview) || _.get(updatedOrg, 'joint_approval_required', false) _.unset(updatedOrg, 'joint_approval_required') // append previous conversations to any conversations that are in the org already const currentConversations = Array.isArray(updatedOrg?.conversation) ? updatedOrg.conversation : [] diff --git a/test/integration-tests/registry-org/registryOrgWithJointReviewTest.js b/test/integration-tests/registry-org/registryOrgWithJointReviewTest.js index d61e4a79a..62dc9996e 100644 --- a/test/integration-tests/registry-org/registryOrgWithJointReviewTest.js +++ b/test/integration-tests/registry-org/registryOrgWithJointReviewTest.js @@ -7,6 +7,14 @@ chai.use(require('chai-http')) const constants = require('../constants.js') const app = require('../../../src/index.js') +const { randomUUID } = require('crypto') +const sinon = require('sinon') +const BaseOrg = require('../../../src/model/baseorg') +const BaseUser = require('../../../src/model/baseuser') +const ReviewObject = require('../../../src/model/reviewobject') +const Audit = require('../../../src/model/audit') +const Conversation = require('../../../src/model/conversation') +const ReviewObjectRepository = require('../../../src/repositories/reviewObjectRepository') const secretariatHeaders = { ...constants.headers, 'content-type': 'application/json' } @@ -124,6 +132,342 @@ const testRegistryOrgAdminUserNewShortName = { } describe('Testing Joint approval', () => { + describe('Partial joint approval through registry PUT', () => { + let original + let proposal + let review + let userUUIDs + + beforeEach(async () => { + userUUIDs = [] + original = { + short_name: `partial_${randomUUID().slice(0, 8)}`, + long_name: 'Published name', + authority: ['CNA'], + id_quota: 100, + disabled: false, + industry: 'Published industry', + partner_country: 'US', + contact_info: { + websites: ['https://published.example'], + emails: ['published@example.com', 'second@example.com'] + } + } + const created = await chai.request(app).post('/api/registry/org').set(secretariatHeaders).send(original) + expect(created, JSON.stringify(created.body)).to.have.status(200) + original.UUID = created.body.created.UUID + proposal = { + ...original, + long_name: 'Proposed name', + industry: 'Proposed industry', + partner_country: 'CA', + contact_info: { websites: ['https://proposed.example'], emails: ['proposed@example.com'] } + } + review = await new ReviewObjectRepository().createReviewOrgObject(proposal, 'original_requester') + }) + + afterEach(async () => { + sinon.restore() + await BaseUser.deleteMany({ UUID: { $in: userUUIDs } }) + await ReviewObject.deleteMany({ target_object_uuid: original.UUID }) + await Conversation.deleteMany({ target_uuid: original.UUID }) + await Audit.deleteMany({ target_uuid: { $in: [original.UUID, ...userUUIDs] } }) + await BaseOrg.deleteMany({ UUID: original.UUID }) + }) + + function update (body) { + return chai.request(app).put(`/api/registry/org/${original.short_name}`).set(secretariatHeaders).send(body) + } + + async function snapshot () { + return { + org: await BaseOrg.findOne({ UUID: original.UUID }).read('primary').lean(), + reviews: await ReviewObject.find({ target_object_uuid: original.UUID }).read('primary').lean(), + audit: await Audit.find({ target_uuid: original.UUID }).read('primary').lean(), + conversations: await Conversation.find({ target_uuid: original.UUID }).read('primary').lean() + } + } + + it('publishes accepted fields, drops denied proposals, and keeps undecided fields pending', async () => { + const response = await update({ + ...original, + long_name: proposal.long_name, + contact_info: { ...original.contact_info, websites: proposal.contact_info.websites }, + conversation: { body: 'Name and website accepted; country denied.', visibility: 'public' }, + x_unresolved_keys: ['industry', 'contact_info.emails'] + }) + expect(response, JSON.stringify(response.body)).to.have.status(200) + expect(Object.keys(response.body)).to.have.members(['message', 'updated']) + expect(response.body.message).to.include('joint approval is required') + expect(response.body.updated.long_name).to.equal(proposal.long_name) + expect(response.body.updated.industry).to.equal(original.industry) + expect(response.body.updated.partner_country).to.equal(original.partner_country) + expect(response.body.updated.contact_info).to.deep.equal({ + websites: proposal.contact_info.websites, emails: original.contact_info.emails + }) + const pending = await ReviewObject.findOne({ uuid: review.uuid }).read('primary').lean() + expect(pending.status).to.equal('pending') + expect(pending.target_object_uuid).to.equal(original.UUID) + expect(pending.requester).to.deep.equal(review.requester) + expect(pending.created).to.deep.equal(review.created) + expect(pending).to.not.have.property('approver') + expect(pending).to.not.have.property('rejector') + expect(pending.new_review_data.long_name).to.equal(proposal.long_name) + expect(pending.new_review_data.partner_country).to.equal(original.partner_country) + expect(pending.new_review_data.industry).to.equal(proposal.industry) + expect(pending.new_review_data.contact_info.emails).to.deep.equal(proposal.contact_info.emails) + const state = await snapshot() + expect(JSON.stringify(state)).to.not.include('x_unresolved_keys') + expect(state.audit[0].history.at(-1).audit_object.industry).to.equal(original.industry) + expect(state.conversations).to.have.lengthOf(1) + expect(state.conversations[0].target_uuid).to.equal(original.UUID) + expect(state.conversations[0].author_role).to.equal('Secretariat') + expect(response.body.updated.conversation[0].body).to.equal(state.conversations[0].body) + + const approved = await chai.request(app).put(`/api/review/${review.uuid}/approve`).set(secretariatHeaders).send({}) + expect(approved, JSON.stringify(approved.body)).to.have.status(200) + expect(approved.body.long_name).to.equal(proposal.long_name) + expect(approved.body.industry).to.equal(proposal.industry) + expect(approved.body.partner_country).to.equal(original.partner_country) + expect(approved.body.contact_info).to.deep.equal(proposal.contact_info) + }) + + it('supports repeated partial decisions and closes the same review when the list becomes empty', async () => { + const first = await update({ ...original, long_name: proposal.long_name, x_unresolved_keys: ['industry', 'contact_info'] }) + expect(first, JSON.stringify(first.body)).to.have.status(200) + const secondBody = { ...original, long_name: proposal.long_name, industry: proposal.industry } + const second = await update({ ...secondBody, x_unresolved_keys: ['contact_info'] }) + expect(second, JSON.stringify(second.body)).to.have.status(200) + let pending = (await snapshot()).reviews[0] + expect(pending).to.include({ uuid: review.uuid, status: 'pending' }) + expect(pending.new_review_data.industry).to.equal(proposal.industry) + const final = await update({ ...secondBody, contact_info: proposal.contact_info, x_unresolved_keys: [] }) + expect(final, JSON.stringify(final.body)).to.have.status(200) + pending = (await snapshot()).reviews[0] + expect(pending).to.include({ uuid: review.uuid, status: 'approved' }) + expect(final.body.message).to.not.include('joint approval is required') + }) + + it('keeps every proposal open and preserves published arrays when all changed paths are unresolved', async () => { + const response = await update({ ...proposal, x_unresolved_keys: ['long_name', 'industry', 'partner_country', 'contact_info'] }) + expect(response, JSON.stringify(response.body)).to.have.status(200) + const state = await snapshot() + for (const field of ['long_name', 'industry', 'partner_country', 'contact_info']) { + expect(state.org[field]).to.deep.equal(original[field]) + expect(state.reviews[0].new_review_data[field]).to.deep.equal(proposal[field]) + } + expect(state.reviews[0].status).to.equal('pending') + }) + + it('preserves null, absent values, empty arrays, false, and Dates without persisting the validation clone', async () => { + const publishedDate = new Date('2025-01-02T00:00:00.000Z') + await BaseOrg.collection.updateOne({ UUID: original.UUID }, { + $set: { charter_or_scope: null, tl_root_start_date: publishedDate, is_cna_discussion_list: false }, + $unset: { industry: 1 } + }) + proposal = { + ...proposal, + charter_or_scope: 'Proposed scope', + tl_root_start_date: '2026-01-02T00:00:00.000Z', + is_cna_discussion_list: true, + contact_info: { websites: [], emails: [] } + } + await new ReviewObjectRepository().updateReviewOrgObject(proposal, review.uuid) + const response = await update({ + ...proposal, + x_unresolved_keys: ['charter_or_scope', 'industry', 'tl_root_start_date', 'is_cna_discussion_list', 'contact_info'] + }) + expect(response, JSON.stringify(response.body)).to.have.status(200) + const state = await snapshot() + expect(state.org).to.have.property('charter_or_scope', null) + expect(state.org).to.not.have.property('industry') + expect(state.org.tl_root_start_date).to.deep.equal(publishedDate) + expect(state.org.is_cna_discussion_list).to.equal(false) + expect(state.org.contact_info).to.deep.equal(original.contact_info) + expect(state.reviews[0].new_review_data.contact_info).to.deep.equal({ websites: [], emails: [] }) + expect(state.reviews[0].new_review_data.industry).to.equal(proposal.industry) + }) + + it('retains proposed absence and null without resurrecting the published values on later approval', async () => { + delete proposal.industry + proposal.partner_country = null + await new ReviewObjectRepository().updateReviewOrgObject(proposal, review.uuid) + const response = await update({ ...original, x_unresolved_keys: ['industry', 'partner_country'] }) + expect(response, JSON.stringify(response.body)).to.have.status(200) + const pending = (await snapshot()).reviews[0] + expect(pending.new_review_data).to.not.have.property('industry') + expect(pending.new_review_data).to.have.property('partner_country', null) + const approved = await chai.request(app).put(`/api/review/${review.uuid}/approve`).set(secretariatHeaders).send({}) + expect(approved, JSON.stringify(approved.body)).to.have.status(200) + const state = await snapshot() + expect(state.org).to.not.have.property('industry') + expect(state.org).to.have.property('partner_country', null) + }) + + it('preserves the review association across an accepted rename and subsequent normal approval', async () => { + const newName = `renamed_${randomUUID().slice(0, 8)}` + const response = await update({ ...original, new_short_name: newName, x_unresolved_keys: ['industry'] }) + expect(response, JSON.stringify(response.body)).to.have.status(200) + const pending = await chai.request(app).get(`/api/review/org/${newName}`).set(secretariatHeaders) + expect(pending.body).to.include({ uuid: review.uuid, target_object_uuid: original.UUID, status: 'pending' }) + expect(pending.body.new_review_data.short_name).to.equal(newName) + const approved = await chai.request(app).put(`/api/review/${review.uuid}/approve`).set(secretariatHeaders).send({}) + expect(approved, JSON.stringify(approved.body)).to.have.status(200) + expect(approved.body.short_name).to.equal(newName) + expect(approved.body.industry).to.equal(proposal.industry) + }) + + it('defers a canonical short_name proposal even when new_short_name is submitted', async () => { + proposal.short_name = `pending_${randomUUID().slice(0, 8)}` + await new ReviewObjectRepository().updateReviewOrgObject(proposal, review.uuid) + const response = await update({ ...original, new_short_name: proposal.short_name, x_unresolved_keys: ['short_name'] }) + expect(response, JSON.stringify(response.body)).to.have.status(200) + expect(response.body.updated.short_name).to.equal(original.short_name) + const state = await snapshot() + expect(state.reviews[0].new_review_data.short_name).to.equal(proposal.short_name) + expect(state.reviews[0].new_review_data).to.not.have.property('new_short_name') + const before = await snapshot() + const conflict = await update({ ...original, short_name: proposal.short_name, new_short_name: 'different_name', x_unresolved_keys: ['short_name'] }) + expect(conflict).to.have.status(400) + expect(await snapshot()).to.deep.equal(before) + }) + + it('preserves historical Secretariat-only proposals at known joint approval paths', async () => { + await BaseOrg.updateOne({ UUID: original.UUID }, { $set: { partner_number: 'old', program_data: { status: 'Active' } } }) + proposal.partner_number = 'new' + proposal.program_data = { status: 'Inactive' } + await new ReviewObjectRepository().updateReviewOrgObject(proposal, review.uuid) + const response = await update({ ...original, x_unresolved_keys: ['partner_number', 'program_data.status'] }) + expect(response, JSON.stringify(response.body)).to.have.status(200) + const state = await snapshot() + expect(state.org.partner_number).to.equal('old') + expect(state.org.program_data.status).to.equal('Active') + expect(state.reviews[0].new_review_data.partner_number).to.equal('new') + expect(state.reviews[0].new_review_data.program_data.status).to.equal('Inactive') + }) + + it('rejects malformed transport metadata before null and object cleanup', async () => { + const before = await snapshot() + for (const keys of [null, {}, 'industry', [null], [1], [''], ['industry', 'industry']]) { + const response = await update({ ...original, x_unresolved_keys: keys }) + expect(response, JSON.stringify(keys)).to.have.status(400) + expect(response.body.error).to.equal('BAD_INPUT') + expect(await snapshot()).to.deep.equal(before) + } + }) + + it('rejects unsupported, overlapping, and unchanged paths without writes', async () => { + const before = await snapshot() + for (const keys of [ + ['reports_to'], ['oversees'], ['top_level_root'], ['UUID'], ['new_short_name'], + ['__proto__.polluted'], ['contact_info.emails.0'], ['contact_info', 'contact_info.emails'], ['id_quota'] + ]) { + const response = await update({ ...original, x_unresolved_keys: keys }) + expect(response, JSON.stringify(keys)).to.have.status(400) + expect(response.body.errors[0].instancePath).to.equal('/x_unresolved_keys') + expect(await snapshot()).to.deep.equal(before) + } + }) + + it('requires a pending review only for nonempty lists and retains missing-org behavior', async () => { + await ReviewObject.deleteOne({ uuid: review.uuid }) + const before = await snapshot() + const missing = await update({ ...original, x_unresolved_keys: ['industry'] }) + expect(missing).to.have.status(400) + expect(await snapshot()).to.deep.equal(before) + const empty = await update({ ...original, x_unresolved_keys: [] }) + expect(empty, JSON.stringify(empty.body)).to.have.status(200) + expect(empty.body.message).to.not.include('joint approval is required') + const noOrg = await chai.request(app).put('/api/registry/org/nonexistent_partial').set(secretariatHeaders) + .send({ ...original, x_unresolved_keys: ['industry'] }) + expect(noOrg).to.have.status(404) + expect(noOrg.body.error).to.equal('ORG_DNE_PARAM') + }) + + it('retains the existing rejection status when an empty list closes a mixed decision', async () => { + const response = await update({ ...original, long_name: proposal.long_name, x_unresolved_keys: [] }) + expect(response, JSON.stringify(response.body)).to.have.status(200) + expect((await snapshot()).reviews[0].status).to.equal('rejected') + }) + + it('rejects metadata from an otherwise authorized same-organization admin', async () => { + const created = await chai.request(app).post(`/api/registry/org/${original.short_name}/user`).set(secretariatHeaders) + .send({ username: 'partial_admin', name: { first: 'Partial', last: 'Admin' }, status: 'active', role: 'ADMIN' }) + expect(created, JSON.stringify(created.body)).to.have.status(200) + userUUIDs.push(created.body.created.UUID) + const auth = { + 'CVE-API-ORG': original.short_name, + 'CVE-API-USER': created.body.created.username, + 'CVE-API-KEY': created.body.created.secret + } + const before = await snapshot() + for (const keys of [[], ['industry']]) { + const response = await chai.request(app).put(`/api/registry/org/${original.short_name}`).set(auth) + .send({ ...original, x_unresolved_keys: keys }) + expect(response).to.have.status(403) + expect(response.body.error).to.equal('SECRETARIAT_ONLY') + expect(response.body.message).to.include('x_unresolved_keys') + expect(await snapshot()).to.deep.equal(before) + } + }) + + it('validates the full input and authority-dependent effective payload before writing', async () => { + proposal.authority = ['ROOT'] + await new ReviewObjectRepository().updateReviewOrgObject(proposal, review.uuid) + const before = await snapshot() + const invalidInput = await update({ ...original, industry: 1, x_unresolved_keys: ['industry'] }) + expect(invalidInput).to.have.status(400) + const { id_quota: omittedQuota, ...rootBody } = original + const invalidEffective = await update({ ...rootBody, authority: ['ROOT'], x_unresolved_keys: ['authority'] }) + expect(invalidEffective).to.have.status(400) + expect(await snapshot()).to.deep.equal(before) + const validEffective = await update({ ...original, x_unresolved_keys: ['authority'] }) + expect(validEffective, JSON.stringify(validEffective.body)).to.have.status(200) + expect(validEffective.body.updated.authority).to.deep.equal(['CNA']) + expect(validEffective.body.updated.id_quota).to.equal(original.id_quota) + expect((await snapshot()).reviews[0].new_review_data.authority).to.deep.equal(['ROOT']) + }) + + it('preserves an absent nested array while holding its proposed value', async () => { + await BaseOrg.collection.updateOne({ UUID: original.UUID }, { $unset: { 'contact_info.emails': 1 } }) + const response = await update({ ...original, x_unresolved_keys: ['contact_info.emails'] }) + expect(response, JSON.stringify(response.body)).to.have.status(200) + const state = await snapshot() + expect(state.org.contact_info).to.not.have.property('emails') + expect(state.org.contact_info.websites).to.deep.equal(original.contact_info.websites) + expect(state.reviews[0].new_review_data.contact_info.emails).to.deep.equal(proposal.contact_info.emails) + }) + + it('rejects a role change that would discard an unresolved published field and rolls back all writes', async () => { + await BaseOrg.collection.updateOne({ UUID: original.UUID }, { $set: { product_list: null } }) + await new ReviewObjectRepository().updateReviewOrgObject({ ...proposal, product_list: 'Proposed products' }, review.uuid) + const before = await snapshot() + const body = { ...original, authority: ['ROOT'], conversation: { body: 'Deferred products', visibility: 'public' }, x_unresolved_keys: ['product_list'] } + delete body.id_quota + const response = await update(body) + expect(response, JSON.stringify(response.body)).to.have.status(400) + expect(await snapshot()).to.deep.equal(before) + }) + + it('rolls back organization, audit, conversation, and review changes if the post-save review update fails', async () => { + const before = await snapshot() + const save = ReviewObjectRepository.prototype.updateReviewOrgObject + sinon.stub(ReviewObjectRepository.prototype, 'updateReviewOrgObject').callsFake(async function (...args) { + await save.apply(this, args) + throw new Error('Injected review persistence failure') + }) + const response = await update({ + ...original, + long_name: proposal.long_name, + conversation: { body: 'This transaction must roll back', visibility: 'public' }, + x_unresolved_keys: ['industry'] + }) + expect(response).to.have.status(500) + expect(JSON.stringify(response.body)).to.not.include('Injected') + expect(await snapshot()).to.deep.equal(before) + }) + }) + describe('Admin user attempts to edit a joint approval field', () => { let secret let orgUUID From 4d66b556d3321e9769faed78cea73db7bfbafe1e Mon Sep 17 00:00:00 2001 From: David T Rocca