Address greptile comments

This commit is contained in:
Carlos Monastyrski
2025-11-06 03:28:21 -03:00
parent 33617dbaa7
commit 208ba59e65
8 changed files with 49 additions and 58 deletions
+1 -1
View File
@@ -2378,7 +2378,7 @@ export const registerRoutes = async (
await dailyReminderQueueService.startSecretReminderMigrationJob(); await dailyReminderQueueService.startSecretReminderMigrationJob();
await dailyExpiringPkiItemAlert.startSendingAlerts(); await dailyExpiringPkiItemAlert.startSendingAlerts();
await pkiSubscriberQueue.startDailyAutoRenewalJob(); await pkiSubscriberQueue.startDailyAutoRenewalJob();
await pkiAlertV2Queue.startDailyAlertProcessing(); await pkiAlertV2Queue.init();
await certificateV3Queue.init(); await certificateV3Queue.init();
await kmsService.startService(hsmStatus); await kmsService.startService(hsmStatus);
await microsoftTeamsService.start(); await microsoftTeamsService.start();
@@ -6,6 +6,7 @@ import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type"; import { AuthMode } from "@app/services/auth/auth-type";
import { import {
CreatePkiAlertV2Schema, CreatePkiAlertV2Schema,
createSecureAlertBeforeValidator,
PkiAlertEventType, PkiAlertEventType,
PkiFilterRuleSchema, PkiFilterRuleSchema,
UpdatePkiAlertV2Schema UpdatePkiAlertV2Schema
@@ -392,7 +393,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
filters: z.array(PkiFilterRuleSchema), filters: z.array(PkiFilterRuleSchema),
alertBefore: z alertBefore: z
.string() .string()
.regex(/^\d+[dwmy]$/) .refine(createSecureAlertBeforeValidator(), "Must be in format like '30d', '1w', '3m', '1y'")
.describe("Alert timing (e.g., '30d', '1w')"), .describe("Alert timing (e.g., '30d', '1w')"),
limit: z.coerce.number().min(1).max(100).default(20), limit: z.coerce.number().min(1).max(100).default(20),
offset: z.coerce.number().min(0).default(0) offset: z.coerce.number().min(0).default(0)
@@ -20,6 +20,10 @@ export const sanitizeLikeInput = (input: string): string => {
}; };
export const parseTimeToPostgresInterval = (duration: string): string => { export const parseTimeToPostgresInterval = (duration: string): string => {
if (duration.length > 32) {
throw new Error(`Invalid duration format: ${duration}. Use format like '30d', '1w', '3m', '1y'`);
}
const durationRegex = new RE2("^(\\d+)([dwmy])$"); const durationRegex = new RE2("^(\\d+)([dwmy])$");
const match = durationRegex.exec(duration); const match = durationRegex.exec(duration);
@@ -1,5 +1,6 @@
/* eslint-disable no-await-in-loop */ /* eslint-disable no-await-in-loop */
import { getConfig } from "@app/lib/config/env";
import { logger } from "@app/lib/logger"; import { logger } from "@app/lib/logger";
import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue"; import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
@@ -24,6 +25,7 @@ export const pkiAlertV2QueueServiceFactory = ({
pkiAlertV2DAL, pkiAlertV2DAL,
pkiAlertHistoryDAL pkiAlertHistoryDAL
}: TPkiAlertV2QueueServiceFactoryDep) => { }: TPkiAlertV2QueueServiceFactoryDep) => {
const appCfg = getConfig();
const calculateDeduplicationWindow = (alertBefore: string): number => { const calculateDeduplicationWindow = (alertBefore: string): number => {
const alertDays = parseTimeToDays(alertBefore); const alertDays = parseTimeToDays(alertBefore);
@@ -185,60 +187,34 @@ export const pkiAlertV2QueueServiceFactory = ({
); );
}; };
queueService.start(QueueName.DailyPkiAlertV2Processing, async () => { const init = async () => {
logger.info(`${QueueName.DailyPkiAlertV2Processing}: queue task started`); if (appCfg.isSecondaryInstance) {
return;
try {
await processDailyAlerts();
logger.info(`${QueueName.DailyPkiAlertV2Processing}: queue task completed successfully`);
} catch (error) {
logger.error(error, `${QueueName.DailyPkiAlertV2Processing}: queue task failed`);
throw error;
} }
});
const startDailyAlertProcessing = async () => { await queueService.startPg<QueueName.DailyPkiAlertV2Processing>(
await queueService.stopRepeatableJob(
QueueName.DailyPkiAlertV2Processing,
QueueJobs.DailyPkiAlertV2Processing, QueueJobs.DailyPkiAlertV2Processing,
{ pattern: "* * * * *", utc: true }, async () => {
QueueName.DailyPkiAlertV2Processing try {
logger.info(`${QueueJobs.DailyPkiAlertV2Processing}: queue task started`);
await processDailyAlerts();
logger.info(`${QueueJobs.DailyPkiAlertV2Processing}: queue task completed successfully`);
} catch (error) {
logger.error(error, `${QueueJobs.DailyPkiAlertV2Processing}: queue task failed`);
throw error;
}
},
{
batchSize: 1,
workerCount: 1,
pollingIntervalSeconds: 60
}
); );
await queueService.queue(QueueName.DailyPkiAlertV2Processing, QueueJobs.DailyPkiAlertV2Processing, undefined, { await queueService.schedulePg(QueueJobs.DailyPkiAlertV2Processing, "* * * * *", undefined, { tz: "UTC" });
delay: 5000,
jobId: QueueName.DailyPkiAlertV2Processing,
repeat: { pattern: "* * * * *", utc: true }
});
logger.info("Daily PKI alert processing job scheduled");
}; };
const stopDailyAlertProcessing = async () => {
await queueService.stopRepeatableJob(
QueueName.DailyPkiAlertV2Processing,
QueueJobs.DailyPkiAlertV2Processing,
{ pattern: "* * * * *", utc: true },
QueueName.DailyPkiAlertV2Processing
);
logger.info("Daily PKI alert processing job stopped");
};
const triggerAlertProcessing = async () => {
await queueService.queue(QueueName.DailyPkiAlertV2Processing, QueueJobs.DailyPkiAlertV2Processing, undefined, {
delay: 1000
});
};
queueService.listen(QueueName.DailyPkiAlertV2Processing, "failed", (_, err) => {
logger.error(err, `${QueueName.DailyPkiAlertV2Processing}: Daily PKI alert processing failed`);
});
return { return {
startDailyAlertProcessing, init
stopDailyAlertProcessing,
triggerAlertProcessing,
processDailyAlerts
}; };
}; };
@@ -374,6 +374,7 @@ export const pkiAlertV2ServiceFactory = ({
const listCurrentMatchingCertificates = async ({ const listCurrentMatchingCertificates = async ({
projectId, projectId,
filters, filters,
alertBefore,
limit = 20, limit = 20,
offset = 0, offset = 0,
actorId, actorId,
@@ -392,14 +393,22 @@ export const pkiAlertV2ServiceFactory = ({
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.PkiAlerts); ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.PkiAlerts);
try {
parseTimeToPostgresInterval(alertBefore);
} catch (error) {
throw new BadRequestError({ message: "Invalid alertBefore format. Use format like '30d', '1w', '3m', '1y'" });
}
const options: { const options: {
limit: number; limit: number;
offset: number; offset: number;
showPreview?: boolean; showPreview?: boolean;
alertBefore?: string;
} = { } = {
limit, limit,
offset, offset,
showPreview: true showPreview: true,
alertBefore: parseTimeToPostgresInterval(alertBefore)
}; };
const result = await pkiAlertV2DAL.findMatchingCertificates(projectId, filters, options); const result = await pkiAlertV2DAL.findMatchingCertificates(projectId, filters, options);
@@ -8,9 +8,12 @@ const createSecureSlugValidator = () => {
return (value: string) => slugRegex.test(value); return (value: string) => slugRegex.test(value);
}; };
const createSecureAlertBeforeValidator = () => { export const createSecureAlertBeforeValidator = () => {
const alertBeforeRegex = new RE2("^\\d+[dwmy]$"); const alertBeforeRegex = new RE2("^\\d+[dwmy]$");
return (value: string) => alertBeforeRegex.test(value); return (value: string) => {
if (value.length > 32) return false;
return alertBeforeRegex.test(value);
};
}; };
export enum PkiAlertEventType { export enum PkiAlertEventType {
+2 -1
View File
@@ -181,7 +181,8 @@ export const createPkiAlertV2Schema = z.object({
eventType: z.nativeEnum(PkiAlertEventTypeV2), eventType: z.nativeEnum(PkiAlertEventTypeV2),
alertBefore: z alertBefore: z
.string() .string()
.regex(/^\d+[dwmy]$/) .regex(/^\d+[dwmy]$/, "Must be in format like '30d', '1w', '3m', '1y'")
.refine((val) => val.length <= 32, "Alert timing too long")
.optional(), .optional(),
filters: z.array(pkiFilterRuleV2Schema), filters: z.array(pkiFilterRuleV2Schema),
enabled: z.boolean().default(true), enabled: z.boolean().default(true),
@@ -249,7 +249,7 @@ export const CreatePkiAlertV2FormSteps = () => {
{watchedFilters?.map((filter, index) => ( {watchedFilters?.map((filter, index) => (
<div <div
key={`filter-${filter.field}-${filter.operator}-${String(filter.value)}-${index}`} key={`filter-${index}`}
className="space-y-2 rounded-md border border-mineshaft-600 p-3" className="space-y-2 rounded-md border border-mineshaft-600 p-3"
> >
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
@@ -551,10 +551,7 @@ export const CreatePkiAlertV2FormSteps = () => {
<div className="flex flex-wrap gap-x-8 gap-y-2"> <div className="flex flex-wrap gap-x-8 gap-y-2">
{watchedFilters && watchedFilters.length > 0 ? ( {watchedFilters && watchedFilters.length > 0 ? (
watchedFilters.map((filter, index) => ( watchedFilters.map((filter, index) => (
<GenericFieldLabel <GenericFieldLabel key={`review-filter-${index}`} label={`Rule ${index + 1}`}>
key={`review-filter-${filter.field}-${filter.operator}-${String(filter.value)}-${index}`}
label={`Rule ${index + 1}`}
>
<span className="font-mono text-xs"> <span className="font-mono text-xs">
{filter.field {filter.field
.replace(/_/g, " ") .replace(/_/g, " ")