Skip to content
Open
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
8 changes: 3 additions & 5 deletions lib/registry.js
Original file line number Diff line number Diff line change
Expand Up @@ -303,11 +303,9 @@ function flattenSharedLabels(labels) {
sharedLabelCache.set(labels, flattened);
return flattened;
}
function escapeLabelValue(str) {
if (typeof str !== 'string') {
return str;
}
return escapeString(str).replace(/"/g, '\\"');
function escapeLabelValue(value) {
// String() handles Symbols; template coercion throws on them
return escapeString(String(value)).replace(/"/g, '\\"');
}
function escapeString(str) {
return str.replace(/\\/g, '\\\\').replace(/\n/g, '\\n');
Expand Down
51 changes: 51 additions & 0 deletions test/registerTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,57 @@ describe('Register', () => {
expect(escapedResult).toMatch(/\\"/);
});

it('should escape quotes and newlines in non-string label values', async () => {
register.registerMetric({
async get() {
return {
name: 'test_metric',
type: 'gauge',
help: 'A test metric',
values: [
{
value: 1,
labels: {
x: ['say "hi"'],
},
},
{
value: 2,
labels: {
y: ['a\nb'],
},
},
],
};
},
});
const escapedResult = await register.metrics();
expect(escapedResult).toContain('x="say \\"hi\\""');
expect(escapedResult).toContain('y="a\\nb"');
});

it('should coerce Symbol label values without throwing', async () => {
register.registerMetric({
async get() {
return {
name: 'test_metric',
type: 'gauge',
help: 'A test metric',
values: [
{
value: 1,
labels: {
sym: Symbol('x'),
},
},
],
};
},
});
const escapedResult = await register.metrics();
expect(escapedResult).toContain('sym="Symbol(x)"');
});

describe('should output metrics as JSON', () => {
it('should output metrics as JSON', async () => {
register.registerMetric(getMetric());
Expand Down