Skip to content

Commit

Permalink
fix: add sanitisation function for products
Browse files Browse the repository at this point in the history
  • Loading branch information
KenLSM committed Nov 8, 2023
1 parent 005e57f commit 3058214
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ import {
getPaymentAmount,
getPaymentIntentDescription,
mapRouteError,
sanitisePaymentProducts,
} from './encrypt-submission.utils'

const logger = createLoggerWithLabel(module)
Expand Down Expand Up @@ -138,8 +139,11 @@ const submitEncryptModeForm = async (
const encryptedPayload = req.formsg.encryptedPayload

// Create Incoming Submission
const { encryptedContent, responseMetadata, paymentProducts } =
encryptedPayload
const {
encryptedContent,
responseMetadata,
paymentProducts: _clientPaymentsProducts,
} = encryptedPayload

// Checks if user is SPCP-authenticated before allowing submission
let uinFin
Expand Down Expand Up @@ -299,6 +303,10 @@ const submitEncryptModeForm = async (
form.payments_field?.enabled &&
form.payments_channel.channel === PaymentChannel.Stripe
) {
const paymentProducts = sanitisePaymentProducts(
form,
_clientPaymentsProducts,
)
return _createPaymentSubmission({
req,
res,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { StatusCodes } from 'http-status-codes'
import _ from 'lodash'
import moment from 'moment-timezone'

import {
FormPaymentsField,
PaymentFieldsDto,
PaymentType,
ProductItem,
StorageModeSubmissionContentDto,
StorageModeSubmissionDto,
SubmissionPaymentDto,
Expand Down Expand Up @@ -359,3 +361,38 @@ export const getPaymentIntentDescription = (
}
}
}

const isNonEmpty = <T>(value: T | null | undefined): value is T => {
return value != null
}

/**
* Sanitizes the payment fields from the form and the incoming submission
* The payment products from incoming submission can be freely altered by the respondent
* which could result in undesirable data seeded into our database
* @param form
* @param uncleanPaymentProducts
*/
export const sanitisePaymentProducts = (
form: IPopulatedEncryptedForm,
dirtyPaymentProducts: ProductItem[] | undefined,
): ProductItem[] | undefined => {
if (!dirtyPaymentProducts) return dirtyPaymentProducts
if (!form.payments_field.products) return dirtyPaymentProducts

const sanitisedProducts = form.payments_field.products
.map((cleanProductData): ProductItem | null => {
const dirtyProduct = dirtyPaymentProducts.find(
({ data }) => data._id === cleanProductData._id,
)
if (!dirtyProduct) return null

return {
..._.pick(dirtyProduct, ['selected', 'quantity']), // only selected and quantity are allowed to be passed through
data: cleanProductData, // only clean product data from the form should be used
}
})
.filter(isNonEmpty)

return sanitisedProducts
}

0 comments on commit 3058214

Please sign in to comment.