🐛 Fixed missing source + resized images producing rendered 404 (#19869)

fixes https://linear.app/tryghost/issue/ENG-746/http-500-responses-when-handle-image-sizes-middleware-hits-missing

- in the event a request comes in for a resized image, but the source
image does not exist, we return a rendered 404 page
- we do this because we pass the NotFoundError to `next`, which skips
over the static asset code where we return a plaintext 404
- also included a breaking test that ensure we go to the next middleware
without an error
This commit is contained in:
Daniel Lockyer 2024-03-18 18:32:10 +01:00 committed by GitHub
parent 3f27ca5c00
commit 134c33cef5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 62 additions and 0 deletions

View File

@ -139,6 +139,11 @@ module.exports = function handleImageSizes(req, res, next) {
if (err.code === 'SHARP_INSTALLATION' || err.code === 'IMAGE_PROCESSING' || err.errorType === 'NoContentError') {
return redirectToOriginal();
}
if (err.errorType === 'NotFoundError') {
return next();
}
next(err);
});
};

View File

@ -0,0 +1,25 @@
const assert = require('assert/strict');
const {agentProvider} = require('../utils/e2e-framework');
describe('Static files', function () {
let frontendAgent;
let ghostServer;
before(async function () {
const agents = await agentProvider.getAgentsWithFrontend();
frontendAgent = agents.frontendAgent;
ghostServer = agents.ghostServer;
});
after(async function () {
await ghostServer.stop();
});
it('serves unstyled 404 for non-existing resized + original files', async function () {
const response = await frontendAgent
.get('/content/images/size/w2000/1995/12/daniel.jpg')
.expect(404);
assert.ok(response.text.includes('NotFoundError: Image not found'));
});
});

View File

@ -3,6 +3,7 @@ const sinon = require('sinon');
const storage = require('../../../../../core/server/adapters/storage');
const activeTheme = require('../../../../../core/frontend/services/theme-engine/active');
const handleImageSizes = require('../../../../../core/frontend/web/middleware/handle-image-sizes.js');
const errors = require('@tryghost/errors');
const imageTransform = require('@tryghost/image-transform');
const fakeResBase = {
@ -673,5 +674,36 @@ describe('handleImageSizes middleware', function () {
done();
});
});
it('goes to next middleware with no error if source and resized image 404', function (done) {
dummyStorage.exists = async function () {
return false;
};
dummyStorage.read = async function () {
throw new errors.NotFoundError({
message: 'File not found'
});
};
const fakeReq = {
url: '/size/w1000/2020/02/test.png',
originalUrl: '/2020/02/test.png'
};
const fakeRes = {
redirect() {
done(new Error('Should not have called redirect'));
},
setHeader() {},
type: function () {}
};
handleImageSizes(fakeReq, fakeRes, function next(err) {
if (err) {
return done(err);
}
done();
});
});
});
});