mirror of https://github.com/wg-easy/wg-easy
committed by
GitHub
3 changed files with 52 additions and 2 deletions
@ -0,0 +1,17 @@ |
|||
export function escapePrometheusLabelValue(value: string): string { |
|||
return value |
|||
.replaceAll('\\', '\\\\') |
|||
.replaceAll('\n', '\\n') |
|||
.replaceAll('"', '\\"'); |
|||
} |
|||
|
|||
export function formatPrometheusLabels( |
|||
labels: Record<string, string | number | boolean> |
|||
): string { |
|||
return Object.entries(labels) |
|||
.map( |
|||
([name, value]) => |
|||
`${name}="${escapePrometheusLabelValue(String(value))}"` |
|||
) |
|||
.join(','); |
|||
} |
|||
@ -0,0 +1,26 @@ |
|||
import { describe, expect, test } from 'vitest'; |
|||
|
|||
import { |
|||
escapePrometheusLabelValue, |
|||
formatPrometheusLabels, |
|||
} from '#server/utils/prometheus'; |
|||
|
|||
describe('Prometheus label formatting', () => { |
|||
test('escapes quotes, backslashes, and newlines in label values', () => { |
|||
expect(escapePrometheusLabelValue('vpn"client')).toBe('vpn\\"client'); |
|||
expect(escapePrometheusLabelValue('path\\client')).toBe('path\\\\client'); |
|||
expect(escapePrometheusLabelValue('line one\nline two')).toBe( |
|||
'line one\\nline two' |
|||
); |
|||
}); |
|||
|
|||
test('formats escaped values without changing scalar values', () => { |
|||
expect( |
|||
formatPrometheusLabels({ |
|||
interface: 'wg"0', |
|||
enabled: true, |
|||
name: 'home\\office\npeer', |
|||
}) |
|||
).toBe('interface="wg\\"0",enabled="true",name="home\\\\office\\npeer"'); |
|||
}); |
|||
}); |
|||
Loading…
Reference in new issue