Reworked non-ascii tag filtering for prometheus metrics

This commit is contained in:
Rick van Drongelen 2025-05-21 12:43:47 +02:00
parent ed1b696d5b
commit 5366212347
No known key found for this signature in database

View file

@ -41,10 +41,10 @@ class Prometheus {
* @param {Array<object>} tags Tags to add to the monitor * @param {Array<object>} tags Tags to add to the monitor
*/ */
constructor(monitor, tags) { constructor(monitor, tags) {
let sanitizedTags = this.sanitizeTags(tags); let filteredValidAsciiTags = this.filterValidAsciiTags(tags);
if (sanitizedTags.length <= 0) { if (filteredValidAsciiTags.length <= 0) {
sanitizedTags = "null"; filteredValidAsciiTags = "null";
} }
this.monitorLabelValues = { this.monitorLabelValues = {
@ -53,34 +53,28 @@ class Prometheus {
monitor_url: monitor.url, monitor_url: monitor.url,
monitor_hostname: monitor.hostname, monitor_hostname: monitor.hostname,
monitor_port: monitor.port, monitor_port: monitor.port,
monitor_tags: sanitizedTags monitor_tags: filteredValidAsciiTags
}; };
} }
/** /**
* Sanitize tags to remove non-ASCII characters * Filter tags to remove the ones that contain non-ASCII characters
* See https://github.com/louislam/uptime-kuma/pull/4704#issuecomment-2366524692 * See https://github.com/louislam/uptime-kuma/pull/4704#issuecomment-2366524692
* @param {Array<object>} tags The tags to sanitize * @param {Array<{name: string, value:string}>} tags The tags to filter
* @returns {*[]} The sanitized tags * @returns {string[]} The filtered tags
*/ */
sanitizeTags(tags) { filterValidAsciiTags(tags) {
const nonAsciiRegex = /[^\x00-\x7F]/g; const asciiRegex = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
const sanitizedTags = []; return tags.reduce((filteredTags, tag) => {
tags.forEach((tag) => { if (asciiRegex.test(tag.name)) {
if (tag.name.match(nonAsciiRegex) || tag.value.match(nonAsciiRegex)) { if (tag.value !== "" && asciiRegex.test(tag.value)) {
// If the tag name or value contains non-ASCII characters, skip it filteredTags.push(`${tag.name}:${tag.value}`);
return; } else {
filteredTags.push(tag.name);
}
} }
return filteredTags;
if (tag.value !== "") { }, []);
sanitizedTags.push(tag.name + ":" + tag.value);
return;
}
sanitizedTags.push(tag.name);
});
return sanitizedTags;
} }
/** /**