From 4db95cfa449baa0ad7622630364ee693fc991f95 Mon Sep 17 00:00:00 2001 From: gorkem-bwl Date: Thu, 7 May 2026 12:29:26 -0400 Subject: [PATCH 1/5] fix(maintenance): stop silent deletion of one-time maintenance windows Maintenance windows could disappear seconds after creation when the API received a payload with end dates already in the past. The repository auto-set expiry = end for one-time windows (repeat = 0), and Mongo's TTL index on the expiry field then deleted the row on its next sweep. This was particularly visible with automation tools sending payloads in non-UTC timezones. ## Changes ### Validator hardening - Add .strict() to create + edit body schemas so unknown keys return 400 instead of being silently dropped. - Refine end > start on create. - Refine end > now for one-time create payloads (repeat = 0). - Refine end > start on edit when both are provided. - Remove the accepted expiry field from both schemas. ### Stop the auto-delete behaviour - Repository.create no longer copies end into expiry. - Schema's expiry field + TTL index removed. - Migration 0007 drops the live TTL index and unsets stale expiry values on existing rows so legacy data is no longer at risk. ### Client - Form submission no longer includes expiry. --- client/src/Pages/Maintenance/create/index.tsx | 4 -- .../0007_dropMaintenanceWindowExpiryIndex.ts | 48 +++++++++++++++ server/src/db/migration/index.ts | 2 + server/src/db/models/MaintenanceWindow.ts | 5 -- .../MongoMaintenanceWindowsRepository.ts | 5 -- .../validation/maintenanceWindowValidation.ts | 58 ++++++++++++------- 6 files changed, 86 insertions(+), 36 deletions(-) create mode 100644 server/src/db/migration/0007_dropMaintenanceWindowExpiryIndex.ts diff --git a/client/src/Pages/Maintenance/create/index.tsx b/client/src/Pages/Maintenance/create/index.tsx index d130ee7c7..44a4b9a81 100644 --- a/client/src/Pages/Maintenance/create/index.tsx +++ b/client/src/Pages/Maintenance/create/index.tsx @@ -85,10 +85,6 @@ const CreateMaintenanceWindowPage = () => { repeat, }; - if (repeat === 0) { - payload.expiry = endDateTime.toISOString(); - } - return payload; }; diff --git a/server/src/db/migration/0007_dropMaintenanceWindowExpiryIndex.ts b/server/src/db/migration/0007_dropMaintenanceWindowExpiryIndex.ts new file mode 100644 index 000000000..850ab19ef --- /dev/null +++ b/server/src/db/migration/0007_dropMaintenanceWindowExpiryIndex.ts @@ -0,0 +1,48 @@ +import { MaintenanceWindowModel } from "../models/MaintenanceWindow.js"; +import { logger } from "@/utils/logger.js"; + +/** + * Drops the TTL index on MaintenanceWindow.expiry and unsets the expiry field. + * + * Earlier versions auto-set expiry = end for one-time maintenance windows. Combined with the + * TTL index ({ expires: "0s" }), this caused Mongo to silently delete completed one-time + * windows shortly after their end-date passed — including windows whose end-date was already + * in the past at creation time (e.g. timezone-mismatched payloads from automation tools). + * The fix stops writing expiry on create, and this migration removes the index and stale field + * so legacy rows are no longer at risk of being deleted by the TTL monitor. + */ +export async function dropMaintenanceWindowExpiryIndex(): Promise { + const SERVICE_NAME = "Migration:DropMaintenanceWindowExpiryIndex"; + + try { + const collection = MaintenanceWindowModel.collection; + const indexes = await collection.indexes(); + const expiryIndex = indexes.find((idx) => idx.key && idx.key.expiry === 1); + + if (expiryIndex?.name) { + await collection.dropIndex(expiryIndex.name); + logger.info({ + service: SERVICE_NAME, + message: `Dropped TTL index ${expiryIndex.name} on MaintenanceWindow.expiry`, + }); + } else { + logger.info({ + service: SERVICE_NAME, + message: "No TTL index found on MaintenanceWindow.expiry", + }); + } + + const result = await collection.updateMany({ expiry: { $exists: true } }, { $unset: { expiry: "" } }); + logger.info({ + service: SERVICE_NAME, + message: `Unset expiry on ${result.modifiedCount} maintenance windows`, + }); + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + logger.error({ + service: SERVICE_NAME, + message: `Error dropping expiry index: ${errorMessage}`, + }); + throw error; + } +} diff --git a/server/src/db/migration/index.ts b/server/src/db/migration/index.ts index 5b74a96fc..fcf0cf1fb 100644 --- a/server/src/db/migration/index.ts +++ b/server/src/db/migration/index.ts @@ -5,6 +5,7 @@ import { fixInfrastructureThresholds } from "./0004_fixInfrastructureThresholds. import MigrationModel from "../models/Migration.js"; import { migrateStatusPageTypeToArray } from "./0005_migrateStatusPageTypeToArray.js"; import { cleanupDuplicateMonitorStatsForUniqueIndex } from "./0006_cleanupDuplicateMonitorStatsForUniqueIndex.js"; +import { dropMaintenanceWindowExpiryIndex } from "./0007_dropMaintenanceWindowExpiryIndex.js"; import type { ILogger } from "@/utils/logger.js"; type MigrationEntry = { @@ -19,6 +20,7 @@ const migrations: MigrationEntry[] = [ { name: "0004_fixInfrastructureThresholds", execute: fixInfrastructureThresholds }, { name: "0005_migrateStatusPageTypeToArray", execute: migrateStatusPageTypeToArray }, { name: "0006_cleanupDuplicateMonitorStatsForUniqueIndex", execute: cleanupDuplicateMonitorStatsForUniqueIndex }, + { name: "0007_dropMaintenanceWindowExpiryIndex", execute: dropMaintenanceWindowExpiryIndex }, ]; const runMigrations = async (logger?: ILogger) => { diff --git a/server/src/db/models/MaintenanceWindow.ts b/server/src/db/models/MaintenanceWindow.ts index 311cf97bf..e3287ce7c 100644 --- a/server/src/db/models/MaintenanceWindow.ts +++ b/server/src/db/models/MaintenanceWindow.ts @@ -6,7 +6,6 @@ type MaintenanceWindowDocumentBase = Omit( end: { type: Date, }, - expiry: { - type: Date, - index: { expires: "0s" }, - }, }, { timestamps: true, diff --git a/server/src/repositories/maintenance-windows/MongoMaintenanceWindowsRepository.ts b/server/src/repositories/maintenance-windows/MongoMaintenanceWindowsRepository.ts index ad96328c5..0cdda805e 100644 --- a/server/src/repositories/maintenance-windows/MongoMaintenanceWindowsRepository.ts +++ b/server/src/repositories/maintenance-windows/MongoMaintenanceWindowsRepository.ts @@ -45,11 +45,6 @@ class MongoMaintenanceWindowsRepository implements IMaintenanceWindowsRepository create = async (data: Partial): Promise => { const maintenanceWindow = new MaintenanceWindowModel(data); - - // If the maintenance window is a one time window, set the expiry to the end date - if (maintenanceWindow.repeat === 0) { - maintenanceWindow.expiry = maintenanceWindow.end; - } const result = await maintenanceWindow.save(); return this.toEntity(result); }; diff --git a/server/src/validation/maintenanceWindowValidation.ts b/server/src/validation/maintenanceWindowValidation.ts index bee06e7bc..5d83b3fed 100644 --- a/server/src/validation/maintenanceWindowValidation.ts +++ b/server/src/validation/maintenanceWindowValidation.ts @@ -7,17 +7,26 @@ const dateToString = z.coerce.date().transform((d) => d.toISOString()); // Maintenance Window Validations //**************************************** -export const createMaintenanceWindowBodyValidation = z.object({ - monitors: z.array(z.string()).min(1, "At least one monitor is required"), - name: z.string().min(1, "Name is required"), - active: z.boolean().optional(), - duration: z.number().min(1, "Duration is required"), - durationUnit: z.enum(["seconds", "minutes", "hours", "days"]), - start: dateToString, - end: dateToString, - repeat: z.number().min(0, "Repeat must be a non-negative number"), - expiry: dateToString.optional(), -}); +export const createMaintenanceWindowBodyValidation = z + .object({ + monitors: z.array(z.string()).min(1, "At least one monitor is required"), + name: z.string().min(1, "Name is required"), + active: z.boolean().optional(), + duration: z.number().min(1, "Duration is required"), + durationUnit: z.enum(["seconds", "minutes", "hours", "days"]), + start: dateToString, + end: dateToString, + repeat: z.number().min(0, "Repeat must be a non-negative number"), + }) + .strict() + .refine((data) => new Date(data.end).getTime() > new Date(data.start).getTime(), { + message: "End must be after start", + path: ["end"], + }) + .refine((data) => data.repeat > 0 || new Date(data.end).getTime() > Date.now(), { + message: "End must be in the future for one-time maintenance windows", + path: ["end"], + }); export const getMaintenanceWindowByIdParamValidation = z.object({ id: z.string().min(1, "ID is required"), @@ -43,14 +52,19 @@ export const editMaintenanceWindowByIdParamValidation = z.object({ id: z.string().min(1, "ID is required"), }); -export const editMaintenanceByIdWindowBodyValidation = z.object({ - active: z.boolean().optional(), - name: z.string().optional(), - repeat: z.number().optional(), - start: dateToString.optional(), - end: dateToString.optional(), - expiry: dateToString.optional(), - monitors: z.array(z.string()).optional(), - duration: z.number().optional(), - durationUnit: z.enum(["seconds", "minutes", "hours", "days"]).optional(), -}); +export const editMaintenanceByIdWindowBodyValidation = z + .object({ + active: z.boolean().optional(), + name: z.string().optional(), + repeat: z.number().optional(), + start: dateToString.optional(), + end: dateToString.optional(), + monitors: z.array(z.string()).optional(), + duration: z.number().optional(), + durationUnit: z.enum(["seconds", "minutes", "hours", "days"]).optional(), + }) + .strict() + .refine((data) => !data.start || !data.end || new Date(data.end).getTime() > new Date(data.start).getTime(), { + message: "End must be after start", + path: ["end"], + }); From bd059da94a3027d7a196a5483067c398107224be Mon Sep 17 00:00:00 2001 From: gorkem-bwl Date: Thu, 7 May 2026 12:33:03 -0400 Subject: [PATCH 2/5] refactor(maintenance): tighten validator + migration per /simplify - Collapse two refines into a single superRefine in createMaintenanceWindowBodyValidation; same on edit. - Match peer migration convention: use mongoose.connection.db directly, not Model.collection. - Tighten TTL index detection: require expireAfterSeconds + single-field key. - Add Starting log at migration top to match peers 0003-0006. --- .../0007_dropMaintenanceWindowExpiryIndex.ts | 30 +++++++++----- .../validation/maintenanceWindowValidation.ts | 39 ++++++++++++++----- 2 files changed, 49 insertions(+), 20 deletions(-) diff --git a/server/src/db/migration/0007_dropMaintenanceWindowExpiryIndex.ts b/server/src/db/migration/0007_dropMaintenanceWindowExpiryIndex.ts index 850ab19ef..38e55c0d7 100644 --- a/server/src/db/migration/0007_dropMaintenanceWindowExpiryIndex.ts +++ b/server/src/db/migration/0007_dropMaintenanceWindowExpiryIndex.ts @@ -1,23 +1,33 @@ -import { MaintenanceWindowModel } from "../models/MaintenanceWindow.js"; +import mongoose from "mongoose"; import { logger } from "@/utils/logger.js"; /** - * Drops the TTL index on MaintenanceWindow.expiry and unsets the expiry field. + * Drops the TTL index on MaintenanceWindow.expiry and unsets the field on existing rows. * - * Earlier versions auto-set expiry = end for one-time maintenance windows. Combined with the - * TTL index ({ expires: "0s" }), this caused Mongo to silently delete completed one-time - * windows shortly after their end-date passed — including windows whose end-date was already - * in the past at creation time (e.g. timezone-mismatched payloads from automation tools). - * The fix stops writing expiry on create, and this migration removes the index and stale field - * so legacy rows are no longer at risk of being deleted by the TTL monitor. + * Why: a previous version copied `end` into `expiry` for one-time windows. Combined with the + * TTL index on `expiry`, this caused Mongo to silently delete rows whose `end` was in the past + * at creation time (a common symptom for automation tools sending non-UTC timestamps). The + * fix stops writing `expiry`; this migration removes the live exposure on existing installs. */ export async function dropMaintenanceWindowExpiryIndex(): Promise { const SERVICE_NAME = "Migration:DropMaintenanceWindowExpiryIndex"; try { - const collection = MaintenanceWindowModel.collection; + logger.info({ + service: SERVICE_NAME, + message: "Starting drop of MaintenanceWindow.expiry TTL index", + }); + + const db = mongoose.connection.db; + if (!db) { + throw new Error("Mongo connection not initialized"); + } + const collection = db.collection("maintenancewindows"); + const indexes = await collection.indexes(); - const expiryIndex = indexes.find((idx) => idx.key && idx.key.expiry === 1); + const expiryIndex = indexes.find( + (idx) => idx.expireAfterSeconds !== undefined && idx.key && Object.keys(idx.key).length === 1 && idx.key.expiry === 1 + ); if (expiryIndex?.name) { await collection.dropIndex(expiryIndex.name); diff --git a/server/src/validation/maintenanceWindowValidation.ts b/server/src/validation/maintenanceWindowValidation.ts index 5d83b3fed..9bf775596 100644 --- a/server/src/validation/maintenanceWindowValidation.ts +++ b/server/src/validation/maintenanceWindowValidation.ts @@ -19,13 +19,23 @@ export const createMaintenanceWindowBodyValidation = z repeat: z.number().min(0, "Repeat must be a non-negative number"), }) .strict() - .refine((data) => new Date(data.end).getTime() > new Date(data.start).getTime(), { - message: "End must be after start", - path: ["end"], - }) - .refine((data) => data.repeat > 0 || new Date(data.end).getTime() > Date.now(), { - message: "End must be in the future for one-time maintenance windows", - path: ["end"], + .superRefine((data, ctx) => { + const start = new Date(data.start).getTime(); + const end = new Date(data.end).getTime(); + if (end <= start) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "End must be after start", + path: ["end"], + }); + } + if (data.repeat === 0 && end <= Date.now()) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "End must be in the future for one-time maintenance windows", + path: ["end"], + }); + } }); export const getMaintenanceWindowByIdParamValidation = z.object({ @@ -64,7 +74,16 @@ export const editMaintenanceByIdWindowBodyValidation = z durationUnit: z.enum(["seconds", "minutes", "hours", "days"]).optional(), }) .strict() - .refine((data) => !data.start || !data.end || new Date(data.end).getTime() > new Date(data.start).getTime(), { - message: "End must be after start", - path: ["end"], + .superRefine((data, ctx) => { + if (data.start && data.end) { + const start = new Date(data.start).getTime(); + const end = new Date(data.end).getTime(); + if (end <= start) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "End must be after start", + path: ["end"], + }); + } + } }); From b462ba756272fbab3364fdf67c32d24db283b2c5 Mon Sep 17 00:00:00 2001 From: gorkem-bwl Date: Thu, 7 May 2026 12:38:54 -0400 Subject: [PATCH 3/5] refactor(maintenance): centralize DurationUnit + sync OpenAPI spec Convention pass per docs/coding-conventions.md (rules 5/8/10/11): - Promote DurationUnit from a raw union type to a const tuple + derived type. - Mongoose schema enum imports DurationUnits instead of inlining the values. - Both validators import DurationUnits instead of inlining z.enum twice. - Drop stale 'expiry' entries from openapi.json (spec is now strict-mode-correct). --- server/openapi.json | 10 ---------- server/src/db/models/MaintenanceWindow.ts | 4 ++-- server/src/types/maintenanceWindow.ts | 3 ++- server/src/validation/maintenanceWindowValidation.ts | 5 +++-- 4 files changed, 7 insertions(+), 15 deletions(-) diff --git a/server/openapi.json b/server/openapi.json index f62062332..058e934b7 100644 --- a/server/openapi.json +++ b/server/openapi.json @@ -4657,11 +4657,6 @@ "repeat": { "type": "number", "minimum": 0 - }, - "expiry": { - "type": "string", - "nullable": true, - "format": "date-time" } }, "required": ["monitors", "name", "duration", "durationUnit", "start", "end", "repeat"] @@ -5190,11 +5185,6 @@ "nullable": true, "format": "date-time" }, - "expiry": { - "type": "string", - "nullable": true, - "format": "date-time" - }, "monitors": { "type": "array", "items": { diff --git a/server/src/db/models/MaintenanceWindow.ts b/server/src/db/models/MaintenanceWindow.ts index e3287ce7c..1fc9b5f4a 100644 --- a/server/src/db/models/MaintenanceWindow.ts +++ b/server/src/db/models/MaintenanceWindow.ts @@ -1,5 +1,5 @@ import { Schema, model, type Types } from "mongoose"; -import type { MaintenanceWindow } from "@/types/maintenanceWindow.js"; +import { DurationUnits, type MaintenanceWindow } from "@/types/maintenanceWindow.js"; type MaintenanceWindowDocumentBase = Omit & { monitorId: Types.ObjectId; @@ -38,7 +38,7 @@ const MaintenanceWindowSchema = new Schema( }, durationUnit: { type: String, - enum: ["seconds", "minutes", "hours", "days"], + enum: DurationUnits, }, repeat: { type: Number, diff --git a/server/src/types/maintenanceWindow.ts b/server/src/types/maintenanceWindow.ts index bcbd075a1..950dc1713 100644 --- a/server/src/types/maintenanceWindow.ts +++ b/server/src/types/maintenanceWindow.ts @@ -1,4 +1,5 @@ -export type DurationUnit = "seconds" | "minutes" | "hours" | "days"; +export const DurationUnits = ["seconds", "minutes", "hours", "days"] as const; +export type DurationUnit = (typeof DurationUnits)[number]; export interface MaintenanceWindow { id: string; diff --git a/server/src/validation/maintenanceWindowValidation.ts b/server/src/validation/maintenanceWindowValidation.ts index 9bf775596..bdd11df5f 100644 --- a/server/src/validation/maintenanceWindowValidation.ts +++ b/server/src/validation/maintenanceWindowValidation.ts @@ -1,5 +1,6 @@ import { z } from "zod"; import { booleanCoercion } from "./shared.js"; +import { DurationUnits } from "@/types/maintenanceWindow.js"; const dateToString = z.coerce.date().transform((d) => d.toISOString()); @@ -13,7 +14,7 @@ export const createMaintenanceWindowBodyValidation = z name: z.string().min(1, "Name is required"), active: z.boolean().optional(), duration: z.number().min(1, "Duration is required"), - durationUnit: z.enum(["seconds", "minutes", "hours", "days"]), + durationUnit: z.enum(DurationUnits), start: dateToString, end: dateToString, repeat: z.number().min(0, "Repeat must be a non-negative number"), @@ -71,7 +72,7 @@ export const editMaintenanceByIdWindowBodyValidation = z end: dateToString.optional(), monitors: z.array(z.string()).optional(), duration: z.number().optional(), - durationUnit: z.enum(["seconds", "minutes", "hours", "days"]).optional(), + durationUnit: z.enum(DurationUnits).optional(), }) .strict() .superRefine((data, ctx) => { From c45bcfaa2fdd323741e45ccdb3111078c2ff1675 Mon Sep 17 00:00:00 2001 From: gorkem-bwl Date: Thu, 7 May 2026 13:38:10 -0400 Subject: [PATCH 4/5] revert(maintenance): keep one-time TTL cleanup, narrow PR to validator-only Per review feedback: auto-deleting completed one-time maintenance windows is intentional cleanup, not a bug. The actual bug is past-dated end values being accepted at creation time, which the validator refines now reject up front. Reverts: - Restore expiry field + TTL index on MaintenanceWindow schema - Restore repository's auto-set of expiry = end for repeat=0 - Drop migration 0007 (no longer needed) - Restore expiry properties in openapi.json - Restore expiry in create/edit validators (still optional) Kept from this PR: - .strict() on create/edit body schemas - end > start refine on create/edit - end > now refine on create when repeat=0 (the real fix) - DurationUnits const tuple + reuse (rules 5/8/10) - Client no longer sends redundant expiry (server still derives it) --- server/openapi.json | 10 ++++ .../0007_dropMaintenanceWindowExpiryIndex.ts | 58 ------------------- server/src/db/migration/index.ts | 2 - server/src/db/models/MaintenanceWindow.ts | 5 ++ .../MongoMaintenanceWindowsRepository.ts | 5 ++ .../validation/maintenanceWindowValidation.ts | 2 + 6 files changed, 22 insertions(+), 60 deletions(-) delete mode 100644 server/src/db/migration/0007_dropMaintenanceWindowExpiryIndex.ts diff --git a/server/openapi.json b/server/openapi.json index 058e934b7..f62062332 100644 --- a/server/openapi.json +++ b/server/openapi.json @@ -4657,6 +4657,11 @@ "repeat": { "type": "number", "minimum": 0 + }, + "expiry": { + "type": "string", + "nullable": true, + "format": "date-time" } }, "required": ["monitors", "name", "duration", "durationUnit", "start", "end", "repeat"] @@ -5185,6 +5190,11 @@ "nullable": true, "format": "date-time" }, + "expiry": { + "type": "string", + "nullable": true, + "format": "date-time" + }, "monitors": { "type": "array", "items": { diff --git a/server/src/db/migration/0007_dropMaintenanceWindowExpiryIndex.ts b/server/src/db/migration/0007_dropMaintenanceWindowExpiryIndex.ts deleted file mode 100644 index 38e55c0d7..000000000 --- a/server/src/db/migration/0007_dropMaintenanceWindowExpiryIndex.ts +++ /dev/null @@ -1,58 +0,0 @@ -import mongoose from "mongoose"; -import { logger } from "@/utils/logger.js"; - -/** - * Drops the TTL index on MaintenanceWindow.expiry and unsets the field on existing rows. - * - * Why: a previous version copied `end` into `expiry` for one-time windows. Combined with the - * TTL index on `expiry`, this caused Mongo to silently delete rows whose `end` was in the past - * at creation time (a common symptom for automation tools sending non-UTC timestamps). The - * fix stops writing `expiry`; this migration removes the live exposure on existing installs. - */ -export async function dropMaintenanceWindowExpiryIndex(): Promise { - const SERVICE_NAME = "Migration:DropMaintenanceWindowExpiryIndex"; - - try { - logger.info({ - service: SERVICE_NAME, - message: "Starting drop of MaintenanceWindow.expiry TTL index", - }); - - const db = mongoose.connection.db; - if (!db) { - throw new Error("Mongo connection not initialized"); - } - const collection = db.collection("maintenancewindows"); - - const indexes = await collection.indexes(); - const expiryIndex = indexes.find( - (idx) => idx.expireAfterSeconds !== undefined && idx.key && Object.keys(idx.key).length === 1 && idx.key.expiry === 1 - ); - - if (expiryIndex?.name) { - await collection.dropIndex(expiryIndex.name); - logger.info({ - service: SERVICE_NAME, - message: `Dropped TTL index ${expiryIndex.name} on MaintenanceWindow.expiry`, - }); - } else { - logger.info({ - service: SERVICE_NAME, - message: "No TTL index found on MaintenanceWindow.expiry", - }); - } - - const result = await collection.updateMany({ expiry: { $exists: true } }, { $unset: { expiry: "" } }); - logger.info({ - service: SERVICE_NAME, - message: `Unset expiry on ${result.modifiedCount} maintenance windows`, - }); - } catch (error) { - const errorMessage = error instanceof Error ? error.message : String(error); - logger.error({ - service: SERVICE_NAME, - message: `Error dropping expiry index: ${errorMessage}`, - }); - throw error; - } -} diff --git a/server/src/db/migration/index.ts b/server/src/db/migration/index.ts index fcf0cf1fb..5b74a96fc 100644 --- a/server/src/db/migration/index.ts +++ b/server/src/db/migration/index.ts @@ -5,7 +5,6 @@ import { fixInfrastructureThresholds } from "./0004_fixInfrastructureThresholds. import MigrationModel from "../models/Migration.js"; import { migrateStatusPageTypeToArray } from "./0005_migrateStatusPageTypeToArray.js"; import { cleanupDuplicateMonitorStatsForUniqueIndex } from "./0006_cleanupDuplicateMonitorStatsForUniqueIndex.js"; -import { dropMaintenanceWindowExpiryIndex } from "./0007_dropMaintenanceWindowExpiryIndex.js"; import type { ILogger } from "@/utils/logger.js"; type MigrationEntry = { @@ -20,7 +19,6 @@ const migrations: MigrationEntry[] = [ { name: "0004_fixInfrastructureThresholds", execute: fixInfrastructureThresholds }, { name: "0005_migrateStatusPageTypeToArray", execute: migrateStatusPageTypeToArray }, { name: "0006_cleanupDuplicateMonitorStatsForUniqueIndex", execute: cleanupDuplicateMonitorStatsForUniqueIndex }, - { name: "0007_dropMaintenanceWindowExpiryIndex", execute: dropMaintenanceWindowExpiryIndex }, ]; const runMigrations = async (logger?: ILogger) => { diff --git a/server/src/db/models/MaintenanceWindow.ts b/server/src/db/models/MaintenanceWindow.ts index 1fc9b5f4a..703c144c8 100644 --- a/server/src/db/models/MaintenanceWindow.ts +++ b/server/src/db/models/MaintenanceWindow.ts @@ -6,6 +6,7 @@ type MaintenanceWindowDocumentBase = Omit( end: { type: Date, }, + expiry: { + type: Date, + index: { expires: "0s" }, + }, }, { timestamps: true, diff --git a/server/src/repositories/maintenance-windows/MongoMaintenanceWindowsRepository.ts b/server/src/repositories/maintenance-windows/MongoMaintenanceWindowsRepository.ts index 0cdda805e..ad96328c5 100644 --- a/server/src/repositories/maintenance-windows/MongoMaintenanceWindowsRepository.ts +++ b/server/src/repositories/maintenance-windows/MongoMaintenanceWindowsRepository.ts @@ -45,6 +45,11 @@ class MongoMaintenanceWindowsRepository implements IMaintenanceWindowsRepository create = async (data: Partial): Promise => { const maintenanceWindow = new MaintenanceWindowModel(data); + + // If the maintenance window is a one time window, set the expiry to the end date + if (maintenanceWindow.repeat === 0) { + maintenanceWindow.expiry = maintenanceWindow.end; + } const result = await maintenanceWindow.save(); return this.toEntity(result); }; diff --git a/server/src/validation/maintenanceWindowValidation.ts b/server/src/validation/maintenanceWindowValidation.ts index bdd11df5f..c53e39b20 100644 --- a/server/src/validation/maintenanceWindowValidation.ts +++ b/server/src/validation/maintenanceWindowValidation.ts @@ -18,6 +18,7 @@ export const createMaintenanceWindowBodyValidation = z start: dateToString, end: dateToString, repeat: z.number().min(0, "Repeat must be a non-negative number"), + expiry: dateToString.optional(), }) .strict() .superRefine((data, ctx) => { @@ -70,6 +71,7 @@ export const editMaintenanceByIdWindowBodyValidation = z repeat: z.number().optional(), start: dateToString.optional(), end: dateToString.optional(), + expiry: dateToString.optional(), monitors: z.array(z.string()).optional(), duration: z.number().optional(), durationUnit: z.enum(DurationUnits).optional(), From 60cded78a646505d1f9dc3bf7ba04a89dc341598 Mon Sep 17 00:00:00 2001 From: Alex Date: Thu, 7 May 2026 11:43:00 -0700 Subject: [PATCH 5/5] validation tests --- server/jest.config.ts | 1 + .../maintenanceWindowValidation.test.ts | 171 ++++++++++++++++++ 2 files changed, 172 insertions(+) create mode 100644 server/test/unit/validation/maintenanceWindowValidation.test.ts diff --git a/server/jest.config.ts b/server/jest.config.ts index be7d359b1..1faf98181 100644 --- a/server/jest.config.ts +++ b/server/jest.config.ts @@ -13,6 +13,7 @@ const config: Config = { "^@/(.*)\\.ts$": "/src/$1.ts", "^@/(.*)\\.js$": "/src/$1.ts", "^@/(.*)$": "/src/$1", + "^(\\.{1,2}/.*)\\.js$": "$1", }, testMatch: ["/test/**/*.test.ts"], setupFilesAfterEnv: [], diff --git a/server/test/unit/validation/maintenanceWindowValidation.test.ts b/server/test/unit/validation/maintenanceWindowValidation.test.ts new file mode 100644 index 000000000..dfede3670 --- /dev/null +++ b/server/test/unit/validation/maintenanceWindowValidation.test.ts @@ -0,0 +1,171 @@ +import { describe, expect, it, jest, afterEach } from "@jest/globals"; +import { + createMaintenanceWindowBodyValidation, + editMaintenanceByIdWindowBodyValidation, +} from "../../../src/validation/maintenanceWindowValidation.ts"; + +const FROZEN_NOW = new Date("2026-05-07T12:00:00Z").getTime(); + +const baseCreateBody = (overrides: Record = {}) => ({ + monitors: ["mon-1"], + name: "Scheduled Maintenance", + duration: 60, + durationUnit: "minutes", + start: new Date(FROZEN_NOW + 60 * 60 * 1000).toISOString(), + end: new Date(FROZEN_NOW + 2 * 60 * 60 * 1000).toISOString(), + repeat: 0, + ...overrides, +}); + +afterEach(() => { + jest.useRealTimers(); +}); + +describe("createMaintenanceWindowBodyValidation", () => { + it("accepts a valid one-time window with end in the future", () => { + jest.useFakeTimers().setSystemTime(FROZEN_NOW); + const result = createMaintenanceWindowBodyValidation.safeParse(baseCreateBody()); + expect(result.success).toBe(true); + }); + + it("accepts a recurring window even when end is in the past", () => { + jest.useFakeTimers().setSystemTime(FROZEN_NOW); + const result = createMaintenanceWindowBodyValidation.safeParse( + baseCreateBody({ + repeat: 1, + start: new Date(FROZEN_NOW - 2 * 60 * 60 * 1000).toISOString(), + end: new Date(FROZEN_NOW - 60 * 60 * 1000).toISOString(), + }) + ); + expect(result.success).toBe(true); + }); + + it("rejects when end is before start", () => { + jest.useFakeTimers().setSystemTime(FROZEN_NOW); + const result = createMaintenanceWindowBodyValidation.safeParse( + baseCreateBody({ + start: new Date(FROZEN_NOW + 2 * 60 * 60 * 1000).toISOString(), + end: new Date(FROZEN_NOW + 60 * 60 * 1000).toISOString(), + }) + ); + expect(result.success).toBe(false); + if (!result.success) { + expect(result.error.issues).toEqual(expect.arrayContaining([expect.objectContaining({ message: "End must be after start", path: ["end"] })])); + } + }); + + it("rejects when end equals start", () => { + jest.useFakeTimers().setSystemTime(FROZEN_NOW); + const sameInstant = new Date(FROZEN_NOW + 60 * 60 * 1000).toISOString(); + const result = createMaintenanceWindowBodyValidation.safeParse(baseCreateBody({ start: sameInstant, end: sameInstant })); + expect(result.success).toBe(false); + if (!result.success) { + expect(result.error.issues).toEqual(expect.arrayContaining([expect.objectContaining({ message: "End must be after start", path: ["end"] })])); + } + }); + + it("rejects a one-time window with end in the past", () => { + jest.useFakeTimers().setSystemTime(FROZEN_NOW); + const result = createMaintenanceWindowBodyValidation.safeParse( + baseCreateBody({ + start: new Date(FROZEN_NOW - 2 * 60 * 60 * 1000).toISOString(), + end: new Date(FROZEN_NOW - 60 * 60 * 1000).toISOString(), + }) + ); + expect(result.success).toBe(false); + if (!result.success) { + expect(result.error.issues).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + message: "End must be in the future for one-time maintenance windows", + path: ["end"], + }), + ]) + ); + } + }); + + it("rejects a one-time window with end exactly equal to now", () => { + jest.useFakeTimers().setSystemTime(FROZEN_NOW); + const result = createMaintenanceWindowBodyValidation.safeParse( + baseCreateBody({ + start: new Date(FROZEN_NOW - 60 * 60 * 1000).toISOString(), + end: new Date(FROZEN_NOW).toISOString(), + }) + ); + expect(result.success).toBe(false); + if (!result.success) { + expect(result.error.issues).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + message: "End must be in the future for one-time maintenance windows", + path: ["end"], + }), + ]) + ); + } + }); + + it("rejects unknown fields under .strict()", () => { + jest.useFakeTimers().setSystemTime(FROZEN_NOW); + const result = createMaintenanceWindowBodyValidation.safeParse(baseCreateBody({ teamId: "team-1" })); + expect(result.success).toBe(false); + }); + + it("rejects an invalid durationUnit value", () => { + jest.useFakeTimers().setSystemTime(FROZEN_NOW); + const result = createMaintenanceWindowBodyValidation.safeParse(baseCreateBody({ durationUnit: "weeks" })); + expect(result.success).toBe(false); + }); + + it("rejects a missing required field", () => { + jest.useFakeTimers().setSystemTime(FROZEN_NOW); + const { name: _name, ...withoutName } = baseCreateBody(); + const result = createMaintenanceWindowBodyValidation.safeParse(withoutName); + expect(result.success).toBe(false); + }); +}); + +describe("editMaintenanceByIdWindowBodyValidation", () => { + it("accepts an empty body (all fields optional)", () => { + const result = editMaintenanceByIdWindowBodyValidation.safeParse({}); + expect(result.success).toBe(true); + }); + + it("accepts a partial update with only active toggled", () => { + const result = editMaintenanceByIdWindowBodyValidation.safeParse({ active: false }); + expect(result.success).toBe(true); + }); + + it("rejects unknown fields under .strict()", () => { + const result = editMaintenanceByIdWindowBodyValidation.safeParse({ + active: false, + id: "mw-1", + }); + expect(result.success).toBe(false); + }); + + it("rejects when start and end are both present and end <= start", () => { + const start = new Date("2026-05-08T10:00:00Z").toISOString(); + const end = new Date("2026-05-08T09:00:00Z").toISOString(); + const result = editMaintenanceByIdWindowBodyValidation.safeParse({ start, end }); + expect(result.success).toBe(false); + if (!result.success) { + expect(result.error.issues).toEqual(expect.arrayContaining([expect.objectContaining({ message: "End must be after start", path: ["end"] })])); + } + }); + + it("does not apply the start/end ordering rule when only end is provided", () => { + const result = editMaintenanceByIdWindowBodyValidation.safeParse({ + end: new Date("2020-01-01T00:00:00Z").toISOString(), + }); + expect(result.success).toBe(true); + }); + + it("does not apply the start/end ordering rule when only start is provided", () => { + const result = editMaintenanceByIdWindowBodyValidation.safeParse({ + start: new Date("2099-01-01T00:00:00Z").toISOString(), + }); + expect(result.success).toBe(true); + }); +});