Skip to content

Commit 51d3ab5

Browse files
committed
fix(core): keep entry card image values out of the generated CSS
The grid card interpolated the image field into an emotion `background-image: url(...)` rule with only encodeURI applied. encodeURI leaves `)` and `;` alone, so a value could close url() and add declarations such as a full-viewport fixed overlay (GHSA-x5xc-5mj7-9vvw). The URL is now quoted as a CSS string, with `"`, `\` and line breaks escaped, and set as an inline style, so the browser parses it as a background-image value and nothing else. encodeURI is dropped: it only existed for spaces in the unquoted url(), it broke getAsset lookups of repository paths with spaces, and it threw URIError on a lone surrogate, which took the whole CMS down to the root error boundary (GHSA-9fg8-wxhv-7v3f). Non-string image values no longer render a card image.
1 parent c4269e2 commit 51d3ab5

2 files changed

Lines changed: 116 additions & 7 deletions

File tree

‎packages/decap-cms-core/src/components/Collection/Entries/EntryCard.js‎

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -86,8 +86,16 @@ const CardBody = styled.div`
8686
}
8787
`;
8888

89+
// The image comes from entry content, so it must only ever be the url()
90+
// argument. Quoting it as a CSS string, with the characters that could end the
91+
// string or the line escaped, keeps `)` and `;` inside it, and setting it as an
92+
// inline style lets the browser parse it as a background-image value and
93+
// nothing else. Interpolating it into the emotion template did neither.
94+
export function cssUrl(value) {
95+
return `url("${value.replace(/["\\\n\r\f]/g, c => `\\${c.charCodeAt(0).toString(16)} `)}")`;
96+
}
97+
8998
const StyledImage = styled.div`
90-
background-image: url(${props => props.src});
9199
background-position: center center;
92100
background-size: cover;
93101
background-repeat: no-repeat;
@@ -138,7 +146,12 @@ function CardImage({ getAsset, value, field }) {
138146
setAsset(value ? getAsset(value, field) : null);
139147
}, [value, field, getAsset]);
140148

141-
return asset ? <StyledImage data-testid="entry-card-image" src={asset.toString()} /> : null;
149+
return asset ? (
150+
<StyledImage
151+
data-testid="entry-card-image"
152+
style={{ backgroundImage: cssUrl(asset.toString()) }}
153+
/>
154+
) : null;
142155
}
143156

144157
function EntryCard({
@@ -214,17 +227,18 @@ function mapStateToProps(state, ownProps) {
214227
const entryData = entry.get('data');
215228
const summary = selectEntryCollectionTitle(collection, entry);
216229

217-
let image = entryData.get(inferredFields.imageField);
218-
if (image) {
219-
image = encodeURI(image);
220-
}
230+
// Passed to getAsset exactly as stored, like every other widget does. It used
231+
// to be encodeURI'd here to keep spaces from breaking an unquoted url(), which
232+
// cssUrl now handles; the encoding broke lookups of repository paths with
233+
// spaces, and threw on a lone UTF-16 surrogate, taking the whole list down.
234+
const image = entryData.get(inferredFields.imageField);
221235

222236
const isLoadingAsset = selectIsLoadingAsset(state.medias);
223237

224238
return {
225239
summary,
226240
path: `/collections/${collection.get('name')}/entries/${entry.get('slug')}`,
227-
image,
241+
image: typeof image === 'string' ? image : undefined,
228242
imageFolder: collection
229243
.get('fields')
230244
?.find(f => f.get('name') === inferredFields.imageField && f.get('widget') === 'image'),
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
import { render, screen } from '@testing-library/react';
2+
import { fromJS } from 'immutable';
3+
import configureStore from 'redux-mock-store';
4+
import thunk from 'redux-thunk';
5+
import { Provider } from 'react-redux';
6+
import { MemoryRouter } from 'react-router-dom';
7+
import { I18n } from 'react-polyglot';
8+
9+
import EntryCard, { cssUrl } from '../EntryCard';
10+
import { VIEW_STYLE_GRID, VIEW_STYLE_LIST } from '../../../../constants/collectionViews';
11+
12+
const mockStore = configureStore([thunk]);
13+
14+
const collection = fromJS({
15+
name: 'posts',
16+
label: 'Posts',
17+
folder: 'content/posts',
18+
fields: [
19+
{ name: 'title', widget: 'string' },
20+
{ name: 'image', widget: 'image' },
21+
],
22+
});
23+
24+
function renderCard(image, viewStyle = VIEW_STYLE_GRID) {
25+
const store = mockStore({
26+
medias: {},
27+
config: fromJS({ media_folder: 'static/media', public_folder: '/media' }),
28+
});
29+
const entry = fromJS({
30+
slug: 'hello',
31+
path: 'content/posts/hello.md',
32+
data: { title: 'Hello', image },
33+
});
34+
return render(
35+
<Provider store={store}>
36+
<I18n locale="en" messages={{}}>
37+
<MemoryRouter>
38+
<EntryCard
39+
entry={entry}
40+
collection={collection}
41+
inferredFields={{ titleField: 'title', imageField: 'image' }}
42+
viewStyle={viewStyle}
43+
/>
44+
</MemoryRouter>
45+
</I18n>
46+
</Provider>,
47+
);
48+
}
49+
50+
function emittedCss() {
51+
return Array.from(document.styleSheets)
52+
.flatMap(sheet => Array.from(sheet.cssRules))
53+
.map(rule => rule.cssText)
54+
.join('\n');
55+
}
56+
57+
// jsdom's CSS parser rejects many valid url() values, so these check the
58+
// string handed to the browser rather than how jsdom parses it.
59+
describe('cssUrl', () => {
60+
it('quotes the URL so spaces, ) and ; stay inside it', () => {
61+
expect(cssUrl('/media/my image.png')).toBe('url("/media/my image.png")');
62+
expect(cssUrl('/x);position:fixed;z-index:9')).toBe('url("/x);position:fixed;z-index:9")');
63+
});
64+
65+
// GHSA-x5xc-5mj7-9vvw
66+
it('escapes the characters that could end the string', () => {
67+
expect(cssUrl('/x");position:fixed')).toBe('url("/x\\22 );position:fixed")');
68+
expect(cssUrl('/a\\b')).toBe('url("/a\\5c b")');
69+
expect(cssUrl('/a\nb\rc\fd')).toBe('url("/a\\a b\\d c\\c d")');
70+
});
71+
});
72+
73+
describe('EntryCard image', () => {
74+
it('sets the image as an inline style, never in the generated stylesheet', () => {
75+
renderCard('https://example.com/x);position:fixed;z-index:99999');
76+
expect(screen.getByTestId('entry-card-image')).toBeInTheDocument();
77+
expect(emittedCss()).not.toContain('example.com');
78+
});
79+
80+
// GHSA-9fg8-wxhv-7v3f: encodeURI threw URIError on a lone surrogate and the
81+
// root error boundary replaced the whole CMS.
82+
it.each([VIEW_STYLE_LIST, VIEW_STYLE_GRID])(
83+
'renders the card when the image is a lone surrogate (%s)',
84+
viewStyle => {
85+
renderCard('https://example.com/\uD800', viewStyle);
86+
expect(screen.getByText('Hello')).toBeInTheDocument();
87+
},
88+
);
89+
90+
it('ignores an image value that is not a string', () => {
91+
renderCard(['a.png', 'b.png']);
92+
expect(screen.getByText('Hello')).toBeInTheDocument();
93+
expect(screen.queryByTestId('entry-card-image')).toBeNull();
94+
});
95+
});

0 commit comments

Comments
 (0)