Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pull out constants into a function to prevent accidental overriding #934

Merged
merged 2 commits into from
Dec 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
175 changes: 98 additions & 77 deletions src/constants/index.js
Original file line number Diff line number Diff line change
@@ -1,82 +1,103 @@
const fs = require('fs')
const cveSchemaV5 = JSON.parse(fs.readFileSync('src/middleware/5.0_bundled_schema.json'))

module.exports = {
MONGOOSE_VALIDATION: {
Org_policies_id_quota_min: 0,
Org_policies_id_quota_min_message: 'Org.policies.id_quota cannot be a negative number.',
Org_policies_id_quota_max: 100000,
Org_policies_id_quota_max_message: 'Org.policies.id_quota cannot exceed maximum threshold.'
},
DEFAULT_ID_QUOTA: 1000,
DEFAULT_AVAILABLE_POOL: 100,
NONSEQUENTIAL_MAX_AMOUNT: 10,
CRYPTO_RANDOM_STRING_LENGTH: 36,
AUTH_ROLE_ENUM: {
SECRETARIAT: 'SECRETARIAT',
CNA: 'CNA',
ROOT_CNA: 'ROOT_CNA',
ADP: 'ADP'
},
ORG_ROLES: [
'CNA',
'SECRETARIAT',
'ROOT_CNA',
'ADP'
],
USER_ROLES: [
'ADMIN'
],
USER_ROLE_ENUM: {
ADMIN: 'ADMIN'
},
AUTH_HEADERS: {
ORG: 'CVE-API-ORG',
USER: 'CVE-API-USER',
KEY: 'CVE-API-KEY'
},
CVE_STATES: {
PUBLISHED: 'PUBLISHED',
RESERVED: 'RESERVED',
REJECTED: 'REJECTED',
AVAILABLE: 'AVAILABLE'
},
QUOTA_HEADER: 'CVE-API-REMAINING-QUOTA',
DEFAULT_CVE_ID_RANGE: {
cve_year: 2020,
ranges: {
priority: {
top_id: 0,
start: 0,
end: 20000
},
general: {
top_id: 20000,
start: 20000,
end: 50000000
/**
* Return default values.
*
* The object is created in this function to prevent accidental
* value re-assignment and still allow IDE type-hints and compiled regex
*
* @return {defaults}
*/
function getConstants () {
/**
* @constant
* @default
* @lends defaults
*/
const defaults = {
MONGOOSE_VALIDATION: {
Org_policies_id_quota_min: 0,
Org_policies_id_quota_min_message: 'Org.policies.id_quota cannot be a negative number.',
Org_policies_id_quota_max: 100000,
Org_policies_id_quota_max_message: 'Org.policies.id_quota cannot exceed maximum threshold.'
},
DEFAULT_ID_QUOTA: 1000,
DEFAULT_AVAILABLE_POOL: 100,
NONSEQUENTIAL_MAX_AMOUNT: 10,
CRYPTO_RANDOM_STRING_LENGTH: 36,
AUTH_ROLE_ENUM: {
SECRETARIAT: 'SECRETARIAT',
CNA: 'CNA',
ROOT_CNA: 'ROOT_CNA',
ADP: 'ADP'
},
ORG_ROLES: [
'CNA',
'SECRETARIAT',
'ROOT_CNA',
'ADP'
],
USER_ROLES: [
'ADMIN'
],
USER_ROLE_ENUM: {
ADMIN: 'ADMIN'
},
AUTH_HEADERS: {
ORG: 'CVE-API-ORG',
USER: 'CVE-API-USER',
KEY: 'CVE-API-KEY'
},
CVE_STATES: {
PUBLISHED: 'PUBLISHED',
RESERVED: 'RESERVED',
REJECTED: 'REJECTED',
AVAILABLE: 'AVAILABLE'
},
QUOTA_HEADER: 'CVE-API-REMAINING-QUOTA',
DEFAULT_CVE_ID_RANGE: {
cve_year: 2020,
ranges: {
priority: {
top_id: 0,
start: 0,
end: 20000
},
general: {
top_id: 20000,
start: 20000,
end: 50000000
}
}
},
PAGINATOR_HEADERS: {
PAGE: 'PAGINATOR-PAGE'
},
PAGINATOR_PAGE: 1,
PAGINATOR_OPTIONS: {
limit: 500,
useFacet: false,
customLabels: {
totalDocs: 'itemCount',
docs: 'itemsList',
limit: 'itemsPerPage',
page: 'currentPage',
totalPages: 'pageCount',
useFacet: false
}
}
},
PAGINATOR_HEADERS: {
PAGE: 'PAGINATOR-PAGE'
},
PAGINATOR_PAGE: 1,
PAGINATOR_OPTIONS: {
limit: 500,
useFacet: false,
customLabels: {
totalDocs: 'itemCount',
docs: 'itemsList',
limit: 'itemsPerPage',
page: 'currentPage',
totalPages: 'pageCount',
useFacet: false
}
},
MAX_SHORTNAME_LENGTH: 32,
MIN_SHORTNAME_LENGTH: 2,
CVE_ID_PATTERN: cveSchemaV5.definitions.cveId.pattern,
// Ajv's pattern validation uses the "u" (unicode) flag:
// https://ajv.js.org/json-schema.html#pattern
CVE_ID_REGEX: new RegExp(cveSchemaV5.definitions.cveId.pattern, 'u')
},
MAX_SHORTNAME_LENGTH: 32,
MIN_SHORTNAME_LENGTH: 2,
CVE_ID_PATTERN: cveSchemaV5.definitions.cveId.pattern,
// Ajv's pattern validation uses the "u" (unicode) flag:
// https://ajv.js.org/json-schema.html#pattern
CVE_ID_REGEX: new RegExp(cveSchemaV5.definitions.cveId.pattern, 'u')
}

return defaults
}

module.exports = {
getConstants
}
23 changes: 19 additions & 4 deletions src/controller/cve-id.controller/cve-id.controller.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,26 @@
require('dotenv').config()
const CveId = require('../../model/cve-id')
const logger = require('../../middleware/logger')
const CONSTANTS = require('../../constants')
const getConstants = require('../../constants').getConstants
const errors = require('./error')
const error = new errors.CveIdControllerError()
const options = CONSTANTS.PAGINATOR_OPTIONS
options.sort = { owning_cna: 'asc', cve_id: 'asc' }

const mongoose = require('mongoose')
mongoose.set('debug', true)

// Called by GET /api/cve-id
async function getFilteredCveId (req, res, next) {
const CONSTANTS = getConstants()

// temporary measure to allow tests to work after fixing #920
// tests required changing the global limit to force pagination
if (req.TEST_PAGINATOR_LIMIT) {
CONSTANTS.PAGINATOR_OPTIONS.limit = req.TEST_PAGINATOR_LIMIT
}

const options = CONSTANTS.PAGINATOR_OPTIONS
options.sort = { owning_cna: 'asc', cve_id: 'asc' }

try {
const orgShortName = req.ctx.org
let state
Expand Down Expand Up @@ -183,7 +192,7 @@ async function reserveCveId (req, res, next) {
} else if (batchType === 'sequential') {
await sequentialReservation(year, amount, shortName, orgShortName, requester, payload.available, false, res, req)
} else if (batchType === 'non-sequential' || batchType === 'nonsequential') {
if (amount > CONSTANTS.NONSEQUENTIAL_MAX_AMOUNT) {
if (amount > getConstants().NONSEQUENTIAL_MAX_AMOUNT) {
return res.status(403).json(error.overNonSequentialMaxAmount())
}
await nonSequentialReservation(year, amount, shortName, orgShortName, requester, payload.available, res, req)
Expand All @@ -208,6 +217,8 @@ Unauthenticated users along with Regular, CNA & Admin users requesting ids not o
owning_org not included for ids in the RESERVED state
*/
async function getCveId (req, res, next) {
const CONSTANTS = getConstants()

try {
const auth = req.ctx.authenticated
const id = req.ctx.params.id
Expand Down Expand Up @@ -354,6 +365,7 @@ async function modifyCveId (req, res, next) {
// Called by POST /cve-id-range/:year
async function createCveIdRange (req, res, next) {
try {
const CONSTANTS = getConstants()
const year = req.ctx.params.year
const cveIdRangeRepo = req.ctx.repositories.getCveIdRangeRepository()
const orgRepo = req.ctx.repositories.getOrgRepository()
Expand Down Expand Up @@ -384,6 +396,7 @@ async function createCveIdRange (req, res, next) {
}

async function priorityReservation (year, amount, shortName, orgShortName, requester, availableIds, res, req) {
const CONSTANTS = getConstants()
const cveIdRangeRepo = req.ctx.repositories.getCveIdRangeRepository()
const reqUUID = req.ctx.uuid
let result = await cveIdRangeRepo.findOne({ cve_year: year })
Expand Down Expand Up @@ -459,6 +472,7 @@ async function priorityReservation (year, amount, shortName, orgShortName, reque
}

async function sequentialReservation (year, amount, shortName, orgShortName, requester, availableIds, isPriority, res, req) {
const CONSTANTS = getConstants()
const cveIdRangeRepo = req.ctx.repositories.getCveIdRangeRepository()
const reqUUID = req.ctx.uuid
let result = await cveIdRangeRepo.findOne({ cve_year: year })
Expand Down Expand Up @@ -550,6 +564,7 @@ async function sequentialReservation (year, amount, shortName, orgShortName, req
}

async function nonSequentialReservation (year, amount, shortName, orgShortName, requester, availableIds, res, req) {
const CONSTANTS = getConstants()
const cveIdRepo = req.ctx.repositories.getCveIdRepository()
const cveIdRangeRepo = req.ctx.repositories.getCveIdRangeRepository()
const reqUUID = req.ctx.uuid
Expand Down
4 changes: 3 additions & 1 deletion src/controller/cve-id.controller/error.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const idrErr = require('../../utils/error')
const CONSTANTS = require('../../constants')
const getConstants = require('../../constants').getConstants

class CveIdControllerError extends idrErr.IDRError {
invalidState (state) { // cve-id
Expand Down Expand Up @@ -32,6 +32,7 @@ class CveIdControllerError extends idrErr.IDRError {

overNonSequentialMaxAmount () { // cve-id
const err = {}
const CONSTANTS = getConstants()
err.error = 'OVER_NONSEQUENTIAL_MAX_AMOUNT'
err.message = 'The amount query parameter exceeds the maximum amount allowed. Only amounts of ' + CONSTANTS.NONSEQUENTIAL_MAX_AMOUNT + ' ids or less can be reserved at a time.'
return err
Expand Down Expand Up @@ -60,6 +61,7 @@ class CveIdControllerError extends idrErr.IDRError {

orgCannotReserveForOther () { // cve-id
const err = {}
const CONSTANTS = getConstants()
err.error = 'ORG_CANNOT_RESERVE_FOR_OTHER'
err.message = 'The organization designated by the ' + CONSTANTS.AUTH_HEADERS.ORG + ' header is not allowed to reserve IDs for the organization specified by the short_name query parameter.'
return err
Expand Down
3 changes: 2 additions & 1 deletion src/controller/cve-id.controller/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ const errorMsgs = require('../../middleware/errorMessages')
const controller = require('./cve-id.controller')
const { param, query } = require('express-validator')
const { parseGetParams, parsePostParams, parseError } = require('./cve-id.middleware')
const CONSTANTS = require('../../constants')
const getConstants = require('../../constants').getConstants
const CONSTANTS = getConstants()
const toDate = require('../../utils/utils').toDate

const CHOICES = [CONSTANTS.CVE_STATES.REJECTED, CONSTANTS.CVE_STATES.PUBLISHED, CONSTANTS.CVE_STATES.RESERVED]
Expand Down
29 changes: 26 additions & 3 deletions src/controller/cve.controller/cve.controller.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
const Cve = require('../../model/cve')
const logger = require('../../middleware/logger')
const errors = require('./error')
const getConstants = require('../../constants').getConstants
const error = new errors.CveControllerError()
const CONSTANTS = require('../../constants')
const options = { ...CONSTANTS.PAGINATOR_OPTIONS }
delete options.sort // Deletes any predefined sort options

const mongoose = require('mongoose')
mongoose.set('debug', true)

// Helper function to create providerMetadata object
function createProviderMetadata (orgId, shortName, updateDate) {
Expand All @@ -29,6 +30,16 @@ async function getCve (req, res, next) {

// Called by GET /cve
async function getFilteredCves (req, res, next) {
const CONSTANTS = getConstants()
const options = CONSTANTS.PAGINATOR_OPTIONS
delete options.sort // Deletes any predefined sort options

// temporary measure to allow tests to work after fixing #920
// tests required changing the global limit to force pagination
if (req.TEST_PAGINATOR_LIMIT) {
CONSTANTS.PAGINATOR_OPTIONS.limit = req.TEST_PAGINATOR_LIMIT
}

try {
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 cveRepo = req.ctx.repositories.getCveRepository()
Expand Down Expand Up @@ -134,6 +145,8 @@ async function getFilteredCves (req, res, next) {
// Creates a new CVE only if it does not exists for the specified CVE ID in the request body. If it exists, it does not
// update the CVE.
async function submitCve (req, res, next) {
const CONSTANTS = getConstants()

try {
const newCve = new Cve({ cve: req.ctx.body })
const id = req.ctx.params.id
Expand Down Expand Up @@ -192,6 +205,8 @@ async function submitCve (req, res, next) {
// Called by PUT /cve/:id
// Updates a CVE if one exists for the specified CVE ID
async function updateCve (req, res, next) {
const CONSTANTS = getConstants()

try {
const newCve = new Cve({ cve: req.ctx.body })
const cveId = req.ctx.params.id
Expand Down Expand Up @@ -249,6 +264,8 @@ async function updateCve (req, res, next) {

// Called by POST /cve/:id/cna
async function submitCna (req, res, next) {
const CONSTANTS = getConstants()

try {
const id = req.ctx.params.id
const cveRepo = req.ctx.repositories.getCveRepository()
Expand Down Expand Up @@ -328,6 +345,8 @@ async function submitCna (req, res, next) {

// Called by PUT /cve/:id/cna
async function updateCna (req, res, next) {
const CONSTANTS = getConstants()

try {
const id = req.ctx.params.id
const cveRepo = req.ctx.repositories.getCveRepository()
Expand Down Expand Up @@ -413,6 +432,8 @@ async function updateCna (req, res, next) {

// Called by POST /cve/:id/reject
async function rejectCVE (req, res, next) {
const CONSTANTS = getConstants()

try {
const id = req.ctx.params.id
const cveIdRepo = req.ctx.repositories.getCveIdRepository()
Expand Down Expand Up @@ -483,6 +504,8 @@ async function rejectCVE (req, res, next) {

// Called by PUT /cve/:id/reject
async function rejectExistingCve (req, res, next) {
const CONSTANTS = getConstants()

try {
const id = req.ctx.params.id
const cveIdRepo = req.ctx.repositories.getCveIdRepository()
Expand Down
3 changes: 2 additions & 1 deletion src/controller/cve.controller/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ const errorMsgs = require('../../middleware/errorMessages')
const controller = require('./cve.controller')
const { body, param, query } = require('express-validator')
const { parseGetParams, parsePostParams, parseError, validateCveCnaContainerJsonSchema, validateRejectBody, validateUniqueEnglishEntry } = require('./cve.middleware')
const CONSTANTS = require('../../constants')
const getConstants = require('../../constants').getConstants
const CONSTANTS = getConstants()
const CHOICES = [CONSTANTS.CVE_STATES.REJECTED, CONSTANTS.CVE_STATES.PUBLISHED]
const toDate = require('../../utils/utils').toDate

Expand Down
3 changes: 2 additions & 1 deletion src/controller/org.controller/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ const errorMsgs = require('../../middleware/errorMessages')
const controller = require('./org.controller')
const { body, param, query } = require('express-validator')
const { parseGetParams, parsePostParams, parseError, isOrgRole, isUserRole, isValidUsername } = require('./org.middleware')
const CONSTANTS = require('../../../src/constants')
const getConstants = require('../../../src/constants').getConstants
const CONSTANTS = getConstants()

router.get('/org',
/*
Expand Down
Loading