Skip to content

Commit

Permalink
feat: ensure the label names are sanitised (#2121)
Browse files Browse the repository at this point in the history
Co-authored-by: Bartlomiej Obecny <bobecny@gmail.com>
Co-authored-by: Weyert de Boer <weyert.deboer@tapico.io>
Co-authored-by: Daniel Dyla <dyladan@users.noreply.github.com>
  • Loading branch information
4 people authored Apr 21, 2021
1 parent c516264 commit 4f9d2b2
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -111,17 +111,19 @@ function stringify(
let labelsStr = '';

for (const [key, val] of Object.entries(labels)) {
const sanitizedLabelName = sanitizePrometheusMetricName(key);
hasLabel = true;
labelsStr += `${labelsStr.length > 0 ? ',' : ''}${key}="${escapeLabelValue(
val
)}"`;
labelsStr += `${
labelsStr.length > 0 ? ',' : ''
}${sanitizedLabelName}="${escapeLabelValue(val)}"`;
}
if (additionalLabels) {
for (const [key, val] of Object.entries(additionalLabels)) {
const sanitizedLabelName = sanitizePrometheusMetricName(key);
hasLabel = true;
labelsStr += `${
labelsStr.length > 0 ? ',' : ''
}${key}="${escapeLabelValue(val)}"`;
}${sanitizedLabelName}="${escapeLabelValue(val)}"`;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,34 @@ describe('PrometheusSerializer', () => {
`} 1 ${mockedHrTimeMs}\n`
);
});

it('should sanitize label names', async () => {
const serializer = new PrometheusSerializer();

const meter = new MeterProvider({
processor: new ExactProcessor(SumAggregator),
}).getMeter('test');
const counter = meter.createCounter('test') as CounterMetric;
// if you try to use a label name like account-id prometheus will complain
// with an error like:
// error while linting: text format parsing error in line 282: expected '=' after label name, found '-'
counter
.bind(({
'account-id': '123456',
} as unknown) as Labels)
.add(1);
const records = await counter.getMetricRecord();
const record = records[0];

const result = serializer.serializeRecord(
record.descriptor.name,
record
);
assert.strictEqual(
result,
`test{account_id="123456"} 1 ${mockedHrTimeMs}\n`
);
});
});
});
});

0 comments on commit 4f9d2b2

Please sign in to comment.