From 72eb6b69dc758cfbad2a8ea77dc3cd45542ecf02 Mon Sep 17 00:00:00 2001 From: David T Rocca Date: Tue, 17 Nov 2026 11:07:36 -0500 Subject: [PATCH 1/6] Preserve organization relationships in audit snapshots Capture derived TLR and hierarchy values, audit indirect relationship changes in the existing transaction, and preserve historical snapshots. Add regression coverage for reassignment, renames, role changes, deletion, and rollback. --- api-docs/openapi.json | 2 +- schemas/Audit.json | 6 +- src/controller/registry.controller/index.js | 2 +- .../org.registry.controller.js | 2 +- src/repositories/baseOrgRepository.js | 172 +++------------- src/repositories/baseOrgRepositoryHelpers.js | 89 ++++++-- src/repositories/orgRelationships.js | 127 ++++++++++++ .../audit/registryOrgCreatesAuditTest.js | 194 +++++++++++++++++- .../org/baseOrgRepositoryHelpersTest.js | 30 +++ test/unit-tests/org/legacy/orgCreateTest.js | 1 + 10 files changed, 452 insertions(+), 173 deletions(-) create mode 100644 src/repositories/orgRelationships.js diff --git a/api-docs/openapi.json b/api-docs/openapi.json index 1573a22dd..35b605ed6 100644 --- a/api-docs/openapi.json +++ b/api-docs/openapi.json @@ -4553,7 +4553,7 @@ "Data Registry — Organizations" ], "summary": "Assigns an organization to report to a ROOT organization (accessible to Secretariat only)", - "description": "

Access Control

User must belong to an organization with the Secretariat role.

Expected Behavior

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.

", + "description": "

Access Control

User must belong to an organization with the Secretariat role.

Expected Behavior

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.

", "operationId": "registryOrgAddOverseeRelationship", "parameters": [ { diff --git a/schemas/Audit.json b/schemas/Audit.json index 348cc210e..5ca9223bd 100644 --- a/schemas/Audit.json +++ b/schemas/Audit.json @@ -25,7 +25,7 @@ }, "audit_object": { "type": "object", - "description": "Complete snapshot of the organization object after the change" + "description": "Snapshot of the organization after the change. Automatically generated snapshots of persisted organizations include the derived top_level_root when available and _hierarchy at the time of the change. Older or manually supplied entries may omit these fields." }, "change_author": { "$ref": "#/definitions/uuidType", @@ -50,7 +50,7 @@ }, "history": { "type": "array", - "description": "Array of audit history entries, ordered chronologically", + "description": "Array of audit history entries, ordered chronologically, including changes to an organization's derived relationships caused by other organizations", "items": { "$ref": "#/definitions/historyEntry" }, @@ -61,4 +61,4 @@ "target_uuid" ], "additionalProperties": false -} \ No newline at end of file +} diff --git a/src/controller/registry.controller/index.js b/src/controller/registry.controller/index.js index a2612de62..7511433fe 100644 --- a/src/controller/registry.controller/index.js +++ b/src/controller/registry.controller/index.js @@ -1339,7 +1339,7 @@ router.post('/registry/org/:shortname/oversees/:shortname2/add',

User must belong to an organization with the Secretariat role.

Expected Behavior

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.

' + 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.

' #swagger.parameters['shortname'] = { description: 'The shortname of the overseeing ROOT organization' } #swagger.parameters['shortname2'] = { description: 'The shortname of the reporting organization' } #swagger.parameters['$ref'] = [ diff --git a/src/controller/registry.controller/org.registry.controller.js b/src/controller/registry.controller/org.registry.controller.js index 3a96398fa..84767895c 100644 --- a/src/controller/registry.controller/org.registry.controller.js +++ b/src/controller/registry.controller/org.registry.controller.js @@ -810,7 +810,7 @@ async function deleteOrg (req, res, next) { } targetOrgUUID = org.UUID - await repo.deleteOrg(shortName, { session }) + await repo.deleteOrg(shortName, { session }, req.ctx.userUUID) await session.commitTransaction() } catch (deleteErr) { if (session?.inTransaction()) { diff --git a/src/repositories/baseOrgRepository.js b/src/repositories/baseOrgRepository.js index 300ce1bbf..8e21786d0 100644 --- a/src/repositories/baseOrgRepository.js +++ b/src/repositories/baseOrgRepository.js @@ -1,4 +1,5 @@ const BaseRepository = require('./baseRepository') +const { createOrgRelationships, ORG_RELATIONSHIP_PROJECTION } = require('./orgRelationships') const BaseOrgModel = require('../model/baseorg') const BaseUserModel = require('../model/baseuser') const CNAOrgModel = require('../model/cnaorg') @@ -17,6 +18,7 @@ const { handleShortNameUpdate, processJointApprovalAndMerge, createAuditLogEntry, + createAuditLogEntries, handleAuthorityModelChange } = require('./baseOrgRepositoryHelpers') const { normalizeOrgCveWebsiteUpdateDate } = require('../utils/dateOnly') @@ -83,86 +85,6 @@ function decorateCnaRelationships (activeOrgs, hierarchyOrgs) { }) } -function buildOrgHierarchy (orgs, orgUUID) { - const orgsByUUID = new Map(orgs.filter(org => org.UUID).map(org => [org.UUID, org])) - const childrenByUUID = new Map() - const parentByUUID = new Map() - - for (const org of orgsByUUID.values()) { - const children = [] - if (org.authority?.includes('ROOT') && Array.isArray(org.oversees)) { - for (const childUUID of org.oversees) { - const child = orgsByUUID.get(childUUID) - if (!child || childUUID === org.UUID) continue - if (child.authority?.includes('ROOT') && child.is_top_level_root === true) continue - children.push(childUUID) - if (!parentByUUID.has(childUUID)) parentByUUID.set(childUUID, org.UUID) - } - } - childrenByUUID.set(org.UUID, children) - } - - // Ancestors expose only the branch leading to the requested organization. - const ancestorChildren = new Map() - let startUUID = orgUUID - if (orgUUID !== undefined) { - if (!orgsByUUID.has(orgUUID)) return [] - const path = new Set([orgUUID]) - while (parentByUUID.has(startUUID)) { - const parentUUID = parentByUUID.get(startUUID) - if (path.has(parentUUID)) break - ancestorChildren.set(parentUUID, [startUUID]) - path.add(parentUUID) - startUUID = parentUUID - } - } - - const hierarchy = [] - const visited = new Set() - const appendBranch = rootUUID => { - const pending = [{ UUID: rootUUID, target: hierarchy }] - while (pending.length > 0) { - const { UUID, target } = pending.pop() - if (visited.has(UUID)) continue - visited.add(UUID) - - const org = orgsByUUID.get(UUID) - const authority = Array.isArray(org.authority) ? org.authority : [] - const node = { - UUID: org.UUID, - short_name: org.short_name || '', - long_name: org.long_name || '', - authority, - children: [] - } - if (authority.includes('ROOT')) node.is_top_level_root = org.is_top_level_root === true - if (authority.includes('CNA')) node.is_last_resort = org.is_last_resort === true - target.push(node) - - const children = ancestorChildren.get(UUID) || childrenByUUID.get(UUID) - // Visit in stored order without recursive calls or repeated database reads. - for (let i = children.length - 1; i >= 0; i--) { - pending.push({ UUID: children[i], target: node.children }) - } - } - } - - if (orgUUID !== undefined) { - appendBranch(startUUID) - return hierarchy - } - - for (const UUID of orgsByUUID.keys()) { - if (!parentByUUID.has(UUID)) appendBranch(UUID) - } - // Retain disconnected cyclic components, omitting already visited edges. - for (const UUID of orgsByUUID.keys()) { - if (!visited.has(UUID)) appendBranch(UUID) - } - - return hierarchy -} - const PROGRAM_DATA_STATUS_BY_LOWERCASE = new Map([ ['active', 'Active'], ['inactive', 'Inactive'], @@ -828,22 +750,22 @@ class BaseOrgRepository extends BaseRepository { const overseeingOrg = await RootOrgModel.findOne({ short_name: overseeingOrgShortName }, null, options) const originalOverseeingOrg = overseeingOrg.toObject() const previousOverseeingOrgs = await RootOrgModel.find({ oversees: reportingOrgUUID }, null, options) + const changes = [] + const orgsToSave = [] for (const previousOverseeingOrg of previousOverseeingOrgs) { if (previousOverseeingOrg.UUID === overseeingOrg.UUID) continue const originalPreviousOverseeingOrg = previousOverseeingOrg.toObject() previousOverseeingOrg.oversees = previousOverseeingOrg.oversees.filter(uuid => uuid !== reportingOrgUUID) - if (requestingUserUUID) { - await createAuditLogEntry(previousOverseeingOrg, originalPreviousOverseeingOrg, requestingUserUUID, options) - } - await previousOverseeingOrg.save(options) + changes.push({ before: originalPreviousOverseeingOrg, after: previousOverseeingOrg.toObject() }) + orgsToSave.push(previousOverseeingOrg) } overseeingOrg.oversees = [...new Set([...(overseeingOrg.oversees || []), reportingOrgUUID])] - if (requestingUserUUID) { - await createAuditLogEntry(overseeingOrg, originalOverseeingOrg, requestingUserUUID, options) - } - await overseeingOrg.save(options) + changes.push({ before: originalOverseeingOrg, after: overseeingOrg.toObject() }) + orgsToSave.push(overseeingOrg) + await createAuditLogEntries(changes, requestingUserUUID, options) + for (const org of orgsToSave) await org.save(options) return overseeingOrg } @@ -953,19 +875,10 @@ class BaseOrgRepository extends BaseRepository { */ async getOrgHierarchy (orgUUID) { const orgs = await BaseOrgModel.find({}) - .select({ - _id: false, - UUID: true, - short_name: true, - long_name: true, - oversees: true, - authority: true, - is_top_level_root: true, - is_last_resort: true - }) + .select(ORG_RELATIONSHIP_PROJECTION) .lean() - return buildOrgHierarchy(orgs, orgUUID) + return createOrgRelationships(orgs).hierarchy(orgUUID) } /** @@ -1250,17 +1163,14 @@ class BaseOrgRepository extends BaseRepository { throw new Error("Unknown Org type requested. Please use either 'SECRETARIAT', 'CNA', 'ADP', 'BULK_DOWNLOAD', or 'ROOT' as the authority role.") } - // ADD AUDIT ENTRY AUTOMATICALLY for the registry object - if (requestingUserUUID) { + if (registryObject) { + await createAuditLogEntry(registryObjectRaw, null, requestingUserUUID, options) + } else if (requestingUserUUID) { + // Preserve the existing audit of proposed creations. Pending proposals do + // not change the live relationship graph or other organizations' histories. try { const AuditRepository = require('./auditRepository') - const auditRepo = new AuditRepository() - await auditRepo.appendToAuditHistoryForOrg( - registryObjectRaw.UUID, - registryObjectRaw, - requestingUserUUID, - options - ) + await new AuditRepository().appendToAuditHistoryForOrg(registryObjectRaw.UUID, registryObjectRaw, requestingUserUUID, options) } catch (auditError) { console.error('Audit entry creation failed:', auditError) } @@ -1380,41 +1290,7 @@ class BaseOrgRepository extends BaseRepository { } normalizeRootOrgQuota(registryOrg) - // ADD AUDIT ENTRY AUTOMATICALLY for the registry object before it gets saved. - if (requestingUserUUID) { - try { - const AuditRepository = require('./auditRepository') - const auditRepo = new AuditRepository() - // Seed the audit history with the existing org data if an audit document doesn't already exist. - // This is necessary because older entities might not have an audit log yet, and we want - // the first entry to be their baseline state before this update. - await auditRepo.seedAuditHistoryForOrg( - registryOrg.UUID, - originalRegistryOrgObject, - requestingUserUUID, - options - ) - // Get the org state before save for comparison - const beforeUpdateObject = originalRegistryOrgObject - const afterUpdateObject = registryOrg.toObject() - - // Clean objects for comparison (remove Mongoose metadata) - const cleanBefore = _.omit(beforeUpdateObject, ['_id', '__v', '__t', 'createdAt', 'updatedAt']) - const cleanAfter = _.omit(afterUpdateObject, ['_id', '__v', '__t', 'createdAt', 'updatedAt']) - - // Only add audit entry if there are changes - if (!_.isEqual(cleanBefore, cleanAfter)) { - await auditRepo.appendToAuditHistoryForOrg( - registryOrg.UUID, - registryOrg.toObject(), - requestingUserUUID, - options - ) - } - } catch (auditError) { - console.error('Audit entry creation failed:', auditError) - } - } + await createAuditLogEntry(registryOrg, originalRegistryOrgObject, requestingUserUUID, options, true) await registryOrg.save(options) if (isLegacyObject) { @@ -1524,9 +1400,8 @@ class BaseOrgRepository extends BaseRepository { conversationArray.push(await conversationRepo.createConversation(registryOrg.UUID, conversation, requestingUser, isSecretariat, executeOptions)) } - await createAuditLogEntry(registryOrg, originalRegistryOrgObject, requestingUserUUID, executeOptions) - updatedRegistryOrg = await handleAuthorityModelChange(updatedRegistryOrg, originalRoles, executeOptions) + await createAuditLogEntry(updatedRegistryOrg, originalRegistryOrgObject, requestingUserUUID, executeOptions) try { await updatedRegistryOrg.save(executeOptions) @@ -1554,9 +1429,14 @@ class BaseOrgRepository extends BaseRepository { * @param {string} shortName - The short name of the organization to delete. * @param {object} [options={}] - Optional settings for the repository query. * + * @param {string|null} [requestingUserUUID=null] - The actor used to audit surviving organizations' relationship changes. * @returns {Promise} */ - async deleteOrg (shortName, options = {}) { + async deleteOrg (shortName, options = {}, requestingUserUUID = null) { + if (requestingUserUUID) { + const originalOrg = await this.findOneByShortName(shortName, options) + if (originalOrg) await createAuditLogEntry(null, originalOrg.toObject(), requestingUserUUID, options) + } await BaseOrgModel.deleteOne({ short_name: shortName }, options) } diff --git a/src/repositories/baseOrgRepositoryHelpers.js b/src/repositories/baseOrgRepositoryHelpers.js index 96cf2bf1c..3fe9bb659 100644 --- a/src/repositories/baseOrgRepositoryHelpers.js +++ b/src/repositories/baseOrgRepositoryHelpers.js @@ -6,6 +6,8 @@ const ADPOrgModel = require('../model/adporg') const BulkDownloadModel = require('../model/bulkdownloadorg') const SecretariatOrgModel = require('../model/secretariatorg') const RootOrgModel = require('../model/rootorg') +const { createOrgRelationships, ORG_RELATIONSHIP_PROJECTION } = require('./orgRelationships') +const AUDIT_METADATA_FIELDS = ['_id', '__v', '__t', 'createdAt', 'updatedAt'] // Check both the stored and requested roles so removing SECRETARIAT cannot // bypass the protection in the same update. Omitted flags must stay enabled @@ -175,40 +177,86 @@ async function processJointApprovalAndMerge (registryOrg, registryObjectRaw, rev * @async * @function createAuditLogEntry * @description Creates an audit log tracing changes to an organization. It seeds the history if none exists, and appends the new change if differences are detected. - * @param {object} registryOrg - The updated registry organization Mongoose document. - * @param {object} originalRegistryOrgObject - A plain javascript object representing the organization before updates were applied. + * @param {object|null} registryOrg - The updated organization, or null for deletion. + * @param {object|null} originalRegistryOrgObject - The organization before updates, or null for creation. * @param {string} requestingUserUUID - The UUID of the user who made the request. * @param {object} options - Mongoose options for database queries. + * @param {boolean} preserveMetadata - Retains metadata for the legacy partial-update snapshot contract. */ -async function createAuditLogEntry (registryOrg, originalRegistryOrgObject, requestingUserUUID, options) { +async function createAuditLogEntry (registryOrg, originalRegistryOrgObject, requestingUserUUID, options = {}, preserveMetadata = false) { + if (!requestingUserUUID) return + const after = registryOrg?.toObject ? registryOrg.toObject() : registryOrg + return createAuditLogEntries([{ before: originalRegistryOrgObject, after, preserveMetadata }], requestingUserUUID, options) +} + +// A reparenting operation changes several stored documents. Resolve its entire +// before/after graph together, never an intermediate detached relationship. +async function createAuditLogEntries (changes, requestingUserUUID, options = {}) { if (!requestingUserUUID) return try { const AuditRepository = require('./auditRepository') const auditRepo = new AuditRepository() + const readOptions = { session: options.session } + const orgs = await BaseOrgModel.find({}, ORG_RELATIONSHIP_PROJECTION, readOptions).lean() + const beforeGraph = new Map(orgs.map(org => [org.UUID, org])) + const afterGraph = new Map(beforeGraph) + const changedUUIDs = new Set() + const relationshipFields = Object.keys(ORG_RELATIONSHIP_PROJECTION).filter(key => key !== '_id') + let relationshipsChanged = false - const beforeUpdateObject = originalRegistryOrgObject - const afterUpdateObject = registryOrg.toObject() + for (const { before, after } of changes) { + const UUID = (after || before).UUID + changedUUIDs.add(UUID) + if (before) beforeGraph.set(UUID, before) + else beforeGraph.delete(UUID) + if (after) afterGraph.set(UUID, after) + else afterGraph.delete(UUID) + if (!_.isEqual(_.pick(before, relationshipFields), _.pick(after, relationshipFields))) { + relationshipsChanged = true + } + } - const cleanBefore = _.omit(beforeUpdateObject, ['_id', '__v', '__t', 'createdAt', 'updatedAt']) - const cleanAfter = _.omit(afterUpdateObject, ['_id', '__v', '__t', 'createdAt', 'updatedAt']) + const beforeRelationships = createOrgRelationships([...beforeGraph.values()]) + const afterRelationships = createOrgRelationships([...afterGraph.values()]) + const affectedUUIDs = [] + if (relationshipsChanged) { + for (const UUID of afterGraph.keys()) { + if (changedUUIDs.has(UUID)) continue + if (!_.isEqual(beforeRelationships.snapshot(UUID), afterRelationships.snapshot(UUID))) affectedUUIDs.push(UUID) + } + } - await auditRepo.seedAuditHistoryForOrg( - registryOrg.UUID, - cleanBefore, - requestingUserUUID, - { ...options, upsert: true } - ) + // Fetch full documents only for organizations whose derived fields changed. + const affectedOrgs = affectedUUIDs.length + ? await BaseOrgModel.find({ UUID: { $in: affectedUUIDs } }, null, readOptions).lean() + : [] + const snapshots = [...changes, ...affectedOrgs.map(org => ({ before: org, after: org }))] + const buildSnapshot = (org, relationships, preserveMetadata) => ({ + ..._.omit(org, [...(preserveMetadata ? [] : AUDIT_METADATA_FIELDS), 'top_level_root', '_hierarchy']), + ...relationships.snapshot(org.UUID) + }) - if (!_.isEqual(cleanBefore, cleanAfter)) { - await auditRepo.appendToAuditHistoryForOrg( - registryOrg.UUID, - cleanAfter, - requestingUserUUID, - { ...options, upsert: true } - ) + for (const { before, after, preserveMetadata } of snapshots) { + // Deletions update surviving organizations' histories, without inventing + // an organization snapshot for a document that no longer exists. + if (!after) continue + const cleanBefore = before ? buildSnapshot(before, beforeRelationships, preserveMetadata) : null + const cleanAfter = buildSnapshot(after, afterRelationships, preserveMetadata) + if (cleanBefore) { + await auditRepo.seedAuditHistoryForOrg(after.UUID, cleanBefore, requestingUserUUID, { ...options, upsert: true }) + } + // Retain audits of stored changes even if a stale stored TLR is replaced + // with the same derived value in both snapshots. + const storedChanged = !_.isEqual(_.omit(before, AUDIT_METADATA_FIELDS), _.omit(after, AUDIT_METADATA_FIELDS)) + if (storedChanged || !_.isEqual(_.omit(cleanBefore, AUDIT_METADATA_FIELDS), _.omit(cleanAfter, AUDIT_METADATA_FIELDS))) { + await auditRepo.appendToAuditHistoryForOrg(after.UUID, cleanAfter, requestingUserUUID, { ...options, upsert: true }) + } } } catch (auditError) { console.error('Audit entry creation failed:', auditError) + // Let the caller's existing transaction roll back every snapshot and the + // organization mutation rather than committing an incomplete history. + throw auditError } } @@ -266,5 +314,6 @@ module.exports = { manageReviewObject, processJointApprovalAndMerge, createAuditLogEntry, + createAuditLogEntries, handleAuthorityModelChange } diff --git a/src/repositories/orgRelationships.js b/src/repositories/orgRelationships.js new file mode 100644 index 000000000..cad92cfcd --- /dev/null +++ b/src/repositories/orgRelationships.js @@ -0,0 +1,127 @@ +const ORG_RELATIONSHIP_PROJECTION = { + _id: false, + UUID: true, + short_name: true, + long_name: true, + oversees: true, + authority: true, + is_top_level_root: true, + is_last_resort: true +} + +function createHierarchyBuilder (orgs) { + const orgsByUUID = new Map(orgs.filter(org => org.UUID).map(org => [org.UUID, org])) + const childrenByUUID = new Map() + const parentByUUID = new Map() + + for (const org of orgsByUUID.values()) { + const children = [] + if (org.authority?.includes('ROOT') && Array.isArray(org.oversees)) { + for (const childUUID of org.oversees) { + const child = orgsByUUID.get(childUUID) + if (!child || childUUID === org.UUID) continue + if (child.authority?.includes('ROOT') && child.is_top_level_root === true) continue + children.push(childUUID) + if (!parentByUUID.has(childUUID)) parentByUUID.set(childUUID, org.UUID) + } + } + childrenByUUID.set(org.UUID, children) + } + + return function buildHierarchy (orgUUID) { + // Ancestors expose only the branch leading to the requested organization. + const ancestorChildren = new Map() + let startUUID = orgUUID + if (orgUUID !== undefined) { + if (!orgsByUUID.has(orgUUID)) return [] + const path = new Set([orgUUID]) + while (parentByUUID.has(startUUID)) { + const parentUUID = parentByUUID.get(startUUID) + if (path.has(parentUUID)) break + ancestorChildren.set(parentUUID, [startUUID]) + path.add(parentUUID) + startUUID = parentUUID + } + } + + const hierarchy = [] + const visited = new Set() + const appendBranch = rootUUID => { + const pending = [{ UUID: rootUUID, target: hierarchy }] + while (pending.length > 0) { + const { UUID, target } = pending.pop() + if (visited.has(UUID)) continue + visited.add(UUID) + + const org = orgsByUUID.get(UUID) + const authority = Array.isArray(org.authority) ? org.authority : [] + const node = { + UUID: org.UUID, + short_name: org.short_name || '', + long_name: org.long_name || '', + authority, + children: [] + } + if (authority.includes('ROOT')) node.is_top_level_root = org.is_top_level_root === true + if (authority.includes('CNA')) node.is_last_resort = org.is_last_resort === true + target.push(node) + + const children = ancestorChildren.get(UUID) || childrenByUUID.get(UUID) + // Visit in stored order without recursive calls or repeated database reads. + for (let i = children.length - 1; i >= 0; i--) { + pending.push({ UUID: children[i], target: node.children }) + } + } + } + + if (orgUUID !== undefined) { + appendBranch(startUUID) + return hierarchy + } + + for (const UUID of orgsByUUID.keys()) { + if (!parentByUUID.has(UUID)) appendBranch(UUID) + } + // Retain disconnected cyclic components, omitting already visited edges. + for (const UUID of orgsByUUID.keys()) { + if (!visited.has(UUID)) appendBranch(UUID) + } + + return hierarchy + } +} + +// The same projected graph builds live hierarchies and immutable audit snapshots. +// Build indexes once so resolving affected organizations needs no per-org graph read. +function createOrgRelationships (orgs) { + const hierarchy = createHierarchyBuilder(orgs) + const byUUID = new Map(orgs.map(org => [org.UUID, org])) + const order = new Map(orgs.map((org, index) => [org.UUID, index])) + const parents = new Map() + for (const org of orgs) { + for (const childUUID of Array.isArray(org.oversees) ? org.oversees : []) { + if (!parents.has(childUUID)) parents.set(childUUID, []) + parents.get(childUUID).push(org) + } + } + + function snapshot (UUID) { + const org = byUUID.get(UUID) + if (!org) return null + const parentOrgs = parents.get(UUID) || [] + const grandparents = parentOrgs.flatMap(parent => parents.get(parent.UUID) || []) + const grandparent = grandparents.reduce((first, candidate) => + !first || order.get(candidate.UUID) < order.get(first.UUID) ? candidate : first, null) + // Match the detail endpoint's self/parent/grandparent lookup, including its + // existing depth limit. A deeper hierarchy must not silently change that API. + const tlr = [org, parentOrgs[0], grandparent].find(candidate => candidate?.is_top_level_root === true) + return { + ...(tlr ? { top_level_root: tlr.short_name } : {}), + _hierarchy: hierarchy(UUID) + } + } + + return { hierarchy, snapshot } +} + +module.exports = { createOrgRelationships, ORG_RELATIONSHIP_PROJECTION } diff --git a/test/integration-tests/audit/registryOrgCreatesAuditTest.js b/test/integration-tests/audit/registryOrgCreatesAuditTest.js index f7611d2ac..461692024 100644 --- a/test/integration-tests/audit/registryOrgCreatesAuditTest.js +++ b/test/integration-tests/audit/registryOrgCreatesAuditTest.js @@ -3,6 +3,11 @@ chai.use(require('chai-http')) const { expect } = chai const { v4: uuidv4 } = require('uuid') const AuditRepo = require('../../../src/repositories/auditRepository') +const sinon = require('sinon') +const BaseOrg = require('../../../src/model/baseorg') +const Audit = require('../../../src/model/audit') +const BaseOrgRepository = require('../../../src/repositories/baseOrgRepository') +const { pick } = require('lodash') const app = require('../../../src/index.js') const constants = require('../constants.js') @@ -26,7 +31,7 @@ async function createTestOrg (customProps = {}) { .set(secretariatHeaders) .send(orgData) if (res.status === 500) console.log('500 ERROR:', JSON.stringify(res.body, null, 2)) - expect(res).to.have.status(200) + expect(res, JSON.stringify(res.body)).to.have.status(200) return { shortName: orgData.short_name, @@ -37,6 +42,193 @@ async function createTestOrg (customProps = {}) { } describe('Create and Update Audit Collection with Org Endpoints', () => { + describe('Historical organization relationships', () => { + let orgs + + async function detail (org) { + const res = await chai.request(app).get(`/api/registry/org/${org.uuid}`).set(secretariatHeaders) + expect(res).to.have.status(200) + return res.body + } + + async function history (org) { + const res = await chai.request(app).get(`/api/audit/org/${org.uuid}`).set(secretariatHeaders) + expect(res).to.have.status(200) + return res.body.history + } + + async function relate (parent, child, action = 'add') { + const res = await chai.request(app) + .post(`/api/registry/org/${parent.shortName}/oversees/${child.shortName}/${action}`) + .set(secretariatHeaders) + expect(res).to.have.status(200) + } + + async function update (org, fields) { + const body = pick(org.fullResponse.created, ['short_name', 'long_name', 'authority', 'is_top_level_root', 'is_last_resort']) + if (body.authority.includes('CNA')) body.id_quota = org.fullResponse.created.id_quota + const res = await chai.request(app).put(`/api/registry/org/${org.shortName}`) + .set(secretariatHeaders).send({ ...body, ...fields }) + expect(res, JSON.stringify(res.body)).to.have.status(200) + org.fullResponse.created = res.body.updated + org.shortName = res.body.updated.short_name + } + + async function expectCurrentSnapshot (org) { + const current = await detail(org) + const entries = await history(org) + const snapshot = entries[entries.length - 1].audit_object + expect(snapshot.top_level_root).to.equal(current.top_level_root) + expect(snapshot._hierarchy).to.deep.equal(current._hierarchy) + return entries + } + + beforeEach(async () => { + orgs = [] + for (const fields of [ + { authority: ['ROOT'], is_top_level_root: true, id_quota: undefined }, + { authority: ['ROOT'], is_top_level_root: true, id_quota: undefined }, + { authority: ['ROOT'], is_top_level_root: false, id_quota: undefined }, + { authority: ['CNA'] }, + { authority: ['CNA'] } + ]) orgs.push(await createTestOrg(fields)) + await relate(orgs[0], orgs[2]) + await relate(orgs[2], orgs[3]) + }) + + afterEach(async () => { + sinon.restore() + const ids = orgs.map(org => org.uuid) + await BaseOrg.deleteMany({ UUID: { $in: ids } }) + await Audit.deleteMany({ target_uuid: { $in: ids } }) + }) + + it('captures derived relationships on creation and unrelated updates, overriding stale stored TLRs', async () => { + await expectCurrentSnapshot(orgs[4]) + await update(orgs[3], { id_quota: 20, top_level_root: 'obsolete-root' }) + await expectCurrentSnapshot(orgs[3]) + }) + + it('records a subtree move once per affected org and preserves earlier snapshots', async () => { + // Simulate an older snapshot without derived fields; it must stay unknown. + const oldChildHistory = await history(orgs[3]) + const lastIndex = oldChildHistory.length - 1 + await Audit.updateOne({ target_uuid: orgs[3].uuid }, { + $unset: { + [`history.${lastIndex}.audit_object.top_level_root`]: 1, + [`history.${lastIndex}.audit_object._hierarchy`]: 1 + } + }) + const before = await Promise.all(orgs.map(history)) + await relate(orgs[1], orgs[2]) + for (let i = 0; i < 4; i++) { + const after = await expectCurrentSnapshot(orgs[i]) + expect(after).to.have.lengthOf(before[i].length + 1) + expect(after.slice(0, -1)).to.deep.equal(before[i]) + } + expect(await history(orgs[4])).to.deep.equal(before[4]) + const child = await detail(orgs[3]) + expect(child.top_level_root).to.equal(orgs[1].shortName) + const afterMove = await history(orgs[3]) + await relate(orgs[1], orgs[2]) + expect(await history(orgs[3])).to.deep.equal(afterMove) + }) + + it('records a parent change within the same TLR without changing the TLR value', async () => { + const before = await detail(orgs[3]) + const oldHistory = await history(orgs[3]) + await relate(orgs[0], orgs[3]) + const entries = await expectCurrentSnapshot(orgs[3]) + const snapshot = entries[entries.length - 1].audit_object + expect(entries).to.have.lengthOf(oldHistory.length + 1) + expect(snapshot.top_level_root).to.equal(before.top_level_root) + expect(snapshot._hierarchy).to.not.deep.equal(before._hierarchy) + }) + + it('seeds the original relationship before moving an unaudited subtree', async () => { + const original = await detail(orgs[3]) + await Audit.deleteMany({ target_uuid: { $in: orgs.map(org => org.uuid) } }) + await relate(orgs[1], orgs[2]) + const entries = await expectCurrentSnapshot(orgs[3]) + expect(entries).to.have.lengthOf(2) + expect(entries[0].audit_object._hierarchy).to.deep.equal(original._hierarchy) + expect(entries[0].audit_object.top_level_root).to.equal(orgs[0].shortName) + }) + + it('records renames using stable node UUIDs and updates ancestor snapshots for descendant changes', async () => { + const original = await detail(orgs[3]) + await update(orgs[0], { new_short_name: `renamed_${uuidv4().slice(0, 8)}` }) + const entries = await expectCurrentSnapshot(orgs[3]) + const snapshot = entries[entries.length - 1].audit_object + expect(snapshot._hierarchy[0].UUID).to.equal(original._hierarchy[0].UUID) + expect(snapshot.top_level_root).to.equal(orgs[0].shortName) + await update(orgs[3], { long_name: 'Renamed descendant', is_last_resort: true }) + await expectCurrentSnapshot(orgs[0]) + await expectCurrentSnapshot(orgs[2]) + }) + + it('records TLR flag changes and removal without retaining stale relationship fields', async () => { + await update(orgs[0], { is_top_level_root: false }) + await expectCurrentSnapshot(orgs[3]) + expect((await detail(orgs[3])).top_level_root).to.equal(undefined) + await relate(orgs[2], orgs[3], 'remove') + const entries = await expectCurrentSnapshot(orgs[3]) + expect(entries[entries.length - 1].audit_object._hierarchy[0].UUID).to.equal(orgs[3].uuid) + await expectCurrentSnapshot(orgs[0]) + }) + + it('uses the final organization type when a Root loses its reporting role', async () => { + await update(orgs[2], { authority: ['ADP'], is_top_level_root: undefined }) + await expectCurrentSnapshot(orgs[0]) + await expectCurrentSnapshot(orgs[2]) + const entries = await expectCurrentSnapshot(orgs[3]) + const snapshot = entries[entries.length - 1].audit_object + expect(snapshot.top_level_root).to.equal(undefined) + expect(snapshot._hierarchy[0].UUID).to.equal(orgs[3].uuid) + }) + + it('rolls back all affected histories when the relationship transaction fails', async () => { + const before = await Promise.all(orgs.map(history)) + const addRelationship = BaseOrgRepository.prototype.addOverseeRelationship + sinon.stub(BaseOrgRepository.prototype, 'addOverseeRelationship').callsFake(async function (...args) { + await addRelationship.apply(this, args) + throw new Error('Forced relationship rollback') + }) + const res = await chai.request(app) + .post(`/api/registry/org/${orgs[1].shortName}/oversees/${orgs[2].shortName}/add`) + .set(secretariatHeaders) + expect(res).to.have.status(500) + expect(await Promise.all(orgs.map(history))).to.deep.equal(before) + expect((await detail(orgs[3])).top_level_root).to.equal(orgs[0].shortName) + }) + + it('aborts the mutation when an affected organization audit cannot be written', async () => { + const before = await Promise.all(orgs.map(history)) + const append = AuditRepo.prototype.appendToAuditHistoryForOrg + const appendStub = sinon.stub(AuditRepo.prototype, 'appendToAuditHistoryForOrg').callsFake(async function (UUID, ...args) { + if (UUID === orgs[3].uuid) throw new Error('Forced audit failure') + return append.call(this, UUID, ...args) + }) + const res = await chai.request(app) + .post(`/api/registry/org/${orgs[1].shortName}/oversees/${orgs[2].shortName}/add`) + .set(secretariatHeaders) + expect(res).to.have.status(500) + expect(appendStub.callCount).to.be.greaterThan(1) + expect(await Promise.all(orgs.map(history))).to.deep.equal(before) + expect((await detail(orgs[3])).top_level_root).to.equal(orgs[0].shortName) + }) + + it('records surviving organizations when their parent is deleted', async () => { + const before = await history(orgs[3]) + const res = await chai.request(app).delete(`/api/registry/org/${orgs[2].shortName}`).set(secretariatHeaders) + expect(res).to.have.status(200) + const after = await expectCurrentSnapshot(orgs[3]) + expect(after).to.have.lengthOf(before.length + 1) + expect(after.slice(0, -1)).to.deep.equal(before) + await expectCurrentSnapshot(orgs[0]) + }) + }) + it('Should automatically create audit document when org is created', async () => { // Create org const org = await createTestOrg({ diff --git a/test/unit-tests/org/baseOrgRepositoryHelpersTest.js b/test/unit-tests/org/baseOrgRepositoryHelpersTest.js index 92cb25c13..2b2e6369d 100644 --- a/test/unit-tests/org/baseOrgRepositoryHelpersTest.js +++ b/test/unit-tests/org/baseOrgRepositoryHelpersTest.js @@ -195,6 +195,10 @@ describe('Testing BaseOrgRepository helper functions', () => { }) context('createAuditLogEntry', () => { + beforeEach(() => { + sinon.stub(BaseOrgModel, 'find').returns({ lean: sinon.stub().resolves([]) }) + }) + it('Should seed audit history and skip append when the org did not change', async () => { sinon.stub(console, 'log') const seedAuditHistoryForOrg = sinon.stub(AuditRepository.prototype, 'seedAuditHistoryForOrg').resolves({}) @@ -237,6 +241,32 @@ describe('Testing BaseOrgRepository helper functions', () => { expect(appendToAuditHistoryForOrg.calledOnce).to.equal(true) expect(appendToAuditHistoryForOrg.firstCall.args[0]).to.equal('org-uuid') expect(appendToAuditHistoryForOrg.firstCall.args[2]).to.equal('requester-uuid') + expect(appendToAuditHistoryForOrg.firstCall.args[1]._hierarchy[0]).to.include({ + UUID: 'org-uuid', short_name: 'new_org' + }) + }) + + it('resolves snapshots within the caller transaction and skips graph reads without an author', async () => { + const session = { id: 'caller-session' } + sinon.stub(AuditRepository.prototype, 'appendToAuditHistoryForOrg').resolves({}) + const org = { UUID: 'org-uuid', short_name: 'root', authority: ['ROOT'], is_top_level_root: true } + await helpers.createAuditLogEntry(org, null, null, { session }) + expect(BaseOrgModel.find.notCalled).to.equal(true) + await helpers.createAuditLogEntry(org, null, 'author-uuid', { session }) + expect(BaseOrgModel.find.firstCall.args[2]).to.deep.equal({ session }) + const append = AuditRepository.prototype.appendToAuditHistoryForOrg.firstCall.args + expect(append[1].top_level_root).to.equal('root') + expect(append[3].session).to.equal(session) + }) + + it('retains legacy snapshot metadata and audits stored TLR edits without reporting a derived TLR change', async () => { + sinon.stub(AuditRepository.prototype, 'seedAuditHistoryForOrg').resolves({}) + const append = sinon.stub(AuditRepository.prototype, 'appendToAuditHistoryForOrg').resolves({}) + const before = { _id: 'stored-id', UUID: 'org-uuid', short_name: 'root', authority: ['ROOT'], is_top_level_root: true, top_level_root: 'stale' } + await helpers.createAuditLogEntry({ ...before, top_level_root: 'another-stale-value' }, before, 'author', {}, true) + expect(append.calledOnce).to.equal(true) + expect(append.firstCall.args[1]).to.include({ _id: 'stored-id', top_level_root: 'root' }) + expect(AuditRepository.prototype.seedAuditHistoryForOrg.firstCall.args[1].top_level_root).to.equal('root') }) }) diff --git a/test/unit-tests/org/legacy/orgCreateTest.js b/test/unit-tests/org/legacy/orgCreateTest.js index c247a2505..a37f0ebf4 100644 --- a/test/unit-tests/org/legacy/orgCreateTest.js +++ b/test/unit-tests/org/legacy/orgCreateTest.js @@ -73,6 +73,7 @@ describe('Testing the ORG_CREATE_SINGLE controller', () => { } sinon.stub(mongoose, 'startSession').resolves(mockSession) sinon.stub(BaseOrgModel, 'findOne').returns({ lean: sinon.stub().resolves(null) }) + sinon.stub(BaseOrgModel, 'find').returns({ lean: sinon.stub().resolves([]) }) fakeBaseSavedObject = { long_name: 'The MITRE Corporation', From fd6a36fc040b9863c4e06dd1d70aa9da9fe64286 Mon Sep 17 00:00:00 2001 From: David T Rocca Date: Mon, 23 Nov 2026 14:08:49 -0500 Subject: [PATCH 2/6] test: allow time for legacy role and quota transitions --- test/integration-tests/org/legacyOrgQuotaContractTest.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/integration-tests/org/legacyOrgQuotaContractTest.js b/test/integration-tests/org/legacyOrgQuotaContractTest.js index c9d5b5770..53940eca3 100644 --- a/test/integration-tests/org/legacyOrgQuotaContractTest.js +++ b/test/integration-tests/org/legacyOrgQuotaContractTest.js @@ -145,7 +145,10 @@ describe('Legacy organization quota contract backed by BaseOrg', () => { }) } - it('preserves identity and non-ROOT quotas through legacy role changes and simultaneous quota updates', async () => { + it('preserves identity and non-ROOT quotas through legacy role changes and simultaneous quota updates', async function () { + // Each role transition checks the stored quota and both quota endpoints. + this.timeout(10000) + const shortName = 'lc01_legacy_transition' const created = await createLegacyOrg(shortName, { active_roles: ['CNA'] }, 12) let previousRole = 'CNA' From 3099bf4842306a429185a434ec9ae91421de200d Mon Sep 17 00:00:00 2001 From: David T Rocca Date: Tue, 24 Nov 2026 12:20:15 -0500 Subject: [PATCH 3/6] Bump CVE Services version to 2.9.4 --- api-docs/openapi.json | 2 +- package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/api-docs/openapi.json b/api-docs/openapi.json index 35b605ed6..97eeeaa9e 100644 --- a/api-docs/openapi.json +++ b/api-docs/openapi.json @@ -1,7 +1,7 @@ { "openapi": "3.0.2", "info": { - "version": "2.9.3", + "version": "2.9.4", "title": "CVE Services API", "description": "The CVE Services API supports automation tooling for the CVE Program. Credentials are required for most service endpoints. Representatives of CVE Numbering Authorities (CNAs) should use one of the methods below to obtain credentials:
  • If your organization already has an Organizational Administrator (OA) account for the CVE Services, ask your admin for credentials
  • Contact your Root (Google, INCIBE, JPCERT/CC, or Red Hat) or Top-Level Root (CISA ICS or MITRE) to request credentials

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 Rocca Date: Tue, 17 Nov 2026 13:44:12 -0500 Subject: [PATCH 4/6] feat: support partial organization joint approvals (#2093) --- api-docs/openapi.json | 2 +- .../update-registry-org-request.json | 35 ++ src/controller/registry.controller/index.js | 3 + .../org.registry.controller.js | 91 ++++- .../registryOrgWithJointReviewTest.js | 344 ++++++++++++++++++ 5 files changed, 470 insertions(+), 5 deletions(-) diff --git a/api-docs/openapi.json b/api-docs/openapi.json index 97eeeaa9e..31d3ba81c 100644 --- a/api-docs/openapi.json +++ b/api-docs/openapi.json @@ -3810,7 +3810,7 @@ "Data Registry — Organizations" ], "summary": "Updates information about the organization specified by short name (accessible to Secretariat or same-organization Admin)", - "description": "

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.

Access Control

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:

Expected Behavior

This endpoint expects a full organization object in the request body.

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.

  • short_name
  • long_name
  • authority
  • aliases
  • oversees
  • top_level_root
  • is_top_level_root
  • is_last_resort
  • charter_or_scope
  • product_list
  • disclosure_policy
  • contact_info.websites
  • contact_info.emails
  • partner_role_type
  • partner_country
  • advisory_locations
  • advisory_location_require_credentials
  • vulnerability_advisory_location_for_web_scraping
  • industry
  • tl_root_start_date
  • is_cna_discussion_list
", + "description": "

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.

Access Control

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:

Expected Behavior

This endpoint expects a full organization object in the request body.

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.

  • short_name
  • long_name
  • authority
  • aliases
  • oversees
  • top_level_root
  • is_top_level_root
  • is_last_resort
  • charter_or_scope
  • product_list
  • disclosure_policy
  • contact_info.websites
  • contact_info.emails
  • partner_role_type
  • partner_country
  • advisory_locations
  • advisory_location_require_credentials
  • vulnerability_advisory_location_for_web_scraping
  • industry
  • tl_root_start_date
  • is_cna_discussion_list
", "operationId": "registryOrgUpdateSingle", "parameters": [ { diff --git a/schemas/registry-org/update-registry-org-request.json b/schemas/registry-org/update-registry-org-request.json index 361d0b50e..5d78ef593 100644 --- a/schemas/registry-org/update-registry-org-request.json +++ b/schemas/registry-org/update-registry-org-request.json @@ -238,6 +238,41 @@ "body" ], "description": "Optional message accompanying the organization update" + }, + "x_unresolved_keys": { + "type": "array", + "uniqueItems": true, + "items": { + "type": "string", + "enum": [ + "short_name", + "long_name", + "authority", + "aliases", + "is_top_level_root", + "is_last_resort", + "charter_or_scope", + "product_list", + "disclosure_policy", + "contact_info", + "partner_role_type", + "partner_number", + "partner_country", + "program_data.cve_website_update_date", + "program_data.cve_website_update_needed", + "program_data.status", + "advisory_locations", + "advisory_location_require_credentials", + "vulnerability_advisory_location_for_web_scraping", + "industry", + "tl_root_start_date", + "is_cna_discussion_list", + "id_quota", + "contact_info.emails", + "contact_info.websites" + ] + }, + "description": "Secretariat-only unresolved pending proposal paths. A nonempty list preserves the published values of these fields and keeps the same review pending with its original proposals. Other fields follow the submitted full organization body. Arrays are atomic; overlapping paths are invalid. Use short_name for a deferred rename. Omitted metadata or an empty list retains existing whole-review approval/rejection behavior; an empty list does not require a pending review. Updates that cannot preserve an unresolved published value are rejected and rolled back; resolve dependent role and quota changes together." } }, "required": [ diff --git a/src/controller/registry.controller/index.js b/src/controller/registry.controller/index.js index 7511433fe..8aec56b53 100644 --- a/src/controller/registry.controller/index.js +++ b/src/controller/registry.controller/index.js @@ -776,6 +776,8 @@ router.put('/registry/org/:shortname',

Expected Behavior

This endpoint expects a full organization object in the request body.

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 Date: Tue, 17 Nov 2026 14:32:11 -0500 Subject: [PATCH 5/6] fix: normalize unset pending organization review fields --- schemas/review/review.json | 2 +- .../org.registry.controller.js | 5 +- .../review-object.controller.js | 22 ++++- src/repositories/baseOrgRepositoryHelpers.js | 20 +++++ .../registryOrgWithJointReviewTest.js | 81 +++++++++++++++++++ .../org/baseOrgRepositoryHelpersTest.js | 21 +++++ .../review-object.controller.test.js | 25 ++++++ 7 files changed, 172 insertions(+), 4 deletions(-) diff --git a/schemas/review/review.json b/schemas/review/review.json index 1845eb5a4..31cc658aa 100644 --- a/schemas/review/review.json +++ b/schemas/review/review.json @@ -24,7 +24,7 @@ }, "new_review_data": { "type": "object", - "description": "The data proposed in the review" + "description": "The data proposed in the review. Pending review GET responses omit null fields when the published value is also null or absent, matching organization responses. A proposed null is retained when it clears a published value. Stored proposals and completed review history are unchanged." }, "created": { "type": "string", diff --git a/src/controller/registry.controller/org.registry.controller.js b/src/controller/registry.controller/org.registry.controller.js index 4a0d1b0e1..3e31c8cf9 100644 --- a/src/controller/registry.controller/org.registry.controller.js +++ b/src/controller/registry.controller/org.registry.controller.js @@ -15,6 +15,7 @@ const { REGISTRY_FORMAT } = require('../format.constants') const { getUserQuotaUsage } = require('../../utils/userQuota') const { deepRemoveEmpty } = require('../../utils/utils') const { normalizeOrgCveWebsiteUpdateDate } = require('../../utils/dateOnly') +const { normalizeReviewOrgData } = require('../../repositories/baseOrgRepositoryHelpers') function addUUIDsToSet (uuidSet, values) { if (!Array.isArray(values)) return @@ -707,8 +708,8 @@ async function updateOrg (req, res, next) { } 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)) + const published = deepRemoveEmpty(JSON.parse(JSON.stringify(org))) + const proposed = normalizeReviewOrgData(JSON.parse(JSON.stringify(partialReview.new_review_data)), published) 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)))) { diff --git a/src/controller/review-object.controller/review-object.controller.js b/src/controller/review-object.controller/review-object.controller.js index ed99d2ed3..044c9ed57 100644 --- a/src/controller/review-object.controller/review-object.controller.js +++ b/src/controller/review-object.controller/review-object.controller.js @@ -9,7 +9,22 @@ const _ = require('lodash') const authContext = require('../../utils/authContext') const { DisabledSecretariatError, isSecretariatOrg } = require('../../utils/orgDisabled') const { SecretariatSelfDemotionError } = require('../../utils/orgAuthority') -const { protectSecretariatOrg } = require('../../repositories/baseOrgRepositoryHelpers') +const { protectSecretariatOrg, normalizeReviewOrgData } = require('../../repositories/baseOrgRepositoryHelpers') + +// Normalize only pending HTTP responses, keeping mutation reads and completed +// history intact. Batch published lookups for paginated review responses. +async function normalizePendingReviewResponses (reviews, orgRepo) { + const pending = reviews.filter(review => review?.status === 'pending' && review.new_review_data) + if (!pending.length) return + + const orgUUIDs = [...new Set(pending.map(review => review.target_object_uuid))] + const orgs = await orgRepo.find({ UUID: { $in: orgUUIDs } }, { lean: true }) + const publishedByUUID = new Map(orgs.map(org => [org.UUID, org])) + for (const review of pending) { + const published = publishedByUUID.get(review.target_object_uuid) + if (published) review.new_review_data = normalizeReviewOrgData(review.new_review_data, published) + } +} /** * Retrieves the PENDING review object for an organization by identifier (short_name or UUID). @@ -45,6 +60,7 @@ async function getReviewObjectByOrgIdentifier (req, res, next) { if (!value) { return res.status(200).json({ pendingReview: null }) } + await normalizePendingReviewResponses([value], orgRepo) return res.status(200).json(value) } catch (err) { next(err) @@ -70,6 +86,7 @@ async function getReviewObjectByUUID (req, res, next) { } } + await normalizePendingReviewResponses([value], orgRepo) return res.status(200).json(value) } catch (err) { next(err) @@ -79,6 +96,7 @@ async function getReviewObjectByUUID (req, res, next) { async function getAllReviewObjects (req, res, next) { try { const repo = req.ctx.repositories.getReviewObjectRepository() + const orgRepo = req.ctx.repositories.getBaseOrgRepository() const CONSTANTS = getConstants() const status = req.query?.status || null @@ -90,6 +108,7 @@ async function getAllReviewObjects (req, res, next) { options.page = req.query?.page ? parseInt(req.query?.page) : CONSTANTS.PAGINATOR_PAGE const response = await repo.getAllReviewObjectsPaginated(options, status) + await normalizePendingReviewResponses(response.reviewObjects, orgRepo) return res.status(200).json(response) } catch (err) { next(err) @@ -289,6 +308,7 @@ async function getReviewHistoryByOrgShortNamePaginated (req, res, next) { includeConversations, isSecretariat ) + await normalizePendingReviewResponses(response.reviewObjects, orgRepo) return res.status(200).json(response) } catch (err) { next(err) diff --git a/src/repositories/baseOrgRepositoryHelpers.js b/src/repositories/baseOrgRepositoryHelpers.js index 3fe9bb659..c397bdb87 100644 --- a/src/repositories/baseOrgRepositoryHelpers.js +++ b/src/repositories/baseOrgRepositoryHelpers.js @@ -9,6 +9,25 @@ const RootOrgModel = require('../model/rootorg') const { createOrgRelationships, ORG_RELATIONSHIP_PROJECTION } = require('./orgRelationships') const AUDIT_METADATA_FIELDS = ['_id', '__v', '__t', 'createdAt', 'updatedAt'] +// Match published response cleanup, retaining null only when it clears a value. +// This is a view/comparison copy; stored proposals must retain their original data. +function normalizeReviewOrgData (proposed, published) { + const { deepRemoveEmpty } = require('../utils/utils') + const normalized = _.cloneDeep(proposed) + const clean = (current, existing) => { + _.forOwn(current, (value, key) => { + if (_.isPlainObject(value)) { + clean(value, existing?.[key]) + if (_.isEmpty(value)) delete current[key] + } else if (value === null && existing?.[key] == null) { + delete current[key] + } + }) + } + clean(normalized, deepRemoveEmpty(published)) + return normalized +} + // Check both the stored and requested roles so removing SECRETARIAT cannot // bypass the protection in the same update. Omitted flags must stay enabled // even when a full update replaces the document's fields. @@ -306,6 +325,7 @@ async function handleAuthorityModelChange (updatedRegistryOrg, originalRoles, op } module.exports = { + normalizeReviewOrgData, protectSecretariatOrg, normalizeRootOrgQuota, skipNulls, diff --git a/test/integration-tests/registry-org/registryOrgWithJointReviewTest.js b/test/integration-tests/registry-org/registryOrgWithJointReviewTest.js index 62dc9996e..b1dbe74f2 100644 --- a/test/integration-tests/registry-org/registryOrgWithJointReviewTest.js +++ b/test/integration-tests/registry-org/registryOrgWithJointReviewTest.js @@ -188,6 +188,87 @@ describe('Testing Joint approval', () => { } } + async function getPendingReviewResponses () { + const responses = [] + for (const path of [ + `/api/review/org/${original.short_name}`, + `/api/review/org/${original.UUID}`, + `/api/review/byUUID/${review.uuid}`, + '/api/review/orgs?status=pending', + `/api/review/org/${original.short_name}/reviews` + ]) { + const response = await chai.request(app).get(path).set(secretariatHeaders) + expect(response, path + ': ' + JSON.stringify(response.body)).to.have.status(200) + const pending = response.body.reviewObjects + ? response.body.reviewObjects.find(item => item.uuid === review.uuid) + : response.body + expect(pending, path).to.have.property('uuid', review.uuid) + responses.push(pending) + } + return responses + } + + it('omits unchanged null proposals across pending responses and validates only substantive unresolved changes', async () => { + await BaseOrg.collection.updateOne({ UUID: original.UUID }, { + $set: { charter_or_scope: null }, $unset: { product_list: 1 } + }) + await new ReviewObjectRepository().updateReviewOrgObject({ ...proposal, charter_or_scope: null, product_list: null }, review.uuid) + const before = await snapshot() + const published = await chai.request(app).get(`/api/registry/org/${original.short_name}`).set(secretariatHeaders) + expect(published).to.have.status(200) + expect(published.body).to.not.have.property('charter_or_scope') + expect(published.body).to.not.have.property('product_list') + const pendingResponses = await getPendingReviewResponses() + for (const pending of pendingResponses) { + expect(pending.new_review_data).to.not.have.property('charter_or_scope') + expect(pending.new_review_data).to.not.have.property('product_list') + expect(pending.new_review_data.industry).to.equal(proposal.industry) + } + expect(await snapshot()).to.deep.equal(before) + + for (const path of ['charter_or_scope', 'product_list']) { + const unchanged = await update({ ...original, x_unresolved_keys: [path] }) + expect(unchanged, path).to.have.status(400) + expect(unchanged.body.errors[0].message).to.equal('Each unresolved field must have a pending change.') + expect(await snapshot()).to.deep.equal(before) + } + const pending = pendingResponses[0].new_review_data + const unresolved = ['charter_or_scope', 'product_list', 'industry'].filter(path => pending[path] !== published.body[path]) + expect(unresolved).to.deep.equal(['industry']) + const response = await update({ ...original, long_name: proposal.long_name, x_unresolved_keys: unresolved }) + expect(response, JSON.stringify(response.body)).to.have.status(200) + expect(response.body.updated.long_name).to.equal(proposal.long_name) + expect((await snapshot()).reviews[0].status).to.equal('pending') + }) + + it('retains proposed null clears of published text through pending responses, partial resolution, and approval', async () => { + await BaseOrg.collection.updateOne({ UUID: original.UUID }, { + $set: { charter_or_scope: 'Published scope', product_list: 'Published products' } + }) + await new ReviewObjectRepository().updateReviewOrgObject({ ...proposal, charter_or_scope: null, product_list: null }, review.uuid) + for (const pending of await getPendingReviewResponses()) { + expect(pending.new_review_data).to.have.property('charter_or_scope', null) + expect(pending.new_review_data).to.have.property('product_list', null) + } + const response = await update({ ...original, x_unresolved_keys: ['charter_or_scope', 'product_list'] }) + expect(response, JSON.stringify(response.body)).to.have.status(200) + expect(response.body.updated.charter_or_scope).to.equal('Published scope') + expect(response.body.updated.product_list).to.equal('Published products') + const pending = await chai.request(app).get(`/api/review/org/${original.UUID}`).set(secretariatHeaders) + expect(pending.body.new_review_data).to.have.property('charter_or_scope', null) + expect(pending.body.new_review_data).to.have.property('product_list', 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.have.property('charter_or_scope', null) + expect(state.org).to.have.property('product_list', null) + const history = await chai.request(app).get(`/api/review/org/${original.short_name}/reviews`).set(secretariatHeaders) + const completed = history.body.reviewObjects.find(item => item.uuid === review.uuid) + expect(completed.status).to.equal('approved') + expect(completed.new_review_data).to.have.property('charter_or_scope', null) + expect(completed.new_review_data).to.have.property('product_list', null) + }) + it('publishes accepted fields, drops denied proposals, and keeps undecided fields pending', async () => { const response = await update({ ...original, diff --git a/test/unit-tests/org/baseOrgRepositoryHelpersTest.js b/test/unit-tests/org/baseOrgRepositoryHelpersTest.js index 2b2e6369d..2c15ff73f 100644 --- a/test/unit-tests/org/baseOrgRepositoryHelpersTest.js +++ b/test/unit-tests/org/baseOrgRepositoryHelpersTest.js @@ -12,6 +12,27 @@ describe('Testing BaseOrgRepository helper functions', () => { sinon.restore() }) + context('normalizeReviewOrgData', () => { + it('omits nulls matching unset published values without mutating either snapshot', () => { + const published = { charter_or_scope: null, program_data: { status: 'Active', cve_website_update_date: null } } + const proposal = { charter_or_scope: null, product_list: null, program_data: { status: null, cve_website_update_date: null }, contact_info: {} } + const result = helpers.normalizeReviewOrgData(proposal, published) + expect(result).to.deep.equal({ program_data: { status: null } }) + expect(proposal).to.have.property('charter_or_scope', null) + expect(proposal).to.have.property('product_list', null) + expect(proposal.program_data).to.have.property('cve_website_update_date', null) + expect(published.program_data).to.deep.equal({ status: 'Active', cve_website_update_date: null }) + }) + + it('preserves null clears of defined values and does not collapse false, zero, empty strings, arrays, or Dates', () => { + const published = { industry: 'Published text', is_cna_discussion_list: false, id_quota: 0, advisory_locations: '', aliases: [] } + const clears = { industry: null, is_cna_discussion_list: null, id_quota: null, advisory_locations: null, aliases: null } + expect(helpers.normalizeReviewOrgData(clears, published)).to.deep.equal(clears) + const proposal = { ...published, tl_root_start_date: new Date('2026-01-01T00:00:00.000Z'), private_contacts: [{ phone: null }] } + expect(helpers.normalizeReviewOrgData(proposal, {})).to.deep.equal(proposal) + }) + }) + context('mergeAllowedFields', () => { it('Should preserve protected fields and replace arrays from incoming data', () => { const targetDoc = { diff --git a/test/unit-tests/review-object/review-object.controller.test.js b/test/unit-tests/review-object/review-object.controller.test.js index c836de4c6..88fd22841 100644 --- a/test/unit-tests/review-object/review-object.controller.test.js +++ b/test/unit-tests/review-object/review-object.controller.test.js @@ -155,6 +155,31 @@ describe('Review Object Controller', function () { const callArgs = repoStub.getAllReviewObjectsPaginated.getCall(0).args expect(callArgs[1]).to.equal('pending') }) + + it('normalizes pending response copies with one published lookup while preserving closed and orphaned reviews', async () => { + const data = { + reviewObjects: [ + { uuid: 'pending-1', status: 'pending', target_object_uuid: 'org-1', new_review_data: { charter_or_scope: null, product_list: null } }, + { uuid: 'pending-2', status: 'pending', target_object_uuid: 'org-1', new_review_data: { industry: null } }, + { uuid: 'closed', status: 'approved', target_object_uuid: 'org-1', new_review_data: { charter_or_scope: null } }, + { uuid: 'orphaned', status: 'pending', target_object_uuid: 'missing-org', new_review_data: { charter_or_scope: null } } + ], + totalCount: 4, + nextPage: 2 + } + repoStub.getAllReviewObjectsPaginated = sinon.stub().resolves(data) + orgRepoStub.find = sinon.stub().resolves([{ UUID: 'org-1', charter_or_scope: null, product_list: 'Published products' }]) + await controller.getAllReviewObjects(req, res, next) + expect(next.notCalled).to.equal(true) + expect(orgRepoStub.find.calledOnceWithExactly({ UUID: { $in: ['org-1', 'missing-org'] } }, { lean: true })).to.equal(true) + const response = res.json.firstCall.args[0] + expect(response).to.include({ totalCount: 4, nextPage: 2 }) + expect(response.reviewObjects.map(review => review.uuid)).to.deep.equal(['pending-1', 'pending-2', 'closed', 'orphaned']) + expect(response.reviewObjects[0].new_review_data).to.deep.equal({ product_list: null }) + expect(response.reviewObjects[1].new_review_data).to.deep.equal({}) + expect(response.reviewObjects[2].new_review_data).to.deep.equal({ charter_or_scope: null }) + expect(response.reviewObjects[3].new_review_data).to.deep.equal({ charter_or_scope: null }) + }) }) describe('updateReviewObjectByReviewUUID', function () { From b72c93d6f541df17ea22385e5df0b4a25adc0211 Mon Sep 17 00:00:00 2001 From: David T Rocca Date: Tue, 1 Dec 2026 10:10:35 -0500 Subject: [PATCH 6/6] Avoid cursor continuation in organization audit transactions --- src/repositories/baseOrgRepositoryHelpers.js | 26 ++++++++++++++++--- .../audit/registryOrgCreatesAuditTest.js | 8 ++++++ .../org/baseOrgRepositoryHelpersTest.js | 2 +- 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/src/repositories/baseOrgRepositoryHelpers.js b/src/repositories/baseOrgRepositoryHelpers.js index c397bdb87..c9ec2cb4c 100644 --- a/src/repositories/baseOrgRepositoryHelpers.js +++ b/src/repositories/baseOrgRepositoryHelpers.js @@ -8,6 +8,7 @@ const SecretariatOrgModel = require('../model/secretariatorg') const RootOrgModel = require('../model/rootorg') const { createOrgRelationships, ORG_RELATIONSHIP_PROJECTION } = require('./orgRelationships') const AUDIT_METADATA_FIELDS = ['_id', '__v', '__t', 'createdAt', 'updatedAt'] +const AUDIT_ORG_BATCH_SIZE = 500 // Match published response cleanup, retaining null only when it clears a value. // This is a view/comparison copy; stored proposals must retain their original data. @@ -208,6 +209,26 @@ async function createAuditLogEntry (registryOrg, originalRegistryOrgObject, requ return createAuditLogEntries([{ before: originalRegistryOrgObject, after, preserveMetadata }], requestingUserUUID, options) } +// DocumentDB requires each transactional find to finish in its first batch. +async function findOrgsForAudit (filter, projection, session) { + const options = { + session, + sort: { _id: 1 }, + limit: AUDIT_ORG_BATCH_SIZE, + batchSize: AUDIT_ORG_BATCH_SIZE, + singleBatch: true + } + const orgs = [] + let pageFilter = filter + while (true) { + const page = await BaseOrgModel.find(pageFilter, projection, options).lean() + if (!page.length) return orgs + orgs.push(...page) + // A batch can reach its byte limit before reaching the document limit. + pageFilter = { ...filter, _id: { $gt: page[page.length - 1]._id } } + } +} + // A reparenting operation changes several stored documents. Resolve its entire // before/after graph together, never an intermediate detached relationship. async function createAuditLogEntries (changes, requestingUserUUID, options = {}) { @@ -215,8 +236,7 @@ async function createAuditLogEntries (changes, requestingUserUUID, options = {}) try { const AuditRepository = require('./auditRepository') const auditRepo = new AuditRepository() - const readOptions = { session: options.session } - const orgs = await BaseOrgModel.find({}, ORG_RELATIONSHIP_PROJECTION, readOptions).lean() + const orgs = await findOrgsForAudit({}, { ...ORG_RELATIONSHIP_PROJECTION, _id: true }, options.session) const beforeGraph = new Map(orgs.map(org => [org.UUID, org])) const afterGraph = new Map(beforeGraph) const changedUUIDs = new Set() @@ -247,7 +267,7 @@ async function createAuditLogEntries (changes, requestingUserUUID, options = {}) // Fetch full documents only for organizations whose derived fields changed. const affectedOrgs = affectedUUIDs.length - ? await BaseOrgModel.find({ UUID: { $in: affectedUUIDs } }, null, readOptions).lean() + ? await findOrgsForAudit({ UUID: { $in: affectedUUIDs } }, null, options.session) : [] const snapshots = [...changes, ...affectedOrgs.map(org => ({ before: org, after: org }))] const buildSnapshot = (org, relationships, preserveMetadata) => ({ diff --git a/test/integration-tests/audit/registryOrgCreatesAuditTest.js b/test/integration-tests/audit/registryOrgCreatesAuditTest.js index 461692024..ecd11b210 100644 --- a/test/integration-tests/audit/registryOrgCreatesAuditTest.js +++ b/test/integration-tests/audit/registryOrgCreatesAuditTest.js @@ -120,7 +120,15 @@ describe('Create and Update Audit Collection with Org Endpoints', () => { } }) const before = await Promise.all(orgs.map(history)) + // Force affected documents into separate batches even for this small subtree. + const find = BaseOrg.find + sinon.stub(BaseOrg, 'find').callsFake(function (filter, ...args) { + const query = find.call(this, filter, ...args) + return filter?.UUID?.$in ? query.batchSize(1) : query + }) + const getMore = sinon.spy(BaseOrg.base.mongo.FindCursor.prototype, 'getMore') await relate(orgs[1], orgs[2]) + expect(getMore.callCount, 'DocumentDB forbids cursor continuation in transactions').to.equal(0) for (let i = 0; i < 4; i++) { const after = await expectCurrentSnapshot(orgs[i]) expect(after).to.have.lengthOf(before[i].length + 1) diff --git a/test/unit-tests/org/baseOrgRepositoryHelpersTest.js b/test/unit-tests/org/baseOrgRepositoryHelpersTest.js index 2c15ff73f..156efda4e 100644 --- a/test/unit-tests/org/baseOrgRepositoryHelpersTest.js +++ b/test/unit-tests/org/baseOrgRepositoryHelpersTest.js @@ -274,7 +274,7 @@ describe('Testing BaseOrgRepository helper functions', () => { await helpers.createAuditLogEntry(org, null, null, { session }) expect(BaseOrgModel.find.notCalled).to.equal(true) await helpers.createAuditLogEntry(org, null, 'author-uuid', { session }) - expect(BaseOrgModel.find.firstCall.args[2]).to.deep.equal({ session }) + expect(BaseOrgModel.find.firstCall.args[2].session).to.equal(session) const append = AuditRepository.prototype.appendToAuditHistoryForOrg.firstCall.args expect(append[1].top_level_root).to.equal('root') expect(append[3].session).to.equal(session)