From ced91c3c59970997a24975c9acab091bf9e0bd47 Mon Sep 17 00:00:00 2001 From: liuliquan Date: Thu, 5 Oct 2023 00:40:46 +0800 Subject: [PATCH 1/9] PLAT-3453 Stop copilots from paying themselves 1. Stop copilots from paying themselves, thus copilots will need to contact manager to launch/complete the task 2. When updateChallenge, the helper.getChallengeResources function is called multiple times, now it's called only once --- src/common/challenge-helper.js | 4 +-- src/common/helper.js | 12 ++++--- src/services/ChallengeService.js | 55 ++++++++++++++++++++++++++++---- 3 files changed, 59 insertions(+), 12 deletions(-) diff --git a/src/common/challenge-helper.js b/src/common/challenge-helper.js index aef2bd1a..ac691cdb 100644 --- a/src/common/challenge-helper.js +++ b/src/common/challenge-helper.js @@ -105,9 +105,9 @@ class ChallengeHelper { } } - async validateChallengeUpdateRequest(currentUser, challenge, data) { + async validateChallengeUpdateRequest(currentUser, challenge, data, challengeResources) { if (process.env.LOCAL != "true") { - await helper.ensureUserCanModifyChallenge(currentUser, challenge); + await helper.ensureUserCanModifyChallenge(currentUser, challenge, challengeResources); } helper.ensureNoDuplicateOrNullElements(data.tags, "tags"); diff --git a/src/common/helper.js b/src/common/helper.js index f39800f0..46db3d85 100644 --- a/src/common/helper.js +++ b/src/common/helper.js @@ -528,14 +528,17 @@ async function getResourceRoles() { * Check if a user has full access on a challenge * @param {String} challengeId the challenge UUID * @param {String} userId the user ID + * @param {Array} challengeResources the challenge resources */ -async function userHasFullAccess(challengeId, userId) { +async function userHasFullAccess(challengeId, userId, challengeResources) { const resourceRoles = await getResourceRoles(); const rolesWithFullAccess = _.map( _.filter(resourceRoles, (r) => r.fullWriteAccess), "id" ); - const challengeResources = await getChallengeResources(challengeId); + if (!challengeResources) { + challengeResources = await getChallengeResources(challengeId); + } return ( _.filter( challengeResources, @@ -982,13 +985,14 @@ async function ensureUserCanViewChallenge(currentUser, challenge) { * * @param {Object} currentUser the user who perform operation * @param {Object} challenge the challenge to check + * @param {Array} challengeResources the challenge resources * @returns {Promise} */ -async function ensureUserCanModifyChallenge(currentUser, challenge) { +async function ensureUserCanModifyChallenge(currentUser, challenge, challengeResources) { // check groups authorization await ensureAccessibleByGroupsAccess(currentUser, challenge); // check full access - const isUserHasFullAccess = await userHasFullAccess(challenge.id, currentUser.userId); + const isUserHasFullAccess = await userHasFullAccess(challenge.id, currentUser.userId, challengeResources); if ( !currentUser.isMachine && !hasAdminRole(currentUser) && diff --git a/src/services/ChallengeService.js b/src/services/ChallengeService.js index 9b0fd8da..12f42ebf 100644 --- a/src/services/ChallengeService.js +++ b/src/services/ChallengeService.js @@ -1364,10 +1364,9 @@ function isDifferentPrizeSets(prizeSets = [], otherPrizeSets = []) { /** * Validate the winners array. * @param {Array} winners the Winner Array - * @param {String} winchallengeIdners the challenge ID + * @param {Array} challengeResources the challenge resources */ -async function validateWinners(winners, challengeId) { - const challengeResources = await helper.getChallengeResources(challengeId); +async function validateWinners(winners, challengeResources) { const registrants = _.filter(challengeResources, (r) => r.roleId === config.SUBMITTER_ROLE_ID); for (const prizeType of _.values(constants.prizeSetTypes)) { const filteredWinners = _.filter(winners, (w) => w.type === prizeType); @@ -1410,6 +1409,48 @@ async function validateWinners(winners, challengeId) { } } +/** + * Task shouldn't be launched/completed when it is assigned to the current user self. + * E.g: stop copilots from paying themselves, thus copilots will need to contact manager to launch/complete the task. + * @param {Object} currentUser the user who perform operation + * @param {Object} challenge the existing challenge + * @param {Object} data the new input challenge data + * @param {Array} challengeResources the challenge resources + */ +function validateTaskSelfAssign(currentUser, challenge, data, challengeResources) { + if (currentUser.isMachine) { + return; + } + + const finalStatus = data.status || challenge.status; + + // Only validate when launch/complete a task + const isLaunchCompleteTask = + _.get(challenge, "legacy.pureV5Task") && + (finalStatus === constants.challengeStatuses.Active || + finalStatus === constants.challengeStatuses.Completed); + if (!isLaunchCompleteTask) { + return; + } + + // Whether task is assigned to current user + const assignedToCurrentUser = + _.filter( + challengeResources, + (r) => + r.roleId === config.SUBMITTER_ROLE_ID && + _.toString(r.memberId) === _.toString(currentUser.userId) + ).length > 0; + + if (assignedToCurrentUser) { + throw new errors.ForbiddenError( + `You are not allowed to ${ + finalStatus === constants.challengeStatuses.Active ? "lanuch" : "complete" + } task assigned to yourself. Please contact manager to operate.` + ); + } +} + /** * Update challenge. * @param {Object} currentUser the user who perform operation @@ -1441,7 +1482,10 @@ async function updateChallenge(currentUser, challengeId, data) { data = sanitizeData(sanitizeChallenge(data), challenge); logger.debug(`Sanitized Data: ${JSON.stringify(data)}`); - await validateChallengeUpdateRequest(currentUser, challenge, data); + const challengeResources = await helper.getChallengeResources(challengeId); + + await validateChallengeUpdateRequest(currentUser, challenge, data, challengeResources); + validateTaskSelfAssign(currentUser, challenge, data, challengeResources); let sendActivationEmail = false; let sendSubmittedEmail = false; @@ -1716,7 +1760,7 @@ async function updateChallenge(currentUser, challengeId, data) { } if (data.winners && data.winners.length && data.winners.length > 0) { - await validateWinners(data.winners, challengeId); + await validateWinners(data.winners, challengeResources); } // Only m2m tokens are allowed to modify the `task.*` information on a challenge @@ -1777,7 +1821,6 @@ async function updateChallenge(currentUser, challengeId, data) { if (_.get(type, "isTask")) { if (!_.isEmpty(_.get(data, "task.memberId"))) { - const challengeResources = await helper.getChallengeResources(challengeId); const registrants = _.filter( challengeResources, (r) => r.roleId === config.SUBMITTER_ROLE_ID From d1e5d122a4d680fcd404ef20e2ef09a37c9cb815 Mon Sep 17 00:00:00 2001 From: liuliquan Date: Thu, 5 Oct 2023 18:31:05 +0800 Subject: [PATCH 2/9] Only restrict launch/complete self-assigned Task Also validate winners is present in request payload when complete a Task --- src/services/ChallengeService.js | 59 ++++++++++++++++++-------------- 1 file changed, 33 insertions(+), 26 deletions(-) diff --git a/src/services/ChallengeService.js b/src/services/ChallengeService.js index 12f42ebf..2bf79f2f 100644 --- a/src/services/ChallengeService.js +++ b/src/services/ChallengeService.js @@ -1417,37 +1417,44 @@ async function validateWinners(winners, challengeResources) { * @param {Object} data the new input challenge data * @param {Array} challengeResources the challenge resources */ -function validateTaskSelfAssign(currentUser, challenge, data, challengeResources) { - if (currentUser.isMachine) { +function validateTask(currentUser, challenge, data, challengeResources) { + if (!_.get(challenge, "legacy.pureV5Task")) { + // Not a Task return; } - const finalStatus = data.status || challenge.status; + // Status from Draft -> Active, indicating launch a Task + const isLaunchTask = + data.status === constants.challengeStatuses.Active && + challenge.status === constants.challengeStatuses.Draft; - // Only validate when launch/complete a task - const isLaunchCompleteTask = - _.get(challenge, "legacy.pureV5Task") && - (finalStatus === constants.challengeStatuses.Active || - finalStatus === constants.challengeStatuses.Completed); - if (!isLaunchCompleteTask) { - return; + // Status from Active -> Completed, indicating complete a Task + const isCompleteTask = + data.status === constants.challengeStatuses.Completed && + challenge.status === constants.challengeStatuses.Active; + + // When complete a Task, input data should have winners + if (isCompleteTask && (!data.winners || !data.winners.length)) { + throw new errors.BadRequestError("The winners is required to complete a Task"); } - // Whether task is assigned to current user - const assignedToCurrentUser = - _.filter( - challengeResources, - (r) => - r.roleId === config.SUBMITTER_ROLE_ID && - _.toString(r.memberId) === _.toString(currentUser.userId) - ).length > 0; - - if (assignedToCurrentUser) { - throw new errors.ForbiddenError( - `You are not allowed to ${ - finalStatus === constants.challengeStatuses.Active ? "lanuch" : "complete" - } task assigned to yourself. Please contact manager to operate.` - ); + if (!currentUser.isMachine && (isLaunchTask || isCompleteTask)) { + // Whether task is assigned to current user + const assignedToCurrentUser = + _.filter( + challengeResources, + (r) => + r.roleId === config.SUBMITTER_ROLE_ID && + _.toString(r.memberId) === _.toString(currentUser.userId) + ).length > 0; + + if (assignedToCurrentUser) { + throw new errors.ForbiddenError( + `You are not allowed to ${ + data.status === constants.challengeStatuses.Active ? "lanuch" : "complete" + } task assigned to yourself. Please contact manager to operate.` + ); + } } } @@ -1485,7 +1492,7 @@ async function updateChallenge(currentUser, challengeId, data) { const challengeResources = await helper.getChallengeResources(challengeId); await validateChallengeUpdateRequest(currentUser, challenge, data, challengeResources); - validateTaskSelfAssign(currentUser, challenge, data, challengeResources); + validateTask(currentUser, challenge, data, challengeResources); let sendActivationEmail = false; let sendSubmittedEmail = false; From 8ee4255fcfb2dd6da62bcefdd49fff31d315ea9c Mon Sep 17 00:00:00 2001 From: liuliquan Date: Thu, 5 Oct 2023 06:31:36 -0500 Subject: [PATCH 3/9] Task status change (#665) --- src/services/ChallengeService.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/services/ChallengeService.js b/src/services/ChallengeService.js index 2bf79f2f..4b1e9e2d 100644 --- a/src/services/ChallengeService.js +++ b/src/services/ChallengeService.js @@ -1423,15 +1423,15 @@ function validateTask(currentUser, challenge, data, challengeResources) { return; } - // Status from Draft -> Active, indicating launch a Task + // Status changed to Active, indicating launch a Task const isLaunchTask = data.status === constants.challengeStatuses.Active && - challenge.status === constants.challengeStatuses.Draft; + challenge.status !== constants.challengeStatuses.Active; - // Status from Active -> Completed, indicating complete a Task + // Status changed to Completed, indicating complete a Task const isCompleteTask = data.status === constants.challengeStatuses.Completed && - challenge.status === constants.challengeStatuses.Active; + challenge.status !== constants.challengeStatuses.Completed; // When complete a Task, input data should have winners if (isCompleteTask && (!data.winners || !data.winners.length)) { From f976de1e9cb8078ad3119ec525ecfc78af598817 Mon Sep 17 00:00:00 2001 From: sarojbehera1 Date: Thu, 5 Oct 2023 03:01:36 +0530 Subject: [PATCH 4/9] Validate Group Ids are valid or not --- src/common/helper.js | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/common/helper.js b/src/common/helper.js index f39800f0..33085b1d 100644 --- a/src/common/helper.js +++ b/src/common/helper.js @@ -898,7 +898,27 @@ async function _filterChallengesByGroupsAccess(currentUser, challenges) { const needToCheckForGroupAccess = !currentUser ? true : !currentUser.isMachine && !hasAdminRole(currentUser); - if (!needToCheckForGroupAccess) return challenges; + if(!needToCheckForGroupAccess) + { + for (const challenge of challenges) { + if(challenge && challenge.groups && challenge.groups.length>0) { + const promises = []; + _.each(challenge.groups, (g) => { + promises.push( + (async () => { + const group = await getGroupById(g); + if ( !group || !group.status==='active') { + throw new errors.BadRequestError("The groups provided are invalid "+g); + } + })() + ); + }); + await Promise.all(promises); + res.push(challenge); + } + } + return res; + } let userGroups; From 3357c683b9f5b4d1429c5339cfaabae693cf49c9 Mon Sep 17 00:00:00 2001 From: sarojbehera1 Date: Fri, 6 Oct 2023 03:40:01 +0530 Subject: [PATCH 5/9] Creating function for validate groups by getGroupById --- src/common/helper.js | 22 +------------------ src/services/ChallengeService.js | 36 ++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 21 deletions(-) diff --git a/src/common/helper.js b/src/common/helper.js index 33085b1d..f39800f0 100644 --- a/src/common/helper.js +++ b/src/common/helper.js @@ -898,27 +898,7 @@ async function _filterChallengesByGroupsAccess(currentUser, challenges) { const needToCheckForGroupAccess = !currentUser ? true : !currentUser.isMachine && !hasAdminRole(currentUser); - if(!needToCheckForGroupAccess) - { - for (const challenge of challenges) { - if(challenge && challenge.groups && challenge.groups.length>0) { - const promises = []; - _.each(challenge.groups, (g) => { - promises.push( - (async () => { - const group = await getGroupById(g); - if ( !group || !group.status==='active') { - throw new errors.BadRequestError("The groups provided are invalid "+g); - } - })() - ); - }); - await Promise.all(promises); - res.push(challenge); - } - } - return res; - } + if (!needToCheckForGroupAccess) return challenges; let userGroups; diff --git a/src/services/ChallengeService.js b/src/services/ChallengeService.js index 9b0fd8da..eed62efb 100644 --- a/src/services/ChallengeService.js +++ b/src/services/ChallengeService.js @@ -910,6 +910,24 @@ searchChallenges.schema = { }) .unknown(true), }; +/** + * Validate Challenge groups. + * @param {Object} groups the group of a challenge + */ +async function validateGroups(groups) { + const promises = []; + _.each(groups, (g) => { + promises.push( + (async () => { + const group = await helper.getGroupById(g); + if (!group || group.status !== "active") { + throw new errors.BadRequestError("The groups provided are invalid " + g); + } + })() + ); + }); + await Promise.all(promises); +} /** * Create challenge. @@ -921,6 +939,15 @@ searchChallenges.schema = { async function createChallenge(currentUser, challenge, userToken) { await challengeHelper.validateCreateChallengeRequest(currentUser, challenge); + //Validate the groups if Valid or Not + if ( + challenge.groups && + challenge.groups.length > 0 && + (currentUser.isMachine || hasAdminRole(currentUser)) + ) { + await validateGroups(challenge.groups); + } + if (challenge.legacy.selfService) { // if self-service, create a new project (what about if projectId is provided in the payload? confirm with business!) if (!challenge.projectId) { @@ -1443,6 +1470,15 @@ async function updateChallenge(currentUser, challengeId, data) { await validateChallengeUpdateRequest(currentUser, challenge, data); + //Validate the groups if Valid or Not + if ( + data.groups && + data.groups.length > 0 && + (currentUser.isMachine || hasAdminRole(currentUser)) + ) { + await validateGroups(data.groups); + } + let sendActivationEmail = false; let sendSubmittedEmail = false; let sendCompletedEmail = false; From 2cf3744507d9872ed1c084d0da4f7eca9af2f43f Mon Sep 17 00:00:00 2001 From: sarojbehera1 Date: Wed, 11 Oct 2023 13:59:01 +0530 Subject: [PATCH 6/9] Moving code to challenge-helper --- src/common/challenge-helper.js | 35 ++++++++++++++++++++++++++++--- src/services/ChallengeService.js | 36 -------------------------------- 2 files changed, 32 insertions(+), 39 deletions(-) diff --git a/src/common/challenge-helper.js b/src/common/challenge-helper.js index aef2bd1a..485bc179 100644 --- a/src/common/challenge-helper.js +++ b/src/common/challenge-helper.js @@ -80,6 +80,25 @@ class ChallengeHelper { } } + /** + * Validate Challenge groups. + * @param {Object} groups the group of a challenge + */ + async validateGroups(groups) { + const promises = []; + _.each(groups, (g) => { + promises.push( + (async () => { + const group = await helper.getGroupById(g); + if (!group || group.status !== "active") { + throw new errors.BadRequestError("The groups provided are invalid " + g); + } + })() + ); + }); + await Promise.all(promises); + } + async validateCreateChallengeRequest(currentUser, challenge) { // projectId is required for non self-service challenges if (challenge.legacy.selfService == null && challenge.projectId == null) { @@ -98,7 +117,13 @@ class ChallengeHelper { // helper.ensureNoDuplicateOrNullElements(challenge.events, 'events') // check groups authorization - await helper.ensureAccessibleByGroupsAccess(currentUser, challenge); + if (challenge.groups && challenge.groups.length > 0) { + if (currentUser.isMachine || hasAdminRole(currentUser)) { + await this.validateGroups(challenge.groups); + } else { + await helper.ensureAccessibleByGroupsAccess(currentUser, challenge); + } + } if (challenge.constraints) { await ChallengeHelper.validateChallengeConstraints(challenge.constraints); @@ -118,8 +143,12 @@ class ChallengeHelper { } // check groups access to be updated group values - if (data.groups) { - await ensureAcessibilityToModifiedGroups(currentUser, data, challenge); + if (data.groups && data.groups.length > 0) { + if (currentUser.isMachine || hasAdminRole(currentUser)) { + await this.validateGroups(data.groups); + } else { + await ensureAcessibilityToModifiedGroups(currentUser, data, challenge); + } } // Ensure descriptionFormat is either 'markdown' or 'html' diff --git a/src/services/ChallengeService.js b/src/services/ChallengeService.js index eed62efb..9b0fd8da 100644 --- a/src/services/ChallengeService.js +++ b/src/services/ChallengeService.js @@ -910,24 +910,6 @@ searchChallenges.schema = { }) .unknown(true), }; -/** - * Validate Challenge groups. - * @param {Object} groups the group of a challenge - */ -async function validateGroups(groups) { - const promises = []; - _.each(groups, (g) => { - promises.push( - (async () => { - const group = await helper.getGroupById(g); - if (!group || group.status !== "active") { - throw new errors.BadRequestError("The groups provided are invalid " + g); - } - })() - ); - }); - await Promise.all(promises); -} /** * Create challenge. @@ -939,15 +921,6 @@ async function validateGroups(groups) { async function createChallenge(currentUser, challenge, userToken) { await challengeHelper.validateCreateChallengeRequest(currentUser, challenge); - //Validate the groups if Valid or Not - if ( - challenge.groups && - challenge.groups.length > 0 && - (currentUser.isMachine || hasAdminRole(currentUser)) - ) { - await validateGroups(challenge.groups); - } - if (challenge.legacy.selfService) { // if self-service, create a new project (what about if projectId is provided in the payload? confirm with business!) if (!challenge.projectId) { @@ -1470,15 +1443,6 @@ async function updateChallenge(currentUser, challengeId, data) { await validateChallengeUpdateRequest(currentUser, challenge, data); - //Validate the groups if Valid or Not - if ( - data.groups && - data.groups.length > 0 && - (currentUser.isMachine || hasAdminRole(currentUser)) - ) { - await validateGroups(data.groups); - } - let sendActivationEmail = false; let sendSubmittedEmail = false; let sendCompletedEmail = false; From d3f8b5d64035845c6fc8aad8272533a1bf43abee Mon Sep 17 00:00:00 2001 From: sarojbehera1 <137802881+sarojbehera1@users.noreply.github.com> Date: Thu, 12 Oct 2023 15:15:09 +0530 Subject: [PATCH 7/9] Correcting error: removing this (#667) --- src/common/challenge-helper.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/common/challenge-helper.js b/src/common/challenge-helper.js index 6ee91781..81764aeb 100644 --- a/src/common/challenge-helper.js +++ b/src/common/challenge-helper.js @@ -119,7 +119,7 @@ class ChallengeHelper { // check groups authorization if (challenge.groups && challenge.groups.length > 0) { if (currentUser.isMachine || hasAdminRole(currentUser)) { - await this.validateGroups(challenge.groups); + await validateGroups(challenge.groups); } else { await helper.ensureAccessibleByGroupsAccess(currentUser, challenge); } @@ -145,7 +145,7 @@ class ChallengeHelper { // check groups access to be updated group values if (data.groups && data.groups.length > 0) { if (currentUser.isMachine || hasAdminRole(currentUser)) { - await this.validateGroups(data.groups); + await validateGroups(data.groups); } else { await ensureAcessibilityToModifiedGroups(currentUser, data, challenge); } From 427dde2738f52e2645246e02ea09221b94f7100c Mon Sep 17 00:00:00 2001 From: sarojbehera1 <137802881+sarojbehera1@users.noreply.github.com> Date: Thu, 12 Oct 2023 17:35:50 +0530 Subject: [PATCH 8/9] Putting back this (#669) * Correcting error: removing this * Putting back *this* * Update challenge-helper.js to use the this keyword --------- Co-authored-by: Thomas Kranitsas --- src/common/challenge-helper.js | 4 ++-- src/services/ChallengeService.js | 3 +-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/common/challenge-helper.js b/src/common/challenge-helper.js index 81764aeb..6ee91781 100644 --- a/src/common/challenge-helper.js +++ b/src/common/challenge-helper.js @@ -119,7 +119,7 @@ class ChallengeHelper { // check groups authorization if (challenge.groups && challenge.groups.length > 0) { if (currentUser.isMachine || hasAdminRole(currentUser)) { - await validateGroups(challenge.groups); + await this.validateGroups(challenge.groups); } else { await helper.ensureAccessibleByGroupsAccess(currentUser, challenge); } @@ -145,7 +145,7 @@ class ChallengeHelper { // check groups access to be updated group values if (data.groups && data.groups.length > 0) { if (currentUser.isMachine || hasAdminRole(currentUser)) { - await validateGroups(data.groups); + await this.validateGroups(data.groups); } else { await ensureAcessibilityToModifiedGroups(currentUser, data, challenge); } diff --git a/src/services/ChallengeService.js b/src/services/ChallengeService.js index 4b1e9e2d..469d8806 100644 --- a/src/services/ChallengeService.js +++ b/src/services/ChallengeService.js @@ -36,7 +36,6 @@ const { ChallengeDomain } = require("@topcoder-framework/domain-challenge"); const { hasAdminRole } = require("../common/role-helper"); const { - validateChallengeUpdateRequest, enrichChallengeForResponse, sanitizeRepeatedFieldsInUpdateRequest, convertPrizeSetValuesToCents, @@ -1491,7 +1490,7 @@ async function updateChallenge(currentUser, challengeId, data) { const challengeResources = await helper.getChallengeResources(challengeId); - await validateChallengeUpdateRequest(currentUser, challenge, data, challengeResources); + await challengeHelper.validateChallengeUpdateRequest(currentUser, challenge, data, challengeResources); validateTask(currentUser, challenge, data, challengeResources); let sendActivationEmail = false; From 6dde37d3814642ef856fa500b05c1f3fe8ca2606 Mon Sep 17 00:00:00 2001 From: sarojbehera1 <137802881+sarojbehera1@users.noreply.github.com> Date: Sat, 14 Oct 2023 03:11:38 +0530 Subject: [PATCH 9/9] Plat 2528 (#676) merge commit