Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 65 additions & 1 deletion __test__/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import express from 'express';
import request from 'supertest';
import { Utilities } from '../src/utils';
import { fakeQueryString, fakeQueryStringRes, options } from './fakeInputs';
import { fakeQueryString, fakeQueryStringRes, options, themes } from './fakeInputs';
import { Handlers } from '../src/handlers';
import { createGraph } from '../src/createChart';

Expand Down Expand Up @@ -31,6 +31,7 @@ describe('Utilities Test', () => {
.get('/graph?username=ashutosh00710')
.expect('Content-Type', 'image/svg+xml; charset=utf-8')
.expect('Cache-Control', 'public, max-age=1800')
.expect('Content-Security-Policy', "script-src 'none'; sandbox")
.expect(200, done);
});
});
Expand All @@ -43,10 +44,73 @@ describe('Utilities Test', () => {
.get('/graph?username=')
.expect('Content-Type', 'image/svg+xml; charset=utf-8')
.expect('Cache-Control', 'no-store, max-age=0')
.expect('Content-Security-Policy', "script-src 'none'; sandbox")
.expect(200, done);
});
});

describe('Color sanitization', () => {
it('falls back to the theme color when a color param is not valid hex', () => {
const utils = new Utilities({
username: 'githubusername',
color: 'red} </style><script>alert(1)</script><style>{',
bg_color: '"><script>alert(1)</script>',
border_color: 'red;"/><script>alert(1)</script>',
area_color: 'javascript:alert(1)',
line: 'red</style><script>alert(1)</script>',
point: 'red</style><script>alert(1)</script>',
title_color: 'red} </style><script>alert(1)</script>',
} as any);

expect(utils.queryOptions().colors).toEqual(themes.default);
});

it('accepts valid hex color params unchanged', () => {
const utils = new Utilities({
username: 'githubusername',
color: 'abc123',
bg_color: 'fff',
} as any);

const { colors } = utils.queryOptions();
expect(colors.color).toBe('abc123');
expect(colors.bgColor).toBe('fff');
});

it('rejects hex-only values with a length CSS/SVG does not support', () => {
const utils = new Utilities({
username: 'githubusername',
color: 'a', // 1 digit
bg_color: 'ab', // 2 digits
line: 'abcde', // 5 digits
point: 'abcdefa', // 7 digits
} as any);

const { colors } = utils.queryOptions();
expect(colors.color).toBe(themes.default.color);
expect(colors.bgColor).toBe(themes.default.bgColor);
expect(colors.lineColor).toBe(themes.default.lineColor);
expect(colors.pointColor).toBe(themes.default.pointColor);
});
});

describe('Title escaping', () => {
it('escapes HTML in custom_title so it cannot break out of the SVG', async () => {
const utils = new Utilities({
username: 'githubusername',
custom_title: '</h1><script>alert(document.domain)</script>',
} as any);

const { finalGraph } = await utils.buildGraph({
name: 'someone',
contributions: [{ contributionCount: 1, date: '1' }],
});

expect(finalGraph).not.toContain('<script>');
expect(finalGraph).toContain('&lt;script&gt;');
});
});

//- Chart Function ([Promise] Inside Graph Cards Class) ✔
it('Graph Generation', async () => {
expect.assertions(1);
Expand Down
1 change: 1 addition & 0 deletions src/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export class Handlers {
res.status(200).send(finalGraph);
} catch (error) {
res.setHeader('Cache-Control', 'no-store, max-age=0');
res.setHeader('Content-Security-Policy', "script-src 'none'; sandbox");
res.set('Content-Type', 'image/svg+xml');
res.send(invalidUserSvg('Something unexpected happened 💥'));
}
Expand Down
70 changes: 47 additions & 23 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,36 @@ import { invalidUserSvg } from './svgs';
import { selectColors } from './styles/themes';
import { QueryOption, ParsedQs, UserDetails } from './interfaces/interface';

// Colors are interpolated raw into SVG attributes and a <style> block (see
// svgs.ts / graphStyle.ts), so anything other than hex digits could break out
// into markup/CSS and inject a <script> or event handler. Restricted to the
// hex lengths CSS/SVG actually accept (3, 4, 6, 8) so invalid lengths fall
// back to the theme default instead of rendering as a broken color.
const HEX_COLOR = /^(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;

function sanitizeColor(value: unknown): string | undefined {
return typeof value === 'string' && HEX_COLOR.test(value) ? value : undefined;
}

// The title is embedded as raw XHTML inside a <foreignObject>, so it must be
// entity-escaped before use or it can inject a <script> the same way.
function escapeHtml(value: string): string {
return value.replace(/[&<>"']/g, (char) => {
switch (char) {
case '&':
return '&amp;';
case '<':
return '&lt;';
case '>':
return '&gt;';
case '"':
return '&quot;';
default:
return '&#39;';
}
});
}

export class Utilities {
public username: string;
constructor(private readonly queryString: ParsedQs) {
Expand All @@ -13,30 +43,20 @@ export class Utilities {

private getColors() {
const theme = this.queryString.theme || 'default';
const themeColors = selectColors(theme);
const color = sanitizeColor(this.queryString.color);
return {
areaColor: this.queryString.area_color
? this.queryString.area_color
: selectColors(theme).areaColor,
bgColor: this.queryString.bg_color
? this.queryString.bg_color
: selectColors(theme).bgColor,
borderColor: this.queryString.border_color
? this.queryString.border_color
: String(this.queryString.hide_border) === 'true'
? '0000' // transparent
: selectColors(theme).borderColor,
color: this.queryString.color ? this.queryString.color : selectColors(theme).color,
titleColor: this.queryString.title_color
? this.queryString.title_color
: this.queryString.color
? this.queryString.color
: selectColors(theme).titleColor,
lineColor: this.queryString.line
? this.queryString.line
: selectColors(theme).lineColor,
pointColor: this.queryString.point
? this.queryString.point
: selectColors(theme).pointColor,
areaColor: sanitizeColor(this.queryString.area_color) ?? themeColors.areaColor,
bgColor: sanitizeColor(this.queryString.bg_color) ?? themeColors.bgColor,
borderColor:
sanitizeColor(this.queryString.border_color) ??
(String(this.queryString.hide_border) === 'true'
? '0000' // transparent
: themeColors.borderColor),
color: color ?? themeColors.color,
titleColor: sanitizeColor(this.queryString.title_color) ?? color ?? themeColors.titleColor,
lineColor: sanitizeColor(this.queryString.line) ?? themeColors.lineColor,
pointColor: sanitizeColor(this.queryString.point) ?? themeColors.pointColor,
};
}

Expand Down Expand Up @@ -145,6 +165,7 @@ export class Utilities {
}'s Contribution Graph`;
}
}
title = escapeHtml(title);

const graph = new Card(
options.height,
Expand Down Expand Up @@ -172,6 +193,9 @@ export class Utilities {

public setHttpHeader(res: Response, directivesAndAge: string): void {
res.setHeader('Cache-Control', `${directivesAndAge}`);
// Defense in depth: even if a future change reintroduces an
// injection bug, this stops any injected <script> from running.
res.setHeader('Content-Security-Policy', "script-src 'none'; sandbox");
res.set('Content-Type', 'image/svg+xml');
Comment thread
chicks-net marked this conversation as resolved.
Resolved
}
}