Merge pull request #33413 from overleaf/revert-33040-em-parse-req-errors

Revert "Replace isZodErrorLike with custom error types in request validation"

GitOrigin-RevId: 1f51fe9e14ffabf283f1229552d3887136420f8f
This commit is contained in:
Eric Mc Sween
2026-05-06 08:06:41 +00:00
committed by Copybot
parent 98def949ec
commit 3da2d53acb
16 changed files with 80 additions and 100 deletions
+2 -26
View File
@@ -1,29 +1,5 @@
// @ts-check
const OError = require('@overleaf/o-error') const OError = require('@overleaf/o-error')
/** class ParamsError extends OError {}
* @typedef {import('zod').ZodError} ZodError
*/
class InvalidRequestError extends OError { module.exports = { ParamsError }
/**
* @param {ZodError} zodError
*/
constructor(zodError) {
super('Invalid request', {}, zodError)
this.zodError = zodError
}
}
class InvalidParamsError extends OError {
/**
* @param {ZodError} zodError
*/
constructor(zodError) {
super('Invalid request parameters', {}, zodError)
this.zodError = zodError
}
}
module.exports = { InvalidParamsError, InvalidRequestError }
@@ -1,20 +1,15 @@
const { fromError } = require('zod-validation-error') const { isZodErrorLike, fromError } = require('zod-validation-error')
const { InvalidParamsError, InvalidRequestError } = require('./Errors')
function createHandleValidationError(statusCode = 400) { function createHandleValidationError(statusCode = 400) {
return (err, req, res, next) => { return [
if (err instanceof InvalidParamsError) { (err, req, res, next) => {
res if (!isZodErrorLike(err)) {
.status(404) return next(err)
.json({ error: fromError(err.zodError).toString(), statusCode: 404 }) }
} else if (err instanceof InvalidRequestError) {
res res.status(statusCode).json({ ...fromError(err), statusCode })
.status(statusCode) },
.json({ error: fromError(err.zodError).toString(), statusCode }) ]
} else {
next(err)
}
}
} }
const handleValidationError = createHandleValidationError(400) const handleValidationError = createHandleValidationError(400)
+2 -3
View File
@@ -1,4 +1,4 @@
const { InvalidParamsError, InvalidRequestError } = require('./Errors') const { ParamsError } = require('./Errors')
const { z } = require('zod') const { z } = require('zod')
const { zz } = require('./zodHelpers') const { zz } = require('./zodHelpers')
const { parseReq } = require('./parseReq') const { parseReq } = require('./parseReq')
@@ -15,6 +15,5 @@ module.exports = {
parseReq, parseReq,
handleValidationError, handleValidationError,
createHandleValidationError, createHandleValidationError,
InvalidRequestError, ParamsError,
InvalidParamsError,
} }
+3 -3
View File
@@ -1,5 +1,5 @@
// @ts-check // @ts-check
const { InvalidRequestError, InvalidParamsError } = require('./Errors') const { ParamsError } = require('./Errors')
/** /**
* @typedef {import('zod').ZodType} ZodType * @typedef {import('zod').ZodType} ZodType
@@ -25,9 +25,9 @@ function parseReq(req, schema) {
return parsed.data return parsed.data
} else if (parsed.error.issues.some(issue => issue.path[0] === 'params')) { } else if (parsed.error.issues.some(issue => issue.path[0] === 'params')) {
// Parts of the URL path failed to validate; throw a specific error // Parts of the URL path failed to validate; throw a specific error
throw new InvalidParamsError(parsed.error) throw new ParamsError('Invalid params').withCause(parsed.error)
} else { } else {
throw new InvalidRequestError(parsed.error) throw parsed.error
} }
} }
@@ -54,7 +54,7 @@ describe('parseReq', () => {
}), }),
}) })
) )
).toThrowError(expect.objectContaining({ name: 'InvalidParamsError' })) ).toThrowError(expect.objectContaining({ name: 'ParamsError' }))
}) })
it('should throw an error containing issues if the schema is invalid', () => { it('should throw an error containing issues if the schema is invalid', () => {
@@ -75,11 +75,9 @@ describe('parseReq', () => {
) )
).toThrowError( ).toThrowError(
expect.objectContaining({ expect.objectContaining({
zodError: expect.objectContaining({ issues: expect.arrayContaining([
issues: expect.arrayContaining([ expect.objectContaining({ path: ['body', 'name'] }),
expect.objectContaining({ path: ['body', 'name'] }), ]),
]),
}),
}) })
) )
}) })
+6 -11
View File
@@ -5,12 +5,8 @@ import { execFile as execFileCb } from 'node:child_process'
import bodyParser from 'body-parser' import bodyParser from 'body-parser'
import express from 'express' import express from 'express'
import YAML from 'js-yaml' import YAML from 'js-yaml'
import { import { isZodErrorLike } from 'zod-validation-error'
InvalidParamsError, import { ParamsError, parseReq, z } from '@overleaf/validation-tools'
InvalidRequestError,
parseReq,
z,
} from '@overleaf/validation-tools'
import { expressify } from '@overleaf/promise-utils' import { expressify } from '@overleaf/promise-utils'
const execFile = promisify(execFileCb) const execFile = promisify(execFileCb)
@@ -478,13 +474,12 @@ app.delete(
) )
app.use((error, req, res, next) => { app.use((error, req, res, next) => {
if (error instanceof InvalidParamsError) { if (error instanceof ParamsError) {
res.status(404).json({ error }) res.status(404).json({ error })
} else if (error instanceof InvalidRequestError) { } else if (isZodErrorLike(error)) {
res.status(400).json({ error: error.zodError }) res.status(400).json({ error })
} else {
next(error)
} }
next(error)
}) })
purgeDataDir() purgeDataDir()
+4 -6
View File
@@ -13,10 +13,8 @@ import methodOverride from 'method-override'
import { mongoClient } from './app/js/mongodb.js' import { mongoClient } from './app/js/mongodb.js'
import NotificationsController from './app/js/NotificationsController.ts' import NotificationsController from './app/js/NotificationsController.ts'
import HealthCheckController from './app/js/HealthCheckController.ts' import HealthCheckController from './app/js/HealthCheckController.ts'
import { import { isZodErrorLike } from 'zod-validation-error'
InvalidParamsError, import { ParamsError } from '@overleaf/validation-tools'
InvalidRequestError,
} from '@overleaf/validation-tools'
const app = express() const app = express()
@@ -58,10 +56,10 @@ const handleApiError: ErrorRequestHandler = (
next: NextFunction next: NextFunction
) => { ) => {
req.logger.addFields({ err }) req.logger.addFields({ err })
if (err instanceof InvalidParamsError) { if (err instanceof ParamsError) {
req.logger.setLevel('warn') req.logger.setLevel('warn')
res.sendStatus(404) res.sendStatus(404)
} else if (err instanceof InvalidRequestError) { } else if (isZodErrorLike(err)) {
req.logger.setLevel('warn') req.logger.setLevel('warn')
res.sendStatus(400) res.sendStatus(400)
} else { } else {
+1 -4
View File
@@ -40,7 +40,7 @@ export default Router = {
attrs.client_id = client.id attrs.client_id = client.id
attrs.err = error attrs.err = error
attrs.method = method attrs.method = method
if (attrs.validation && isZodErrorLike(error)) { if (isZodErrorLike(error)) {
logger.info(attrs, 'validation error') logger.info(attrs, 'validation error')
let message = 'invalid' let message = 'invalid'
try { try {
@@ -456,7 +456,6 @@ export default Router = {
joinDocSchema.parse({ doc_id: docId, fromVersion, options }) joinDocSchema.parse({ doc_id: docId, fromVersion, options })
} catch (error) { } catch (error) {
return Router._handleError(callback, error, client, 'joinDoc', { return Router._handleError(callback, error, client, 'joinDoc', {
validation: 1,
disconnect: 1, disconnect: 1,
}) })
} }
@@ -486,7 +485,6 @@ export default Router = {
zz.objectId().parse(docId) zz.objectId().parse(docId)
} catch (error) { } catch (error) {
return Router._handleError(callback, error, client, 'joinDoc', { return Router._handleError(callback, error, client, 'joinDoc', {
validation: 1,
disconnect: 1, disconnect: 1,
}) })
} }
@@ -572,7 +570,6 @@ export default Router = {
applyOtUpdateSchema.parse({ doc_id: docId, update }) applyOtUpdateSchema.parse({ doc_id: docId, update })
} catch (error) { } catch (error) {
return Router._handleError(callback, error, client, 'applyOtUpdate', { return Router._handleError(callback, error, client, 'applyOtUpdate', {
validation: 1,
disconnect: 1, disconnect: 1,
}) })
} }
@@ -1,14 +1,11 @@
import { fromZodError } from 'zod-validation-error' import { isZodErrorLike, fromZodError } from 'zod-validation-error'
import {
InvalidRequestError,
InvalidParamsError,
} from '@overleaf/validation-tools'
import Errors, { NotFoundError } from './Errors.js' import Errors, { NotFoundError } from './Errors.js'
import SessionManager from '../Authentication/SessionManager.mjs' import SessionManager from '../Authentication/SessionManager.mjs'
import SamlLogHandler from '../SamlLog/SamlLogHandler.mjs' import SamlLogHandler from '../SamlLog/SamlLogHandler.mjs'
import HttpErrorHandler from './HttpErrorHandler.mjs' import HttpErrorHandler from './HttpErrorHandler.mjs'
import { plainTextResponse } from '../../infrastructure/Response.mjs' import { plainTextResponse } from '../../infrastructure/Response.mjs'
import { expressifyErrorHandler } from '@overleaf/promise-utils' import { expressifyErrorHandler } from '@overleaf/promise-utils'
import { ParamsError } from '@overleaf/validation-tools'
function notFound(req, res) { function notFound(req, res) {
res.status(404) res.status(404)
@@ -45,7 +42,7 @@ async function handleError(error, req, res, next) {
if (shouldSendErrorResponse) { if (shouldSendErrorResponse) {
notFound(req, res) notFound(req, res)
} }
} else if (error instanceof InvalidParamsError) { } else if (error instanceof ParamsError) {
req.logger.setLevel('warn') req.logger.setLevel('warn')
if (shouldSendErrorResponse) { if (shouldSendErrorResponse) {
notFound(req, res) notFound(req, res)
@@ -107,11 +104,11 @@ async function handleError(error, req, res, next) {
res.status(400) res.status(400)
plainTextResponse(res, error.message) plainTextResponse(res, error.message)
} }
} else if (error instanceof InvalidRequestError) { } else if (isZodErrorLike(error)) {
req.logger.setLevel('warn') req.logger.setLevel('warn')
res.status(400) res.status(400)
if (shouldSendErrorResponse) { if (shouldSendErrorResponse) {
const validationError = fromZodError(error.zodError) const validationError = fromZodError(error)
res.render('general/400', { message: validationError.message }) res.render('general/400', { message: validationError.message })
} }
} else { } else {
@@ -129,10 +126,7 @@ async function handleError(error, req, res, next) {
function handleApiError(err, req, res, next) { function handleApiError(err, req, res, next) {
req.logger.addFields({ err }) req.logger.addFields({ err })
if ( if (err instanceof Errors.NotFoundError || err instanceof ParamsError) {
err instanceof Errors.NotFoundError ||
err instanceof InvalidParamsError
) {
req.logger.setLevel('warn') req.logger.setLevel('warn')
res.sendStatus(404) res.sendStatus(404)
} else if ( } else if (
@@ -147,7 +141,7 @@ function handleApiError(err, req, res, next) {
} else if (err instanceof Errors.ForbiddenError) { } else if (err instanceof Errors.ForbiddenError) {
req.logger.setLevel('warn') req.logger.setLevel('warn')
res.sendStatus(403) res.sendStatus(403)
} else if (err instanceof InvalidRequestError) { } else if (isZodErrorLike(err)) {
req.logger.setLevel('warn') req.logger.setLevel('warn')
res.sendStatus(400) res.sendStatus(400)
} else { } else {
@@ -2,7 +2,6 @@ import { RateLimiter } from '../../infrastructure/RateLimiter.mjs'
import { callbackify } from '@overleaf/promise-utils' import { callbackify } from '@overleaf/promise-utils'
import Settings from '@overleaf/settings' import Settings from '@overleaf/settings'
import EmailHelper from '../Helpers/EmailHelper.mjs' import EmailHelper from '../Helpers/EmailHelper.mjs'
import { InvalidRequestError } from '@overleaf/validation-tools'
const rateLimiterLoginEmail = new RateLimiter( const rateLimiterLoginEmail = new RateLimiter(
'login', 'login',
@@ -13,11 +12,7 @@ const rateLimiterLoginEmail = new RateLimiter(
) )
async function processLoginRequest(email) { async function processLoginRequest(email) {
try { email = EmailHelper.emailSchema.parse(email)
email = EmailHelper.emailSchema.parse(email)
} catch (err) {
throw new InvalidRequestError(err)
}
try { try {
await rateLimiterLoginEmail.consume(email, 1, { await rateLimiterLoginEmail.consume(email, 1, {
method: 'email', method: 'email',
@@ -2,7 +2,7 @@
import { parseReq, z, zz } from '@overleaf/validation-tools' import { parseReq, z, zz } from '@overleaf/validation-tools'
export { InvalidParamsError, parseReq, z, zz } from '@overleaf/validation-tools' export { ParamsError, parseReq, z, zz } from '@overleaf/validation-tools'
export default { export default {
parseReq, parseReq,
@@ -176,12 +176,31 @@ describe('Authentication', function () {
} }
}) })
it('should return 400 with bad email (missing @)', async function () { it('should return 400 with bad email (missing @)', async function () {
const { statusCode } = await tryLoginWithEmail('foo') const { statusCode, body } = await tryLoginWithEmail('foo')
expect(statusCode).to.equal(400) expect(statusCode).to.equal(400)
expect(body).to.deep.equal({
name: 'ZodValidationError',
details: [
{ code: 'custom', path: [], message: 'Invalid email address' },
],
statusCode: 400,
})
}) })
it('should return 400 with bad email (number)', async function () { it('should return 400 with bad email (number)', async function () {
const { statusCode } = await tryLoginWithEmail(1) const { statusCode, body } = await tryLoginWithEmail(1)
expect(statusCode).to.equal(400) expect(statusCode).to.equal(400)
expect(body).to.deep.equal({
name: 'ZodValidationError',
details: [
{
expected: 'string',
code: 'invalid_type',
path: [],
message: 'Invalid input: expected string, received number',
},
],
statusCode: 400,
})
}) })
}) })
}) })
@@ -219,13 +219,14 @@ describe('Project CRUD', function () {
}) })
it('returns a 400 when publicAccessLevel is an unsupported access level', async function () { it('returns a 400 when publicAccessLevel is an unsupported access level', async function () {
await this.user.makePrivate(this.projectId) await this.user.makePrivate(this.projectId)
const { response } = await this.user.doRequest('POST', { const { response, body } = await this.user.doRequest('POST', {
url: `/project/${this.projectId}/settings/admin`, url: `/project/${this.projectId}/settings/admin`,
json: { json: {
publicAccessLevel: 'readOnly', publicAccessLevel: 'readOnly',
}, },
}) })
expect(response.statusCode).to.equal(400) expect(response.statusCode).to.equal(400)
expect(body.details[0].message).to.equal('unexpected access level')
const project = await Project.findById(this.projectId).exec() const project = await Project.findById(this.projectId).exec()
expect(project.publicAccesLevel).to.equal('private') expect(project.publicAccesLevel).to.equal('private')
}) })
@@ -375,6 +375,11 @@ describe('ProjectInviteTests', function () {
return done(err) return done(err)
} }
expect(response.statusCode).to.equal(400) expect(response.statusCode).to.equal(400)
expect(body.details).to.have.lengthOf(1)
expect(response.body.details[0].path).to.eql(['body', 'email'])
expect(response.body.details[0].message).to.equal(
'Invalid input: expected string, received object'
)
done() done()
} }
) )
@@ -399,6 +404,14 @@ describe('ProjectInviteTests', function () {
return done(err) return done(err)
} }
expect(response.statusCode).to.equal(400) expect(response.statusCode).to.equal(400)
expect(body.details).to.have.lengthOf(1)
expect(response.body.details[0].path).to.eql([
'body',
'privileges',
])
expect(response.body.details[0].message).to.equal(
'Invalid option: expected one of "readOnly"|"readAndWrite"|"review"'
)
done() done()
} }
) )
@@ -685,7 +685,7 @@ describe('SubscriptionController', function () {
ctx.next = sinon.stub() ctx.next = sinon.stub()
await expect( await expect(
ctx.SubscriptionController.pauseSubscription(ctx.req, ctx.res, ctx.next) ctx.SubscriptionController.pauseSubscription(ctx.req, ctx.res, ctx.next)
).to.be.rejectedWith('Invalid request parameters') ).to.be.rejectedWith('Invalid params')
}) })
it('should throw an error if an invalid pause length is provided', async function (ctx) { it('should throw an error if an invalid pause length is provided', async function (ctx) {
@@ -1,6 +1,6 @@
import { assert, beforeEach, describe, it, vi } from 'vitest' import { assert, beforeEach, describe, it, vi } from 'vitest'
import sinon from 'sinon' import sinon from 'sinon'
import { InvalidRequestError } from '@overleaf/validation-tools' import { ZodError } from 'zod'
const modulePath = '../../../../app/src/Features/Tags/TagsController.mjs' const modulePath = '../../../../app/src/Features/Tags/TagsController.mjs'
@@ -202,7 +202,7 @@ describe('TagsController', function () {
it('without a name', function (ctx) { it('without a name', function (ctx) {
ctx.req.body = { name: undefined } ctx.req.body = { name: undefined }
ctx.TagsController.renameTag(ctx.req, ctx.res).should.be.rejectedWith( ctx.TagsController.renameTag(ctx.req, ctx.res).should.be.rejectedWith(
InvalidRequestError ZodError
) )
}) })
}) })