0
Fork 0
mirror of https://github.com/TryGhost/Ghost.git synced 2025-02-03 23:00:14 -05:00

🐛 Fixed a 500 error when uploading invalid routes.yaml

closes https://github.com/TryGhost/Toolbox/issues/111

- Just like with invalid JSON redirects files we should return a BadRequestError instead of throwing a generic 500 when the redirects.yaml file fails parsing
This commit is contained in:
Naz 2021-11-04 11:50:06 +04:00
parent f421ee79d8
commit df5c87fae3
2 changed files with 32 additions and 4 deletions

View file

@ -11,7 +11,8 @@ const validation = require('./validation');
const messages = {
jsonParse: 'Could not parse JSON: {context}.',
yamlParse: 'YAML input cannot be a plain string. Check the format of your YAML file.',
yamlParse: 'Could not parse YAML: {context}.',
yamlPlainString: 'YAML input cannot be a plain string. Check the format of your YAML file.',
redirectsHelp: 'https://ghost.org/docs/themes/routing/#redirects',
redirectsRegister: 'Could not register custom redirects.'
};
@ -70,7 +71,15 @@ const parseRedirectsFile = (content, ext) => {
if (ext === '.yaml') {
let redirects = [];
let configYaml = yaml.load(content);
let configYaml;
try {
configYaml = yaml.load(content);
} catch (err) {
throw new errors.BadRequestError({
message: tpl(messages.yamlParse, {context: err.message})
});
}
// yaml.load passes almost every yaml code.
// Because of that, it's hard to detect if there's an error in the file.
@ -78,7 +87,7 @@ const parseRedirectsFile = (content, ext) => {
// Here we check if the user made this mistake.
if (typeof configYaml === 'string') {
throw new errors.BadRequestError({
message: tpl(messages.yamlParse),
message: tpl(messages.yamlPlainString),
help: tpl(messages.redirectsHelp)
});
}

View file

@ -106,7 +106,7 @@ describe('UNIT: redirects CustomRedirectsAPI class', function () {
}
});
it('throws a syntax error when setting invalid YAML redirects file', async function () {
it('throws a syntax error when setting invalid (plain string) YAML redirects file', async function () {
const invalidFilePath = path.join(__dirname, '/invalid/redirects/yaml.json');
fs.readFile.withArgs(invalidFilePath, 'utf-8').resolves('x');
@ -118,5 +118,24 @@ describe('UNIT: redirects CustomRedirectsAPI class', function () {
err.message.should.eql('YAML input cannot be a plain string. Check the format of your YAML file.');
}
});
it('throws bad request error when the YAML file is invalid', async function () {
const invalidFilePath = path.join(__dirname, '/invalid/redirects/yaml.json');
fs.readFile.withArgs(invalidFilePath, 'utf-8').resolves(`
routes:
\
invalid yaml:
/
`);
try {
await customRedirectsAPI.setFromFilePath(invalidFilePath, '.yaml');
should.fail('setFromFilePath did not throw');
} catch (err) {
should.exist(err);
err.errorType.should.eql('BadRequestError');
err.message.should.match(/Could not parse YAML: can not read an implicit mapping pair/);
}
});
});
});