From 4a2429d316b171873956bf43803d0fe4560665b0 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 21 Sep 2026 10:22:46 -0700 Subject: [PATCH 1/2] docker capture fixes --- client/src/Pages/CreateMonitor/index.tsx | 15 +++-- .../ContainerDetails/Components/StatBoxes.tsx | 5 +- .../Docker/ContainerDetails/TabOverview.tsx | 6 +- .../Components/DockerContainersTable.tsx | 4 +- .../src/Pages/Logs/components/StatGauges.tsx | 3 +- client/src/Pages/Logs/components/Stats.tsx | 2 +- client/src/Utils/FormatUtils.ts | 3 + client/src/Validation/monitor.ts | 21 ++----- .../src/api/validation/monitorValidation.ts | 19 +++--- server/src/domain/monitors/monitor.service.ts | 26 +++++++- server/src/service/network/DockerProvider.ts | 28 ++++++--- .../providers/network/dockerProvider.test.ts | 40 +++++++++++++ .../test/unit/services/monitorService.test.ts | 59 +++++++++++++++++++ 13 files changed, 180 insertions(+), 51 deletions(-) diff --git a/client/src/Pages/CreateMonitor/index.tsx b/client/src/Pages/CreateMonitor/index.tsx index 7f2305d24..1de12d265 100644 --- a/client/src/Pages/CreateMonitor/index.tsx +++ b/client/src/Pages/CreateMonitor/index.tsx @@ -351,6 +351,7 @@ const CreateMonitorPage = () => { const watchedType = watch("type") as MonitorType; const watchedUrl = watch("url") as string; + const isCaptureDocker = watchedType === "docker" && isCaptureDockerUrl(watchedUrl); const watchedMethod = watch("method") as HttpMethod | undefined; const watchedProxyMode = watch("proxyMode") as ProxyMode | undefined; const watchedUseAdvancedMatching = watch("useAdvancedMatching") as boolean; @@ -381,6 +382,13 @@ const CreateMonitorPage = () => { } }, [watchedType, showTypeSelector, reset, clearErrors]); + // The logs switch is hidden for Capture hosts, so a value left over from a socket host must not be submitted. + useEffect(() => { + if (isCaptureDocker) { + setValue("dockerLogsEnabled", false); + } + }, [isCaptureDocker, setValue]); + const generalSettingsConfig = useMemo( () => getGeneralSettingsConfig(watchedType, t), [watchedType, t] @@ -711,8 +719,7 @@ const CreateMonitorPage = () => { )} {/* Capture API secret - used by hardware and Capture-backed Docker monitors */} - {(generalSettingsConfig.showSecret || - (watchedType === "docker" && isCaptureDockerUrl(watchedUrl))) && ( + {(generalSettingsConfig.showSecret || isCaptureDocker) && ( { )} /> )} - {watchedType === "docker" && isCaptureDockerUrl(watchedUrl) && ( + {isCaptureDocker && ( { /> )} - {showStep(1) && watchedType === "docker" && !isCaptureDockerUrl(watchedUrl) && ( + {showStep(1) && watchedType === "docker" && !isCaptureDocker && ( - {dedupedPorts.length === 0 && —} + {dedupedPorts.length === 0 && {PLACEHOLDER}} {dedupedPorts.map((port) => { const containerPort = `${port.privatePort}/${port.protocol}`; const label = @@ -117,7 +117,7 @@ export const TabOverview = ({ Volumes - {!mounts?.length && —} + {!mounts?.length && {PLACEHOLDER}} {mounts?.map((mount) => { return ( diff --git a/client/src/Pages/Docker/HostDetails/Components/DockerContainersTable.tsx b/client/src/Pages/Docker/HostDetails/Components/DockerContainersTable.tsx index 72d828f45..b76aca968 100644 --- a/client/src/Pages/Docker/HostDetails/Components/DockerContainersTable.tsx +++ b/client/src/Pages/Docker/HostDetails/Components/DockerContainersTable.tsx @@ -12,7 +12,7 @@ import type { Header } from "@/Components/design-elements/Table"; import type { DockerContainerInfo } from "@/Types/Check"; // Utils -import { formatPercentage } from "@/Utils/FormatUtils"; +import { formatPercentage, PLACEHOLDER } from "@/Utils/FormatUtils"; interface DockerContainersTableProps { monitorId: string | undefined; @@ -91,7 +91,7 @@ export const DockerContainersTable = ({ id: "restarts", content: t("common.labels.restarts"), render: (row) => { - return {row.restartCount}; + return {row.restartCount ?? PLACEHOLDER}; }, }, ]; diff --git a/client/src/Pages/Logs/components/StatGauges.tsx b/client/src/Pages/Logs/components/StatGauges.tsx index 9abcbbaed..19be51c09 100644 --- a/client/src/Pages/Logs/components/StatGauges.tsx +++ b/client/src/Pages/Logs/components/StatGauges.tsx @@ -1,7 +1,7 @@ import Box from "@mui/material/Box"; import { DetailGauge } from "@/Components/design-elements"; -import { getPercentage, formatPercentageFromWhole } from "@/Utils/FormatUtils"; +import { getPercentage, formatPercentageFromWhole, PLACEHOLDER } from "@/Utils/FormatUtils"; import prettyBytes from "pretty-bytes"; import { useTranslation } from "react-i18next"; import { useTheme } from "@mui/material"; @@ -11,7 +11,6 @@ interface StatGaugesProps { diagnostics: Diagnostics | null; } -const PLACEHOLDER = "—"; export const StatGauges = ({ diagnostics }: StatGaugesProps) => { const theme = useTheme(); diff --git a/client/src/Pages/Logs/components/Stats.tsx b/client/src/Pages/Logs/components/Stats.tsx index d76aa7443..45d2199e1 100644 --- a/client/src/Pages/Logs/components/Stats.tsx +++ b/client/src/Pages/Logs/components/Stats.tsx @@ -6,12 +6,12 @@ import { useTheme } from "@mui/material"; import { useTranslation } from "react-i18next"; import type { Diagnostics } from "@/Types/Diagnostics"; import { formatDuration, formatMs } from "@/Utils/TimeUtils"; +import { PLACEHOLDER } from "@/Utils/FormatUtils"; interface StatsProps { diagnostics: Diagnostics | null; } -const PLACEHOLDER = "—"; export const Stats = ({ diagnostics }: StatsProps) => { const { t } = useTranslation(); diff --git a/client/src/Utils/FormatUtils.ts b/client/src/Utils/FormatUtils.ts index 52c1e9076..4a0dac5ed 100644 --- a/client/src/Utils/FormatUtils.ts +++ b/client/src/Utils/FormatUtils.ts @@ -47,3 +47,6 @@ export const getPercentage = (value: number, total: number) => { if (!value || !total) return 0; return (value / total) * 100; }; + +// Shown wherever a value is not available for the current data source. +export const PLACEHOLDER = "—"; diff --git a/client/src/Validation/monitor.ts b/client/src/Validation/monitor.ts index a17ed021c..682c76a7e 100644 --- a/client/src/Validation/monitor.ts +++ b/client/src/Validation/monitor.ts @@ -267,21 +267,12 @@ export const monitorSchema = monitorSchemaUnion.superRefine((data, ctx) => { }); } - if (data.type === "docker" && isCaptureDockerUrl(data.url)) { - if (!data.secret.trim()) { - ctx.addIssue({ - code: "custom", - path: ["secret"], - message: "Capture API secret is required", - }); - } - if (data.dockerLogsEnabled) { - ctx.addIssue({ - code: "custom", - path: ["dockerLogsEnabled"], - message: "Capture-backed Docker monitors do not support container logs", - }); - } + if (data.type === "docker" && isCaptureDockerUrl(data.url) && !data.secret.trim()) { + ctx.addIssue({ + code: "custom", + path: ["secret"], + message: "Capture API secret is required", + }); } if (data.type === "docker" && isDockerTlsUrl(data.url)) { diff --git a/server/src/api/validation/monitorValidation.ts b/server/src/api/validation/monitorValidation.ts index 50e932aed..651cf786d 100644 --- a/server/src/api/validation/monitorValidation.ts +++ b/server/src/api/validation/monitorValidation.ts @@ -134,15 +134,11 @@ const refineDockerUrl = (data: { type?: string; url?: string }, ctx: z.Refinemen } }; -const refineCaptureDocker = - (mode: "create" | "edit") => (data: { type?: string; url?: string; secret?: string; dockerLogsEnabled?: boolean }, ctx: z.RefinementCtx) => { - if (data.type !== "docker" || !isCaptureDockerUrl(data.url)) return; - const secretMissing = mode === "create" ? !data.secret?.trim() : data.secret !== undefined && !data.secret.trim(); - if (secretMissing) ctx.addIssue({ code: "custom", path: ["secret"], message: "Capture API secret is required" }); - if (data.dockerLogsEnabled) { - ctx.addIssue({ code: "custom", path: ["dockerLogsEnabled"], message: "Capture-backed Docker monitors do not support container logs" }); - } - }; +// Edits are checked in the monitor service against the stored secret, since the body may omit either the url or the secret. +const refineCaptureSecret = (data: { type?: string; url?: string; secret?: string }, ctx: z.RefinementCtx) => { + if (data.type !== "docker" || !isCaptureDockerUrl(data.url)) return; + if (!data.secret?.trim()) ctx.addIssue({ code: "custom", path: ["secret"], message: "Capture API secret is required" }); +}; type DockerTlsFields = { type?: string; @@ -236,7 +232,7 @@ export const createMonitorBodyValidation = z .superRefine(refineRegexPattern) .superRefine(refineProxySelection) .superRefine(refineDockerUrl) - .superRefine(refineCaptureDocker("create")) + .superRefine(refineCaptureSecret) .superRefine(refineDockerTls("create")); export const editMonitorBodyValidation = z @@ -286,7 +282,6 @@ export const editMonitorBodyValidation = z .superRefine(refineRegexPattern) .superRefine(refineProxySelection) .superRefine(refineDockerUrl) - .superRefine(refineCaptureDocker("edit")) .superRefine(refineDockerTls("edit")); export const pauseMonitorParamValidation = z.object({ @@ -366,7 +361,7 @@ const importedMonitorSchema = z .superRefine(refineRegexPattern) .superRefine(refineProxySelection) .superRefine(refineDockerUrl) - .superRefine(refineCaptureDocker("create")); + .superRefine(refineCaptureSecret); export const importMonitorsBodyValidation = z.object({ monitors: z.array(importedMonitorSchema).min(1, "At least one monitor is required"), diff --git a/server/src/domain/monitors/monitor.service.ts b/server/src/domain/monitors/monitor.service.ts index 5d02098ba..54dc96527 100644 --- a/server/src/domain/monitors/monitor.service.ts +++ b/server/src/domain/monitors/monitor.service.ts @@ -34,7 +34,7 @@ import { IJobScheduler } from "@/worker/worker.interface.js"; import { DateRange } from "@/types/query.js"; import { IDockerLogsRepository } from "@/domain/docker/docker-log.repository.interface.js"; import { IEncryptionService } from "@/service/encryption/encryptionService.js"; -import { isDockerTlsUrl } from "@/utils/dockerHost.js"; +import { isCaptureDockerUrl, isDockerTlsUrl } from "@/utils/dockerHost.js"; const SERVICE_NAME = "MonitorService"; @@ -194,6 +194,9 @@ export class MonitorService implements IMonitorService { // Encrypt docker TLS keys this.encryptDockerTls(body, "create"); + if (body.type === "docker" && isCaptureDockerUrl(body.url)) { + body.dockerLogsEnabled = false; + } const monitor = await this.monitorsRepository.create(body, teamId, userId); if (!monitor) { @@ -561,6 +564,7 @@ export class MonitorService implements IMonitorService { }); } } + await this.normalizeCaptureDocker(body, monitorId, teamId); const editedMonitor = await this.monitorsRepository.updateById(monitorId, teamId, body, { unsetProxyId }); await this.scheduler.updateJob(editedMonitor); return editedMonitor; @@ -749,6 +753,26 @@ export class MonitorService implements IMonitorService { return { imported: createdMonitors!.length, errors }; }; + // Capture-backed Docker monitors authenticate with the API secret and never collect logs; socket and TLS hosts have no secret. + private normalizeCaptureDocker = async (body: Partial, monitorId: string, teamId: string) => { + if (body.type !== "docker") return; + + if (body.url !== undefined && !isCaptureDockerUrl(body.url)) { + body.secret = ""; + return; + } + if (body.url === undefined && body.secret === undefined) return; + + const stored = await this.monitorsRepository.findById(monitorId, teamId); + if (body.url === undefined && !isCaptureDockerUrl(stored.url)) return; + + body.dockerLogsEnabled = false; + const secret = body.secret === undefined ? stored.secret : body.secret.trim(); + if (!secret) { + throw new AppError({ message: "Capture API secret is required", status: 422, service: SERVICE_NAME, method: "editMonitor" }); + } + }; + private encryptDockerTls = (body: Partial, mode: "create" | "edit") => { if (body.type !== "docker" && mode === "create") return; diff --git a/server/src/service/network/DockerProvider.ts b/server/src/service/network/DockerProvider.ts index e429dfca5..39011a13b 100644 --- a/server/src/service/network/DockerProvider.ts +++ b/server/src/service/network/DockerProvider.ts @@ -151,14 +151,16 @@ export class DockerProvider implements IStatusProvider { private toCaptureContainer(container: CaptureDockerContainer): DockerContainerInfo { const startedAt = container.started_at && container.started_at > 0 ? new Date(container.started_at * 1000).toISOString() : undefined; - const stats = container.stats - ? { - cpuPct: container.stats.cpu_percent / 100, - memoryUsedBytes: container.stats.memory_usage, - memoryLimitBytes: container.stats.memory_limit, - memoryPct: container.stats.memory_percent / 100, - } - : {}; + // Capture reports zeroed stats for stopped containers; only running ones carry real metrics, matching toContainerInfo. + const stats = + container.status === "running" && container.stats + ? { + cpuPct: container.stats.cpu_percent / 100, + memoryUsedBytes: container.stats.memory_usage, + memoryLimitBytes: container.stats.memory_limit, + memoryPct: container.stats.memory_percent / 100, + } + : {}; return { id: container.container_id, name: container.container_name || container.container_id.slice(0, 12), @@ -177,6 +179,14 @@ export class DockerProvider implements IStatusProvider { }; } + private isCapturePayload = (payload: unknown): payload is CaptureDockerStatusPayload => { + if (!payload || typeof payload !== "object") return false; + const { data, errors } = payload as Partial; + if (!Array.isArray(data) && data !== null) return false; + if (errors === undefined || errors === null) return true; + return Array.isArray(errors) && errors.every((error) => Array.isArray(error?.metric)); + }; + private handleCapture = async (monitor: Monitor, ctx?: CheckContext): Promise> => { const captureUrl = new URL(monitor.url.trim()); captureUrl.searchParams.set("all", "true"); @@ -184,7 +194,7 @@ export class DockerProvider implements IStatusProvider { if (!response.status) return this.failed(monitor, response.code, response.message, response.responseTime ?? 0); const payload = response.payload; - if (!payload || typeof payload === "string" || (!Array.isArray(payload.data) && payload.data !== null)) { + if (!this.isCapturePayload(payload)) { this.logger.warn({ message: "Capture returned an invalid Docker metrics payload", service: SERVICE_NAME, diff --git a/server/test/unit/providers/network/dockerProvider.test.ts b/server/test/unit/providers/network/dockerProvider.test.ts index 19ffe7137..a90e2b65f 100644 --- a/server/test/unit/providers/network/dockerProvider.test.ts +++ b/server/test/unit/providers/network/dockerProvider.test.ts @@ -289,6 +289,46 @@ describe("DockerProvider", () => { message: "Capture returned an invalid Docker metrics payload", }); }); + + it("rejects a malformed errors field as an invalid payload instead of throwing", async () => { + const httpHandle = jest.fn(); + const { provider } = setup({ httpHandle }); + const monitor = makeMonitor({ url: "http://capture:59232/api/v1/metrics/docker", secret: "secret" }); + + for (const errors of [{}, [{ err: "no metric" }], [{ metric: "docker.client", err: "x" }]]) { + httpHandle.mockResolvedValueOnce(makeCaptureResponse({ payload: { data: [], errors } })); + const result = await provider.handle(monitor); + expect(result).toMatchObject({ + status: false, + code: NETWORK_ERROR, + message: "Capture returned an invalid Docker metrics payload", + }); + } + }); + + it("records no stats for containers that are not running", async () => { + const response = makeCaptureResponse({ + payload: { + data: [ + makeCaptureContainer({ + status: "exited", + running: false, + stats: { cpu_percent: 0, memory_usage: 0, memory_limit: 0, memory_percent: 0 }, + }), + ], + errors: [], + }, + }); + const { provider } = setup({ httpHandle: jest.fn().mockResolvedValue(response) }); + + const result = await provider.handle(makeMonitor({ url: "http://capture:59232/api/v1/metrics/docker", secret: "secret" })); + + const [container] = result.payload!.containers; + expect(container.state).toBe("exited"); + expect(container).not.toHaveProperty("cpuPct"); + expect(container).not.toHaveProperty("memoryPct"); + expect(container).not.toHaveProperty("memoryUsedBytes"); + }); }); // ── TLS host urls ──────────────────────────────────────────────────── diff --git a/server/test/unit/services/monitorService.test.ts b/server/test/unit/services/monitorService.test.ts index 31328cd18..bc8c13c20 100644 --- a/server/test/unit/services/monitorService.test.ts +++ b/server/test/unit/services/monitorService.test.ts @@ -2160,4 +2160,63 @@ describe("MonitorService — Docker TLS credentials", () => { expect(monitorsRepository.updateById).not.toHaveBeenCalled(); }); }); + + describe("editMonitor for Capture hosts", () => { + const captureUrl = "http://capture:59232/api/v1/metrics/docker"; + + it("rejects a url change to Capture with a 422 when no secret is stored or provided", async () => { + const monitorsRepository = createMonitorsRepositoryMock(); + (monitorsRepository.findById as jest.Mock).mockResolvedValue(makeMonitor({ type: "docker", url: "unix:///var/run/docker.sock" })); + const { service } = createService({ monitorsRepository }); + + await expectAppError( + () => service.editMonitor({ teamId: TEAM_ID, monitorId: MONITOR_ID, body: { type: "docker", url: captureUrl } }), + 422, + /Capture API secret is required/ + ); + expect(monitorsRepository.updateById).not.toHaveBeenCalled(); + }); + + it("keeps the stored secret and disables logs when only the url changes to Capture", async () => { + const monitorsRepository = createMonitorsRepositoryMock(); + (monitorsRepository.findById as jest.Mock).mockResolvedValue(makeMonitor({ type: "docker", secret: "stored-secret", dockerLogsEnabled: true })); + (monitorsRepository.updateById as jest.Mock).mockResolvedValue(makeMonitor({ type: "docker" })); + const { service } = createService({ monitorsRepository }); + + await service.editMonitor({ teamId: TEAM_ID, monitorId: MONITOR_ID, body: { type: "docker", url: captureUrl } }); + + const [, , patch] = (monitorsRepository.updateById as jest.Mock).mock.calls[0] as [string, string, Record]; + expect(patch).not.toHaveProperty("secret"); + expect(patch.dockerLogsEnabled).toBe(false); + }); + + it("rejects a blank secret against a stored Capture url when the body omits the url", async () => { + const monitorsRepository = createMonitorsRepositoryMock(); + (monitorsRepository.findById as jest.Mock).mockResolvedValue(makeMonitor({ type: "docker", url: captureUrl, secret: "stored-secret" })); + const { service } = createService({ monitorsRepository }); + + await expectAppError( + () => service.editMonitor({ teamId: TEAM_ID, monitorId: MONITOR_ID, body: { type: "docker", secret: " " } }), + 422, + /Capture API secret is required/ + ); + expect(monitorsRepository.updateById).not.toHaveBeenCalled(); + }); + + it("clears the secret without reading the stored monitor when the url changes to a socket", async () => { + const monitorsRepository = createMonitorsRepositoryMock(); + (monitorsRepository.updateById as jest.Mock).mockResolvedValue(makeMonitor({ type: "docker" })); + const { service } = createService({ monitorsRepository }); + + await service.editMonitor({ + teamId: TEAM_ID, + monitorId: MONITOR_ID, + body: { type: "docker", url: "unix:///var/run/docker.sock", secret: "stale-capture-secret" }, + }); + + expect(monitorsRepository.findById).not.toHaveBeenCalled(); + const [, , patch] = (monitorsRepository.updateById as jest.Mock).mock.calls[0] as [string, string, Record]; + expect(patch.secret).toBe(""); + }); + }); }); From fe6f755451afc0fdd94bc8283afdbde526492c3a Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 21 Sep 2026 10:26:53 -0700 Subject: [PATCH 2/2] add readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7d7cd463f..1de4e16d1 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,7 @@ The **Docker host** field accepts three forms: | Remote daemon | `tcp://docker.example.com:2376` | Always uses mutual TLS; the port defaults to `2376`. Unencrypted daemons on `2375` are not supported. | | Capture agent | `https://capture.example.com/api/v1/metrics/docker` | Enter the full endpoint ending in `/metrics/docker` and its authorization secret. Checkmate requests `all=true` so stopped containers are included. | -Capture-backed monitors normalize Capture's container state, health, CPU, memory, start time and exposed ports into the same Docker pages. Capture does not currently provide restart counts, mounts, published host-port bindings or container logs, so those values are shown as unavailable. +Capture-backed monitors normalize Capture's container state, health, CPU, memory, start time and exposed ports into the same Docker pages. Capture does not currently provide restart counts, mounts, published host-port bindings or container logs, so those values are shown as unavailable. Capture also reports a container whose health check is still starting as healthy, so the `starting` health state only appears on direct monitors, and stopped containers carry no CPU or memory metrics. **Monitoring the local socket.** The reference Compose file does not mount the socket, so add it and grant the container the host's `docker` group. The image runs as an unprivileged user and cannot read the socket otherwise. Find the group id with `stat -c %g /var/run/docker.sock`, then: