From f1a8c0316476142eaa6bb9cc5ecb2f04cf0fa122 Mon Sep 17 00:00:00 2001 From: David T Rocca Date: Mon, 30 Nov 2026 10:46:51 -0500 Subject: [PATCH 01/19] fix: upgrade the xlsx development dependency to 0.20.3 --- package-lock.json | 107 ++-------------------------------------------- package.json | 2 +- 2 files changed, 5 insertions(+), 104 deletions(-) diff --git a/package-lock.json b/package-lock.json index 2c66c90d2..cc1caed06 100644 --- a/package-lock.json +++ b/package-lock.json @@ -65,7 +65,7 @@ "sinon": "^15.0.4", "standard": "^16.0.3", "swagger-autogen": "^2.19.0", - "xlsx": "^0.18.5" + "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz" } }, "node_modules/@babel/code-frame": { @@ -1095,16 +1095,6 @@ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, - "node_modules/adler-32": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/adler-32/-/adler-32-1.3.1.tgz", - "integrity": "sha512-ynZ4w/nUUv5rrsR8UUGoe1VC9hZj6V5hU9Qw1HlMDJGEJw5S7TfTErWTjMys6M7vr0YWcPqs3qAr4ss0nDfP+A==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=0.8" - } - }, "node_modules/aggregate-error": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.1.0.tgz", @@ -1766,20 +1756,6 @@ ], "license": "CC-BY-4.0" }, - "node_modules/cfb": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/cfb/-/cfb-1.2.2.tgz", - "integrity": "sha512-KfdUZsSOw19/ObEWasvBP/Ac4reZvAGauZhs6S/gqNhXhI7cKwvlH7ulj+dOEYnca4bm4SGo8C1bTAQvnTjgQA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "adler-32": "~1.3.0", - "crc-32": "~1.2.0" - }, - "engines": { - "node": ">=0.8" - } - }, "node_modules/chai": { "version": "4.5.0", "resolved": "https://registry.npmjs.org/chai/-/chai-4.5.0.tgz", @@ -1962,16 +1938,6 @@ "wrap-ansi": "^7.0.0" } }, - "node_modules/codepage": { - "version": "1.15.0", - "resolved": "https://registry.npmjs.org/codepage/-/codepage-1.15.0.tgz", - "integrity": "sha512-3g6NUTPd/YtuuGrhMnOMRjFc+LJw/bnMp3+0r/Wcz3IXUuCosKRJvMphm5+Q+bvTVGcJJuRvVLuYba+WojaFaA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=0.8" - } - }, "node_modules/color": { "version": "5.0.3", "resolved": "https://registry.npmjs.org/color/-/color-5.0.3.tgz", @@ -2183,19 +2149,6 @@ "node": ">=10" } }, - "node_modules/crc-32": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz", - "integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "crc32": "bin/crc32.njs" - }, - "engines": { - "node": ">=0.8" - } - }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", @@ -3773,16 +3726,6 @@ "node": ">= 0.6" } }, - "node_modules/frac": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/frac/-/frac-1.1.2.tgz", - "integrity": "sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=0.8" - } - }, "node_modules/fresh": { "version": "0.5.2", "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", @@ -8389,19 +8332,6 @@ "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", "license": "BSD-3-Clause" }, - "node_modules/ssf": { - "version": "0.11.2", - "resolved": "https://registry.npmjs.org/ssf/-/ssf-0.11.2.tgz", - "integrity": "sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "frac": "~1.1.2" - }, - "engines": { - "node": ">=0.8" - } - }, "node_modules/stack-trace": { "version": "0.0.10", "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", @@ -9939,26 +9869,6 @@ "node": ">= 12.0.0" } }, - "node_modules/wmf": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wmf/-/wmf-1.0.2.tgz", - "integrity": "sha512-/p9K7bEh0Dj6WbXg4JG0xvLQmIadrner1bi45VMJTfnbVHsc7yIajZyoSoK60/dtVBs12Fm6WkUI5/3WAVsNMw==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=0.8" - } - }, - "node_modules/word": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/word/-/word-0.3.0.tgz", - "integrity": "sha512-OELeY0Q61OXpdUfTp+oweA/vtLVg5VDOXh+3he3PNzLGG/y0oylSOC1xRVj0+l4vQ3tj/bB1HVHv1ocXkQceFA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=0.8" - } - }, "node_modules/word-wrap": { "version": "1.2.5", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", @@ -10024,20 +9934,11 @@ } }, "node_modules/xlsx": { - "version": "0.18.5", - "resolved": "https://registry.npmjs.org/xlsx/-/xlsx-0.18.5.tgz", - "integrity": "sha512-dmg3LCjBPHZnQp5/F/+nnTa+miPJxUXB6vtk42YjBBKayDNagxGEeIdWApkYPOf3Z3pm3k62Knjzp7lMeTEtFQ==", + "version": "0.20.3", + "resolved": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz", + "integrity": "sha512-oLDq3jw7AcLqKWH2AhCpVTZl8mf6X2YReP+Neh0SJUzV/BdZYjth94tG5toiMB1PPrYtxOCfaoUCkvtuH+3AJA==", "dev": true, "license": "Apache-2.0", - "dependencies": { - "adler-32": "~1.3.0", - "cfb": "~1.2.1", - "codepage": "~1.15.0", - "crc-32": "~1.2.1", - "ssf": "~0.11.2", - "wmf": "~1.0.1", - "word": "~0.3.0" - }, "bin": { "xlsx": "bin/xlsx.njs" }, diff --git a/package.json b/package.json index 0de5a20f0..8632557ac 100644 --- a/package.json +++ b/package.json @@ -27,7 +27,7 @@ "sinon": "^15.0.4", "standard": "^16.0.3", "swagger-autogen": "^2.19.0", - "xlsx": "^0.18.5" + "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz" }, "dependencies": { "@cveproject/cve-validation-library": "github:CVEProject/cve-validation-library#v1.2.0", From 7a4e81d33076f56fd43255f38fc33af206fc2c10 Mon Sep 17 00:00:00 2001 From: David T Rocca Date: Tue, 1 Dec 2026 14:15:53 -0500 Subject: [PATCH 02/19] chore: remove the Monday migration and xlsx dependency --- package-lock.json | 16 +- package.json | 4 +- src/scripts/MondayHelpers.js | 376 ----------------------------------- src/scripts/MondayMigrate.js | 373 ---------------------------------- src/scripts/countries.js | 249 ----------------------- 5 files changed, 2 insertions(+), 1016 deletions(-) delete mode 100644 src/scripts/MondayHelpers.js delete mode 100644 src/scripts/MondayMigrate.js delete mode 100644 src/scripts/countries.js diff --git a/package-lock.json b/package-lock.json index cc1caed06..8fd534911 100644 --- a/package-lock.json +++ b/package-lock.json @@ -64,8 +64,7 @@ "replace-in-file": "6.3.5", "sinon": "^15.0.4", "standard": "^16.0.3", - "swagger-autogen": "^2.19.0", - "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz" + "swagger-autogen": "^2.19.0" } }, "node_modules/@babel/code-frame": { @@ -9933,19 +9932,6 @@ "node": ">=8" } }, - "node_modules/xlsx": { - "version": "0.20.3", - "resolved": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz", - "integrity": "sha512-oLDq3jw7AcLqKWH2AhCpVTZl8mf6X2YReP+Neh0SJUzV/BdZYjth94tG5toiMB1PPrYtxOCfaoUCkvtuH+3AJA==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "xlsx": "bin/xlsx.njs" - }, - "engines": { - "node": ">=0.8" - } - }, "node_modules/xtend": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", diff --git a/package.json b/package.json index 8632557ac..06c1ed4d4 100644 --- a/package.json +++ b/package.json @@ -26,8 +26,7 @@ "replace-in-file": "6.3.5", "sinon": "^15.0.4", "standard": "^16.0.3", - "swagger-autogen": "^2.19.0", - "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz" + "swagger-autogen": "^2.19.0" }, "dependencies": { "@cveproject/cve-validation-library": "github:CVEProject/cve-validation-library#v1.2.0", @@ -81,7 +80,6 @@ "lint:src": "node node_modules/eslint/bin/eslint.js src/ --fix", "lint:test": "node node_modules/eslint/bin/eslint.js test/ --fix", "lint:test-utils": "node node_modules/eslint/bin/eslint.js test-utils/ --fix", - "migrate:dev:monday": "NODE_ENV=development MONGO_CONN_STRING=mongodb://localhost:27017 MONGO_DB_NAME=cve_dev node-dev src/scripts/MondayMigrate.js", "db:preflight": "node src/scripts/databasePreflight.js", "db:migrate": "node migrations/node_modules/migrate-mongo/bin/migrate-mongo.js up -f src/scripts/migrationConfig.js", "db:migrate:dev": "NODE_ENV=development node migrations/node_modules/migrate-mongo/bin/migrate-mongo.js up -f src/scripts/migrationConfig.js", diff --git a/src/scripts/MondayHelpers.js b/src/scripts/MondayHelpers.js deleted file mode 100644 index 5ead4fe1d..000000000 --- a/src/scripts/MondayHelpers.js +++ /dev/null @@ -1,376 +0,0 @@ -const _ = require('lodash') -const XLSX = require('xlsx') -const path = require('path') -const { countryList } = require('./countries') -const { normalizeDateOnlyInput } = require('../utils/dateOnly') - -const mondayExportPath = path.join(__dirname, 'export.xlsx') - -const mondayTracker = { - dbOnlyShortNames: [], - mondayDuplicateShortNames: [], - mondayOnlyShortNames: [] -} -const pocEmailColumnNumbers = Array.from( - { length: 10 }, - (_, index) => index + 1 -) -const partnerRoleTypeValues = new Set([ - '', - 'Bug Bounty Provider', - 'CERT', - 'Consortium', - 'Hosted Service', - 'N/A', - 'Open Source', - 'Researcher', - 'Vendor' -]) - -const countryNames = new Set(countryList.map((country) => country.name)) -const countryAliases = new Map([ - ['UK', 'United Kingdom'], - ['Slovak Republic', 'Slovakia'], - ['Vietnam', 'Viet Nam'], - ['Russia', 'Russian Federation'], - ['South Korea', 'Korea, Republic of'], - ['T\u00fcrkiye', 'Turkey'], - ['Turkiye', 'Turkey'], - ['Czechia', 'Czech Republic'] -]) - -function toSnakeCase (header) { - return _.snakeCase( - String(header) - .replace( - /([A-Z]+)['\u2019]s\b/g, - (match, acronym) => `${acronym.toLowerCase()}s` - ) - .replace(/['\u2019]/g, '') - ) -} - -function loadMondayExport (exportPath = mondayExportPath) { - const workbook = XLSX.readFile(exportPath) - - // First sheet - org data - const worksheet = workbook.Sheets[workbook.SheetNames[0]] - const rows = XLSX.utils.sheet_to_json(worksheet, { header: 1, defval: '' }) - const headerIndex = rows.findIndex( - (row) => String(row[11]).trim() === 'Short Name' - ) - - if (headerIndex === -1) { - throw new Error( - 'Could not find Monday export header row with column L "Short Name".' - ) - } - - const headers = rows[headerIndex].map(toSnakeCase) - const shortNameIndex = headers.indexOf('short_name') - - if (shortNameIndex === -1) { - throw new Error('Could not find "short_name" column in Monday export.') - } - - const rawRows = rows.slice(headerIndex + 1).reduce((result, row) => { - const shortName = String(row[shortNameIndex]).trim() - if (!shortName || shortName === 'Short Name') return result - - result.push( - headers.reduce((record, header, index) => { - if (header) { - record[header] = index === shortNameIndex ? shortName : row[index] - } - return record - }, {}) - ) - - return result - }, []) - - findDuplicateShortNames(rawRows) - - // Second sheet - update (audit) data - const updatesWorksheet = workbook.Sheets[workbook.SheetNames[1]] - const updatesRows = XLSX.utils.sheet_to_json(updatesWorksheet, { header: 1, defval: '' }) - const updatesHeaderIndex = updatesRows.findIndex( - (row) => String(row[1]).trim() === 'Item Name' - ) - - if (updatesHeaderIndex === -1) { - throw new Error( - 'Could not find Monday export header row for updates with column B "Item Name".' - ) - } - - const updatesHeaders = updatesRows[updatesHeaderIndex].map(toSnakeCase) - const partnerNumberIndex = updatesHeaders.indexOf('item_name') - - if (partnerNumberIndex === -1) { - throw new Error('Could not find "item_name" column in Monday export.') - } - - const rawUpdatesRows = updatesRows.slice(updatesHeaderIndex + 1).reduce((result, row) => { - const partnerNumber = String(row[partnerNumberIndex]).trim() - if (!partnerNumber || partnerNumber === 'Item Name') return result - - result.push( - updatesHeaders.reduce((record, header, index) => { - if (header) { - record[header] = index === partnerNumberIndex ? partnerNumber : row[index] - } - return record - }, {}) - ) - - return result - }, []) - - return { - rawRows, - asOrgRows: buildAsOrgRows(rawRows), - rawUpdatesRows - } -} - -function buildAsOrgRows (rawRows) { - const unknownCountries = new Map() - const asOrgRows = rawRows.map((row) => ({ - short_name: row.short_name, - long_name: row.cna_long_name, - authority: [row.org_level], - top_level_root: row.top_level_root, - charter_or_scope: row.scope, - disclosure_policy: row.disclosure_policy, - advisory_locations: row.advisory_location, - advisory_location_require_credentials: - formatAdvisoryLocationRequireCredentials( - row.does_advisory_location_require_login_credentials - ), - vulnerability_advisory_location_for_web_scraping: toOptionalSingleItemArray( - row.vulnerability_advisory_location_s_for_web_scraping - ), - partner_role_type: formatPartnerRoleType(row.cna_role_type), - partner_number: formatPartnerNumber(row), - partner_country: normalizePartnerCountry(row, unknownCountries), - primary_poc_name: formatPocName(row.primary_poc_name), - poc_phone_1: formatPocPhone(row.poc_phone_1), - secondary_poc_name: formatPocName(row.secondary_poc_name), - poc_phone_2: formatPocPhone(row.poc_phone_2), - third_poc_name: formatPocName(row.third_poc_name), - ...buildPocEmailFields(row), - poc_emails: formatPocEmails(row), - industry: row.industry, - tl_root_start_date: formatDate(row.tl_root_start_date), - program_data: { - cve_website_update_date: formatDateOnly(row.date_website_updates), - partner_active_date: formatDateOnly(row.partner_active_date), - partner_inactive_date: formatDateOnly(row.partner_inactive_date), - status: row.status - } - })) - - for (const [country, shortNames] of unknownCountries.entries()) { - console.warn( - `Unknown CNA country "${country}" for short_name(s): ${shortNames.join(', ')}` - ) - } - - return asOrgRows -} - -function findDuplicateShortNames (rawRows) { - const shortNameCounts = new Map() - - for (const mondayOrg of rawRows) { - const shortName = String(mondayOrg.short_name || '').trim() - if (!shortName) continue - - shortNameCounts.set(shortName, (shortNameCounts.get(shortName) || 0) + 1) - } - - mondayTracker.mondayDuplicateShortNames = Array.from( - shortNameCounts.entries() - ) - .filter(([, count]) => count > 1) - .map(([shortName, count]) => ({ shortName, count })) -} - -function formatPartnerNumber (mondayOrg) { - const partnerName = String(mondayOrg.name || '').trim() - if (!partnerName) return '' - - const match = partnerName.match( - /^([^-]+)-(\d{4})-(\d+)(?:\s*\(([^)]*)\)?)?$/ - ) - if (!match) return partnerName - - const [, role, year, number, parentheticalRole] = match - const orgLevel = mondayOrg.org_level || parentheticalRole || role - const normalizedOrgLevel = String(orgLevel) - .trim() - .replace(/-/g, '') - .replace(/\s+/g, '') - .toUpperCase() - - return `${normalizedOrgLevel}-${year}-${number}` -} - -function formatPartnerRoleType (value) { - const values = Array.isArray(value) ? value : String(value || '').split(/[,\n;]/) - const validValues = values - .map((roleType) => String(roleType || '').trim()) - .filter((roleType) => partnerRoleTypeValues.has(roleType)) - - return validValues.length ? _.uniq(validValues) : undefined -} - -function normalizePartnerCountry (mondayOrg, unknownCountries) { - const shortName = String(mondayOrg.short_name || '').trim() - const country = String(mondayOrg.cna_country || '').trim() - const partnerCountry = countryAliases.get(country) || country - - if (!country) { - return '' - } else if (country === 'USA') { - return 'United States' - } else if (countryNames.has(partnerCountry)) { - return partnerCountry - } - - const shortNames = unknownCountries.get(partnerCountry) || [] - shortNames.push(shortName) - unknownCountries.set(partnerCountry, shortNames) - - return partnerCountry -} - -function toSingleItemArray (value) { - if (value == null) return [] - - const trimmedValue = String(value).trim() - if (!trimmedValue) return [] - - return [trimmedValue] -} - -function toOptionalSingleItemArray (value) { - const items = toSingleItemArray(value) - return items.length ? items : undefined -} - -function buildPocEmailFields (mondayOrg) { - return pocEmailColumnNumbers.reduce((fields, number) => { - fields[`poc_email_${number}`] = formatPocEmail( - mondayOrg[`poc_email_${number}`] - ) - return fields - }, {}) -} - -function formatPocEmails (mondayOrg) { - return _.uniqBy( - pocEmailColumnNumbers - .map((number) => mondayOrg[`poc_email_${number}`]) - .flatMap(formatPocEmailList), - (email) => email.toLowerCase() - ) -} - -function formatPocEmail (email) { - return String(email || '').trim() -} - -function formatPocName (name) { - return String(name || '').trim() -} - -function formatPocPhone (phone) { - return String(phone || '').trim() -} - -function formatPocEmailList (value) { - return formatPocEmail(value) - .split(',') - .map(formatPocEmail) - .filter(Boolean) -} - -function formatAdvisoryLocationRequireCredentials (value) { - if (value == null) return undefined - - const normalizedValue = String(value).trim().toLowerCase() - if (!normalizedValue) return undefined - if (normalizedValue.includes('yes')) return true - if (normalizedValue === 'no') return false - - return undefined -} - -function formatDate (value) { - if (value == null || value === '') return undefined - - if (value instanceof Date) { - return isNaN(value) ? undefined : value - } - - if (typeof value === 'number') { - const parsedDate = XLSX.SSF.parse_date_code(value) - if (!parsedDate) return undefined - - return new Date(Date.UTC(parsedDate.y, parsedDate.m - 1, parsedDate.d)) - } - - const date = new Date(String(value).trim()) - return isNaN(date) ? undefined : date -} - -function formatDateOnly (value) { - if (value == null || value === '') return null - - if (value instanceof Date) { - return normalizeDateOnlyInput(value) - } - - if (typeof value === 'number') { - const parsedDate = XLSX.SSF.parse_date_code(value) - if (!parsedDate) return value - - return [ - String(parsedDate.y).padStart(4, '0'), - String(parsedDate.m).padStart(2, '0'), - String(parsedDate.d).padStart(2, '0') - ].join('-') - } - - return normalizeDateOnlyInput(String(value).trim()) -} - -function runCli () { - const mondayExport = loadMondayExport() - - console.log( - `Loaded ${mondayExport.rawRows.length} raw Monday rows and ${mondayExport.asOrgRows.length} converted org rows.` - ) - console.log( - JSON.stringify( - { - firstRawRow: mondayExport.rawRows[0], - firstAsOrgRow: mondayExport.asOrgRows[0], - duplicateShortNames: mondayTracker.mondayDuplicateShortNames - }, - null, - 2 - ) - ) -} - -if (require.main === module) { - runCli() -} - -module.exports = { - loadMondayExport, - mondayTracker -} diff --git a/src/scripts/MondayMigrate.js b/src/scripts/MondayMigrate.js deleted file mode 100644 index 6f7e9b4cc..000000000 --- a/src/scripts/MondayMigrate.js +++ /dev/null @@ -1,373 +0,0 @@ -/** - * MondayMigrate.js - * - * Optional migration step for applying Monday export data to populated BaseOrg records. - * - * Run this against a database that already contains BaseOrg and BaseUser records, and make sure - * export.xlsx is available in src/scripts. - */ - -require('dotenv').config() -const { MongoClient } = require('mongodb') -const _ = require('lodash') -const validator = require('validator') -const uuid = require('uuid') -const { loadMondayExport } = require('./MondayHelpers') - -const dbConnStr = process.env.MONGO_CONN_STRING - -const mondayMigrationStats = { - matchedCount: 0, - dbOnlyShortNames: [], - duplicateMatchesResolved: [], - duplicateMatchesUnresolved: [] -} -const pocContactFields = [ - { - emailField: 'poc_email_1', - nameField: 'primary_poc_name', - phoneField: 'poc_phone_1' - }, - { - emailField: 'poc_email_2', - nameField: 'secondary_poc_name', - phoneField: 'poc_phone_2' - }, - { - emailField: 'poc_email_3', - nameField: 'third_poc_name' - }, - ...Array.from({ length: 7 }, (_, index) => ({ - emailField: `poc_email_${index + 4}` - })) -] -let allBaseOrgs = [] - -function deepRemoveEmpty (obj) { - if (_.isArray(obj)) { - return obj - .map(v => deepRemoveEmpty(v)) - .filter(v => { - return !( - v === undefined || - v === null || - (_.isArray(v) && v.length === 0) || - (_.isPlainObject(v) && _.isEmpty(v)) - ) - }) - } else if (_.isPlainObject(obj)) { - return _.transform(obj, (result, value, key) => { - const cleaned = deepRemoveEmpty(value) - if ( - !( - cleaned === undefined || - cleaned === null || - (_.isArray(cleaned) && cleaned.length === 0) || - (_.isPlainObject(cleaned) && _.isEmpty(cleaned)) - ) - ) { - result[key] = cleaned - } - }) - } - return obj -} - -async function run () { - const dbClient = new MongoClient(dbConnStr) - try { - await dbClient.connect() - - const db = await dbClient.db(process.env.MONGO_DB_NAME) - const mondayExport = loadMondayExport() - const unmatchedAsOrgRows = [...mondayExport.asOrgRows] - console.log( - `Loaded ${mondayExport.rawRows.length} raw Monday rows, ${mondayExport.asOrgRows.length} converted org rows, and ${mondayExport.rawUpdatesRows.length} update rows.` - ) - - await mondayOrgHelper(db, unmatchedAsOrgRows) - await mondayUpdatesHelper(db, mondayExport.rawUpdatesRows) - printMondayMigrationStats(unmatchedAsOrgRows) - } catch (err) { - await dbClient.close() - - console.error(err) - } finally { - await dbClient.close() - } -} - -function normalizeAuthority (authority) { - return String(authority || '') - .trim() - .replace(/[^a-zA-Z0-9]/g, '') - .toUpperCase() -} - -function hasMatchingAuthority (doc, asOrgRow) { - const docAuthorities = new Set( - (doc.authority || []).map(normalizeAuthority) - ) - return (asOrgRow.authority || []).some((authority) => - docAuthorities.has(normalizeAuthority(authority)) - ) -} - -function describeAsOrgRow (asOrgRow) { - return `${asOrgRow.short_name} [${(asOrgRow.authority || []).join(', ') || 'no authority'}] ${asOrgRow.partner_number || 'no partner_number'}` -} - -function consumeAsOrgRow (asOrgRows, asOrgRow) { - const index = asOrgRows.indexOf(asOrgRow) - - if (index !== -1) { - asOrgRows.splice(index, 1) - } - - mondayMigrationStats.matchedCount += 1 - return asOrgRow -} - -function findAsOrgRowForOrg (doc, asOrgRows) { - const shortNameMatches = asOrgRows.filter( - (asOrgRow) => asOrgRow.short_name === doc.short_name - ) - - if (shortNameMatches.length === 0) { - mondayMigrationStats.dbOnlyShortNames.push(doc.short_name) - return null - } - - if (shortNameMatches.length === 1) { - return consumeAsOrgRow(asOrgRows, shortNameMatches[0]) - } - - const authorityMatches = shortNameMatches.filter((asOrgRow) => - hasMatchingAuthority(doc, asOrgRow) - ) - - if (authorityMatches.length === 1) { - mondayMigrationStats.duplicateMatchesResolved.push({ - short_name: doc.short_name, - db_authority: doc.authority || [], - matched: describeAsOrgRow(authorityMatches[0]) - }) - return consumeAsOrgRow(asOrgRows, authorityMatches[0]) - } - - mondayMigrationStats.duplicateMatchesUnresolved.push({ - short_name: doc.short_name, - db_authority: doc.authority || [], - candidates: shortNameMatches.map(describeAsOrgRow) - }) - return null -} - -function normalizeEmail (email) { - return String(email || '').trim().toLowerCase() -} - -function isValidEmail (email) { - return validator.isEmail(String(email || '').trim()) -} - -function splitEmailList (value) { - return String(value || '') - .split(',') - .map((email) => email.trim()) - .filter(isValidEmail) -} - -function formatBaseUserName (name) { - if (typeof name === 'string') return name.trim() - if (!name || typeof name !== 'object') return '' - - return [name.suffix, name.first, name.middle, name.last] - .map((value) => String(value || '').trim()) - .filter(Boolean) - .join(' ') -} - -function buildUsersByUsername (users) { - return users.reduce((usersByUsername, user) => { - const username = normalizeEmail(user.username) - if (username && !usersByUsername.has(username)) { - usersByUsername.set(username, user) - } - - return usersByUsername - }, new Map()) -} - -function buildPrivateContacts (asOrgRow, usersByUsername) { - return pocContactFields.flatMap((pocContactField) => { - const emails = splitEmailList(asOrgRow[pocContactField.emailField]) - const fallbackName = pocContactField.nameField - ? String(asOrgRow[pocContactField.nameField] || '').trim() - : '' - const phone = pocContactField.phoneField - ? String(asOrgRow[pocContactField.phoneField] || '').trim() - : '' - - return emails.map((email) => { - const user = usersByUsername.get(normalizeEmail(email)) - const poc = formatBaseUserName(user?.name) || fallbackName - - return { - poc_email: email, - poc, - phone - } - }) - }) -} - -function buildMondayOrgUpdateFields (asOrgRow, usersByUsername = new Map()) { - if (!asOrgRow) return {} - - return { - long_name: asOrgRow.long_name, - authority: asOrgRow.authority, - top_level_root: asOrgRow.top_level_root, - charter_or_scope: asOrgRow.charter_or_scope, - disclosure_policy: asOrgRow.disclosure_policy, - advisory_locations: asOrgRow.advisory_locations, - advisory_location_require_credentials: - asOrgRow.advisory_location_require_credentials, - vulnerability_advisory_location_for_web_scraping: - asOrgRow.vulnerability_advisory_location_for_web_scraping, - partner_role_type: asOrgRow.partner_role_type, - partner_number: asOrgRow.partner_number, - partner_country: asOrgRow.partner_country, - industry: asOrgRow.industry, - tl_root_start_date: asOrgRow.tl_root_start_date, - private_contacts: buildPrivateContacts(asOrgRow, usersByUsername), - program_data: asOrgRow.program_data - } -} - -function printMondayMigrationStats (unmatchedAsOrgRows) { - console.log( - `Matched BaseOrg records to Monday rows: ${mondayMigrationStats.matchedCount}/${allBaseOrgs.length}.` - ) - - if (mondayMigrationStats.dbOnlyShortNames.length) { - console.log( - `BaseOrg records without Monday row (${mondayMigrationStats.dbOnlyShortNames.length}): ${mondayMigrationStats.dbOnlyShortNames.join(', ')}` - ) - } - - if (mondayMigrationStats.duplicateMatchesResolved.length) { - console.log( - `Duplicate Monday rows resolved by authority (${mondayMigrationStats.duplicateMatchesResolved.length}): ${mondayMigrationStats.duplicateMatchesResolved.map((match) => `${match.short_name} -> ${match.matched}`).join(', ')}` - ) - } - - if (mondayMigrationStats.duplicateMatchesUnresolved.length) { - console.log( - `Duplicate Monday rows not resolved by authority (${mondayMigrationStats.duplicateMatchesUnresolved.length}): ${mondayMigrationStats.duplicateMatchesUnresolved.map((match) => `${match.short_name} [DB: ${(match.db_authority || []).join(', ') || 'no authority'}] candidates: ${match.candidates.join(' | ')}`).join('; ')}` - ) - } - - console.log(`Unconsumed Monday org rows: ${unmatchedAsOrgRows.length}.`) - - if (unmatchedAsOrgRows.length) { - console.log( - `Unconsumed Monday org row(s): ${unmatchedAsOrgRows.map(describeAsOrgRow).join(', ')}` - ) - } -} - -async function mondayOrgHelper (db, asOrgRows) { - console.log('Running Monday Org sync...') - const trgOrgCol = await db.collection('BaseOrg') - const trgUserCol = await db.collection('BaseUser') - - allBaseOrgs = await trgOrgCol.find().toArray() - const allBaseUsers = await trgUserCol.find().toArray() - const usersByUsername = buildUsersByUsername(allBaseUsers) - - for (const doc of allBaseOrgs) { - const asOrgRow = findAsOrgRowForOrg(doc, asOrgRows) - if (!asOrgRow) continue - - const trgQuery = { - short_name: doc.short_name - } - const mondayFields = buildMondayOrgUpdateFields(asOrgRow, usersByUsername) - const updateDoc = deepRemoveEmpty({ - $set: mondayFields - }) - if (mondayFields.private_contacts.length === 0) { - updateDoc.$set = updateDoc.$set || {} - updateDoc.$set.private_contacts = [] - } - - await trgOrgCol.updateOne(trgQuery, updateDoc) - } -} - -async function mondayUpdatesHelper (db, asUpdateRows) { - console.log('Running Monday updates sync...') - const orgCol = await db.collection('BaseOrg') - const conversationCol = await db.collection('Conversation') - const updatesMap = {} - - // Map to partner number - for (const updateRow of asUpdateRows) { - const partnerNumber = String(updateRow.item_name || '').trim().split(' ')[0] - if (!partnerNumber) continue - - if (!updatesMap[partnerNumber]) { - updatesMap[partnerNumber] = [] - } - updatesMap[partnerNumber].push(updateRow) - } - - for (const [partnerNumber, updateRows] of Object.entries(updatesMap)) { - const orgDoc = await orgCol.findOne({ partner_number: partnerNumber }) - if (!orgDoc) continue - - updateRows.sort((a, b) => new Date(a.created_at) - new Date(b.created_at)) - - // Check for existing conversations (should be none on initial migration, but just in case) - const existingConversations = await conversationCol.find({ target_uuid: orgDoc.UUID }).sort({ posted_at: -1 }).toArray() - let previousUUID = existingConversations.length > 0 ? existingConversations[0].UUID : null - const firstNewUUID = uuid.v4() - let newUUID = firstNewUUID - - for (const [idx, updateRow] of updateRows.entries()) { - const conversationDoc = { - UUID: newUUID, - previous_conversation_uuid: previousUUID, - target_uuid: orgDoc.UUID, - author_name: String(updateRow.user || 'Unknown User').trim(), - body: String(updateRow.update_content || '').trim(), - visibility: 'private', - posted_at: new Date(updateRow.created_at) - } - - previousUUID = conversationDoc.UUID - newUUID = idx === updateRows.length - 1 ? null : uuid.v4() - conversationDoc.next_conversation_uuid = newUUID - await conversationCol.insertOne(conversationDoc) - } - - if (existingConversations.length > 0) { - // Link the last existing conversation to the first new one - await conversationCol.updateOne({ UUID: existingConversations[0].UUID }, { $set: { next_conversation_uuid: firstNewUUID } }) - } - } -} - -if (require.main === module) { - run() -} - -module.exports = { - buildMondayOrgUpdateFields, - buildPrivateContacts, - findAsOrgRowForOrg, - mondayMigrationStats, - run -} diff --git a/src/scripts/countries.js b/src/scripts/countries.js deleted file mode 100644 index 3fd494f64..000000000 --- a/src/scripts/countries.js +++ /dev/null @@ -1,249 +0,0 @@ -const countryList = [ - { name: 'Non Affiliate', code: 'N/A' }, - { name: 'Afghanistan', code: 'AF' }, - { name: 'land Islands', code: 'AX' }, - { name: 'Albania', code: 'AL' }, - { name: 'Algeria', code: 'DZ' }, - { name: 'American Samoa', code: 'AS' }, - { name: 'AndorrA', code: 'AD' }, - { name: 'Angola', code: 'AO' }, - { name: 'Anguilla', code: 'AI' }, - { name: 'Antarctica', code: 'AQ' }, - { name: 'Antigua and Barbuda', code: 'AG' }, - { name: 'Argentina', code: 'AR' }, - { name: 'Armenia', code: 'AM' }, - { name: 'Aruba', code: 'AW' }, - { name: 'Australia', code: 'AU' }, - { name: 'Austria', code: 'AT' }, - { name: 'Azerbaijan', code: 'AZ' }, - { name: 'Bahamas', code: 'BS' }, - { name: 'Bahrain', code: 'BH' }, - { name: 'Bangladesh', code: 'BD' }, - { name: 'Barbados', code: 'BB' }, - { name: 'Belarus', code: 'BY' }, - { name: 'Belgium', code: 'BE' }, - { name: 'Belize', code: 'BZ' }, - { name: 'Benin', code: 'BJ' }, - { name: 'Bermuda', code: 'BM' }, - { name: 'Bhutan', code: 'BT' }, - { name: 'Bolivia', code: 'BO' }, - { name: 'Bosnia and Herzegovina', code: 'BA' }, - { name: 'Botswana', code: 'BW' }, - { name: 'Bouvet Island', code: 'BV' }, - { name: 'Brazil', code: 'BR' }, - { name: 'British Indian Ocean Territory', code: 'IO' }, - { name: 'Brunei Darussalam', code: 'BN' }, - { name: 'Bulgaria', code: 'BG' }, - { name: 'Burkina Faso', code: 'BF' }, - { name: 'Burundi', code: 'BI' }, - { name: 'Cambodia', code: 'KH' }, - { name: 'Cameroon', code: 'CM' }, - { name: 'Canada', code: 'CA' }, - { name: 'Cape Verde', code: 'CV' }, - { name: 'Cayman Islands', code: 'KY' }, - { name: 'Central African Republic', code: 'CF' }, - { name: 'Chad', code: 'TD' }, - { name: 'Chile', code: 'CL' }, - { name: 'China', code: 'CN' }, - { name: 'Christmas Island', code: 'CX' }, - { name: 'Cocos (Keeling) Islands', code: 'CC' }, - { name: 'Colombia', code: 'CO' }, - { name: 'Comoros', code: 'KM' }, - { name: 'Congo', code: 'CG' }, - { name: 'Congo, The Democratic Republic of the', code: 'CD' }, - { name: 'Cook Islands', code: 'CK' }, - { name: 'Costa Rica', code: 'CR' }, - { name: 'Cote D"Ivoire', code: 'CI' }, - { name: 'Croatia', code: 'HR' }, - { name: 'Cuba', code: 'CU' }, - { name: 'Cyprus', code: 'CY' }, - { name: 'Czech Republic', code: 'CZ' }, - { name: 'Denmark', code: 'DK' }, - { name: 'Djibouti', code: 'DJ' }, - { name: 'Dominica', code: 'DM' }, - { name: 'Dominican Republic', code: 'DO' }, - { name: 'Ecuador', code: 'EC' }, - { name: 'Egypt', code: 'EG' }, - { name: 'El Salvador', code: 'SV' }, - { name: 'Equatorial Guinea', code: 'GQ' }, - { name: 'Eritrea', code: 'ER' }, - { name: 'Estonia', code: 'EE' }, - { name: 'Ethiopia', code: 'ET' }, - { name: 'Falkland Islands (Malvinas)', code: 'FK' }, - { name: 'Faroe Islands', code: 'FO' }, - { name: 'Fiji', code: 'FJ' }, - { name: 'Finland', code: 'FI' }, - { name: 'France', code: 'FR' }, - { name: 'French Guiana', code: 'GF' }, - { name: 'French Polynesia', code: 'PF' }, - { name: 'French Southern Territories', code: 'TF' }, - { name: 'Gabon', code: 'GA' }, - { name: 'Gambia', code: 'GM' }, - { name: 'Georgia', code: 'GE' }, - { name: 'Germany', code: 'DE' }, - { name: 'Ghana', code: 'GH' }, - { name: 'Gibraltar', code: 'GI' }, - { name: 'Greece', code: 'GR' }, - { name: 'Greenland', code: 'GL' }, - { name: 'Grenada', code: 'GD' }, - { name: 'Guadeloupe', code: 'GP' }, - { name: 'Guam', code: 'GU' }, - { name: 'Guatemala', code: 'GT' }, - { name: 'Guernsey', code: 'GG' }, - { name: 'Guinea', code: 'GN' }, - { name: 'Guinea-Bissau', code: 'GW' }, - { name: 'Guyana', code: 'GY' }, - { name: 'Haiti', code: 'HT' }, - { name: 'Heard Island and Mcdonald Islands', code: 'HM' }, - { name: 'Holy See (Vatican City State)', code: 'VA' }, - { name: 'Honduras', code: 'HN' }, - { name: 'Hong Kong', code: 'HK' }, - { name: 'Hungary', code: 'HU' }, - { name: 'Iceland', code: 'IS' }, - { name: 'India', code: 'IN' }, - { name: 'Indonesia', code: 'ID' }, - { name: 'Iran, Islamic Republic Of', code: 'IR' }, - { name: 'Iraq', code: 'IQ' }, - { name: 'Ireland', code: 'IE' }, - { name: 'Isle of Man', code: 'IM' }, - { name: 'Israel', code: 'IL' }, - { name: 'Italy', code: 'IT' }, - { name: 'Jamaica', code: 'JM' }, - { name: 'Japan', code: 'JP' }, - { name: 'Jersey', code: 'JE' }, - { name: 'Jordan', code: 'JO' }, - { name: 'Kazakhstan', code: 'KZ' }, - { name: 'Kenya', code: 'KE' }, - { name: 'Kiribati', code: 'KI' }, - { name: 'Korea, Democratic People"S Republic of', code: 'KP' }, - { name: 'Korea, Republic of', code: 'KR' }, - { name: 'Kuwait', code: 'KW' }, - { name: 'Kyrgyzstan', code: 'KG' }, - { name: 'Lao People"S Democratic Republic', code: 'LA' }, - { name: 'Latvia', code: 'LV' }, - { name: 'Lebanon', code: 'LB' }, - { name: 'Lesotho', code: 'LS' }, - { name: 'Liberia', code: 'LR' }, - { name: 'Libyan Arab Jamahiriya', code: 'LY' }, - { name: 'Liechtenstein', code: 'LI' }, - { name: 'Lithuania', code: 'LT' }, - { name: 'Luxembourg', code: 'LU' }, - { name: 'Macao', code: 'MO' }, - { name: 'Macedonia, The Former Yugoslav Republic of', code: 'MK' }, - { name: 'Madagascar', code: 'MG' }, - { name: 'Malawi', code: 'MW' }, - { name: 'Malaysia', code: 'MY' }, - { name: 'Maldives', code: 'MV' }, - { name: 'Mali', code: 'ML' }, - { name: 'Malta', code: 'MT' }, - { name: 'Marshall Islands', code: 'MH' }, - { name: 'Martinique', code: 'MQ' }, - { name: 'Mauritania', code: 'MR' }, - { name: 'Mauritius', code: 'MU' }, - { name: 'Mayotte', code: 'YT' }, - { name: 'Mexico', code: 'MX' }, - { name: 'Micronesia, Federated States of', code: 'FM' }, - { name: 'Moldova, Republic of', code: 'MD' }, - { name: 'Monaco', code: 'MC' }, - { name: 'Mongolia', code: 'MN' }, - { name: 'Montenegro', code: 'ME' }, - { name: 'Montserrat', code: 'MS' }, - { name: 'Morocco', code: 'MA' }, - { name: 'Mozambique', code: 'MZ' }, - { name: 'Myanmar', code: 'MM' }, - { name: 'Namibia', code: 'NA' }, - { name: 'Nauru', code: 'NR' }, - { name: 'Nepal', code: 'NP' }, - { name: 'Netherlands', code: 'NL' }, - { name: 'Netherlands Antilles', code: 'AN' }, - { name: 'New Caledonia', code: 'NC' }, - { name: 'New Zealand', code: 'NZ' }, - { name: 'Nicaragua', code: 'NI' }, - { name: 'Niger', code: 'NE' }, - { name: 'Nigeria', code: 'NG' }, - { name: 'Niue', code: 'NU' }, - { name: 'Norfolk Island', code: 'NF' }, - { name: 'Northern Mariana Islands', code: 'MP' }, - { name: 'Norway', code: 'NO' }, - { name: 'Oman', code: 'OM' }, - { name: 'Pakistan', code: 'PK' }, - { name: 'Palau', code: 'PW' }, - { name: 'Palestinian Territory, Occupied', code: 'PS' }, - { name: 'Panama', code: 'PA' }, - { name: 'Papua New Guinea', code: 'PG' }, - { name: 'Paraguay', code: 'PY' }, - { name: 'Peru', code: 'PE' }, - { name: 'Philippines', code: 'PH' }, - { name: 'Pitcairn', code: 'PN' }, - { name: 'Poland', code: 'PL' }, - { name: 'Portugal', code: 'PT' }, - { name: 'Puerto Rico', code: 'PR' }, - { name: 'Qatar', code: 'QA' }, - { name: 'Reunion', code: 'RE' }, - { name: 'Romania', code: 'RO' }, - { name: 'Russian Federation', code: 'RU' }, - { name: 'RWANDA', code: 'RW' }, - { name: 'Saint Helena', code: 'SH' }, - { name: 'Saint Kitts and Nevis', code: 'KN' }, - { name: 'Saint Lucia', code: 'LC' }, - { name: 'Saint Pierre and Miquelon', code: 'PM' }, - { name: 'Saint Vincent and the Grenadines', code: 'VC' }, - { name: 'Samoa', code: 'WS' }, - { name: 'San Marino', code: 'SM' }, - { name: 'Sao Tome and Principe', code: 'ST' }, - { name: 'Saudi Arabia', code: 'SA' }, - { name: 'Senegal', code: 'SN' }, - { name: 'Serbia', code: 'RS' }, - { name: 'Seychelles', code: 'SC' }, - { name: 'Sierra Leone', code: 'SL' }, - { name: 'Singapore', code: 'SG' }, - { name: 'Slovakia', code: 'SK' }, - { name: 'Slovenia', code: 'SI' }, - { name: 'Solomon Islands', code: 'SB' }, - { name: 'Somalia', code: 'SO' }, - { name: 'South Africa', code: 'ZA' }, - { name: 'South Georgia and the South Sandwich Islands', code: 'GS' }, - { name: 'Spain', code: 'ES' }, - { name: 'Sri Lanka', code: 'LK' }, - { name: 'Sudan', code: 'SD' }, - { name: 'Suriname', code: 'SR' }, - { name: 'Svalbard and Jan Mayen', code: 'SJ' }, - { name: 'Swaziland', code: 'SZ' }, - { name: 'Sweden', code: 'SE' }, - { name: 'Switzerland', code: 'CH' }, - { name: 'Syrian Arab Republic', code: 'SY' }, - { name: 'Taiwan', code: 'TW' }, - { name: 'Tajikistan', code: 'TJ' }, - { name: 'Tanzania, United Republic of', code: 'TZ' }, - { name: 'Thailand', code: 'TH' }, - { name: 'Timor-Leste', code: 'TL' }, - { name: 'Togo', code: 'TG' }, - { name: 'Tokelau', code: 'TK' }, - { name: 'Tonga', code: 'TO' }, - { name: 'Trinidad and Tobago', code: 'TT' }, - { name: 'Tunisia', code: 'TN' }, - { name: 'Turkey', code: 'TR' }, - { name: 'Turkmenistan', code: 'TM' }, - { name: 'Turks and Caicos Islands', code: 'TC' }, - { name: 'Tuvalu', code: 'TV' }, - { name: 'Uganda', code: 'UG' }, - { name: 'Ukraine', code: 'UA' }, - { name: 'United Arab Emirates', code: 'AE' }, - { name: 'United Kingdom', code: 'GB' }, - { name: 'United States', code: 'US' }, - { name: 'United States Minor Outlying Islands', code: 'UM' }, - { name: 'Uruguay', code: 'UY' }, - { name: 'Uzbekistan', code: 'UZ' }, - { name: 'Vanuatu', code: 'VU' }, - { name: 'Venezuela', code: 'VE' }, - { name: 'Viet Nam', code: 'VN' }, - { name: 'Virgin Islands, British', code: 'VG' }, - { name: 'Virgin Islands, U.S.', code: 'VI' }, - { name: 'Wallis and Futuna', code: 'WF' }, - { name: 'Western Sahara', code: 'EH' }, - { name: 'Yemen', code: 'YE' }, - { name: 'Zambia', code: 'ZM' }, - { name: 'Zimbabwe', code: 'ZW' } -] - -module.exports = { countryList } From e42555ab8ab4a4a8b698da8fdaeb30210455e4d2 Mon Sep 17 00:00:00 2001 From: David T Rocca Date: Mon, 30 Nov 2026 11:12:20 -0500 Subject: [PATCH 03/19] fix: replace depcheck with Knip and patch nested uuid dependencies --- package-lock.json | 1628 ++++++++++++++++++++++++++++++--------------- package.json | 17 +- 2 files changed, 1098 insertions(+), 547 deletions(-) diff --git a/package-lock.json b/package-lock.json index 8fd534911..471a92e1f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -50,7 +50,6 @@ "chai-string": "^1.5.0", "chai-things": "^0.2.0", "chai-uuid": "^1.0.6", - "depcheck": "^1.4.7", "eslint": "^8.20.0", "eslint-config-standard": "^14.1.1", "eslint-plugin-import": "^2.26.0", @@ -58,6 +57,7 @@ "eslint-plugin-node": "^11.0.0", "eslint-plugin-promise": "^4.2.1", "eslint-plugin-standard": "^4.0.1", + "knip": "6.49.0", "mocha": "^10.8.2", "node-dev": "^7.4.3", "nyc": "^15.1.0", @@ -398,6 +398,40 @@ "kuler": "^2.0.0" } }, + "node_modules/@emnapi/core": { + "version": "1.11.2", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.2.tgz", + "integrity": "sha512-TC8MkTuZUtcTSiFeuC0ksCh9QIJ5+F21MvZ4Wn4ORfYaFJ/0dsiudv5tVkejgwZlwQ39jL9WWDe2lz8x0WglOA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.2", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.11.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.2.tgz", + "integrity": "sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.2.tgz", + "integrity": "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@eslint-community/eslint-utils": { "version": "4.9.1", "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz", @@ -770,6 +804,28 @@ "sparse-bitfield": "^3.0.3" } }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.7.tgz", + "integrity": "sha512-zJccwplOAbgfZju95IUHazLnx9RAPtPN2YGJXI6UbrgeaR9QfPjGrQL6ERkSAtnVCA4Q+83ApGyaX5zdpCaKkQ==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3" + } + }, "node_modules/@noble/hashes": { "version": "1.8.0", "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", @@ -818,9 +874,661 @@ "fastq": "^1.6.0" }, "engines": { - "node": ">= 8" + "node": ">= 8" + } + }, + "node_modules/@oxc-parser/binding-android-arm-eabi": { + "version": "0.160.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-android-arm-eabi/-/binding-android-arm-eabi-0.160.0.tgz", + "integrity": "sha512-IGhHufQ5uRhivrpzCcUJ92Mj4kYyFVhghaWk9hgZP/b+7WxdzdhFqBbH+PwEcfssDdIW10YHXcFvWib3kMX4Zg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-android-arm64": { + "version": "0.160.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-android-arm64/-/binding-android-arm64-0.160.0.tgz", + "integrity": "sha512-VxqVDFdTJG/QrJJ5pc/JIocKExtxCGcKf9qBsjIMS2VymVnHNdDu58d35pkgxIMFhxJ92YD79+66SBv86GXfCw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-darwin-arm64": { + "version": "0.160.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-darwin-arm64/-/binding-darwin-arm64-0.160.0.tgz", + "integrity": "sha512-W5ULJkX2YAZAi6h2gkWCZCq1Ws5ZTIejBXjQP3tdf/UOeJaNQes4Vo5659/szYrFoBTef+WWcOU4HaY3TT4OYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-darwin-x64": { + "version": "0.160.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-darwin-x64/-/binding-darwin-x64-0.160.0.tgz", + "integrity": "sha512-NNV6qakT/DX8SLqpe/gJ2ab2yDVJ+y6DKdJrbyTAdkpMjTP1KljiUxtAwoKVlHVPqfGMFPpSHIU9yL3FAWG/3w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-freebsd-x64": { + "version": "0.160.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-freebsd-x64/-/binding-freebsd-x64-0.160.0.tgz", + "integrity": "sha512-P1Ay7bTnFJarHefoBOOrzZ8ynRluk0w92p/+PwkAYgg38Fh5Z2eQN2slzYqODyNQRDd2YrdecLV038V6KmqfXw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-arm-gnueabihf": { + "version": "0.160.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.160.0.tgz", + "integrity": "sha512-jw16rzFMeyaGRTVoHTiKAe5qHa6T5v54GX0TGoAvbEskN+hQcK0pZQ+pi5n3yGZ7b1+vTF2eBuqQP98mgcd6XA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-arm-musleabihf": { + "version": "0.160.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.160.0.tgz", + "integrity": "sha512-B55bnJn8XMC8NDBbEsL6Za2ZuFx6RIG49GMSlHYfpIc2pWQ6sbJRwarP+iKXnPgpJ1N7wfOAotMp58NUYjzQaQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-arm64-gnu": { + "version": "0.160.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.160.0.tgz", + "integrity": "sha512-YKVHxONDpWXTPfilLv2MKvaI7VbYnKHARr5wJ3KKKGk0OkauDc0tVFyZlKFwIy9+br46fh8AjTVCnz6+9gKxVA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-arm64-musl": { + "version": "0.160.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.160.0.tgz", + "integrity": "sha512-uiVA0AemCVB3+oZ3JmjQCSEqiGIgl+o3+bLqORIfviJbyYlVUChoRh6cVbyyDG6zm4fW0RtQIdKq3fVYuNTA3Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-ppc64-gnu": { + "version": "0.160.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.160.0.tgz", + "integrity": "sha512-h/tr4lWGdRXs4rUktl84Z0CprQhdDlxN4D82/cCcoKr0Kb4TEIJriXZVqHPznp12/uBWcV+BiihUBPbeyZm1KQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-riscv64-gnu": { + "version": "0.160.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.160.0.tgz", + "integrity": "sha512-bA/Ba24KZYxorIUBHF2NbXM0OVY24xowGu4L0YBzpXhivt+ks1z8BT/c+BYGSfdFFqWrfNkC5TJjQGWdRkUHWQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-riscv64-musl": { + "version": "0.160.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.160.0.tgz", + "integrity": "sha512-1uI9RghjO7/JQzkL9M/EDnG0Egy5z4v3k5TCUbPESZVUawHEmC52MMnCLe7f2CjMtiLjsm879CnO2HkRtsECNA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-s390x-gnu": { + "version": "0.160.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.160.0.tgz", + "integrity": "sha512-1gaVKLXjT+UML8w8ypK93KUJurvUUmegqgQ/7qijDNpGCuogmTOIu0KgsYqL2hH//amY3AtfQhTTMlw9l363wA==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-x64-gnu": { + "version": "0.160.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.160.0.tgz", + "integrity": "sha512-v44/JCrzpIof2jAJwF9W1j9l7mZKEaKihd8vBECBaNyIPcOiO4dtkeGX51MxnGmrJbsltdvTJb60VXLyMyAD2w==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-x64-musl": { + "version": "0.160.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-x64-musl/-/binding-linux-x64-musl-0.160.0.tgz", + "integrity": "sha512-NOT9x+x27Aitn+z6PggidaeHiKOpbglRXwzcHg+3VqbMT7nv/C3fnXKeVESy4o0u3Yb3mEocwPrtzlT5O53JSA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-openharmony-arm64": { + "version": "0.160.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-openharmony-arm64/-/binding-openharmony-arm64-0.160.0.tgz", + "integrity": "sha512-kXFdUqEkbB1E66dfqu7sk65w0CaDVp+uPeJ4eOacxBuVgKk/poy+b8/XpFfV443UNB8LUUvzgTzyWLxDQte2Dw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-win32-arm64-msvc": { + "version": "0.160.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.160.0.tgz", + "integrity": "sha512-tzYHz6BOwmKCY2c8txeV06CkMzwEVQhFwug8OR75q2UVRMfksf9yD5UBjAeauPEiFhzNogg1RRyk8UZ0bjMXvg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-win32-ia32-msvc": { + "version": "0.160.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.160.0.tgz", + "integrity": "sha512-vyYZ4gcWUPuPANDj66eBnZ7+CFzUU0pzX28a5armxejWxM7onM3awHkM4PB/al8eEZ3MH8l0AprX/1jXrfGh7Q==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-win32-x64-msvc": { + "version": "0.160.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.160.0.tgz", + "integrity": "sha512-KvENUAjmLfLBJBTF9yQ2wb5/DH41+FPM45oM7NMTgW0R3kN49NUj314SaDqqqkba+4cNTBt8NA2Ux5dekZB68w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.160.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.160.0.tgz", + "integrity": "sha512-gw4k9syEmnckbOgw2A2FU1TBDdX9hfwV9jEn/uio65pguPzwWiXQS3OIJDMEhv9m06tj9XiEe6RoD0YA+LgreA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@oxc-resolver/binding-android-arm-eabi": { + "version": "11.24.2", + "resolved": "https://registry.npmjs.org/@oxc-resolver/binding-android-arm-eabi/-/binding-android-arm-eabi-11.24.2.tgz", + "integrity": "sha512-y09e0L0SRI2OA2tUIrjBgoV3eH5hvUKXNkJqXmNo5V2WxIjyC7I7aJfRLMEVpA8yi95f90gFDvO0VMgrDw+vwA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@oxc-resolver/binding-android-arm64": { + "version": "11.24.2", + "resolved": "https://registry.npmjs.org/@oxc-resolver/binding-android-arm64/-/binding-android-arm64-11.24.2.tgz", + "integrity": "sha512-cl4icWaZFnLdg8m6qtnh5rBMuGbxc/ptStFHLeCNwr+2cZjkjNwQu/jYRS0CHlnPecOJMpuS5M6/BH+0J/YkEg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@oxc-resolver/binding-darwin-arm64": { + "version": "11.24.2", + "resolved": "https://registry.npmjs.org/@oxc-resolver/binding-darwin-arm64/-/binding-darwin-arm64-11.24.2.tgz", + "integrity": "sha512-At29QEMF6HajbQvgY8K6OXnHD1x9rad74xBEfmCB6ZqCGsdq75aK7tOYcTbOanMy8qdIBrfL3SMr3p/lfSlb9w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@oxc-resolver/binding-darwin-x64": { + "version": "11.24.2", + "resolved": "https://registry.npmjs.org/@oxc-resolver/binding-darwin-x64/-/binding-darwin-x64-11.24.2.tgz", + "integrity": "sha512-A5Kqr1EUj4oIL5CF4WRssq/o5P0Y11cwoFouMRmQ7YnC/A8V93nv1nb7aSU8HwcgmXropjLNkVTl4MN87cu28Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@oxc-resolver/binding-freebsd-x64": { + "version": "11.24.2", + "resolved": "https://registry.npmjs.org/@oxc-resolver/binding-freebsd-x64/-/binding-freebsd-x64-11.24.2.tgz", + "integrity": "sha512-R5xkRBRRz7ceH/P5Jrc6G7FmdUdgpLYyESFAUDVTNQ9K0sGPxcp4ljiwEwEqsvNcQ4sYbMRrWcHHBCu7ksAJVw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@oxc-resolver/binding-linux-arm-gnueabihf": { + "version": "11.24.2", + "resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-11.24.2.tgz", + "integrity": "sha512-k/RuYL4L/R58IBn3wT5ma3Wh4k62bp1eYCFRWCmMsasUOqL+H6sW0VGFadEzKWXFFlz+2uIMoeMk9ySSZJHgbg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@oxc-resolver/binding-linux-arm-musleabihf": { + "version": "11.24.2", + "resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-11.24.2.tgz", + "integrity": "sha512-bnHAak3ujYfH5pKk4NieFNbvYvernfoQDgwLddbZ3OtMYrem87/qjlA+u+aKG0oZcqSLGCful/6/CEA+aeAgaA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@oxc-resolver/binding-linux-arm64-gnu": { + "version": "11.24.2", + "resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-11.24.2.tgz", + "integrity": "sha512-vDT3KHgzYp47gmtNOqL2VNhCyl5Zv643eyxm//A68J8DeUGXrvD1pZFiaT4jSfe+RInfnn1R2yVHye4enx6RnA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@oxc-resolver/binding-linux-arm64-musl": { + "version": "11.24.2", + "resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-arm64-musl/-/binding-linux-arm64-musl-11.24.2.tgz", + "integrity": "sha512-+kMlQvbzfyEYtu5FcjE4p+ttBLpKW4d/AsAsuE69BxV6V4twZJeIQZFfD8gh/wqglY0MkPSezWXQH0jBV13MUw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@oxc-resolver/binding-linux-ppc64-gnu": { + "version": "11.24.2", + "resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-11.24.2.tgz", + "integrity": "sha512-shjfMhmZ3gq9fv/w7bi3PnZlgOPG+2QAOFf0BJF0EgBSIGZ6PMLN2zbGEblTUYB/NKVDRyYhE2ff3dJ1QqNPkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@oxc-resolver/binding-linux-riscv64-gnu": { + "version": "11.24.2", + "resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-11.24.2.tgz", + "integrity": "sha512-zGelwFR5oRo+b69k8Lrzun86DyUHzfKN6cnjbR9l7Z7NIRznOE/2ZvPa1IUKqAL2PzAXOdwkfVqNvO1H2RlpAw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@oxc-resolver/binding-linux-riscv64-musl": { + "version": "11.24.2", + "resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-11.24.2.tgz", + "integrity": "sha512-qxZ1SWCXJY0eyhAlP6Lmo9F2Nrtx7EkYj9oCgL8apDPCwXwCEDA2U697bbT81JIc2IrVjxO4KX6WU2N+oN9Z4w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@oxc-resolver/binding-linux-s390x-gnu": { + "version": "11.24.2", + "resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-11.24.2.tgz", + "integrity": "sha512-sGCecF3cx2DFlH4t/z7ApnOnXqN48p5p5mlHDEnHTAukQa2P+qMVE4CwyWE9W+q/m3QJ7kKfGrIjax31f44oFQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@oxc-resolver/binding-linux-x64-gnu": { + "version": "11.24.2", + "resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-x64-gnu/-/binding-linux-x64-gnu-11.24.2.tgz", + "integrity": "sha512-k/VlMMcSzMlahb3/fENM4rTlsJ0s3fFROA0KXPBmKggqmTSaE383sl8F3KCOXPLmVsYfW6hCitMhXCEtNeZxxg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@oxc-resolver/binding-linux-x64-musl": { + "version": "11.24.2", + "resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-x64-musl/-/binding-linux-x64-musl-11.24.2.tgz", + "integrity": "sha512-8hbnZyNi97b/8wapYaIF9+t9GmZKBW2vunaOc3h9HGJptH7b7XpvZqOTBSm/MpTjr7H497BlgOaSfLUdhmy2bw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@oxc-resolver/binding-openharmony-arm64": { + "version": "11.24.2", + "resolved": "https://registry.npmjs.org/@oxc-resolver/binding-openharmony-arm64/-/binding-openharmony-arm64-11.24.2.tgz", + "integrity": "sha512-MvyGik3a6pVgZ0t/kWlbmFxFLmXQJwgLsY2eYFHLpy0wGwRbfzeIGgDwQ3kXqE30z+kSXennRkCrT7TUvkptNg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@oxc-resolver/binding-wasm32-wasi": { + "version": "11.24.2", + "resolved": "https://registry.npmjs.org/@oxc-resolver/binding-wasm32-wasi/-/binding-wasm32-wasi-11.24.2.tgz", + "integrity": "sha512-vHcssMPwO08RTvj/c0iOBz90attxyG3wQJ0dTcyEQK43LRpcdLWZlV5feBhv6Isn6ahbQIzHbCgfa81+RiML0Q==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "1.11.2", + "@emnapi/runtime": "1.11.2", + "@napi-rs/wasm-runtime": "^1.1.6" + }, + "engines": { + "node": ">=14.0.0" } }, + "node_modules/@oxc-resolver/binding-win32-arm64-msvc": { + "version": "11.24.2", + "resolved": "https://registry.npmjs.org/@oxc-resolver/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-11.24.2.tgz", + "integrity": "sha512-uokJqro2iBqkFvJdKQLP7d8/BUmFwESQFVmIJUQKj1Xn1a/LysJoe1vmeECLF5b3jsV8CAL5sEMJXX6SdK9Nhg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@oxc-resolver/binding-win32-x64-msvc": { + "version": "11.24.2", + "resolved": "https://registry.npmjs.org/@oxc-resolver/binding-win32-x64-msvc/-/binding-win32-x64-msvc-11.24.2.tgz", + "integrity": "sha512-UqGPmo56KDfLlfXFAFIrNflHT8tFxWGEivWg3Zeyp4Uy2NlKN1FGPr6/BxcLGG3+kZ6Wp14g5Uj+n71boqZfiw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, "node_modules/@paralleldrive/cuid2": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/@paralleldrive/cuid2/-/cuid2-2.3.1.tgz", @@ -913,6 +1621,24 @@ "text-hex": "1.0.x" } }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.5", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz", + "integrity": "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@types/chai": { "version": "4.3.20", "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.3.20.tgz", @@ -934,13 +1660,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/minimatch": { - "version": "3.0.5", - "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.5.tgz", - "integrity": "sha512-Klz949h02Gz2uZCMGwDUSDS1YBlTdDDgbWHi+81l29tQALUtvz4rAYi5uoVhE5Lagoq6DeqAUlbrHvW/mXDgdQ==", - "dev": true, - "license": "MIT" - }, "node_modules/@types/node": { "version": "25.5.0", "resolved": "https://registry.npmjs.org/@types/node/-/node-25.5.0.tgz", @@ -951,13 +1670,6 @@ "undici-types": "~7.18.0" } }, - "node_modules/@types/parse-json": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.2.tgz", - "integrity": "sha512-dISoDXWWQwUquiKsyZ4Ng+HX2KsPL7LyHKHQwgGFEA3IaKac4Obd+h2a/a6waisAoepJlBcx9paWqjA8/HVjCw==", - "dev": true, - "license": "MIT" - }, "node_modules/@types/superagent": { "version": "4.1.13", "resolved": "https://registry.npmjs.org/@types/superagent/-/superagent-4.1.13.tgz", @@ -997,67 +1709,6 @@ "dev": true, "license": "ISC" }, - "node_modules/@vue/compiler-core": { - "version": "3.5.31", - "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.31.tgz", - "integrity": "sha512-k/ueL14aNIEy5Onf0OVzR8kiqF/WThgLdFhxwa4e/KF/0qe38IwIdofoSWBTvvxQOesaz6riAFAUaYjoF9fLLQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.29.2", - "@vue/shared": "3.5.31", - "entities": "^7.0.1", - "estree-walker": "^2.0.2", - "source-map-js": "^1.2.1" - } - }, - "node_modules/@vue/compiler-dom": { - "version": "3.5.31", - "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.5.31.tgz", - "integrity": "sha512-BMY/ozS/xxjYqRFL+tKdRpATJYDTTgWSo0+AJvJNg4ig+Hgb0dOsHPXvloHQ5hmlivUqw1Yt2pPIqp4e0v1GUw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vue/compiler-core": "3.5.31", - "@vue/shared": "3.5.31" - } - }, - "node_modules/@vue/compiler-sfc": { - "version": "3.5.31", - "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.5.31.tgz", - "integrity": "sha512-M8wpPgR9UJ8MiRGjppvx9uWJfLV7A/T+/rL8s/y3QG3u0c2/YZgff3d6SuimKRIhcYnWg5fTfDMlz2E6seUW8Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.29.2", - "@vue/compiler-core": "3.5.31", - "@vue/compiler-dom": "3.5.31", - "@vue/compiler-ssr": "3.5.31", - "@vue/shared": "3.5.31", - "estree-walker": "^2.0.2", - "magic-string": "^0.30.21", - "postcss": "^8.5.8", - "source-map-js": "^1.2.1" - } - }, - "node_modules/@vue/compiler-ssr": { - "version": "3.5.31", - "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.5.31.tgz", - "integrity": "sha512-h0xIMxrt/LHOvJKMri+vdYT92BrK3HFLtDqq9Pr/lVVfE4IyKZKvWf0vJFW10Yr6nX02OR4MkJwI0c1HDa1hog==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vue/compiler-dom": "3.5.31", - "@vue/shared": "3.5.31" - } - }, - "node_modules/@vue/shared": { - "version": "3.5.31", - "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.31.tgz", - "integrity": "sha512-nBxuiuS9Lj5bPkPbWogPUnjxxWpkRniX7e5UBQDWl6Fsf4roq9wwV+cR7ezQ4zXswNvPIlsdj1slcLB7XCsRAw==", - "dev": true, - "license": "MIT" - }, "node_modules/accepts": { "version": "1.3.8", "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", @@ -1251,16 +1902,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/array-differ": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/array-differ/-/array-differ-3.0.0.tgz", - "integrity": "sha512-THtfYS6KtME/yIAhKjZ2ul7XI96lQGHRputJQHO80LAWQnuGP4iCIN8vdMRboGbIEYBwU33q8Tch1os2+X0kMg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/array-flatten": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", @@ -1290,16 +1931,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/array-union": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", - "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/array.prototype.findlastindex": { "version": "1.2.6", "resolved": "https://registry.npmjs.org/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.6.tgz", @@ -1382,16 +2013,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/arrify": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/arrify/-/arrify-2.0.1.tgz", - "integrity": "sha512-3duEwti880xqi4eAMN8AyR4a0ByT90zoYdLlevfrvU43vb0YZwZVfxOgxWrLXXXpyugL0hNZc9G6BiB5B3nUug==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/asap": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz", @@ -1702,15 +2323,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/callsite": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/callsite/-/callsite-1.0.0.tgz", - "integrity": "sha512-0vdNRFXn5q+dtOqjfFtmtlI9N2eVZ7LMyEV2iKC5mEEFvSg/69Ml6b/WU2qF8W1nLRa0wiSrDT3Y5jOHZCwKPQ==", - "dev": true, - "engines": { - "node": "*" - } - }, "node_modules/callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", @@ -2131,23 +2743,6 @@ "url": "https://opencollective.com/express" } }, - "node_modules/cosmiconfig": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-7.1.0.tgz", - "integrity": "sha512-AdmX6xUzdNASswsFtmwSt7Vj8po9IuqXm0UXz7QKPuEUmPB4XyjGfaAr2PSuELMwkRMVH1EpIkX5bTZGRB3eCA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/parse-json": "^4.0.0", - "import-fresh": "^3.2.1", - "parse-json": "^5.0.0", - "path-type": "^4.0.0", - "yaml": "^1.10.0" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", @@ -2365,44 +2960,6 @@ "node": ">=0.4.0" } }, - "node_modules/depcheck": { - "version": "1.4.7", - "resolved": "https://registry.npmjs.org/depcheck/-/depcheck-1.4.7.tgz", - "integrity": "sha512-1lklS/bV5chOxwNKA/2XUUk/hPORp8zihZsXflr8x0kLwmcZ9Y9BsS6Hs3ssvA+2wUVbG0U2Ciqvm1SokNjPkA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.23.0", - "@babel/traverse": "^7.23.2", - "@vue/compiler-sfc": "^3.3.4", - "callsite": "^1.0.0", - "camelcase": "^6.3.0", - "cosmiconfig": "^7.1.0", - "debug": "^4.3.4", - "deps-regex": "^0.2.0", - "findup-sync": "^5.0.0", - "ignore": "^5.2.4", - "is-core-module": "^2.12.0", - "js-yaml": "^3.14.1", - "json5": "^2.2.3", - "lodash": "^4.17.21", - "minimatch": "^7.4.6", - "multimatch": "^5.0.0", - "please-upgrade-node": "^3.2.0", - "readdirp": "^3.6.0", - "require-package-name": "^2.0.1", - "resolve": "^1.22.3", - "resolve-from": "^5.0.0", - "semver": "^7.5.4", - "yargs": "^16.2.0" - }, - "bin": { - "depcheck": "bin/depcheck.js" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/depd": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", @@ -2412,13 +2969,6 @@ "node": ">= 0.8" } }, - "node_modules/deps-regex": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/deps-regex/-/deps-regex-0.2.0.tgz", - "integrity": "sha512-PwuBojGMQAYbWkMXOY9Pd/NWCDNHVH12pnS7WHqZkTSeMESe4hwnKKRp0yR87g37113x4JPbo/oIvXY+s/f56Q==", - "dev": true, - "license": "MIT" - }, "node_modules/destroy": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", @@ -2429,16 +2979,6 @@ "npm": "1.2.8000 || >= 1.4.16" } }, - "node_modules/detect-file": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/detect-file/-/detect-file-1.0.0.tgz", - "integrity": "sha512-DtCOLG98P007x7wiiOmfI0fi3eIKyWiLTGJ2MDnVi/E04lWGbf+JzrRHMm0rgIIZJGtHpKpbVgLWHrv8xXpc3Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/dezalgo": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/dezalgo/-/dezalgo-1.0.4.tgz", @@ -2555,19 +3095,6 @@ "node": ">=8.6" } }, - "node_modules/entities": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", - "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=0.12" - }, - "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" - } - }, "node_modules/error-ex": { "version": "1.3.4", "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz", @@ -3300,13 +3827,6 @@ "node": ">=4.0" } }, - "node_modules/estree-walker": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", - "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", - "dev": true, - "license": "MIT" - }, "node_modules/esutils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", @@ -3326,19 +3846,6 @@ "node": ">= 0.6" } }, - "node_modules/expand-tilde": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/expand-tilde/-/expand-tilde-2.0.2.tgz", - "integrity": "sha512-A5EmesHW6rfnZ9ysHQjPdJRni0SRar0tjtG5MNtm9n5TUvsYU8oozprtRD4AqHxcZWWlVuAmQo2nWKfN9oyjTw==", - "dev": true, - "license": "MIT", - "dependencies": { - "homedir-polyfill": "^1.0.1" - }, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/express": { "version": "4.22.3", "resolved": "https://registry.npmjs.org/express/-/express-4.22.3.tgz", @@ -3489,6 +3996,16 @@ "reusify": "^1.0.4" } }, + "node_modules/fd-package-json": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fd-package-json/-/fd-package-json-2.0.0.tgz", + "integrity": "sha512-jKmm9YtsNXN789RS/0mSzOC1NUq9mkVd65vbSSVsKdjGvYXBuE4oWe2QOEoFeRmJg+lPuZxpmrfFclNhoRMneQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "walk-up-path": "^4.0.0" + } + }, "node_modules/fecha": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/fecha/-/fecha-4.2.3.tgz", @@ -3599,22 +4116,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/findup-sync": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-5.0.0.tgz", - "integrity": "sha512-MzwXju70AuyflbgeOhzvQWAvvQdo1XL0A9bVvlXsYcFEBM87WR4OakL4OfZq+QRmr+duJubio+UtNQCPsVESzQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "detect-file": "^1.0.0", - "is-glob": "^4.0.3", - "micromatch": "^4.0.4", - "resolve-dir": "^1.0.1" - }, - "engines": { - "node": ">= 10.13.0" - } - }, "node_modules/flat": { "version": "5.0.2", "resolved": "https://registry.npmjs.org/flat/-/flat-5.0.2.tgz", @@ -3700,6 +4201,26 @@ "node": ">= 6" } }, + "node_modules/formatly": { + "version": "0.12.3", + "resolved": "https://registry.npmjs.org/formatly/-/formatly-0.12.3.tgz", + "integrity": "sha512-jGtjZLVw6OXvfwqxrxYBc+x+CxmOcMT/KjZagmkrYCQTEtQxJPablRqZPFSNq75drNsHsadjb1djIsE9KE705w==", + "dev": true, + "license": "MIT", + "dependencies": { + "fd-package-json": "^2.0.0", + "package-manager-detector": "^1.8.0", + "parse-standard-args": "^0.3.0", + "tinyexec": "^1.3.1", + "zod": "^4.2.0" + }, + "bin": { + "formatly": "bin/index.mjs" + }, + "engines": { + "node": "^20.12.0 || >=22" + } + }, "node_modules/formidable": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/formidable/-/formidable-2.1.5.tgz", @@ -3941,6 +4462,19 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/get-tsconfig": { + "version": "4.14.3", + "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.14.3.tgz", + "integrity": "sha512-++QEw4DIY7WGoukz+/+A/8dGYPT9l9yIadnmSgZ8Rjr3YVSVDipQSO9CdnJo9ePqFqUUqh+wk9uIaoiAwsiPkA==", + "dev": true, + "license": "MIT", + "dependencies": { + "resolve-pkg-maps": "^1.0.0" + }, + "funding": { + "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" + } + }, "node_modules/glob": { "version": "8.1.0", "resolved": "https://registry.npmjs.org/glob/-/glob-8.1.0.tgz", @@ -3988,51 +4522,6 @@ "node": ">=10" } }, - "node_modules/global-modules": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/global-modules/-/global-modules-1.0.0.tgz", - "integrity": "sha512-sKzpEkf11GpOFuw0Zzjzmt4B4UZwjOcG757PPvrfhxcLFbq0wpsgpOqxpxtxFiCG4DtG93M6XRVbF2oGdev7bg==", - "dev": true, - "license": "MIT", - "dependencies": { - "global-prefix": "^1.0.1", - "is-windows": "^1.0.1", - "resolve-dir": "^1.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/global-prefix": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/global-prefix/-/global-prefix-1.0.2.tgz", - "integrity": "sha512-5lsx1NUDHtSjfg0eHlmYvZKv8/nVqX4ckFbM+FrGcQ+04KWcWFo9P5MxPZYSzUvyzmdTbI7Eix8Q4IbELDqzKg==", - "dev": true, - "license": "MIT", - "dependencies": { - "expand-tilde": "^2.0.2", - "homedir-polyfill": "^1.0.1", - "ini": "^1.3.4", - "is-windows": "^1.0.1", - "which": "^1.2.14" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/global-prefix/node_modules/which": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", - "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "which": "bin/which" - } - }, "node_modules/globals": { "version": "13.24.0", "resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz", @@ -4249,19 +4738,6 @@ "node": ">=16.0.0" } }, - "node_modules/homedir-polyfill": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/homedir-polyfill/-/homedir-polyfill-1.0.3.tgz", - "integrity": "sha512-eSmmWE5bZTK2Nou4g0AI3zZ9rswp7GRKoKXS1BLUkvPviOqs4YTN1djQIqrXy9k5gEtdLPy86JjRwsNM9tnDcA==", - "dev": true, - "license": "MIT", - "dependencies": { - "parse-passwd": "^1.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/hosted-git-info": { "version": "2.8.9", "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.9.tgz", @@ -4382,13 +4858,6 @@ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "license": "ISC" }, - "node_modules/ini": { - "version": "1.3.8", - "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", - "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", - "dev": true, - "license": "ISC" - }, "node_modules/internal-slot": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.1.0.tgz", @@ -5031,13 +5500,17 @@ } }, "node_modules/istanbul-lib-processinfo/node_modules/uuid": { - "version": "8.3.2", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", - "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "version": "11.1.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.1.tgz", + "integrity": "sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==", "dev": true, + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], "license": "MIT", "bin": { - "uuid": "dist/bin/uuid" + "uuid": "dist/esm/bin/uuid" } }, "node_modules/istanbul-lib-report": { @@ -5100,6 +5573,16 @@ "node": ">=8" } }, + "node_modules/jiti": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", + "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", + "dev": true, + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -5148,13 +5631,6 @@ "dev": true, "license": "MIT" }, - "node_modules/json-parse-even-better-errors": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", - "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", - "dev": true, - "license": "MIT" - }, "node_modules/json-schema-traverse": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", @@ -5274,7 +5750,86 @@ "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", "license": "MIT", "engines": { - "node": ">=6" + "node": ">=6" + } + }, + "node_modules/knip": { + "version": "6.49.0", + "resolved": "https://registry.npmjs.org/knip/-/knip-6.49.0.tgz", + "integrity": "sha512-8Gf4R0xcJx1NdNKfr6gOGgSVBE1flB+KHPKPybDTKJ/hPtnswxyFE7Zpsk71kBvzAKReezakbe3DbQ0qAT4vzA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/webpro" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/knip" + } + ], + "license": "ISC", + "dependencies": { + "formatly": "^0.12.3", + "get-tsconfig": "4.14.3", + "jiti": "^2.7.0", + "oxc-parser": "^0.160.0", + "oxc-resolver": "11.24.2", + "picomatch": "^4.0.7", + "smol-toml": "^1.9.1", + "strip-json-comments": "5.0.3", + "tinyglobby": "^0.2.17", + "unbash": "^6.0.5", + "yaml": "^2.9.1" + }, + "bin": { + "knip": "bin/knip.js", + "knip-bun": "bin/knip-bun.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/knip/node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/knip/node_modules/strip-json-comments": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-5.0.3.tgz", + "integrity": "sha512-1tB5mhVo7U+ETBKNf92xT4hrQa3pm0MZ0PQvuDnWgAAGHDsfp4lPSpiS6psrSiet87wyGPh9ft6wmhOMQ0hDiw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/knip/node_modules/yaml": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz", + "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", + "dev": true, + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" } }, "node_modules/kuler": { @@ -5297,13 +5852,6 @@ "node": ">= 0.8.0" } }, - "node_modules/lines-and-columns": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", - "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", - "dev": true, - "license": "MIT" - }, "node_modules/load-json-file": { "version": "5.3.0", "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-5.3.0.tgz", @@ -5474,16 +6022,6 @@ "node": ">=12" } }, - "node_modules/magic-string": { - "version": "0.30.21", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", - "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.5" - } - }, "node_modules/make-dir": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", @@ -5552,20 +6090,6 @@ "node": ">= 0.6" } }, - "node_modules/micromatch": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", - "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", - "dev": true, - "license": "MIT", - "dependencies": { - "braces": "^3.0.3", - "picomatch": "^2.3.1" - }, - "engines": { - "node": ">=8.6" - } - }, "node_modules/mime": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", @@ -5599,22 +6123,6 @@ "node": ">= 0.6" } }, - "node_modules/minimatch": { - "version": "7.4.9", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-7.4.9.tgz", - "integrity": "sha512-Brg/fp/iAVDOQoHxkuN5bEYhyQlZhxddI78yWsCbeEwTHXQjlNLtiJDUsp1GIptVqMI7/gkJMz4vVAc01mpoBw==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^2.0.2" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, "node_modules/minimist": { "version": "1.2.8", "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", @@ -5895,69 +6403,6 @@ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "license": "MIT" }, - "node_modules/multimatch": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/multimatch/-/multimatch-5.0.0.tgz", - "integrity": "sha512-ypMKuglUrZUD99Tk2bUQ+xNQj43lPEfAeX2o9cTteAmShXy2VHDJpuwu1o0xqoKCt9jLVAvwyFKdLTPXKAfJyA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/minimatch": "^3.0.3", - "array-differ": "^3.0.0", - "array-union": "^2.1.0", - "arrify": "^2.0.1", - "minimatch": "^3.0.4" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/multimatch/node_modules/brace-expansion": { - "version": "1.1.21", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", - "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/multimatch/node_modules/minimatch": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", - "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/nanoid": { - "version": "3.3.18", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz", - "integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "bin": { - "nanoid": "bin/nanoid.cjs" - }, - "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" - } - }, "node_modules/natural-compare": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", @@ -6093,13 +6538,17 @@ } }, "node_modules/node-notifier/node_modules/uuid": { - "version": "8.3.2", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", - "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "version": "11.1.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.1.tgz", + "integrity": "sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==", "dev": true, + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], "license": "MIT", "bin": { - "uuid": "dist/bin/uuid" + "uuid": "dist/esm/bin/uuid" } }, "node_modules/node-preload": { @@ -6606,6 +7055,74 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/oxc-parser": { + "version": "0.160.0", + "resolved": "https://registry.npmjs.org/oxc-parser/-/oxc-parser-0.160.0.tgz", + "integrity": "sha512-IIc9PydmdnTcH1hucWCHfTUbAuHWPDEs8+WlmW7td3jJnaYrbzvPQgcc99FEJc0gURrVU8EskpAr2VMyJ8VbzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "^0.160.0" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/sponsors/oxc-project" + }, + "optionalDependencies": { + "@oxc-parser/binding-android-arm-eabi": "0.160.0", + "@oxc-parser/binding-android-arm64": "0.160.0", + "@oxc-parser/binding-darwin-arm64": "0.160.0", + "@oxc-parser/binding-darwin-x64": "0.160.0", + "@oxc-parser/binding-freebsd-x64": "0.160.0", + "@oxc-parser/binding-linux-arm-gnueabihf": "0.160.0", + "@oxc-parser/binding-linux-arm-musleabihf": "0.160.0", + "@oxc-parser/binding-linux-arm64-gnu": "0.160.0", + "@oxc-parser/binding-linux-arm64-musl": "0.160.0", + "@oxc-parser/binding-linux-ppc64-gnu": "0.160.0", + "@oxc-parser/binding-linux-riscv64-gnu": "0.160.0", + "@oxc-parser/binding-linux-riscv64-musl": "0.160.0", + "@oxc-parser/binding-linux-s390x-gnu": "0.160.0", + "@oxc-parser/binding-linux-x64-gnu": "0.160.0", + "@oxc-parser/binding-linux-x64-musl": "0.160.0", + "@oxc-parser/binding-openharmony-arm64": "0.160.0", + "@oxc-parser/binding-win32-arm64-msvc": "0.160.0", + "@oxc-parser/binding-win32-ia32-msvc": "0.160.0", + "@oxc-parser/binding-win32-x64-msvc": "0.160.0" + } + }, + "node_modules/oxc-resolver": { + "version": "11.24.2", + "resolved": "https://registry.npmjs.org/oxc-resolver/-/oxc-resolver-11.24.2.tgz", + "integrity": "sha512-FY91FiDBj7ls5MsFS9jN3tjz2o0/zsdSsymlakySaBwVJZorHhkWyICLZMKxlu1R9vYo+sd3z1jwb4J8x7bNDw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/Boshen" + }, + "optionalDependencies": { + "@oxc-resolver/binding-android-arm-eabi": "11.24.2", + "@oxc-resolver/binding-android-arm64": "11.24.2", + "@oxc-resolver/binding-darwin-arm64": "11.24.2", + "@oxc-resolver/binding-darwin-x64": "11.24.2", + "@oxc-resolver/binding-freebsd-x64": "11.24.2", + "@oxc-resolver/binding-linux-arm-gnueabihf": "11.24.2", + "@oxc-resolver/binding-linux-arm-musleabihf": "11.24.2", + "@oxc-resolver/binding-linux-arm64-gnu": "11.24.2", + "@oxc-resolver/binding-linux-arm64-musl": "11.24.2", + "@oxc-resolver/binding-linux-ppc64-gnu": "11.24.2", + "@oxc-resolver/binding-linux-riscv64-gnu": "11.24.2", + "@oxc-resolver/binding-linux-riscv64-musl": "11.24.2", + "@oxc-resolver/binding-linux-s390x-gnu": "11.24.2", + "@oxc-resolver/binding-linux-x64-gnu": "11.24.2", + "@oxc-resolver/binding-linux-x64-musl": "11.24.2", + "@oxc-resolver/binding-openharmony-arm64": "11.24.2", + "@oxc-resolver/binding-wasm32-wasi": "11.24.2", + "@oxc-resolver/binding-win32-arm64-msvc": "11.24.2", + "@oxc-resolver/binding-win32-x64-msvc": "11.24.2" + } + }, "node_modules/p-limit": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", @@ -6677,6 +7194,13 @@ "node": ">=8" } }, + "node_modules/package-manager-detector": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/package-manager-detector/-/package-manager-detector-1.10.0.tgz", + "integrity": "sha512-FlC7wr4YYRfVyk1E3u3qwi7Vh6qVvPowYkHQSDEoSKCN0o0F7w0TzNfJSBb/1rwEQbU3c96Exx/2vMYiCIx+wQ==", + "dev": true, + "license": "MIT" + }, "node_modules/packageurl-js": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/packageurl-js/-/packageurl-js-2.0.1.tgz", @@ -6696,33 +7220,25 @@ "node": ">=6" } }, - "node_modules/parse-json": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", - "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", + "node_modules/parse-standard-args": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/parse-standard-args/-/parse-standard-args-0.3.0.tgz", + "integrity": "sha512-SH663jox6V7vxSZgroZJw9DgvSbcNHWOnjHjgvsPyj0/+OIbFraNJyDQbA+ATaAUIi0OGAmV27bIGUgcAEM41g==", "dev": true, "license": "MIT", "dependencies": { - "@babel/code-frame": "^7.0.0", - "error-ex": "^1.3.1", - "json-parse-even-better-errors": "^2.3.0", - "lines-and-columns": "^1.1.6" + "@standard-schema/spec": "^1.1.0" }, "engines": { - "node": ">=8" + "node": ">=18.7.0" }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/parse-passwd": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/parse-passwd/-/parse-passwd-1.0.0.tgz", - "integrity": "sha512-1Y1A//QUXEZK7YKz+rD9WydcE1+EuPr6ZBgKecAB8tmoW6UFv0NREVJe1p+jRxtThkcbbKkfwIbWJe/IeE6m2Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" + "peerDependencies": { + "@clack/prompts": ">=0.11" + }, + "peerDependenciesMeta": { + "@clack/prompts": { + "optional": true + } } }, "node_modules/parseurl": { @@ -6776,16 +7292,6 @@ "integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==", "license": "MIT" }, - "node_modules/path-type": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", - "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/pathval": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.1.tgz", @@ -7061,16 +7567,6 @@ "node": ">=4" } }, - "node_modules/please-upgrade-node": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/please-upgrade-node/-/please-upgrade-node-3.2.0.tgz", - "integrity": "sha512-gQR3WpIgNIKwBMVLkpMUeR3e1/E1y42bqDQZfql+kDeXd8COYfM8PQA4X6y7a8u9Ua9FHmsrrmirW2vHs45hWg==", - "dev": true, - "license": "MIT", - "dependencies": { - "semver-compare": "^1.0.0" - } - }, "node_modules/possible-typed-array-names": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz", @@ -7081,35 +7577,6 @@ "node": ">= 0.4" } }, - "node_modules/postcss": { - "version": "8.5.26", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz", - "integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/postcss" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "nanoid": "^3.3.17", - "picocolors": "^1.1.1", - "source-map-js": "^1.2.1" - }, - "engines": { - "node": "^10 || ^12 || >=14" - } - }, "node_modules/prelude-ls": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", @@ -7703,13 +8170,6 @@ "dev": true, "license": "ISC" }, - "node_modules/require-package-name": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/require-package-name/-/require-package-name-2.0.1.tgz", - "integrity": "sha512-uuoJ1hU/k6M0779t3VMVIYpb2VMJk05cehCaABFhXaibcbvfgR8wKiozLjVFSzJPmQMRqIcO0HMyTFqfV09V6Q==", - "dev": true, - "license": "MIT" - }, "node_modules/resolve": { "version": "1.22.11", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz", @@ -7731,20 +8191,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/resolve-dir": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/resolve-dir/-/resolve-dir-1.0.1.tgz", - "integrity": "sha512-R7uiTjECzvOsWSfdM0QKFNBVFcK27aHOUwdvK53BcW8zqnGdYp0Fbj82cy54+2A4P2tFM22J5kRfe1R+lM/1yg==", - "dev": true, - "license": "MIT", - "dependencies": { - "expand-tilde": "^2.0.0", - "global-modules": "^1.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/resolve-from": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", @@ -7755,6 +8201,16 @@ "node": ">=8" } }, + "node_modules/resolve-pkg-maps": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", + "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" + } + }, "node_modules/reusify": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", @@ -7956,13 +8412,6 @@ "node": ">=10" } }, - "node_modules/semver-compare": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz", - "integrity": "sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==", - "dev": true, - "license": "MIT" - }, "node_modules/send": { "version": "0.19.2", "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz", @@ -8242,20 +8691,23 @@ "url": "https://github.com/chalk/slice-ansi?sponsor=1" } }, - "node_modules/source-map": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "node_modules/smol-toml": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.9.1.tgz", + "integrity": "sha512-j7WyPdf0CJoutMzMoPLF/bVXHtKZIT9Rb4eGeEbWw8X2t5oirjPgpL+OpaENZrILYaXqYwnVH+qgUwVbl+pUJQ==", "dev": true, "license": "BSD-3-Clause", "engines": { - "node": ">=0.10.0" + "node": ">= 18" + }, + "funding": { + "url": "https://github.com/sponsors/cyyynthia" } }, - "node_modules/source-map-js": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", - "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", "dev": true, "license": "BSD-3-Clause", "engines": { @@ -9331,6 +9783,64 @@ "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==", "license": "MIT" }, + "node_modules/tinyexec": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.4.0.tgz", + "integrity": "sha512-PV6lIcJQh57aFeJDwx16JNHmgFRh5xguzallrDW1qe8nAghYgr5MKz2K5k7wEyV/ygZhdnIAP8+HZSarHPBCsg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyglobby/node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/tinyglobby/node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", @@ -9410,6 +9920,14 @@ "node": ">=4" } }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "dev": true, + "license": "0BSD", + "optional": true + }, "node_modules/type-check": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", @@ -9543,6 +10061,16 @@ "is-typedarray": "^1.0.0" } }, + "node_modules/unbash": { + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/unbash/-/unbash-6.0.5.tgz", + "integrity": "sha512-5P8o+nYRueKpHxmemofYqZRZCSWAi+Tqy31MQS8l/sT54Z+Axn55N9CnWPo19BxxJD4wYYf6RqlcURhWkrFXew==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=14" + } + }, "node_modules/unbox-primitive": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.1.0.tgz", @@ -9698,6 +10226,16 @@ "node": ">= 0.8" } }, + "node_modules/walk-up-path": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/walk-up-path/-/walk-up-path-4.0.0.tgz", + "integrity": "sha512-3hu+tD8YzSLGuFYtPRb48vdhKMi0KQV5sn+uWr8+7dMEq/2G/dtLrdDinkLjqq5TIbIBjYJ4Ax/n3YiaW7QM8A==", + "dev": true, + "license": "ISC", + "engines": { + "node": "20 || >=22" + } + }, "node_modules/webidl-conversions": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", @@ -9959,16 +10497,6 @@ "dev": true, "license": "ISC" }, - "node_modules/yaml": { - "version": "1.10.3", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.3.tgz", - "integrity": "sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">= 6" - } - }, "node_modules/yamljs": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/yamljs/-/yamljs-0.3.0.tgz", @@ -10096,6 +10624,16 @@ "funding": { "url": "https://github.com/sponsors/sindresorhus" } + }, + "node_modules/zod": { + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } } } } diff --git a/package.json b/package.json index 06c1ed4d4..dbda4624f 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,6 @@ "chai-string": "^1.5.0", "chai-things": "^0.2.0", "chai-uuid": "^1.0.6", - "depcheck": "^1.4.7", "eslint": "^8.20.0", "eslint-config-standard": "^14.1.1", "eslint-plugin-import": "^2.26.0", @@ -20,6 +19,7 @@ "eslint-plugin-node": "^11.0.0", "eslint-plugin-promise": "^4.2.1", "eslint-plugin-standard": "^4.0.1", + "knip": "6.49.0", "mocha": "^10.8.2", "node-dev": "^7.4.3", "nyc": "^15.1.0", @@ -62,11 +62,24 @@ "yamljs": "^0.3.0" }, "overrides": { + "istanbul-lib-processinfo@2.0.3": { + "uuid": "11.1.1" + }, "mongo-cursor-pagination": { "bson": "^6.10.1" }, + "node-notifier@8.0.2": { + "uuid": "11.1.1" + }, "serialize-javascript": "^7.0.3" }, + "knip": { + "entry": [ + "src/scripts/**/*.js", + "test/**/*.js", + "test-examples/**/*.js" + ] + }, "nyc": { "exclude": "test-utils/" }, @@ -76,7 +89,7 @@ "action:lint-src": "node node_modules/eslint/bin/eslint.js src/", "action:lint-test": "node node_modules/eslint/bin/eslint.js test/", "action:lint-test-utils": "node node_modules/eslint/bin/eslint.js test-utils/", - "clean": "node node_modules/depcheck/bin/depcheck.js", + "clean": "knip --dependencies", "lint:src": "node node_modules/eslint/bin/eslint.js src/ --fix", "lint:test": "node node_modules/eslint/bin/eslint.js test/ --fix", "lint:test-utils": "node node_modules/eslint/bin/eslint.js test-utils/ --fix", From 2782fc30cf2f0dc823d1754aa9021f3a7a7334fc Mon Sep 17 00:00:00 2001 From: David T Rocca Date: Mon, 30 Nov 2026 11:53:32 -0500 Subject: [PATCH 04/19] fix: update and pin Node and Python container images --- README.md | 4 ++-- docker/Dockerfile | 4 ++-- docker/Dockerfile.dev | 2 +- docker/README.md | 2 +- test-http/docker/Dockerfile | 2 +- test/README.md | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 21179bcb5..8c339c08f 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ Please consult our [SECURITY.md](SECURITY.md) for specific instructions on repor This project uses: -- [Node.js](https://nodejs.org/) 24.22.1 for local development and the production image build; CI and the development Docker image use Node.js 24. +- [Node.js](https://nodejs.org/) 24.22.3 for local development and the production image build; CI and the development Docker image use Node.js 24. - [Express](https://github.com/expressjs) - [MongoDB](https://www.mongodb.com/) replica sets for local development and testing - [Amazon DocumentDB](https://aws.amazon.com/documentdb/) in production @@ -85,7 +85,7 @@ See the [Docker README](docker/README.md) to run both the application and MongoD ##### Install dependencies -Install Node.js 24.22.1 with its bundled npm, then install the application and migration dependencies: +Install Node.js 24.22.3 with its bundled npm, then install the application and migration dependencies: ```sh npm ci diff --git a/docker/Dockerfile b/docker/Dockerfile index f05dad5fe..3fb9503cb 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -1,4 +1,4 @@ -FROM node:24.22.1-trixie-slim@sha256:43b9ba1142b8dcf33fa8f922ca1be85714adc444e0586c7cf7726daaeabc1bea AS build +FROM node:24.22.3-trixie-slim@sha256:4d00acb4bcc42c454c4eb801526f7ad7f772ea3bd4fd168c5cc2e384abcbb9d4 AS build LABEL \ mitre.name=cveawg \ @@ -38,7 +38,7 @@ RUN node src/swagger.js \ && npm prune --omit=dev \ && npm cache clean --force -FROM gcr.io/distroless/nodejs24-debian13:nonroot@sha256:cb606325b7ec4af55462cb0b424a53b452a5b4a894ffe841fcf1048d216fb9f8 AS runtime +FROM gcr.io/distroless/nodejs24-debian13:nonroot-d80a5ba65a6abbacd7f441962bdba2ab57e81379@sha256:675c532423b908f9e56f9d60a4e62309b63cd2a3175acb90a46b96f7ee68e121 AS runtime LABEL \ mitre.name=cveawg \ diff --git a/docker/Dockerfile.dev b/docker/Dockerfile.dev index bdf1d34c6..49b3f0009 100644 --- a/docker/Dockerfile.dev +++ b/docker/Dockerfile.dev @@ -1,4 +1,4 @@ -FROM node:24-alpine3.22 +FROM node:24.22.3-alpine3.24@sha256:116b800c3754b440ee0aa3ed2f20f5bf3d99a554bfd9adeea09ea8017f6e85f5 # do not copy files we mount in compose # our local and production docker files could co-exist using "targets" in # the `FROM` statements diff --git a/docker/README.md b/docker/README.md index cc8a9eaf1..18c1f8f25 100644 --- a/docker/README.md +++ b/docker/README.md @@ -59,7 +59,7 @@ show `Serving on port 3000`; press Ctrl+C to leave the log view. Open Swagger UI [http://localhost:3000/api-docs/](http://localhost:3000/api-docs/). The Compose application uses [Dockerfile.dev](Dockerfile.dev), based on Node.js 24. The -separate [production Dockerfile](Dockerfile) builds with Node.js 24.22.1 and uses a +separate [production Dockerfile](Dockerfile) builds with Node.js 24.22.3 and uses a Distroless Node.js 24 runtime. Shell, population, and test commands in this guide apply to the development image. diff --git a/test-http/docker/Dockerfile b/test-http/docker/Dockerfile index 4470845e0..e5a82b545 100644 --- a/test-http/docker/Dockerfile +++ b/test-http/docker/Dockerfile @@ -1,4 +1,4 @@ -FROM python:3.9-slim-buster +FROM python:3.13.18-slim-trixie@sha256:168d3a5d10f2152f8e8d77b6843ac82c22a846cfefeef7afdf9aa630404e82a7 LABEL name="Dockerized Endpoint Testing" diff --git a/test/README.md b/test/README.md index 22d93ae71..4efd71622 100644 --- a/test/README.md +++ b/test/README.md @@ -1,7 +1,7 @@ # CVE Services Tests The JavaScript test suites use [Mocha](https://mochajs.org/) and [Chai](https://www.chaijs.com/). -Use Node.js 24.22.1 and run commands from the repository root. Install dependencies with +Use Node.js 24.22.3 and run commands from the repository root. Install dependencies with `npm ci` as described in the [local setup guide](../README.md#local-development). ## Unit tests From b713e8978aed9753e0b78fa71cbeaccc7b5e4571 Mon Sep 17 00:00:00 2001 From: David T Rocca Date: Tue, 1 Dec 2026 15:05:33 -0500 Subject: [PATCH 05/19] test: allow 10 seconds for legacy organization role transitions --- test/integration-tests/org/disabledOrgRoleContractTest.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/integration-tests/org/disabledOrgRoleContractTest.js b/test/integration-tests/org/disabledOrgRoleContractTest.js index 0ec5ac1ef..c73e76337 100644 --- a/test/integration-tests/org/disabledOrgRoleContractTest.js +++ b/test/integration-tests/org/disabledOrgRoleContractTest.js @@ -239,7 +239,9 @@ describe('Disabled organization legacy role contract', () => { expect((await BaseOrg.findOne({ UUID: org.UUID }).read('primary').lean()).disabled).to.equal(true) }) - it('enables a disabled org on a legacy role grant and disables it when the last active role is removed', async () => { + it('enables a disabled org on a legacy role grant and disables it when the last active role is removed', async function () { + this.timeout(10000) + const org = await createOrg(['CNA'], true) const edits = [ { action: 'add', role: 'ADP', activeRoles: ['ADP'], storedRoles: ['ADP'], disabled: false, type: 'ADPOrg' }, From 879c950a8cdc08285d1721836293556e89820179 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:44:54 +0000 Subject: [PATCH 06/19] Bump cross-spawn from 7.0.6 to 7.1.2 Bumps [cross-spawn](https://github.com/moxystudio/node-cross-spawn) from 7.0.6 to 7.1.2. - [Release notes](https://github.com/moxystudio/node-cross-spawn/releases) - [Changelog](https://github.com/moxystudio/node-cross-spawn/blob/master/CHANGELOG.md) - [Commits](https://github.com/moxystudio/node-cross-spawn/compare/v7.0.6...v7.1.2) --- updated-dependencies: - dependency-name: cross-spawn dependency-version: 7.1.2 dependency-type: indirect ... Signed-off-by: dependabot[bot] --- package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 471a92e1f..71fb52283 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2744,9 +2744,9 @@ } }, "node_modules/cross-spawn": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", - "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.1.2.tgz", + "integrity": "sha512-8BPK2r+sKWC8sDinRwLwrFMq2lXTBBwzYYEB9LiCznfMurOi4FOvQflq3XOLGG+HPdMSVpe+k/s96+AtDEOgPg==", "dev": true, "license": "MIT", "dependencies": { From d695b20a6217ad88abab6c217d889863f090d39f Mon Sep 17 00:00:00 2001 From: David T Rocca Date: Mon, 26 Oct 2026 09:50:52 -0400 Subject: [PATCH 07/19] Root read impl --- README.md | 34 +++ api-docs/openapi.json | 26 +- datadump/pre-population/root-orgs.json | 14 +- datadump/pre-population/users.json | 44 +++ src/controller/registry.controller/index.js | 39 +-- .../org.registry.controller.js | 74 ++--- .../user.registry.controller.js | 18 +- src/middleware/middleware.js | 64 ++++ src/repositories/baseOrgRepository.js | 16 +- src/repositories/baseUserRepository.js | 5 +- src/scripts/populate.js | 2 + src/utils/authContext.js | 53 ++++ .../registry-org/populatedOrgHierarchyTest.js | 130 ++++++++ .../registry-org/rootReadAccessTest.js | 281 ++++++++++++++++++ .../middleware/registryReadAccessTest.js | 184 ++++++++++++ test/unit-tests/org/baseOrgRepositoryTest.js | 12 + test/unit-tests/org/orgHierarchyTest.js | 4 +- .../org/registry/registryOrgControllerTest.js | 1 + .../org/registry/registryOrgGetSingleTest.js | 8 +- 19 files changed, 920 insertions(+), 89 deletions(-) create mode 100644 test/integration-tests/registry-org/rootReadAccessTest.js create mode 100644 test/unit-tests/middleware/registryReadAccessTest.js diff --git a/README.md b/README.md index 8c339c08f..695612939 100644 --- a/README.md +++ b/README.md @@ -197,6 +197,40 @@ The default local port is `8081`, configurable with `PORT`. Swagger UI is availa to the database. API routes use the `/api/` prefix. The example `TEST_PORT=3001` gives the integration suite a separate listener port. The full Docker setup uses port `3000`. +### Root demo accounts + +Running `npm run populate:dev` resets the local development database and creates these active accounts: + +| Organization | Ordinary user | Administrator | +| --- | --- | --- | +| `top_root_1` | `top_root_1_user@demo.test` | `top_root_1_admin@demo.test` | +| `root_1_4` | `root_1_4_user@demo.test` | `root_1_4_admin@demo.test` | + +All four accounts use the existing `LOCAL_KEY` API secret configured for local population. The population command prints this key. Administrators belong to both their organization's `users` and `admins` lists; ordinary users belong only to `users`. + +The demo hierarchy includes `top_root_1` → `root_1_4` → `window_1`. Both account types can read descendant organizations and users. With the local server running, replace `YOUR_LOCAL_KEY` with the printed secret to try an expanded organization read: + +```sh +curl 'http://localhost:8081/api/registry/org/window_1?expand=users' \ + -H 'CVE-API-ORG: top_root_1' \ + -H 'CVE-API-USER: top_root_1_user@demo.test' \ + -H 'CVE-API-KEY: YOUR_LOCAL_KEY' +``` + +Use the organization and username from either row above to try these requests: + +| Request | Expected result | +| --- | --- | +| `GET /api/registry/org` | A flat, paginated list of all direct and indirect descendants, excluding the requesting Root itself. Counts and pages cover only those descendants. | +| `GET /api/registry/org-hierarchy` | The requesting Root's subtree, with its ancestor path for context. | +| `GET /api/registry/org/window_1` | The descendant organization's details. | +| `GET /api/registry/org/window_1?expand=users` | The descendant organization with expanded user metadata. | +| `GET /api/registry/org/window_1/users` | Users belonging to `window_1`. | +| `GET /api/registry/org/window_1/user/ashleyruiz@window_1.com` | The specified descendant user. | +| `GET /api/registry/org/top_root_2` | `403`: outside both Roots' oversight. | + +The `top_root_1` accounts can also read `root_1_4` and its users. The `root_1_4` accounts receive `403` when reading ancestor organization `top_root_1` or sibling Root `root_1_3`. Organization lists exclude those records as well. Root oversight does not grant access to the global user list or permission to write to descendant organizations and users. Secretariat continues to receive the complete organization list. + ### API Documentation Use the Swagger documentation for the instance you are calling: diff --git a/api-docs/openapi.json b/api-docs/openapi.json index 31d3ba81c..c97475ecf 100644 --- a/api-docs/openapi.json +++ b/api-docs/openapi.json @@ -3057,8 +3057,8 @@ "tags": [ "Data Registry — Organizations" ], - "summary": "Retrieves all registry organizations (accessible to Secretariat)", - "description": "

Related legacy endpoint: GET /org. Data Registry responses use long_name and an authority array; legacy responses use name and authority.active_roles.

Access Control

User must belong to an organization with the Secretariat role

Expected Behavior

Secretariat: Retrieves information about all registry organizations

", + "summary": "Lists registry organizations for Secretariat or overseeing Root users", + "description": "

Related legacy endpoint: GET /org. Data Registry responses use long_name and an authority array; legacy responses use name and authority.active_roles.

Access Control

User must belong to an organization with SECRETARIAT or ROOT authority. Both ordinary Root users and Root administrators have access.

Expected Behavior

Secretariat: Retrieves information about all registry organizations.

Root and top-level Root users: Retrieves a flat list of all direct and indirect descendants, including subordinate Roots and organizations beneath them. The requesting organization itself, ancestors, sibling branches, and unrelated organizations are excluded. A Root without descendants receives an empty list.

Results use existing non-Secretariat field filtering and are sorted by short_name. Pagination and totalCount apply only to organizations within the authorized scope. Authorization uses current ROOT authority and reporting relationships.

", "operationId": "registryOrgAll", "parameters": [ { @@ -3076,7 +3076,7 @@ ], "responses": { "200": { - "description": "Returns information about all registry organizations, along with pagination fields if results span multiple pages of data", + "description": "Returns registry organizations and pagination metadata. Secretariat receives all organizations; Root users receive only their descendants, with scoped totals.", "content": { "application/json": { "schema": { @@ -3251,8 +3251,8 @@ "tags": [ "Data Registry — Organizations" ], - "summary": "Retrieves the complete registry organization hierarchy (Secretariat only)", - "description": "

Access Control

User must belong to an organization with the Secretariat role.

Expected Behavior

Returns an unpaginated array of organization trees. Each node contains UUID, short_name, long_name, authority, and children. ROOT nodes also contain is_top_level_root, and CNA nodes contain is_last_resort. Organizations without a parent appear at the top level, and leaves have an empty children array.

", + "summary": "Retrieves the organization hierarchy for Secretariat or Root users", + "description": "

Access Control

User must belong to an organization with SECRETARIAT or ROOT authority. Both ordinary Root users and Root administrators have access.

Expected Behavior

Secretariat receives the complete hierarchy. Root users receive their own subtree, including subordinate Roots and descendants, with only the ancestor path for context. Ancestors shown for context do not grant access to their organization or user records. Siblings and unrelated branches are excluded.

Returns an unpaginated array of organization trees. Each node contains UUID, short_name, long_name, authority, and children. ROOT nodes also contain is_top_level_root, and CNA nodes contain is_last_resort. Organizations without a parent appear at the top level, and leaves have an empty children array.

", "operationId": "registryOrgHierarchy", "parameters": [ { @@ -3267,7 +3267,7 @@ ], "responses": { "200": { - "description": "Returns the complete organization hierarchy with UUIDs, organization names, roles, role-specific flags, and nested children", + "description": "Returns the complete hierarchy for Secretariat or the requesting Root's scoped hierarchy, with UUIDs, names, roles, role-specific flags, and nested children", "content": { "application/json": { "schema": { @@ -3406,8 +3406,8 @@ "tags": [ "Data Registry — Users" ], - "summary": "Retrieves all users for the organization with the specified short name (accessible to same-organization users or Secretariat)", - "description": "

Related legacy endpoint: GET /org/{shortname}/users. Data Registry responses expose status and role; legacy responses expose active and authority.active_roles.

Access Control

Authenticated users can access this endpoint only for their own organization. Secretariat users can access any organization.

Expected Behavior

Regular, CNA & Admin Users: Retrieves information about users in the same organization

Secretariat: Retrieves all user information for any organization

", + "summary": "Retrieves all users for the organization with the specified short name (same-organization users, overseeing Root users, or Secretariat)", + "description": "

Related legacy endpoint: GET /org/{shortname}/users. Data Registry responses expose status and role; legacy responses expose active and authority.active_roles.

Access Control

Authenticated users can access their own organization. Ordinary users and administrators in an organization with ROOT authority can also access direct and indirect descendants, including organizations beneath subordinate Roots, using current reporting relationships. Secretariat users can access any organization.

Expected Behavior

Regular, CNA & Admin Users: Retrieves information about users in the same organization

Secretariat: Retrieves all user information for any organization

", "operationId": "registryOrgUsersAll", "parameters": [ { @@ -3707,14 +3707,14 @@ "tags": [ "Data Registry — Organizations" ], - "summary": "Retrieves information about the registry organization specified by short name or UUID (accessible to same-organization users or Secretariat)", - "description": "

Related legacy endpoint: GET /org/{shortname}. Data Registry responses use long_name and an authority array; legacy responses use name and authority.active_roles.

Access Control

Authenticated users can access this endpoint only for their own organization. Secretariat users can access any organization.

Expected Behavior

Regular, CNA & Admin Users: Retrieves registry organization record for the specified shortname or UUID if it is the user's organization

Secretariat: Retrieves information about any registry organization

The reports_to, top_level_root, and oversees relationship fields contain organization short names.

The _hierarchy array contains the ancestor path from the top-level Root to the requested organization and that organization's complete subtree. Ancestors include only the child on that path. Nodes contain UUID, short_name, long_name, authority, and children. ROOT nodes also contain is_top_level_root, and CNA nodes contain is_last_resort. An organization without a parent begins its own tree.

", + "summary": "Retrieves registry organization information by short name or UUID (same-organization users, overseeing Root users, or Secretariat)", + "description": "

Related legacy endpoint: GET /org/{shortname}. Data Registry responses use long_name and an authority array; legacy responses use name and authority.active_roles.

Access Control

Authenticated users can access their own organization. Ordinary users and administrators in an organization with ROOT authority can also access direct and indirect descendants, including organizations beneath subordinate Roots, using current reporting relationships. Secretariat users can access any organization. Root oversight does not grant write or administrator permissions.

Expected Behavior

Regular, CNA & Admin Users: Retrieves registry organization record for the specified shortname or UUID if it is the user's organization

Secretariat: Retrieves information about any registry organization

The reports_to, top_level_root, and oversees relationship fields contain organization short names.

The _hierarchy array contains the ancestor path from the top-level Root to the requested organization and that organization's complete subtree. Ancestors include only the child on that path and do not grant access to ancestor organization or user records. Siblings and unrelated branches remain outside Root oversight. Nodes contain UUID, short_name, long_name, authority, and children. ROOT nodes also contain is_top_level_root, and CNA nodes contain is_last_resort. An organization without a parent begins its own tree.

", "operationId": "registryOrgSingle", "parameters": [ { "name": "expand", "in": "query", - "description": "Optional expanded related data. Accepted value: users.", + "description": "Optional expanded related data. Accepted value: users. Overseeing Root users can expand the authorized target organization's users, administrators, and additional contacts. Existing Secretariat and same-organization expansion rules apply.", "required": false, "schema": { "type": "string", @@ -4009,8 +4009,8 @@ "tags": [ "Data Registry — Users" ], - "summary": "Retrieves information about a user for the specified username and organization short name (accessible to same-organization users or Secretariat)", - "description": "

Related legacy endpoint: GET /org/{shortname}/user/{username}. Data Registry responses expose status and role; legacy responses expose active and authority.active_roles.

Access Control

Authenticated users can access this endpoint only for users in their own organization. Secretariat users can access any user.

Expected Behavior

Regular, CNA & Admin Users: Retrieves information about a registry user in the same organization

Secretariat: Retrieves any registry user's information

", + "summary": "Retrieves a user by username and organization short name (same-organization users, overseeing Root users, or Secretariat)", + "description": "

Related legacy endpoint: GET /org/{shortname}/user/{username}. Data Registry responses expose status and role; legacy responses expose active and authority.active_roles.

Access Control

Authenticated users can access users in their own organization. Ordinary users and administrators in an organization with ROOT authority can also access users belonging to direct and indirect descendant organizations, including organizations beneath subordinate Roots, using current reporting relationships. Secretariat users can access any user. Root oversight excludes ancestors, sibling branches, and unrelated organizations.

Expected Behavior

Regular, CNA & Admin Users: Retrieves information about a registry user in the same organization

Secretariat: Retrieves any registry user's information

", "operationId": "registryUserSingle", "parameters": [ { diff --git a/datadump/pre-population/root-orgs.json b/datadump/pre-population/root-orgs.json index 0f2668762..44f3a69fd 100644 --- a/datadump/pre-population/root-orgs.json +++ b/datadump/pre-population/root-orgs.json @@ -4,7 +4,12 @@ "name": "Top Level Root 1", "short_name": "top_root_1", "is_top_level_root": true, - "oversees": ["root_1_1", "root_1_2", "root_1_3", "root_1_4"] + "oversees": ["root_1_1", "root_1_2", "root_1_3", "root_1_4"], + "users": [ + "20000000-0000-4000-8000-000000000062", + "20000000-0000-4000-8000-000000000063" + ], + "admins": ["20000000-0000-4000-8000-000000000063"] }, { "authority": { "active_roles": ["ROOT"] }, @@ -53,7 +58,12 @@ "name": "Root 1.4", "short_name": "root_1_4", "is_top_level_root": false, - "oversees": [] + "oversees": [], + "users": [ + "20000000-0000-4000-8000-000000000064", + "20000000-0000-4000-8000-000000000065" + ], + "admins": ["20000000-0000-4000-8000-000000000065"] }, { "authority": { "active_roles": ["ROOT"] }, diff --git a/datadump/pre-population/users.json b/datadump/pre-population/users.json index 076179768..06d9e27f8 100644 --- a/datadump/pre-population/users.json +++ b/datadump/pre-population/users.json @@ -791,5 +791,49 @@ "status": "active", "created": "2021-05-11T15:07:20.674347Z", "last_updated": "2021-05-11T15:07:20.674347Z" + }, + { + "UUID": "20000000-0000-4000-8000-000000000062", + "username": "top_root_1_user@demo.test", + "name": { + "first": "Top Root 1", + "last": "User" + }, + "status": "active", + "created": "2021-05-11T15:07:20.674347Z", + "last_updated": "2021-05-11T15:07:20.674347Z" + }, + { + "UUID": "20000000-0000-4000-8000-000000000063", + "username": "top_root_1_admin@demo.test", + "name": { + "first": "Top Root 1", + "last": "Administrator" + }, + "status": "active", + "created": "2021-05-11T15:07:20.674347Z", + "last_updated": "2021-05-11T15:07:20.674347Z" + }, + { + "UUID": "20000000-0000-4000-8000-000000000064", + "username": "root_1_4_user@demo.test", + "name": { + "first": "Root 1.4", + "last": "User" + }, + "status": "active", + "created": "2021-05-11T15:07:20.674347Z", + "last_updated": "2021-05-11T15:07:20.674347Z" + }, + { + "UUID": "20000000-0000-4000-8000-000000000065", + "username": "root_1_4_admin@demo.test", + "name": { + "first": "Root 1.4", + "last": "Administrator" + }, + "status": "active", + "created": "2021-05-11T15:07:20.674347Z", + "last_updated": "2021-05-11T15:07:20.674347Z" } ] diff --git a/src/controller/registry.controller/index.js b/src/controller/registry.controller/index.js index 8aec56b53..058a47edd 100644 --- a/src/controller/registry.controller/index.js +++ b/src/controller/registry.controller/index.js @@ -18,13 +18,15 @@ router.get('/registry/org', /* #swagger.tags = ['Data Registry — Organizations'] #swagger.operationId = 'registryOrgAll' - #swagger.summary = "Retrieves all registry organizations (accessible to Secretariat)" + #swagger.summary = "Lists registry organizations for Secretariat or overseeing Root users" #swagger.description = "

Related legacy endpoint: GET /org. Data Registry responses use long_name and an authority array; legacy responses use name and authority.active_roles.

Access Control

-

User must belong to an organization with the Secretariat role

+

User must belong to an organization with SECRETARIAT or ROOT authority. Both ordinary Root users and Root administrators have access.

Expected Behavior

-

Secretariat: Retrieves information about all registry organizations

" +

Secretariat: Retrieves information about all registry organizations.

+

Root and top-level Root users: Retrieves a flat list of all direct and indirect descendants, including subordinate Roots and organizations beneath them. The requesting organization itself, ancestors, sibling branches, and unrelated organizations are excluded. A Root without descendants receives an empty list.

+

Results use existing non-Secretariat field filtering and are sorted by short_name. Pagination and totalCount apply only to organizations within the authorized scope. Authorization uses current ROOT authority and reporting relationships.

" #swagger.parameters['$ref'] = [ '#/components/parameters/pageQuery', '#/components/parameters/apiEntityHeader', @@ -32,7 +34,7 @@ router.get('/registry/org', '#/components/parameters/apiSecretHeader' ] #swagger.responses[200] = { - description: 'Returns information about all registry organizations, along with pagination fields if results span multiple pages of data', + description: 'Returns registry organizations and pagination metadata. Secretariat receives all organizations; Root users receive only their descendants, with scoped totals.', content: { "application/json": { schema: { @@ -84,12 +86,12 @@ router.get('/registry/org', */ mw.useRegistry(), mw.validateUser, - mw.onlySecretariat, query().custom((query) => { return mw.validateQueryParameterNames(query, ['page']) }), query(['page']).custom((val) => { return mw.containsNoInvalidCharacters(val) }), query(['page']).optional().isInt({ min: CONSTANTS.PAGINATOR_PAGE }), parseError, parseGetParams, + mw.authorizeRegistryHierarchyRead, registryOrgController.ALL_ORGS ) @@ -97,15 +99,15 @@ router.get('/registry/org-hierarchy', /* #swagger.tags = ['Data Registry — Organizations'] #swagger.operationId = 'registryOrgHierarchy' - #swagger.summary = 'Retrieves the complete registry organization hierarchy (Secretariat only)' - #swagger.description = '

Access Control

User must belong to an organization with the Secretariat role.

Expected Behavior

Returns an unpaginated array of organization trees. Each node contains UUID, short_name, long_name, authority, and children. ROOT nodes also contain is_top_level_root, and CNA nodes contain is_last_resort. Organizations without a parent appear at the top level, and leaves have an empty children array.

' + #swagger.summary = 'Retrieves the organization hierarchy for Secretariat or Root users' + #swagger.description = '

Access Control

User must belong to an organization with SECRETARIAT or ROOT authority. Both ordinary Root users and Root administrators have access.

Expected Behavior

Secretariat receives the complete hierarchy. Root users receive their own subtree, including subordinate Roots and descendants, with only the ancestor path for context. Ancestors shown for context do not grant access to their organization or user records. Siblings and unrelated branches are excluded.

Returns an unpaginated array of organization trees. Each node contains UUID, short_name, long_name, authority, and children. ROOT nodes also contain is_top_level_root, and CNA nodes contain is_last_resort. Organizations without a parent appear at the top level, and leaves have an empty children array.

' #swagger.parameters['$ref'] = [ '#/components/parameters/apiEntityHeader', '#/components/parameters/apiUserHeader', '#/components/parameters/apiSecretHeader' ] #swagger.responses[200] = { - description: 'Returns the complete organization hierarchy with UUIDs, organization names, roles, role-specific flags, and nested children', + description: 'Returns the complete hierarchy for Secretariat or the requesting Root\'s scoped hierarchy, with UUIDs, names, roles, role-specific flags, and nested children', content: { 'application/json': { schema: { $ref: '../schemas/registry-org/get-org-hierarchy-response.json' } @@ -156,7 +158,7 @@ router.get('/registry/org-hierarchy', */ mw.useRegistry(), mw.validateUser, - mw.onlySecretariat, + mw.authorizeRegistryHierarchyRead, registryOrgController.ORG_HIERARCHY ) @@ -222,11 +224,11 @@ router.get('/registry/org/:shortname/users', /* #swagger.tags = ['Data Registry — Users'] #swagger.operationId = 'registryOrgUsersAll' - #swagger.summary = "Retrieves all users for the organization with the specified short name (accessible to same-organization users or Secretariat)" + #swagger.summary = "Retrieves all users for the organization with the specified short name (same-organization users, overseeing Root users, or Secretariat)" #swagger.description = "

Related legacy endpoint: GET /org/{shortname}/users. Data Registry responses expose status and role; legacy responses expose active and authority.active_roles.

Access Control

-

Authenticated users can access this endpoint only for their own organization. Secretariat users can access any organization.

+

Authenticated users can access their own organization. Ordinary users and administrators in an organization with ROOT authority can also access direct and indirect descendants, including organizations beneath subordinate Roots, using current reporting relationships. Secretariat users can access any organization.

Expected Behavior

Regular, CNA & Admin Users: Retrieves information about users in the same organization

Secretariat: Retrieves all user information for any organization

" @@ -318,6 +320,7 @@ router.get('/registry/org/:shortname/users', query(['page']).optional().isInt({ min: CONSTANTS.PAGINATOR_PAGE }), parseError, parseGetParams, + mw.authorizeRegistryOrgRead, registryOrgController.USER_ALL) router.get('/registry/org/:shortname/user_quota', @@ -477,19 +480,19 @@ router.get('/registry/org/:identifier', /* #swagger.tags = ['Data Registry — Organizations'] #swagger.operationId = 'registryOrgSingle' - #swagger.summary = "Retrieves information about the registry organization specified by short name or UUID (accessible to same-organization users or Secretariat)" + #swagger.summary = "Retrieves registry organization information by short name or UUID (same-organization users, overseeing Root users, or Secretariat)" #swagger.description = "

Related legacy endpoint: GET /org/{shortname}. Data Registry responses use long_name and an authority array; legacy responses use name and authority.active_roles.

Access Control

-

Authenticated users can access this endpoint only for their own organization. Secretariat users can access any organization.

+

Authenticated users can access their own organization. Ordinary users and administrators in an organization with ROOT authority can also access direct and indirect descendants, including organizations beneath subordinate Roots, using current reporting relationships. Secretariat users can access any organization. Root oversight does not grant write or administrator permissions.

Expected Behavior

Regular, CNA & Admin Users: Retrieves registry organization record for the specified shortname or UUID if it is the user's organization

Secretariat: Retrieves information about any registry organization

The reports_to, top_level_root, and oversees relationship fields contain organization short names.

-

The _hierarchy array contains the ancestor path from the top-level Root to the requested organization and that organization's complete subtree. Ancestors include only the child on that path. Nodes contain UUID, short_name, long_name, authority, and children. ROOT nodes also contain is_top_level_root, and CNA nodes contain is_last_resort. An organization without a parent begins its own tree.

" +

The _hierarchy array contains the ancestor path from the top-level Root to the requested organization and that organization's complete subtree. Ancestors include only the child on that path and do not grant access to ancestor organization or user records. Siblings and unrelated branches remain outside Root oversight. Nodes contain UUID, short_name, long_name, authority, and children. ROOT nodes also contain is_top_level_root, and CNA nodes contain is_last_resort. An organization without a parent begins its own tree.

" #swagger.parameters['expand'] = { in: 'query', - description: 'Optional expanded related data. Accepted value: users.', + description: 'Optional expanded related data. Accepted value: users. Overseeing Root users can expand the authorized target organization\'s users, administrators, and additional contacts. Existing Secretariat and same-organization expansion rules apply.', required: false, '@schema': { type: 'string', @@ -569,6 +572,7 @@ router.get('/registry/org/:identifier', query(['expand']).optional().isIn(['users']), parseError, parseGetParams, + mw.authorizeRegistryOrgRead, registryOrgController.SINGLE_ORG ) @@ -576,11 +580,11 @@ router.get('/registry/org/:shortname/user/:username', /* #swagger.tags = ['Data Registry — Users'] #swagger.operationId = 'registryUserSingle' - #swagger.summary = "Retrieves information about a user for the specified username and organization short name (accessible to same-organization users or Secretariat)" + #swagger.summary = "Retrieves a user by username and organization short name (same-organization users, overseeing Root users, or Secretariat)" #swagger.description = "

Related legacy endpoint: GET /org/{shortname}/user/{username}. Data Registry responses expose status and role; legacy responses expose active and authority.active_roles.

Access Control

-

Authenticated users can access this endpoint only for users in their own organization. Secretariat users can access any user.

+

Authenticated users can access users in their own organization. Ordinary users and administrators in an organization with ROOT authority can also access users belonging to direct and indirect descendant organizations, including organizations beneath subordinate Roots, using current reporting relationships. Secretariat users can access any user. Root oversight excludes ancestors, sibling branches, and unrelated organizations.

Expected Behavior

Regular, CNA & Admin Users: Retrieves information about a registry user in the same organization

Secretariat: Retrieves any registry user's information

" @@ -655,6 +659,7 @@ router.get('/registry/org/:shortname/user/:username', query().custom((query) => { return mw.validateQueryParameterNames(query, ['']) }), parseError, parseGetParams, + mw.authorizeRegistryOrgRead, registryUserController.SINGLE_USER ) diff --git a/src/controller/registry.controller/org.registry.controller.js b/src/controller/registry.controller/org.registry.controller.js index 3e31c8cf9..b8215765c 100644 --- a/src/controller/registry.controller/org.registry.controller.js +++ b/src/controller/registry.controller/org.registry.controller.js @@ -16,6 +16,7 @@ const { getUserQuotaUsage } = require('../../utils/userQuota') const { deepRemoveEmpty } = require('../../utils/utils') const { normalizeOrgCveWebsiteUpdateDate } = require('../../utils/dateOnly') const { normalizeReviewOrgData } = require('../../repositories/baseOrgRepositoryHelpers') +const NON_SECRETARIAT_CONVERSATION_FIELDS = ['__v', '_id', 'UUID', 'previous_conversation_uuid', 'next_conversation_uuid', 'target_uuid', 'visibility'] function addUUIDsToSet (uuidSet, values) { if (!Array.isArray(values)) return @@ -113,14 +114,22 @@ function removeAdditionalContactUUIDFields (org) { * @param {object} res - The Express response object. * @param {function} next - The next middleware function. * @returns {Promise} - A promise that resolves when the response is sent. - * @description This endpoint is accessible to Secretariat only. It retrieves a list of all registry organizations. + * @description Secretariat receives all registry organizations; Root users receive only their descendants. * Called by GET /api/registry/org */ async function getAllOrgs (req, res, next) { try { + const access = req.ctx.registryRead + if (!access || (!access.isSecretariat && !access.hierarchyScope)) { + return res.status(403).json(error.notSameOrgOrSecretariat()) + } const repo = req.ctx.repositories.getBaseOrgRepository() + const { isSecretariat, hierarchyScope } = access + const orgUUIDs = isSecretariat ? undefined : await authContext.getRequestOrgDescendantUUIDs(req, repo, hierarchyScope) + if (!isSecretariat && !Array.isArray(orgUUIDs)) { + return res.status(403).json(error.notSameOrgOrSecretariat()) + } const conversationRepo = req.ctx.repositories.getConversationRepository() - const isSecretariat = await authContext.isRequesterSecretariat(req, repo) const CONSTANTS = getConstants() let returnValue @@ -135,10 +144,12 @@ async function getAllOrgs (req, res, next) { options.page = req.ctx.query.page ? parseInt(req.ctx.query.page) : CONSTANTS.PAGINATOR_PAGE // if 'page' query parameter is not defined, set 'page' to the default page value try { - returnValue = await repo.getAllOrgs({ ...options }, REGISTRY_FORMAT, isSecretariat) + returnValue = await repo.getAllOrgs({ ...options }, REGISTRY_FORMAT, isSecretariat, orgUUIDs) for (let i = 0; i < returnValue.organizations.length; i++) { const conversation = await conversationRepo.getAllByTargetUUID(returnValue.organizations[i].UUID, isSecretariat) - returnValue.organizations[i].conversation = conversation?.length ? conversation : undefined + returnValue.organizations[i].conversation = conversation?.length + ? (isSecretariat ? conversation : conversation.map(c => _.omit(c, NON_SECRETARIAT_CONVERSATION_FIELDS))) + : undefined } } catch (error) { // Handle the specific error thrown by BaseOrgRepository.createOrg @@ -156,13 +167,17 @@ async function getAllOrgs (req, res, next) { } /** - * Retrieves the complete registry organization hierarchy for Secretariat users. + * Retrieves the complete hierarchy for Secretariat or the requesting Root's branch. * Called by GET /api/registry/org-hierarchy. */ async function getOrgHierarchy (req, res, next) { try { const repo = req.ctx.repositories.getBaseOrgRepository() - const hierarchy = await repo.getOrgHierarchy() + const access = req.ctx.registryRead + if (!access || (!access.isSecretariat && !access.hierarchyScope)) { + return res.status(403).json(error.notSameOrgOrSecretariat()) + } + const hierarchy = await authContext.getRequestOrgHierarchy(req, repo, access.hierarchyScope) return res.status(200).json(hierarchy) } catch (err) { if (res.headersSent) return next(err) @@ -248,7 +263,7 @@ async function getActiveCnas (req, res, next) { * @param {object} res - The Express response object. * @param {function} next - The next middleware function. * @returns {Promise} - A promise that resolves when the response is sent. - * @description This endpoint is accessible to Secretariat only. It retrieves information about the specified registry organization. + * @description Accessible to Secretariat, same-organization users, and overseeing Root users. * Called by GET /api/registry/org/:identifier */ async function getOrg (req, res, next) { @@ -261,24 +276,20 @@ async function getOrg (req, res, next) { let returnValue try { - const requesterOrg = await authContext.getRequesterOrg(req, repo) - const isSecretariat = await authContext.isRequesterSecretariat(req, repo) - const isRequesterSameOrg = identifierIsUUID - ? requesterOrg.UUID === identifier - : await authContext.isRequesterSameOrg(req, repo, identifier) - - if (!isRequesterSameOrg && !isSecretariat) { - logger.info({ uuid: req.ctx.uuid, message: identifier + ' organization can only be viewed by the users of the same organization or the Secretariat.' }) + const access = req.ctx.registryRead + if (!access) { return res.status(403).json(error.notSameOrgOrSecretariat()) } - returnValue = await repo.getOrg(identifier, identifierIsUUID, {}, REGISTRY_FORMAT, isSecretariat) + const { isSecretariat, targetOrg, reason } = access + const isParentOrg = reason === 'PARENT_ORG' + returnValue = await repo.getOrg(targetOrg?.UUID || identifier, Boolean(targetOrg?.UUID) || identifierIsUUID, {}, REGISTRY_FORMAT, isSecretariat) if (returnValue) { - returnValue._hierarchy = returnValue.UUID ? await repo.getOrgHierarchy(returnValue.UUID) : [] + returnValue._hierarchy = returnValue.UUID ? await authContext.getRequestOrgHierarchy(req, repo, returnValue.UUID) : [] let userRepo let isAdminOfRequestedOrg = false - if (!isSecretariat) { + if (!isSecretariat && !isParentOrg) { userRepo = req.ctx.repositories.getBaseUserRepository() isAdminOfRequestedOrg = await userRepo.isAdmin(req.ctx.user, returnValue.short_name, {}) } @@ -288,20 +299,20 @@ async function getOrg (req, res, next) { if (isSecretariat) { returnValue.conversation = conversation?.length ? _.map(conversation, c => _.omit(c, ['__v', '_id', 'previous_conversation_uuid', 'next_conversation_uuid', 'target_uuid'])) : undefined } else { - returnValue.conversation = conversation?.length ? _.map(conversation, c => _.omit(c, ['__v', '_id', 'UUID', 'previous_conversation_uuid', 'next_conversation_uuid', 'target_uuid', 'visibility'])) : undefined + returnValue.conversation = conversation?.length ? _.map(conversation, c => _.omit(c, NON_SECRETARIAT_CONVERSATION_FIELDS)) : undefined } if (req.ctx.query?.expand === 'users') { userRepo = userRepo || req.ctx.repositories.getBaseUserRepository() if (isSecretariat) { returnValue._userMap = await buildUserMap(returnValue, userRepo, repo) - } else if (isAdminOfRequestedOrg) { - returnValue._userMap = await buildOrgUserMap(requesterOrg, userRepo, repo) + } else if (isAdminOfRequestedOrg || isParentOrg) { + returnValue._userMap = await buildOrgUserMap(targetOrg, userRepo, repo) } } if (!isSecretariat) { - if (!isAdminOfRequestedOrg) { + if (!isAdminOfRequestedOrg && !isParentOrg) { removeUserUUIDFields(returnValue) } } @@ -1010,7 +1021,7 @@ async function removeOverseeRelationship (req, res, next) { * @param {object} res - The Express response object. * @param {function} next - The next middleware function. * @returns {Promise} - A promise that resolves when the response is sent. Registry-format responses include 'role' for admins. - * @description This endpoint is accessible to Secretariat only. It retrieves user information for any organization. + * @description Accessible to Secretariat, same-organization users, and overseeing Root users. * Called by GET /api/registry/org/:shortname/users */ async function getUsers (req, res, next) { @@ -1027,26 +1038,15 @@ async function getUsers (req, res, next) { options.sort = { username: 'asc' } options.page = req.ctx.query.page ? parseInt(req.ctx.query.page) : CONSTANTS.PAGINATOR_PAGE // if 'page' query parameter is not defined, set 'page' to the default page value const orgShortName = req.ctx.params.shortname - const orgRepo = req.ctx.repositories.getBaseOrgRepository() const userRepo = req.ctx.repositories.getBaseUserRepository() - const orgUUID = await orgRepo.getOrgUUID(orgShortName) - const isSecretariat = await authContext.isRequesterSecretariat(req, orgRepo) - - if (!orgUUID) { - logger.info({ uuid: req.ctx.uuid, message: orgShortName + ' organization does not exist.' }) - return res.status(404).json(error.orgDnePathParam(orgShortName)) - } - - const isSameOrg = await authContext.isRequesterSameOrg(req, orgRepo, { UUID: orgUUID, short_name: orgShortName }) - if (!isSameOrg && !isSecretariat) { - logger.info({ uuid: req.ctx.uuid, message: orgShortName + ' organization can only be viewed by the users of the same organization or the Secretariat.' }) + const org = req.ctx.registryRead?.targetOrg + if (!org) { return res.status(403).json(error.notSameOrgOrSecretariat()) } - const payload = await userRepo.getAllUsersByOrgShortname(orgShortName, options) + const payload = await userRepo.getAllUsersByOrgShortname(org.short_name, options, org) // Hydrate the role field for registry responses. - const org = await orgRepo.findOneByShortName(orgShortName) payload.users.forEach(user => { user.role = org.admins.includes(user.UUID) ? 'ADMIN' : user.role // Default to existing role if not admin }) diff --git a/src/controller/registry.controller/user.registry.controller.js b/src/controller/registry.controller/user.registry.controller.js index 231f620cc..259636a69 100644 --- a/src/controller/registry.controller/user.registry.controller.js +++ b/src/controller/registry.controller/user.registry.controller.js @@ -86,7 +86,7 @@ async function getAllUsers (req, res, next) { * @param {object} res - The Express response object. * @param {function} next - The next middleware function. * @returns {Promise} - A promise that resolves when the response is sent. Registry-format responses include 'role' for admins. - * @description This endpoint is accessible to Secretariat only. It retrieves information about the specified registry user. + * @description Accessible to Secretariat, same-organization users, and overseeing Root users. * Called by GET /api/registry/org/:shortname/user/:username */ async function getUser (req, res, next) { @@ -112,7 +112,9 @@ async function getUser (req, res, next) { const userRepo = req.ctx.repositories.getBaseUserRepository() const repo = req.ctx.repositories.getBaseOrgRepository() - const isSecretariat = await authContext.isRequesterSecretariat(req, repo, {}, REGISTRY_FORMAT) + const isSecretariat = identifier + ? await authContext.isRequesterSecretariat(req, repo, {}, REGISTRY_FORMAT) + : req.ctx.registryRead?.isSecretariat let result let org @@ -137,15 +139,13 @@ async function getUser (req, res, next) { username: result.username } } else { - org = await repo.findOneByShortName(req.ctx.params.shortname, {}, REGISTRY_FORMAT) - - const isSameOrg = await authContext.isRequesterSameOrg(req, repo, org, {}, REGISTRY_FORMAT) - if (!isSecretariat && !isSameOrg) { - logger.info({ uuid: req.ctx.uuid, message: userToGetParameters.org + ' organization can only be viewed by the users of the same organization or the Secretariat.' }) + if (!req.ctx.registryRead) { return res.status(403).json(error.notSameOrgOrSecretariat()) } - - result = await userRepo.findOneByUsernameAndOrgShortname(userToGetParameters.username, userToGetParameters.org, {}, REGISTRY_FORMAT) + org = req.ctx.registryRead.targetOrg + result = org + ? await userRepo.findUserByUsernameAndOrgUUID(userToGetParameters.username, org.UUID, { readPreference: 'primary' }, REGISTRY_FORMAT) + : null if (!result) { logger.info({ uuid: req.ctx.uuid, message: userToGetParameters.username + ' user could not be found.' }) return res.status(404).json(error.userDne(userToGetParameters.username)) diff --git a/src/middleware/middleware.js b/src/middleware/middleware.js index 249659161..c476d0259 100644 --- a/src/middleware/middleware.js +++ b/src/middleware/middleware.js @@ -225,6 +225,68 @@ async function onlySecretariat (req, res, next) { } } +// Read authorization is deliberately separate from same-org and administrator write checks. +async function authorizeRegistryOrgRead (req, res, next) { + try { + if (!req.ctx.authenticated || !req.ctx.orgUUID) { + return res.status(403).json(registryOrgErrors.notSameOrgOrSecretariat()) + } + const repo = req.ctx.repositories.getBaseOrgRepository() + const { identifier, shortname, username } = req.ctx.params + const options = { readPreference: 'primary' } + const targetOrg = identifier && uuid.validate(identifier) + ? await repo.findOneByUUID(identifier, options) + : await repo.findOneByShortName(identifier || shortname, options) + + // Preserve the organization-user list's existing missing-organization response. + if (!targetOrg && !identifier && !username) { + return res.status(404).json(registryOrgErrors.orgDnePathParam(shortname)) + } + + const isSecretariat = await authContext.isRequesterSecretariat(req, repo, options) + let reason + if (isSecretariat) { + reason = 'SECRETARIAT' + } else if (await authContext.isRequesterSameOrg(req, repo, targetOrg)) { + reason = 'SAME_ORG' + } else if (await authContext.isRequesterParentOrg(req, repo, targetOrg)) { + reason = 'PARENT_ORG' + } else { + return res.status(403).json(registryOrgErrors.notSameOrgOrSecretariat()) + } + + req.ctx.registryRead = { targetOrg, isSecretariat, reason } + next() + } catch (err) { + next(err) + } +} + +async function authorizeRegistryHierarchyRead (req, res, next) { + try { + if (!req.ctx.authenticated || !req.ctx.orgUUID) { + return res.status(403).json(error.secretariatOnly()) + } + const repo = req.ctx.repositories.getBaseOrgRepository() + const options = { readPreference: 'primary' } + const isSecretariat = await authContext.isRequesterSecretariat(req, repo, options) + if (!isSecretariat) { + const requesterOrg = await authContext.getRequesterOrg(req, repo, options) + if (!authContext.orgHasRole(requesterOrg, 'ROOT')) { + return res.status(403).json(error.secretariatOnly()) + } + } + req.ctx.registryRead = { + isSecretariat, + reason: isSecretariat ? 'SECRETARIAT' : 'ROOT', + hierarchyScope: isSecretariat ? undefined : req.ctx.orgUUID + } + next() + } catch (err) { + next(err) + } +} + // Checks that the requester belongs to an org that has the 'SECRETARIAT' role or is a user with the 'ADMIN' role async function onlySecretariatOrAdmin (req, res, next) { const org = req.ctx.org @@ -558,6 +620,8 @@ module.exports = { validateUser, useRegistry, onlySecretariat, + authorizeRegistryOrgRead, + authorizeRegistryHierarchyRead, onlySecretariatOrBulkDownload, onlySecretariatOrAdmin, onlyCnas, diff --git a/src/repositories/baseOrgRepository.js b/src/repositories/baseOrgRepository.js index 8e21786d0..56f1e4e5b 100644 --- a/src/repositories/baseOrgRepository.js +++ b/src/repositories/baseOrgRepository.js @@ -796,17 +796,20 @@ class BaseOrgRepository extends BaseRepository { /** * @async * @function getAllOrgs - * @description Retrieves all organizations with pagination. + * @description Retrieves organizations with pagination, optionally scoped to authorized UUIDs. * @param {object} [options={}] - Pagination and query options. * @param {boolean} [returnLegacyFormat=false] - If true, returns data in legacy format. + * @param {boolean} [isSecretariat=false] - Whether restricted registry fields may be returned. + * @param {string[]} [orgUUIDs] - Authorized registry organization UUIDs; an empty array matches nothing. * @returns {Promise} Paginated result containing organizations and metadata. */ - async getAllOrgs (options = {}, returnLegacyFormat = false, isSecretariat = false) { + async getAllOrgs (options = {}, returnLegacyFormat = false, isSecretariat = false, orgUUIDs) { if (returnLegacyFormat) { return this.getLegacyOrgs(options) } - const agt = setAggregateRegistryOrgObj({}, isSecretariat) + const query = orgUUIDs === undefined ? {} : { UUID: { $in: orgUUIDs } } + const agt = setAggregateRegistryOrgObj(query, isSecretariat) const pg = await this.aggregatePaginate(agt, options) // Strip nulls returned by DocumentDB to prevent schema validation errors @@ -871,13 +874,16 @@ class BaseOrgRepository extends BaseRepository { * The UUID projection assembles relationships and identifies nodes in full forests. * * @param {string} [orgUUID] - Restricts the forest to this org's ancestor path and subtree. + * @param {object} [options] - Database read options. + * @param {object} [cache] - Request-local projected organization data, reusable for other scopes. * @returns {Promise} Organization UUIDs, names, roles, role flags, and nested children. */ - async getOrgHierarchy (orgUUID) { - const orgs = await BaseOrgModel.find({}) + async getOrgHierarchy (orgUUID, options = {}, cache) { + const orgs = cache?.organizations || await BaseOrgModel.find({}, null, options) .select(ORG_RELATIONSHIP_PROJECTION) .lean() + if (cache) cache.organizations = orgs return createOrgRelationships(orgs).hierarchy(orgUUID) } diff --git a/src/repositories/baseUserRepository.js b/src/repositories/baseUserRepository.js index b1012a2d5..f6a67d8c2 100644 --- a/src/repositories/baseUserRepository.js +++ b/src/repositories/baseUserRepository.js @@ -759,12 +759,13 @@ class BaseUserRepository extends BaseRepository { * * @param {string} orgShortname - The short name of the organization. * @param {object} options - Pagination options (e.g., limit, page). + * @param {object} [targetOrg] - The organization resolved by registry read authorization. * @returns {Promise} An object containing the list of users and pagination details. */ - async getAllUsersByOrgShortname (orgShortname, options = {}) { + async getAllUsersByOrgShortname (orgShortname, options = {}, targetOrg) { const CONSTANTS = getConstants() const baseOrgRepository = new BaseOrgRepository() - const org = await baseOrgRepository.findOneByShortName(orgShortname) + const org = targetOrg || await baseOrgRepository.findOneByShortName(orgShortname) const orgObject = toPlainObject(org) const usersInOrg = orgObject.users diff --git a/src/scripts/populate.js b/src/scripts/populate.js index bed140b97..1678227e2 100644 --- a/src/scripts/populate.js +++ b/src/scripts/populate.js @@ -108,6 +108,8 @@ async function populateBaseOrgCollection () { long_name: org.name, authority: org.authority.active_roles, id_quota: org.policies?.id_quota, + users: org.users, + admins: org.admins, disabled: false, program_data: { status: 'Active' }, created: new Date(), diff --git a/src/utils/authContext.js b/src/utils/authContext.js index 29c9d4fca..df6e35538 100644 --- a/src/utils/authContext.js +++ b/src/utils/authContext.js @@ -257,6 +257,56 @@ async function isRequesterSameOrg (req, orgRepo, targetOrgOrShortName, options = return Boolean(requesterOrgUUID && targetOrgUUID && requesterOrgUUID === targetOrgUUID) } +// The cache belongs to this request so authorization never survives relationship changes. +async function getRequestOrgHierarchy (req, orgRepo, orgUUID) { + const cache = req.ctx.orgHierarchyCache || (req.ctx.orgHierarchyCache = { scopes: new Map() }) + if (!cache.scopes.has(orgUUID)) { + cache.scopes.set(orgUUID, await orgRepo.getOrgHierarchy(orgUUID, { readPreference: 'primary' }, cache)) + } + return cache.scopes.get(orgUUID) +} + +function findHierarchyNode (nodes, orgUUID) { + const pending = [...nodes] + while (pending.length > 0) { + const node = pending.pop() + if (node.UUID === orgUUID) return node + pending.push(...node.children) + } + return null +} + +async function getRequestOrgDescendantUUIDs (req, orgRepo, orgUUID) { + if (!orgUUID) return null + const hierarchy = await getRequestOrgHierarchy(req, orgRepo, orgUUID) + const requesterNode = findHierarchyNode(hierarchy, orgUUID) + if (!orgHasRole(requesterNode, 'ROOT')) return null + + const descendants = new Set() + const pending = [...requesterNode.children] + while (pending.length > 0) { + const node = pending.pop() + if (node.UUID && node.UUID !== orgUUID) descendants.add(node.UUID) + pending.push(...node.children) + } + return [...descendants] +} + +async function isRequesterParentOrg (req, orgRepo, targetOrg, options = {}) { + const requesterOrgUUID = req.ctx.orgUUID + if (!isAuthenticatedRequest(req) || !requesterOrgUUID || !targetOrg?.UUID || targetOrg.UUID === requesterOrgUUID) { + return false + } + + const requesterOrg = await getRequesterOrg(req, orgRepo, { ...options, readPreference: 'primary' }) + if (!orgHasRole(requesterOrg, 'ROOT')) return false + + const hierarchy = await getRequestOrgHierarchy(req, orgRepo, requesterOrgUUID) + const requesterNode = findHierarchyNode(hierarchy, requesterOrgUUID) + // Ancestors in the contextual path are not part of the requester's oversight. + return Boolean(requesterNode && findHierarchyNode(requesterNode.children, targetOrg.UUID)) +} + async function isRequesterSecretariat (req, orgRepo, options = {}, returnLegacyFormat = false) { if (isAuthenticatedRequest(req) || req.ctx.orgUUID) { const orgUUID = await getRequesterOrgUUID(req, orgRepo, options, returnLegacyFormat) @@ -425,6 +475,8 @@ async function getRequesterContext (req, repositories = {}, options = {}, isLega } module.exports = { + getRequestOrgDescendantUUIDs, + getRequestOrgHierarchy, getRequesterContext, getRequesterOrg, getRequesterOrgUUID, @@ -433,6 +485,7 @@ module.exports = { isRequesterAdmin, isRequesterAdminOfOrg, isRequesterBulkDownload, + isRequesterParentOrg, isRequesterSameOrg, isRequesterSecretariat, orgHasRole diff --git a/test/integration-tests/registry-org/populatedOrgHierarchyTest.js b/test/integration-tests/registry-org/populatedOrgHierarchyTest.js index 06bea6cc5..753d46c9c 100644 --- a/test/integration-tests/registry-org/populatedOrgHierarchyTest.js +++ b/test/integration-tests/registry-org/populatedOrgHierarchyTest.js @@ -2,6 +2,10 @@ const chai = require('chai') const expect = chai.expect chai.use(require('chai-http')) +const express = require('express') +const { withHttpServer } = require('../../httpServer') +const middleware = require('../../../src/middleware/middleware') +const registryRouter = require('../../../src/controller/registry.controller') const constants = require('../constants.js') const app = require('../../../src/index.js') @@ -35,6 +39,27 @@ const sampleTopRootShortName = topRootSeeds .find(root => root.oversees.includes(sampleRootShortName)) .short_name +function demoRootHeaders (shortName, role) { + return { + ...constants.headers, + 'CVE-API-ORG': shortName, + 'CVE-API-USER': `${shortName}_${role}@demo.test` + } +} + +function createPaginatedRegistryApp () { + const app = express() + app.set('query parser', 'extended') + app.use(middleware.createCtxAndReqUUID) + app.use((req, res, next) => { + req.TEST_PAGINATOR_LIMIT = 100 + next() + }) + app.use('/api', registryRouter) + app.use(middleware.errorHandler) + return app +} + async function getOrg (shortName) { const res = await chai.request(app) .get(`/api/registry/org/${shortName}`) @@ -179,4 +204,109 @@ describe('Populated registry organization hierarchy', () => { expect(cna.CNA.root.shortName).to.equal(sampleRootShortName) expect(cna.CNA.TLR.shortName).to.equal(sampleTopRootShortName) }) + + context('Seeded Root demo accounts', () => { + for (const shortName of ['top_root_1', 'root_1_4']) { + it(`populates an active ordinary user and administrator in ${shortName}`, async () => { + const response = await chai.request(app) + .get(`/api/registry/org/${shortName}/users`) + .set(constants.headers) + + expect(response).to.have.status(200) + expect(response.body.users.map(user => user.username)).to.have.members([ + `${shortName}_user@demo.test`, `${shortName}_admin@demo.test` + ]) + for (const user of response.body.users) { + expect(user.status).to.equal('active') + expect(user).to.not.have.property('secret') + if (user.username === `${shortName}_admin@demo.test`) { + expect(user.role).to.equal('ADMIN') + } else { + expect(user.role).to.not.equal('ADMIN') + } + } + }) + + for (const role of ['user', 'admin']) { + it(`paginates only descendants for the seeded ${shortName} ${role}`, async () => { + const expected = shortName === 'top_root_1' + ? [ + ...topRootSeeds[0].oversees, + ...directCnaShortNames.slice(0, DIRECT_CNAS_PER_TOP_ROOT), + ...childRootCnaShortNames.filter((_name, index) => index % rootShortNames.length < topRootSeeds[0].oversees.length) + ] + : childRootCnaShortNames.filter((_name, index) => index % rootShortNames.length === rootShortNames.indexOf(shortName)) + const names = [] + await withHttpServer(createPaginatedRegistryApp(), async url => { + let page = 1 + while (page) { + expect(page).to.be.at.most(expected.length) + const response = await chai.request(url).get('/api/registry/org') + .query({ page }).set(demoRootHeaders(shortName, role)) + expect(response).to.have.status(200) + expect(response.body.totalCount).to.equal(expected.length) + expect(response.body.currentPage).to.equal(page) + expect(response.body.itemsPerPage).to.equal(100) + expect(response.body.pageCount).to.equal(Math.ceil(expected.length / response.body.itemsPerPage)) + expect(response.body.pageCount).to.be.greaterThan(1) + names.push(...response.body.organizations.map(org => org.short_name)) + response.body.organizations.forEach(org => expect(org).to.not.have.property('program_data')) + page = response.body.nextPage + } + }) + expect(names).to.have.members(expected) + expect(new Set(names).size).to.equal(expected.length) + expect(names).to.deep.equal([...names].sort()) + expect(names).to.not.include(shortName) + }) + + it(`lets the seeded ${shortName} ${role} retrieve the scoped hierarchy and descendant users`, async () => { + const headers = demoRootHeaders(shortName, role) + const response = await chai.request(app).get('/api/registry/org-hierarchy').set(headers) + const ownOrg = await getOrg(shortName) + expect(response).to.have.status(200) + expect(response.body).to.deep.equal(ownOrg._hierarchy) + + const cna = await getOrg('window_1') + const expanded = await chai.request(app) + .get(`/api/registry/org/${cna.UUID}?expand=users`).set(headers) + expect(expanded).to.have.status(200) + expect(expanded.body.UUID).to.equal(cna.UUID) + expect(Object.keys(expanded.body._userMap)).to.have.members(cna.users) + + const users = await chai.request(app).get('/api/registry/org/window_1/users').set(headers) + expect(users).to.have.status(200) + expect(users.body.users.map(user => user.UUID)).to.have.members(cna.users) + + const user = await chai.request(app) + .get('/api/registry/org/window_1/user/ashleyruiz@window_1.com').set(headers) + expect(user).to.have.status(200) + expect(user.body.username).to.equal('ashleyruiz@window_1.com') + expect(user.body).to.not.have.property('secret') + + if (shortName === 'top_root_1') { + const subordinate = await chai.request(app) + .get('/api/registry/org/root_1_4?expand=users').set(headers) + expect(subordinate).to.have.status(200) + expect(Object.values(subordinate.body._userMap).map(user => user.username)).to.have.members([ + 'root_1_4_user@demo.test', 'root_1_4_admin@demo.test' + ]) + } + }) + + it(`keeps the seeded ${shortName} ${role} within its oversight branch`, async () => { + const headers = demoRootHeaders(shortName, role) + const deniedOrgs = shortName === 'root_1_4' + ? ['top_root_1', 'root_1_3', 'top_root_2'] + : ['top_root_2'] + for (const target of deniedOrgs) { + const response = await chai.request(app).get(`/api/registry/org/${target}`).set(headers) + expect(response).to.have.status(403) + } + const allUsers = await chai.request(app).get('/api/registry/users').set(headers) + expect(allUsers).to.have.status(403) + }) + } + } + }) }) diff --git a/test/integration-tests/registry-org/rootReadAccessTest.js b/test/integration-tests/registry-org/rootReadAccessTest.js new file mode 100644 index 000000000..6da5c527b --- /dev/null +++ b/test/integration-tests/registry-org/rootReadAccessTest.js @@ -0,0 +1,281 @@ +/* eslint-disable no-unused-expressions */ +const chai = require('chai') +const { expect } = chai +chai.use(require('chai-http')) +const { v4: uuidv4 } = require('uuid') +const constants = require('../constants') +const app = require('../../../src/index') +const Conversation = require('../../../src/model/conversation') + +const secretariat = constants.headers +const runId = uuidv4().slice(0, 8) + +function flatten (nodes) { + return nodes.flatMap(node => [node, ...flatten(node.children)]) +} + +describe('Root oversight registry read access', () => { + const orgs = {} + const users = {} + const createdUsers = [] + + function headers (label, admin = false) { + const user = users[`${label}${admin ? 'Admin' : ''}`] + return { + 'CVE-API-ORG': orgs[label].short_name, + 'CVE-API-USER': user.username, + 'CVE-API-KEY': user.secret + } + } + + async function relate (parent, child, action = 'add') { + const response = await chai.request(app) + .post(`/api/registry/org/${orgs[parent].short_name}/oversees/${orgs[child].short_name}/${action}`) + .set(secretariat) + expect(response).to.have.status(200) + } + + async function expectReads (requestHeaders, label, status) { + const org = orgs[label] + for (const path of [ + `/api/registry/org/${org.short_name}`, + `/api/registry/org/${org.UUID}?expand=users`, + `/api/registry/org/${org.short_name}/users`, + `/api/registry/org/${org.short_name}/user/${users[label].username}` + ]) { + const response = await chai.request(app).get(path).set(requestHeaders) + expect(response.status, path).to.equal(status) + } + } + + async function expectOrgList (requestHeaders, labels) { + const response = await chai.request(app).get('/api/registry/org').set(requestHeaders) + expect(response).to.have.status(200) + expect(response.body.organizations.map(org => org.UUID)).to.have.members(labels.map(label => orgs[label].UUID)) + expect(response.body.totalCount).to.equal(labels.length) + const names = response.body.organizations.map(org => org.short_name) + expect(names).to.deep.equal([...names].sort()) + response.body.organizations.forEach(org => expect(org).to.not.have.property('program_data')) + return response.body + } + + before(async () => { + for (const label of ['top', 'root', 'branch', 'cna', 'peer', 'other']) { + const isRoot = label !== 'cna' + const response = await chai.request(app).post('/api/registry/org').set(secretariat).send({ + short_name: `read_${label}_${runId}`, + long_name: `Root read access ${label}`, + disabled: false, + authority: [isRoot ? 'ROOT' : 'CNA'], + ...(isRoot ? { is_top_level_root: ['top', 'other'].includes(label) } : { id_quota: 10 }), + private_contacts: [{ poc: 'Private contact', poc_email: 'private@example.test' }] + }) + expect(response).to.have.status(200) + orgs[label] = response.body.created + + for (const admin of [false, true]) { + // Shared names across organizations must still resolve the target's user. + const username = `${admin ? 'admin' : 'shared'}_${runId}@example.test` + const userResponse = await chai.request(app) + .post(`/api/registry/org/${orgs[label].short_name}/user`) + .set(secretariat).send({ + username, + name: { first: label, last: admin ? 'Admin' : 'User' }, + status: 'active', + ...(admin ? { role: 'ADMIN' } : {}) + }) + expect(userResponse).to.have.status(200) + users[`${label}${admin ? 'Admin' : ''}`] = userResponse.body.created + createdUsers.push({ shortName: orgs[label].short_name, username }) + } + } + await relate('top', 'root') + await relate('top', 'peer') + await relate('root', 'branch') + await relate('branch', 'cna') + const peerOnly = await chai.request(app) + .post(`/api/registry/org/${orgs.peer.short_name}/user`).set(secretariat) + .send({ username: `peer_only_${runId}@example.test`, status: 'active' }) + expect(peerOnly).to.have.status(200) + users.peerOnly = peerOnly.body.created + createdUsers.push({ shortName: orgs.peer.short_name, username: users.peerOnly.username }) + for (const visibility of ['public', 'private']) { + const response = await chai.request(app).post(`/api/conversation/target/${orgs.cna.UUID}`) + .set(secretariat).send({ visibility, body: `${visibility} Root list ${runId}` }) + expect(response).to.have.status(200) + } + }) + + after(async () => { + if (orgs.cna) await Conversation.deleteMany({ target_uuid: orgs.cna.UUID }) + for (const user of createdUsers) { + const response = await chai.request(app) + .delete(`/api/registry/org/${user.shortName}/user/${user.username}`).set(secretariat) + expect([200, 404]).to.include(response.status) + } + for (const org of Object.values(orgs)) { + const response = await chai.request(app).delete(`/api/registry/org/${org.short_name}`).set(secretariat) + expect([200, 404]).to.include(response.status) + } + }) + + for (const admin of [false, true]) { + context(admin ? 'Root administrator' : 'Ordinary Root user', () => { + it('receives the ancestor path and own subtree without sibling branches', async () => { + const response = await chai.request(app).get('/api/registry/org-hierarchy').set(headers('root', admin)) + const own = await chai.request(app).get(`/api/registry/org/${orgs.root.UUID}`).set(secretariat) + expect(response).to.have.status(200) + expect(own).to.have.status(200) + expect(response.body).to.deep.equal(own.body._hierarchy) + expect(flatten(response.body).map(node => node.UUID)).to.have.members([ + orgs.top.UUID, orgs.root.UUID, orgs.branch.UUID, orgs.cna.UUID + ]) + }) + + it('reads direct and indirect descendants by short name and UUID', async () => { + await expectReads(headers('root', admin), 'branch', 200) + await expectReads(headers('root', admin), 'cna', 200) + }) + + it('expands only the authorized target organization membership', async () => { + const response = await chai.request(app) + .get(`/api/registry/org/${orgs.cna.short_name}?expand=users`).set(headers('root', admin)) + expect(response).to.have.status(200) + expect(response.body.users).to.have.members([users.cna.UUID, users.cnaAdmin.UUID]) + expect(response.body.admins).to.deep.equal([users.cnaAdmin.UUID]) + expect(Object.keys(response.body._userMap)).to.have.members([users.cna.UUID, users.cnaAdmin.UUID]) + expect(response.body._userMap[users.cna.UUID].org.short_name).to.equal(orgs.cna.short_name) + expect(response.body).to.not.have.property('program_data') + expect(JSON.stringify(response.body)).to.not.include(users.cna.secret) + }) + + it('returns target users in username order and derives their admin roles', async () => { + const response = await chai.request(app) + .get(`/api/registry/org/${orgs.cna.short_name}/users`).set(headers('root', admin)) + expect(response).to.have.status(200) + expect(response.body.users.map(user => user.UUID)).to.deep.equal([users.cnaAdmin.UUID, users.cna.UUID]) + expect(response.body.users[0].role).to.equal('ADMIN') + response.body.users.forEach(user => expect(user).to.not.have.property('secret')) + + const user = await chai.request(app) + .get(`/api/registry/org/${orgs.cna.short_name}/user/${users.cna.username}`).set(headers('root', admin)) + expect(user).to.have.status(200) + expect(user.body.UUID).to.equal(users.cna.UUID) + expect(user.body).to.not.have.property('secret') + }) + + it('denies ancestors, siblings and unrelated organizations and users', async () => { + for (const label of ['top', 'peer', 'other']) await expectReads(headers('root', admin), label, 403) + }) + + it('lists all descendants for Roots and top-level Roots, excluding the requester and other branches', async () => { + await expectOrgList(headers('root', admin), ['branch', 'cna']) + await expectOrgList(headers('top', admin), ['root', 'branch', 'cna', 'peer']) + }) + + it('returns an empty list for a Root without descendants', async () => { + const response = await expectOrgList(headers('peer', admin), []) + expect(response.nextPage).to.equal(null) + }) + + it('applies non-Secretariat conversation filtering to list entries', async () => { + const payload = await expectOrgList(headers('root', admin), ['branch', 'cna']) + const org = payload.organizations.find(org => org.UUID === orgs.cna.UUID) + expect(org.conversation).to.have.lengthOf(1) + expect(org.conversation[0].body).to.equal(`public Root list ${runId}`) + for (const field of ['_id', '__v', 'UUID', 'target_uuid', 'visibility', 'previous_conversation_uuid', 'next_conversation_uuid', 'author_id', 'author_name']) { + expect(org.conversation[0]).to.not.have.property(field) + } + }) + + it('retains global user list and write restrictions', async () => { + for (const path of ['/api/registry/users']) { + const response = await chai.request(app).get(path).set(headers('root', admin)) + expect(response).to.have.status(403) + } + const orgUpdate = await chai.request(app) + .put(`/api/registry/org/${orgs.cna.short_name}`).set(headers('root', admin)) + .send({ short_name: orgs.cna.short_name, long_name: 'Unauthorized', authority: ['CNA'], id_quota: 10 }) + expect(orgUpdate).to.have.status(403) + const userCreate = await chai.request(app) + .post(`/api/registry/org/${orgs.cna.short_name}/user`).set(headers('root', admin)) + .send({ username: `forbidden_${runId}@example.test`, status: 'active' }) + expect(userCreate).to.have.status(403) + const userDelete = await chai.request(app) + .delete(`/api/registry/org/${orgs.cna.short_name}/user/${users.cna.username}`).set(headers('root', admin)) + expect(userDelete).to.have.status(403) + }) + + it('preserves user-list pagination and query validation', async () => { + const path = `/api/registry/org/${orgs.cna.short_name}/users?page=2` + const response = await chai.request(app).get(path).set(headers('root', admin)) + const baseline = await chai.request(app).get(path).set(secretariat) + expect(response).to.have.status(200) + expect(baseline).to.have.status(200) + expect(response.body).to.deep.equal(baseline.body) + const invalid = await chai.request(app) + .get(`/api/registry/org/${orgs.cna.short_name}/users?page=0`).set(headers('root', admin)) + expect(invalid).to.have.status(400) + }) + }) + } + + it('keeps Secretariat and non-Root same-organization reads working', async () => { + await expectReads(secretariat, 'other', 200) + await expectReads(headers('cna'), 'cna', 200) + await expectReads(headers('cna'), 'branch', 403) + const hierarchy = await chai.request(app).get('/api/registry/org-hierarchy').set(headers('cna')) + expect(hierarchy).to.have.status(403) + const list = await chai.request(app).get('/api/registry/org').set(headers('cna')) + expect(list).to.have.status(403) + const fullList = await chai.request(app).get('/api/registry/org').set(secretariat) + expect(fullList).to.have.status(200) + expect(fullList.body.totalCount).to.be.greaterThan(1000) + }) + + it('does not return a user who is outside the specified target membership', async () => { + const response = await chai.request(app) + .get(`/api/registry/org/${orgs.cna.short_name}/user/${users.peerOnly.username}`).set(headers('root')) + expect(response).to.have.status(404) + expect(response.body.error).to.equal('USER_DNE') + }) + + it('uses current parent relationships after reassignment and removal', async () => { + try { + await relate('other', 'branch') + await expectReads(headers('root'), 'cna', 403) + await expectReads(headers('other'), 'cna', 200) + await expectOrgList(headers('root'), []) + await expectOrgList(headers('other'), ['branch', 'cna']) + await relate('other', 'branch', 'remove') + await expectReads(headers('other'), 'cna', 403) + await expectOrgList(headers('other'), []) + } finally { + await relate('root', 'branch') + } + await expectReads(headers('root'), 'cna', 200) + await expectOrgList(headers('root'), ['branch', 'cna']) + }) + + it('revokes oversight when the requesting organization loses ROOT authority', async () => { + try { + const response = await chai.request(app) + .put(`/api/registry/org/${orgs.root.short_name}`).set(secretariat).send({ + short_name: orgs.root.short_name, long_name: orgs.root.long_name, authority: ['CNA'], id_quota: 10 + }) + expect(response).to.have.status(200) + await expectReads(headers('root'), 'cna', 403) + const hierarchy = await chai.request(app).get('/api/registry/org-hierarchy').set(headers('root')) + expect(hierarchy).to.have.status(403) + const list = await chai.request(app).get('/api/registry/org').set(headers('root')) + expect(list).to.have.status(403) + } finally { + const response = await chai.request(app) + .put(`/api/registry/org/${orgs.root.short_name}`).set(secretariat).send({ + short_name: orgs.root.short_name, long_name: orgs.root.long_name, authority: ['ROOT'], is_top_level_root: false + }) + expect(response).to.have.status(200) + await relate('root', 'branch') + } + }) +}) diff --git a/test/unit-tests/middleware/registryReadAccessTest.js b/test/unit-tests/middleware/registryReadAccessTest.js new file mode 100644 index 000000000..ecd47a757 --- /dev/null +++ b/test/unit-tests/middleware/registryReadAccessTest.js @@ -0,0 +1,184 @@ +const { expect } = require('chai') +const sinon = require('sinon') +const middleware = require('../../../src/middleware/middleware') +const authContext = require('../../../src/utils/authContext') +const BaseOrgRepository = require('../../../src/repositories/baseOrgRepository') +const BaseOrgModel = require('../../../src/model/baseorg') +const { ORG_HIERARCHY, ALL_ORGS } = require('../../../src/controller/registry.controller/org.registry.controller') + +describe('Registry read authorization', () => { + let req, res, next, orgRepo, find + + beforeEach(() => { + const organizations = [ + { UUID: 'top', authority: ['ROOT'], oversees: ['root', 'sibling'] }, + { UUID: 'root', authority: ['ROOT'], oversees: ['branch'] }, + { UUID: 'branch', authority: ['ROOT'], oversees: ['child'] }, + { UUID: 'child', short_name: 'child', authority: ['CNA'] }, + { UUID: 'sibling', authority: ['ROOT'] }, + { UUID: 'unrelated', authority: ['ROOT'] } + ] + find = sinon.stub(BaseOrgModel, 'find').returns({ + select: sinon.stub().returns({ lean: sinon.stub().resolves(organizations) }) + }) + orgRepo = { + findOneByUUID: sinon.stub().callsFake(async UUID => organizations.find(org => org.UUID === UUID)), + findOneByShortName: sinon.stub().callsFake(async shortName => organizations.find(org => org.UUID === shortName)), + getAllOrgs: sinon.stub().resolves({ organizations: [] }), + getOrgHierarchy: BaseOrgRepository.prototype.getOrgHierarchy + } + req = { + ctx: { + authenticated: true, + authenticationChecked: true, + orgUUID: 'root', + org: 'untrusted-header', + params: { identifier: 'child' }, + query: {}, + repositories: { + getBaseOrgRepository: () => orgRepo, + getConversationRepository: () => ({ getAllByTargetUUID: sinon.stub().resolves([]) }) + } + } + } + res = { status: sinon.stub(), json: sinon.stub() } + res.status.returns(res) + next = sinon.spy() + }) + + afterEach(() => sinon.restore()) + + it('recognizes only descendants below the authenticated Root within a contextual hierarchy', async () => { + expect(await authContext.isRequesterParentOrg(req, orgRepo, { UUID: 'branch' })).to.equal(true) + expect(await authContext.isRequesterParentOrg(req, orgRepo, { UUID: 'child' })).to.equal(true) + for (const UUID of ['top', 'root', 'sibling', 'unrelated', 'missing']) { + expect(await authContext.isRequesterParentOrg(req, orgRepo, { UUID }), UUID).to.equal(false) + } + expect(find.calledOnce).to.equal(true) + expect(find.firstCall.args[2]).to.deep.equal({ readPreference: 'primary' }) + expect(orgRepo.findOneByShortName.called).to.equal(false) + }) + + it('supplies the resolved target and access decision and reuses the hierarchy data', async () => { + await middleware.authorizeRegistryOrgRead(req, res, next) + expect(next.calledOnceWithExactly()).to.equal(true) + expect(req.ctx.registryRead.reason).to.equal('PARENT_ORG') + expect(req.ctx.registryRead.targetOrg.UUID).to.equal('child') + expect(req.ctx.registryRead.isSecretariat).to.equal(false) + const hierarchy = await authContext.getRequestOrgHierarchy(req, orgRepo, 'child') + expect(hierarchy[0].UUID).to.equal('top') + expect(find.calledOnce).to.equal(true) + }) + + it('fails closed without an authenticated requester UUID even if the header names a Root', async () => { + req.ctx.orgUUID = null + req.ctx.org = 'root' + expect(await authContext.isRequesterParentOrg(req, orgRepo, { UUID: 'child' })).to.equal(false) + await middleware.authorizeRegistryHierarchyRead(req, res, next) + expect(res.status.calledOnceWith(403)).to.equal(true) + expect(next.called).to.equal(false) + expect(find.called).to.equal(false) + expect(orgRepo.findOneByShortName.called).to.equal(false) + expect(orgRepo.findOneByUUID.called).to.equal(false) + }) + + it('does not infer parent access from an unauthenticated UUID context', async () => { + req.ctx.authenticated = false + expect(await authContext.isRequesterParentOrg(req, orgRepo, { UUID: 'child' })).to.equal(false) + await middleware.authorizeRegistryOrgRead(req, res, next) + expect(res.status.calledOnceWith(403)).to.equal(true) + expect(next.called).to.equal(false) + expect(find.called).to.equal(false) + }) + + it('never calls the full hierarchy when a Root response scope is missing', async () => { + req.ctx.registryRead = { isSecretariat: false, reason: 'ROOT' } + await ORG_HIERARCHY(req, res, next) + expect(res.status.calledOnceWith(403)).to.equal(true) + expect(find.called).to.equal(false) + }) + + it('denies oversight when ROOT authority cannot be established', async () => { + orgRepo.findOneByUUID.withArgs('root').resolves({ UUID: 'root', authority: ['CNA'], oversees: ['child'] }) + expect(await authContext.isRequesterParentOrg(req, orgRepo, { UUID: 'child' })).to.equal(false) + expect(find.called).to.equal(false) + orgRepo.findOneByUUID.withArgs('root').resolves(null) + await middleware.authorizeRegistryHierarchyRead(req, res, next) + expect(res.status.calledOnceWith(403)).to.equal(true) + expect(next.called).to.equal(false) + }) + + it('forwards hierarchy lookup failures without authorizing the read', async () => { + orgRepo.getOrgHierarchy = sinon.stub().rejects(new Error('database unavailable')) + await middleware.authorizeRegistryOrgRead(req, res, next) + expect(next.calledOnce).to.equal(true) + expect(next.firstCall.args[0].message).to.equal('database unavailable') + expect(req.ctx.registryRead).to.equal(undefined) + }) + + it('does not reuse hierarchy data across requests after relationship removal', async () => { + expect(await authContext.isRequesterParentOrg(req, orgRepo, { UUID: 'child' })).to.equal(true) + find.returns({ + select: sinon.stub().returns({ + lean: sinon.stub().resolves([ + { UUID: 'root', authority: ['ROOT'], oversees: [] }, + { UUID: 'child', authority: ['CNA'] } + ]) + }) + }) + const newRequest = { ctx: { ...req.ctx } } + delete newRequest.ctx.orgHierarchyCache + expect(await authContext.isRequesterParentOrg(newRequest, orgRepo, { UUID: 'child' })).to.equal(false) + expect(find.calledTwice).to.equal(true) + }) + + it('fails closed when the authenticated Root is absent from the hierarchy', async () => { + find.returns({ select: sinon.stub().returns({ lean: sinon.stub().resolves([]) }) }) + expect(await authContext.isRequesterParentOrg(req, orgRepo, { UUID: 'child' })).to.equal(false) + }) + + it('passes only descendant UUIDs from the authenticated Root to the organization list query', async () => { + await middleware.authorizeRegistryHierarchyRead(req, res, next) + await ALL_ORGS(req, res, next) + expect(res.status.calledOnceWith(200)).to.equal(true) + expect(orgRepo.getAllOrgs.firstCall.args[2]).to.equal(false) + expect(orgRepo.getAllOrgs.firstCall.args[3]).to.have.members(['branch', 'child']) + expect(find.calledOnce).to.equal(true) + expect(orgRepo.findOneByShortName.called).to.equal(false) + }) + + it('keeps an empty Root list explicitly scoped to an empty UUID set', async () => { + req.ctx.orgUUID = 'sibling' + await middleware.authorizeRegistryHierarchyRead(req, res, next) + await ALL_ORGS(req, res, next) + expect(res.status.calledOnceWith(200)).to.equal(true) + expect(orgRepo.getAllOrgs.firstCall.args[3]).to.deep.equal([]) + }) + + it('never runs an organization list query when the Root scope is missing', async () => { + req.ctx.orgUUID = null + req.ctx.registryRead = { isSecretariat: false, reason: 'ROOT' } + await ALL_ORGS(req, res, next) + expect(res.status.calledOnceWith(403)).to.equal(true) + expect(orgRepo.getAllOrgs.called).to.equal(false) + expect(find.called).to.equal(false) + }) + + it('denies the organization list when the Root cannot be found in the hierarchy', async () => { + find.returns({ select: sinon.stub().returns({ lean: sinon.stub().resolves([]) }) }) + await middleware.authorizeRegistryHierarchyRead(req, res, next) + await ALL_ORGS(req, res, next) + expect(res.status.calledOnceWith(403)).to.equal(true) + expect(orgRepo.getAllOrgs.called).to.equal(false) + }) + + it('preserves the Secretariat organization list without a descendant filter', async () => { + orgRepo.findOneByUUID.withArgs('root').resolves({ UUID: 'root', authority: ['SECRETARIAT'] }) + await middleware.authorizeRegistryHierarchyRead(req, res, next) + await ALL_ORGS(req, res, next) + expect(res.status.calledOnceWith(200)).to.equal(true) + expect(orgRepo.getAllOrgs.firstCall.args[2]).to.equal(true) + expect(orgRepo.getAllOrgs.firstCall.args[3]).to.equal(undefined) + expect(find.called).to.equal(false) + }) +}) diff --git a/test/unit-tests/org/baseOrgRepositoryTest.js b/test/unit-tests/org/baseOrgRepositoryTest.js index 507a20988..df867cd43 100644 --- a/test/unit-tests/org/baseOrgRepositoryTest.js +++ b/test/unit-tests/org/baseOrgRepositoryTest.js @@ -9,6 +9,18 @@ describe('Testing BaseOrgRepository', () => { sinon.restore() }) + it('filters scoped organization UUIDs before pagination, including an empty scope', async () => { + const repo = new BaseOrgRepository() + const paginate = sinon.stub(repo, 'aggregatePaginate').resolves({ itemsList: [], itemCount: 0 }) + for (const scope of [['child-uuid'], []]) { + await repo.getAllOrgs({ limit: 100 }, false, false, scope) + expect(paginate.lastCall.args[0][0]).to.deep.equal({ $match: { UUID: { $in: scope } } }) + expect(paginate.lastCall.args[0].at(-1).$project.program_data).to.equal(false) + } + await repo.getAllOrgs({ limit: 100 }, false, true) + expect(paginate.lastCall.args[0][0]).to.deep.equal({ $match: {} }) + }) + it('Checks org existence without using $expr', async () => { const findOne = sinon.stub(BaseOrgModel, 'findOne').returns({ lean: sinon.stub().resolves(null) }) const repo = new BaseOrgRepository() diff --git a/test/unit-tests/org/orgHierarchyTest.js b/test/unit-tests/org/orgHierarchyTest.js index fa6740d1d..cd0a94a96 100644 --- a/test/unit-tests/org/orgHierarchyTest.js +++ b/test/unit-tests/org/orgHierarchyTest.js @@ -52,7 +52,7 @@ describe('Organization hierarchy repository', () => { const result = await new BaseOrgRepository().getOrgHierarchy() expect(result).to.deep.equal([]) - expect(find.calledOnceWithExactly({})).to.equal(true) + expect(find.calledOnceWithExactly({}, null, {})).to.equal(true) expect(select.calledOnceWithExactly({ _id: false, UUID: true, @@ -152,7 +152,7 @@ describe('Organization hierarchy repository', () => { }] }] }])) - expect(find.calledOnceWithExactly({})).to.equal(true) + expect(find.calledOnceWithExactly({}, null, {})).to.equal(true) expect(flattenHierarchy(result)).to.have.lengthOf(6) }) diff --git a/test/unit-tests/org/registry/registryOrgControllerTest.js b/test/unit-tests/org/registry/registryOrgControllerTest.js index 4ae01ea62..9c73a84e2 100644 --- a/test/unit-tests/org/registry/registryOrgControllerTest.js +++ b/test/unit-tests/org/registry/registryOrgControllerTest.js @@ -57,6 +57,7 @@ describe('Testing Registry Org Controller', () => { ctx: { authenticated: true, uuid: 'request-uuid', + registryRead: { targetOrg: requesterOrg, isSecretariat: false, reason: 'SAME_ORG' }, org: 'activity_6', orgUUID: requesterOrg.UUID, user: 'user@activity_6.com', diff --git a/test/unit-tests/org/registry/registryOrgGetSingleTest.js b/test/unit-tests/org/registry/registryOrgGetSingleTest.js index e28c3a06e..b0a188f82 100644 --- a/test/unit-tests/org/registry/registryOrgGetSingleTest.js +++ b/test/unit-tests/org/registry/registryOrgGetSingleTest.js @@ -114,6 +114,7 @@ describe('Testing the GET /registry/org/:identifier endpoint in Registry Org Con req = { ctx: { + registryRead: { targetOrg, isSecretariat: true, reason: 'SECRETARIAT' }, authenticated: true, org: requesterOrg.short_name, orgUUID: requesterOrg.UUID, @@ -142,7 +143,7 @@ describe('Testing the GET /registry/org/:identifier endpoint in Registry Org Con expect(next.called).to.be.false expect(status.calledOnceWithExactly(200)).to.be.true - expect(orgRepo.getOrgHierarchy.calledOnceWithExactly(targetOrg.UUID)).to.be.true + expect(orgRepo.getOrgHierarchy.calledOnceWithExactly(targetOrg.UUID, { readPreference: 'primary' }, req.ctx.orgHierarchyCache)).to.be.true expect(json.firstCall.args[0]._hierarchy).to.deep.equal([{ short_name: targetOrg.short_name, long_name: targetOrg.long_name, @@ -198,6 +199,7 @@ describe('Testing the GET /registry/org/:identifier endpoint in Registry Org Con orgRepo.findOneByShortName.withArgs(targetOrg.short_name).resolves(sameOrgRequester) orgRepo.findOneByUUID.withArgs(targetOrg.UUID).resolves(sameOrgRequester) orgRepo.isSecretariat.resolves(false) + req.ctx.registryRead = { targetOrg: sameOrgRequester, isSecretariat: false, reason: 'SAME_ORG' } userRepo.isAdmin.resolves(false) await SINGLE_ORG(req, res, next) @@ -215,7 +217,7 @@ describe('Testing the GET /registry/org/:identifier endpoint in Registry Org Con expect(userRepo.findUsersByUUIDs.called).to.be.false expect(orgRepo.findOrgsByUserUUIDs.called).to.be.false expect(orgRepo.getOrg.args[0][4]).to.equal(false) - expect(orgRepo.getOrgHierarchy.calledOnceWithExactly(targetOrg.UUID)).to.be.true + expect(orgRepo.getOrgHierarchy.calledOnceWithExactly(targetOrg.UUID, { readPreference: 'primary' }, req.ctx.orgHierarchyCache)).to.be.true expect(responseBody._hierarchy).to.have.lengthOf(1) expect(conversationRepo.getAllByTargetUUID.args[0][1]).to.equal(false) }) @@ -232,6 +234,7 @@ describe('Testing the GET /registry/org/:identifier endpoint in Registry Org Con orgRepo.findOneByShortName.withArgs(targetOrg.short_name).resolves(sameOrgRequester) orgRepo.findOneByUUID.withArgs(targetOrg.UUID).resolves(sameOrgRequester) orgRepo.isSecretariat.resolves(false) + req.ctx.registryRead = { targetOrg: sameOrgRequester, isSecretariat: false, reason: 'SAME_ORG' } userRepo.isAdmin.resolves(true) await SINGLE_ORG(req, res, next) @@ -265,6 +268,7 @@ describe('Testing the GET /registry/org/:identifier endpoint in Registry Org Con orgRepo.findOneByShortName.withArgs(targetOrg.short_name).resolves(sameOrgRequester) orgRepo.findOneByUUID.withArgs(targetOrg.UUID).resolves(sameOrgRequester) orgRepo.isSecretariat.resolves(false) + req.ctx.registryRead = { targetOrg: sameOrgRequester, isSecretariat: false, reason: 'SAME_ORG' } userRepo.isAdmin.resolves(true) await SINGLE_ORG(req, res, next) From a5446ab7ea46f026cf3989daf1ca03589d3758c1 Mon Sep 17 00:00:00 2001 From: David T Rocca Date: Tue, 3 Nov 2026 14:54:02 -0500 Subject: [PATCH 08/19] Root users should be able to pull user lists like orgs now --- api-docs/openapi.json | 6 +- src/controller/registry.controller/index.js | 12 +- .../user.registry.controller.js | 53 ++++--- src/repositories/baseOrgRepository.js | 4 +- src/repositories/baseUserRepository.js | 8 +- .../registry-org/populatedOrgHierarchyTest.js | 9 +- .../registry-org/rootReadAccessTest.js | 139 +++++++++++++++++- .../baseUserRepositoryFormatSemanticsTest.js | 35 +++++ .../user/registryUserControllerTest.js | 89 +++++++++++ 9 files changed, 314 insertions(+), 41 deletions(-) diff --git a/api-docs/openapi.json b/api-docs/openapi.json index c97475ecf..02c5d6392 100644 --- a/api-docs/openapi.json +++ b/api-docs/openapi.json @@ -5122,8 +5122,8 @@ "tags": [ "Data Registry — Users" ], - "summary": "Retrieves information about all registered users (accessible to Secretariat)", - "description": "

Related legacy endpoint: GET /users. Data Registry responses expose status and role; legacy responses expose active and authority.active_roles.

Access Control

User must belong to an organization with the Secretariat role

Expected Behavior

Secretariat: Retrieves information about all users for all organizations

", + "summary": "Lists registry users for Secretariat or overseeing Root users", + "description": "

Related legacy endpoint: GET /users. Data Registry responses expose status and role; legacy responses expose active and authority.active_roles.

Access Control

User must belong to an organization with SECRETARIAT or ROOT authority. Both ordinary Root users and Root administrators have access.

Expected Behavior

Secretariat: Retrieves information about all users for all organizations.

Root and top-level Root users: Retrieves users belonging to all direct and indirect descendant organizations, including subordinate Roots and organizations beneath them. Users in the requesting organization itself, ancestors, sibling branches, and unrelated organizations are excluded. A Root without descendant users receives an empty list.

Pagination and counts apply only to authorized users. Pagination metadata is included when the scoped user count reaches the page size. Authorization uses current ROOT authority and reporting relationships; user membership and administrator roles come from the descendant organizations. User secrets are excluded.

", "operationId": "registryUserAll", "parameters": [ { @@ -5141,7 +5141,7 @@ ], "responses": { "200": { - "description": "Returns all users, along with pagination fields if results span multiple pages of data.", + "description": "Returns registry users: all users for Secretariat, or descendant organization users for Roots. Pagination metadata is included when the authorized user count reaches the page size.", "content": { "application/json": { "schema": { diff --git a/src/controller/registry.controller/index.js b/src/controller/registry.controller/index.js index 058a47edd..99c077ad6 100644 --- a/src/controller/registry.controller/index.js +++ b/src/controller/registry.controller/index.js @@ -1689,13 +1689,15 @@ router.get('/registry/users', /* #swagger.tags = ['Data Registry — Users'] #swagger.operationId = 'registryUserAll' - #swagger.summary = "Retrieves information about all registered users (accessible to Secretariat)" + #swagger.summary = "Lists registry users for Secretariat or overseeing Root users" #swagger.description = "

Related legacy endpoint: GET /users. Data Registry responses expose status and role; legacy responses expose active and authority.active_roles.

Access Control

-

User must belong to an organization with the Secretariat role

+

User must belong to an organization with SECRETARIAT or ROOT authority. Both ordinary Root users and Root administrators have access.

Expected Behavior

-

Secretariat: Retrieves information about all users for all organizations

" +

Secretariat: Retrieves information about all users for all organizations.

+

Root and top-level Root users: Retrieves users belonging to all direct and indirect descendant organizations, including subordinate Roots and organizations beneath them. Users in the requesting organization itself, ancestors, sibling branches, and unrelated organizations are excluded. A Root without descendant users receives an empty list.

+

Pagination and counts apply only to authorized users. Pagination metadata is included when the scoped user count reaches the page size. Authorization uses current ROOT authority and reporting relationships; user membership and administrator roles come from the descendant organizations. User secrets are excluded.

" #swagger.parameters['$ref'] = [ '#/components/parameters/pageQuery', '#/components/parameters/apiEntityHeader', @@ -1703,7 +1705,7 @@ router.get('/registry/users', '#/components/parameters/apiSecretHeader' ] #swagger.responses[200] = { - description: 'Returns all users, along with pagination fields if results span multiple pages of data.', + description: 'Returns registry users: all users for Secretariat, or descendant organization users for Roots. Pagination metadata is included when the authorized user count reaches the page size.', content:{ "application/json":{ schema: { @@ -1755,7 +1757,7 @@ router.get('/registry/users', */ mw.useRegistry(), mw.validateUser, - mw.onlySecretariat, + mw.authorizeRegistryHierarchyRead, query().custom((query) => { return mw.validateQueryParameterNames(query, ['page']) }), query(['page']).optional().isInt({ min: CONSTANTS.PAGINATOR_PAGE }), query(['page']).custom((val) => { return mw.containsNoInvalidCharacters(val) }), diff --git a/src/controller/registry.controller/user.registry.controller.js b/src/controller/registry.controller/user.registry.controller.js index 259636a69..b1b0e4345 100644 --- a/src/controller/registry.controller/user.registry.controller.js +++ b/src/controller/registry.controller/user.registry.controller.js @@ -26,11 +26,28 @@ function removeImmutableUpdateFields (body) { * @param {object} res - The Express response object. * @param {function} next - The next middleware function. * @returns {Promise} - A promise that resolves when the response is sent. Registry-format responses include 'role' for admins. - * @description This endpoint is accessible to Secretariat only. It retrieves a list of all registry users. + * @description Secretariat receives all registry users; Root users receive users in descendant organizations. * Called by GET /api/registry/users */ async function getAllUsers (req, res, next) { try { + const access = req.ctx.registryRead + if (!access || (!access.isSecretariat && !access.hierarchyScope)) { + return res.status(403).json(error.notSameOrgOrSecretariat()) + } + const orgRepo = req.ctx.repositories.getBaseOrgRepository() + const { isSecretariat, hierarchyScope } = access + let userUUIDs + const adminUUIDs = new Set() + if (!isSecretariat) { + const orgUUIDs = await authContext.getRequestOrgDescendantUUIDs(req, orgRepo, hierarchyScope) + if (!Array.isArray(orgUUIDs)) { + return res.status(403).json(error.notSameOrgOrSecretariat()) + } + const orgs = await orgRepo.findOrgsByUUIDs(orgUUIDs, { readPreference: 'primary' }) + userUUIDs = [...new Set(orgs.flatMap(org => org.users || []))] + orgs.forEach(org => (org.admins || []).forEach(UUID => adminUUIDs.add(UUID))) + } const CONSTANTS = getConstants() const repo = req.ctx.repositories.getBaseUserRepository() @@ -44,33 +61,25 @@ async function getAllUsers (req, res, next) { options.sort = { short_name: 'asc' } options.page = req.ctx.query.page ? parseInt(req.ctx.query.page) : CONSTANTS.PAGINATOR_PAGE // if 'page' query parameter is not defined, set 'page' to the default page value - const returnValue = await repo.getAllUsers(options) - // Hydrate roles - const orgRepo = req.ctx.repositories.getBaseOrgRepository() - const distinctOrgUUIDs = [...new Set(returnValue.users.map(u => u.org_UUID))] - - // Fetch all relevant orgs in one go (or in parallel) if possible, but map is easy for now - // Since we don't have a "getManyOrgsByUUID", we might need to do it one by one or improve repository - // For now, let's iterate and fetch. It's not optimal but safe given repo limitations. - // Optimization: We can build a map of orgUUID -> orgObject - const orgMap = {} - for (const uuid of distinctOrgUUIDs) { - // We need the org content to get admins - const org = await orgRepo.findOneByUUID(uuid, {}, REGISTRY_FORMAT) - if (org) { - orgMap[uuid] = org + const returnValue = await repo.getAllUsers(options, userUUIDs) + if (isSecretariat) { + // Preserve the existing Secretariat role mapping. + const distinctOrgUUIDs = [...new Set(returnValue.users.map(u => u.org_UUID))] + const orgMap = {} + for (const uuid of distinctOrgUUIDs) { + const org = await orgRepo.findOneByUUID(uuid, {}, REGISTRY_FORMAT) + if (org) orgMap[uuid] = org } + returnValue.users.forEach(user => { + if (orgMap[user.org_UUID]?.admins?.includes(user.UUID)) adminUUIDs.add(user.UUID) + }) } returnValue.users.forEach(user => { - const org = orgMap[user.org_UUID] - if (org && org.admins && org.admins.includes(user.UUID)) { - user.role = 'ADMIN' - } - // If not admin, leave as is (undefined or empty or whatever it was) + if (adminUUIDs.has(user.UUID)) user.role = 'ADMIN' }) - logger.info({ uuid: req.ctx.uuid, message: 'The user information was sent to the secretariat user.' }) + logger.info({ uuid: req.ctx.uuid, message: 'The authorized registry user information was sent to the user.' }) return res.status(200).json(returnValue) } catch (err) { next(err) diff --git a/src/repositories/baseOrgRepository.js b/src/repositories/baseOrgRepository.js index 56f1e4e5b..81a28110e 100644 --- a/src/repositories/baseOrgRepository.js +++ b/src/repositories/baseOrgRepository.js @@ -525,7 +525,7 @@ class BaseOrgRepository extends BaseRepository { /** * Finds organizations by UUID with the fields needed to associate users - * and organization short names in read response mappings. + * and organization short names and administrator roles in read response mappings. * * @param {string[]} orgUUIDs - Organization UUIDs to retrieve. * @param {object} [options={}] - Optional settings for the repository query. @@ -538,7 +538,7 @@ class BaseOrgRepository extends BaseRepository { return await BaseOrgModel.find( { UUID: { $in: orgUUIDs } }, - { _id: 0, UUID: 1, short_name: 1, users: 1 }, + { _id: 0, UUID: 1, short_name: 1, users: 1, admins: 1 }, options ) } diff --git a/src/repositories/baseUserRepository.js b/src/repositories/baseUserRepository.js index f6a67d8c2..21dc56f46 100644 --- a/src/repositories/baseUserRepository.js +++ b/src/repositories/baseUserRepository.js @@ -392,12 +392,14 @@ class BaseUserRepository extends BaseRepository { /** * @async * @function getAllUsers - * @description Retrieves all users with pagination. + * @description Retrieves users with pagination, optionally scoped to authorized UUIDs. * @param {object} [options={}] - Pagination and query options. + * @param {string[]} [userUUIDs] - Authorized user UUIDs; an empty array matches nothing. * @returns {Promise} Paginated result containing users and metadata. */ - async getAllUsers (options = {}) { - const agt = setAggregateRegistryUserObj({}) + async getAllUsers (options = {}, userUUIDs) { + const query = userUUIDs === undefined ? {} : { UUID: { $in: userUUIDs } } + const agt = setAggregateRegistryUserObj(query) const pg = await this.aggregatePaginate(agt, options) const data = { users: pg.itemsList } if (pg.itemCount >= options.limit) { diff --git a/test/integration-tests/registry-org/populatedOrgHierarchyTest.js b/test/integration-tests/registry-org/populatedOrgHierarchyTest.js index 753d46c9c..8c8d5a152 100644 --- a/test/integration-tests/registry-org/populatedOrgHierarchyTest.js +++ b/test/integration-tests/registry-org/populatedOrgHierarchyTest.js @@ -299,12 +299,19 @@ describe('Populated registry organization hierarchy', () => { const deniedOrgs = shortName === 'root_1_4' ? ['top_root_1', 'root_1_3', 'top_root_2'] : ['top_root_2'] + const excludedUsers = [...(await getOrg(shortName)).users] for (const target of deniedOrgs) { const response = await chai.request(app).get(`/api/registry/org/${target}`).set(headers) expect(response).to.have.status(403) + excludedUsers.push(...(await getOrg(target)).users) } const allUsers = await chai.request(app).get('/api/registry/users').set(headers) - expect(allUsers).to.have.status(403) + expect(allUsers).to.have.status(200) + expect(allUsers.body.users).to.be.an('array').that.is.not.empty + allUsers.body.users.forEach(user => { + expect(excludedUsers).to.not.include(user.UUID) + expect(user).to.not.have.property('secret') + }) }) } } diff --git a/test/integration-tests/registry-org/rootReadAccessTest.js b/test/integration-tests/registry-org/rootReadAccessTest.js index 6da5c527b..d4e8ef895 100644 --- a/test/integration-tests/registry-org/rootReadAccessTest.js +++ b/test/integration-tests/registry-org/rootReadAccessTest.js @@ -6,6 +6,10 @@ const { v4: uuidv4 } = require('uuid') const constants = require('../constants') const app = require('../../../src/index') const Conversation = require('../../../src/model/conversation') +const express = require('express') +const { withHttpServer } = require('../../httpServer') +const middleware = require('../../../src/middleware/middleware') +const registryRouter = require('../../../src/controller/registry.controller') const secretariat = constants.headers const runId = uuidv4().slice(0, 8) @@ -59,6 +63,22 @@ describe('Root oversight registry read access', () => { return response.body } + async function expectUserList (requestHeaders, labels, extraUsers = []) { + const response = await chai.request(app).get('/api/registry/users').set(requestHeaders) + expect(response).to.have.status(200) + const expectedUsers = [...labels.flatMap(label => [users[label], users[`${label}Admin`]]), ...extraUsers] + if (labels.includes('peer')) expectedUsers.push(users.peerOnly) + expect(response.body.users.map(user => user.UUID)).to.have.members(expectedUsers.map(user => user.UUID)) + expect(response.body).to.have.all.keys('users') + const admins = new Set(labels.map(label => users[`${label}Admin`].UUID)) + response.body.users.forEach(user => { + for (const field of ['secret', '_id', '__v']) expect(user).to.not.have.property(field) + if (admins.has(user.UUID)) expect(user.role).to.equal('ADMIN') + else expect(user).to.not.have.property('role') + }) + return response.body + } + before(async () => { for (const label of ['top', 'root', 'branch', 'cna', 'peer', 'other']) { const isRoot = label !== 'cna' @@ -173,9 +193,15 @@ describe('Root oversight registry read access', () => { await expectOrgList(headers('top', admin), ['root', 'branch', 'cna', 'peer']) }) + it('lists only descendant users for Roots and top-level Roots, including distinct users with shared usernames', async () => { + await expectUserList(headers('root', admin), ['branch', 'cna']) + await expectUserList(headers('top', admin), ['root', 'branch', 'cna', 'peer']) + }) + it('returns an empty list for a Root without descendants', async () => { const response = await expectOrgList(headers('peer', admin), []) expect(response.nextPage).to.equal(null) + await expectUserList(headers('peer', admin), []) }) it('applies non-Secretariat conversation filtering to list entries', async () => { @@ -188,11 +214,14 @@ describe('Root oversight registry read access', () => { } }) - it('retains global user list and write restrictions', async () => { - for (const path of ['/api/registry/users']) { - const response = await chai.request(app).get(path).set(headers('root', admin)) - expect(response).to.have.status(403) - } + it('retains legacy global user list and write restrictions', async () => { + const legacyList = await chai.request(app).get('/api/users').set(headers('root', admin)) + expect(legacyList).to.have.status(403) + const widenScope = await chai.request(app) + .post(`/api/registry/org/${orgs.root.short_name}/oversees/${orgs.peer.short_name}/add`) + .set(headers('root', admin)) + expect(widenScope).to.have.status(403) + await expectUserList(headers('root', admin), ['branch', 'cna']) const orgUpdate = await chai.request(app) .put(`/api/registry/org/${orgs.cna.short_name}`).set(headers('root', admin)) .send({ short_name: orgs.cna.short_name, long_name: 'Unauthorized', authority: ['CNA'], id_quota: 10 }) @@ -220,6 +249,96 @@ describe('Root oversight registry read access', () => { }) } + it('paginates and counts only authorized users across the descendant organizations', async () => { + const paginatedApp = express() + paginatedApp.set('query parser', 'extended') + paginatedApp.use(middleware.createCtxAndReqUUID) + paginatedApp.use((req, res, next) => { + req.TEST_PAGINATOR_LIMIT = 3 + next() + }) + paginatedApp.use('/api', registryRouter) + paginatedApp.use(middleware.errorHandler) + + await withHttpServer(paginatedApp, async url => { + const returnedUUIDs = [] + for (const page of [1, 2, 3]) { + const response = await chai.request(url).get(`/api/registry/users?page=${page}`).set(headers('root')) + expect(response).to.have.status(200) + expect(response.body.totalCount).to.equal(4) + expect(response.body.itemsPerPage).to.equal(3) + expect(response.body.pageCount).to.equal(2) + expect(response.body.currentPage).to.equal(page) + expect(response.body.prevPage).to.equal(page === 1 ? null : page - 1) + expect(response.body.nextPage).to.equal(page === 1 ? 2 : null) + expect(response.body.users).to.have.lengthOf(page === 1 ? 3 : page === 2 ? 1 : 0) + returnedUUIDs.push(...response.body.users.map(user => user.UUID)) + } + expect(returnedUUIDs).to.have.members([users.branch.UUID, users.branchAdmin.UUID, users.cna.UUID, users.cnaAdmin.UUID]) + const global = await chai.request(url).get('/api/registry/users').set(secretariat) + expect(global).to.have.status(200) + expect(global.body.totalCount).to.be.greaterThan(4) + }) + }) + + it('validates Root user-list queries and still requires authentication', async () => { + for (const query of ['?page=0', '?page=bad', '?unknown=value', '?page[$ne]=0', + `?org_UUID=${orgs.other.UUID}`, '?registryRead[isSecretariat]=true']) { + const response = await chai.request(app).get(`/api/registry/users${query}`).set(headers('root')) + expect(response).to.have.status(400) + const baseline = await chai.request(app).get(`/api/registry/users${query}`).set(secretariat) + expect(response.body).to.deep.equal(baseline.body) + } + const anonymous = await chai.request(app).get('/api/registry/users') + expect(anonymous).to.have.status(400) + const invalidKey = await chai.request(app).get('/api/registry/users') + .set({ ...headers('root'), 'CVE-API-KEY': 'invalid-key' }) + expect(invalidKey).to.have.status(401) + }) + + it('cannot widen the user scope through a forged request body or organization header', async () => { + const response = await chai.request(app).get('/api/registry/users').set(headers('root')).send({ + isSecretariat: true, + hierarchyScope: orgs.top.UUID, + orgUUID: orgs.other.UUID, + ctx: { registryRead: { isSecretariat: true }, orgUUID: orgs.top.UUID } + }) + expect(response).to.have.status(200) + expect(response.body.users.map(user => user.UUID)).to.have.members([ + users.branch.UUID, users.branchAdmin.UUID, users.cna.UUID, users.cnaAdmin.UUID + ]) + for (const org of [orgs.top.short_name, 'mitre']) { + const spoofed = await chai.request(app).get('/api/registry/users') + .set({ ...headers('root'), 'CVE-API-ORG': org }) + expect(spoofed).to.have.status(401) + expect(spoofed.body).to.not.have.property('users') + } + }) + + it('stops exposing a user as soon as their membership moves outside the Root tree', async () => { + let currentOrg = 'peer' + const move = async target => { + const response = await chai.request(app) + .put(`/api/registry/org/${orgs[currentOrg].short_name}/user/${users.peerOnly.username}`) + .set(secretariat).send({ + username: users.peerOnly.username, + status: 'active', + org_short_name: orgs[target].short_name + }) + expect(response).to.have.status(200) + currentOrg = target + } + try { + await expectUserList(headers('root'), ['branch', 'cna']) + await move('cna') + await expectUserList(headers('root'), ['branch', 'cna'], [users.peerOnly]) + await move('peer') + await expectUserList(headers('root'), ['branch', 'cna']) + } finally { + if (currentOrg !== 'peer') await move('peer') + } + }) + it('keeps Secretariat and non-Root same-organization reads working', async () => { await expectReads(secretariat, 'other', 200) await expectReads(headers('cna'), 'cna', 200) @@ -228,6 +347,10 @@ describe('Root oversight registry read access', () => { expect(hierarchy).to.have.status(403) const list = await chai.request(app).get('/api/registry/org').set(headers('cna')) expect(list).to.have.status(403) + for (const admin of [false, true]) { + const userList = await chai.request(app).get('/api/registry/users').set(headers('cna', admin)) + expect(userList).to.have.status(403) + } const fullList = await chai.request(app).get('/api/registry/org').set(secretariat) expect(fullList).to.have.status(200) expect(fullList.body.totalCount).to.be.greaterThan(1000) @@ -247,14 +370,18 @@ describe('Root oversight registry read access', () => { await expectReads(headers('other'), 'cna', 200) await expectOrgList(headers('root'), []) await expectOrgList(headers('other'), ['branch', 'cna']) + await expectUserList(headers('root'), []) + await expectUserList(headers('other'), ['branch', 'cna']) await relate('other', 'branch', 'remove') await expectReads(headers('other'), 'cna', 403) await expectOrgList(headers('other'), []) + await expectUserList(headers('other'), []) } finally { await relate('root', 'branch') } await expectReads(headers('root'), 'cna', 200) await expectOrgList(headers('root'), ['branch', 'cna']) + await expectUserList(headers('root'), ['branch', 'cna']) }) it('revokes oversight when the requesting organization loses ROOT authority', async () => { @@ -269,6 +396,8 @@ describe('Root oversight registry read access', () => { expect(hierarchy).to.have.status(403) const list = await chai.request(app).get('/api/registry/org').set(headers('root')) expect(list).to.have.status(403) + const userList = await chai.request(app).get('/api/registry/users').set(headers('root')) + expect(userList).to.have.status(403) } finally { const response = await chai.request(app) .put(`/api/registry/org/${orgs.root.short_name}`).set(secretariat).send({ diff --git a/test/unit-tests/user/baseUserRepositoryFormatSemanticsTest.js b/test/unit-tests/user/baseUserRepositoryFormatSemanticsTest.js index 9a02cd9fc..aea507e54 100644 --- a/test/unit-tests/user/baseUserRepositoryFormatSemanticsTest.js +++ b/test/unit-tests/user/baseUserRepositoryFormatSemanticsTest.js @@ -29,6 +29,7 @@ describe('Testing BaseUserRepository format flag semantics', () => { expect(result).to.deep.equal({ users: [{ UUID: 'user-uuid' }] }) expect(registryAggregate.calledOnce).to.be.true + expect(registryAggregate.firstCall.args[0][0]).to.deep.equal({ $match: {} }) expect(registryAggregate.firstCall.args[0][1].$project).to.deep.equal({ _id: false, __v: false, @@ -36,6 +37,40 @@ describe('Testing BaseUserRepository format flag semantics', () => { }) }) + it('applies authorized user UUIDs before pagination and preserves scoped metadata', async () => { + registryAggregate = sinon.stub(repo, 'aggregatePaginate').resolves({ + itemsList: [{ UUID: 'child-user' }], + itemCount: 3, + itemsPerPage: 2, + pageCount: 2, + currentPage: 2, + prevPage: 1, + nextPage: null + }) + const options = { limit: 2, page: 2 } + const result = await repo.getAllUsers(options, ['branch-user', 'branch-admin', 'child-user']) + expect(registryAggregate.firstCall.args[0][0]).to.deep.equal({ + $match: { UUID: { $in: ['branch-user', 'branch-admin', 'child-user'] } } + }) + expect(registryAggregate.firstCall.args[1]).to.equal(options) + expect(result).to.deep.equal({ + users: [{ UUID: 'child-user' }], + totalCount: 3, + itemsPerPage: 2, + pageCount: 2, + currentPage: 2, + prevPage: 1, + nextPage: null + }) + }) + + it('matches no users for an explicitly empty authorization scope', async () => { + registryAggregate = sinon.stub(repo, 'aggregatePaginate').resolves({ itemsList: [], itemCount: 0 }) + const result = await repo.getAllUsers({ limit: 100 }, []) + expect(registryAggregate.firstCall.args[0][0]).to.deep.equal({ $match: { UUID: { $in: [] } } }) + expect(result).to.deep.equal({ users: [] }) + }) + it('Should source legacy global user lists from BaseUser', async () => { registryAggregate = sinon.stub(repo, 'aggregatePaginate').resolves({ itemsList: [{ diff --git a/test/unit-tests/user/registryUserControllerTest.js b/test/unit-tests/user/registryUserControllerTest.js index e8ecdee79..bb07fe4a1 100644 --- a/test/unit-tests/user/registryUserControllerTest.js +++ b/test/unit-tests/user/registryUserControllerTest.js @@ -3,6 +3,7 @@ const sinon = require('sinon') const mongoose = require('mongoose') const controller = require('../../../src/controller/registry.controller/user.registry.controller') +const authContext = require('../../../src/utils/authContext') function mockResponse () { const res = {} @@ -42,6 +43,7 @@ describe('Testing Registry User Controller', () => { const req = { ctx: { uuid: 'request-uuid', + registryRead: { isSecretariat: true }, query: {}, repositories: { getBaseUserRepository: () => userRepo, @@ -56,6 +58,93 @@ describe('Testing Registry User Controller', () => { const payload = res.json.firstCall.args[0] expect(payload.users[0]).to.have.property('role', 'ADMIN') expect(payload.users[1]).to.not.have.property('role') + expect(userRepo.getAllUsers.firstCall.args[1]).to.equal(undefined) + }) + + context('Root scope', () => { + let req, res, next, userRepo, orgRepo, descendants + + beforeEach(() => { + userRepo = { getAllUsers: sinon.stub().resolves({ users: [] }) } + orgRepo = { findOrgsByUUIDs: sinon.stub().resolves([]) } + descendants = sinon.stub(authContext, 'getRequestOrgDescendantUUIDs').resolves(['branch', 'child']) + req = { + ctx: { + registryRead: { isSecretariat: false, hierarchyScope: 'root' }, + query: {}, + repositories: { + getBaseUserRepository: () => userRepo, + getBaseOrgRepository: () => orgRepo + } + } + } + res = mockResponse() + next = sinon.spy() + }) + + it('filters by descendant memberships and derives roles without user org_UUID fields', async () => { + orgRepo.findOrgsByUUIDs.resolves([ + { UUID: 'branch', users: ['admin', 'regular'], admins: ['admin'] }, + { UUID: 'child', users: ['child-user', 'regular'], admins: [] } + ]) + userRepo.getAllUsers.resolves({ users: [{ UUID: 'admin' }, { UUID: 'regular' }, { UUID: 'child-user' }] }) + + await controller.ALL_USERS(req, res, next) + + expect(descendants.calledOnceWithExactly(req, orgRepo, 'root')).to.equal(true) + expect(orgRepo.findOrgsByUUIDs.calledOnceWithExactly(['branch', 'child'], { readPreference: 'primary' })).to.equal(true) + expect(userRepo.getAllUsers.firstCall.args[1]).to.deep.equal(['admin', 'regular', 'child-user']) + expect(res.status.calledOnceWith(200)).to.equal(true) + expect(res.json.firstCall.args[0].users).to.deep.equal([ + { UUID: 'admin', role: 'ADMIN' }, { UUID: 'regular' }, { UUID: 'child-user' } + ]) + expect(next.called).to.equal(false) + }) + + it('keeps a Root without descendants explicitly scoped to no users', async () => { + descendants.resolves([]) + await controller.ALL_USERS(req, res, next) + expect(orgRepo.findOrgsByUUIDs.firstCall.args[0]).to.deep.equal([]) + expect(userRepo.getAllUsers.firstCall.args[1]).to.deep.equal([]) + expect(res.json.firstCall.args[0]).to.deep.equal({ users: [] }) + }) + + it('keeps descendants without memberships explicitly scoped to no users', async () => { + orgRepo.findOrgsByUUIDs.resolves([{ UUID: 'branch', users: [] }, { UUID: 'child' }]) + await controller.ALL_USERS(req, res, next) + expect(userRepo.getAllUsers.firstCall.args[1]).to.deep.equal([]) + expect(res.json.firstCall.args[0]).to.deep.equal({ users: [] }) + }) + + for (const access of [undefined, { isSecretariat: false }]) { + it(`denies a request with ${access ? 'no hierarchy scope' : 'no authorization decision'}`, async () => { + req.ctx.registryRead = access + await controller.ALL_USERS(req, res, next) + expect(res.status.calledOnceWith(403)).to.equal(true) + expect(descendants.called).to.equal(false) + expect(userRepo.getAllUsers.called).to.equal(false) + }) + } + + it('denies a Root absent from the current hierarchy without querying users', async () => { + descendants.resolves(null) + await controller.ALL_USERS(req, res, next) + expect(res.status.calledOnceWith(403)).to.equal(true) + expect(orgRepo.findOrgsByUUIDs.called).to.equal(false) + expect(userRepo.getAllUsers.called).to.equal(false) + }) + + for (const lookup of ['hierarchy', 'membership']) { + it(`forwards ${lookup} lookup failures without querying users`, async () => { + const failure = new Error('database unavailable') + const failingLookup = lookup === 'hierarchy' ? descendants : orgRepo.findOrgsByUUIDs + failingLookup.rejects(failure) + await controller.ALL_USERS(req, res, next) + expect(next.calledOnceWithExactly(failure)).to.equal(true) + expect(userRepo.getAllUsers.called).to.equal(false) + expect(res.json.called).to.equal(false) + }) + } }) }) From fd37cfe494889f62e73f76f997ec4824a5cb7a4f Mon Sep 17 00:00:00 2001 From: David T Rocca Date: Tue, 3 Nov 2026 15:28:40 -0500 Subject: [PATCH 09/19] Also return their org --- api-docs/openapi.json | 4 +- src/controller/registry.controller/index.js | 6 +-- .../user.registry.controller.js | 8 ++-- .../registry-org/populatedOrgHierarchyTest.js | 2 +- .../registry-org/rootReadAccessTest.js | 42 +++++++++---------- .../user/registryUserControllerTest.js | 28 ++++++++----- 6 files changed, 49 insertions(+), 41 deletions(-) diff --git a/api-docs/openapi.json b/api-docs/openapi.json index 02c5d6392..66c3e36d4 100644 --- a/api-docs/openapi.json +++ b/api-docs/openapi.json @@ -5123,7 +5123,7 @@ "Data Registry — Users" ], "summary": "Lists registry users for Secretariat or overseeing Root users", - "description": "

Related legacy endpoint: GET /users. Data Registry responses expose status and role; legacy responses expose active and authority.active_roles.

Access Control

User must belong to an organization with SECRETARIAT or ROOT authority. Both ordinary Root users and Root administrators have access.

Expected Behavior

Secretariat: Retrieves information about all users for all organizations.

Root and top-level Root users: Retrieves users belonging to all direct and indirect descendant organizations, including subordinate Roots and organizations beneath them. Users in the requesting organization itself, ancestors, sibling branches, and unrelated organizations are excluded. A Root without descendant users receives an empty list.

Pagination and counts apply only to authorized users. Pagination metadata is included when the scoped user count reaches the page size. Authorization uses current ROOT authority and reporting relationships; user membership and administrator roles come from the descendant organizations. User secrets are excluded.

", + "description": "

Related legacy endpoint: GET /users. Data Registry responses expose status and role; legacy responses expose active and authority.active_roles.

Access Control

User must belong to an organization with SECRETARIAT or ROOT authority. Both ordinary Root users and Root administrators have access.

Expected Behavior

Secretariat: Retrieves information about all users for all organizations.

Root and top-level Root users: Retrieves users belonging to the requesting organization itself and all direct and indirect descendant organizations, including subordinate Roots and organizations beneath them. Users in ancestors, sibling branches, and unrelated organizations are excluded. A Root without descendants receives its own organization's users.

Pagination and counts apply only to authorized users. Pagination metadata is included when the scoped user count reaches the page size. Authorization uses current ROOT authority and reporting relationships; user membership and administrator roles come from the requesting organization and its descendants. User secrets are excluded.

", "operationId": "registryUserAll", "parameters": [ { @@ -5141,7 +5141,7 @@ ], "responses": { "200": { - "description": "Returns registry users: all users for Secretariat, or descendant organization users for Roots. Pagination metadata is included when the authorized user count reaches the page size.", + "description": "Returns registry users: all users for Secretariat, or users in the requesting organization and its descendants for Roots. Pagination metadata is included when the authorized user count reaches the page size.", "content": { "application/json": { "schema": { diff --git a/src/controller/registry.controller/index.js b/src/controller/registry.controller/index.js index 99c077ad6..56049d429 100644 --- a/src/controller/registry.controller/index.js +++ b/src/controller/registry.controller/index.js @@ -1696,8 +1696,8 @@ router.get('/registry/users',

User must belong to an organization with SECRETARIAT or ROOT authority. Both ordinary Root users and Root administrators have access.

Expected Behavior

Secretariat: Retrieves information about all users for all organizations.

-

Root and top-level Root users: Retrieves users belonging to all direct and indirect descendant organizations, including subordinate Roots and organizations beneath them. Users in the requesting organization itself, ancestors, sibling branches, and unrelated organizations are excluded. A Root without descendant users receives an empty list.

-

Pagination and counts apply only to authorized users. Pagination metadata is included when the scoped user count reaches the page size. Authorization uses current ROOT authority and reporting relationships; user membership and administrator roles come from the descendant organizations. User secrets are excluded.

" +

Root and top-level Root users: Retrieves users belonging to the requesting organization itself and all direct and indirect descendant organizations, including subordinate Roots and organizations beneath them. Users in ancestors, sibling branches, and unrelated organizations are excluded. A Root without descendants receives its own organization's users.

+

Pagination and counts apply only to authorized users. Pagination metadata is included when the scoped user count reaches the page size. Authorization uses current ROOT authority and reporting relationships; user membership and administrator roles come from the requesting organization and its descendants. User secrets are excluded.

" #swagger.parameters['$ref'] = [ '#/components/parameters/pageQuery', '#/components/parameters/apiEntityHeader', @@ -1705,7 +1705,7 @@ router.get('/registry/users', '#/components/parameters/apiSecretHeader' ] #swagger.responses[200] = { - description: 'Returns registry users: all users for Secretariat, or descendant organization users for Roots. Pagination metadata is included when the authorized user count reaches the page size.', + description: 'Returns registry users: all users for Secretariat, or users in the requesting organization and its descendants for Roots. Pagination metadata is included when the authorized user count reaches the page size.', content:{ "application/json":{ schema: { diff --git a/src/controller/registry.controller/user.registry.controller.js b/src/controller/registry.controller/user.registry.controller.js index b1b0e4345..3451b86a1 100644 --- a/src/controller/registry.controller/user.registry.controller.js +++ b/src/controller/registry.controller/user.registry.controller.js @@ -26,7 +26,7 @@ function removeImmutableUpdateFields (body) { * @param {object} res - The Express response object. * @param {function} next - The next middleware function. * @returns {Promise} - A promise that resolves when the response is sent. Registry-format responses include 'role' for admins. - * @description Secretariat receives all registry users; Root users receive users in descendant organizations. + * @description Secretariat receives all registry users; Root users receive users in their own and descendant organizations. * Called by GET /api/registry/users */ async function getAllUsers (req, res, next) { @@ -40,11 +40,11 @@ async function getAllUsers (req, res, next) { let userUUIDs const adminUUIDs = new Set() if (!isSecretariat) { - const orgUUIDs = await authContext.getRequestOrgDescendantUUIDs(req, orgRepo, hierarchyScope) - if (!Array.isArray(orgUUIDs)) { + const descendantOrgUUIDs = await authContext.getRequestOrgDescendantUUIDs(req, orgRepo, hierarchyScope) + if (!Array.isArray(descendantOrgUUIDs)) { return res.status(403).json(error.notSameOrgOrSecretariat()) } - const orgs = await orgRepo.findOrgsByUUIDs(orgUUIDs, { readPreference: 'primary' }) + const orgs = await orgRepo.findOrgsByUUIDs([hierarchyScope, ...descendantOrgUUIDs], { readPreference: 'primary' }) userUUIDs = [...new Set(orgs.flatMap(org => org.users || []))] orgs.forEach(org => (org.admins || []).forEach(UUID => adminUUIDs.add(UUID))) } diff --git a/test/integration-tests/registry-org/populatedOrgHierarchyTest.js b/test/integration-tests/registry-org/populatedOrgHierarchyTest.js index 8c8d5a152..a59ce5ab1 100644 --- a/test/integration-tests/registry-org/populatedOrgHierarchyTest.js +++ b/test/integration-tests/registry-org/populatedOrgHierarchyTest.js @@ -299,7 +299,7 @@ describe('Populated registry organization hierarchy', () => { const deniedOrgs = shortName === 'root_1_4' ? ['top_root_1', 'root_1_3', 'top_root_2'] : ['top_root_2'] - const excludedUsers = [...(await getOrg(shortName)).users] + const excludedUsers = [] for (const target of deniedOrgs) { const response = await chai.request(app).get(`/api/registry/org/${target}`).set(headers) expect(response).to.have.status(403) diff --git a/test/integration-tests/registry-org/rootReadAccessTest.js b/test/integration-tests/registry-org/rootReadAccessTest.js index d4e8ef895..5547a077d 100644 --- a/test/integration-tests/registry-org/rootReadAccessTest.js +++ b/test/integration-tests/registry-org/rootReadAccessTest.js @@ -193,15 +193,15 @@ describe('Root oversight registry read access', () => { await expectOrgList(headers('top', admin), ['root', 'branch', 'cna', 'peer']) }) - it('lists only descendant users for Roots and top-level Roots, including distinct users with shared usernames', async () => { - await expectUserList(headers('root', admin), ['branch', 'cna']) - await expectUserList(headers('top', admin), ['root', 'branch', 'cna', 'peer']) + it('lists own and descendant users for Roots and top-level Roots, including distinct users with shared usernames', async () => { + await expectUserList(headers('root', admin), ['root', 'branch', 'cna']) + await expectUserList(headers('top', admin), ['top', 'root', 'branch', 'cna', 'peer']) }) - it('returns an empty list for a Root without descendants', async () => { + it('returns no descendant organizations but includes own users for a Root without descendants', async () => { const response = await expectOrgList(headers('peer', admin), []) expect(response.nextPage).to.equal(null) - await expectUserList(headers('peer', admin), []) + await expectUserList(headers('peer', admin), ['peer']) }) it('applies non-Secretariat conversation filtering to list entries', async () => { @@ -221,7 +221,7 @@ describe('Root oversight registry read access', () => { .post(`/api/registry/org/${orgs.root.short_name}/oversees/${orgs.peer.short_name}/add`) .set(headers('root', admin)) expect(widenScope).to.have.status(403) - await expectUserList(headers('root', admin), ['branch', 'cna']) + await expectUserList(headers('root', admin), ['root', 'branch', 'cna']) const orgUpdate = await chai.request(app) .put(`/api/registry/org/${orgs.cna.short_name}`).set(headers('root', admin)) .send({ short_name: orgs.cna.short_name, long_name: 'Unauthorized', authority: ['CNA'], id_quota: 10 }) @@ -249,12 +249,12 @@ describe('Root oversight registry read access', () => { }) } - it('paginates and counts only authorized users across the descendant organizations', async () => { + it('paginates and counts own and descendant users together', async () => { const paginatedApp = express() paginatedApp.set('query parser', 'extended') paginatedApp.use(middleware.createCtxAndReqUUID) paginatedApp.use((req, res, next) => { - req.TEST_PAGINATOR_LIMIT = 3 + req.TEST_PAGINATOR_LIMIT = 4 next() }) paginatedApp.use('/api', registryRouter) @@ -265,19 +265,19 @@ describe('Root oversight registry read access', () => { for (const page of [1, 2, 3]) { const response = await chai.request(url).get(`/api/registry/users?page=${page}`).set(headers('root')) expect(response).to.have.status(200) - expect(response.body.totalCount).to.equal(4) - expect(response.body.itemsPerPage).to.equal(3) + expect(response.body.totalCount).to.equal(6) + expect(response.body.itemsPerPage).to.equal(4) expect(response.body.pageCount).to.equal(2) expect(response.body.currentPage).to.equal(page) expect(response.body.prevPage).to.equal(page === 1 ? null : page - 1) expect(response.body.nextPage).to.equal(page === 1 ? 2 : null) - expect(response.body.users).to.have.lengthOf(page === 1 ? 3 : page === 2 ? 1 : 0) + expect(response.body.users).to.have.lengthOf(page === 1 ? 4 : page === 2 ? 2 : 0) returnedUUIDs.push(...response.body.users.map(user => user.UUID)) } - expect(returnedUUIDs).to.have.members([users.branch.UUID, users.branchAdmin.UUID, users.cna.UUID, users.cnaAdmin.UUID]) + expect(returnedUUIDs).to.have.members([users.root.UUID, users.rootAdmin.UUID, users.branch.UUID, users.branchAdmin.UUID, users.cna.UUID, users.cnaAdmin.UUID]) const global = await chai.request(url).get('/api/registry/users').set(secretariat) expect(global).to.have.status(200) - expect(global.body.totalCount).to.be.greaterThan(4) + expect(global.body.totalCount).to.be.greaterThan(6) }) }) @@ -305,7 +305,7 @@ describe('Root oversight registry read access', () => { }) expect(response).to.have.status(200) expect(response.body.users.map(user => user.UUID)).to.have.members([ - users.branch.UUID, users.branchAdmin.UUID, users.cna.UUID, users.cnaAdmin.UUID + users.root.UUID, users.rootAdmin.UUID, users.branch.UUID, users.branchAdmin.UUID, users.cna.UUID, users.cnaAdmin.UUID ]) for (const org of [orgs.top.short_name, 'mitre']) { const spoofed = await chai.request(app).get('/api/registry/users') @@ -329,11 +329,11 @@ describe('Root oversight registry read access', () => { currentOrg = target } try { - await expectUserList(headers('root'), ['branch', 'cna']) + await expectUserList(headers('root'), ['root', 'branch', 'cna']) await move('cna') - await expectUserList(headers('root'), ['branch', 'cna'], [users.peerOnly]) + await expectUserList(headers('root'), ['root', 'branch', 'cna'], [users.peerOnly]) await move('peer') - await expectUserList(headers('root'), ['branch', 'cna']) + await expectUserList(headers('root'), ['root', 'branch', 'cna']) } finally { if (currentOrg !== 'peer') await move('peer') } @@ -370,18 +370,18 @@ describe('Root oversight registry read access', () => { await expectReads(headers('other'), 'cna', 200) await expectOrgList(headers('root'), []) await expectOrgList(headers('other'), ['branch', 'cna']) - await expectUserList(headers('root'), []) - await expectUserList(headers('other'), ['branch', 'cna']) + await expectUserList(headers('root'), ['root']) + await expectUserList(headers('other'), ['other', 'branch', 'cna']) await relate('other', 'branch', 'remove') await expectReads(headers('other'), 'cna', 403) await expectOrgList(headers('other'), []) - await expectUserList(headers('other'), []) + await expectUserList(headers('other'), ['other']) } finally { await relate('root', 'branch') } await expectReads(headers('root'), 'cna', 200) await expectOrgList(headers('root'), ['branch', 'cna']) - await expectUserList(headers('root'), ['branch', 'cna']) + await expectUserList(headers('root'), ['root', 'branch', 'cna']) }) it('revokes oversight when the requesting organization loses ROOT authority', async () => { diff --git a/test/unit-tests/user/registryUserControllerTest.js b/test/unit-tests/user/registryUserControllerTest.js index bb07fe4a1..87b1c5658 100644 --- a/test/unit-tests/user/registryUserControllerTest.js +++ b/test/unit-tests/user/registryUserControllerTest.js @@ -82,35 +82,43 @@ describe('Testing Registry User Controller', () => { next = sinon.spy() }) - it('filters by descendant memberships and derives roles without user org_UUID fields', async () => { + it('includes own and descendant memberships and derives roles without user org_UUID fields', async () => { orgRepo.findOrgsByUUIDs.resolves([ + { UUID: 'root', users: ['root-admin', 'root-user'], admins: ['root-admin'] }, { UUID: 'branch', users: ['admin', 'regular'], admins: ['admin'] }, { UUID: 'child', users: ['child-user', 'regular'], admins: [] } ]) - userRepo.getAllUsers.resolves({ users: [{ UUID: 'admin' }, { UUID: 'regular' }, { UUID: 'child-user' }] }) + userRepo.getAllUsers.resolves({ + users: [ + { UUID: 'root-admin' }, { UUID: 'root-user' }, { UUID: 'admin' }, { UUID: 'regular' }, { UUID: 'child-user' } + ] + }) await controller.ALL_USERS(req, res, next) expect(descendants.calledOnceWithExactly(req, orgRepo, 'root')).to.equal(true) - expect(orgRepo.findOrgsByUUIDs.calledOnceWithExactly(['branch', 'child'], { readPreference: 'primary' })).to.equal(true) - expect(userRepo.getAllUsers.firstCall.args[1]).to.deep.equal(['admin', 'regular', 'child-user']) + expect(orgRepo.findOrgsByUUIDs.calledOnceWithExactly(['root', 'branch', 'child'], { readPreference: 'primary' })).to.equal(true) + expect(userRepo.getAllUsers.firstCall.args[1]).to.deep.equal(['root-admin', 'root-user', 'admin', 'regular', 'child-user']) expect(res.status.calledOnceWith(200)).to.equal(true) expect(res.json.firstCall.args[0].users).to.deep.equal([ + { UUID: 'root-admin', role: 'ADMIN' }, { UUID: 'root-user' }, { UUID: 'admin', role: 'ADMIN' }, { UUID: 'regular' }, { UUID: 'child-user' } ]) expect(next.called).to.equal(false) }) - it('keeps a Root without descendants explicitly scoped to no users', async () => { + it('includes only own users for a Root without descendants', async () => { descendants.resolves([]) + orgRepo.findOrgsByUUIDs.resolves([{ UUID: 'root', users: ['root-user'], admins: [] }]) + userRepo.getAllUsers.resolves({ users: [{ UUID: 'root-user' }] }) await controller.ALL_USERS(req, res, next) - expect(orgRepo.findOrgsByUUIDs.firstCall.args[0]).to.deep.equal([]) - expect(userRepo.getAllUsers.firstCall.args[1]).to.deep.equal([]) - expect(res.json.firstCall.args[0]).to.deep.equal({ users: [] }) + expect(orgRepo.findOrgsByUUIDs.firstCall.args[0]).to.deep.equal(['root']) + expect(userRepo.getAllUsers.firstCall.args[1]).to.deep.equal(['root-user']) + expect(res.json.firstCall.args[0]).to.deep.equal({ users: [{ UUID: 'root-user' }] }) }) - it('keeps descendants without memberships explicitly scoped to no users', async () => { - orgRepo.findOrgsByUUIDs.resolves([{ UUID: 'branch', users: [] }, { UUID: 'child' }]) + it('keeps a tree without memberships explicitly scoped to no users', async () => { + orgRepo.findOrgsByUUIDs.resolves([{ UUID: 'root', users: [] }, { UUID: 'branch', users: [] }, { UUID: 'child' }]) await controller.ALL_USERS(req, res, next) expect(userRepo.getAllUsers.firstCall.args[1]).to.deep.equal([]) expect(res.json.firstCall.args[0]).to.deep.equal({ users: [] }) From 27aed77a7acb36264dc07e04ec4f42d37d765434 Mon Sep 17 00:00:00 2001 From: David T Rocca Date: Wed, 11 Nov 2026 11:43:00 -0500 Subject: [PATCH 10/19] fixing the org responses --- api-docs/openapi.json | 4 +- src/controller/registry.controller/index.js | 4 +- .../org.registry.controller.js | 7 +-- .../registry-org/populatedOrgHierarchyTest.js | 7 +-- .../registry-org/rootReadAccessTest.js | 46 ++++++++++--------- .../middleware/registryReadAccessTest.js | 8 ++-- 6 files changed, 41 insertions(+), 35 deletions(-) diff --git a/api-docs/openapi.json b/api-docs/openapi.json index 66c3e36d4..3742b8324 100644 --- a/api-docs/openapi.json +++ b/api-docs/openapi.json @@ -3058,7 +3058,7 @@ "Data Registry — Organizations" ], "summary": "Lists registry organizations for Secretariat or overseeing Root users", - "description": "

Related legacy endpoint: GET /org. Data Registry responses use long_name and an authority array; legacy responses use name and authority.active_roles.

Access Control

User must belong to an organization with SECRETARIAT or ROOT authority. Both ordinary Root users and Root administrators have access.

Expected Behavior

Secretariat: Retrieves information about all registry organizations.

Root and top-level Root users: Retrieves a flat list of all direct and indirect descendants, including subordinate Roots and organizations beneath them. The requesting organization itself, ancestors, sibling branches, and unrelated organizations are excluded. A Root without descendants receives an empty list.

Results use existing non-Secretariat field filtering and are sorted by short_name. Pagination and totalCount apply only to organizations within the authorized scope. Authorization uses current ROOT authority and reporting relationships.

", + "description": "

Related legacy endpoint: GET /org. Data Registry responses use long_name and an authority array; legacy responses use name and authority.active_roles.

Access Control

User must belong to an organization with SECRETARIAT or ROOT authority. Both ordinary Root users and Root administrators have access.

Expected Behavior

Secretariat: Retrieves information about all registry organizations.

Root and top-level Root users: Retrieves a flat list containing the requesting organization itself and all direct and indirect descendants, including subordinate Roots and organizations beneath them. Ancestors, sibling branches, and unrelated organizations are excluded. A Root without descendants receives only its own organization.

Results use existing non-Secretariat field filtering and are sorted by short_name. Pagination and totalCount apply only to organizations within the authorized scope. Authorization uses current ROOT authority and reporting relationships.

", "operationId": "registryOrgAll", "parameters": [ { @@ -3076,7 +3076,7 @@ ], "responses": { "200": { - "description": "Returns registry organizations and pagination metadata. Secretariat receives all organizations; Root users receive only their descendants, with scoped totals.", + "description": "Returns registry organizations and pagination metadata. Secretariat receives all organizations; Root users receive their own organization and descendants, with scoped totals.", "content": { "application/json": { "schema": { diff --git a/src/controller/registry.controller/index.js b/src/controller/registry.controller/index.js index 56049d429..07e0717bb 100644 --- a/src/controller/registry.controller/index.js +++ b/src/controller/registry.controller/index.js @@ -25,7 +25,7 @@ router.get('/registry/org',

User must belong to an organization with SECRETARIAT or ROOT authority. Both ordinary Root users and Root administrators have access.

Expected Behavior

Secretariat: Retrieves information about all registry organizations.

-

Root and top-level Root users: Retrieves a flat list of all direct and indirect descendants, including subordinate Roots and organizations beneath them. The requesting organization itself, ancestors, sibling branches, and unrelated organizations are excluded. A Root without descendants receives an empty list.

+

Root and top-level Root users: Retrieves a flat list containing the requesting organization itself and all direct and indirect descendants, including subordinate Roots and organizations beneath them. Ancestors, sibling branches, and unrelated organizations are excluded. A Root without descendants receives only its own organization.

Results use existing non-Secretariat field filtering and are sorted by short_name. Pagination and totalCount apply only to organizations within the authorized scope. Authorization uses current ROOT authority and reporting relationships.

" #swagger.parameters['$ref'] = [ '#/components/parameters/pageQuery', @@ -34,7 +34,7 @@ router.get('/registry/org', '#/components/parameters/apiSecretHeader' ] #swagger.responses[200] = { - description: 'Returns registry organizations and pagination metadata. Secretariat receives all organizations; Root users receive only their descendants, with scoped totals.', + description: 'Returns registry organizations and pagination metadata. Secretariat receives all organizations; Root users receive their own organization and descendants, with scoped totals.', content: { "application/json": { schema: { diff --git a/src/controller/registry.controller/org.registry.controller.js b/src/controller/registry.controller/org.registry.controller.js index b8215765c..45605c038 100644 --- a/src/controller/registry.controller/org.registry.controller.js +++ b/src/controller/registry.controller/org.registry.controller.js @@ -114,7 +114,7 @@ function removeAdditionalContactUUIDFields (org) { * @param {object} res - The Express response object. * @param {function} next - The next middleware function. * @returns {Promise} - A promise that resolves when the response is sent. - * @description Secretariat receives all registry organizations; Root users receive only their descendants. + * @description Secretariat receives all registry organizations; Root users receive their own organization and descendants. * Called by GET /api/registry/org */ async function getAllOrgs (req, res, next) { @@ -125,10 +125,11 @@ async function getAllOrgs (req, res, next) { } const repo = req.ctx.repositories.getBaseOrgRepository() const { isSecretariat, hierarchyScope } = access - const orgUUIDs = isSecretariat ? undefined : await authContext.getRequestOrgDescendantUUIDs(req, repo, hierarchyScope) - if (!isSecretariat && !Array.isArray(orgUUIDs)) { + const descendantOrgUUIDs = isSecretariat ? undefined : await authContext.getRequestOrgDescendantUUIDs(req, repo, hierarchyScope) + if (!isSecretariat && !Array.isArray(descendantOrgUUIDs)) { return res.status(403).json(error.notSameOrgOrSecretariat()) } + const orgUUIDs = isSecretariat ? undefined : [hierarchyScope, ...descendantOrgUUIDs] const conversationRepo = req.ctx.repositories.getConversationRepository() const CONSTANTS = getConstants() let returnValue diff --git a/test/integration-tests/registry-org/populatedOrgHierarchyTest.js b/test/integration-tests/registry-org/populatedOrgHierarchyTest.js index a59ce5ab1..d9c3f949d 100644 --- a/test/integration-tests/registry-org/populatedOrgHierarchyTest.js +++ b/test/integration-tests/registry-org/populatedOrgHierarchyTest.js @@ -228,14 +228,15 @@ describe('Populated registry organization hierarchy', () => { }) for (const role of ['user', 'admin']) { - it(`paginates only descendants for the seeded ${shortName} ${role}`, async () => { - const expected = shortName === 'top_root_1' + it(`paginates the own organization and descendants for the seeded ${shortName} ${role}`, async () => { + const descendants = shortName === 'top_root_1' ? [ ...topRootSeeds[0].oversees, ...directCnaShortNames.slice(0, DIRECT_CNAS_PER_TOP_ROOT), ...childRootCnaShortNames.filter((_name, index) => index % rootShortNames.length < topRootSeeds[0].oversees.length) ] : childRootCnaShortNames.filter((_name, index) => index % rootShortNames.length === rootShortNames.indexOf(shortName)) + const expected = [shortName, ...descendants] const names = [] await withHttpServer(createPaginatedRegistryApp(), async url => { let page = 1 @@ -257,7 +258,7 @@ describe('Populated registry organization hierarchy', () => { expect(names).to.have.members(expected) expect(new Set(names).size).to.equal(expected.length) expect(names).to.deep.equal([...names].sort()) - expect(names).to.not.include(shortName) + expect(names.filter(name => name === shortName)).to.have.lengthOf(1) }) it(`lets the seeded ${shortName} ${role} retrieve the scoped hierarchy and descendant users`, async () => { diff --git a/test/integration-tests/registry-org/rootReadAccessTest.js b/test/integration-tests/registry-org/rootReadAccessTest.js index 5547a077d..1ff8aebe3 100644 --- a/test/integration-tests/registry-org/rootReadAccessTest.js +++ b/test/integration-tests/registry-org/rootReadAccessTest.js @@ -119,15 +119,17 @@ describe('Root oversight registry read access', () => { expect(peerOnly).to.have.status(200) users.peerOnly = peerOnly.body.created createdUsers.push({ shortName: orgs.peer.short_name, username: users.peerOnly.username }) - for (const visibility of ['public', 'private']) { - const response = await chai.request(app).post(`/api/conversation/target/${orgs.cna.UUID}`) - .set(secretariat).send({ visibility, body: `${visibility} Root list ${runId}` }) - expect(response).to.have.status(200) + for (const label of ['root', 'cna']) { + for (const visibility of ['public', 'private']) { + const response = await chai.request(app).post(`/api/conversation/target/${orgs[label].UUID}`) + .set(secretariat).send({ visibility, body: `${visibility} Root list ${runId}` }) + expect(response).to.have.status(200) + } } }) after(async () => { - if (orgs.cna) await Conversation.deleteMany({ target_uuid: orgs.cna.UUID }) + await Conversation.deleteMany({ target_uuid: { $in: Object.values(orgs).map(org => org.UUID) } }) for (const user of createdUsers) { const response = await chai.request(app) .delete(`/api/registry/org/${user.shortName}/user/${user.username}`).set(secretariat) @@ -188,9 +190,9 @@ describe('Root oversight registry read access', () => { for (const label of ['top', 'peer', 'other']) await expectReads(headers('root', admin), label, 403) }) - it('lists all descendants for Roots and top-level Roots, excluding the requester and other branches', async () => { - await expectOrgList(headers('root', admin), ['branch', 'cna']) - await expectOrgList(headers('top', admin), ['root', 'branch', 'cna', 'peer']) + it('lists the own organization and all descendants for Roots and top-level Roots, excluding other branches', async () => { + await expectOrgList(headers('root', admin), ['root', 'branch', 'cna']) + await expectOrgList(headers('top', admin), ['top', 'root', 'branch', 'cna', 'peer']) }) it('lists own and descendant users for Roots and top-level Roots, including distinct users with shared usernames', async () => { @@ -198,19 +200,21 @@ describe('Root oversight registry read access', () => { await expectUserList(headers('top', admin), ['top', 'root', 'branch', 'cna', 'peer']) }) - it('returns no descendant organizations but includes own users for a Root without descendants', async () => { - const response = await expectOrgList(headers('peer', admin), []) + it('returns only the own organization and its users for a Root without descendants', async () => { + const response = await expectOrgList(headers('peer', admin), ['peer']) expect(response.nextPage).to.equal(null) await expectUserList(headers('peer', admin), ['peer']) }) - it('applies non-Secretariat conversation filtering to list entries', async () => { - const payload = await expectOrgList(headers('root', admin), ['branch', 'cna']) - const org = payload.organizations.find(org => org.UUID === orgs.cna.UUID) - expect(org.conversation).to.have.lengthOf(1) - expect(org.conversation[0].body).to.equal(`public Root list ${runId}`) - for (const field of ['_id', '__v', 'UUID', 'target_uuid', 'visibility', 'previous_conversation_uuid', 'next_conversation_uuid', 'author_id', 'author_name']) { - expect(org.conversation[0]).to.not.have.property(field) + it('applies non-Secretariat conversation filtering to own and descendant list entries', async () => { + const payload = await expectOrgList(headers('root', admin), ['root', 'branch', 'cna']) + for (const label of ['root', 'cna']) { + const org = payload.organizations.find(org => org.UUID === orgs[label].UUID) + expect(org.conversation).to.have.lengthOf(1) + expect(org.conversation[0].body).to.equal(`public Root list ${runId}`) + for (const field of ['_id', '__v', 'UUID', 'target_uuid', 'visibility', 'previous_conversation_uuid', 'next_conversation_uuid', 'author_id', 'author_name']) { + expect(org.conversation[0]).to.not.have.property(field) + } } }) @@ -368,19 +372,19 @@ describe('Root oversight registry read access', () => { await relate('other', 'branch') await expectReads(headers('root'), 'cna', 403) await expectReads(headers('other'), 'cna', 200) - await expectOrgList(headers('root'), []) - await expectOrgList(headers('other'), ['branch', 'cna']) + await expectOrgList(headers('root'), ['root']) + await expectOrgList(headers('other'), ['other', 'branch', 'cna']) await expectUserList(headers('root'), ['root']) await expectUserList(headers('other'), ['other', 'branch', 'cna']) await relate('other', 'branch', 'remove') await expectReads(headers('other'), 'cna', 403) - await expectOrgList(headers('other'), []) + await expectOrgList(headers('other'), ['other']) await expectUserList(headers('other'), ['other']) } finally { await relate('root', 'branch') } await expectReads(headers('root'), 'cna', 200) - await expectOrgList(headers('root'), ['branch', 'cna']) + await expectOrgList(headers('root'), ['root', 'branch', 'cna']) await expectUserList(headers('root'), ['root', 'branch', 'cna']) }) diff --git a/test/unit-tests/middleware/registryReadAccessTest.js b/test/unit-tests/middleware/registryReadAccessTest.js index ecd47a757..3542f36a4 100644 --- a/test/unit-tests/middleware/registryReadAccessTest.js +++ b/test/unit-tests/middleware/registryReadAccessTest.js @@ -137,22 +137,22 @@ describe('Registry read authorization', () => { expect(await authContext.isRequesterParentOrg(req, orgRepo, { UUID: 'child' })).to.equal(false) }) - it('passes only descendant UUIDs from the authenticated Root to the organization list query', async () => { + it('passes the authenticated Root UUID and its descendants to the organization list query', async () => { await middleware.authorizeRegistryHierarchyRead(req, res, next) await ALL_ORGS(req, res, next) expect(res.status.calledOnceWith(200)).to.equal(true) expect(orgRepo.getAllOrgs.firstCall.args[2]).to.equal(false) - expect(orgRepo.getAllOrgs.firstCall.args[3]).to.have.members(['branch', 'child']) + expect(orgRepo.getAllOrgs.firstCall.args[3]).to.have.members(['root', 'branch', 'child']) expect(find.calledOnce).to.equal(true) expect(orgRepo.findOneByShortName.called).to.equal(false) }) - it('keeps an empty Root list explicitly scoped to an empty UUID set', async () => { + it('scopes a Root without descendants to its own organization', async () => { req.ctx.orgUUID = 'sibling' await middleware.authorizeRegistryHierarchyRead(req, res, next) await ALL_ORGS(req, res, next) expect(res.status.calledOnceWith(200)).to.equal(true) - expect(orgRepo.getAllOrgs.firstCall.args[3]).to.deep.equal([]) + expect(orgRepo.getAllOrgs.firstCall.args[3]).to.deep.equal(['sibling']) }) it('never runs an organization list query when the Root scope is missing', async () => { From ec6a1a475a5b3c0048be0be8881bddac13a41a42 Mon Sep 17 00:00:00 2001 From: David T Rocca Date: Mon, 16 Nov 2026 10:19:04 -0500 Subject: [PATCH 11/19] Manage users --- api-docs/openapi.json | 8 +- .../update-registry-user-request.json | 2 +- src/controller/registry.controller/index.js | 8 +- .../registry.controller/org.error.js | 7 + .../org.registry.controller.js | 9 +- .../user.registry.controller.js | 45 ++- src/controller/user.controller/error.js | 9 +- src/utils/authContext.js | 19 ++ .../registry-org/rootReadAccessTest.js | 11 +- .../user/userMoveAdminContractTest.js | 275 +++++++++++++++++- test/unit-tests/utils/authContextTest.js | 61 ++++ 11 files changed, 425 insertions(+), 29 deletions(-) diff --git a/api-docs/openapi.json b/api-docs/openapi.json index 3742b8324..f14974cc8 100644 --- a/api-docs/openapi.json +++ b/api-docs/openapi.json @@ -4109,8 +4109,8 @@ "tags": [ "Data Registry — Users" ], - "summary": "Updates information about a user for the specified username and organization shortname (accessible to self, same-organization Admins, or Secretariat)", - "description": "

Related legacy endpoint: PUT /org/{shortname}/user/{username}. This endpoint accepts updates through a JSON request body. The legacy endpoint uses query parameters and the legacy user schema.

Access Control

Authenticated users can update their own name fields. Organization admins can update users in their organization. Secretariat users can update users in any organization.

Expected Behavior

Regular User: Updates the user's own information. Only name fields may be changed.

Admin User: Updates information about a user in the Admin's organization. Allowed to change all fields except org_short_name.

Secretariat: Updates information about a user in any organization. Allowed to change all fields.

Deactivation preserves assigned ADMIN membership while preventing authentication. Reactivation retains that assignment unless ADMIN was explicitly revoked or the user moved organizations. Omitting role from a profile update does not revoke ADMIN.

Moving a user to another organization removes ADMIN in both the source and destination. ADMIN requested in the move is not granted; promotion requires a separate authorized request after the move.

", + "summary": "Updates a user (self, same-organization Admins, or Secretariat); Root Admins can move users within their hierarchy", + "description": "

Related legacy endpoint: PUT /org/{shortname}/user/{username}. This endpoint accepts updates through a JSON request body. The legacy endpoint uses query parameters and the legacy user schema.

Access Control

Authenticated users can update their own name fields. Organization admins can update users in their organization. Secretariat users can update users in any organization.

Expected Behavior

Regular User: Updates the user's own information. Only name fields may be changed.

Admin User: Updates information about a user in the Admin's organization. Allowed to change all fields except org_short_name.

Secretariat: Updates information about a user in any organization. Allowed to change all fields.

Root Admin: May supply org_short_name to move a user when both the source and destination are its own organization or descendants, including nested Roots. This permission does not grant profile editing in descendant organizations: supply the existing username, status, and all existing name fields unchanged. Source-organization Admins retain their existing profile-edit permissions. Ordinary Root users cannot move users.

Deactivation preserves assigned ADMIN membership while preventing authentication. Reactivation retains that assignment unless ADMIN was explicitly revoked or the user moved organizations. Omitting role from a profile update does not revoke ADMIN.

Moving a user to another organization removes ADMIN in both the source and destination. ADMIN requested in the move is not granted; promotion requires a separate authorized request after the move.

", "operationId": "registryUserUpdateSingle", "parameters": [ { @@ -4341,8 +4341,8 @@ "tags": [ "Data Registry — Users" ], - "summary": "Create a user with the provided short name as the owning organization (accessible to Secretariat or target organization Admin)", - "description": "

Related legacy endpoint: POST /org/{shortname}/user. Uses the Data Registry user request schema, including the required status field. Compare the legacy request schema before switching.

Access Control

User must belong to an organization with the Secretariat role or be an Admin of the target organization

Expected Behavior

Admin User: Creates a user for the Admin's organization

Secretariat: Creates a user for any organization

", + "summary": "Create a user for an organization (accessible to Secretariat, target organization Admins, or overseeing Root Admins)", + "description": "

Related legacy endpoint: POST /org/{shortname}/user. Uses the Data Registry user request schema, including the required status field. Compare the legacy request schema before switching.

Access Control

User must belong to an organization with the Secretariat role, be an Admin of the target organization, or be an Admin of a Root that oversees the target organization.

Expected Behavior

Admin User: Creates a user for the Admin's organization

Root Admin: Creates regular or ADMIN users in its own organization or any descendant, including nested Roots. Ordinary Root users cannot create users.

Secretariat: Creates a user for any organization

", "operationId": "registryUserCreateSingle", "parameters": [ { diff --git a/schemas/registry-user/update-registry-user-request.json b/schemas/registry-user/update-registry-user-request.json index a9b249281..5979b3d02 100644 --- a/schemas/registry-user/update-registry-user-request.json +++ b/schemas/registry-user/update-registry-user-request.json @@ -73,7 +73,7 @@ "type": "string" }, "org_short_name": { - "description": "Moves the user to another organization and removes ADMIN in both the source and destination. Promotion requires a separate authorized request after the move.", + "description": "Moves the user to another organization and removes ADMIN in both the source and destination. Allowed for Secretariat or a Root ADMIN when both organizations are its own organization or descendants. Root move permission alone requires username, status, and all existing name fields to remain unchanged. Promotion requires a separate authorized request after the move.", "type": "string", "minLength": 2, "maxLength": 32 diff --git a/src/controller/registry.controller/index.js b/src/controller/registry.controller/index.js index 07e0717bb..1195ec93d 100644 --- a/src/controller/registry.controller/index.js +++ b/src/controller/registry.controller/index.js @@ -970,13 +970,14 @@ router.post('/registry/org/:shortname/user', /* #swagger.tags = ['Data Registry — Users'] #swagger.operationId = 'registryUserCreateSingle' - #swagger.summary = "Create a user with the provided short name as the owning organization (accessible to Secretariat or target organization Admin)" + #swagger.summary = "Create a user for an organization (accessible to Secretariat, target organization Admins, or overseeing Root Admins)" #swagger.description = "

Related legacy endpoint: POST /org/{shortname}/user. Uses the Data Registry user request schema, including the required status field. Compare the legacy request schema before switching.

Access Control

-

User must belong to an organization with the Secretariat role or be an Admin of the target organization

+

User must belong to an organization with the Secretariat role, be an Admin of the target organization, or be an Admin of a Root that oversees the target organization.

Expected Behavior

Admin User: Creates a user for the Admin's organization

+

Root Admin: Creates regular or ADMIN users in its own organization or any descendant, including nested Roots. Ordinary Root users cannot create users.

Secretariat: Creates a user for any organization

" #swagger.requestBody = { "required": true, @@ -1078,7 +1079,7 @@ router.put('/registry/org/:shortname/user/:username', /* #swagger.tags = ['Data Registry — Users'] #swagger.operationId = 'registryUserUpdateSingle' - #swagger.summary = "Updates information about a user for the specified username and organization shortname (accessible to self, same-organization Admins, or Secretariat)" + #swagger.summary = "Updates a user (self, same-organization Admins, or Secretariat); Root Admins can move users within their hierarchy" #swagger.description = "

Related legacy endpoint: PUT /org/{shortname}/user/{username}. This endpoint accepts updates through a JSON request body. The legacy endpoint uses query parameters and the legacy user schema.

Access Control

@@ -1087,6 +1088,7 @@ router.put('/registry/org/:shortname/user/:username',

Regular User: Updates the user's own information. Only name fields may be changed.

Admin User: Updates information about a user in the Admin's organization. Allowed to change all fields except org_short_name.

Secretariat: Updates information about a user in any organization. Allowed to change all fields.

+

Root Admin: May supply org_short_name to move a user when both the source and destination are its own organization or descendants, including nested Roots. This permission does not grant profile editing in descendant organizations: supply the existing username, status, and all existing name fields unchanged. Source-organization Admins retain their existing profile-edit permissions. Ordinary Root users cannot move users.

Deactivation preserves assigned ADMIN membership while preventing authentication. Reactivation retains that assignment unless ADMIN was explicitly revoked or the user moved organizations. Omitting role from a profile update does not revoke ADMIN.

Moving a user to another organization removes ADMIN in both the source and destination. ADMIN requested in the move is not granted; promotion requires a separate authorized request after the move.

" #swagger.parameters['shortname'] = { description: 'The shortname of the organization' } diff --git a/src/controller/registry.controller/org.error.js b/src/controller/registry.controller/org.error.js index a0e314b02..cd973e28b 100644 --- a/src/controller/registry.controller/org.error.js +++ b/src/controller/registry.controller/org.error.js @@ -16,6 +16,13 @@ class RegistryOrgControllerError extends idrErr.IDRError { return err } + notOrgAdminOrSecretariatOrRoot () { + return { + ...this.notOrgAdminOrSecretariat(), + message: 'User creation requires Secretariat, an admin of the target organization, or an overseeing Root admin.' + } + } + orgDnePathParam (shortname) { // org const err = {} err.error = 'ORG_DNE_PARAM' diff --git a/src/controller/registry.controller/org.registry.controller.js b/src/controller/registry.controller/org.registry.controller.js index 45605c038..94d06dda7 100644 --- a/src/controller/registry.controller/org.registry.controller.js +++ b/src/controller/registry.controller/org.registry.controller.js @@ -1068,7 +1068,7 @@ async function getUsers (req, res, next) { * @param {object} res - The Express response object. * @param {function} next - The next middleware function. * @returns {Promise} - A promise that resolves when the response is sent. - * @description This endpoint is accessible to Secretariat only. It creates a user for any organization. + * @description Secretariat, target organization admins, and overseeing Root admins can create users. * Called by POST /api/registry/org/:shortname/user */ async function createUserByOrg (req, res, next) { @@ -1119,9 +1119,12 @@ async function createUserByOrg (req, res, next) { const isRequesterSecretariat = await authContext.isRequesterSecretariat(req, orgRepo, { session }) const isRequesterAdminOfTargetOrg = await authContext.isRequesterAdminOfOrg(req, userRepo, orgRepo, orgShortName, { session }) - if (!isRequesterSecretariat && !isRequesterAdminOfTargetOrg) { + const isOverseeingRootAdmin = !isRequesterSecretariat && !isRequesterAdminOfTargetOrg && + await authContext.isRequesterRootAdminOfOrgs(req, userRepo, orgRepo, + [await orgRepo.findOneByShortName(orgShortName, { session }, REGISTRY_FORMAT)], { session }) + if (!isRequesterSecretariat && !isRequesterAdminOfTargetOrg && !isOverseeingRootAdmin) { await session.abortTransaction() - return res.status(403).json(error.notOrgAdminOrSecretariat()) // The Admin user must belong to the new user's organization + return res.status(403).json(error.notOrgAdminOrSecretariatOrRoot()) } const requestingUserUUID = await authContext.getRequesterUserUUID(req, userRepo, orgRepo, { session }) diff --git a/src/controller/registry.controller/user.registry.controller.js b/src/controller/registry.controller/user.registry.controller.js index 3451b86a1..bbfd2a8e1 100644 --- a/src/controller/registry.controller/user.registry.controller.js +++ b/src/controller/registry.controller/user.registry.controller.js @@ -226,9 +226,6 @@ async function updateUser (req, res, next) { const isSecretariat = await authContext.isRequesterSecretariat(req, orgRepo, {}, REGISTRY_FORMAT) - // TODO: This will need to be atomic at some point like revoke or grant - // Specific check for org_short_name (Secretariat only) - let userToEdit let org if (identifier) { @@ -272,9 +269,12 @@ async function updateUser (req, res, next) { } } + let isRootMove = false if (body.org_short_name && !isSecretariat) { - logger.info({ uuid: req.ctx.uuid, message: 'Only Secretariat can reassign user organization.' }) - return res.status(403).json(error.notAllowedToChangeOrganization()) + isRootMove = await authContext.isRequesterRootAdminOfOrgs(req, userRepo, orgRepo, [org]) + if (!isRootMove) { + return res.status(403).json(error.notAllowedToChangeOrganization()) + } } if (body.org_short_name) { @@ -285,7 +285,7 @@ async function updateUser (req, res, next) { } } - if (body.org_short_name && isSecretariat && userToEditParameters.org === org.short_name && body.org_short_name === org.short_name) { + if (body.org_short_name && (isSecretariat || isRootMove) && userToEditParameters.org === org.short_name && body.org_short_name === org.short_name) { logger.info({ uuid: req.ctx.uuid, message: `User ${userToEditParameters.username} is already in organization ${userToEditParameters.org}.` }) return res.status(403).json(error.alreadyInOrg(org.short_name, userToEditParameters.username)) } @@ -296,12 +296,12 @@ async function updateUser (req, res, next) { } const requesterSameOrg = await authContext.isRequesterSameOrg(req, orgRepo, org, {}, REGISTRY_FORMAT) - if (!isSecretariat && !isAdmin && !requesterSameOrg) { + if (!isSecretariat && !isAdmin && !requesterSameOrg && !isRootMove) { logger.info({ uuid: req.ctx.uuid, message: requestingUserParameters.org + ' user can only be updated by the user or admins of the same organization or the Secretariat.' }) return res.status(403).json(error.notSameOrgOrSecretariat()) } - if (!isSecretariat && !isAdmin) { + if (!isSecretariat && !isAdmin && !isRootMove) { if (requesterUserUUID !== userToEdit?.UUID) { if (!userToEdit) { logger.info({ uuid: req.ctx.uuid, message: 'User DNE' }) @@ -328,8 +328,35 @@ async function updateUser (req, res, next) { try { session.startTransaction({ readPreference: 'primary' }) + if (isRootMove) { + // The source may have changed after initial lookup. Recheck membership and + // both endpoints in the same snapshot used by updateUserFull. + const currentOrgUUID = await orgRepo.getOrgUUIDByUserUUID(userToEdit.UUID, { session }) + const targetOrg = await orgRepo.findOneByShortName(body.org_short_name, { session }, REGISTRY_FORMAT) + if (currentOrgUUID !== org.UUID || + !await authContext.isRequesterRootAdminOfOrgs(req, userRepo, orgRepo, [org, targetOrg], { session })) { + await session.abortTransaction() + return res.status(403).json(error.notAllowedToChangeOrganization()) + } + + const isSourceAdmin = await authContext.isRequesterAdminOfOrg(req, userRepo, orgRepo, org, { session }, REGISTRY_FORMAT) + if (!isSourceAdmin) { + const currentUser = await userRepo.findUserByUUID(userToEdit.UUID, { session }, REGISTRY_FORMAT) + const profileFields = ['username', 'status', 'name'] + const currentProfile = _.pick(JSON.parse(JSON.stringify(currentUser)), profileFields) + // Compare every effective update, including dotted paths such as name.first. + // Identity fields are normalized above; move role fields and legacy active + // are ignored by the existing registry repository. + const incomingProfile = _.omit(body, ['org_short_name', 'role', 'authority', 'active', 'UUID', 'uuid', 'org_UUID', 'org_uuid']) + if (!_.isEqual(incomingProfile, currentProfile)) { + await session.abortTransaction() + return res.status(400).json(error.rootMoveProfileChange()) + } + } + } + // if a user is NOT an ADMIN OR SECRETARIAT they can only update their name fields - if (!isSecretariat && !isAdmin) { + if (!isSecretariat && !isAdmin && !isRootMove) { const allowedFields = ['name', 'name.first', 'name.last', 'name.middle', 'name.suffix'] const restrictedUpdates = _.omit(body, allowedFields) diff --git a/src/controller/user.controller/error.js b/src/controller/user.controller/error.js index 75fa8581c..f874f1714 100644 --- a/src/controller/user.controller/error.js +++ b/src/controller/user.controller/error.js @@ -11,7 +11,7 @@ class UserControllerError extends idrErr.IDRError { notAllowedToChangeOrganization () { const err = {} err.error = 'NOT_ALLOWED_TO_CHANGE_ORGANIZATION' - err.message = 'Only the Secretariat can change the organization for a user.' + err.message = 'User moves require Secretariat or a Root admin with both organizations in their hierarchy.' return err } @@ -23,6 +23,13 @@ class UserControllerError extends idrErr.IDRError { } } + rootMoveProfileChange () { + return { + error: 'NOT_ALLOWED_TO_CHANGE_FIELD', + message: 'Root move permission does not allow profile changes. Supply the existing username, status, and name fields unchanged.' + } + } + orgDnePathParam (shortname) { // org const err = {} err.error = 'ORG_DNE_PARAM' diff --git a/src/utils/authContext.js b/src/utils/authContext.js index df6e35538..3c322db18 100644 --- a/src/utils/authContext.js +++ b/src/utils/authContext.js @@ -307,6 +307,24 @@ async function isRequesterParentOrg (req, orgRepo, targetOrg, options = {}) { return Boolean(requesterNode && findHierarchyNode(requesterNode.children, targetOrg.UUID)) } +// Write authorization reads through the caller's session, never the read-route cache. +// A move must authorize both organizations against the same Root subtree. +async function isRequesterRootAdminOfOrgs (req, userRepo, orgRepo, targetOrgs, options = {}) { + if (!isAuthenticatedRequest(req) || !req.ctx.orgUUID || !req.ctx.userUUID || + !Array.isArray(targetOrgs) || targetOrgs.length === 0 || targetOrgs.some(org => !org?.UUID)) { + return false + } + + const requesterOrg = await getRequesterOrg(req, orgRepo, options) + if (!orgHasRole(requesterOrg, 'ROOT') || !await isRequesterAdmin(req, userRepo, orgRepo, options)) return false + + const hierarchy = await orgRepo.getOrgHierarchy(req.ctx.orgUUID, { ...options, readPreference: 'primary' }) + if (!Array.isArray(hierarchy)) return false + const requesterNode = findHierarchyNode(hierarchy, req.ctx.orgUUID) + if (!orgHasRole(requesterNode, 'ROOT')) return false + return targetOrgs.every(org => Boolean(findHierarchyNode([requesterNode], org.UUID))) +} + async function isRequesterSecretariat (req, orgRepo, options = {}, returnLegacyFormat = false) { if (isAuthenticatedRequest(req) || req.ctx.orgUUID) { const orgUUID = await getRequesterOrgUUID(req, orgRepo, options, returnLegacyFormat) @@ -486,6 +504,7 @@ module.exports = { isRequesterAdminOfOrg, isRequesterBulkDownload, isRequesterParentOrg, + isRequesterRootAdminOfOrgs, isRequesterSameOrg, isRequesterSecretariat, orgHasRole diff --git a/test/integration-tests/registry-org/rootReadAccessTest.js b/test/integration-tests/registry-org/rootReadAccessTest.js index 1ff8aebe3..8ca457478 100644 --- a/test/integration-tests/registry-org/rootReadAccessTest.js +++ b/test/integration-tests/registry-org/rootReadAccessTest.js @@ -230,10 +230,13 @@ describe('Root oversight registry read access', () => { .put(`/api/registry/org/${orgs.cna.short_name}`).set(headers('root', admin)) .send({ short_name: orgs.cna.short_name, long_name: 'Unauthorized', authority: ['CNA'], id_quota: 10 }) expect(orgUpdate).to.have.status(403) - const userCreate = await chai.request(app) - .post(`/api/registry/org/${orgs.cna.short_name}/user`).set(headers('root', admin)) - .send({ username: `forbidden_${runId}@example.test`, status: 'active' }) - expect(userCreate).to.have.status(403) + // Root admin creation is covered by the Root user-management tests. + if (!admin) { + const userCreate = await chai.request(app) + .post(`/api/registry/org/${orgs.cna.short_name}/user`).set(headers('root', admin)) + .send({ username: `forbidden_${runId}@example.test`, status: 'active' }) + expect(userCreate).to.have.status(403) + } const userDelete = await chai.request(app) .delete(`/api/registry/org/${orgs.cna.short_name}/user/${users.cna.username}`).set(headers('root', admin)) expect(userDelete).to.have.status(403) diff --git a/test/integration-tests/user/userMoveAdminContractTest.js b/test/integration-tests/user/userMoveAdminContractTest.js index 171cf8390..f2f72e65f 100644 --- a/test/integration-tests/user/userMoveAdminContractTest.js +++ b/test/integration-tests/user/userMoveAdminContractTest.js @@ -11,6 +11,8 @@ const BaseOrg = require('../../../src/model/baseorg') const BaseUser = require('../../../src/model/baseuser') const Audit = require('../../../src/model/audit') const BaseUserRepository = require('../../../src/repositories/baseUserRepository') +const BaseOrgRepository = require('../../../src/repositories/baseOrgRepository') +const authContext = require('../../../src/utils/authContext') function userPath (org, user, registry = true) { return `/api/${registry ? 'registry/' : ''}org/${org.short_name}/user/${encodeURIComponent(user.username)}` @@ -27,10 +29,14 @@ describe('Organization moves clear ADMIN in both API formats', () => { let userUUIDs let sandbox - async function createOrg () { + async function createOrg (root = false) { const shortName = `move_admin_${uuidv4().slice(0, 8)}` const response = await chai.request(app).post('/api/registry/org').set(constants.headers).send({ - short_name: shortName, long_name: shortName, authority: ['CNA'], disabled: false, id_quota: 100 + short_name: shortName, + long_name: shortName, + authority: [root ? 'ROOT' : 'CNA'], + disabled: false, + ...(root ? { is_top_level_root: false } : { id_quota: 100 }) }) expect(response, JSON.stringify(response.body)).to.have.status(200) orgUUIDs.push(response.body.created.UUID) @@ -48,8 +54,8 @@ describe('Organization moves clear ADMIN in both API formats', () => { return response.body.created } - function moveUser (user, registry, extra = {}) { - const request = chai.request(app).put(userPath(source, user, registry)).set(constants.headers) + function moveUser (user, registry, extra = {}, headers = constants.headers) { + const request = chai.request(app).put(userPath(source, user, registry)).set(headers) return registry ? request.send({ username: user.username, status: user.status, org_short_name: destination.short_name, ...extra }) : request.query({ org_short_name: destination.short_name, ...extra }) @@ -114,6 +120,267 @@ describe('Organization moves clear ADMIN in both API formats', () => { await Audit.deleteMany({ target_uuid: { $in: orgUUIDs } }) }) + describe('Root admin creation and moves', () => { + let root + let branch + let ancestor + let outside + let admin + let headers + + async function relate (parent, child) { + const response = await chai.request(app) + .post(`/api/registry/org/${parent.short_name}/oversees/${child.short_name}/add`).set(constants.headers) + expect(response).to.have.status(200) + } + + async function createAsRoot (org, extra = {}, requestHeaders = headers, registry = true) { + const response = await chai.request(app) + .post(`/api/${registry ? 'registry/' : ''}org/${org.short_name}/user`).set(requestHeaders) + .send({ username: `root-created-${uuidv4()}@example.org`, status: 'active', ...extra }) + if (response.body.created?.UUID) userUUIDs.push(response.body.created.UUID) + return response + } + + async function snapshot (user) { + return { + orgs: await BaseOrg.find({ UUID: { $in: orgUUIDs } }).sort({ UUID: 1 }).read('primary').lean(), + user: user ? await BaseUser.findOne({ UUID: user.UUID }).read('primary').lean() : null, + audits: await Audit.find({ target_uuid: { $in: orgUUIDs } }).sort({ _id: 1 }).read('primary').lean(), + userCount: await BaseUser.countDocuments().read('primary') + } + } + + async function denyMove (user, extra = {}, requestHeaders = headers, registry = true, status = 403) { + const before = await snapshot(user) + const response = await moveUser(user, registry, extra, requestHeaders) + expect(response, JSON.stringify(response.body)).to.have.status(status) + expect(await snapshot(user)).to.deep.equal(before) + return response + } + + beforeEach(async () => { + root = await createOrg(true) + branch = await createOrg(true) + ancestor = await createOrg(true) + outside = await createOrg() + await relate(ancestor, root) + await relate(root, source) + await relate(root, branch) + await relate(branch, destination) + admin = await createUser(root, true, true) + headers = userHeaders(root, admin) + }) + + it('creates regular and ADMIN users in its own organization and descendants with audit attribution', async () => { + for (const [org, role] of [[root, ''], [source, ''], [branch, 'ADMIN'], [destination, 'ADMIN']]) { + const response = await createAsRoot(org, role ? { role } : {}) + expect(response, JSON.stringify(response.body)).to.have.status(200) + const user = response.body.created + expect(user.secret).to.be.a('string') + const stored = await BaseOrg.findOne({ UUID: org.UUID }).read('primary').lean() + expect(stored.users).to.include(user.UUID) + expect(stored.admins.includes(user.UUID)).to.equal(role === 'ADMIN') + const audit = await Audit.findOne({ target_uuid: org.UUID }).read('primary').lean() + expect(audit.history.at(-1).change_author).to.equal(admin.UUID) + expect(audit.history.at(-1).audit_object.users).to.include(user.UUID) + } + }) + + it('retains duplicate-user and capacity validation for Root creation', async () => { + await BaseOrg.updateOne({ UUID: source.UUID }, { $set: { user_quota: 1 } }) + const existing = await createUser(source, true, false) + const before = await snapshot(existing) + const duplicate = await createAsRoot(source, { username: existing.username }) + expect(duplicate).to.have.status(400) + expect(duplicate.body.error).to.equal('USER_EXISTS') + expect(await snapshot(existing)).to.deep.equal(before) + const full = await createAsRoot(source) + expect(full).to.have.status(400) + expect(full.body.error).to.equal('NUMBER_OF_USERS_IN_ORG_LIMIT_REACHED') + expect(await snapshot(existing)).to.deep.equal(before) + }) + + it('denies creation for ordinary Root users and targets outside the subtree without writes', async () => { + const regular = await createUser(root, true, false) + const before = await snapshot(regular) + expect(await createAsRoot(source, {}, userHeaders(root, regular))).to.have.status(403) + for (const org of [ancestor, outside]) expect(await createAsRoot(org)).to.have.status(403) + expect(await snapshot(regular)).to.deep.equal(before) + }) + + it('moves between direct and nested descendants, clears ADMIN, and audits both organizations', async () => { + const user = await createUser(source, true, true) + await BaseOrg.collection.updateOne({ UUID: destination.UUID }, { $push: { admins: user.UUID } }) + const original = await BaseUser.findOne({ UUID: user.UUID }).read('primary').lean() + const response = await moveUser(user, true, { role: 'ADMIN' }, headers) + expectMoveResponse(response, true) + await assertMoved(user) + expect(response.body).to.have.all.keys('message', 'updated') + expect(response.body.updated).to.not.have.property('secret') + const stored = await BaseUser.findOne({ UUID: user.UUID }).read('primary').lean() + expect(stored.secret).to.equal(original.secret) + expect(stored.UUID).to.equal(original.UUID) + for (const org of [source, destination]) { + const audit = await Audit.findOne({ target_uuid: org.UUID }).read('primary').lean() + expect(audit.history.at(-1).change_author).to.equal(admin.UUID) + expect(audit.history.at(-1).audit_object.users.includes(user.UUID)).to.equal(org.UUID === destination.UUID) + } + }) + + it('moves users into and out of its own organization and a nested Root', async () => { + const leaf = destination + source = root + destination = branch + const user = await createUser(source, true, false) + expectMoveResponse(await moveUser(user, true, {}, headers), true) + await assertMoved(user) + source = branch + destination = leaf + expectMoveResponse(await moveUser(user, true, {}, headers), true) + source = leaf + destination = root + expectMoveResponse(await moveUser(user, true, {}, headers), true) + await assertMoved(user) + }) + + it('denies moves when either actual endpoint is outside the Root subtree', async () => { + const inside = source + for (const external of [outside, ancestor]) { + source = external + const user = await createUser(source, true, false) + await denyMove(user) + source = inside + const insideUser = await createUser(source, true, false) + await denyMove(insideUser, { org_short_name: external.short_name }) + } + }) + + it('denies ordinary Root users and preserves legacy create and move permissions', async () => { + const user = await createUser(source, true, false) + const regular = await createUser(root, true, false) + await denyMove(user, {}, userHeaders(root, regular)) + await denyMove(user, {}, headers, false) + expect(await createAsRoot(source, {}, headers, false)).to.have.status(403) + }) + + it('revokes creation and move permissions after ADMIN, ROOT, or oversight removal', async () => { + const user = await createUser(source, true, false) + for (const update of [ + { $set: { admins: [] } }, + { $set: { authority: ['CNA'] } }, + { $set: { oversees: [] } } + ]) { + const original = await BaseOrg.findOne({ UUID: root.UUID }).read('primary').lean() + await BaseOrg.collection.updateOne({ UUID: root.UUID }, update) + const before = await snapshot(user) + expect(await createAsRoot(source)).to.have.status(403) + await denyMove(user) + expect(await snapshot(user)).to.deep.equal(before) + await BaseOrg.collection.updateOne({ UUID: root.UUID }, { + $set: { admins: original.admins, authority: original.authority, oversees: original.oversees } + }) + } + }) + + it('rejects bundled profile changes or omissions while allowing an unchanged full profile', async () => { + const user = await createUser(source, true, false) + const name = { first: 'Existing', last: 'User' } + await BaseUser.updateOne({ UUID: user.UUID }, { $set: { name } }) + for (const extra of [ + { name, username: 'renamed-user' }, + { name, status: 'inactive' }, + { name: { first: 'Changed', last: 'User' } }, + { name, 'name.first': 'Changed' }, + {} + ]) { + await denyMove(user, extra, headers, true, 400) + } + expectMoveResponse(await moveUser(user, true, { name }, headers), true) + const stored = await BaseUser.findOne({ UUID: user.UUID }).read('primary').lean() + expect(stored.name).to.deep.equal(name) + }) + + it('retains a source-organization admin\'s permission to edit a profile while moving it', async () => { + source = root + const user = await createUser(source, true, false) + const name = { first: 'Updated', last: 'User' } + expectMoveResponse(await moveUser(user, true, { name }, headers), true) + expect((await BaseUser.findOne({ UUID: user.UUID }).read('primary').lean()).name).to.deep.equal(name) + await assertMoved(user) + }) + + it('does not grant cross-organization profile editing, role management, deletion, or secret reset', async () => { + const user = await createUser(source, true, false) + const path = userPath(source, user) + const before = await snapshot(user) + expect(await chai.request(app).put(path).set(headers).send({ username: user.username, status: 'inactive' })).to.have.status(403) + expect(await chai.request(app).post(`${path}/grant-role`).set(headers).send({ role: 'ADMIN' })).to.have.status(403) + expect(await chai.request(app).put(`${path}/reset_secret`).set(headers)).to.have.status(403) + expect(await chai.request(app).delete(path).set(headers)).to.have.status(403) + expect(await snapshot(user)).to.deep.equal(before) + }) + + it('preserves missing-destination and same-organization move errors', async () => { + const user = await createUser(source, true, true) + const same = await denyMove(user, { org_short_name: source.short_name }) + expect(same.body.error).to.equal('USER_ALREADY_IN_ORG') + const missing = await denyMove(user, { org_short_name: 'missing-root-destination' }, headers, true, 404) + expect(missing.body.error).to.equal('ORG_DNE_PARAM') + }) + + it('rolls back membership, ADMIN, user data, and audits after a Root move fails', async () => { + const user = await createUser(source, true, true) + const original = BaseUserRepository.prototype.updateUserFull + let wroteMove = false + sandbox.stub(BaseUserRepository.prototype, 'updateUserFull').callsFake(async function (...args) { + await original.apply(this, args) + wroteMove = true + throw new Error('Simulated Root move persistence failure') + }) + await denyMove(user, {}, headers, true, 500) + expect(wroteMove).to.equal(true) + }) + + it('rejects a user whose actual owning organization changes before the move transaction', async () => { + const user = await createUser(source, true, false) + const original = authContext.isRequesterRootAdminOfOrgs + let afterExternalMove + sandbox.stub(authContext, 'isRequesterRootAdminOfOrgs').callsFake(async function (...args) { + const allowed = await original.apply(this, args) + if (!args[4]?.session) { + await BaseOrg.updateOne({ UUID: source.UUID }, { $pull: { users: user.UUID } }) + await BaseOrg.updateOne({ UUID: outside.UUID }, { $addToSet: { users: user.UUID } }) + afterExternalMove = await snapshot(user) + } + return allowed + }) + const response = await moveUser(user, true, {}, headers) + expect(response).to.have.status(403) + expect(afterExternalMove).to.be.an('object') + expect(await snapshot(user)).to.deep.equal(afterExternalMove) + }) + + it('authorizes the destination resolved inside the transaction if its short name is reassigned', async () => { + const user = await createUser(source, true, false) + const original = BaseOrgRepository.prototype.findOneByShortName + let afterRename + sandbox.stub(BaseOrgRepository.prototype, 'findOneByShortName').callsFake(async function (...args) { + const org = await original.apply(this, args) + if (args[0] === destination.short_name && !args[1]?.session && !afterRename) { + await BaseOrg.updateOne({ UUID: destination.UUID }, { $set: { short_name: `renamed_${uuidv4().slice(0, 8)}` } }) + await BaseOrg.updateOne({ UUID: outside.UUID }, { $set: { short_name: destination.short_name } }) + afterRename = await snapshot(user) + } + return org + }) + const response = await moveUser(user, true, {}, headers) + expect(response).to.have.status(403) + expect(afterRename).to.be.an('object') + expect(await snapshot(user)).to.deep.equal(afterRename) + }) + }) + for (const registry of [false, true]) { const api = registry ? 'registry' : 'legacy' diff --git a/test/unit-tests/utils/authContextTest.js b/test/unit-tests/utils/authContextTest.js index d8e62f10b..744321eef 100644 --- a/test/unit-tests/utils/authContextTest.js +++ b/test/unit-tests/utils/authContextTest.js @@ -173,4 +173,65 @@ describe('Testing authContext requester helpers', () => { ['admin-user', 'target-org', options, true] ]) }) + + describe('Root admin write scope', () => { + beforeEach(() => { + Object.assign(req.ctx, { authenticated: true, orgUUID: 'root', userUUID: 'admin' }) + orgRepo.findOneByUUID.resolves({ UUID: 'root', authority: ['ROOT'] }) + orgRepo.getOrgHierarchy = sinon.stub().resolves([{ + UUID: 'ancestor', + authority: ['ROOT'], + children: [{ + UUID: 'root', + authority: ['ROOT'], + children: [{ + UUID: 'branch', + authority: ['ROOT'], + children: [{ UUID: 'leaf', children: [] }] + }] + }, { UUID: 'peer', children: [] }] + }]) + }) + + it('allows own organization and direct and nested descendants together', async () => { + const targets = ['root', 'branch', 'leaf'].map(UUID => ({ UUID })) + expect(await authContext.isRequesterRootAdminOfOrgs(req, userRepo, orgRepo, targets)).to.equal(true) + }) + + it('rejects a move if either endpoint is outside the Root subtree', async () => { + for (const UUID of ['ancestor', 'peer', 'unrelated']) { + for (const targets of [[{ UUID }, { UUID: 'leaf' }], [{ UUID: 'leaf' }, { UUID }]]) { + expect(await authContext.isRequesterRootAdminOfOrgs(req, userRepo, orgRepo, targets)).to.equal(false) + } + } + }) + + it('requires authenticated identity and authoritative ADMIN and ROOT membership', async () => { + const targets = [{ UUID: 'leaf' }] + req.ctx.authenticated = false + expect(await authContext.isRequesterRootAdminOfOrgs(req, userRepo, orgRepo, targets)).to.equal(false) + req.ctx.authenticated = true + userRepo.isUserAdminOfOrgUUID.resolves(false) + expect(await authContext.isRequesterRootAdminOfOrgs(req, userRepo, orgRepo, targets)).to.equal(false) + userRepo.isUserAdminOfOrgUUID.resolves(true) + orgRepo.findOneByUUID.resolves({ UUID: 'root', authority: ['CNA'] }) + expect(await authContext.isRequesterRootAdminOfOrgs(req, userRepo, orgRepo, targets)).to.equal(false) + }) + + it('fails closed for missing targets and missing hierarchy', async () => { + for (const targets of [[], [null], [{}]]) { + expect(await authContext.isRequesterRootAdminOfOrgs(req, userRepo, orgRepo, targets)).to.equal(false) + } + orgRepo.getOrgHierarchy.resolves([]) + expect(await authContext.isRequesterRootAdminOfOrgs(req, userRepo, orgRepo, [{ UUID: 'leaf' }])).to.equal(false) + }) + + it('uses the transaction snapshot instead of a cached read hierarchy', async () => { + req.ctx.orgHierarchyCache = { scopes: new Map([['root', [{ UUID: 'root', children: [{ UUID: 'old-child', children: [] }] }]]]) } + const options = { session: 'transaction-session' } + expect(await authContext.isRequesterRootAdminOfOrgs(req, userRepo, orgRepo, [{ UUID: 'old-child' }], options)).to.equal(false) + expect(orgRepo.getOrgHierarchy.calledWith('root', { ...options, readPreference: 'primary' })).to.equal(true) + expect(userRepo.isUserAdminOfOrgUUID.calledWith('admin', 'root', options, false)).to.equal(true) + }) + }) }) From cde2025b68ef588b64b3d6b61bf00c6444655f78 Mon Sep 17 00:00:00 2001 From: David T Rocca Date: Mon, 23 Nov 2026 12:38:07 -0500 Subject: [PATCH 12/19] Allow Root admins to grant and revoke ADMIN in descendant organizations --- README.md | 4 +- api-docs/openapi.json | 10 ++--- src/controller/registry.controller/index.js | 16 +++---- .../user.registry.controller.js | 40 ++++++++--------- .../user/userMoveAdminContractTest.js | 43 +++++++++++++++++-- 5 files changed, 70 insertions(+), 43 deletions(-) diff --git a/README.md b/README.md index 695612939..92ff673e6 100644 --- a/README.md +++ b/README.md @@ -229,7 +229,9 @@ Use the organization and username from either row above to try these requests: | `GET /api/registry/org/window_1/user/ashleyruiz@window_1.com` | The specified descendant user. | | `GET /api/registry/org/top_root_2` | `403`: outside both Roots' oversight. | -The `top_root_1` accounts can also read `root_1_4` and its users. The `root_1_4` accounts receive `403` when reading ancestor organization `top_root_1` or sibling Root `root_1_3`. Organization lists exclude those records as well. Root oversight does not grant access to the global user list or permission to write to descendant organizations and users. Secretariat continues to receive the complete organization list. +The `top_root_1` accounts can also read `root_1_4` and its users. The `root_1_4` accounts receive `403` when reading ancestor organization `top_root_1` or sibling Root `root_1_3`. Organization lists exclude those records as well. Secretariat continues to receive the complete organization list. + +Both demo administrators can grant or revoke `ADMIN` for users in `window_1`. Send `POST /api/registry/org/window_1/user/{username}/grant-role` or `POST /api/registry/org/window_1/user/{username}/revoke-role` with the JSON body `{"role":"ADMIN"}`. This permission covers the administrator's own Root and all its direct and indirect descendants. Attempting to revoke one's own `ADMIN` role returns `403`. ### API Documentation diff --git a/api-docs/openapi.json b/api-docs/openapi.json index f14974cc8..03314cace 100644 --- a/api-docs/openapi.json +++ b/api-docs/openapi.json @@ -3708,7 +3708,7 @@ "Data Registry — Organizations" ], "summary": "Retrieves registry organization information by short name or UUID (same-organization users, overseeing Root users, or Secretariat)", - "description": "

Related legacy endpoint: GET /org/{shortname}. Data Registry responses use long_name and an authority array; legacy responses use name and authority.active_roles.

Access Control

Authenticated users can access their own organization. Ordinary users and administrators in an organization with ROOT authority can also access direct and indirect descendants, including organizations beneath subordinate Roots, using current reporting relationships. Secretariat users can access any organization. Root oversight does not grant write or administrator permissions.

Expected Behavior

Regular, CNA & Admin Users: Retrieves registry organization record for the specified shortname or UUID if it is the user's organization

Secretariat: Retrieves information about any registry organization

The reports_to, top_level_root, and oversees relationship fields contain organization short names.

The _hierarchy array contains the ancestor path from the top-level Root to the requested organization and that organization's complete subtree. Ancestors include only the child on that path and do not grant access to ancestor organization or user records. Siblings and unrelated branches remain outside Root oversight. Nodes contain UUID, short_name, long_name, authority, and children. ROOT nodes also contain is_top_level_root, and CNA nodes contain is_last_resort. An organization without a parent begins its own tree.

", + "description": "

Related legacy endpoint: GET /org/{shortname}. Data Registry responses use long_name and an authority array; legacy responses use name and authority.active_roles.

Access Control

Authenticated users can access their own organization. Ordinary users and administrators in an organization with ROOT authority can also access direct and indirect descendants, including organizations beneath subordinate Roots, using current reporting relationships. Secretariat users can access any organization.

Expected Behavior

Regular, CNA & Admin Users: Retrieves registry organization record for the specified shortname or UUID if it is the user's organization

Secretariat: Retrieves information about any registry organization

The reports_to, top_level_root, and oversees relationship fields contain organization short names.

The _hierarchy array contains the ancestor path from the top-level Root to the requested organization and that organization's complete subtree. Ancestors include only the child on that path and do not grant access to ancestor organization or user records. Siblings and unrelated branches remain outside Root oversight. Nodes contain UUID, short_name, long_name, authority, and children. ROOT nodes also contain is_top_level_root, and CNA nodes contain is_last_resort. An organization without a parent begins its own tree.

", "operationId": "registryOrgSingle", "parameters": [ { @@ -4764,8 +4764,8 @@ "tags": [ "Data Registry — Users" ], - "summary": "Grants a role to a user (accessible to Secretariat or Org Admin)", - "description": "

Access Control

User must belong to an organization with the Secretariat role or be an Admin of the target organization

Expected Behavior

Admin User: Grants a role to a user in the Admin's organization

Secretariat: Grants a role to a user in any organization

", + "summary": "Grants the ADMIN role to a registry user", + "description": "

Access Control

Secretariat can grant ADMIN in any organization. Organization admins can grant ADMIN in their own organization. Root admins can also grant ADMIN in direct and indirect descendants, including subordinate Roots and their descendants.

", "operationId": "registryUserGrantRole", "parameters": [ { @@ -4873,8 +4873,8 @@ "tags": [ "Data Registry — Users" ], - "summary": "Revokes a role from a user (accessible to Secretariat or Org Admin)", - "description": "

Access Control

User must belong to an organization with the Secretariat role or be an Admin of the target organization

Expected Behavior

Admin User: Revokes a role from a user in the Admin's organization

Secretariat: Revokes a role from a user in any organization

", + "summary": "Revokes the ADMIN role from a registry user", + "description": "

Access Control

Secretariat can revoke ADMIN in any organization. Organization admins can revoke ADMIN in their own organization. Root admins can also revoke ADMIN in direct and indirect descendants, including subordinate Roots and their descendants. Attempts to revoke your own ADMIN role return HTTP 403.

", "operationId": "registryUserRevokeRole", "parameters": [ { diff --git a/src/controller/registry.controller/index.js b/src/controller/registry.controller/index.js index 1195ec93d..df20f2b96 100644 --- a/src/controller/registry.controller/index.js +++ b/src/controller/registry.controller/index.js @@ -484,7 +484,7 @@ router.get('/registry/org/:identifier', #swagger.description = "

Related legacy endpoint: GET /org/{shortname}. Data Registry responses use long_name and an authority array; legacy responses use name and authority.active_roles.

Access Control

-

Authenticated users can access their own organization. Ordinary users and administrators in an organization with ROOT authority can also access direct and indirect descendants, including organizations beneath subordinate Roots, using current reporting relationships. Secretariat users can access any organization. Root oversight does not grant write or administrator permissions.

+

Authenticated users can access their own organization. Ordinary users and administrators in an organization with ROOT authority can also access direct and indirect descendants, including organizations beneath subordinate Roots, using current reporting relationships. Secretariat users can access any organization.

Expected Behavior

Regular, CNA & Admin Users: Retrieves registry organization record for the specified shortname or UUID if it is the user's organization

Secretariat: Retrieves information about any registry organization

@@ -1414,13 +1414,10 @@ router.post('/registry/org/:shortname/user/:username/grant-role', /* #swagger.tags = ['Data Registry — Users'] #swagger.operationId = 'registryUserGrantRole' - #swagger.summary = "Grants a role to a user (accessible to Secretariat or Org Admin)" + #swagger.summary = "Grants the ADMIN role to a registry user" #swagger.description = "

Access Control

-

User must belong to an organization with the Secretariat role or be an Admin of the target organization

-

Expected Behavior

-

Admin User: Grants a role to a user in the Admin's organization

-

Secretariat: Grants a role to a user in any organization

" +

Secretariat can grant ADMIN in any organization. Organization admins can grant ADMIN in their own organization. Root admins can also grant ADMIN in direct and indirect descendants, including subordinate Roots and their descendants.

" #swagger.parameters['shortname'] = { description: 'The shortname of the organization' } #swagger.parameters['username'] = { description: 'The username of the user' } #swagger.parameters['$ref'] = [ @@ -1492,13 +1489,10 @@ router.post('/registry/org/:shortname/user/:username/revoke-role', /* #swagger.tags = ['Data Registry — Users'] #swagger.operationId = 'registryUserRevokeRole' - #swagger.summary = "Revokes a role from a user (accessible to Secretariat or Org Admin)" + #swagger.summary = "Revokes the ADMIN role from a registry user" #swagger.description = "

Access Control

-

User must belong to an organization with the Secretariat role or be an Admin of the target organization

-

Expected Behavior

-

Admin User: Revokes a role from a user in the Admin's organization

-

Secretariat: Revokes a role from a user in any organization

" +

Secretariat can revoke ADMIN in any organization. Organization admins can revoke ADMIN in their own organization. Root admins can also revoke ADMIN in direct and indirect descendants, including subordinate Roots and their descendants. Attempts to revoke your own ADMIN role return HTTP 403.

" #swagger.parameters['shortname'] = { description: 'The shortname of the organization' } #swagger.parameters['username'] = { description: 'The username of the user' } #swagger.parameters['$ref'] = [ diff --git a/src/controller/registry.controller/user.registry.controller.js b/src/controller/registry.controller/user.registry.controller.js index bbfd2a8e1..4936f025f 100644 --- a/src/controller/registry.controller/user.registry.controller.js +++ b/src/controller/registry.controller/user.registry.controller.js @@ -472,6 +472,18 @@ async function deleteUser (req, res, next) { } } +async function getRoleChangeAuthorizationError (req, userRepo, orgRepo, targetOrg, options) { + if (await authContext.isRequesterSecretariat(req, orgRepo, options, REGISTRY_FORMAT)) return null + + if (await authContext.isRequesterSameOrg(req, orgRepo, targetOrg, options, REGISTRY_FORMAT)) { + const isAdmin = await authContext.isRequesterAdminOfOrg(req, userRepo, orgRepo, targetOrg, options, REGISTRY_FORMAT) + return isAdmin ? null : error.notOrgAdminOrSecretariatUpdate() + } + + const isOverseeingRootAdmin = await authContext.isRequesterRootAdminOfOrgs(req, userRepo, orgRepo, [targetOrg], options) + return isOverseeingRootAdmin ? null : error.notSameOrgOrSecretariat() +} + async function grantRole (req, res, next) { // Explicitly configuring causalConsistency flag for clear DocumentDB context documentation try { @@ -502,19 +514,11 @@ async function grantRole (req, res, next) { return res.status(404).json(error.orgDnePathParam(orgShortName)) } - const isSecretariat = await authContext.isRequesterSecretariat(req, orgRepo, { session }, REGISTRY_FORMAT) const targetOrg = { UUID: targetOrgUUID, short_name: orgShortName } - - const requesterSameOrg = await authContext.isRequesterSameOrg(req, orgRepo, targetOrg, { session }, REGISTRY_FORMAT) - if (!requesterSameOrg && !isSecretariat) { + const denial = await getRoleChangeAuthorizationError(req, userRepo, orgRepo, targetOrg, { session }) + if (denial) { await session.abortTransaction() - return res.status(403).json(error.notSameOrgOrSecretariat()) - } - - const isAdmin = await authContext.isRequesterAdminOfOrg(req, userRepo, orgRepo, targetOrg, { session }, REGISTRY_FORMAT) - if (!isSecretariat && !isAdmin) { - await session.abortTransaction() - return res.status(403).json(error.notOrgAdminOrSecretariatUpdate()) + return res.status(403).json(denial) } // Check if target user exists in target org @@ -577,19 +581,11 @@ async function revokeRole (req, res, next) { return res.status(404).json(error.orgDnePathParam(orgShortName)) } - const isSecretariat = await authContext.isRequesterSecretariat(req, orgRepo, { session }, REGISTRY_FORMAT) const targetOrg = { UUID: targetOrgUUID, short_name: orgShortName } - - const requesterSameOrg = await authContext.isRequesterSameOrg(req, orgRepo, targetOrg, { session }, REGISTRY_FORMAT) - if (!requesterSameOrg && !isSecretariat) { - await session.abortTransaction() - return res.status(403).json(error.notSameOrgOrSecretariat()) - } - - const isAdmin = await authContext.isRequesterAdminOfOrg(req, userRepo, orgRepo, targetOrg, { session }, REGISTRY_FORMAT) - if (!isSecretariat && !isAdmin) { + const denial = await getRoleChangeAuthorizationError(req, userRepo, orgRepo, targetOrg, { session }) + if (denial) { await session.abortTransaction() - return res.status(403).json(error.notOrgAdminOrSecretariatUpdate()) + return res.status(403).json(denial) } // Check if target user exists in target org diff --git a/test/integration-tests/user/userMoveAdminContractTest.js b/test/integration-tests/user/userMoveAdminContractTest.js index f2f72e65f..836e925ec 100644 --- a/test/integration-tests/user/userMoveAdminContractTest.js +++ b/test/integration-tests/user/userMoveAdminContractTest.js @@ -120,7 +120,7 @@ describe('Organization moves clear ADMIN in both API formats', () => { await Audit.deleteMany({ target_uuid: { $in: orgUUIDs } }) }) - describe('Root admin creation and moves', () => { + describe('Root admin user management', () => { let root let branch let ancestor @@ -142,6 +142,10 @@ describe('Organization moves clear ADMIN in both API formats', () => { return response } + function changeRole (org, user, action) { + return chai.request(app).post(`${userPath(org, user)}/${action}-role`).set(headers).send({ role: 'ADMIN' }) + } + async function snapshot (user) { return { orgs: await BaseOrg.find({ UUID: { $in: orgUUIDs } }).sort({ UUID: 1 }).read('primary').lean(), @@ -201,6 +205,36 @@ describe('Organization moves clear ADMIN in both API formats', () => { expect(await snapshot(existing)).to.deep.equal(before) }) + it('grants and revokes ADMIN in a subordinate Root and its descendant with audit attribution', async () => { + for (const org of [branch, destination]) { + const user = await createUser(org, true, false) + for (const action of ['grant', 'revoke']) { + const response = await changeRole(org, user, action) + expect(response, JSON.stringify(response.body)).to.have.status(200) + const stored = await BaseOrg.findOne({ UUID: org.UUID }).read('primary').lean() + expect(stored.admins.includes(user.UUID)).to.equal(action === 'grant') + const audit = await Audit.findOne({ target_uuid: org.UUID }).read('primary').lean() + expect(audit.history.at(-1).change_author).to.equal(admin.UUID) + expect(audit.history.at(-1).audit_object.admins.includes(user.UUID)).to.equal(action === 'grant') + } + } + }) + + it('denies role changes in ancestor and sibling organizations and preserves self-demotion protection', async () => { + await relate(ancestor, outside) + for (const org of [ancestor, outside]) { + const user = await createUser(org, true, false) + const before = await snapshot(user) + for (const action of ['grant', 'revoke']) { + expect(await changeRole(org, user, action)).to.have.status(403) + } + expect(await snapshot(user)).to.deep.equal(before) + } + const self = await changeRole(root, admin, 'revoke') + expect(self).to.have.status(403) + expect(self.body.error).to.equal('NOT_ALLOWED_TO_SELF_DEMOTE') + }) + it('denies creation for ordinary Root users and targets outside the subtree without writes', async () => { const regular = await createUser(root, true, false) const before = await snapshot(regular) @@ -264,7 +298,7 @@ describe('Organization moves clear ADMIN in both API formats', () => { expect(await createAsRoot(source, {}, headers, false)).to.have.status(403) }) - it('revokes creation and move permissions after ADMIN, ROOT, or oversight removal', async () => { + it('revokes creation, move, and role permissions after ADMIN, ROOT, or oversight removal', async () => { const user = await createUser(source, true, false) for (const update of [ { $set: { admins: [] } }, @@ -275,6 +309,8 @@ describe('Organization moves clear ADMIN in both API formats', () => { await BaseOrg.collection.updateOne({ UUID: root.UUID }, update) const before = await snapshot(user) expect(await createAsRoot(source)).to.have.status(403) + expect(await changeRole(source, user, 'grant')).to.have.status(403) + expect(await changeRole(source, user, 'revoke')).to.have.status(403) await denyMove(user) expect(await snapshot(user)).to.deep.equal(before) await BaseOrg.collection.updateOne({ UUID: root.UUID }, { @@ -310,12 +346,11 @@ describe('Organization moves clear ADMIN in both API formats', () => { await assertMoved(user) }) - it('does not grant cross-organization profile editing, role management, deletion, or secret reset', async () => { + it('does not grant cross-organization profile editing, deletion, or secret reset', async () => { const user = await createUser(source, true, false) const path = userPath(source, user) const before = await snapshot(user) expect(await chai.request(app).put(path).set(headers).send({ username: user.username, status: 'inactive' })).to.have.status(403) - expect(await chai.request(app).post(`${path}/grant-role`).set(headers).send({ role: 'ADMIN' })).to.have.status(403) expect(await chai.request(app).put(`${path}/reset_secret`).set(headers)).to.have.status(403) expect(await chai.request(app).delete(path).set(headers)).to.have.status(403) expect(await snapshot(user)).to.deep.equal(before) From 068f42ce05696b3a2213d1b3df95c8ca12eb1f44 Mon Sep 17 00:00:00 2001 From: David T Rocca Date: Mon, 23 Nov 2026 13:43:45 -0500 Subject: [PATCH 13/19] docs: clarify Root inclusion in registry organization pagination --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 92ff673e6..5a4343fee 100644 --- a/README.md +++ b/README.md @@ -221,7 +221,7 @@ Use the organization and username from either row above to try these requests: | Request | Expected result | | --- | --- | -| `GET /api/registry/org` | A flat, paginated list of all direct and indirect descendants, excluding the requesting Root itself. Counts and pages cover only those descendants. | +| `GET /api/registry/org` | The flat list and its pagination totals include the requesting Root and all its direct and indirect descendants. | | `GET /api/registry/org-hierarchy` | The requesting Root's subtree, with its ancestor path for context. | | `GET /api/registry/org/window_1` | The descendant organization's details. | | `GET /api/registry/org/window_1?expand=users` | The descendant organization with expanded user metadata. | From 2a670240630db7895d1417fbbb90253ce0d03428 Mon Sep 17 00:00:00 2001 From: David T Rocca Date: Mon, 23 Nov 2026 13:57:14 -0500 Subject: [PATCH 14/19] test: allow time for Root oversight fixture setup and teardown --- test/integration-tests/registry-org/rootReadAccessTest.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/test/integration-tests/registry-org/rootReadAccessTest.js b/test/integration-tests/registry-org/rootReadAccessTest.js index 8ca457478..e5832e1b8 100644 --- a/test/integration-tests/registry-org/rootReadAccessTest.js +++ b/test/integration-tests/registry-org/rootReadAccessTest.js @@ -13,6 +13,7 @@ const registryRouter = require('../../../src/controller/registry.controller') const secretariat = constants.headers const runId = uuidv4().slice(0, 8) +const fixtureTimeoutMs = 30000 function flatten (nodes) { return nodes.flatMap(node => [node, ...flatten(node.children)]) @@ -79,7 +80,8 @@ describe('Root oversight registry read access', () => { return response.body } - before(async () => { + before(async function () { + this.timeout(fixtureTimeoutMs) for (const label of ['top', 'root', 'branch', 'cna', 'peer', 'other']) { const isRoot = label !== 'cna' const response = await chai.request(app).post('/api/registry/org').set(secretariat).send({ @@ -128,7 +130,8 @@ describe('Root oversight registry read access', () => { } }) - after(async () => { + after(async function () { + this.timeout(fixtureTimeoutMs) await Conversation.deleteMany({ target_uuid: { $in: Object.values(orgs).map(org => org.UUID) } }) for (const user of createdUsers) { const response = await chai.request(app) From c078369a4c28b380d3beba6470f740a3857ccfd0 Mon Sep 17 00:00:00 2001 From: David T Rocca Date: Mon, 23 Nov 2026 14:34:52 -0500 Subject: [PATCH 15/19] test: allow time for Root oversight reassignment checks --- test/integration-tests/registry-org/rootReadAccessTest.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/integration-tests/registry-org/rootReadAccessTest.js b/test/integration-tests/registry-org/rootReadAccessTest.js index e5832e1b8..f557a2bde 100644 --- a/test/integration-tests/registry-org/rootReadAccessTest.js +++ b/test/integration-tests/registry-org/rootReadAccessTest.js @@ -373,7 +373,10 @@ describe('Root oversight registry read access', () => { expect(response.body.error).to.equal('USER_DNE') }) - it('uses current parent relationships after reassignment and removal', async () => { + it('uses current parent relationships after reassignment and removal', async function () { + // Each relationship change is followed by reads of organization and user endpoints. + this.timeout(10000) + try { await relate('other', 'branch') await expectReads(headers('root'), 'cna', 403) From 8399cbde58a1898c807b15b681858513a08bbda9 Mon Sep 17 00:00:00 2001 From: David T Rocca Date: Mon, 23 Nov 2026 14:39:01 -0500 Subject: [PATCH 16/19] Allow Root admins to edit descendant user profiles and reset API secrets --- api-docs/openapi.json | 8 +- .../org.controller/org.controller.js | 27 +++-- src/controller/registry.controller/index.js | 11 ++- .../user.registry.controller.js | 55 +++++------ .../user/userMoveAdminContractTest.js | 99 ++++++++++++++----- 5 files changed, 120 insertions(+), 80 deletions(-) diff --git a/api-docs/openapi.json b/api-docs/openapi.json index 03314cace..afe016c79 100644 --- a/api-docs/openapi.json +++ b/api-docs/openapi.json @@ -4109,8 +4109,8 @@ "tags": [ "Data Registry — Users" ], - "summary": "Updates a user (self, same-organization Admins, or Secretariat); Root Admins can move users within their hierarchy", - "description": "

Related legacy endpoint: PUT /org/{shortname}/user/{username}. This endpoint accepts updates through a JSON request body. The legacy endpoint uses query parameters and the legacy user schema.

Access Control

Authenticated users can update their own name fields. Organization admins can update users in their organization. Secretariat users can update users in any organization.

Expected Behavior

Regular User: Updates the user's own information. Only name fields may be changed.

Admin User: Updates information about a user in the Admin's organization. Allowed to change all fields except org_short_name.

Secretariat: Updates information about a user in any organization. Allowed to change all fields.

Root Admin: May supply org_short_name to move a user when both the source and destination are its own organization or descendants, including nested Roots. This permission does not grant profile editing in descendant organizations: supply the existing username, status, and all existing name fields unchanged. Source-organization Admins retain their existing profile-edit permissions. Ordinary Root users cannot move users.

Deactivation preserves assigned ADMIN membership while preventing authentication. Reactivation retains that assignment unless ADMIN was explicitly revoked or the user moved organizations. Omitting role from a profile update does not revoke ADMIN.

Moving a user to another organization removes ADMIN in both the source and destination. ADMIN requested in the move is not granted; promotion requires a separate authorized request after the move.

", + "summary": "Updates a user (self, same-organization Admins, overseeing Root Admins, or Secretariat)", + "description": "

Related legacy endpoint: PUT /org/{shortname}/user/{username}. This endpoint accepts updates through a JSON request body. The legacy endpoint uses query parameters and the legacy user schema.

Access Control

Authenticated users can update their own name fields. Organization admins can update users in their organization. Root admins can also update users in direct and indirect descendant organizations, including subordinate Roots. Secretariat users can update users in any organization.

Expected Behavior

Regular User: Updates the user's own information. Only name fields may be changed.

Admin User: Updates information about a user in the Admin's organization. Allowed to change all fields except org_short_name.

Secretariat: Updates information about a user in any organization. Allowed to change all fields.

Root Admin: May edit username, name, and status in a descendant organization. Use the grant-role and revoke-role endpoints for ADMIN changes. To move a user, both organizations must be within the Root's own subtree. When moving a user from a descendant organization, submit the current username, status, and all existing name fields. Submit profile changes in a separate request.

Deactivation preserves assigned ADMIN membership while preventing authentication. Reactivation retains that assignment unless ADMIN was explicitly revoked or the user moved organizations. Omitting role from a profile update does not revoke ADMIN.

Moving a user to another organization removes ADMIN in both the source and destination. ADMIN requested in the move is not granted; promotion requires a separate authorized request after the move.

", "operationId": "registryUserUpdateSingle", "parameters": [ { @@ -4451,8 +4451,8 @@ "tags": [ "Data Registry — Users" ], - "summary": "Reset the API key for a user (accessible to self, same-organization Admins, or Secretariat)", - "description": "

Related legacy endpoint: PUT /org/{shortname}/user/{username}/reset_secret.

Access Control

Authenticated users can reset their own API secret. Organization admins can reset users in their organization. Secretariat users can reset any user's API secret.

Expected Behavior

Regular User: Resets user's own API secret

Admin User: Resets any user's API secret in the Admin's organization

Secretariat: Resets any user's API secret

", + "summary": "Reset the API key for a user (self, same-organization Admins, overseeing Root Admins, or Secretariat)", + "description": "

Related legacy endpoint: PUT /org/{shortname}/user/{username}/reset_secret.

Access Control

Authenticated users can reset their own API secret. Organization admins can reset users in their organization. Root admins can also reset users in direct and indirect descendant organizations, including subordinate Roots. Secretariat users can reset any user's API secret.

Expected Behavior

Regular User: Resets user's own API secret

Admin User: Resets any user's API secret in the Admin's organization

Root Admin: Resets any user's API secret in an organization the Root oversees

Secretariat: Resets any user's API secret

", "operationId": "registryUserResetSecret", "parameters": [ { diff --git a/src/controller/org.controller/org.controller.js b/src/controller/org.controller/org.controller.js index 78cb3817c..bd40cc0d0 100644 --- a/src/controller/org.controller/org.controller.js +++ b/src/controller/org.controller/org.controller.js @@ -715,10 +715,11 @@ async function resetSecret (req, res, next) { const requesterUserUUID = await authContext.getRequesterUserUUID(req, userRepo, orgRepo, { session }, objectFormat) const isRequesterSecretariat = await authContext.isRequesterSecretariat(req, orgRepo, { session }, objectFormat) - if (!isRequesterSecretariat) { - const requesterSameOrg = await authContext.isRequesterSameOrg(req, orgRepo, targetOrg, { session }, objectFormat) - if (!requesterSameOrg) { - logger.info({ uuid: req.ctx.uuid, message: 'The api secret can only be reset by the Secretariat, an Org admin or if the requester is the user.' }) + const requesterSameOrg = !isRequesterSecretariat && await authContext.isRequesterSameOrg(req, orgRepo, targetOrg, { session }, objectFormat) + if (!isRequesterSecretariat && !requesterSameOrg) { + const overseesOrg = req.useRegistry && await authContext.isRequesterRootAdminOfOrgs(req, userRepo, orgRepo, [targetOrg], { session }) + if (!overseesOrg) { + logger.info({ uuid: req.ctx.uuid, message: 'API secret reset denied for the target organization.' }) await session.abortTransaction() return res.status(403).json(error.notSameOrgOrSecretariat()) } @@ -732,18 +733,12 @@ async function resetSecret (req, res, next) { return res.status(404).json(error.userDne(targetUsername)) } - if (!isRequesterSecretariat) { - // If they are in the same organization, they must be the target user themselves OR an admin of the target org. - // 1. WE are not the same user - if (requesterUserUUID !== targetUserUUID) { - // Check to see if we are the admin of the target organization - const isAdminOfTargetOrg = await authContext.isRequesterAdminOfOrg(req, userRepo, orgRepo, targetOrg, { session }, objectFormat) - - if (!isAdminOfTargetOrg) { - logger.info({ uuid: req.ctx.uuid, message: 'The api secret can only be reset by the Secretariat, an Org admin or if the requester is the user.' }) - await session.abortTransaction() - return res.status(403).json(error.notSameUserOrSecretariat()) - } + if (requesterSameOrg && requesterUserUUID !== targetUserUUID) { + const isAdminOfTargetOrg = await authContext.isRequesterAdminOfOrg(req, userRepo, orgRepo, targetOrg, { session }, objectFormat) + if (!isAdminOfTargetOrg) { + logger.info({ uuid: req.ctx.uuid, message: 'The api secret can only be reset by the Secretariat, an Org admin or if the requester is the user.' }) + await session.abortTransaction() + return res.status(403).json(error.notSameUserOrSecretariat()) } } diff --git a/src/controller/registry.controller/index.js b/src/controller/registry.controller/index.js index df20f2b96..d2ace7007 100644 --- a/src/controller/registry.controller/index.js +++ b/src/controller/registry.controller/index.js @@ -1079,16 +1079,16 @@ router.put('/registry/org/:shortname/user/:username', /* #swagger.tags = ['Data Registry — Users'] #swagger.operationId = 'registryUserUpdateSingle' - #swagger.summary = "Updates a user (self, same-organization Admins, or Secretariat); Root Admins can move users within their hierarchy" + #swagger.summary = "Updates a user (self, same-organization Admins, overseeing Root Admins, or Secretariat)" #swagger.description = "

Related legacy endpoint: PUT /org/{shortname}/user/{username}. This endpoint accepts updates through a JSON request body. The legacy endpoint uses query parameters and the legacy user schema.

Access Control

-

Authenticated users can update their own name fields. Organization admins can update users in their organization. Secretariat users can update users in any organization.

+

Authenticated users can update their own name fields. Organization admins can update users in their organization. Root admins can also update users in direct and indirect descendant organizations, including subordinate Roots. Secretariat users can update users in any organization.

Expected Behavior

Regular User: Updates the user's own information. Only name fields may be changed.

Admin User: Updates information about a user in the Admin's organization. Allowed to change all fields except org_short_name.

Secretariat: Updates information about a user in any organization. Allowed to change all fields.

-

Root Admin: May supply org_short_name to move a user when both the source and destination are its own organization or descendants, including nested Roots. This permission does not grant profile editing in descendant organizations: supply the existing username, status, and all existing name fields unchanged. Source-organization Admins retain their existing profile-edit permissions. Ordinary Root users cannot move users.

+

Root Admin: May edit username, name, and status in a descendant organization. Use the grant-role and revoke-role endpoints for ADMIN changes. To move a user, both organizations must be within the Root's own subtree. When moving a user from a descendant organization, submit the current username, status, and all existing name fields. Submit profile changes in a separate request.

Deactivation preserves assigned ADMIN membership while preventing authentication. Reactivation retains that assignment unless ADMIN was explicitly revoked or the user moved organizations. Omitting role from a profile update does not revoke ADMIN.

Moving a user to another organization removes ADMIN in both the source and destination. ADMIN requested in the move is not granted; promotion requires a separate authorized request after the move.

" #swagger.parameters['shortname'] = { description: 'The shortname of the organization' } @@ -1266,14 +1266,15 @@ router.put('/registry/org/:shortname/user/:username/reset_secret', /* #swagger.tags = ['Data Registry — Users'] #swagger.operationId = 'registryUserResetSecret' - #swagger.summary = "Reset the API key for a user (accessible to self, same-organization Admins, or Secretariat)" + #swagger.summary = "Reset the API key for a user (self, same-organization Admins, overseeing Root Admins, or Secretariat)" #swagger.description = "

Related legacy endpoint: PUT /org/{shortname}/user/{username}/reset_secret.

Access Control

-

Authenticated users can reset their own API secret. Organization admins can reset users in their organization. Secretariat users can reset any user's API secret.

+

Authenticated users can reset their own API secret. Organization admins can reset users in their organization. Root admins can also reset users in direct and indirect descendant organizations, including subordinate Roots. Secretariat users can reset any user's API secret.

Expected Behavior

Regular User: Resets user's own API secret

Admin User: Resets any user's API secret in the Admin's organization

+

Root Admin: Resets any user's API secret in an organization the Root oversees

Secretariat: Resets any user's API secret

" #swagger.parameters['shortname'] = { description: 'The shortname of the organization' } #swagger.parameters['username'] = { description: 'The username of the user' } diff --git a/src/controller/registry.controller/user.registry.controller.js b/src/controller/registry.controller/user.registry.controller.js index 4936f025f..29b0e2b09 100644 --- a/src/controller/registry.controller/user.registry.controller.js +++ b/src/controller/registry.controller/user.registry.controller.js @@ -214,11 +214,6 @@ async function updateUser (req, res, next) { return res.status(400).json(error.secretUpdateNotAllowed()) } - const requestingUserParameters = { - org: req.ctx.org, - username: req.ctx.user - } - const userToEditParameters = { org: req.ctx.params.shortname, username: req.ctx.params.username @@ -296,31 +291,7 @@ async function updateUser (req, res, next) { } const requesterSameOrg = await authContext.isRequesterSameOrg(req, orgRepo, org, {}, REGISTRY_FORMAT) - if (!isSecretariat && !isAdmin && !requesterSameOrg && !isRootMove) { - logger.info({ uuid: req.ctx.uuid, message: requestingUserParameters.org + ' user can only be updated by the user or admins of the same organization or the Secretariat.' }) - return res.status(403).json(error.notSameOrgOrSecretariat()) - } - - if (!isSecretariat && !isAdmin && !isRootMove) { - if (requesterUserUUID !== userToEdit?.UUID) { - if (!userToEdit) { - logger.info({ uuid: req.ctx.uuid, message: 'User DNE' }) - return res.status(404).json(error.userDne(userToEditParameters.username)) - } - logger.info({ uuid: req.ctx.uuid, message: 'Not same user or secretariat' }) - return res.status(403).json(error.notSameUserOrSecretariat()) - } - } - - if (!org) { - logger.info({ uuid: req.ctx.uuid, message: `Target organization ${userToEditParameters.org} does not exist.` }) - return res.status(404).json(error.orgDnePathParam(userToEditParameters.org)) - } - - if (!userToEdit) { - logger.info({ uuid: req.ctx.uuid, message: userToEditParameters.username + ' user could not be found.' }) - return res.status(404).json(error.userDne(userToEditParameters.username)) - } + const requiresProfileAuthorization = !isSecretariat && !isAdmin && !isRootMove let result let updatedUser let updatedUserUUID @@ -328,6 +299,21 @@ async function updateUser (req, res, next) { try { session.startTransaction({ readPreference: 'primary' }) + if (requiresProfileAuthorization && !requesterSameOrg) { + const overseesOrg = await authContext.isRequesterRootAdminOfOrgs(req, userRepo, orgRepo, [org], { session }) + if (!overseesOrg || (userToEdit && await orgRepo.getOrgUUIDByUserUUID(userToEdit.UUID, { session }) !== org.UUID)) { + logger.info({ uuid: req.ctx.uuid, message: 'Profile update denied for the target organization.' }) + await session.abortTransaction() + return res.status(403).json(error.notSameOrgOrSecretariat()) + } + } + + if (!userToEdit) { + logger.info({ uuid: req.ctx.uuid, message: userToEditParameters.username + ' user could not be found.' }) + await session.abortTransaction() + return res.status(404).json(error.userDne(userToEditParameters.username)) + } + if (isRootMove) { // The source may have changed after initial lookup. Recheck membership and // both endpoints in the same snapshot used by updateUserFull. @@ -355,8 +341,13 @@ async function updateUser (req, res, next) { } } - // if a user is NOT an ADMIN OR SECRETARIAT they can only update their name fields - if (!isSecretariat && !isAdmin && !isRootMove) { + if (requiresProfileAuthorization && requesterSameOrg) { + if (requesterUserUUID !== userToEdit.UUID) { + logger.info({ uuid: req.ctx.uuid, message: 'Not same user or secretariat' }) + await session.abortTransaction() + return res.status(403).json(error.notSameUserOrSecretariat()) + } + const allowedFields = ['name', 'name.first', 'name.last', 'name.middle', 'name.suffix'] const restrictedUpdates = _.omit(body, allowedFields) diff --git a/test/integration-tests/user/userMoveAdminContractTest.js b/test/integration-tests/user/userMoveAdminContractTest.js index 836e925ec..8fc5d342e 100644 --- a/test/integration-tests/user/userMoveAdminContractTest.js +++ b/test/integration-tests/user/userMoveAdminContractTest.js @@ -12,7 +12,6 @@ const BaseUser = require('../../../src/model/baseuser') const Audit = require('../../../src/model/audit') const BaseUserRepository = require('../../../src/repositories/baseUserRepository') const BaseOrgRepository = require('../../../src/repositories/baseOrgRepository') -const authContext = require('../../../src/utils/authContext') function userPath (org, user, registry = true) { return `/api/${registry ? 'registry/' : ''}org/${org.short_name}/user/${encodeURIComponent(user.username)}` @@ -146,6 +145,18 @@ describe('Organization moves clear ADMIN in both API formats', () => { return chai.request(app).post(`${userPath(org, user)}/${action}-role`).set(headers).send({ role: 'ADMIN' }) } + async function expectProfileAndResetDenied (org, user, requestHeaders = headers, registry = true) { + const path = userPath(org, user, registry) + const before = await snapshot(user) + const request = chai.request(app).put(path).set(requestHeaders) + const edit = registry + ? await request.send({ username: user.username, status: 'inactive' }) + : await request.query({ active: 'false' }) + expect(edit).to.have.status(403) + expect(await chai.request(app).put(`${path}/reset_secret`).set(requestHeaders)).to.have.status(403) + expect(await snapshot(user)).to.deep.equal(before) + } + async function snapshot (user) { return { orgs: await BaseOrg.find({ UUID: { $in: orgUUIDs } }).sort({ UUID: 1 }).read('primary').lean(), @@ -290,15 +301,17 @@ describe('Organization moves clear ADMIN in both API formats', () => { } }) - it('denies ordinary Root users and preserves legacy create and move permissions', async () => { + it('denies ordinary Root users and preserves legacy user management permissions', async () => { const user = await createUser(source, true, false) const regular = await createUser(root, true, false) await denyMove(user, {}, userHeaders(root, regular)) await denyMove(user, {}, headers, false) expect(await createAsRoot(source, {}, headers, false)).to.have.status(403) + await expectProfileAndResetDenied(source, user, userHeaders(root, regular)) + await expectProfileAndResetDenied(source, user, headers, false) }) - it('revokes creation, move, and role permissions after ADMIN, ROOT, or oversight removal', async () => { + it('revokes user management permissions after ADMIN, ROOT, or oversight removal', async () => { const user = await createUser(source, true, false) for (const update of [ { $set: { admins: [] } }, @@ -311,6 +324,7 @@ describe('Organization moves clear ADMIN in both API formats', () => { expect(await createAsRoot(source)).to.have.status(403) expect(await changeRole(source, user, 'grant')).to.have.status(403) expect(await changeRole(source, user, 'revoke')).to.have.status(403) + await expectProfileAndResetDenied(source, user) await denyMove(user) expect(await snapshot(user)).to.deep.equal(before) await BaseOrg.collection.updateOne({ UUID: root.UUID }, { @@ -346,12 +360,47 @@ describe('Organization moves clear ADMIN in both API formats', () => { await assertMoved(user) }) - it('does not grant cross-organization profile editing, deletion, or secret reset', async () => { + it('edits profiles in direct and nested descendants while preserving role assignments', async () => { + for (const [org, isAdmin] of [[branch, true], [destination, false]]) { + const user = await createUser(org, true, isAdmin) + const profile = { username: 'renamed-user', name: { first: 'Updated', last: 'User' }, status: 'inactive' } + const response = await chai.request(app).put(userPath(org, user)).set(headers).send({ ...profile, role: 'ADMIN' }) + expect(response).to.have.status(200) + expect(response.body.updated).to.deep.include({ ...profile, UUID: user.UUID }) + expect(response.body.updated).to.not.have.property('secret') + const stored = await BaseUser.findOne({ UUID: user.UUID }).read('primary').lean() + expect(stored).to.deep.include(profile) + const owner = await BaseOrg.findOne({ UUID: org.UUID }).read('primary').lean() + expect(owner.users).to.include(user.UUID) + expect(owner.admins.includes(user.UUID)).to.equal(isAdmin) + } + }) + + it('rotates API secrets for users in direct and nested descendants', async () => { + for (const org of [branch, destination]) { + const user = await createUser(org, true, false) + const path = userPath(org, user) + const response = await chai.request(app).put(`${path}/reset_secret`).set(headers) + expect(response).to.have.status(200) + expect(response.body).to.have.all.keys('API-secret') + expect(await chai.request(app).get(path).set(userHeaders(org, user))).to.have.status(401) + const credentials = userHeaders(org, { ...user, secret: response.body['API-secret'] }) + expect(await chai.request(app).get(path).set(credentials)).to.have.status(200) + } + }) + + it('denies profile edits and resets in ancestor, sibling, and unrelated organizations', async () => { + const sibling = await createOrg() + await relate(ancestor, sibling) + for (const org of [ancestor, sibling, outside]) { + await expectProfileAndResetDenied(org, await createUser(org, true, false)) + } + }) + + it('denies deletion in a descendant organization', async () => { const user = await createUser(source, true, false) const path = userPath(source, user) const before = await snapshot(user) - expect(await chai.request(app).put(path).set(headers).send({ username: user.username, status: 'inactive' })).to.have.status(403) - expect(await chai.request(app).put(`${path}/reset_secret`).set(headers)).to.have.status(403) expect(await chai.request(app).delete(path).set(headers)).to.have.status(403) expect(await snapshot(user)).to.deep.equal(before) }) @@ -377,24 +426,28 @@ describe('Organization moves clear ADMIN in both API formats', () => { expect(wroteMove).to.equal(true) }) - it('rejects a user whose actual owning organization changes before the move transaction', async () => { - const user = await createUser(source, true, false) - const original = authContext.isRequesterRootAdminOfOrgs - let afterExternalMove - sandbox.stub(authContext, 'isRequesterRootAdminOfOrgs').callsFake(async function (...args) { - const allowed = await original.apply(this, args) - if (!args[4]?.session) { - await BaseOrg.updateOne({ UUID: source.UUID }, { $pull: { users: user.UUID } }) - await BaseOrg.updateOne({ UUID: outside.UUID }, { $addToSet: { users: user.UUID } }) - afterExternalMove = await snapshot(user) - } - return allowed + for (const operation of ['move', 'profile edit']) { + it(`rejects a ${operation} if the user changes organization before the transaction`, async () => { + const user = await createUser(source, true, false) + const original = BaseOrgRepository.prototype.findOneByShortName + let afterExternalMove + sandbox.stub(BaseOrgRepository.prototype, 'findOneByShortName').callsFake(async function (...args) { + const org = await original.apply(this, args) + if (args[0] === source.short_name && !args[1]?.session && !afterExternalMove) { + await BaseOrg.updateOne({ UUID: source.UUID }, { $pull: { users: user.UUID } }) + await BaseOrg.updateOne({ UUID: outside.UUID }, { $addToSet: { users: user.UUID } }) + afterExternalMove = await snapshot(user) + } + return org + }) + const response = operation === 'move' + ? await moveUser(user, true, {}, headers) + : await chai.request(app).put(userPath(source, user)).set(headers).send({ username: user.username, status: 'inactive' }) + expect(response).to.have.status(403) + expect(afterExternalMove).to.be.an('object') + expect(await snapshot(user)).to.deep.equal(afterExternalMove) }) - const response = await moveUser(user, true, {}, headers) - expect(response).to.have.status(403) - expect(afterExternalMove).to.be.an('object') - expect(await snapshot(user)).to.deep.equal(afterExternalMove) - }) + } it('authorizes the destination resolved inside the transaction if its short name is reassigned', async () => { const user = await createUser(source, true, false) From 46de2d0075d04dd1a35f85126a168dd6608e8a4b Mon Sep 17 00:00:00 2001 From: David T Rocca Date: Tue, 1 Dec 2026 15:42:16 -0500 Subject: [PATCH 17/19] Bump CVE Services version to 2.10.0 --- 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 afe016c79..f19af78f8 100644 --- a/api-docs/openapi.json +++ b/api-docs/openapi.json @@ -1,7 +1,7 @@ { "openapi": "3.0.2", "info": { - "version": "2.9.4", + "version": "2.10.0", "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 71fb52283..2b72deaa4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "cve-services", - "version": "2.9.4", + "version": "2.10.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "cve-services", - "version": "2.9.4", + "version": "2.10.0", "license": "(CC0)", "dependencies": { "@cveproject/cve-validation-library": "github:CVEProject/cve-validation-library#v1.2.0", diff --git a/package.json b/package.json index dbda4624f..39a5c74b0 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "cve-services", "author": "Automation Working Group", - "version": "2.9.4", + "version": "2.10.0", "license": "(CC0)", "devDependencies": { "@faker-js/faker": "^10.5.0", From 15b10c7f41b7e43a9faf96a897e2f5b38a40e017 Mon Sep 17 00:00:00 2001 From: David T Rocca Date: Thu, 3 Dec 2026 09:51:20 -0500 Subject: [PATCH 18/19] Hide descendant CNA conversations from Root users and admins --- api-docs/openapi.json | 4 +- src/controller/registry.controller/index.js | 2 + .../org.registry.controller.js | 22 +++-- .../registry-org/rootReadAccessTest.js | 85 +++++++++++++++---- .../middleware/registryReadAccessTest.js | 22 ++++- .../org/registry/registryOrgGetSingleTest.js | 9 ++ 6 files changed, 117 insertions(+), 27 deletions(-) diff --git a/api-docs/openapi.json b/api-docs/openapi.json index f19af78f8..0023ed518 100644 --- a/api-docs/openapi.json +++ b/api-docs/openapi.json @@ -3058,7 +3058,7 @@ "Data Registry — Organizations" ], "summary": "Lists registry organizations for Secretariat or overseeing Root users", - "description": "

Related legacy endpoint: GET /org. Data Registry responses use long_name and an authority array; legacy responses use name and authority.active_roles.

Access Control

User must belong to an organization with SECRETARIAT or ROOT authority. Both ordinary Root users and Root administrators have access.

Expected Behavior

Secretariat: Retrieves information about all registry organizations.

Root and top-level Root users: Retrieves a flat list containing the requesting organization itself and all direct and indirect descendants, including subordinate Roots and organizations beneath them. Ancestors, sibling branches, and unrelated organizations are excluded. A Root without descendants receives only its own organization.

Results use existing non-Secretariat field filtering and are sorted by short_name. Pagination and totalCount apply only to organizations within the authorized scope. Authorization uses current ROOT authority and reporting relationships.

", + "description": "

Related legacy endpoint: GET /org. Data Registry responses use long_name and an authority array; legacy responses use name and authority.active_roles.

Access Control

User must belong to an organization with SECRETARIAT or ROOT authority. Both ordinary Root users and Root administrators have access.

Expected Behavior

Secretariat: Retrieves information about all registry organizations.

Root and top-level Root users: Retrieves a flat list containing the requesting organization itself and all direct and indirect descendants, including subordinate Roots and organizations beneath them. Ancestors, sibling branches, and unrelated organizations are excluded. A Root without descendants receives only its own organization.

Root users and administrators can read public conversation messages on their own organization. Descendant records omit the optional conversation field.

Results use existing non-Secretariat field filtering and are sorted by short_name. Pagination and totalCount apply only to organizations within the authorized scope. Authorization uses current ROOT authority and reporting relationships.

", "operationId": "registryOrgAll", "parameters": [ { @@ -3708,7 +3708,7 @@ "Data Registry — Organizations" ], "summary": "Retrieves registry organization information by short name or UUID (same-organization users, overseeing Root users, or Secretariat)", - "description": "

Related legacy endpoint: GET /org/{shortname}. Data Registry responses use long_name and an authority array; legacy responses use name and authority.active_roles.

Access Control

Authenticated users can access their own organization. Ordinary users and administrators in an organization with ROOT authority can also access direct and indirect descendants, including organizations beneath subordinate Roots, using current reporting relationships. Secretariat users can access any organization.

Expected Behavior

Regular, CNA & Admin Users: Retrieves registry organization record for the specified shortname or UUID if it is the user's organization

Secretariat: Retrieves information about any registry organization

The reports_to, top_level_root, and oversees relationship fields contain organization short names.

The _hierarchy array contains the ancestor path from the top-level Root to the requested organization and that organization's complete subtree. Ancestors include only the child on that path and do not grant access to ancestor organization or user records. Siblings and unrelated branches remain outside Root oversight. Nodes contain UUID, short_name, long_name, authority, and children. ROOT nodes also contain is_top_level_root, and CNA nodes contain is_last_resort. An organization without a parent begins its own tree.

", + "description": "

Related legacy endpoint: GET /org/{shortname}. Data Registry responses use long_name and an authority array; legacy responses use name and authority.active_roles.

Access Control

Authenticated users can access their own organization. Ordinary users and administrators in an organization with ROOT authority can also access direct and indirect descendants, including organizations beneath subordinate Roots, using current reporting relationships. Secretariat users can access any organization.

Expected Behavior

Regular, CNA & Admin Users: Retrieves registry organization record for the specified shortname or UUID if it is the user's organization

Secretariat: Retrieves information about any registry organization

Root users and administrators can read public conversation messages on their own organization. Descendant records omit the optional conversation field.

The reports_to, top_level_root, and oversees relationship fields contain organization short names.

The _hierarchy array contains the ancestor path from the top-level Root to the requested organization and that organization's complete subtree. Ancestors include only the child on that path and do not grant access to ancestor organization or user records. Siblings and unrelated branches remain outside Root oversight. Nodes contain UUID, short_name, long_name, authority, and children. ROOT nodes also contain is_top_level_root, and CNA nodes contain is_last_resort. An organization without a parent begins its own tree.

", "operationId": "registryOrgSingle", "parameters": [ { diff --git a/src/controller/registry.controller/index.js b/src/controller/registry.controller/index.js index d2ace7007..87cf14563 100644 --- a/src/controller/registry.controller/index.js +++ b/src/controller/registry.controller/index.js @@ -26,6 +26,7 @@ router.get('/registry/org',

Expected Behavior

Secretariat: Retrieves information about all registry organizations.

Root and top-level Root users: Retrieves a flat list containing the requesting organization itself and all direct and indirect descendants, including subordinate Roots and organizations beneath them. Ancestors, sibling branches, and unrelated organizations are excluded. A Root without descendants receives only its own organization.

+

Root users and administrators can read public conversation messages on their own organization. Descendant records omit the optional conversation field.

Results use existing non-Secretariat field filtering and are sorted by short_name. Pagination and totalCount apply only to organizations within the authorized scope. Authorization uses current ROOT authority and reporting relationships.

" #swagger.parameters['$ref'] = [ '#/components/parameters/pageQuery', @@ -488,6 +489,7 @@ router.get('/registry/org/:identifier',

Expected Behavior

Regular, CNA & Admin Users: Retrieves registry organization record for the specified shortname or UUID if it is the user's organization

Secretariat: Retrieves information about any registry organization

+

Root users and administrators can read public conversation messages on their own organization. Descendant records omit the optional conversation field.

The reports_to, top_level_root, and oversees relationship fields contain organization short names.

The _hierarchy array contains the ancestor path from the top-level Root to the requested organization and that organization's complete subtree. Ancestors include only the child on that path and do not grant access to ancestor organization or user records. Siblings and unrelated branches remain outside Root oversight. Nodes contain UUID, short_name, long_name, authority, and children. ROOT nodes also contain is_top_level_root, and CNA nodes contain is_last_resort. An organization without a parent begins its own tree.

" #swagger.parameters['expand'] = { diff --git a/src/controller/registry.controller/org.registry.controller.js b/src/controller/registry.controller/org.registry.controller.js index 94d06dda7..e78f5265f 100644 --- a/src/controller/registry.controller/org.registry.controller.js +++ b/src/controller/registry.controller/org.registry.controller.js @@ -146,9 +146,13 @@ async function getAllOrgs (req, res, next) { try { returnValue = await repo.getAllOrgs({ ...options }, REGISTRY_FORMAT, isSecretariat, orgUUIDs) - for (let i = 0; i < returnValue.organizations.length; i++) { - const conversation = await conversationRepo.getAllByTargetUUID(returnValue.organizations[i].UUID, isSecretariat) - returnValue.organizations[i].conversation = conversation?.length + for (const org of returnValue.organizations) { + if (!isSecretariat && org.UUID !== hierarchyScope) { + delete org.conversation + continue + } + const conversation = await conversationRepo.getAllByTargetUUID(org.UUID, isSecretariat) + org.conversation = conversation?.length ? (isSecretariat ? conversation : conversation.map(c => _.omit(c, NON_SECRETARIAT_CONVERSATION_FIELDS))) : undefined } @@ -295,12 +299,14 @@ async function getOrg (req, res, next) { isAdminOfRequestedOrg = await userRepo.isAdmin(req.ctx.user, returnValue.short_name, {}) } - // fetch conversation - const conversation = await conversationRepo.getAllByTargetUUID(returnValue.UUID, isSecretariat) - if (isSecretariat) { - returnValue.conversation = conversation?.length ? _.map(conversation, c => _.omit(c, ['__v', '_id', 'previous_conversation_uuid', 'next_conversation_uuid', 'target_uuid'])) : undefined + if (isSecretariat || reason === 'SAME_ORG') { + const conversation = await conversationRepo.getAllByTargetUUID(returnValue.UUID, isSecretariat) + const fieldsToOmit = isSecretariat + ? ['__v', '_id', 'previous_conversation_uuid', 'next_conversation_uuid', 'target_uuid'] + : NON_SECRETARIAT_CONVERSATION_FIELDS + returnValue.conversation = conversation?.length ? conversation.map(c => _.omit(c, fieldsToOmit)) : undefined } else { - returnValue.conversation = conversation?.length ? _.map(conversation, c => _.omit(c, NON_SECRETARIAT_CONVERSATION_FIELDS)) : undefined + delete returnValue.conversation } if (req.ctx.query?.expand === 'users') { diff --git a/test/integration-tests/registry-org/rootReadAccessTest.js b/test/integration-tests/registry-org/rootReadAccessTest.js index f557a2bde..53d2cedce 100644 --- a/test/integration-tests/registry-org/rootReadAccessTest.js +++ b/test/integration-tests/registry-org/rootReadAccessTest.js @@ -64,6 +64,21 @@ describe('Root oversight registry read access', () => { return response.body } + function expectPublicConversation (org, label) { + expect(org.conversation.map(message => message.body)).to.deep.equal([ + `${label} partner ${runId}`, `${label} public ${runId}` + ]) + const [partnerMessage, secretariatReply] = org.conversation + expect(partnerMessage.author_id).to.equal(users[`${label}Admin`].UUID) + expect(secretariatReply).to.not.have.property('author_id') + expect(secretariatReply).to.not.have.property('author_name') + for (const message of org.conversation) { + for (const field of ['_id', '__v', 'UUID', 'target_uuid', 'visibility', 'previous_conversation_uuid', 'next_conversation_uuid']) { + expect(message).to.not.have.property(field) + } + } + } + async function expectUserList (requestHeaders, labels, extraUsers = []) { const response = await chai.request(app).get('/api/registry/users').set(requestHeaders) expect(response).to.have.status(200) @@ -82,8 +97,8 @@ describe('Root oversight registry read access', () => { before(async function () { this.timeout(fixtureTimeoutMs) - for (const label of ['top', 'root', 'branch', 'cna', 'peer', 'other']) { - const isRoot = label !== 'cna' + for (const label of ['top', 'root', 'branch', 'cna', 'peer', 'other', 'secondCna']) { + const isRoot = !['cna', 'secondCna'].includes(label) const response = await chai.request(app).post('/api/registry/org').set(secretariat).send({ short_name: `read_${label}_${runId}`, long_name: `Root read access ${label}`, @@ -121,10 +136,13 @@ describe('Root oversight registry read access', () => { expect(peerOnly).to.have.status(200) users.peerOnly = peerOnly.body.created createdUsers.push({ shortName: orgs.peer.short_name, username: users.peerOnly.username }) - for (const label of ['root', 'cna']) { + for (const label of ['root', 'cna', 'secondCna']) { + const partnerMessage = await chai.request(app).post(`/api/conversation/target/${orgs[label].UUID}`) + .set(headers(label, true)).send({ body: `${label} partner ${runId}` }) + expect(partnerMessage).to.have.status(200) for (const visibility of ['public', 'private']) { const response = await chai.request(app).post(`/api/conversation/target/${orgs[label].UUID}`) - .set(secretariat).send({ visibility, body: `${visibility} Root list ${runId}` }) + .set(secretariat).send({ visibility, body: `${label} ${visibility} ${runId}` }) expect(response).to.have.status(200) } } @@ -171,6 +189,7 @@ describe('Root oversight registry read access', () => { expect(Object.keys(response.body._userMap)).to.have.members([users.cna.UUID, users.cnaAdmin.UUID]) expect(response.body._userMap[users.cna.UUID].org.short_name).to.equal(orgs.cna.short_name) expect(response.body).to.not.have.property('program_data') + expect(response.body).to.not.have.property('conversation') expect(JSON.stringify(response.body)).to.not.include(users.cna.secret) }) @@ -209,16 +228,40 @@ describe('Root oversight registry read access', () => { await expectUserList(headers('peer', admin), ['peer']) }) - it('applies non-Secretariat conversation filtering to own and descendant list entries', async () => { + it('shows public messages on the Root’s own record and omits descendant conversations', async () => { const payload = await expectOrgList(headers('root', admin), ['root', 'branch', 'cna']) - for (const label of ['root', 'cna']) { - const org = payload.organizations.find(org => org.UUID === orgs[label].UUID) - expect(org.conversation).to.have.lengthOf(1) - expect(org.conversation[0].body).to.equal(`public Root list ${runId}`) - for (const field of ['_id', '__v', 'UUID', 'target_uuid', 'visibility', 'previous_conversation_uuid', 'next_conversation_uuid', 'author_id', 'author_name']) { - expect(org.conversation[0]).to.not.have.property(field) - } + const own = payload.organizations.find(org => org.UUID === orgs.root.UUID) + expectPublicConversation(own, 'root') + const detail = await chai.request(app).get(`/api/registry/org/${orgs.root.short_name}`).set(headers('root', admin)) + expect(detail).to.have.status(200) + expect(detail.body.conversation).to.deep.equal(own.conversation) + for (const org of payload.organizations.filter(org => org.UUID !== own.UUID)) { + expect(org).to.not.have.property('conversation') + } + const direct = await chai.request(app).get(`/api/registry/org/${orgs.cna.UUID}`).set(headers('branch', admin)) + expect(direct).to.have.status(200) + expect(direct.body.UUID).to.equal(orgs.cna.UUID) + expect(direct.body).to.not.have.property('conversation') + }) + + it('keeps each CNA’s public conversation visible only on its own organization reads', async () => { + for (const label of ['cna', 'secondCna']) { + const own = await chai.request(app).get(`/api/registry/org/${orgs[label].UUID}`).set(headers(label, admin)) + expect(own).to.have.status(200) + expectPublicConversation(own.body, label) } + const other = await chai.request(app).get(`/api/registry/org/${orgs.secondCna.short_name}`).set(headers('cna', admin)) + expect(other).to.have.status(403) + const list = await chai.request(app).get('/api/registry/org').set(headers('cna', admin)) + expect(list).to.have.status(403) + }) + + it('delivers the Root’s public reply only to its own organization among the partners in the tree', async () => { + const inbox = await chai.request(app).get('/api/notification').set(headers('root', admin)) + expect(inbox).to.have.status(200) + const bodies = inbox.body.notifications.map(notification => notification.body) + expect(bodies).to.include(`root public ${runId}`) + expect(bodies).to.not.include(`cna public ${runId}`) }) it('retains legacy global user list and write restrictions', async () => { @@ -259,7 +302,7 @@ describe('Root oversight registry read access', () => { }) } - it('paginates and counts own and descendant users together', async () => { + it('paginates and counts organizations and users in the Root subtree', async () => { const paginatedApp = express() paginatedApp.set('query parser', 'extended') paginatedApp.use(middleware.createCtxAndReqUUID) @@ -271,6 +314,15 @@ describe('Root oversight registry read access', () => { paginatedApp.use(middleware.errorHandler) await withHttpServer(paginatedApp, async url => { + const page = await chai.request(url).get('/api/registry/org?page=1').set(headers('top')) + expect(page).to.have.status(200) + expect(page.body.totalCount).to.equal(5) + expect(page.body.nextPage).to.equal(2) + expect(page.body.organizations.map(org => org.UUID)).to.deep.equal([ + orgs.branch.UUID, orgs.cna.UUID, orgs.peer.UUID, orgs.root.UUID + ]) + page.body.organizations.forEach(org => expect(org).to.not.have.property('conversation')) + const returnedUUIDs = [] for (const page of [1, 2, 3]) { const response = await chai.request(url).get(`/api/registry/users?page=${page}`).set(headers('root')) @@ -355,8 +407,11 @@ describe('Root oversight registry read access', () => { await expectReads(headers('cna'), 'branch', 403) const hierarchy = await chai.request(app).get('/api/registry/org-hierarchy').set(headers('cna')) expect(hierarchy).to.have.status(403) - const list = await chai.request(app).get('/api/registry/org').set(headers('cna')) - expect(list).to.have.status(403) + const detail = await chai.request(app).get(`/api/registry/org/${orgs.cna.UUID}`).set(secretariat) + expect(detail).to.have.status(200) + expect(detail.body.conversation.map(message => message.body)).to.deep.equal([ + `cna partner ${runId}`, `cna public ${runId}`, `cna private ${runId}` + ]) for (const admin of [false, true]) { const userList = await chai.request(app).get('/api/registry/users').set(headers('cna', admin)) expect(userList).to.have.status(403) diff --git a/test/unit-tests/middleware/registryReadAccessTest.js b/test/unit-tests/middleware/registryReadAccessTest.js index 3542f36a4..9c38dcecc 100644 --- a/test/unit-tests/middleware/registryReadAccessTest.js +++ b/test/unit-tests/middleware/registryReadAccessTest.js @@ -7,7 +7,7 @@ const BaseOrgModel = require('../../../src/model/baseorg') const { ORG_HIERARCHY, ALL_ORGS } = require('../../../src/controller/registry.controller/org.registry.controller') describe('Registry read authorization', () => { - let req, res, next, orgRepo, find + let req, res, next, orgRepo, conversationRepo, find beforeEach(() => { const organizations = [ @@ -27,6 +27,7 @@ describe('Registry read authorization', () => { getAllOrgs: sinon.stub().resolves({ organizations: [] }), getOrgHierarchy: BaseOrgRepository.prototype.getOrgHierarchy } + conversationRepo = { getAllByTargetUUID: sinon.stub().resolves([]) } req = { ctx: { authenticated: true, @@ -37,7 +38,7 @@ describe('Registry read authorization', () => { query: {}, repositories: { getBaseOrgRepository: () => orgRepo, - getConversationRepository: () => ({ getAllByTargetUUID: sinon.stub().resolves([]) }) + getConversationRepository: () => conversationRepo } } } @@ -138,15 +139,27 @@ describe('Registry read authorization', () => { }) it('passes the authenticated Root UUID and its descendants to the organization list query', async () => { + orgRepo.getAllOrgs.resolves({ organizations: [{ UUID: 'root' }, { UUID: 'child', conversation: [{ body: 'Stored message' }] }] }) await middleware.authorizeRegistryHierarchyRead(req, res, next) await ALL_ORGS(req, res, next) expect(res.status.calledOnceWith(200)).to.equal(true) expect(orgRepo.getAllOrgs.firstCall.args[2]).to.equal(false) expect(orgRepo.getAllOrgs.firstCall.args[3]).to.have.members(['root', 'branch', 'child']) + expect(conversationRepo.getAllByTargetUUID.calledOnceWithExactly('root', false)).to.equal(true) + expect(res.json.firstCall.args[0].organizations[1]).to.deep.equal({ UUID: 'child' }) expect(find.calledOnce).to.equal(true) expect(orgRepo.findOneByShortName.called).to.equal(false) }) + it('skips conversation reads on an organization page containing only descendants', async () => { + orgRepo.getAllOrgs.resolves({ organizations: [{ UUID: 'child' }], currentPage: 2, totalCount: 3 }) + req.ctx.query.page = '2' + await middleware.authorizeRegistryHierarchyRead(req, res, next) + await ALL_ORGS(req, res, next) + expect(res.json.firstCall.args[0]).to.deep.equal({ organizations: [{ UUID: 'child' }], currentPage: 2, totalCount: 3 }) + expect(conversationRepo.getAllByTargetUUID.notCalled).to.equal(true) + }) + it('scopes a Root without descendants to its own organization', async () => { req.ctx.orgUUID = 'sibling' await middleware.authorizeRegistryHierarchyRead(req, res, next) @@ -174,11 +187,16 @@ describe('Registry read authorization', () => { it('preserves the Secretariat organization list without a descendant filter', async () => { orgRepo.findOneByUUID.withArgs('root').resolves({ UUID: 'root', authority: ['SECRETARIAT'] }) + orgRepo.getAllOrgs.resolves({ organizations: [{ UUID: 'child' }] }) + const messages = [{ body: 'Secretariat note', visibility: 'private' }] + conversationRepo.getAllByTargetUUID.resolves(messages) await middleware.authorizeRegistryHierarchyRead(req, res, next) await ALL_ORGS(req, res, next) expect(res.status.calledOnceWith(200)).to.equal(true) expect(orgRepo.getAllOrgs.firstCall.args[2]).to.equal(true) expect(orgRepo.getAllOrgs.firstCall.args[3]).to.equal(undefined) + expect(conversationRepo.getAllByTargetUUID.calledOnceWithExactly('child', true)).to.equal(true) + expect(res.json.firstCall.args[0].organizations[0].conversation).to.deep.equal(messages) expect(find.called).to.equal(false) }) }) diff --git a/test/unit-tests/org/registry/registryOrgGetSingleTest.js b/test/unit-tests/org/registry/registryOrgGetSingleTest.js index b0a188f82..675f4643b 100644 --- a/test/unit-tests/org/registry/registryOrgGetSingleTest.js +++ b/test/unit-tests/org/registry/registryOrgGetSingleTest.js @@ -154,6 +154,15 @@ describe('Testing the GET /registry/org/:identifier endpoint in Registry Org Con expect(json.firstCall.args[0]).to.not.have.property('_relatedOrganizations') }) + it('omits stored conversation data and skips the conversation query for an overseeing Root', async () => { + req.ctx.registryRead = { targetOrg, isSecretariat: false, reason: 'PARENT_ORG' } + orgRepo.getOrg.resolves({ ...targetOrg, conversation: conversations }) + await SINGLE_ORG(req, res, next) + expect(status.calledOnceWithExactly(200)).to.be.true + expect(json.firstCall.args[0]).to.not.have.property('conversation') + expect(conversationRepo.getAllByTargetUUID.notCalled).to.be.true + }) + it('does not query a hierarchy for an organization that does not exist', async () => { orgRepo.getOrg.resolves(null) From c9aecfe63c6915ab3eda2c277d208110fadcbffd Mon Sep 17 00:00:00 2001 From: David T Rocca Date: Thu, 3 Dec 2026 10:30:56 -0500 Subject: [PATCH 19/19] Allow 30 seconds for advisory location migration tests --- .../registry-org/advisoryLocationsTextTest.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/integration-tests/registry-org/advisoryLocationsTextTest.js b/test/integration-tests/registry-org/advisoryLocationsTextTest.js index 2956b3d21..60e3e57cc 100644 --- a/test/integration-tests/registry-org/advisoryLocationsTextTest.js +++ b/test/integration-tests/registry-org/advisoryLocationsTextTest.js @@ -13,7 +13,8 @@ const shortName = `advisory_text_${randomUUID().slice(0, 8)}` const headers = { ...constants.headers, 'content-type': 'application/json' } describe('Advisory locations text', () => { - context('Migration', () => { + context('Migration', function () { + this.timeout(30000) let db before(async () => {