Skip to content

Lightweight server monitoring with historical data, docker stats, and alerts.

Fix bulk monitor copy and import for URLs containing commas (#2716)

Vo Nguyen Thai Hoc504d490ed413
diff --git a/internal/site/src/components/network-monitors-table/monitor-dialog.tsx b/internal/site/src/components/network-monitors-table/monitor-dialog.tsx
index 07eeac337..416ef4ce8 100644
--- a/internal/site/src/components/network-monitors-table/monitor-dialog.tsx
+++ b/internal/site/src/components/network-monitors-table/monitor-dialog.tsx
@@ -28,7 +28,7 @@ import { ChevronDownIcon, GlobeIcon, ListIcon, type LucideIcon, PlusIcon, Search
import { useToast } from "@/components/ui/use-toast"
import { $systems } from "@/lib/stores"
import { cn, supportsNetworkMonitors } from "@/lib/utils"
-import { getMonitorTarget, isHttpsTarget } from "@/lib/network-monitor-utils"
+import { formatMonitorFields, getMonitorTarget, isHttpsTarget, parseMonitorFields } from "@/lib/network-monitor-utils"
import type { NetworkMonitorRecord } from "@/types"
import * as v from "valibot"
@@ -182,7 +182,13 @@ function getMonitorIdentityKey({ system, target, protocol, port, server }: Monit
}
function parseBulkMonitorLine(line: string, lineNumber: number, system: string) {
- const [rawTarget = "", rawProtocol = "", rawPort = "", rawInterval = "", rawServer = ""] = line.split(",")
+ let fields: string[]
+ try {
+ fields = parseMonitorFields(line)
+ } catch (err) {
+ throw new Error(`Line ${lineNumber}: ${err instanceof Error ? err.message : "invalid monitor entry"}`)
+ }
+ const [rawTarget = "", rawProtocol = "", rawPort = "", rawInterval = "", rawServer = ""] = fields
const parsed = v.safeParse(BulkMonitorSchema, {
target: rawTarget,
protocol: rawProtocol,
@@ -211,7 +217,7 @@ export function formatBulkMonitorLine(monitor: BulkMonitorLineSource) {
const port = monitor.protocol !== "tcp" || monitor.port === 443 ? "" : `${monitor.port}`
const interval = monitor.interval === defaultInterval ? "" : `${monitor.interval}`
const server = monitor.protocol !== "dns" ? "" : monitor.server
- return trimTrailingEmptyFields([monitor.target, monitor.protocol, port, interval, server]).join(",")
+ return formatMonitorFields(trimTrailingEmptyFields([monitor.target, monitor.protocol, port, interval, server]))
}
export function SystemMultiSelect({
diff --git a/internal/site/src/lib/network-monitor-utils.ts b/internal/site/src/lib/network-monitor-utils.ts
index d76d52cf6..93d7fa6a7 100644
--- a/internal/site/src/lib/network-monitor-utils.ts
+++ b/internal/site/src/lib/network-monitor-utils.ts
@@ -111,3 +111,47 @@ export function getCertExpiryLevel(daysLeft: number): "ok" | "warning" | "critic
if (daysLeft < 14) return "warning"
return "ok"
}
+
+/** Read one bulk-monitor row, including CSV-quoted targets containing commas. */
+export function parseMonitorFields(line: string): string[] {
+ const fields: string[] = []
+ let position = 0
+ while (position <= line.length) {
+ let value = ""
+ // allow whitespace before an opening quote, e.g. an indented line or `a, "b,c"`
+ let start = position
+ while (start < line.length && /\s/.test(line[start])) start++
+ if (line[start] === '"') {
+ position = start + 1
+ let closed = false
+ while (position < line.length) {
+ const character = line[position++]
+ if (character !== '"') {
+ value += character
+ } else if (line[position] === '"') {
+ value += '"'
+ position++
+ } else {
+ closed = true
+ break
+ }
+ }
+ if (!closed) throw new Error("Unclosed quoted field")
+ while (position < line.length && /\s/.test(line[position])) position++
+ if (position < line.length && line[position] !== ",") throw new Error("Expected comma after quoted field")
+ } else {
+ const end = line.indexOf(",", position)
+ const next = end === -1 ? line.length : end
+ value = line.slice(position, next)
+ position = next
+ }
+ fields.push(value)
+ if (position === line.length) break
+ position++
+ }
+ return fields
+}
+
+export function formatMonitorFields(fields: string[]): string {
+ return fields.map((field) => (/[",]/.test(field) ? `"${field.replaceAll('"', '""')}"` : field)).join(",")
+}
diff --git a/internal/site/tests/network-monitor-utils.test.ts b/internal/site/tests/network-monitor-utils.test.ts
index 16c69aeae..25232da83 100644
--- a/internal/site/tests/network-monitor-utils.test.ts
+++ b/internal/site/tests/network-monitor-utils.test.ts
@@ -5,9 +5,14 @@ mock.module("@lingui/core/macro", () => ({
plural: (_count: number, forms: { other?: string }) => forms.other ?? "",
}))
-const { getMonitorStats, mergeMonitorStats, mergeSameTimestamps, withMonitorGaps } = await import(
- "../src/lib/network-monitor-utils"
-)
+const {
+ formatMonitorFields,
+ getMonitorStats,
+ mergeMonitorStats,
+ mergeSameTimestamps,
+ parseMonitorFields,
+ withMonitorGaps,
+} = await import("../src/lib/network-monitor-utils")
describe("monitor stats derived from stored counts", () => {
test("retains probe weights and response precision", () => {
@@ -124,3 +129,43 @@ describe("merging stats across monitors", () => {
expect(remaining.map((r) => r.created)).toEqual([120_000])
})
})
+
+describe("bulk monitor rows", () => {
+ test.each(
+ [
+ ["1.1.1.1", "icmp"],
+ ["example.com", "tcp", "8080", "60"],
+ ["example.com", "dns", "", "", "1.1.1.1"],
+ ["https://example.com/status?ids=1,2", "http", "", "60"],
+ ['https://example.com/status?q="a,b"', "http"],
+ ["", "http", ""],
+ ].map((fields) => ({ fields }))
+ )("round-trips $fields", ({ fields }) => {
+ expect(parseMonitorFields(formatMonitorFields(fields))).toEqual(fields)
+ })
+
+ test("keeps the existing unquoted format for ordinary entries", () => {
+ expect(formatMonitorFields(["example.com", "tcp", "", "60"])).toBe("example.com,tcp,,60")
+ expect(parseMonitorFields("example.com,tcp,,60")).toEqual(["example.com", "tcp", "", "60"])
+ })
+
+ test("does not treat a quoted target's comma as its protocol separator", () => {
+ expect(parseMonitorFields('"https://example.com/status?ids=1,2",http')).toEqual([
+ "https://example.com/status?ids=1,2",
+ "http",
+ ])
+ })
+
+ test("allows whitespace before a quoted field", () => {
+ expect(parseMonitorFields(' "https://example.com/status?ids=1,2",http')).toEqual([
+ "https://example.com/status?ids=1,2",
+ "http",
+ ])
+ expect(parseMonitorFields('example.com, "a,b", 53')).toEqual(["example.com", "a,b", " 53"])
+ })
+
+ test("rejects malformed quoted rows instead of shifting fields", () => {
+ expect(() => parseMonitorFields('"https://example.com,status,http')).toThrow("Unclosed quoted field")
+ expect(() => parseMonitorFields('"example.com"extra,tcp')).toThrow("Expected comma after quoted field")
+ })
+})