@absolutejs/vulnerabilities-postgres 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -0
- package/dist/drizzle.d.ts +1561 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +553 -76
- package/package.json +4 -3
package/dist/index.js
CHANGED
|
@@ -338,6 +338,477 @@ var createPostgresVulnerabilityAlertStores = (options) => {
|
|
|
338
338
|
};
|
|
339
339
|
return { alertIncidents, alertPolicies, ensureAlertSchema };
|
|
340
340
|
};
|
|
341
|
+
// src/drizzle.ts
|
|
342
|
+
import { and, asc, desc, eq, inArray, lte, max, or, sql } from "drizzle-orm";
|
|
343
|
+
import {
|
|
344
|
+
bigserial,
|
|
345
|
+
customType,
|
|
346
|
+
index,
|
|
347
|
+
integer,
|
|
348
|
+
pgTable,
|
|
349
|
+
primaryKey,
|
|
350
|
+
text,
|
|
351
|
+
timestamp,
|
|
352
|
+
uniqueIndex,
|
|
353
|
+
uuid
|
|
354
|
+
} from "drizzle-orm/pg-core";
|
|
355
|
+
import {
|
|
356
|
+
resolveVulnerabilityAlertAudiences as resolveVulnerabilityAlertAudiences2,
|
|
357
|
+
validateVulnerabilityAlertConfiguration as validateVulnerabilityAlertConfiguration2
|
|
358
|
+
} from "@absolutejs/vulnerabilities";
|
|
359
|
+
var databaseNow = sql`now()`;
|
|
360
|
+
var portableJsonb = customType({
|
|
361
|
+
dataType: () => "jsonb",
|
|
362
|
+
fromDriver: (value) => typeof value === "string" ? JSON.parse(value) : value,
|
|
363
|
+
toDriver: (value) => JSON.stringify(value)
|
|
364
|
+
});
|
|
365
|
+
var encodedJsonb = (value) => sql`${JSON.stringify(value)}::text::jsonb`;
|
|
366
|
+
var boundedLimit2 = (value = 1000) => {
|
|
367
|
+
if (!Number.isInteger(value) || value < 1 || value > 1000)
|
|
368
|
+
throw new Error("Alert query limit must be an integer from 1 through 1000");
|
|
369
|
+
return value;
|
|
370
|
+
};
|
|
371
|
+
var vulnerabilityAlertPolicyVersions = pgTable("vulnerability_alert_policy_versions", {
|
|
372
|
+
activated_at: timestamp({ mode: "date", withTimezone: true }).notNull(),
|
|
373
|
+
activated_by: uuid().notNull(),
|
|
374
|
+
configuration: portableJsonb().$type().notNull(),
|
|
375
|
+
reason: text().notNull(),
|
|
376
|
+
status: text().$type().notNull(),
|
|
377
|
+
tenant_id: text().notNull(),
|
|
378
|
+
version: integer().notNull()
|
|
379
|
+
}, (table) => [
|
|
380
|
+
primaryKey({ columns: [table.tenant_id, table.version] }),
|
|
381
|
+
uniqueIndex("vulnerability_alert_policy_versions_active_idx").on(table.tenant_id).where(sql`${table.status} = 'active'`),
|
|
382
|
+
index("vulnerability_alert_policy_versions_history_idx").on(table.tenant_id, table.activated_at)
|
|
383
|
+
]);
|
|
384
|
+
var vulnerabilityAlertIncidents = pgTable("vulnerability_alert_incidents", {
|
|
385
|
+
acknowledged_at: timestamp({ mode: "date", withTimezone: true }),
|
|
386
|
+
acknowledged_by: uuid(),
|
|
387
|
+
alert_id: text().primaryKey(),
|
|
388
|
+
asset_id: text(),
|
|
389
|
+
body: text().notNull(),
|
|
390
|
+
due_at: timestamp({ mode: "date", withTimezone: true }),
|
|
391
|
+
finding_id: text(),
|
|
392
|
+
first_observed_at: timestamp({
|
|
393
|
+
mode: "date",
|
|
394
|
+
withTimezone: true
|
|
395
|
+
}).notNull(),
|
|
396
|
+
kind: text().$type().notNull(),
|
|
397
|
+
last_observed_at: timestamp({
|
|
398
|
+
mode: "date",
|
|
399
|
+
withTimezone: true
|
|
400
|
+
}).notNull(),
|
|
401
|
+
next_escalation_at: timestamp({ mode: "date", withTimezone: true }),
|
|
402
|
+
observation_count: integer().notNull().default(1),
|
|
403
|
+
occurrence_count: integer().notNull().default(1),
|
|
404
|
+
plan_id: text(),
|
|
405
|
+
policy_version: integer(),
|
|
406
|
+
resolved_at: timestamp({ mode: "date", withTimezone: true }),
|
|
407
|
+
severity: text().$type().notNull(),
|
|
408
|
+
source_id: text(),
|
|
409
|
+
status: text().$type().notNull().default("open"),
|
|
410
|
+
tenant_id: text().notNull(),
|
|
411
|
+
title: text().notNull(),
|
|
412
|
+
updated_at: timestamp({ mode: "date", withTimezone: true }).notNull().defaultNow(),
|
|
413
|
+
value: portableJsonb().$type().notNull()
|
|
414
|
+
}, (table) => [
|
|
415
|
+
index("vulnerability_alert_incidents_status_idx").on(table.status, table.last_observed_at),
|
|
416
|
+
index("vulnerability_alert_incidents_tenant_idx").on(table.tenant_id, table.status),
|
|
417
|
+
index("vulnerability_alert_incidents_escalation_idx").on(table.status, table.next_escalation_at)
|
|
418
|
+
]);
|
|
419
|
+
var vulnerabilityAlertEvents = pgTable("vulnerability_alert_events", {
|
|
420
|
+
actor_id: uuid(),
|
|
421
|
+
alert_id: text().notNull().references(() => vulnerabilityAlertIncidents.alert_id, {
|
|
422
|
+
onDelete: "cascade"
|
|
423
|
+
}),
|
|
424
|
+
created_at: timestamp({ mode: "date", withTimezone: true }).notNull().defaultNow(),
|
|
425
|
+
id: bigserial({ mode: "number" }).primaryKey(),
|
|
426
|
+
kind: text().$type().notNull(),
|
|
427
|
+
metadata: portableJsonb().$type().notNull().default(sql`'{}'::jsonb`)
|
|
428
|
+
}, (table) => [
|
|
429
|
+
index("vulnerability_alert_events_alert_idx").on(table.alert_id, table.created_at)
|
|
430
|
+
]);
|
|
431
|
+
var vulnerabilityAlertDeliveries = pgTable("vulnerability_alert_deliveries", {
|
|
432
|
+
alert_id: text().notNull().references(() => vulnerabilityAlertIncidents.alert_id, {
|
|
433
|
+
onDelete: "cascade"
|
|
434
|
+
}),
|
|
435
|
+
attempt_count: integer().notNull().default(0),
|
|
436
|
+
audience: text().$type().notNull(),
|
|
437
|
+
created_at: timestamp({ mode: "date", withTimezone: true }).notNull().defaultNow(),
|
|
438
|
+
delivered_at: timestamp({ mode: "date", withTimezone: true }),
|
|
439
|
+
id: uuid().primaryKey().defaultRandom(),
|
|
440
|
+
idempotency_key: text().notNull(),
|
|
441
|
+
kind: text().$type().notNull(),
|
|
442
|
+
last_error: text(),
|
|
443
|
+
lease_expires_at: timestamp({ mode: "date", withTimezone: true }),
|
|
444
|
+
next_attempt_at: timestamp({ mode: "date", withTimezone: true }).notNull().defaultNow(),
|
|
445
|
+
state: text().$type().notNull().default("pending"),
|
|
446
|
+
updated_at: timestamp({ mode: "date", withTimezone: true }).notNull().defaultNow()
|
|
447
|
+
}, (table) => [
|
|
448
|
+
uniqueIndex("vulnerability_alert_deliveries_key_idx").on(table.idempotency_key),
|
|
449
|
+
index("vulnerability_alert_deliveries_state_idx").on(table.state, table.next_attempt_at)
|
|
450
|
+
]);
|
|
451
|
+
var vulnerabilityAlertDrizzleSchema = {
|
|
452
|
+
vulnerabilityAlertDeliveries,
|
|
453
|
+
vulnerabilityAlertEvents,
|
|
454
|
+
vulnerabilityAlertIncidents,
|
|
455
|
+
vulnerabilityAlertPolicyVersions
|
|
456
|
+
};
|
|
457
|
+
var queue = async (transaction2, alert, configuration, kind, occurrence) => {
|
|
458
|
+
const audiences = resolveVulnerabilityAlertAudiences2({
|
|
459
|
+
configuration,
|
|
460
|
+
hasOwner: alert.assetId !== null,
|
|
461
|
+
kind,
|
|
462
|
+
severity: alert.severity
|
|
463
|
+
});
|
|
464
|
+
if (audiences.length === 0)
|
|
465
|
+
return;
|
|
466
|
+
await transaction2.insert(vulnerabilityAlertDeliveries).values(audiences.map((audience) => ({
|
|
467
|
+
alert_id: alert.id,
|
|
468
|
+
audience,
|
|
469
|
+
id: crypto.randomUUID(),
|
|
470
|
+
idempotency_key: `${alert.id}:${audience}:${kind}:${occurrence}`,
|
|
471
|
+
kind
|
|
472
|
+
}))).onConflictDoNothing({
|
|
473
|
+
target: vulnerabilityAlertDeliveries.idempotency_key
|
|
474
|
+
});
|
|
475
|
+
};
|
|
476
|
+
var createDrizzleVulnerabilityAlertStores = (db) => {
|
|
477
|
+
const alertPolicies = {
|
|
478
|
+
activate: async (input) => {
|
|
479
|
+
let configuration;
|
|
480
|
+
try {
|
|
481
|
+
configuration = validateVulnerabilityAlertConfiguration2(input.configuration);
|
|
482
|
+
} catch (error) {
|
|
483
|
+
throw new VulnerabilityAlertValidationError(error instanceof Error ? error.message : "Policy is invalid");
|
|
484
|
+
}
|
|
485
|
+
const reason = input.reason.trim();
|
|
486
|
+
if (!reason)
|
|
487
|
+
throw new VulnerabilityAlertValidationError("Policy activation reason is required");
|
|
488
|
+
return db.transaction(async (transaction2) => {
|
|
489
|
+
await transaction2.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${`vulnerability-alert-policy:${input.tenantId}`}))`);
|
|
490
|
+
const [latest] = await transaction2.select({
|
|
491
|
+
version: sql`COALESCE(${max(vulnerabilityAlertPolicyVersions.version)}, 0)::integer`
|
|
492
|
+
}).from(vulnerabilityAlertPolicyVersions).where(eq(vulnerabilityAlertPolicyVersions.tenant_id, input.tenantId));
|
|
493
|
+
const version = (latest?.version ?? 0) + 1;
|
|
494
|
+
await transaction2.update(vulnerabilityAlertPolicyVersions).set({ status: "superseded" }).where(and(eq(vulnerabilityAlertPolicyVersions.tenant_id, input.tenantId), eq(vulnerabilityAlertPolicyVersions.status, "active")));
|
|
495
|
+
await transaction2.insert(vulnerabilityAlertPolicyVersions).values({
|
|
496
|
+
activated_at: new Date(input.activatedAt),
|
|
497
|
+
activated_by: input.activatedBy,
|
|
498
|
+
configuration: encodedJsonb(configuration),
|
|
499
|
+
reason,
|
|
500
|
+
status: "active",
|
|
501
|
+
tenant_id: input.tenantId,
|
|
502
|
+
version
|
|
503
|
+
});
|
|
504
|
+
return {
|
|
505
|
+
activatedAt: input.activatedAt,
|
|
506
|
+
configuration,
|
|
507
|
+
reason,
|
|
508
|
+
tenantId: input.tenantId,
|
|
509
|
+
version
|
|
510
|
+
};
|
|
511
|
+
});
|
|
512
|
+
},
|
|
513
|
+
active: async () => {
|
|
514
|
+
const rows = await db.select({
|
|
515
|
+
configuration: vulnerabilityAlertPolicyVersions.configuration,
|
|
516
|
+
tenantId: vulnerabilityAlertPolicyVersions.tenant_id,
|
|
517
|
+
version: vulnerabilityAlertPolicyVersions.version
|
|
518
|
+
}).from(vulnerabilityAlertPolicyVersions).where(eq(vulnerabilityAlertPolicyVersions.status, "active"));
|
|
519
|
+
return rows.map((row) => ({
|
|
520
|
+
configuration: validateVulnerabilityAlertConfiguration2(row.configuration),
|
|
521
|
+
tenantId: row.tenantId,
|
|
522
|
+
version: row.version
|
|
523
|
+
}));
|
|
524
|
+
},
|
|
525
|
+
list: (requestedLimit) => db.select().from(vulnerabilityAlertPolicyVersions).orderBy(desc(vulnerabilityAlertPolicyVersions.activated_at)).limit(boundedLimit2(requestedLimit))
|
|
526
|
+
};
|
|
527
|
+
const observe = async ({
|
|
528
|
+
alert,
|
|
529
|
+
policy,
|
|
530
|
+
observedAt
|
|
531
|
+
}) => {
|
|
532
|
+
const at = observedAt ?? new Date().toISOString();
|
|
533
|
+
const configuration = validateVulnerabilityAlertConfiguration2(policy.configuration);
|
|
534
|
+
return db.transaction(async (transaction2) => {
|
|
535
|
+
const [existing] = await transaction2.select({
|
|
536
|
+
occurrenceCount: vulnerabilityAlertIncidents.occurrence_count,
|
|
537
|
+
status: vulnerabilityAlertIncidents.status
|
|
538
|
+
}).from(vulnerabilityAlertIncidents).where(eq(vulnerabilityAlertIncidents.alert_id, alert.id)).for("update").limit(1);
|
|
539
|
+
const reopened = existing?.status === "resolved";
|
|
540
|
+
const nextEscalationAt = new Date(new Date(at).getTime() + configuration.escalationAfterMs[alert.severity]);
|
|
541
|
+
await transaction2.insert(vulnerabilityAlertIncidents).values({
|
|
542
|
+
alert_id: alert.id,
|
|
543
|
+
asset_id: alert.assetId,
|
|
544
|
+
body: alert.body,
|
|
545
|
+
due_at: alert.dueAt ? new Date(alert.dueAt) : null,
|
|
546
|
+
finding_id: alert.findingId,
|
|
547
|
+
first_observed_at: new Date(alert.observedAt),
|
|
548
|
+
kind: alert.kind,
|
|
549
|
+
last_observed_at: new Date(alert.observedAt),
|
|
550
|
+
next_escalation_at: nextEscalationAt,
|
|
551
|
+
plan_id: alert.planId,
|
|
552
|
+
policy_version: policy.version,
|
|
553
|
+
severity: alert.severity,
|
|
554
|
+
source_id: alert.sourceId,
|
|
555
|
+
status: "open",
|
|
556
|
+
tenant_id: alert.tenantId,
|
|
557
|
+
title: alert.title,
|
|
558
|
+
value: encodedJsonb(alert)
|
|
559
|
+
}).onConflictDoUpdate({
|
|
560
|
+
set: {
|
|
561
|
+
asset_id: sql`excluded.asset_id`,
|
|
562
|
+
body: sql`excluded.body`,
|
|
563
|
+
due_at: sql`excluded.due_at`,
|
|
564
|
+
finding_id: sql`excluded.finding_id`,
|
|
565
|
+
last_observed_at: sql`excluded.last_observed_at`,
|
|
566
|
+
next_escalation_at: sql`CASE
|
|
567
|
+
WHEN ${vulnerabilityAlertIncidents.status} = 'resolved'
|
|
568
|
+
THEN excluded.next_escalation_at
|
|
569
|
+
WHEN ${vulnerabilityAlertIncidents.status} = 'open'
|
|
570
|
+
AND ${vulnerabilityAlertIncidents.policy_version}
|
|
571
|
+
IS DISTINCT FROM excluded.policy_version
|
|
572
|
+
THEN excluded.next_escalation_at
|
|
573
|
+
ELSE ${vulnerabilityAlertIncidents.next_escalation_at}
|
|
574
|
+
END`,
|
|
575
|
+
observation_count: sql`${vulnerabilityAlertIncidents.observation_count} + 1`,
|
|
576
|
+
occurrence_count: sql`CASE
|
|
577
|
+
WHEN ${vulnerabilityAlertIncidents.status} = 'resolved'
|
|
578
|
+
THEN ${vulnerabilityAlertIncidents.occurrence_count} + 1
|
|
579
|
+
ELSE ${vulnerabilityAlertIncidents.occurrence_count}
|
|
580
|
+
END`,
|
|
581
|
+
plan_id: sql`excluded.plan_id`,
|
|
582
|
+
policy_version: sql`excluded.policy_version`,
|
|
583
|
+
resolved_at: sql`CASE
|
|
584
|
+
WHEN ${vulnerabilityAlertIncidents.status} = 'resolved'
|
|
585
|
+
THEN null
|
|
586
|
+
ELSE ${vulnerabilityAlertIncidents.resolved_at}
|
|
587
|
+
END`,
|
|
588
|
+
severity: sql`excluded.severity`,
|
|
589
|
+
source_id: sql`excluded.source_id`,
|
|
590
|
+
status: sql`CASE
|
|
591
|
+
WHEN ${vulnerabilityAlertIncidents.status} = 'resolved'
|
|
592
|
+
THEN 'open'
|
|
593
|
+
ELSE ${vulnerabilityAlertIncidents.status}
|
|
594
|
+
END`,
|
|
595
|
+
tenant_id: sql`excluded.tenant_id`,
|
|
596
|
+
title: sql`excluded.title`,
|
|
597
|
+
updated_at: databaseNow,
|
|
598
|
+
value: sql`excluded.value`
|
|
599
|
+
},
|
|
600
|
+
target: vulnerabilityAlertIncidents.alert_id
|
|
601
|
+
});
|
|
602
|
+
if (!existing || reopened) {
|
|
603
|
+
await transaction2.insert(vulnerabilityAlertEvents).values({
|
|
604
|
+
alert_id: alert.id,
|
|
605
|
+
kind: "opened",
|
|
606
|
+
metadata: encodedJsonb({})
|
|
607
|
+
});
|
|
608
|
+
await queue(transaction2, alert, configuration, "opened", existing ? existing.occurrenceCount + 1 : 1);
|
|
609
|
+
}
|
|
610
|
+
return !existing ? "opened" : reopened ? "reopened" : "observed";
|
|
611
|
+
});
|
|
612
|
+
};
|
|
613
|
+
const alertIncidents = {
|
|
614
|
+
acknowledge: (input) => db.transaction(async (transaction2) => {
|
|
615
|
+
const [present] = await transaction2.select({ status: vulnerabilityAlertIncidents.status }).from(vulnerabilityAlertIncidents).where(eq(vulnerabilityAlertIncidents.alert_id, input.alertId)).for("update").limit(1);
|
|
616
|
+
if (!present)
|
|
617
|
+
throw new VulnerabilityAlertNotFoundError("Vulnerability alert not found");
|
|
618
|
+
if (present.status === "resolved")
|
|
619
|
+
throw new VulnerabilityAlertConflictError("Resolved vulnerability alerts cannot be acknowledged");
|
|
620
|
+
if (present.status === "acknowledged")
|
|
621
|
+
return false;
|
|
622
|
+
await transaction2.update(vulnerabilityAlertIncidents).set({
|
|
623
|
+
acknowledged_at: new Date(input.acknowledgedAt),
|
|
624
|
+
acknowledged_by: input.acknowledgedBy,
|
|
625
|
+
next_escalation_at: null,
|
|
626
|
+
status: "acknowledged",
|
|
627
|
+
updated_at: new Date(input.acknowledgedAt)
|
|
628
|
+
}).where(eq(vulnerabilityAlertIncidents.alert_id, input.alertId));
|
|
629
|
+
await transaction2.insert(vulnerabilityAlertEvents).values({
|
|
630
|
+
actor_id: input.acknowledgedBy,
|
|
631
|
+
alert_id: input.alertId,
|
|
632
|
+
kind: "acknowledged",
|
|
633
|
+
metadata: encodedJsonb({})
|
|
634
|
+
});
|
|
635
|
+
return true;
|
|
636
|
+
}),
|
|
637
|
+
claimDeliveries: (input = {}) => db.transaction(async (transaction2) => {
|
|
638
|
+
const leaseMs = input.leaseMs ?? 300000;
|
|
639
|
+
const queryLimit = boundedLimit2(input.limit ?? 100);
|
|
640
|
+
const due = or(and(inArray(vulnerabilityAlertDeliveries.state, ["pending", "failed"]), lte(vulnerabilityAlertDeliveries.next_attempt_at, databaseNow)), and(eq(vulnerabilityAlertDeliveries.state, "delivering"), lte(vulnerabilityAlertDeliveries.lease_expires_at, databaseNow)));
|
|
641
|
+
const candidates = await transaction2.select({ id: vulnerabilityAlertDeliveries.id }).from(vulnerabilityAlertDeliveries).innerJoin(vulnerabilityAlertIncidents, eq(vulnerabilityAlertIncidents.alert_id, vulnerabilityAlertDeliveries.alert_id)).where(and(due, input.tenantIds && input.tenantIds.length > 0 ? inArray(vulnerabilityAlertIncidents.tenant_id, [
|
|
642
|
+
...input.tenantIds
|
|
643
|
+
]) : undefined)).orderBy(asc(vulnerabilityAlertDeliveries.created_at)).limit(queryLimit).for("update", {
|
|
644
|
+
of: vulnerabilityAlertDeliveries,
|
|
645
|
+
skipLocked: true
|
|
646
|
+
});
|
|
647
|
+
const ids = candidates.map(({ id }) => id);
|
|
648
|
+
if (ids.length === 0)
|
|
649
|
+
return [];
|
|
650
|
+
await transaction2.update(vulnerabilityAlertDeliveries).set({
|
|
651
|
+
attempt_count: sql`${vulnerabilityAlertDeliveries.attempt_count} + 1`,
|
|
652
|
+
lease_expires_at: sql`now() + ${leaseMs} * interval '1 millisecond'`,
|
|
653
|
+
state: "delivering",
|
|
654
|
+
updated_at: databaseNow
|
|
655
|
+
}).where(inArray(vulnerabilityAlertDeliveries.id, ids));
|
|
656
|
+
return transaction2.select({
|
|
657
|
+
alert_id: vulnerabilityAlertDeliveries.alert_id,
|
|
658
|
+
asset_id: vulnerabilityAlertIncidents.asset_id,
|
|
659
|
+
attempt_count: vulnerabilityAlertDeliveries.attempt_count,
|
|
660
|
+
audience: vulnerabilityAlertDeliveries.audience,
|
|
661
|
+
body: vulnerabilityAlertIncidents.body,
|
|
662
|
+
created_at: vulnerabilityAlertDeliveries.created_at,
|
|
663
|
+
delivered_at: vulnerabilityAlertDeliveries.delivered_at,
|
|
664
|
+
id: vulnerabilityAlertDeliveries.id,
|
|
665
|
+
idempotency_key: vulnerabilityAlertDeliveries.idempotency_key,
|
|
666
|
+
kind: vulnerabilityAlertDeliveries.kind,
|
|
667
|
+
last_error: vulnerabilityAlertDeliveries.last_error,
|
|
668
|
+
lease_expires_at: vulnerabilityAlertDeliveries.lease_expires_at,
|
|
669
|
+
next_attempt_at: vulnerabilityAlertDeliveries.next_attempt_at,
|
|
670
|
+
severity: vulnerabilityAlertIncidents.severity,
|
|
671
|
+
state: vulnerabilityAlertDeliveries.state,
|
|
672
|
+
tenant_id: vulnerabilityAlertIncidents.tenant_id,
|
|
673
|
+
title: vulnerabilityAlertIncidents.title,
|
|
674
|
+
updated_at: vulnerabilityAlertDeliveries.updated_at
|
|
675
|
+
}).from(vulnerabilityAlertDeliveries).innerJoin(vulnerabilityAlertIncidents, eq(vulnerabilityAlertIncidents.alert_id, vulnerabilityAlertDeliveries.alert_id)).where(inArray(vulnerabilityAlertDeliveries.id, ids));
|
|
676
|
+
}),
|
|
677
|
+
completeDelivery: (input) => db.transaction(async (transaction2) => {
|
|
678
|
+
const updated = await transaction2.update(vulnerabilityAlertDeliveries).set({
|
|
679
|
+
delivered_at: databaseNow,
|
|
680
|
+
last_error: null,
|
|
681
|
+
lease_expires_at: null,
|
|
682
|
+
state: "delivered",
|
|
683
|
+
updated_at: databaseNow
|
|
684
|
+
}).where(and(eq(vulnerabilityAlertDeliveries.id, input.deliveryId), eq(vulnerabilityAlertDeliveries.state, "delivering"))).returning({ id: vulnerabilityAlertDeliveries.id });
|
|
685
|
+
if (updated.length === 0)
|
|
686
|
+
return false;
|
|
687
|
+
await transaction2.insert(vulnerabilityAlertEvents).values({
|
|
688
|
+
alert_id: input.alertId,
|
|
689
|
+
kind: "delivered",
|
|
690
|
+
metadata: encodedJsonb({
|
|
691
|
+
audience: input.audience,
|
|
692
|
+
kind: input.kind
|
|
693
|
+
})
|
|
694
|
+
});
|
|
695
|
+
return true;
|
|
696
|
+
}),
|
|
697
|
+
deliveries: (requestedLimit) => db.select().from(vulnerabilityAlertDeliveries).orderBy(desc(vulnerabilityAlertDeliveries.created_at)).limit(boundedLimit2(requestedLimit)),
|
|
698
|
+
events: (requestedLimit) => db.select().from(vulnerabilityAlertEvents).orderBy(desc(vulnerabilityAlertEvents.created_at)).limit(boundedLimit2(requestedLimit)),
|
|
699
|
+
failDelivery: (input) => db.transaction(async (transaction2) => {
|
|
700
|
+
const updated = await transaction2.update(vulnerabilityAlertDeliveries).set({
|
|
701
|
+
last_error: input.error,
|
|
702
|
+
lease_expires_at: null,
|
|
703
|
+
next_attempt_at: new Date(input.retryAt),
|
|
704
|
+
state: "failed",
|
|
705
|
+
updated_at: databaseNow
|
|
706
|
+
}).where(and(eq(vulnerabilityAlertDeliveries.id, input.deliveryId), eq(vulnerabilityAlertDeliveries.state, "delivering"))).returning({ id: vulnerabilityAlertDeliveries.id });
|
|
707
|
+
if (updated.length === 0)
|
|
708
|
+
return false;
|
|
709
|
+
await transaction2.insert(vulnerabilityAlertEvents).values({
|
|
710
|
+
alert_id: input.alertId,
|
|
711
|
+
kind: "delivery_failed",
|
|
712
|
+
metadata: encodedJsonb({ error: input.error, kind: input.kind })
|
|
713
|
+
});
|
|
714
|
+
return true;
|
|
715
|
+
}),
|
|
716
|
+
incidents: (requestedLimit) => db.select().from(vulnerabilityAlertIncidents).orderBy(desc(vulnerabilityAlertIncidents.last_observed_at)).limit(boundedLimit2(requestedLimit)),
|
|
717
|
+
observe,
|
|
718
|
+
processEscalations: async ({ fallbackPolicy, policies, tenantIds }) => {
|
|
719
|
+
const due = await db.select({
|
|
720
|
+
alertId: vulnerabilityAlertIncidents.alert_id,
|
|
721
|
+
assetId: vulnerabilityAlertIncidents.asset_id,
|
|
722
|
+
occurrenceCount: vulnerabilityAlertIncidents.occurrence_count,
|
|
723
|
+
severity: vulnerabilityAlertIncidents.severity,
|
|
724
|
+
tenantId: vulnerabilityAlertIncidents.tenant_id
|
|
725
|
+
}).from(vulnerabilityAlertIncidents).where(and(eq(vulnerabilityAlertIncidents.status, "open"), lte(vulnerabilityAlertIncidents.next_escalation_at, databaseNow), tenantIds && tenantIds.length > 0 ? inArray(vulnerabilityAlertIncidents.tenant_id, [...tenantIds]) : undefined));
|
|
726
|
+
let processed = 0;
|
|
727
|
+
for (const incident of due) {
|
|
728
|
+
const policy = policies.get(incident.tenantId) ?? fallbackPolicy;
|
|
729
|
+
if (!policy)
|
|
730
|
+
continue;
|
|
731
|
+
const changed = await db.transaction(async (transaction2) => {
|
|
732
|
+
const claimed = await transaction2.update(vulnerabilityAlertIncidents).set({
|
|
733
|
+
next_escalation_at: null,
|
|
734
|
+
updated_at: databaseNow
|
|
735
|
+
}).where(and(eq(vulnerabilityAlertIncidents.alert_id, incident.alertId), eq(vulnerabilityAlertIncidents.status, "open"), lte(vulnerabilityAlertIncidents.next_escalation_at, databaseNow))).returning({ id: vulnerabilityAlertIncidents.alert_id });
|
|
736
|
+
if (claimed.length === 0)
|
|
737
|
+
return false;
|
|
738
|
+
await transaction2.insert(vulnerabilityAlertEvents).values({
|
|
739
|
+
alert_id: incident.alertId,
|
|
740
|
+
kind: "escalated",
|
|
741
|
+
metadata: encodedJsonb({})
|
|
742
|
+
});
|
|
743
|
+
await queue(transaction2, {
|
|
744
|
+
assetId: incident.assetId,
|
|
745
|
+
id: incident.alertId,
|
|
746
|
+
severity: incident.severity
|
|
747
|
+
}, policy.configuration, "escalated", incident.occurrenceCount);
|
|
748
|
+
return true;
|
|
749
|
+
});
|
|
750
|
+
if (changed)
|
|
751
|
+
processed += 1;
|
|
752
|
+
}
|
|
753
|
+
return processed;
|
|
754
|
+
},
|
|
755
|
+
resolveInactive: async ({
|
|
756
|
+
activeAlertIds,
|
|
757
|
+
fallbackPolicy,
|
|
758
|
+
policies,
|
|
759
|
+
resolvedAt,
|
|
760
|
+
tenantIds
|
|
761
|
+
}) => {
|
|
762
|
+
const open = await db.select({
|
|
763
|
+
alertId: vulnerabilityAlertIncidents.alert_id,
|
|
764
|
+
assetId: vulnerabilityAlertIncidents.asset_id,
|
|
765
|
+
occurrenceCount: vulnerabilityAlertIncidents.occurrence_count,
|
|
766
|
+
severity: vulnerabilityAlertIncidents.severity,
|
|
767
|
+
tenantId: vulnerabilityAlertIncidents.tenant_id
|
|
768
|
+
}).from(vulnerabilityAlertIncidents).where(and(inArray(vulnerabilityAlertIncidents.status, [
|
|
769
|
+
"open",
|
|
770
|
+
"acknowledged"
|
|
771
|
+
]), tenantIds && tenantIds.length > 0 ? inArray(vulnerabilityAlertIncidents.tenant_id, [...tenantIds]) : undefined));
|
|
772
|
+
const at = new Date(resolvedAt ?? new Date().toISOString());
|
|
773
|
+
let processed = 0;
|
|
774
|
+
for (const incident of open) {
|
|
775
|
+
if (activeAlertIds.has(incident.alertId))
|
|
776
|
+
continue;
|
|
777
|
+
const policy = policies.get(incident.tenantId) ?? fallbackPolicy;
|
|
778
|
+
if (!policy)
|
|
779
|
+
continue;
|
|
780
|
+
const changed = await db.transaction(async (transaction2) => {
|
|
781
|
+
const resolved = await transaction2.update(vulnerabilityAlertIncidents).set({
|
|
782
|
+
next_escalation_at: null,
|
|
783
|
+
resolved_at: at,
|
|
784
|
+
status: "resolved",
|
|
785
|
+
updated_at: databaseNow
|
|
786
|
+
}).where(and(eq(vulnerabilityAlertIncidents.alert_id, incident.alertId), inArray(vulnerabilityAlertIncidents.status, [
|
|
787
|
+
"open",
|
|
788
|
+
"acknowledged"
|
|
789
|
+
]))).returning({ id: vulnerabilityAlertIncidents.alert_id });
|
|
790
|
+
if (resolved.length === 0)
|
|
791
|
+
return false;
|
|
792
|
+
await transaction2.insert(vulnerabilityAlertEvents).values({
|
|
793
|
+
alert_id: incident.alertId,
|
|
794
|
+
kind: "resolved",
|
|
795
|
+
metadata: encodedJsonb({})
|
|
796
|
+
});
|
|
797
|
+
await queue(transaction2, {
|
|
798
|
+
assetId: incident.assetId,
|
|
799
|
+
id: incident.alertId,
|
|
800
|
+
severity: incident.severity
|
|
801
|
+
}, policy.configuration, "resolved", incident.occurrenceCount);
|
|
802
|
+
return true;
|
|
803
|
+
});
|
|
804
|
+
if (changed)
|
|
805
|
+
processed += 1;
|
|
806
|
+
}
|
|
807
|
+
return processed;
|
|
808
|
+
}
|
|
809
|
+
};
|
|
810
|
+
return { alertIncidents, alertPolicies };
|
|
811
|
+
};
|
|
341
812
|
|
|
342
813
|
// src/index.ts
|
|
343
814
|
var IDENTIFIER2 = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
|
|
@@ -359,7 +830,7 @@ var limit = (value, fallback = 100) => {
|
|
|
359
830
|
throw new Error("Postgres query limit must be an integer from 1 through 1000");
|
|
360
831
|
return normalized;
|
|
361
832
|
};
|
|
362
|
-
var
|
|
833
|
+
var timestamp2 = (value, label) => {
|
|
363
834
|
if (value instanceof Date)
|
|
364
835
|
return value.toISOString();
|
|
365
836
|
if (typeof value !== "string" || !Number.isFinite(Date.parse(value)))
|
|
@@ -565,7 +1036,7 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
565
1036
|
const tablePrefix = options.tablePrefix ?? "vulnerability";
|
|
566
1037
|
const ddl = vulnerabilityPostgresSchemaSql(tablePrefix);
|
|
567
1038
|
const table = prefixTables(tablePrefix);
|
|
568
|
-
const
|
|
1039
|
+
const sql2 = options.sql;
|
|
569
1040
|
const shouldEnsureSchema = options.ensureSchema ?? true;
|
|
570
1041
|
const alertStores = createPostgresVulnerabilityAlertStores({
|
|
571
1042
|
ensureSchema: shouldEnsureSchema,
|
|
@@ -578,7 +1049,7 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
578
1049
|
return Promise.resolve();
|
|
579
1050
|
if (schemaPromise)
|
|
580
1051
|
return schemaPromise;
|
|
581
|
-
schemaPromise = Promise.resolve(
|
|
1052
|
+
schemaPromise = Promise.resolve(sql2.unsafe(ddl)).then(() => {
|
|
582
1053
|
return;
|
|
583
1054
|
});
|
|
584
1055
|
return schemaPromise;
|
|
@@ -587,7 +1058,7 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
587
1058
|
load: async (feedId) => {
|
|
588
1059
|
await ensureSchema();
|
|
589
1060
|
const id = requiredText(feedId, "Feed id");
|
|
590
|
-
const rows = await
|
|
1061
|
+
const rows = await sql2`
|
|
591
1062
|
SELECT
|
|
592
1063
|
snapshot.feed_id,
|
|
593
1064
|
snapshot.feed_name,
|
|
@@ -603,10 +1074,10 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
603
1074
|
'value', record.value
|
|
604
1075
|
) ORDER BY record.record_id
|
|
605
1076
|
)
|
|
606
|
-
FROM ${
|
|
1077
|
+
FROM ${sql2.unsafe(table.records)} record
|
|
607
1078
|
WHERE record.feed_id = snapshot.feed_id
|
|
608
1079
|
), '[]'::jsonb) AS records
|
|
609
|
-
FROM ${
|
|
1080
|
+
FROM ${sql2.unsafe(table.snapshots)} snapshot
|
|
610
1081
|
WHERE snapshot.feed_id = ${id}
|
|
611
1082
|
`;
|
|
612
1083
|
const row = rows[0];
|
|
@@ -622,10 +1093,10 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
622
1093
|
name: row.feed_name,
|
|
623
1094
|
url: row.feed_url
|
|
624
1095
|
},
|
|
625
|
-
fetchedAt:
|
|
1096
|
+
fetchedAt: timestamp2(row.fetched_at, "Feed fetchedAt"),
|
|
626
1097
|
records: records.map((record) => ({
|
|
627
1098
|
id: requiredText(record.id, "Feed record id"),
|
|
628
|
-
modifiedAt:
|
|
1099
|
+
modifiedAt: timestamp2(record.modifiedAt, "Feed record modifiedAt"),
|
|
629
1100
|
value: record.value
|
|
630
1101
|
})),
|
|
631
1102
|
revision: row.revision
|
|
@@ -635,20 +1106,20 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
635
1106
|
await ensureSchema();
|
|
636
1107
|
const records = JSON.stringify(snapshot.records.map((record) => ({
|
|
637
1108
|
id: requiredText(record.id, "Feed record id"),
|
|
638
|
-
modified_at:
|
|
1109
|
+
modified_at: timestamp2(record.modifiedAt, "Feed record modifiedAt"),
|
|
639
1110
|
value: record.value
|
|
640
1111
|
})));
|
|
641
1112
|
const cursor = JSON.stringify(snapshot.cursor);
|
|
642
|
-
await
|
|
1113
|
+
await sql2`
|
|
643
1114
|
WITH saved_snapshot AS (
|
|
644
|
-
INSERT INTO ${
|
|
1115
|
+
INSERT INTO ${sql2.unsafe(table.snapshots)} (
|
|
645
1116
|
feed_id, feed_name, feed_url, cursor, fetched_at, revision, updated_at
|
|
646
1117
|
) VALUES (
|
|
647
1118
|
${requiredText(snapshot.feed.id, "Feed id")},
|
|
648
1119
|
${requiredText(snapshot.feed.name, "Feed name")},
|
|
649
1120
|
${requiredText(snapshot.feed.url, "Feed URL")},
|
|
650
1121
|
${cursor}::jsonb,
|
|
651
|
-
${
|
|
1122
|
+
${timestamp2(snapshot.fetchedAt, "Feed fetchedAt")}::timestamptz,
|
|
652
1123
|
${snapshot.revision},
|
|
653
1124
|
now()
|
|
654
1125
|
)
|
|
@@ -665,14 +1136,14 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
665
1136
|
FROM jsonb_to_recordset(${records}::jsonb)
|
|
666
1137
|
AS item(id text, modified_at text, value jsonb)
|
|
667
1138
|
), removed AS (
|
|
668
|
-
DELETE FROM ${
|
|
1139
|
+
DELETE FROM ${sql2.unsafe(table.records)} record
|
|
669
1140
|
WHERE record.feed_id = ${snapshot.feed.id}
|
|
670
1141
|
AND NOT EXISTS (
|
|
671
1142
|
SELECT 1 FROM incoming WHERE incoming.id = record.record_id
|
|
672
1143
|
)
|
|
673
1144
|
RETURNING record_id
|
|
674
1145
|
), written AS (
|
|
675
|
-
INSERT INTO ${
|
|
1146
|
+
INSERT INTO ${sql2.unsafe(table.records)} (
|
|
676
1147
|
feed_id, record_id, modified_at, value
|
|
677
1148
|
)
|
|
678
1149
|
SELECT saved_snapshot.feed_id, incoming.id, incoming.modified_at, incoming.value
|
|
@@ -695,14 +1166,14 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
695
1166
|
throw new Error(`Unsupported feed sync status: ${run.status}`);
|
|
696
1167
|
if (!Number.isInteger(run.records) || run.records < 0)
|
|
697
1168
|
throw new Error("Feed sync records must be a non-negative integer");
|
|
698
|
-
await
|
|
699
|
-
INSERT INTO ${
|
|
1169
|
+
await sql2`
|
|
1170
|
+
INSERT INTO ${sql2.unsafe(table.runs)} (
|
|
700
1171
|
id, feed_id, started_at, completed_at, status, error, records, revision
|
|
701
1172
|
) VALUES (
|
|
702
1173
|
${requiredText(run.id, "Feed sync run id")},
|
|
703
1174
|
${requiredText(run.feedId, "Feed sync feed id")},
|
|
704
|
-
${
|
|
705
|
-
${
|
|
1175
|
+
${timestamp2(run.startedAt, "Feed sync startedAt")}::timestamptz,
|
|
1176
|
+
${timestamp2(run.completedAt, "Feed sync completedAt")}::timestamptz,
|
|
706
1177
|
${run.status}, ${run.error}, ${run.records}, ${run.revision}
|
|
707
1178
|
)
|
|
708
1179
|
ON CONFLICT (id) DO UPDATE SET
|
|
@@ -719,22 +1190,22 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
719
1190
|
await ensureSchema();
|
|
720
1191
|
const feedId = filter.feedId?.trim() || null;
|
|
721
1192
|
const status = filter.status ?? null;
|
|
722
|
-
const rows = await
|
|
1193
|
+
const rows = await sql2`
|
|
723
1194
|
SELECT id, feed_id, started_at, completed_at, status, error, records, revision
|
|
724
|
-
FROM ${
|
|
1195
|
+
FROM ${sql2.unsafe(table.runs)}
|
|
725
1196
|
WHERE (${feedId}::text IS NULL OR feed_id = ${feedId})
|
|
726
1197
|
AND (${status}::text IS NULL OR status = ${status})
|
|
727
1198
|
ORDER BY started_at DESC, id DESC
|
|
728
1199
|
LIMIT ${limit(filter.limit)}
|
|
729
1200
|
`;
|
|
730
1201
|
return rows.map((row) => ({
|
|
731
|
-
completedAt:
|
|
1202
|
+
completedAt: timestamp2(row.completed_at, "Feed sync completedAt"),
|
|
732
1203
|
error: row.error,
|
|
733
1204
|
feedId: row.feed_id,
|
|
734
1205
|
id: row.id,
|
|
735
1206
|
records: Number(row.records),
|
|
736
1207
|
revision: row.revision,
|
|
737
|
-
startedAt:
|
|
1208
|
+
startedAt: timestamp2(row.started_at, "Feed sync startedAt"),
|
|
738
1209
|
status: row.status
|
|
739
1210
|
}));
|
|
740
1211
|
}
|
|
@@ -759,8 +1230,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
759
1230
|
tenant_id: finding.tenantId,
|
|
760
1231
|
value: finding
|
|
761
1232
|
})));
|
|
762
|
-
await
|
|
763
|
-
INSERT INTO ${
|
|
1233
|
+
await sql2`
|
|
1234
|
+
INSERT INTO ${sql2.unsafe(table.findings)} (
|
|
764
1235
|
tenant_id, finding_id, asset_id, component_id, severity, status,
|
|
765
1236
|
first_seen_at, last_seen_at, value, updated_at
|
|
766
1237
|
)
|
|
@@ -778,8 +1249,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
778
1249
|
component_id = EXCLUDED.component_id,
|
|
779
1250
|
severity = EXCLUDED.severity,
|
|
780
1251
|
status = EXCLUDED.status,
|
|
781
|
-
first_seen_at = LEAST(${
|
|
782
|
-
last_seen_at = GREATEST(${
|
|
1252
|
+
first_seen_at = LEAST(${sql2.unsafe(table.findings)}.first_seen_at, EXCLUDED.first_seen_at),
|
|
1253
|
+
last_seen_at = GREATEST(${sql2.unsafe(table.findings)}.last_seen_at, EXCLUDED.last_seen_at),
|
|
783
1254
|
value = EXCLUDED.value,
|
|
784
1255
|
updated_at = now()
|
|
785
1256
|
`;
|
|
@@ -793,8 +1264,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
793
1264
|
const findings = {
|
|
794
1265
|
get: async (tenantId, findingId) => {
|
|
795
1266
|
await ensureSchema();
|
|
796
|
-
const rows = await
|
|
797
|
-
SELECT value FROM ${
|
|
1267
|
+
const rows = await sql2`
|
|
1268
|
+
SELECT value FROM ${sql2.unsafe(table.findings)}
|
|
798
1269
|
WHERE tenant_id = ${requiredText(tenantId, "Tenant id")}
|
|
799
1270
|
AND finding_id = ${requiredText(findingId, "Finding id")}
|
|
800
1271
|
`;
|
|
@@ -806,8 +1277,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
806
1277
|
const assetId = filter.assetId?.trim() || null;
|
|
807
1278
|
const severity = filter.severity ?? null;
|
|
808
1279
|
const status = filter.status ?? null;
|
|
809
|
-
const rows = await
|
|
810
|
-
SELECT value FROM ${
|
|
1280
|
+
const rows = await sql2`
|
|
1281
|
+
SELECT value FROM ${sql2.unsafe(table.findings)}
|
|
811
1282
|
WHERE tenant_id = ${tenantId}
|
|
812
1283
|
AND (${assetId}::text IS NULL OR asset_id = ${assetId})
|
|
813
1284
|
AND (${severity}::text IS NULL OR severity = ${severity})
|
|
@@ -843,8 +1314,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
843
1314
|
observed_at: observation.observedAt,
|
|
844
1315
|
value: observation
|
|
845
1316
|
})));
|
|
846
|
-
await
|
|
847
|
-
INSERT INTO ${
|
|
1317
|
+
await sql2`
|
|
1318
|
+
INSERT INTO ${sql2.unsafe(table.observations)} (
|
|
848
1319
|
tenant_id, observation_id, asset_id, component_id, observed_at, value,
|
|
849
1320
|
updated_at
|
|
850
1321
|
)
|
|
@@ -866,8 +1337,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
866
1337
|
const observations = {
|
|
867
1338
|
get: async (tenantId, observationId) => {
|
|
868
1339
|
await ensureSchema();
|
|
869
|
-
const rows = await
|
|
870
|
-
SELECT value FROM ${
|
|
1340
|
+
const rows = await sql2`
|
|
1341
|
+
SELECT value FROM ${sql2.unsafe(table.observations)}
|
|
871
1342
|
WHERE tenant_id = ${requiredText(tenantId, "Tenant id")}
|
|
872
1343
|
AND observation_id = ${requiredText(observationId, "Observation id")}
|
|
873
1344
|
`;
|
|
@@ -878,8 +1349,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
878
1349
|
const tenantId = requiredText(filter.tenantId, "Tenant id");
|
|
879
1350
|
const assetId = filter.assetId?.trim() || null;
|
|
880
1351
|
const componentId = filter.componentId?.trim() || null;
|
|
881
|
-
const rows = await
|
|
882
|
-
SELECT value FROM ${
|
|
1352
|
+
const rows = await sql2`
|
|
1353
|
+
SELECT value FROM ${sql2.unsafe(table.observations)}
|
|
883
1354
|
WHERE tenant_id = ${tenantId}
|
|
884
1355
|
AND (${assetId}::text IS NULL OR asset_id = ${assetId})
|
|
885
1356
|
AND (${componentId}::text IS NULL OR component_id = ${componentId})
|
|
@@ -914,8 +1385,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
914
1385
|
remediate_by: assessment.remediateBy,
|
|
915
1386
|
value: assessment
|
|
916
1387
|
})));
|
|
917
|
-
await
|
|
918
|
-
INSERT INTO ${
|
|
1388
|
+
await sql2`
|
|
1389
|
+
INSERT INTO ${sql2.unsafe(table.riskAssessments)} (
|
|
919
1390
|
tenant_id, finding_id, priority, assessed_at, remediate_by, value,
|
|
920
1391
|
updated_at
|
|
921
1392
|
)
|
|
@@ -938,8 +1409,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
938
1409
|
const riskAssessments = {
|
|
939
1410
|
get: async (tenantId, findingId) => {
|
|
940
1411
|
await ensureSchema();
|
|
941
|
-
const rows = await
|
|
942
|
-
SELECT value FROM ${
|
|
1412
|
+
const rows = await sql2`
|
|
1413
|
+
SELECT value FROM ${sql2.unsafe(table.riskAssessments)}
|
|
943
1414
|
WHERE tenant_id = ${requiredText(tenantId, "Tenant id")}
|
|
944
1415
|
AND finding_id = ${requiredText(findingId, "Finding id")}
|
|
945
1416
|
`;
|
|
@@ -949,8 +1420,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
949
1420
|
await ensureSchema();
|
|
950
1421
|
const tenantId = requiredText(filter.tenantId, "Tenant id");
|
|
951
1422
|
const priority = filter.priority ?? null;
|
|
952
|
-
const rows = await
|
|
953
|
-
SELECT value FROM ${
|
|
1423
|
+
const rows = await sql2`
|
|
1424
|
+
SELECT value FROM ${sql2.unsafe(table.riskAssessments)}
|
|
954
1425
|
WHERE tenant_id = ${tenantId}
|
|
955
1426
|
AND (${priority}::text IS NULL OR priority = ${priority})
|
|
956
1427
|
ORDER BY assessed_at DESC, finding_id
|
|
@@ -970,8 +1441,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
970
1441
|
const remediationPlans = {
|
|
971
1442
|
get: async (tenantId, planId) => {
|
|
972
1443
|
await ensureSchema();
|
|
973
|
-
const rows = await
|
|
974
|
-
SELECT value FROM ${
|
|
1444
|
+
const rows = await sql2`
|
|
1445
|
+
SELECT value FROM ${sql2.unsafe(table.remediationPlans)}
|
|
975
1446
|
WHERE tenant_id = ${requiredText(tenantId, "Tenant id")}
|
|
976
1447
|
AND plan_id = ${requiredText(planId, "Remediation plan id")}
|
|
977
1448
|
`;
|
|
@@ -981,8 +1452,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
981
1452
|
await ensureSchema();
|
|
982
1453
|
const tenantId = requiredText(filter.tenantId, "Tenant id");
|
|
983
1454
|
const status = filter.status ?? null;
|
|
984
|
-
const rows = await
|
|
985
|
-
SELECT value FROM ${
|
|
1455
|
+
const rows = await sql2`
|
|
1456
|
+
SELECT value FROM ${sql2.unsafe(table.remediationPlans)}
|
|
986
1457
|
WHERE tenant_id = ${tenantId}
|
|
987
1458
|
AND (${status}::text IS NULL OR status = ${status})
|
|
988
1459
|
ORDER BY created_at DESC, plan_id
|
|
@@ -995,8 +1466,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
995
1466
|
const planId = plan.id;
|
|
996
1467
|
if (!Value.Check(RemediationPlanSchema, plan))
|
|
997
1468
|
throw new Error(`Remediation plan ${planId} is invalid`);
|
|
998
|
-
await
|
|
999
|
-
INSERT INTO ${
|
|
1469
|
+
await sql2`
|
|
1470
|
+
INSERT INTO ${sql2.unsafe(table.remediationPlans)} (
|
|
1000
1471
|
tenant_id, plan_id, status, created_at, value, updated_at
|
|
1001
1472
|
) VALUES (
|
|
1002
1473
|
${requiredText(tenantId, "Tenant id")}, ${plan.id}, ${plan.status},
|
|
@@ -1019,8 +1490,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1019
1490
|
const remediationExecutions = {
|
|
1020
1491
|
get: async (tenantId, executionId) => {
|
|
1021
1492
|
await ensureSchema();
|
|
1022
|
-
const rows = await
|
|
1023
|
-
SELECT value FROM ${
|
|
1493
|
+
const rows = await sql2`
|
|
1494
|
+
SELECT value FROM ${sql2.unsafe(table.remediationExecutions)}
|
|
1024
1495
|
WHERE tenant_id = ${requiredText(tenantId, "Tenant id")}
|
|
1025
1496
|
AND execution_id = ${requiredText(executionId, "Remediation execution id")}
|
|
1026
1497
|
`;
|
|
@@ -1028,8 +1499,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1028
1499
|
},
|
|
1029
1500
|
list: async (tenantId, planId) => {
|
|
1030
1501
|
await ensureSchema();
|
|
1031
|
-
const rows = await
|
|
1032
|
-
SELECT value FROM ${
|
|
1502
|
+
const rows = await sql2`
|
|
1503
|
+
SELECT value FROM ${sql2.unsafe(table.remediationExecutions)}
|
|
1033
1504
|
WHERE tenant_id = ${requiredText(tenantId, "Tenant id")}
|
|
1034
1505
|
AND plan_id = ${requiredText(planId, "Remediation plan id")}
|
|
1035
1506
|
ORDER BY started_at DESC, execution_id
|
|
@@ -1042,8 +1513,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1042
1513
|
const executionId = execution.id;
|
|
1043
1514
|
if (!Value.Check(RemediationExecutionSchema, execution))
|
|
1044
1515
|
throw new Error(`Remediation execution ${executionId} is invalid`);
|
|
1045
|
-
await
|
|
1046
|
-
INSERT INTO ${
|
|
1516
|
+
await sql2`
|
|
1517
|
+
INSERT INTO ${sql2.unsafe(table.remediationExecutions)} (
|
|
1047
1518
|
tenant_id, execution_id, plan_id, status, started_at, completed_at,
|
|
1048
1519
|
value, updated_at
|
|
1049
1520
|
) VALUES (
|
|
@@ -1072,8 +1543,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1072
1543
|
const remediationVerifications = {
|
|
1073
1544
|
get: async (tenantId, verificationId) => {
|
|
1074
1545
|
await ensureSchema();
|
|
1075
|
-
const rows = await
|
|
1076
|
-
SELECT value FROM ${
|
|
1546
|
+
const rows = await sql2`
|
|
1547
|
+
SELECT value FROM ${sql2.unsafe(table.remediationVerifications)}
|
|
1077
1548
|
WHERE tenant_id = ${requiredText(tenantId, "Tenant id")}
|
|
1078
1549
|
AND verification_id = ${requiredText(verificationId, "Remediation verification id")}
|
|
1079
1550
|
`;
|
|
@@ -1081,8 +1552,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1081
1552
|
},
|
|
1082
1553
|
list: async (tenantId, executionId) => {
|
|
1083
1554
|
await ensureSchema();
|
|
1084
|
-
const rows = await
|
|
1085
|
-
SELECT value FROM ${
|
|
1555
|
+
const rows = await sql2`
|
|
1556
|
+
SELECT value FROM ${sql2.unsafe(table.remediationVerifications)}
|
|
1086
1557
|
WHERE tenant_id = ${requiredText(tenantId, "Tenant id")}
|
|
1087
1558
|
AND execution_id = ${requiredText(executionId, "Remediation execution id")}
|
|
1088
1559
|
ORDER BY observed_at DESC, verification_id
|
|
@@ -1095,8 +1566,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1095
1566
|
const verificationId = verification.id;
|
|
1096
1567
|
if (!Value.Check(RemediationVerificationSchema, verification))
|
|
1097
1568
|
throw new Error(`Remediation verification ${verificationId} is invalid`);
|
|
1098
|
-
await
|
|
1099
|
-
INSERT INTO ${
|
|
1569
|
+
await sql2`
|
|
1570
|
+
INSERT INTO ${sql2.unsafe(table.remediationVerifications)} (
|
|
1100
1571
|
tenant_id, verification_id, execution_id, plan_id, status,
|
|
1101
1572
|
observed_at, value, updated_at
|
|
1102
1573
|
) VALUES (
|
|
@@ -1140,8 +1611,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1140
1611
|
value: decision,
|
|
1141
1612
|
vulnerability_id: decision.vulnerabilityId
|
|
1142
1613
|
})));
|
|
1143
|
-
await
|
|
1144
|
-
INSERT INTO ${
|
|
1614
|
+
await sql2`
|
|
1615
|
+
INSERT INTO ${sql2.unsafe(table.vexDecisions)} (
|
|
1145
1616
|
tenant_id, decision_id, product_id, vulnerability_id, status,
|
|
1146
1617
|
created_at, expires_at, value, updated_at
|
|
1147
1618
|
)
|
|
@@ -1166,8 +1637,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1166
1637
|
const vexDecisions = {
|
|
1167
1638
|
get: async (tenantId, decisionId) => {
|
|
1168
1639
|
await ensureSchema();
|
|
1169
|
-
const rows = await
|
|
1170
|
-
SELECT value FROM ${
|
|
1640
|
+
const rows = await sql2`
|
|
1641
|
+
SELECT value FROM ${sql2.unsafe(table.vexDecisions)}
|
|
1171
1642
|
WHERE tenant_id = ${requiredText(tenantId, "Tenant id")}
|
|
1172
1643
|
AND decision_id = ${requiredText(decisionId, "Decision id")}
|
|
1173
1644
|
`;
|
|
@@ -1178,8 +1649,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1178
1649
|
const tenantId = requiredText(filter.tenantId, "Tenant id");
|
|
1179
1650
|
const productId = filter.productId?.trim() || null;
|
|
1180
1651
|
const vulnerabilityId = filter.vulnerabilityId?.trim() || null;
|
|
1181
|
-
const rows = await
|
|
1182
|
-
SELECT value FROM ${
|
|
1652
|
+
const rows = await sql2`
|
|
1653
|
+
SELECT value FROM ${sql2.unsafe(table.vexDecisions)}
|
|
1183
1654
|
WHERE tenant_id = ${tenantId}
|
|
1184
1655
|
AND (${productId}::text IS NULL OR product_id = ${productId})
|
|
1185
1656
|
AND (${vulnerabilityId}::text IS NULL OR vulnerability_id = ${vulnerabilityId})
|
|
@@ -1214,8 +1685,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1214
1685
|
tenant_id: application.tenantId,
|
|
1215
1686
|
value: application
|
|
1216
1687
|
})));
|
|
1217
|
-
await
|
|
1218
|
-
INSERT INTO ${
|
|
1688
|
+
await sql2`
|
|
1689
|
+
INSERT INTO ${sql2.unsafe(table.vexApplications)} (
|
|
1219
1690
|
tenant_id, finding_id, decision_id, applied_at, ended_at, value,
|
|
1220
1691
|
updated_at
|
|
1221
1692
|
)
|
|
@@ -1238,8 +1709,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1238
1709
|
const vexApplications = {
|
|
1239
1710
|
get: async (tenantId, findingId) => {
|
|
1240
1711
|
await ensureSchema();
|
|
1241
|
-
const rows = await
|
|
1242
|
-
SELECT value FROM ${
|
|
1712
|
+
const rows = await sql2`
|
|
1713
|
+
SELECT value FROM ${sql2.unsafe(table.vexApplications)}
|
|
1243
1714
|
WHERE tenant_id = ${requiredText(tenantId, "Tenant id")}
|
|
1244
1715
|
AND finding_id = ${requiredText(findingId, "Finding id")}
|
|
1245
1716
|
`;
|
|
@@ -1255,8 +1726,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1255
1726
|
throw new Error("Feed lease ttlMs must be positive and finite");
|
|
1256
1727
|
const now = request.now ?? new Date;
|
|
1257
1728
|
const expiresAt = new Date(now.getTime() + request.ttlMs);
|
|
1258
|
-
const rows = await
|
|
1259
|
-
INSERT INTO ${
|
|
1729
|
+
const rows = await sql2`
|
|
1730
|
+
INSERT INTO ${sql2.unsafe(table.leases)} (
|
|
1260
1731
|
feed_id, owner_id, expires_at, updated_at
|
|
1261
1732
|
) VALUES (
|
|
1262
1733
|
${requiredText(request.feedId, "Feed lease feed id")},
|
|
@@ -1268,16 +1739,16 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1268
1739
|
owner_id = EXCLUDED.owner_id,
|
|
1269
1740
|
expires_at = EXCLUDED.expires_at,
|
|
1270
1741
|
updated_at = EXCLUDED.updated_at
|
|
1271
|
-
WHERE ${
|
|
1272
|
-
OR ${
|
|
1742
|
+
WHERE ${sql2.unsafe(table.leases)}.expires_at <= ${now.toISOString()}::timestamptz
|
|
1743
|
+
OR ${sql2.unsafe(table.leases)}.owner_id = EXCLUDED.owner_id
|
|
1273
1744
|
RETURNING owner_id
|
|
1274
1745
|
`;
|
|
1275
1746
|
return rows[0]?.owner_id === request.ownerId.trim();
|
|
1276
1747
|
},
|
|
1277
1748
|
release: async (feedId, ownerId) => {
|
|
1278
1749
|
await ensureSchema();
|
|
1279
|
-
const rows = await
|
|
1280
|
-
DELETE FROM ${
|
|
1750
|
+
const rows = await sql2`
|
|
1751
|
+
DELETE FROM ${sql2.unsafe(table.leases)}
|
|
1281
1752
|
WHERE feed_id = ${requiredText(feedId, "Feed lease feed id")}
|
|
1282
1753
|
AND owner_id = ${requiredText(ownerId, "Feed lease owner id")}
|
|
1283
1754
|
RETURNING feed_id
|
|
@@ -1305,8 +1776,14 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1305
1776
|
export {
|
|
1306
1777
|
vulnerabilityPostgresSchemaSql,
|
|
1307
1778
|
vulnerabilityAlertPostgresSchemaSql,
|
|
1779
|
+
vulnerabilityAlertPolicyVersions,
|
|
1780
|
+
vulnerabilityAlertIncidents,
|
|
1781
|
+
vulnerabilityAlertEvents,
|
|
1782
|
+
vulnerabilityAlertDrizzleSchema,
|
|
1783
|
+
vulnerabilityAlertDeliveries,
|
|
1308
1784
|
createPostgresVulnerabilityStore,
|
|
1309
1785
|
createPostgresVulnerabilityAlertStores,
|
|
1786
|
+
createDrizzleVulnerabilityAlertStores,
|
|
1310
1787
|
VulnerabilityAlertValidationError,
|
|
1311
1788
|
VulnerabilityAlertNotFoundError,
|
|
1312
1789
|
VulnerabilityAlertConflictError
|