Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
Fix trpc router (#1888)
Thibault Le Ouay443bb37486a6
diff --git a/packages/api/src/router/maintenance.test.ts b/packages/api/src/router/maintenance.test.tsnew file mode 100644index 000000000..156c48668--- /dev/null+++ b/packages/api/src/router/maintenance.test.ts@@ -0,0 +1,111 @@+import { afterAll, beforeAll, expect, test } from "bun:test";+import { db, eq } from "@openstatus/db";+import {+ maintenance,+ maintenancesToPageComponents,+} from "@openstatus/db/src/schema";+import { TRPCError } from "@trpc/server";++import { edgeRouter } from "../edge";+import { createInnerTRPCContext } from "../trpc";++let otherWorkspaceMaintenanceId: number;++beforeAll(async () => {+ // Maintenance for workspace 2, referencing page 1 (page ownership is not+ // enforced at DB level, only at API level, so this insert works for testing)+ const m = await db+ .insert(maintenance)+ .values({+ workspaceId: 2,+ title: "Other workspace maintenance",+ message: "Scheduled maintenance",+ pageId: 1,+ from: new Date(),+ to: new Date(Date.now() + 3_600_000),+ })+ .returning()+ .get();+ otherWorkspaceMaintenanceId = m.id;++ await db+ .insert(maintenancesToPageComponents)+ .values({+ maintenanceId: otherWorkspaceMaintenanceId,+ pageComponentId: 1,+ })+ .run();+});++afterAll(async () => {+ await db+ .delete(maintenancesToPageComponents)+ .where(+ eq(+ maintenancesToPageComponents.maintenanceId,+ otherWorkspaceMaintenanceId,+ ),+ );+ await db+ .delete(maintenance)+ .where(eq(maintenance.id, otherWorkspaceMaintenanceId));+});++test("maintenance.update rejects maintenance from another workspace", async () => {+ const ctx = createInnerTRPCContext({+ req: undefined,+ session: { user: { id: "1" } },+ // @ts-expect-error - minimal workspace for test+ workspace: { id: 1 },+ });+ const caller = edgeRouter.createCaller(ctx);++ try {+ await caller.maintenance.update({+ id: otherWorkspaceMaintenanceId,+ title: "Unauthorized Modification",+ message: "Should not work",+ startDate: new Date(),+ endDate: new Date(Date.now() + 3_600_000),+ pageComponents: [],+ });+ throw new Error("Should have thrown");+ } catch (e) {+ expect(e).toBeInstanceOf(TRPCError);+ expect((e as TRPCError).code).toBe("NOT_FOUND");+ }++ // Verify page component associations were NOT deleted+ const associations = await db.query.maintenancesToPageComponents.findMany({+ where: eq(+ maintenancesToPageComponents.maintenanceId,+ otherWorkspaceMaintenanceId,+ ),+ });+ expect(associations.length).toBe(1);+});++test("maintenance.update succeeds for own workspace maintenance", async () => {+ const ctx = createInnerTRPCContext({+ req: undefined,+ session: { user: { id: "1" } },+ // @ts-expect-error - minimal workspace for test+ workspace: { id: 1 },+ });+ const caller = edgeRouter.createCaller(ctx);++ // Seed maintenance 1 belongs to workspace 1+ await caller.maintenance.update({+ id: 1,+ title: "Updated Maintenance Title",+ message: "Updated message",+ startDate: new Date(),+ endDate: new Date(Date.now() + 7_200_000),+ pageComponents: [1],+ });++ const updated = await db.query.maintenance.findFirst({+ where: eq(maintenance.id, 1),+ });+ expect(updated?.title).toBe("Updated Maintenance Title");+});diff --git a/packages/api/src/router/maintenance.ts b/packages/api/src/router/maintenance.tsindex 1757c31b6..2b2ed6b25 100644--- a/packages/api/src/router/maintenance.ts+++ b/packages/api/src/router/maintenance.ts@@ -182,12 +182,21 @@ export const maintenanceRouter = createTRPCRouter({}}- await opts.ctx.db.transaction(async (tx) => {- const whereConditions: SQL[] = [+ const existing = await opts.ctx.db.query.maintenance.findFirst({+ where: and(eq(maintenance.id, opts.input.id),eq(maintenance.workspaceId, opts.ctx.workspace.id),- ];+ ),+ });++ if (!existing) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Maintenance not found",+ });+ }+ await opts.ctx.db.transaction(async (tx) => {// Update the maintenanceconst _maintenance = await tx.update(maintenance)@@ -199,7 +208,12 @@ export const maintenanceRouter = createTRPCRouter({workspaceId: opts.ctx.workspace.id,updatedAt: new Date(),})- .where(and(...whereConditions))+ .where(+ and(+ eq(maintenance.id, opts.input.id),+ eq(maintenance.workspaceId, opts.ctx.workspace.id),+ ),+ ).returning().get();diff --git a/packages/api/src/router/monitor.test.ts b/packages/api/src/router/monitor.test.tsindex 4bab71d80..ae4cff535 100644--- a/packages/api/src/router/monitor.test.ts+++ b/packages/api/src/router/monitor.test.ts@@ -1,6 +1,11 @@import { afterAll, beforeAll, expect, test } from "bun:test";import { db, eq } from "@openstatus/db";-import { monitorTag, monitorTagsToMonitors } from "@openstatus/db/src/schema";+import {+ monitorTag,+ monitorTagsToMonitors,+ privateLocationToMonitors,+} from "@openstatus/db/src/schema";+import { allPlans } from "@openstatus/db/src/schema/plan/config";import { TRPCError } from "@trpc/server";import { edgeRouter } from "../edge";@@ -93,3 +98,57 @@ test("monitor.updateNotifiers succeeds for own workspace monitor", async () => {await caller.monitor.updateNotifiers({ id: 1, notifiers: [1] });});++test("monitor.updateSchedulingRegions rejects monitor from another workspace", async () => {+ // Monitor 5 belongs to workspace 3; try to update it from workspace 1+ const ctx = createInnerTRPCContext({+ req: undefined,+ session: { user: { id: "1" } },+ // @ts-expect-error - minimal workspace for test+ workspace: { id: 1, limits: allPlans.team.limits },+ });+ const caller = edgeRouter.createCaller(ctx);++ // Verify the seed private location association exists before the attack+ const before = await db.query.privateLocationToMonitors.findMany({+ where: eq(privateLocationToMonitors.monitorId, 5),+ });+ const beforeCount = before.length;++ try {+ await caller.monitor.updateSchedulingRegions({+ id: 5,+ regions: ["ams"],+ periodicity: "30s",+ privateLocations: [],+ });+ throw new Error("Should have thrown");+ } catch (e) {+ expect(e).toBeInstanceOf(TRPCError);+ expect((e as TRPCError).code).toBe("NOT_FOUND");+ }++ // Verify private location associations were NOT deleted+ const after = await db.query.privateLocationToMonitors.findMany({+ where: eq(privateLocationToMonitors.monitorId, 5),+ });+ expect(after.length).toBe(beforeCount);+});++test("monitor.updateSchedulingRegions succeeds for own workspace monitor", async () => {+ const ctx = createInnerTRPCContext({+ req: undefined,+ session: { user: { id: "1" } },+ // @ts-expect-error - minimal workspace for test+ workspace: { id: 1, limits: allPlans.team.limits },+ });+ const caller = edgeRouter.createCaller(ctx);++ // Monitor 1 belongs to workspace 1+ await caller.monitor.updateSchedulingRegions({+ id: 1,+ regions: ["ams"],+ periodicity: "1m",+ privateLocations: [],+ });+});diff --git a/packages/api/src/router/monitor.ts b/packages/api/src/router/monitor.tsindex f295877c9..4d93a2843 100644--- a/packages/api/src/router/monitor.ts+++ b/packages/api/src/router/monitor.ts@@ -431,6 +431,17 @@ export const monitorRouter = createTRPCRouter({});}+ const existingMonitor = await ctx.db.query.monitor.findFirst({+ where: and(...whereConditions),+ });++ if (!existingMonitor) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Monitor not found.",+ });+ }+await ctx.db.transaction(async (tx) => {await tx.update(monitor)diff --git a/packages/api/src/router/notification.test.ts b/packages/api/src/router/notification.test.tsindex ebd962d66..bd9167df7 100644--- a/packages/api/src/router/notification.test.ts+++ b/packages/api/src/router/notification.test.ts@@ -1,6 +1,10 @@import { afterAll, beforeAll, expect, test } from "bun:test";import { db, eq } from "@openstatus/db";-import { notification } from "@openstatus/db/src/schema";+import {+ notification,+ notificationsToMonitors,+} from "@openstatus/db/src/schema";+import { TRPCError } from "@trpc/server";import { edgeRouter } from "../edge";import { createInnerTRPCContext } from "../trpc";@@ -19,9 +23,19 @@ beforeAll(async () => {.returning().get();otherWorkspaceNotifId = notif.id;++ // Link the other workspace's notification to a monitor so we can verify+ // the junction table is not wiped by a cross-workspace updateNotifier call+ await db+ .insert(notificationsToMonitors)+ .values({ notificationId: otherWorkspaceNotifId, monitorId: 5 })+ .run();});afterAll(async () => {+ await db+ .delete(notificationsToMonitors)+ .where(eq(notificationsToMonitors.notificationId, otherWorkspaceNotifId));await db.delete(notification).where(eq(notification.id, otherWorkspaceNotifId));@@ -72,3 +86,32 @@ test("notification.delete succeeds for own workspace notification", async () =>});expect(notifAfter).toBeUndefined();});++test("notification.updateNotifier rejects notification from another workspace", async () => {+ const ctx = createInnerTRPCContext({+ req: undefined,+ session: { user: { id: "1" } },+ // @ts-expect-error - minimal workspace for test+ workspace: { id: 1 },+ });+ const caller = edgeRouter.createCaller(ctx);++ try {+ await caller.notification.updateNotifier({+ id: otherWorkspaceNotifId,+ name: "Hacked notification",+ data: { email: "[email protected]" },+ monitors: [],+ });+ throw new Error("Should have thrown");+ } catch (e) {+ expect(e).toBeInstanceOf(TRPCError);+ expect((e as TRPCError).code).toBe("NOT_FOUND");+ }++ // Verify monitor associations were NOT deleted+ const associations = await db.query.notificationsToMonitors.findMany({+ where: eq(notificationsToMonitors.notificationId, otherWorkspaceNotifId),+ });+ expect(associations.length).toBe(1);+});diff --git a/packages/api/src/router/notification.ts b/packages/api/src/router/notification.tsindex 863628a8c..67ae3d506 100644--- a/packages/api/src/router/notification.ts+++ b/packages/api/src/router/notification.ts@@ -1,7 +1,7 @@import { TRPCError } from "@trpc/server";import { z } from "zod";-import { type SQL, and, count, eq, inArray } from "@openstatus/db";+import { and, count, eq, inArray } from "@openstatus/db";import {NotificationDataSchema,googleChatDataSchema,@@ -72,10 +72,19 @@ export const notificationRouter = createTRPCRouter({}),).mutation(async (opts) => {- const whereCondition: SQL[] = [- eq(notification.id, opts.input.id),- eq(notification.workspaceId, opts.ctx.workspace.id),- ];+ const existing = await opts.ctx.db.query.notification.findFirst({+ where: and(+ eq(notification.id, opts.input.id),+ eq(notification.workspaceId, opts.ctx.workspace.id),+ ),+ });++ if (!existing) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Notification not found",+ });+ }const allMonitors = await opts.ctx.db.query.monitor.findMany({where: and(@@ -108,7 +117,12 @@ export const notificationRouter = createTRPCRouter({data: JSON.stringify(opts.input.data),updatedAt: new Date(),})- .where(and(...whereCondition));+ .where(+ and(+ eq(notification.id, opts.input.id),+ eq(notification.workspaceId, opts.ctx.workspace.id),+ ),+ );await tx.delete(notificationsToMonitors)diff --git a/packages/api/src/router/privateLocation.test.ts b/packages/api/src/router/privateLocation.test.tsnew file mode 100644index 000000000..014d0dd34--- /dev/null+++ b/packages/api/src/router/privateLocation.test.ts@@ -0,0 +1,114 @@+import { afterAll, beforeAll, expect, test } from "bun:test";+import { db, eq } from "@openstatus/db";+import {+ privateLocation,+ privateLocationToMonitors,+} from "@openstatus/db/src/schema";+import { TRPCError } from "@trpc/server";++import { edgeRouter } from "../edge";+import { createInnerTRPCContext } from "../trpc";++let otherWorkspaceLocationId: number;+let ownWorkspaceLocationId: number;++beforeAll(async () => {+ const otherLoc = await db+ .insert(privateLocation)+ .values({+ workspaceId: 2,+ name: "Other workspace location",+ token: "test-token-idor",+ })+ .returning()+ .get();+ otherWorkspaceLocationId = otherLoc.id;++ await db+ .insert(privateLocationToMonitors)+ .values({+ privateLocationId: otherWorkspaceLocationId,+ monitorId: 5,+ })+ .run();++ const ownLoc = await db+ .insert(privateLocation)+ .values({+ workspaceId: 1,+ name: "Own workspace location",+ token: "test-token-own",+ })+ .returning()+ .get();+ ownWorkspaceLocationId = ownLoc.id;+});++afterAll(async () => {+ await db+ .delete(privateLocationToMonitors)+ .where(+ eq(privateLocationToMonitors.privateLocationId, otherWorkspaceLocationId),+ );+ await db+ .delete(privateLocation)+ .where(eq(privateLocation.id, otherWorkspaceLocationId));+ await db+ .delete(privateLocationToMonitors)+ .where(+ eq(privateLocationToMonitors.privateLocationId, ownWorkspaceLocationId),+ );+ await db+ .delete(privateLocation)+ .where(eq(privateLocation.id, ownWorkspaceLocationId));+});++test("privateLocation.update rejects location from another workspace", async () => {+ const ctx = createInnerTRPCContext({+ req: undefined,+ session: { user: { id: "1" } },+ // @ts-expect-error - minimal workspace for test+ workspace: { id: 1 },+ });+ const caller = edgeRouter.createCaller(ctx);++ try {+ await caller.privateLocation.update({+ id: otherWorkspaceLocationId,+ name: "Unauthorized Name Change",+ monitors: [],+ });+ throw new Error("Should have thrown");+ } catch (e) {+ expect(e).toBeInstanceOf(TRPCError);+ expect((e as TRPCError).code).toBe("NOT_FOUND");+ }++ // Verify monitor associations were NOT deleted+ const associations = await db.query.privateLocationToMonitors.findMany({+ where: eq(+ privateLocationToMonitors.privateLocationId,+ otherWorkspaceLocationId,+ ),+ });+ expect(associations.length).toBe(1);+});++test("privateLocation.update succeeds for own workspace location", async () => {+ const ctx = createInnerTRPCContext({+ req: undefined,+ session: { user: { id: "1" } },+ // @ts-expect-error - minimal workspace for test+ workspace: { id: 1 },+ });+ const caller = edgeRouter.createCaller(ctx);++ const result = await caller.privateLocation.update({+ id: ownWorkspaceLocationId,+ name: "Updated Location Name",+ monitors: [1],+ });++ expect(result).toBeDefined();+ expect(result.name).toBe("Updated Location Name");+});diff --git a/packages/api/src/router/privateLocation.ts b/packages/api/src/router/privateLocation.tsindex f7eaa42a0..69ffd2bb4 100644--- a/packages/api/src/router/privateLocation.ts+++ b/packages/api/src/router/privateLocation.ts@@ -3,6 +3,7 @@ import {privateLocation,privateLocationToMonitors,} from "@openstatus/db/src/schema";+import { TRPCError } from "@trpc/server";import { z } from "zod";import { createTRPCRouter, protectedProcedure } from "../trpc";@@ -67,6 +68,20 @@ export const privateLocationRouter = createTRPCRouter({}),).mutation(async (opts) => {+ const existing = await opts.ctx.db.query.privateLocation.findFirst({+ where: and(+ eq(privateLocation.id, opts.input.id),+ eq(privateLocation.workspaceId, opts.ctx.workspace.id),+ ),+ });++ if (!existing) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Private location not found",+ });+ }+return await opts.ctx.db.transaction(async (tx) => {const _privateLocation = await tx.update(privateLocation)diff --git a/packages/api/src/router/statusReport.test.ts b/packages/api/src/router/statusReport.test.tsindex 8b524ef77..d3400448b 100644--- a/packages/api/src/router/statusReport.test.ts+++ b/packages/api/src/router/statusReport.test.ts@@ -1,12 +1,17 @@import { afterAll, beforeAll, expect, test } from "bun:test";import { db, eq } from "@openstatus/db";-import { page, statusReport } from "@openstatus/db/src/schema";+import {+ page,+ statusReport,+ statusReportsToPageComponents,+} from "@openstatus/db/src/schema";import { TRPCError } from "@trpc/server";import { edgeRouter } from "../edge";import { createInnerTRPCContext } from "../trpc";let otherWorkspacePageId: number;+let otherWorkspaceReportId: number;beforeAll(async () => {const p = await db@@ -21,9 +26,34 @@ beforeAll(async () => {.returning().get();otherWorkspacePageId = p.id;++ const report = await db+ .insert(statusReport)+ .values({+ workspaceId: 2,+ title: "Other workspace report",+ status: "investigating",+ pageId: otherWorkspacePageId,+ })+ .returning()+ .get();+ otherWorkspaceReportId = report.id;++ await db+ .insert(statusReportsToPageComponents)+ .values({ statusReportId: otherWorkspaceReportId, pageComponentId: 1 })+ .run();});afterAll(async () => {+ await db+ .delete(statusReportsToPageComponents)+ .where(+ eq(statusReportsToPageComponents.statusReportId, otherWorkspaceReportId),+ );+ await db+ .delete(statusReport)+ .where(eq(statusReport.id, otherWorkspaceReportId));await db.delete(page).where(eq(page.id, otherWorkspacePageId));});@@ -75,3 +105,58 @@ test("statusReport.create succeeds for own workspace page", async () => {// Clean upawait db.delete(statusReport).where(eq(statusReport.id, result.id));});++test("statusReport.updateStatus rejects report from another workspace", async () => {+ const ctx = createInnerTRPCContext({+ req: undefined,+ session: { user: { id: "1" } },+ // @ts-expect-error - minimal workspace for test+ workspace: { id: 1 },+ });+ const caller = edgeRouter.createCaller(ctx);++ try {+ await caller.statusReport.updateStatus({+ id: otherWorkspaceReportId,+ pageComponents: [],+ title: "Unauthorized Modification",+ status: "investigating",+ });+ throw new Error("Should have thrown");+ } catch (e) {+ expect(e).toBeInstanceOf(TRPCError);+ expect((e as TRPCError).code).toBe("NOT_FOUND");+ }++ // Verify page component associations were NOT deleted+ const associations = await db.query.statusReportsToPageComponents.findMany({+ where: eq(+ statusReportsToPageComponents.statusReportId,+ otherWorkspaceReportId,+ ),+ });+ expect(associations.length).toBe(1);+});++test("statusReport.updateStatus succeeds for own workspace report", async () => {+ const ctx = createInnerTRPCContext({+ req: undefined,+ session: { user: { id: "1" } },+ // @ts-expect-error - minimal workspace for test+ workspace: { id: 1 },+ });+ const caller = edgeRouter.createCaller(ctx);++ // Seed status report 1 belongs to workspace 1+ await caller.statusReport.updateStatus({+ id: 1,+ pageComponents: [1],+ title: "Updated Title",+ status: "resolved",+ });++ const updated = await db.query.statusReport.findFirst({+ where: eq(statusReport.id, 1),+ });+ expect(updated?.title).toBe("Updated Title");+});diff --git a/packages/api/src/router/statusReport.ts b/packages/api/src/router/statusReport.tsindex 840e0918c..ceb3cda6d 100644--- a/packages/api/src/router/statusReport.ts+++ b/packages/api/src/router/statusReport.ts@@ -264,6 +264,20 @@ export const statusReportRouter = createTRPCRouter({}),).mutation(async (opts) => {+ const existing = await opts.ctx.db.query.statusReport.findFirst({+ where: and(+ eq(statusReport.id, opts.input.id),+ eq(statusReport.workspaceId, opts.ctx.workspace.id),+ ),+ });++ if (!existing) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Status report not found",+ });+ }+await opts.ctx.db.transaction(async (tx) => {await tx.update(statusReport)