Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
Add SSRF protection to monitor URL validation (#2566)
Maximilian Kaske9d2cdc049fdc
diff --git a/apps/server/src/routes/rpc/handlers/monitor/__tests__/monitor.test.ts b/apps/server/src/routes/rpc/handlers/monitor/__tests__/monitor.test.tsindex 098e2e804..91b33ac27 100644--- a/apps/server/src/routes/rpc/handlers/monitor/__tests__/monitor.test.ts+++ b/apps/server/src/routes/rpc/handlers/monitor/__tests__/monitor.test.ts@@ -1343,6 +1343,97 @@ describe("MonitorService.UpdateDNSMonitor", () => {});});+describe("MonitorService - private and internal URLs", () => {+ // Valid URIs, so protovalidate passes them through to the service guard.+ const BLOCKED = [+ "http://localhost:3000",+ "http://127.0.0.1/health",+ "http://192.168.1.10/",+ "http://169.254.169.254/latest/meta-data/",+ ];++ for (const url of BLOCKED) {+ test(`CreateHTTPMonitor rejects ${url}`, async () => {+ const res = await connectRequest(+ "CreateHTTPMonitor",+ {+ monitor: {+ name: `${TEST_PREFIX}-ssrf`,+ url,+ periodicity: "PERIODICITY_5M",+ method: "HTTP_METHOD_GET",+ },+ },+ { "x-openstatus-key": "1" },+ );++ expect(res.status).toBe(400);++ const data = await res.json();+ expect(data.message).toContain("private or internal");++ const leaked = await db+ .select()+ .from(monitor)+ .where(and(eq(monitor.workspaceId, 1), eq(monitor.url, url)))+ .get();+ expect(leaked).toBeUndefined();+ });+ }++ test("UpdateHTTPMonitor rejects a private URL and leaves the stored one intact", async () => {+ const before = await db+ .select()+ .from(monitor)+ .where(eq(monitor.id, testHttpMonitorId))+ .get();++ const res = await connectRequest(+ "UpdateHTTPMonitor",+ {+ id: String(testHttpMonitorId),+ monitor: { url: "http://127.0.0.1:8080" },+ },+ { "x-openstatus-key": "1" },+ );++ expect(res.status).toBe(400);++ const data = await res.json();+ expect(data.message).toContain("private or internal");++ const after = await db+ .select()+ .from(monitor)+ .where(eq(monitor.id, testHttpMonitorId))+ .get();+ expect(after?.url).toBe(before?.url);+ });++ test("CreateTCPMonitor accepts a private target", async () => {+ const res = await connectRequest(+ "CreateTCPMonitor",+ {+ monitor: {+ name: `${TEST_PREFIX}-ssrf-tcp`,+ uri: "192.168.1.10:8080",+ periodicity: "PERIODICITY_10M",+ },+ },+ { "x-openstatus-key": "1" },+ );++ expect(res.status).toBe(200);++ const data = await res.json();+ expect(data.monitor.uri).toBe("192.168.1.10:8080");++ if (data.monitor.id) {+ await db.delete(monitor).where(eq(monitor.id, Number(data.monitor.id)));+ }+ });+});+describe("MonitorService.TriggerMonitor", () => {test("returns 404 for non-existent monitor", async () => {const res = await connectRequest(diff --git a/apps/server/src/routes/v1/check/http/post.test.ts b/apps/server/src/routes/v1/check/http/post.test.tsindex ab47edfa1..68612aff3 100644--- a/apps/server/src/routes/v1/check/http/post.test.ts+++ b/apps/server/src/routes/v1/check/http/post.test.ts@@ -79,6 +79,30 @@ test("Create a single check ", async () => {});});+for (const url of [+ "http://localhost:3000",+ "http://127.0.0.1/health",+ "http://192.168.1.10/",+ "http://169.254.169.254/latest/meta-data/",+]) {+ test(`rejects a check against ${url} without probing it`, async () => {+ const res = await app.request("/v1/check/http", {+ method: "POST",+ headers: {+ "x-openstatus-key": "1",+ "content-type": "application/json",+ },+ body: JSON.stringify({ url, regions: ["ams"], method: "GET" }),+ });++ expect(res.status).toBe(400);+ // Pin the reason so a schema change can't turn this into a passing+ // test that never reaches the guard.+ expect((await res.json()).message).toContain("private or internal");+ expect(mockFetch).not.toHaveBeenCalled();+ });+}+test("Create a multiple check", async () => {const data = {url: "https://www.openstatus.dev",diff --git a/apps/server/src/routes/v1/check/http/post.ts b/apps/server/src/routes/v1/check/http/post.tsindex 99f34b433..3bf01a0bb 100644--- a/apps/server/src/routes/v1/check/http/post.ts+++ b/apps/server/src/routes/v1/check/http/post.ts@@ -7,6 +7,7 @@ import percentile from "percentile";import { env } from "@/env";import { openApiErrorResponses } from "@/libs/errors";+import { assertSafeMonitorUrl } from "../../monitors/utils";import type { checkApi } from "../index";const logger = getLogger("api-server");@@ -54,6 +55,9 @@ export function registerHTTPPostCheck(api: typeof checkApi) {const { headers, regions, runCount, aggregated, ...rest } = data;+ // Guard before the insert so a rejected target leaves no `check` row.+ assertSafeMonitorUrl({ jobType: "http", url: data.url });+const newCheck = await db.insert(check).values({diff --git a/apps/server/src/routes/v1/monitors/post.ts b/apps/server/src/routes/v1/monitors/post.tsindex 733774eb1..9125f61a9 100644--- a/apps/server/src/routes/v1/monitors/post.ts+++ b/apps/server/src/routes/v1/monitors/post.ts@@ -9,7 +9,7 @@ import { trackMiddleware } from "@/libs/middlewares";import type { monitorsApi } from "./index";import { MonitorSchema } from "./schema";-import { getAssertions } from "./utils";+import { assertSafeMonitorUrl, getAssertions } from "./utils";const postRoute = createRoute({method: "post",@@ -93,6 +93,9 @@ export function registerPostMonitor(api: typeof monitorsApi) {});}+ // `jobType` is nullable on the wire; the column defaults to "http".+ assertSafeMonitorUrl({ jobType: input.jobType ?? "http", url: input.url });+const { headers, regions, assertions, ...rest } = input;const assert = assertions ? getAssertions(assertions) : [];diff --git a/apps/server/src/routes/v1/monitors/post_http.ts b/apps/server/src/routes/v1/monitors/post_http.tsindex d4747cb93..65121278c 100644--- a/apps/server/src/routes/v1/monitors/post_http.ts+++ b/apps/server/src/routes/v1/monitors/post_http.ts@@ -9,7 +9,7 @@ import { trackMiddleware } from "@/libs/middlewares";import type { monitorsApi } from "./index";import { HTTPMonitorSchema, MonitorSchema } from "./schema";-import { getAssertionNew } from "./utils";+import { assertSafeMonitorUrl, getAssertionNew } from "./utils";const postRoute = createRoute({method: "post",@@ -85,6 +85,8 @@ export function registerPostMonitorHTTP(api: typeof monitorsApi) {}}+ assertSafeMonitorUrl({ jobType: "http", url: input.request.url });+const { request, regions, assertions, openTelemetry, ...rest } = input;const headers = input.request.headersdiff --git a/apps/server/src/routes/v1/monitors/put.ts b/apps/server/src/routes/v1/monitors/put.tsindex 15b913951..2bb43b564 100644--- a/apps/server/src/routes/v1/monitors/put.ts+++ b/apps/server/src/routes/v1/monitors/put.ts@@ -9,7 +9,7 @@ import { trackMiddleware } from "@/libs/middlewares";import type { monitorsApi } from "./index";import { MonitorSchema, ParamsSchema } from "./schema";-import { getAssertions } from "./utils";+import { assertSafeMonitorUrl, getAssertions } from "./utils";const putRoute = createRoute({method: "put",@@ -100,6 +100,10 @@ export function registerPutMonitor(api: typeof monitorsApi) {});}+ if (input.url !== undefined) {+ assertSafeMonitorUrl({ jobType: _monitor.jobType, url: input.url });+ }+const { headers, regions, assertions, ...rest } = input;const assert = assertions ? getAssertions(assertions) : [];diff --git a/apps/server/src/routes/v1/monitors/put_http.ts b/apps/server/src/routes/v1/monitors/put_http.tsindex 5d6f6842e..591679f81 100644--- a/apps/server/src/routes/v1/monitors/put_http.ts+++ b/apps/server/src/routes/v1/monitors/put_http.ts@@ -9,7 +9,7 @@ import { trackMiddleware } from "@/libs/middlewares";import type { monitorsApi } from "./index";import { HTTPMonitorSchema, MonitorSchema, ParamsSchema } from "./schema";-import { getAssertionNew } from "./utils";+import { assertSafeMonitorUrl, getAssertionNew } from "./utils";const putRoute = createRoute({method: "put",@@ -92,6 +92,8 @@ export function registerPutHTTPMonitor(api: typeof monitorsApi) {});}+ assertSafeMonitorUrl({ jobType: "http", url: input.request.url });+const { request, regions, assertions, openTelemetry, ...rest } = input;const headers = input.request.headersdiff --git a/apps/server/src/routes/v1/monitors/utils.ts b/apps/server/src/routes/v1/monitors/utils.tsindex 119dd29c2..25fd4cb10 100644--- a/apps/server/src/routes/v1/monitors/utils.ts+++ b/apps/server/src/routes/v1/monitors/utils.ts@@ -4,10 +4,35 @@ import {StatusAssertion,TextBodyAssertion,} from "@openstatus/assertions";+import { ServiceError } from "@openstatus/services";+import { assertMonitorUrlSafe } from "@openstatus/services/monitor";import type { z } from "zod";+import { OpenStatusApiError } from "@/libs/errors";+import type { assertion, assertionsSchema } from "./schema";+/**+ * These routes write to the DB directly instead of going through+ * `@openstatus/services`, so the SSRF guard has to be invoked by hand.+ */+export function assertSafeMonitorUrl(args: {+ jobType: string;+ url: string;+}): void {+ try {+ assertMonitorUrlSafe(args);+ } catch (err) {+ if (err instanceof ServiceError) {+ throw new OpenStatusApiError({+ code: "BAD_REQUEST",+ message: err.message,+ });+ }+ throw err;+ }+}+export const getAssertions = (assertions: z.infer<typeof assertion>[],): Assertion[] => {diff --git a/packages/services/src/monitor/__tests__/url-safety.test.ts b/packages/services/src/monitor/__tests__/url-safety.test.tsnew file mode 100644index 000000000..4d7256af1--- /dev/null+++ b/packages/services/src/monitor/__tests__/url-safety.test.ts@@ -0,0 +1,138 @@+import { selectWorkspaceSchema } from "@openstatus/db/src/schema";+import { createWorkspace } from "@openstatus/db/src/test/factories";+import { expect } from "@std/expect";+import { beforeAll, describe, test } from "@std/testing/bdd";++import { makeUserCtx, withTestTransaction } from "../../../test/helpers";+import type { ServiceContext } from "../../context";+import { ValidationError } from "../../errors";+import { createMonitor } from "../create";+import { updateMonitorConfig, updateMonitorGeneral } from "../update";++const TEST_PREFIX = "svc-monitor-url-safety";++let ctx: ServiceContext;++beforeAll(async () => {+ const ws = selectWorkspaceSchema.parse(await createWorkspace());+ ctx = makeUserCtx(ws, { userId: 1 });+});++const BLOCKED = [+ "http://localhost:3000",+ "http://127.0.0.1/health",+ "http://192.168.1.10/",+ "http://10.0.0.1/",+ "http://172.16.0.1/",+ "http://169.254.169.254/latest/meta-data/",+ "http://metadata.google.internal/",+ "http://[::1]/",+ "http://[::ffff:7f00:1]/",+];++function httpInput(url: string) {+ return {+ name: `${TEST_PREFIX}-monitor`,+ jobType: "http" as const,+ url,+ method: "GET" as const,+ headers: [],+ assertions: [],+ active: false,+ };+}++describe("monitor url SSRF guard", () => {+ test("createMonitor rejects private and internal http targets", async () => {+ for (const url of BLOCKED) {+ await withTestTransaction(async (tx) => {+ await expect(+ createMonitor({ ctx: { ...ctx, db: tx }, input: httpInput(url) }),+ ).rejects.toThrow(ValidationError);+ });+ }+ });++ test("createMonitor allows public http targets", async () => {+ await withTestTransaction(async (tx) => {+ const row = await createMonitor({+ ctx: { ...ctx, db: tx },+ input: httpInput("https://example.com/health"),+ });+ expect(row.url).toBe("https://example.com/health");+ });+ });++ test("tcp and dns monitors are not url-checked", async () => {+ await withTestTransaction(async (tx) => {+ const tcp = await createMonitor({+ ctx: { ...ctx, db: tx },+ input: { ...httpInput("127.0.0.1:8080"), jobType: "tcp" },+ });+ expect(tcp.url).toBe("127.0.0.1:8080");++ const dns = await createMonitor({+ ctx: { ...ctx, db: tx },+ input: { ...httpInput("localhost"), jobType: "dns" },+ });+ expect(dns.url).toBe("localhost");+ });+ });++ test("updateMonitorGeneral rejects a private target", async () => {+ await withTestTransaction(async (tx) => {+ const created = await createMonitor({+ ctx: { ...ctx, db: tx },+ input: httpInput("https://example.com"),+ });++ await expect(+ updateMonitorGeneral({+ ctx: { ...ctx, db: tx },+ input: {+ id: created.id,+ name: created.name,+ jobType: "http",+ url: "http://127.0.0.1:8080",+ method: "GET",+ headers: [],+ assertions: [],+ active: false,+ },+ }),+ ).rejects.toThrow(ValidationError);+ });+ });++ test("updateMonitorConfig rejects a private target using the stored jobType", async () => {+ await withTestTransaction(async (tx) => {+ const created = await createMonitor({+ ctx: { ...ctx, db: tx },+ input: httpInput("https://example.com"),+ });++ await expect(+ updateMonitorConfig({+ ctx: { ...ctx, db: tx },+ input: { id: created.id, url: "http://localhost:3000" },+ }),+ ).rejects.toThrow(ValidationError);+ });+ });++ test("updateMonitorConfig leaves tcp urls alone", async () => {+ await withTestTransaction(async (tx) => {+ const created = await createMonitor({+ ctx: { ...ctx, db: tx },+ input: { ...httpInput("example.com:443"), jobType: "tcp" },+ });++ const updated = await updateMonitorConfig({+ ctx: { ...ctx, db: tx },+ input: { id: created.id, url: "10.0.0.5:8080" },+ });++ expect(updated.url).toBe("10.0.0.5:8080");+ });+ });+});diff --git a/packages/services/src/monitor/create.ts b/packages/services/src/monitor/create.tsindex 7b7343012..c1bd5aca9 100644--- a/packages/services/src/monitor/create.ts+++ b/packages/services/src/monitor/create.ts@@ -11,6 +11,7 @@ import {serialiseAssertions,} from "./internal";import { CreateMonitorInput } from "./schemas";+import { assertMonitorUrlSafe } from "./url-safety";export async function createMonitor(args: {ctx: ServiceContext;@@ -20,6 +21,8 @@ export async function createMonitor(args: {requireScope(ctx, "write");const input = CreateMonitorInput.parse(args.input);+ assertMonitorUrlSafe({ jobType: input.jobType, url: input.url });+return withTransaction(ctx, async (tx) => {await assertWithinLimit({tx,diff --git a/packages/services/src/monitor/index.ts b/packages/services/src/monitor/index.tsindex 699f9d1b8..87ce2d9ec 100644--- a/packages/services/src/monitor/index.ts+++ b/packages/services/src/monitor/index.ts@@ -39,6 +39,7 @@ export {streamMonitorPreview,} from "./stream-monitor-preview";export { triggerMonitorRun, type TriggerMonitorResult } from "./trigger";+export { assertMonitorUrlSafe } from "./url-safety";export {bulkUpdateMonitors,updateMonitorConfig,diff --git a/packages/services/src/monitor/update.ts b/packages/services/src/monitor/update.tsindex 63d079487..c4e8c916f 100644--- a/packages/services/src/monitor/update.ts+++ b/packages/services/src/monitor/update.ts@@ -20,6 +20,7 @@ import {UpdateMonitorResponseTimeInput,UpdateMonitorRetryInput,} from "./schemas";+import { assertMonitorUrlSafe } from "./url-safety";/*** Apply a whole-object patch in a single UPDATE. `undefined` fields are@@ -40,6 +41,11 @@ export async function updateMonitorConfig(args: {workspaceId: ctx.workspace.id,});+ if (input.url !== undefined) {+ // `jobType` is absent from this patch, so the stored type decides.+ assertMonitorUrlSafe({ jobType: existing.jobType, url: input.url });+ }+const values: Record<string, unknown> = { updatedAt: new Date() };if (input.name !== undefined) values.name = input.name;if (input.url !== undefined) values.url = input.url;@@ -103,6 +109,7 @@ export async function updateMonitorGeneral(args: {const { ctx } = args;requireScope(ctx, "write");const input = UpdateMonitorGeneralInput.parse(args.input);+ assertMonitorUrlSafe({ jobType: input.jobType, url: input.url });return withTransaction(ctx, async (tx) => {const existing = await getMonitorInWorkspace({diff --git a/packages/services/src/monitor/url-safety.ts b/packages/services/src/monitor/url-safety.tsnew file mode 100644index 000000000..869be9a3d--- /dev/null+++ b/packages/services/src/monitor/url-safety.ts@@ -0,0 +1,26 @@+import { assertSafeUrlSync } from "@openstatus/utils";++import { ValidationError } from "../errors";++/**+ * Reject monitor URLs pointing at private/internal infrastructure.+ *+ * Only `http` is checked: TCP takes `host:port` and DNS a bare hostname,+ * neither of which parses as a URL, and TCP documents private targets as a+ * supported input.+ */+export function assertMonitorUrlSafe(args: {+ jobType: string;+ url: string;+}): void {+ if (args.jobType !== "http") return;++ try {+ assertSafeUrlSync(args.url);+ } catch (err) {+ throw new ValidationError(+ err instanceof Error ? err.message : "Invalid URL",+ err,+ );+ }+}