@absolutejs/vulnerabilities-postgres 0.7.0 → 0.9.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 +25 -4
- package/dist/coreDrizzle.d.ts +3230 -0
- package/dist/drizzle.d.ts +1561 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1303 -145
- package/dist/manifest.js +40 -0
- package/dist/manifest.json +42 -0
- package/package.json +4 -3
package/dist/index.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
// src/index.ts
|
|
3
3
|
import {
|
|
4
|
-
ManagedVulnerabilityFindingSchema,
|
|
5
|
-
RemediationExecutionSchema,
|
|
6
|
-
RemediationPlanSchema,
|
|
7
|
-
RemediationVerificationSchema,
|
|
8
|
-
VulnerabilityObservationSchema,
|
|
9
|
-
VulnerabilityRiskAssessmentSchema,
|
|
10
|
-
VexDecisionSchema,
|
|
11
|
-
VexFindingApplicationSchema
|
|
4
|
+
ManagedVulnerabilityFindingSchema as ManagedVulnerabilityFindingSchema2,
|
|
5
|
+
RemediationExecutionSchema as RemediationExecutionSchema2,
|
|
6
|
+
RemediationPlanSchema as RemediationPlanSchema2,
|
|
7
|
+
RemediationVerificationSchema as RemediationVerificationSchema2,
|
|
8
|
+
VulnerabilityObservationSchema as VulnerabilityObservationSchema2,
|
|
9
|
+
VulnerabilityRiskAssessmentSchema as VulnerabilityRiskAssessmentSchema2,
|
|
10
|
+
VexDecisionSchema as VexDecisionSchema2,
|
|
11
|
+
VexFindingApplicationSchema as VexFindingApplicationSchema2
|
|
12
12
|
} from "@absolutejs/vulnerabilities";
|
|
13
|
-
import { Value } from "@sinclair/typebox/value";
|
|
13
|
+
import { Value as Value2 } from "@sinclair/typebox/value";
|
|
14
14
|
|
|
15
15
|
// src/alerts.ts
|
|
16
16
|
import {
|
|
@@ -338,6 +338,1144 @@ var createPostgresVulnerabilityAlertStores = (options) => {
|
|
|
338
338
|
};
|
|
339
339
|
return { alertIncidents, alertPolicies, ensureAlertSchema };
|
|
340
340
|
};
|
|
341
|
+
// src/coreDrizzle.ts
|
|
342
|
+
import {
|
|
343
|
+
ManagedVulnerabilityFindingSchema,
|
|
344
|
+
RemediationExecutionSchema,
|
|
345
|
+
RemediationPlanSchema,
|
|
346
|
+
RemediationVerificationSchema,
|
|
347
|
+
VexDecisionSchema,
|
|
348
|
+
VexFindingApplicationSchema,
|
|
349
|
+
VulnerabilityObservationSchema,
|
|
350
|
+
VulnerabilityRiskAssessmentSchema
|
|
351
|
+
} from "@absolutejs/vulnerabilities";
|
|
352
|
+
import { Value } from "@sinclair/typebox/value";
|
|
353
|
+
import { and as and2, desc as desc2, eq as eq2, lte as lte2, notInArray, or as or2, sql as sql2 } from "drizzle-orm";
|
|
354
|
+
import {
|
|
355
|
+
check,
|
|
356
|
+
index as index2,
|
|
357
|
+
integer as integer2,
|
|
358
|
+
jsonb,
|
|
359
|
+
pgTable as pgTable2,
|
|
360
|
+
primaryKey as primaryKey2,
|
|
361
|
+
text as text2,
|
|
362
|
+
timestamp as timestamp2
|
|
363
|
+
} from "drizzle-orm/pg-core";
|
|
364
|
+
|
|
365
|
+
// src/drizzle.ts
|
|
366
|
+
import { and, asc, desc, eq, inArray, lte, max, or, sql } from "drizzle-orm";
|
|
367
|
+
import {
|
|
368
|
+
bigserial,
|
|
369
|
+
customType,
|
|
370
|
+
index,
|
|
371
|
+
integer,
|
|
372
|
+
pgTable,
|
|
373
|
+
primaryKey,
|
|
374
|
+
text,
|
|
375
|
+
timestamp,
|
|
376
|
+
uniqueIndex,
|
|
377
|
+
uuid
|
|
378
|
+
} from "drizzle-orm/pg-core";
|
|
379
|
+
import {
|
|
380
|
+
resolveVulnerabilityAlertAudiences as resolveVulnerabilityAlertAudiences2,
|
|
381
|
+
validateVulnerabilityAlertConfiguration as validateVulnerabilityAlertConfiguration2
|
|
382
|
+
} from "@absolutejs/vulnerabilities";
|
|
383
|
+
var databaseNow = sql`now()`;
|
|
384
|
+
var portableJsonb = customType({
|
|
385
|
+
dataType: () => "jsonb",
|
|
386
|
+
fromDriver: (value) => typeof value === "string" ? JSON.parse(value) : value,
|
|
387
|
+
toDriver: (value) => JSON.stringify(value)
|
|
388
|
+
});
|
|
389
|
+
var encodedJsonb = (value) => sql`${JSON.stringify(value)}::text::jsonb`;
|
|
390
|
+
var boundedLimit2 = (value = 1000) => {
|
|
391
|
+
if (!Number.isInteger(value) || value < 1 || value > 1000)
|
|
392
|
+
throw new Error("Alert query limit must be an integer from 1 through 1000");
|
|
393
|
+
return value;
|
|
394
|
+
};
|
|
395
|
+
var vulnerabilityAlertPolicyVersions = pgTable("vulnerability_alert_policy_versions", {
|
|
396
|
+
activated_at: timestamp({ mode: "date", withTimezone: true }).notNull(),
|
|
397
|
+
activated_by: uuid().notNull(),
|
|
398
|
+
configuration: portableJsonb().$type().notNull(),
|
|
399
|
+
reason: text().notNull(),
|
|
400
|
+
status: text().$type().notNull(),
|
|
401
|
+
tenant_id: text().notNull(),
|
|
402
|
+
version: integer().notNull()
|
|
403
|
+
}, (table) => [
|
|
404
|
+
primaryKey({ columns: [table.tenant_id, table.version] }),
|
|
405
|
+
uniqueIndex("vulnerability_alert_policy_versions_active_idx").on(table.tenant_id).where(sql`${table.status} = 'active'`),
|
|
406
|
+
index("vulnerability_alert_policy_versions_history_idx").on(table.tenant_id, table.activated_at)
|
|
407
|
+
]);
|
|
408
|
+
var vulnerabilityAlertIncidents = pgTable("vulnerability_alert_incidents", {
|
|
409
|
+
acknowledged_at: timestamp({ mode: "date", withTimezone: true }),
|
|
410
|
+
acknowledged_by: uuid(),
|
|
411
|
+
alert_id: text().primaryKey(),
|
|
412
|
+
asset_id: text(),
|
|
413
|
+
body: text().notNull(),
|
|
414
|
+
due_at: timestamp({ mode: "date", withTimezone: true }),
|
|
415
|
+
finding_id: text(),
|
|
416
|
+
first_observed_at: timestamp({
|
|
417
|
+
mode: "date",
|
|
418
|
+
withTimezone: true
|
|
419
|
+
}).notNull(),
|
|
420
|
+
kind: text().$type().notNull(),
|
|
421
|
+
last_observed_at: timestamp({
|
|
422
|
+
mode: "date",
|
|
423
|
+
withTimezone: true
|
|
424
|
+
}).notNull(),
|
|
425
|
+
next_escalation_at: timestamp({ mode: "date", withTimezone: true }),
|
|
426
|
+
observation_count: integer().notNull().default(1),
|
|
427
|
+
occurrence_count: integer().notNull().default(1),
|
|
428
|
+
plan_id: text(),
|
|
429
|
+
policy_version: integer(),
|
|
430
|
+
resolved_at: timestamp({ mode: "date", withTimezone: true }),
|
|
431
|
+
severity: text().$type().notNull(),
|
|
432
|
+
source_id: text(),
|
|
433
|
+
status: text().$type().notNull().default("open"),
|
|
434
|
+
tenant_id: text().notNull(),
|
|
435
|
+
title: text().notNull(),
|
|
436
|
+
updated_at: timestamp({ mode: "date", withTimezone: true }).notNull().defaultNow(),
|
|
437
|
+
value: portableJsonb().$type().notNull()
|
|
438
|
+
}, (table) => [
|
|
439
|
+
index("vulnerability_alert_incidents_status_idx").on(table.status, table.last_observed_at),
|
|
440
|
+
index("vulnerability_alert_incidents_tenant_idx").on(table.tenant_id, table.status),
|
|
441
|
+
index("vulnerability_alert_incidents_escalation_idx").on(table.status, table.next_escalation_at)
|
|
442
|
+
]);
|
|
443
|
+
var vulnerabilityAlertEvents = pgTable("vulnerability_alert_events", {
|
|
444
|
+
actor_id: uuid(),
|
|
445
|
+
alert_id: text().notNull().references(() => vulnerabilityAlertIncidents.alert_id, {
|
|
446
|
+
onDelete: "cascade"
|
|
447
|
+
}),
|
|
448
|
+
created_at: timestamp({ mode: "date", withTimezone: true }).notNull().defaultNow(),
|
|
449
|
+
id: bigserial({ mode: "number" }).primaryKey(),
|
|
450
|
+
kind: text().$type().notNull(),
|
|
451
|
+
metadata: portableJsonb().$type().notNull().default(sql`'{}'::jsonb`)
|
|
452
|
+
}, (table) => [
|
|
453
|
+
index("vulnerability_alert_events_alert_idx").on(table.alert_id, table.created_at)
|
|
454
|
+
]);
|
|
455
|
+
var vulnerabilityAlertDeliveries = pgTable("vulnerability_alert_deliveries", {
|
|
456
|
+
alert_id: text().notNull().references(() => vulnerabilityAlertIncidents.alert_id, {
|
|
457
|
+
onDelete: "cascade"
|
|
458
|
+
}),
|
|
459
|
+
attempt_count: integer().notNull().default(0),
|
|
460
|
+
audience: text().$type().notNull(),
|
|
461
|
+
created_at: timestamp({ mode: "date", withTimezone: true }).notNull().defaultNow(),
|
|
462
|
+
delivered_at: timestamp({ mode: "date", withTimezone: true }),
|
|
463
|
+
id: uuid().primaryKey().defaultRandom(),
|
|
464
|
+
idempotency_key: text().notNull(),
|
|
465
|
+
kind: text().$type().notNull(),
|
|
466
|
+
last_error: text(),
|
|
467
|
+
lease_expires_at: timestamp({ mode: "date", withTimezone: true }),
|
|
468
|
+
next_attempt_at: timestamp({ mode: "date", withTimezone: true }).notNull().defaultNow(),
|
|
469
|
+
state: text().$type().notNull().default("pending"),
|
|
470
|
+
updated_at: timestamp({ mode: "date", withTimezone: true }).notNull().defaultNow()
|
|
471
|
+
}, (table) => [
|
|
472
|
+
uniqueIndex("vulnerability_alert_deliveries_key_idx").on(table.idempotency_key),
|
|
473
|
+
index("vulnerability_alert_deliveries_state_idx").on(table.state, table.next_attempt_at)
|
|
474
|
+
]);
|
|
475
|
+
var vulnerabilityAlertDrizzleSchema = {
|
|
476
|
+
vulnerabilityAlertDeliveries,
|
|
477
|
+
vulnerabilityAlertEvents,
|
|
478
|
+
vulnerabilityAlertIncidents,
|
|
479
|
+
vulnerabilityAlertPolicyVersions
|
|
480
|
+
};
|
|
481
|
+
var queue = async (transaction2, alert, configuration, kind, occurrence) => {
|
|
482
|
+
const audiences = resolveVulnerabilityAlertAudiences2({
|
|
483
|
+
configuration,
|
|
484
|
+
hasOwner: alert.assetId !== null,
|
|
485
|
+
kind,
|
|
486
|
+
severity: alert.severity
|
|
487
|
+
});
|
|
488
|
+
if (audiences.length === 0)
|
|
489
|
+
return;
|
|
490
|
+
await transaction2.insert(vulnerabilityAlertDeliveries).values(audiences.map((audience) => ({
|
|
491
|
+
alert_id: alert.id,
|
|
492
|
+
audience,
|
|
493
|
+
id: crypto.randomUUID(),
|
|
494
|
+
idempotency_key: `${alert.id}:${audience}:${kind}:${occurrence}`,
|
|
495
|
+
kind
|
|
496
|
+
}))).onConflictDoNothing({
|
|
497
|
+
target: vulnerabilityAlertDeliveries.idempotency_key
|
|
498
|
+
});
|
|
499
|
+
};
|
|
500
|
+
var createDrizzleVulnerabilityAlertStores = (db) => {
|
|
501
|
+
const alertPolicies = {
|
|
502
|
+
activate: async (input) => {
|
|
503
|
+
let configuration;
|
|
504
|
+
try {
|
|
505
|
+
configuration = validateVulnerabilityAlertConfiguration2(input.configuration);
|
|
506
|
+
} catch (error) {
|
|
507
|
+
throw new VulnerabilityAlertValidationError(error instanceof Error ? error.message : "Policy is invalid");
|
|
508
|
+
}
|
|
509
|
+
const reason = input.reason.trim();
|
|
510
|
+
if (!reason)
|
|
511
|
+
throw new VulnerabilityAlertValidationError("Policy activation reason is required");
|
|
512
|
+
return db.transaction(async (transaction2) => {
|
|
513
|
+
await transaction2.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${`vulnerability-alert-policy:${input.tenantId}`}))`);
|
|
514
|
+
const [latest] = await transaction2.select({
|
|
515
|
+
version: sql`COALESCE(${max(vulnerabilityAlertPolicyVersions.version)}, 0)::integer`
|
|
516
|
+
}).from(vulnerabilityAlertPolicyVersions).where(eq(vulnerabilityAlertPolicyVersions.tenant_id, input.tenantId));
|
|
517
|
+
const version = (latest?.version ?? 0) + 1;
|
|
518
|
+
await transaction2.update(vulnerabilityAlertPolicyVersions).set({ status: "superseded" }).where(and(eq(vulnerabilityAlertPolicyVersions.tenant_id, input.tenantId), eq(vulnerabilityAlertPolicyVersions.status, "active")));
|
|
519
|
+
await transaction2.insert(vulnerabilityAlertPolicyVersions).values({
|
|
520
|
+
activated_at: new Date(input.activatedAt),
|
|
521
|
+
activated_by: input.activatedBy,
|
|
522
|
+
configuration: encodedJsonb(configuration),
|
|
523
|
+
reason,
|
|
524
|
+
status: "active",
|
|
525
|
+
tenant_id: input.tenantId,
|
|
526
|
+
version
|
|
527
|
+
});
|
|
528
|
+
return {
|
|
529
|
+
activatedAt: input.activatedAt,
|
|
530
|
+
configuration,
|
|
531
|
+
reason,
|
|
532
|
+
tenantId: input.tenantId,
|
|
533
|
+
version
|
|
534
|
+
};
|
|
535
|
+
});
|
|
536
|
+
},
|
|
537
|
+
active: async () => {
|
|
538
|
+
const rows = await db.select({
|
|
539
|
+
configuration: vulnerabilityAlertPolicyVersions.configuration,
|
|
540
|
+
tenantId: vulnerabilityAlertPolicyVersions.tenant_id,
|
|
541
|
+
version: vulnerabilityAlertPolicyVersions.version
|
|
542
|
+
}).from(vulnerabilityAlertPolicyVersions).where(eq(vulnerabilityAlertPolicyVersions.status, "active"));
|
|
543
|
+
return rows.map((row) => ({
|
|
544
|
+
configuration: validateVulnerabilityAlertConfiguration2(row.configuration),
|
|
545
|
+
tenantId: row.tenantId,
|
|
546
|
+
version: row.version
|
|
547
|
+
}));
|
|
548
|
+
},
|
|
549
|
+
list: (requestedLimit) => db.select().from(vulnerabilityAlertPolicyVersions).orderBy(desc(vulnerabilityAlertPolicyVersions.activated_at)).limit(boundedLimit2(requestedLimit))
|
|
550
|
+
};
|
|
551
|
+
const observe = async ({
|
|
552
|
+
alert,
|
|
553
|
+
policy,
|
|
554
|
+
observedAt
|
|
555
|
+
}) => {
|
|
556
|
+
const at = observedAt ?? new Date().toISOString();
|
|
557
|
+
const configuration = validateVulnerabilityAlertConfiguration2(policy.configuration);
|
|
558
|
+
return db.transaction(async (transaction2) => {
|
|
559
|
+
const [existing] = await transaction2.select({
|
|
560
|
+
occurrenceCount: vulnerabilityAlertIncidents.occurrence_count,
|
|
561
|
+
status: vulnerabilityAlertIncidents.status
|
|
562
|
+
}).from(vulnerabilityAlertIncidents).where(eq(vulnerabilityAlertIncidents.alert_id, alert.id)).for("update").limit(1);
|
|
563
|
+
const reopened = existing?.status === "resolved";
|
|
564
|
+
const nextEscalationAt = new Date(new Date(at).getTime() + configuration.escalationAfterMs[alert.severity]);
|
|
565
|
+
await transaction2.insert(vulnerabilityAlertIncidents).values({
|
|
566
|
+
alert_id: alert.id,
|
|
567
|
+
asset_id: alert.assetId,
|
|
568
|
+
body: alert.body,
|
|
569
|
+
due_at: alert.dueAt ? new Date(alert.dueAt) : null,
|
|
570
|
+
finding_id: alert.findingId,
|
|
571
|
+
first_observed_at: new Date(alert.observedAt),
|
|
572
|
+
kind: alert.kind,
|
|
573
|
+
last_observed_at: new Date(alert.observedAt),
|
|
574
|
+
next_escalation_at: nextEscalationAt,
|
|
575
|
+
plan_id: alert.planId,
|
|
576
|
+
policy_version: policy.version,
|
|
577
|
+
severity: alert.severity,
|
|
578
|
+
source_id: alert.sourceId,
|
|
579
|
+
status: "open",
|
|
580
|
+
tenant_id: alert.tenantId,
|
|
581
|
+
title: alert.title,
|
|
582
|
+
value: encodedJsonb(alert)
|
|
583
|
+
}).onConflictDoUpdate({
|
|
584
|
+
set: {
|
|
585
|
+
asset_id: sql`excluded.asset_id`,
|
|
586
|
+
body: sql`excluded.body`,
|
|
587
|
+
due_at: sql`excluded.due_at`,
|
|
588
|
+
finding_id: sql`excluded.finding_id`,
|
|
589
|
+
last_observed_at: sql`excluded.last_observed_at`,
|
|
590
|
+
next_escalation_at: sql`CASE
|
|
591
|
+
WHEN ${vulnerabilityAlertIncidents.status} = 'resolved'
|
|
592
|
+
THEN excluded.next_escalation_at
|
|
593
|
+
WHEN ${vulnerabilityAlertIncidents.status} = 'open'
|
|
594
|
+
AND ${vulnerabilityAlertIncidents.policy_version}
|
|
595
|
+
IS DISTINCT FROM excluded.policy_version
|
|
596
|
+
THEN excluded.next_escalation_at
|
|
597
|
+
ELSE ${vulnerabilityAlertIncidents.next_escalation_at}
|
|
598
|
+
END`,
|
|
599
|
+
observation_count: sql`${vulnerabilityAlertIncidents.observation_count} + 1`,
|
|
600
|
+
occurrence_count: sql`CASE
|
|
601
|
+
WHEN ${vulnerabilityAlertIncidents.status} = 'resolved'
|
|
602
|
+
THEN ${vulnerabilityAlertIncidents.occurrence_count} + 1
|
|
603
|
+
ELSE ${vulnerabilityAlertIncidents.occurrence_count}
|
|
604
|
+
END`,
|
|
605
|
+
plan_id: sql`excluded.plan_id`,
|
|
606
|
+
policy_version: sql`excluded.policy_version`,
|
|
607
|
+
resolved_at: sql`CASE
|
|
608
|
+
WHEN ${vulnerabilityAlertIncidents.status} = 'resolved'
|
|
609
|
+
THEN null
|
|
610
|
+
ELSE ${vulnerabilityAlertIncidents.resolved_at}
|
|
611
|
+
END`,
|
|
612
|
+
severity: sql`excluded.severity`,
|
|
613
|
+
source_id: sql`excluded.source_id`,
|
|
614
|
+
status: sql`CASE
|
|
615
|
+
WHEN ${vulnerabilityAlertIncidents.status} = 'resolved'
|
|
616
|
+
THEN 'open'
|
|
617
|
+
ELSE ${vulnerabilityAlertIncidents.status}
|
|
618
|
+
END`,
|
|
619
|
+
tenant_id: sql`excluded.tenant_id`,
|
|
620
|
+
title: sql`excluded.title`,
|
|
621
|
+
updated_at: databaseNow,
|
|
622
|
+
value: sql`excluded.value`
|
|
623
|
+
},
|
|
624
|
+
target: vulnerabilityAlertIncidents.alert_id
|
|
625
|
+
});
|
|
626
|
+
if (!existing || reopened) {
|
|
627
|
+
await transaction2.insert(vulnerabilityAlertEvents).values({
|
|
628
|
+
alert_id: alert.id,
|
|
629
|
+
kind: "opened",
|
|
630
|
+
metadata: encodedJsonb({})
|
|
631
|
+
});
|
|
632
|
+
await queue(transaction2, alert, configuration, "opened", existing ? existing.occurrenceCount + 1 : 1);
|
|
633
|
+
}
|
|
634
|
+
return !existing ? "opened" : reopened ? "reopened" : "observed";
|
|
635
|
+
});
|
|
636
|
+
};
|
|
637
|
+
const alertIncidents = {
|
|
638
|
+
acknowledge: (input) => db.transaction(async (transaction2) => {
|
|
639
|
+
const [present] = await transaction2.select({ status: vulnerabilityAlertIncidents.status }).from(vulnerabilityAlertIncidents).where(eq(vulnerabilityAlertIncidents.alert_id, input.alertId)).for("update").limit(1);
|
|
640
|
+
if (!present)
|
|
641
|
+
throw new VulnerabilityAlertNotFoundError("Vulnerability alert not found");
|
|
642
|
+
if (present.status === "resolved")
|
|
643
|
+
throw new VulnerabilityAlertConflictError("Resolved vulnerability alerts cannot be acknowledged");
|
|
644
|
+
if (present.status === "acknowledged")
|
|
645
|
+
return false;
|
|
646
|
+
await transaction2.update(vulnerabilityAlertIncidents).set({
|
|
647
|
+
acknowledged_at: new Date(input.acknowledgedAt),
|
|
648
|
+
acknowledged_by: input.acknowledgedBy,
|
|
649
|
+
next_escalation_at: null,
|
|
650
|
+
status: "acknowledged",
|
|
651
|
+
updated_at: new Date(input.acknowledgedAt)
|
|
652
|
+
}).where(eq(vulnerabilityAlertIncidents.alert_id, input.alertId));
|
|
653
|
+
await transaction2.insert(vulnerabilityAlertEvents).values({
|
|
654
|
+
actor_id: input.acknowledgedBy,
|
|
655
|
+
alert_id: input.alertId,
|
|
656
|
+
kind: "acknowledged",
|
|
657
|
+
metadata: encodedJsonb({})
|
|
658
|
+
});
|
|
659
|
+
return true;
|
|
660
|
+
}),
|
|
661
|
+
claimDeliveries: (input = {}) => db.transaction(async (transaction2) => {
|
|
662
|
+
const leaseMs = input.leaseMs ?? 300000;
|
|
663
|
+
const queryLimit = boundedLimit2(input.limit ?? 100);
|
|
664
|
+
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)));
|
|
665
|
+
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, [
|
|
666
|
+
...input.tenantIds
|
|
667
|
+
]) : undefined)).orderBy(asc(vulnerabilityAlertDeliveries.created_at)).limit(queryLimit).for("update", {
|
|
668
|
+
of: vulnerabilityAlertDeliveries,
|
|
669
|
+
skipLocked: true
|
|
670
|
+
});
|
|
671
|
+
const ids = candidates.map(({ id }) => id);
|
|
672
|
+
if (ids.length === 0)
|
|
673
|
+
return [];
|
|
674
|
+
await transaction2.update(vulnerabilityAlertDeliveries).set({
|
|
675
|
+
attempt_count: sql`${vulnerabilityAlertDeliveries.attempt_count} + 1`,
|
|
676
|
+
lease_expires_at: sql`now() + ${leaseMs} * interval '1 millisecond'`,
|
|
677
|
+
state: "delivering",
|
|
678
|
+
updated_at: databaseNow
|
|
679
|
+
}).where(inArray(vulnerabilityAlertDeliveries.id, ids));
|
|
680
|
+
return transaction2.select({
|
|
681
|
+
alert_id: vulnerabilityAlertDeliveries.alert_id,
|
|
682
|
+
asset_id: vulnerabilityAlertIncidents.asset_id,
|
|
683
|
+
attempt_count: vulnerabilityAlertDeliveries.attempt_count,
|
|
684
|
+
audience: vulnerabilityAlertDeliveries.audience,
|
|
685
|
+
body: vulnerabilityAlertIncidents.body,
|
|
686
|
+
created_at: vulnerabilityAlertDeliveries.created_at,
|
|
687
|
+
delivered_at: vulnerabilityAlertDeliveries.delivered_at,
|
|
688
|
+
id: vulnerabilityAlertDeliveries.id,
|
|
689
|
+
idempotency_key: vulnerabilityAlertDeliveries.idempotency_key,
|
|
690
|
+
kind: vulnerabilityAlertDeliveries.kind,
|
|
691
|
+
last_error: vulnerabilityAlertDeliveries.last_error,
|
|
692
|
+
lease_expires_at: vulnerabilityAlertDeliveries.lease_expires_at,
|
|
693
|
+
next_attempt_at: vulnerabilityAlertDeliveries.next_attempt_at,
|
|
694
|
+
severity: vulnerabilityAlertIncidents.severity,
|
|
695
|
+
state: vulnerabilityAlertDeliveries.state,
|
|
696
|
+
tenant_id: vulnerabilityAlertIncidents.tenant_id,
|
|
697
|
+
title: vulnerabilityAlertIncidents.title,
|
|
698
|
+
updated_at: vulnerabilityAlertDeliveries.updated_at
|
|
699
|
+
}).from(vulnerabilityAlertDeliveries).innerJoin(vulnerabilityAlertIncidents, eq(vulnerabilityAlertIncidents.alert_id, vulnerabilityAlertDeliveries.alert_id)).where(inArray(vulnerabilityAlertDeliveries.id, ids));
|
|
700
|
+
}),
|
|
701
|
+
completeDelivery: (input) => db.transaction(async (transaction2) => {
|
|
702
|
+
const updated = await transaction2.update(vulnerabilityAlertDeliveries).set({
|
|
703
|
+
delivered_at: databaseNow,
|
|
704
|
+
last_error: null,
|
|
705
|
+
lease_expires_at: null,
|
|
706
|
+
state: "delivered",
|
|
707
|
+
updated_at: databaseNow
|
|
708
|
+
}).where(and(eq(vulnerabilityAlertDeliveries.id, input.deliveryId), eq(vulnerabilityAlertDeliveries.state, "delivering"))).returning({ id: vulnerabilityAlertDeliveries.id });
|
|
709
|
+
if (updated.length === 0)
|
|
710
|
+
return false;
|
|
711
|
+
await transaction2.insert(vulnerabilityAlertEvents).values({
|
|
712
|
+
alert_id: input.alertId,
|
|
713
|
+
kind: "delivered",
|
|
714
|
+
metadata: encodedJsonb({
|
|
715
|
+
audience: input.audience,
|
|
716
|
+
kind: input.kind
|
|
717
|
+
})
|
|
718
|
+
});
|
|
719
|
+
return true;
|
|
720
|
+
}),
|
|
721
|
+
deliveries: (requestedLimit) => db.select().from(vulnerabilityAlertDeliveries).orderBy(desc(vulnerabilityAlertDeliveries.created_at)).limit(boundedLimit2(requestedLimit)),
|
|
722
|
+
events: (requestedLimit) => db.select().from(vulnerabilityAlertEvents).orderBy(desc(vulnerabilityAlertEvents.created_at)).limit(boundedLimit2(requestedLimit)),
|
|
723
|
+
failDelivery: (input) => db.transaction(async (transaction2) => {
|
|
724
|
+
const updated = await transaction2.update(vulnerabilityAlertDeliveries).set({
|
|
725
|
+
last_error: input.error,
|
|
726
|
+
lease_expires_at: null,
|
|
727
|
+
next_attempt_at: new Date(input.retryAt),
|
|
728
|
+
state: "failed",
|
|
729
|
+
updated_at: databaseNow
|
|
730
|
+
}).where(and(eq(vulnerabilityAlertDeliveries.id, input.deliveryId), eq(vulnerabilityAlertDeliveries.state, "delivering"))).returning({ id: vulnerabilityAlertDeliveries.id });
|
|
731
|
+
if (updated.length === 0)
|
|
732
|
+
return false;
|
|
733
|
+
await transaction2.insert(vulnerabilityAlertEvents).values({
|
|
734
|
+
alert_id: input.alertId,
|
|
735
|
+
kind: "delivery_failed",
|
|
736
|
+
metadata: encodedJsonb({ error: input.error, kind: input.kind })
|
|
737
|
+
});
|
|
738
|
+
return true;
|
|
739
|
+
}),
|
|
740
|
+
incidents: (requestedLimit) => db.select().from(vulnerabilityAlertIncidents).orderBy(desc(vulnerabilityAlertIncidents.last_observed_at)).limit(boundedLimit2(requestedLimit)),
|
|
741
|
+
observe,
|
|
742
|
+
processEscalations: async ({ fallbackPolicy, policies, tenantIds }) => {
|
|
743
|
+
const due = await db.select({
|
|
744
|
+
alertId: vulnerabilityAlertIncidents.alert_id,
|
|
745
|
+
assetId: vulnerabilityAlertIncidents.asset_id,
|
|
746
|
+
occurrenceCount: vulnerabilityAlertIncidents.occurrence_count,
|
|
747
|
+
severity: vulnerabilityAlertIncidents.severity,
|
|
748
|
+
tenantId: vulnerabilityAlertIncidents.tenant_id
|
|
749
|
+
}).from(vulnerabilityAlertIncidents).where(and(eq(vulnerabilityAlertIncidents.status, "open"), lte(vulnerabilityAlertIncidents.next_escalation_at, databaseNow), tenantIds && tenantIds.length > 0 ? inArray(vulnerabilityAlertIncidents.tenant_id, [...tenantIds]) : undefined));
|
|
750
|
+
let processed = 0;
|
|
751
|
+
for (const incident of due) {
|
|
752
|
+
const policy = policies.get(incident.tenantId) ?? fallbackPolicy;
|
|
753
|
+
if (!policy)
|
|
754
|
+
continue;
|
|
755
|
+
const changed = await db.transaction(async (transaction2) => {
|
|
756
|
+
const claimed = await transaction2.update(vulnerabilityAlertIncidents).set({
|
|
757
|
+
next_escalation_at: null,
|
|
758
|
+
updated_at: databaseNow
|
|
759
|
+
}).where(and(eq(vulnerabilityAlertIncidents.alert_id, incident.alertId), eq(vulnerabilityAlertIncidents.status, "open"), lte(vulnerabilityAlertIncidents.next_escalation_at, databaseNow))).returning({ id: vulnerabilityAlertIncidents.alert_id });
|
|
760
|
+
if (claimed.length === 0)
|
|
761
|
+
return false;
|
|
762
|
+
await transaction2.insert(vulnerabilityAlertEvents).values({
|
|
763
|
+
alert_id: incident.alertId,
|
|
764
|
+
kind: "escalated",
|
|
765
|
+
metadata: encodedJsonb({})
|
|
766
|
+
});
|
|
767
|
+
await queue(transaction2, {
|
|
768
|
+
assetId: incident.assetId,
|
|
769
|
+
id: incident.alertId,
|
|
770
|
+
severity: incident.severity
|
|
771
|
+
}, policy.configuration, "escalated", incident.occurrenceCount);
|
|
772
|
+
return true;
|
|
773
|
+
});
|
|
774
|
+
if (changed)
|
|
775
|
+
processed += 1;
|
|
776
|
+
}
|
|
777
|
+
return processed;
|
|
778
|
+
},
|
|
779
|
+
resolveInactive: async ({
|
|
780
|
+
activeAlertIds,
|
|
781
|
+
fallbackPolicy,
|
|
782
|
+
policies,
|
|
783
|
+
resolvedAt,
|
|
784
|
+
tenantIds
|
|
785
|
+
}) => {
|
|
786
|
+
const open = await db.select({
|
|
787
|
+
alertId: vulnerabilityAlertIncidents.alert_id,
|
|
788
|
+
assetId: vulnerabilityAlertIncidents.asset_id,
|
|
789
|
+
occurrenceCount: vulnerabilityAlertIncidents.occurrence_count,
|
|
790
|
+
severity: vulnerabilityAlertIncidents.severity,
|
|
791
|
+
tenantId: vulnerabilityAlertIncidents.tenant_id
|
|
792
|
+
}).from(vulnerabilityAlertIncidents).where(and(inArray(vulnerabilityAlertIncidents.status, [
|
|
793
|
+
"open",
|
|
794
|
+
"acknowledged"
|
|
795
|
+
]), tenantIds && tenantIds.length > 0 ? inArray(vulnerabilityAlertIncidents.tenant_id, [...tenantIds]) : undefined));
|
|
796
|
+
const at = new Date(resolvedAt ?? new Date().toISOString());
|
|
797
|
+
let processed = 0;
|
|
798
|
+
for (const incident of open) {
|
|
799
|
+
if (activeAlertIds.has(incident.alertId))
|
|
800
|
+
continue;
|
|
801
|
+
const policy = policies.get(incident.tenantId) ?? fallbackPolicy;
|
|
802
|
+
if (!policy)
|
|
803
|
+
continue;
|
|
804
|
+
const changed = await db.transaction(async (transaction2) => {
|
|
805
|
+
const resolved = await transaction2.update(vulnerabilityAlertIncidents).set({
|
|
806
|
+
next_escalation_at: null,
|
|
807
|
+
resolved_at: at,
|
|
808
|
+
status: "resolved",
|
|
809
|
+
updated_at: databaseNow
|
|
810
|
+
}).where(and(eq(vulnerabilityAlertIncidents.alert_id, incident.alertId), inArray(vulnerabilityAlertIncidents.status, [
|
|
811
|
+
"open",
|
|
812
|
+
"acknowledged"
|
|
813
|
+
]))).returning({ id: vulnerabilityAlertIncidents.alert_id });
|
|
814
|
+
if (resolved.length === 0)
|
|
815
|
+
return false;
|
|
816
|
+
await transaction2.insert(vulnerabilityAlertEvents).values({
|
|
817
|
+
alert_id: incident.alertId,
|
|
818
|
+
kind: "resolved",
|
|
819
|
+
metadata: encodedJsonb({})
|
|
820
|
+
});
|
|
821
|
+
await queue(transaction2, {
|
|
822
|
+
assetId: incident.assetId,
|
|
823
|
+
id: incident.alertId,
|
|
824
|
+
severity: incident.severity
|
|
825
|
+
}, policy.configuration, "resolved", incident.occurrenceCount);
|
|
826
|
+
return true;
|
|
827
|
+
});
|
|
828
|
+
if (changed)
|
|
829
|
+
processed += 1;
|
|
830
|
+
}
|
|
831
|
+
return processed;
|
|
832
|
+
}
|
|
833
|
+
};
|
|
834
|
+
return { alertIncidents, alertPolicies };
|
|
835
|
+
};
|
|
836
|
+
|
|
837
|
+
// src/coreDrizzle.ts
|
|
838
|
+
var encodedJsonb2 = (value) => sql2`${JSON.stringify(value)}::text::jsonb`;
|
|
839
|
+
var databaseNow2 = sql2`now()`;
|
|
840
|
+
var requiredText = (value, label) => {
|
|
841
|
+
const normalized = value.trim();
|
|
842
|
+
if (normalized.length === 0)
|
|
843
|
+
throw new Error(`${label} is required`);
|
|
844
|
+
return normalized;
|
|
845
|
+
};
|
|
846
|
+
var boundedLimit3 = (value, fallback = 100) => {
|
|
847
|
+
const normalized = value ?? fallback;
|
|
848
|
+
if (!Number.isInteger(normalized) || normalized < 1 || normalized > 1000)
|
|
849
|
+
throw new Error("Postgres query limit must be an integer from 1 through 1000");
|
|
850
|
+
return normalized;
|
|
851
|
+
};
|
|
852
|
+
var valid = (schema, value, label) => {
|
|
853
|
+
if (!Value.Check(schema, value))
|
|
854
|
+
throw new Error(`${label} is invalid`);
|
|
855
|
+
return value;
|
|
856
|
+
};
|
|
857
|
+
var iso = (value) => value.toISOString();
|
|
858
|
+
var vulnerabilityFeedSnapshots = pgTable2("vulnerability_feed_snapshots", {
|
|
859
|
+
cursor: jsonb().$type().notNull(),
|
|
860
|
+
feed_id: text2().primaryKey(),
|
|
861
|
+
feed_name: text2().notNull(),
|
|
862
|
+
feed_url: text2().notNull(),
|
|
863
|
+
fetched_at: timestamp2({ mode: "date", withTimezone: true }).notNull(),
|
|
864
|
+
revision: text2(),
|
|
865
|
+
updated_at: timestamp2({ mode: "date", withTimezone: true }).notNull().defaultNow()
|
|
866
|
+
});
|
|
867
|
+
var vulnerabilityFeedRecords = pgTable2("vulnerability_feed_records", {
|
|
868
|
+
feed_id: text2().notNull().references(() => vulnerabilityFeedSnapshots.feed_id, {
|
|
869
|
+
onDelete: "cascade"
|
|
870
|
+
}),
|
|
871
|
+
modified_at: timestamp2({ mode: "date", withTimezone: true }).notNull(),
|
|
872
|
+
record_id: text2().notNull(),
|
|
873
|
+
value: jsonb().notNull()
|
|
874
|
+
}, (table) => [
|
|
875
|
+
primaryKey2({ columns: [table.feed_id, table.record_id] }),
|
|
876
|
+
index2("vulnerability_feed_records_modified_idx").on(table.feed_id, table.modified_at)
|
|
877
|
+
]);
|
|
878
|
+
var vulnerabilityFeedSyncRuns = pgTable2("vulnerability_feed_sync_runs", {
|
|
879
|
+
completed_at: timestamp2({ mode: "date", withTimezone: true }).notNull(),
|
|
880
|
+
error: text2(),
|
|
881
|
+
feed_id: text2().notNull(),
|
|
882
|
+
id: text2().primaryKey(),
|
|
883
|
+
records: integer2().notNull(),
|
|
884
|
+
revision: text2(),
|
|
885
|
+
started_at: timestamp2({ mode: "date", withTimezone: true }).notNull(),
|
|
886
|
+
status: text2().$type().notNull()
|
|
887
|
+
}, (table) => [
|
|
888
|
+
check("vulnerability_feed_sync_runs_records_check", sql2`${table.records} >= 0`),
|
|
889
|
+
check("vulnerability_feed_sync_runs_status_check", sql2`${table.status} IN ('failed', 'not_modified', 'stale', 'updated')`),
|
|
890
|
+
index2("vulnerability_feed_sync_runs_feed_started_idx").on(table.feed_id, table.started_at),
|
|
891
|
+
index2("vulnerability_feed_sync_runs_status_started_idx").on(table.status, table.started_at)
|
|
892
|
+
]);
|
|
893
|
+
var vulnerabilityFindings = pgTable2("vulnerability_findings", {
|
|
894
|
+
asset_id: text2().notNull(),
|
|
895
|
+
component_id: text2().notNull(),
|
|
896
|
+
finding_id: text2().notNull(),
|
|
897
|
+
first_seen_at: timestamp2({
|
|
898
|
+
mode: "date",
|
|
899
|
+
withTimezone: true
|
|
900
|
+
}).notNull(),
|
|
901
|
+
last_seen_at: timestamp2({ mode: "date", withTimezone: true }).notNull(),
|
|
902
|
+
severity: text2().notNull(),
|
|
903
|
+
status: text2().notNull(),
|
|
904
|
+
tenant_id: text2().notNull(),
|
|
905
|
+
updated_at: timestamp2({ mode: "date", withTimezone: true }).notNull().defaultNow(),
|
|
906
|
+
value: jsonb().$type().notNull()
|
|
907
|
+
}, (table) => [
|
|
908
|
+
primaryKey2({ columns: [table.tenant_id, table.finding_id] }),
|
|
909
|
+
index2("vulnerability_findings_tenant_status_idx").on(table.tenant_id, table.status, table.last_seen_at),
|
|
910
|
+
index2("vulnerability_findings_tenant_severity_idx").on(table.tenant_id, table.severity, table.last_seen_at),
|
|
911
|
+
index2("vulnerability_findings_tenant_asset_idx").on(table.tenant_id, table.asset_id, table.last_seen_at)
|
|
912
|
+
]);
|
|
913
|
+
var vulnerabilityObservations = pgTable2("vulnerability_observations", {
|
|
914
|
+
asset_id: text2().notNull(),
|
|
915
|
+
component_id: text2().notNull(),
|
|
916
|
+
observation_id: text2().notNull(),
|
|
917
|
+
observed_at: timestamp2({ mode: "date", withTimezone: true }).notNull(),
|
|
918
|
+
tenant_id: text2().notNull(),
|
|
919
|
+
updated_at: timestamp2({ mode: "date", withTimezone: true }).notNull().defaultNow(),
|
|
920
|
+
value: jsonb().$type().notNull()
|
|
921
|
+
}, (table) => [
|
|
922
|
+
primaryKey2({ columns: [table.tenant_id, table.observation_id] }),
|
|
923
|
+
index2("vulnerability_observations_tenant_asset_idx").on(table.tenant_id, table.asset_id, table.observed_at),
|
|
924
|
+
index2("vulnerability_observations_tenant_component_idx").on(table.tenant_id, table.component_id, table.observed_at)
|
|
925
|
+
]);
|
|
926
|
+
var vulnerabilityRiskAssessments = pgTable2("vulnerability_risk_assessments", {
|
|
927
|
+
assessed_at: timestamp2({ mode: "date", withTimezone: true }).notNull(),
|
|
928
|
+
finding_id: text2().notNull(),
|
|
929
|
+
priority: text2().notNull(),
|
|
930
|
+
remediate_by: timestamp2({ mode: "date", withTimezone: true }),
|
|
931
|
+
tenant_id: text2().notNull(),
|
|
932
|
+
updated_at: timestamp2({ mode: "date", withTimezone: true }).notNull().defaultNow(),
|
|
933
|
+
value: jsonb().$type().notNull()
|
|
934
|
+
}, (table) => [
|
|
935
|
+
primaryKey2({ columns: [table.tenant_id, table.finding_id] }),
|
|
936
|
+
index2("vulnerability_risk_assessments_tenant_priority_idx").on(table.tenant_id, table.priority, table.assessed_at),
|
|
937
|
+
index2("vulnerability_risk_assessments_tenant_due_idx").on(table.tenant_id, table.remediate_by).where(sql2`${table.remediate_by} IS NOT NULL`)
|
|
938
|
+
]);
|
|
939
|
+
var vulnerabilityRemediationPlans = pgTable2("vulnerability_remediation_plans", {
|
|
940
|
+
created_at: timestamp2({ mode: "date", withTimezone: true }).notNull(),
|
|
941
|
+
plan_id: text2().notNull(),
|
|
942
|
+
status: text2().notNull(),
|
|
943
|
+
tenant_id: text2().notNull(),
|
|
944
|
+
updated_at: timestamp2({ mode: "date", withTimezone: true }).notNull().defaultNow(),
|
|
945
|
+
value: jsonb().$type().notNull()
|
|
946
|
+
}, (table) => [
|
|
947
|
+
primaryKey2({ columns: [table.tenant_id, table.plan_id] }),
|
|
948
|
+
index2("vulnerability_remediation_plans_tenant_status_idx").on(table.tenant_id, table.status, table.created_at)
|
|
949
|
+
]);
|
|
950
|
+
var vulnerabilityRemediationExecutions = pgTable2("vulnerability_remediation_executions", {
|
|
951
|
+
completed_at: timestamp2({ mode: "date", withTimezone: true }),
|
|
952
|
+
execution_id: text2().notNull(),
|
|
953
|
+
plan_id: text2().notNull(),
|
|
954
|
+
started_at: timestamp2({ mode: "date", withTimezone: true }).notNull(),
|
|
955
|
+
status: text2().notNull(),
|
|
956
|
+
tenant_id: text2().notNull(),
|
|
957
|
+
updated_at: timestamp2({ mode: "date", withTimezone: true }).notNull().defaultNow(),
|
|
958
|
+
value: jsonb().$type().notNull()
|
|
959
|
+
}, (table) => [
|
|
960
|
+
primaryKey2({ columns: [table.tenant_id, table.execution_id] }),
|
|
961
|
+
index2("vulnerability_remediation_executions_tenant_plan_idx").on(table.tenant_id, table.plan_id, table.started_at)
|
|
962
|
+
]);
|
|
963
|
+
var vulnerabilityRemediationVerifications = pgTable2("vulnerability_remediation_verifications", {
|
|
964
|
+
execution_id: text2().notNull(),
|
|
965
|
+
observed_at: timestamp2({ mode: "date", withTimezone: true }).notNull(),
|
|
966
|
+
plan_id: text2().notNull(),
|
|
967
|
+
status: text2().notNull(),
|
|
968
|
+
tenant_id: text2().notNull(),
|
|
969
|
+
updated_at: timestamp2({ mode: "date", withTimezone: true }).notNull().defaultNow(),
|
|
970
|
+
value: jsonb().$type().notNull(),
|
|
971
|
+
verification_id: text2().notNull()
|
|
972
|
+
}, (table) => [
|
|
973
|
+
primaryKey2({ columns: [table.tenant_id, table.verification_id] }),
|
|
974
|
+
index2("vulnerability_remediation_verifications_tenant_execution_idx").on(table.tenant_id, table.execution_id, table.observed_at)
|
|
975
|
+
]);
|
|
976
|
+
var vulnerabilityVexDecisions = pgTable2("vulnerability_vex_decisions", {
|
|
977
|
+
created_at: timestamp2({ mode: "date", withTimezone: true }).notNull(),
|
|
978
|
+
decision_id: text2().notNull(),
|
|
979
|
+
expires_at: timestamp2({ mode: "date", withTimezone: true }),
|
|
980
|
+
product_id: text2().notNull(),
|
|
981
|
+
status: text2().notNull(),
|
|
982
|
+
tenant_id: text2().notNull(),
|
|
983
|
+
updated_at: timestamp2({ mode: "date", withTimezone: true }).notNull().defaultNow(),
|
|
984
|
+
value: jsonb().$type().notNull(),
|
|
985
|
+
vulnerability_id: text2().notNull()
|
|
986
|
+
}, (table) => [
|
|
987
|
+
primaryKey2({ columns: [table.tenant_id, table.decision_id] }),
|
|
988
|
+
index2("vulnerability_vex_decisions_tenant_product_idx").on(table.tenant_id, table.product_id, table.created_at),
|
|
989
|
+
index2("vulnerability_vex_decisions_tenant_vulnerability_idx").on(table.tenant_id, table.vulnerability_id, table.created_at)
|
|
990
|
+
]);
|
|
991
|
+
var vulnerabilityVexApplications = pgTable2("vulnerability_vex_applications", {
|
|
992
|
+
applied_at: timestamp2({ mode: "date", withTimezone: true }).notNull(),
|
|
993
|
+
decision_id: text2().notNull(),
|
|
994
|
+
ended_at: timestamp2({ mode: "date", withTimezone: true }),
|
|
995
|
+
finding_id: text2().notNull(),
|
|
996
|
+
tenant_id: text2().notNull(),
|
|
997
|
+
updated_at: timestamp2({ mode: "date", withTimezone: true }).notNull().defaultNow(),
|
|
998
|
+
value: jsonb().$type().notNull()
|
|
999
|
+
}, (table) => [
|
|
1000
|
+
primaryKey2({ columns: [table.tenant_id, table.finding_id] }),
|
|
1001
|
+
index2("vulnerability_vex_applications_tenant_decision_idx").on(table.tenant_id, table.decision_id, table.applied_at)
|
|
1002
|
+
]);
|
|
1003
|
+
var vulnerabilityFeedLeases = pgTable2("vulnerability_feed_leases", {
|
|
1004
|
+
expires_at: timestamp2({ mode: "date", withTimezone: true }).notNull(),
|
|
1005
|
+
feed_id: text2().primaryKey(),
|
|
1006
|
+
owner_id: text2().notNull(),
|
|
1007
|
+
updated_at: timestamp2({ mode: "date", withTimezone: true }).notNull().defaultNow()
|
|
1008
|
+
});
|
|
1009
|
+
var vulnerabilityCoreDrizzleSchema = {
|
|
1010
|
+
vulnerabilityFeedLeases,
|
|
1011
|
+
vulnerabilityFeedRecords,
|
|
1012
|
+
vulnerabilityFeedSnapshots,
|
|
1013
|
+
vulnerabilityFeedSyncRuns,
|
|
1014
|
+
vulnerabilityFindings,
|
|
1015
|
+
vulnerabilityObservations,
|
|
1016
|
+
vulnerabilityRemediationExecutions,
|
|
1017
|
+
vulnerabilityRemediationPlans,
|
|
1018
|
+
vulnerabilityRemediationVerifications,
|
|
1019
|
+
vulnerabilityRiskAssessments,
|
|
1020
|
+
vulnerabilityVexApplications,
|
|
1021
|
+
vulnerabilityVexDecisions
|
|
1022
|
+
};
|
|
1023
|
+
var createDrizzleVulnerabilityStore = (db) => {
|
|
1024
|
+
const alertStores = createDrizzleVulnerabilityAlertStores(db);
|
|
1025
|
+
const snapshots = () => ({
|
|
1026
|
+
load: async (feedId) => {
|
|
1027
|
+
const id = requiredText(feedId, "Feed id");
|
|
1028
|
+
const [snapshot] = await db.select().from(vulnerabilityFeedSnapshots).where(eq2(vulnerabilityFeedSnapshots.feed_id, id)).limit(1);
|
|
1029
|
+
if (!snapshot)
|
|
1030
|
+
return null;
|
|
1031
|
+
const records = await db.select().from(vulnerabilityFeedRecords).where(eq2(vulnerabilityFeedRecords.feed_id, id)).orderBy(vulnerabilityFeedRecords.record_id);
|
|
1032
|
+
return {
|
|
1033
|
+
cursor: snapshot.cursor,
|
|
1034
|
+
feed: {
|
|
1035
|
+
id: snapshot.feed_id,
|
|
1036
|
+
name: snapshot.feed_name,
|
|
1037
|
+
url: snapshot.feed_url
|
|
1038
|
+
},
|
|
1039
|
+
fetchedAt: iso(snapshot.fetched_at),
|
|
1040
|
+
records: records.map((record) => ({
|
|
1041
|
+
id: record.record_id,
|
|
1042
|
+
modifiedAt: iso(record.modified_at),
|
|
1043
|
+
value: record.value
|
|
1044
|
+
})),
|
|
1045
|
+
revision: snapshot.revision
|
|
1046
|
+
};
|
|
1047
|
+
},
|
|
1048
|
+
save: async (snapshot) => {
|
|
1049
|
+
const feedId = requiredText(snapshot.feed.id, "Feed id");
|
|
1050
|
+
await db.transaction(async (transaction2) => {
|
|
1051
|
+
await transaction2.insert(vulnerabilityFeedSnapshots).values({
|
|
1052
|
+
cursor: encodedJsonb2(snapshot.cursor),
|
|
1053
|
+
feed_id: feedId,
|
|
1054
|
+
feed_name: requiredText(snapshot.feed.name, "Feed name"),
|
|
1055
|
+
feed_url: requiredText(snapshot.feed.url, "Feed URL"),
|
|
1056
|
+
fetched_at: new Date(snapshot.fetchedAt),
|
|
1057
|
+
revision: snapshot.revision,
|
|
1058
|
+
updated_at: databaseNow2
|
|
1059
|
+
}).onConflictDoUpdate({
|
|
1060
|
+
set: {
|
|
1061
|
+
cursor: encodedJsonb2(snapshot.cursor),
|
|
1062
|
+
feed_name: requiredText(snapshot.feed.name, "Feed name"),
|
|
1063
|
+
feed_url: requiredText(snapshot.feed.url, "Feed URL"),
|
|
1064
|
+
fetched_at: new Date(snapshot.fetchedAt),
|
|
1065
|
+
revision: snapshot.revision,
|
|
1066
|
+
updated_at: databaseNow2
|
|
1067
|
+
},
|
|
1068
|
+
target: vulnerabilityFeedSnapshots.feed_id
|
|
1069
|
+
});
|
|
1070
|
+
const recordIds = snapshot.records.map((record) => requiredText(record.id, "Feed record id"));
|
|
1071
|
+
await transaction2.delete(vulnerabilityFeedRecords).where(and2(eq2(vulnerabilityFeedRecords.feed_id, feedId), recordIds.length === 0 ? undefined : notInArray(vulnerabilityFeedRecords.record_id, recordIds)));
|
|
1072
|
+
if (snapshot.records.length > 0)
|
|
1073
|
+
await transaction2.insert(vulnerabilityFeedRecords).values(snapshot.records.map((record) => ({
|
|
1074
|
+
feed_id: feedId,
|
|
1075
|
+
modified_at: new Date(record.modifiedAt),
|
|
1076
|
+
record_id: requiredText(record.id, "Feed record id"),
|
|
1077
|
+
value: encodedJsonb2(record.value)
|
|
1078
|
+
}))).onConflictDoUpdate({
|
|
1079
|
+
set: {
|
|
1080
|
+
modified_at: sql2`excluded.modified_at`,
|
|
1081
|
+
value: sql2`excluded.value`
|
|
1082
|
+
},
|
|
1083
|
+
target: [
|
|
1084
|
+
vulnerabilityFeedRecords.feed_id,
|
|
1085
|
+
vulnerabilityFeedRecords.record_id
|
|
1086
|
+
]
|
|
1087
|
+
});
|
|
1088
|
+
});
|
|
1089
|
+
}
|
|
1090
|
+
});
|
|
1091
|
+
const syncRuns = {
|
|
1092
|
+
append: async (run) => {
|
|
1093
|
+
if (!Number.isInteger(run.records) || run.records < 0)
|
|
1094
|
+
throw new Error("Feed sync records must be a non-negative integer");
|
|
1095
|
+
await db.insert(vulnerabilityFeedSyncRuns).values({
|
|
1096
|
+
completed_at: new Date(run.completedAt),
|
|
1097
|
+
error: run.error,
|
|
1098
|
+
feed_id: requiredText(run.feedId, "Feed sync feed id"),
|
|
1099
|
+
id: requiredText(run.id, "Feed sync run id"),
|
|
1100
|
+
records: run.records,
|
|
1101
|
+
revision: run.revision,
|
|
1102
|
+
started_at: new Date(run.startedAt),
|
|
1103
|
+
status: run.status
|
|
1104
|
+
}).onConflictDoUpdate({
|
|
1105
|
+
set: {
|
|
1106
|
+
completed_at: new Date(run.completedAt),
|
|
1107
|
+
error: run.error,
|
|
1108
|
+
feed_id: requiredText(run.feedId, "Feed sync feed id"),
|
|
1109
|
+
records: run.records,
|
|
1110
|
+
revision: run.revision,
|
|
1111
|
+
started_at: new Date(run.startedAt),
|
|
1112
|
+
status: run.status
|
|
1113
|
+
},
|
|
1114
|
+
target: vulnerabilityFeedSyncRuns.id
|
|
1115
|
+
});
|
|
1116
|
+
},
|
|
1117
|
+
list: async (filter = {}) => {
|
|
1118
|
+
const rows = await db.select().from(vulnerabilityFeedSyncRuns).where(and2(filter.feedId ? eq2(vulnerabilityFeedSyncRuns.feed_id, filter.feedId.trim()) : undefined, filter.status ? eq2(vulnerabilityFeedSyncRuns.status, filter.status) : undefined)).orderBy(desc2(vulnerabilityFeedSyncRuns.started_at), desc2(vulnerabilityFeedSyncRuns.id)).limit(boundedLimit3(filter.limit));
|
|
1119
|
+
return rows.map((row) => ({
|
|
1120
|
+
completedAt: iso(row.completed_at),
|
|
1121
|
+
error: row.error,
|
|
1122
|
+
feedId: row.feed_id,
|
|
1123
|
+
id: row.id,
|
|
1124
|
+
records: row.records,
|
|
1125
|
+
revision: row.revision,
|
|
1126
|
+
startedAt: iso(row.started_at),
|
|
1127
|
+
status: row.status
|
|
1128
|
+
}));
|
|
1129
|
+
}
|
|
1130
|
+
};
|
|
1131
|
+
const saveFindings = async (findings2) => {
|
|
1132
|
+
if (findings2.length === 0)
|
|
1133
|
+
return;
|
|
1134
|
+
for (const finding of findings2)
|
|
1135
|
+
valid(ManagedVulnerabilityFindingSchema, finding, `Managed finding ${finding.id}`);
|
|
1136
|
+
await db.insert(vulnerabilityFindings).values(findings2.map((finding) => ({
|
|
1137
|
+
asset_id: finding.assetId,
|
|
1138
|
+
component_id: finding.componentId,
|
|
1139
|
+
finding_id: finding.id,
|
|
1140
|
+
first_seen_at: new Date(finding.firstSeenAt),
|
|
1141
|
+
last_seen_at: new Date(finding.lastSeenAt),
|
|
1142
|
+
severity: finding.severity,
|
|
1143
|
+
status: finding.status,
|
|
1144
|
+
tenant_id: finding.tenantId,
|
|
1145
|
+
value: encodedJsonb2(finding)
|
|
1146
|
+
}))).onConflictDoUpdate({
|
|
1147
|
+
set: {
|
|
1148
|
+
asset_id: sql2`excluded.asset_id`,
|
|
1149
|
+
component_id: sql2`excluded.component_id`,
|
|
1150
|
+
first_seen_at: sql2`least(${vulnerabilityFindings.first_seen_at}, excluded.first_seen_at)`,
|
|
1151
|
+
last_seen_at: sql2`greatest(${vulnerabilityFindings.last_seen_at}, excluded.last_seen_at)`,
|
|
1152
|
+
severity: sql2`excluded.severity`,
|
|
1153
|
+
status: sql2`excluded.status`,
|
|
1154
|
+
updated_at: databaseNow2,
|
|
1155
|
+
value: sql2`excluded.value`
|
|
1156
|
+
},
|
|
1157
|
+
target: [
|
|
1158
|
+
vulnerabilityFindings.tenant_id,
|
|
1159
|
+
vulnerabilityFindings.finding_id
|
|
1160
|
+
]
|
|
1161
|
+
});
|
|
1162
|
+
};
|
|
1163
|
+
const findings = {
|
|
1164
|
+
get: async (tenantId, findingId) => {
|
|
1165
|
+
const [row] = await db.select({ value: vulnerabilityFindings.value }).from(vulnerabilityFindings).where(and2(eq2(vulnerabilityFindings.tenant_id, requiredText(tenantId, "Tenant id")), eq2(vulnerabilityFindings.finding_id, requiredText(findingId, "Finding id")))).limit(1);
|
|
1166
|
+
return row ? valid(ManagedVulnerabilityFindingSchema, row.value, "Stored managed finding") : null;
|
|
1167
|
+
},
|
|
1168
|
+
list: async (filter) => {
|
|
1169
|
+
const rows = await db.select({ value: vulnerabilityFindings.value }).from(vulnerabilityFindings).where(and2(eq2(vulnerabilityFindings.tenant_id, requiredText(filter.tenantId, "Tenant id")), filter.assetId ? eq2(vulnerabilityFindings.asset_id, filter.assetId.trim()) : undefined, filter.severity ? eq2(vulnerabilityFindings.severity, filter.severity) : undefined, filter.status ? eq2(vulnerabilityFindings.status, filter.status) : undefined)).orderBy(desc2(vulnerabilityFindings.last_seen_at), vulnerabilityFindings.finding_id).limit(boundedLimit3(filter.limit));
|
|
1170
|
+
return rows.map(({ value }) => valid(ManagedVulnerabilityFindingSchema, value, "Stored managed finding"));
|
|
1171
|
+
},
|
|
1172
|
+
save: async (finding) => saveFindings([finding]),
|
|
1173
|
+
saveMany: saveFindings
|
|
1174
|
+
};
|
|
1175
|
+
const saveObservations = async (tenantId, observations2) => {
|
|
1176
|
+
if (observations2.length === 0)
|
|
1177
|
+
return;
|
|
1178
|
+
const normalizedTenantId = requiredText(tenantId, "Tenant id");
|
|
1179
|
+
for (const observation of observations2)
|
|
1180
|
+
valid(VulnerabilityObservationSchema, observation, `Vulnerability observation ${observation.id}`);
|
|
1181
|
+
await db.insert(vulnerabilityObservations).values(observations2.map((observation) => ({
|
|
1182
|
+
asset_id: observation.assetId,
|
|
1183
|
+
component_id: observation.componentId,
|
|
1184
|
+
observation_id: observation.id,
|
|
1185
|
+
observed_at: new Date(observation.observedAt),
|
|
1186
|
+
tenant_id: normalizedTenantId,
|
|
1187
|
+
value: encodedJsonb2(observation)
|
|
1188
|
+
}))).onConflictDoUpdate({
|
|
1189
|
+
set: {
|
|
1190
|
+
asset_id: sql2`excluded.asset_id`,
|
|
1191
|
+
component_id: sql2`excluded.component_id`,
|
|
1192
|
+
observed_at: sql2`excluded.observed_at`,
|
|
1193
|
+
updated_at: databaseNow2,
|
|
1194
|
+
value: sql2`excluded.value`
|
|
1195
|
+
},
|
|
1196
|
+
target: [
|
|
1197
|
+
vulnerabilityObservations.tenant_id,
|
|
1198
|
+
vulnerabilityObservations.observation_id
|
|
1199
|
+
]
|
|
1200
|
+
});
|
|
1201
|
+
};
|
|
1202
|
+
const observations = {
|
|
1203
|
+
get: async (tenantId, observationId) => {
|
|
1204
|
+
const [row] = await db.select({ value: vulnerabilityObservations.value }).from(vulnerabilityObservations).where(and2(eq2(vulnerabilityObservations.tenant_id, requiredText(tenantId, "Tenant id")), eq2(vulnerabilityObservations.observation_id, requiredText(observationId, "Observation id")))).limit(1);
|
|
1205
|
+
return row ? valid(VulnerabilityObservationSchema, row.value, "Stored vulnerability observation") : null;
|
|
1206
|
+
},
|
|
1207
|
+
list: async (filter) => {
|
|
1208
|
+
const rows = await db.select({ value: vulnerabilityObservations.value }).from(vulnerabilityObservations).where(and2(eq2(vulnerabilityObservations.tenant_id, requiredText(filter.tenantId, "Tenant id")), filter.assetId ? eq2(vulnerabilityObservations.asset_id, filter.assetId.trim()) : undefined, filter.componentId ? eq2(vulnerabilityObservations.component_id, filter.componentId.trim()) : undefined)).orderBy(desc2(vulnerabilityObservations.observed_at), vulnerabilityObservations.observation_id).limit(boundedLimit3(filter.limit));
|
|
1209
|
+
return rows.map(({ value }) => valid(VulnerabilityObservationSchema, value, "Stored vulnerability observation"));
|
|
1210
|
+
},
|
|
1211
|
+
save: async (tenantId, observation) => saveObservations(tenantId, [observation]),
|
|
1212
|
+
saveMany: saveObservations
|
|
1213
|
+
};
|
|
1214
|
+
const saveRiskAssessments = async (tenantId, assessments) => {
|
|
1215
|
+
if (assessments.length === 0)
|
|
1216
|
+
return;
|
|
1217
|
+
const normalizedTenantId = requiredText(tenantId, "Tenant id");
|
|
1218
|
+
for (const assessment of assessments)
|
|
1219
|
+
valid(VulnerabilityRiskAssessmentSchema, assessment, `Vulnerability risk assessment ${assessment.findingId}`);
|
|
1220
|
+
await db.insert(vulnerabilityRiskAssessments).values(assessments.map((assessment) => ({
|
|
1221
|
+
assessed_at: new Date(assessment.assessedAt),
|
|
1222
|
+
finding_id: assessment.findingId,
|
|
1223
|
+
priority: assessment.priority,
|
|
1224
|
+
remediate_by: assessment.remediateBy ? new Date(assessment.remediateBy) : null,
|
|
1225
|
+
tenant_id: normalizedTenantId,
|
|
1226
|
+
value: encodedJsonb2(assessment)
|
|
1227
|
+
}))).onConflictDoUpdate({
|
|
1228
|
+
set: {
|
|
1229
|
+
assessed_at: sql2`excluded.assessed_at`,
|
|
1230
|
+
priority: sql2`excluded.priority`,
|
|
1231
|
+
remediate_by: sql2`excluded.remediate_by`,
|
|
1232
|
+
updated_at: databaseNow2,
|
|
1233
|
+
value: sql2`excluded.value`
|
|
1234
|
+
},
|
|
1235
|
+
target: [
|
|
1236
|
+
vulnerabilityRiskAssessments.tenant_id,
|
|
1237
|
+
vulnerabilityRiskAssessments.finding_id
|
|
1238
|
+
]
|
|
1239
|
+
});
|
|
1240
|
+
};
|
|
1241
|
+
const riskAssessments = {
|
|
1242
|
+
get: async (tenantId, findingId) => {
|
|
1243
|
+
const [row] = await db.select({ value: vulnerabilityRiskAssessments.value }).from(vulnerabilityRiskAssessments).where(and2(eq2(vulnerabilityRiskAssessments.tenant_id, requiredText(tenantId, "Tenant id")), eq2(vulnerabilityRiskAssessments.finding_id, requiredText(findingId, "Finding id")))).limit(1);
|
|
1244
|
+
return row ? valid(VulnerabilityRiskAssessmentSchema, row.value, "Stored vulnerability risk assessment") : null;
|
|
1245
|
+
},
|
|
1246
|
+
list: async (filter) => {
|
|
1247
|
+
const rows = await db.select({ value: vulnerabilityRiskAssessments.value }).from(vulnerabilityRiskAssessments).where(and2(eq2(vulnerabilityRiskAssessments.tenant_id, requiredText(filter.tenantId, "Tenant id")), filter.priority ? eq2(vulnerabilityRiskAssessments.priority, filter.priority) : undefined)).orderBy(desc2(vulnerabilityRiskAssessments.assessed_at), vulnerabilityRiskAssessments.finding_id).limit(boundedLimit3(filter.limit));
|
|
1248
|
+
return rows.map(({ value }) => valid(VulnerabilityRiskAssessmentSchema, value, "Stored vulnerability risk assessment"));
|
|
1249
|
+
},
|
|
1250
|
+
save: async (tenantId, assessment) => saveRiskAssessments(tenantId, [assessment]),
|
|
1251
|
+
saveMany: saveRiskAssessments
|
|
1252
|
+
};
|
|
1253
|
+
const remediationPlans = {
|
|
1254
|
+
get: async (tenantId, planId) => {
|
|
1255
|
+
const [row] = await db.select({ value: vulnerabilityRemediationPlans.value }).from(vulnerabilityRemediationPlans).where(and2(eq2(vulnerabilityRemediationPlans.tenant_id, requiredText(tenantId, "Tenant id")), eq2(vulnerabilityRemediationPlans.plan_id, requiredText(planId, "Remediation plan id")))).limit(1);
|
|
1256
|
+
return row ? valid(RemediationPlanSchema, row.value, "Stored remediation plan") : null;
|
|
1257
|
+
},
|
|
1258
|
+
list: async (filter) => {
|
|
1259
|
+
const rows = await db.select({ value: vulnerabilityRemediationPlans.value }).from(vulnerabilityRemediationPlans).where(and2(eq2(vulnerabilityRemediationPlans.tenant_id, requiredText(filter.tenantId, "Tenant id")), filter.status ? eq2(vulnerabilityRemediationPlans.status, filter.status) : undefined)).orderBy(desc2(vulnerabilityRemediationPlans.created_at), vulnerabilityRemediationPlans.plan_id).limit(boundedLimit3(filter.limit));
|
|
1260
|
+
return rows.map(({ value }) => valid(RemediationPlanSchema, value, "Stored remediation plan"));
|
|
1261
|
+
},
|
|
1262
|
+
save: async (tenantId, plan) => {
|
|
1263
|
+
valid(RemediationPlanSchema, plan, `Remediation plan ${plan.id}`);
|
|
1264
|
+
await db.insert(vulnerabilityRemediationPlans).values({
|
|
1265
|
+
created_at: new Date(plan.createdAt),
|
|
1266
|
+
plan_id: plan.id,
|
|
1267
|
+
status: plan.status,
|
|
1268
|
+
tenant_id: requiredText(tenantId, "Tenant id"),
|
|
1269
|
+
value: encodedJsonb2(plan)
|
|
1270
|
+
}).onConflictDoUpdate({
|
|
1271
|
+
set: {
|
|
1272
|
+
created_at: new Date(plan.createdAt),
|
|
1273
|
+
status: plan.status,
|
|
1274
|
+
updated_at: databaseNow2,
|
|
1275
|
+
value: encodedJsonb2(plan)
|
|
1276
|
+
},
|
|
1277
|
+
target: [
|
|
1278
|
+
vulnerabilityRemediationPlans.tenant_id,
|
|
1279
|
+
vulnerabilityRemediationPlans.plan_id
|
|
1280
|
+
]
|
|
1281
|
+
});
|
|
1282
|
+
}
|
|
1283
|
+
};
|
|
1284
|
+
const remediationExecutions = {
|
|
1285
|
+
get: async (tenantId, executionId) => {
|
|
1286
|
+
const [row] = await db.select({ value: vulnerabilityRemediationExecutions.value }).from(vulnerabilityRemediationExecutions).where(and2(eq2(vulnerabilityRemediationExecutions.tenant_id, requiredText(tenantId, "Tenant id")), eq2(vulnerabilityRemediationExecutions.execution_id, requiredText(executionId, "Remediation execution id")))).limit(1);
|
|
1287
|
+
return row ? valid(RemediationExecutionSchema, row.value, "Stored remediation execution") : null;
|
|
1288
|
+
},
|
|
1289
|
+
list: async (tenantId, planId) => {
|
|
1290
|
+
const rows = await db.select({ value: vulnerabilityRemediationExecutions.value }).from(vulnerabilityRemediationExecutions).where(and2(eq2(vulnerabilityRemediationExecutions.tenant_id, requiredText(tenantId, "Tenant id")), eq2(vulnerabilityRemediationExecutions.plan_id, requiredText(planId, "Remediation plan id")))).orderBy(desc2(vulnerabilityRemediationExecutions.started_at), vulnerabilityRemediationExecutions.execution_id).limit(1000);
|
|
1291
|
+
return rows.map(({ value }) => valid(RemediationExecutionSchema, value, "Stored remediation execution"));
|
|
1292
|
+
},
|
|
1293
|
+
save: async (tenantId, execution) => {
|
|
1294
|
+
valid(RemediationExecutionSchema, execution, `Remediation execution ${execution.id}`);
|
|
1295
|
+
await db.insert(vulnerabilityRemediationExecutions).values({
|
|
1296
|
+
completed_at: execution.completedAt ? new Date(execution.completedAt) : null,
|
|
1297
|
+
execution_id: execution.id,
|
|
1298
|
+
plan_id: execution.planId,
|
|
1299
|
+
started_at: new Date(execution.startedAt),
|
|
1300
|
+
status: execution.status,
|
|
1301
|
+
tenant_id: requiredText(tenantId, "Tenant id"),
|
|
1302
|
+
value: encodedJsonb2(execution)
|
|
1303
|
+
}).onConflictDoUpdate({
|
|
1304
|
+
set: {
|
|
1305
|
+
completed_at: execution.completedAt ? new Date(execution.completedAt) : null,
|
|
1306
|
+
plan_id: execution.planId,
|
|
1307
|
+
started_at: new Date(execution.startedAt),
|
|
1308
|
+
status: execution.status,
|
|
1309
|
+
updated_at: databaseNow2,
|
|
1310
|
+
value: encodedJsonb2(execution)
|
|
1311
|
+
},
|
|
1312
|
+
target: [
|
|
1313
|
+
vulnerabilityRemediationExecutions.tenant_id,
|
|
1314
|
+
vulnerabilityRemediationExecutions.execution_id
|
|
1315
|
+
]
|
|
1316
|
+
});
|
|
1317
|
+
}
|
|
1318
|
+
};
|
|
1319
|
+
const remediationVerifications = {
|
|
1320
|
+
get: async (tenantId, verificationId) => {
|
|
1321
|
+
const [row] = await db.select({
|
|
1322
|
+
value: vulnerabilityRemediationVerifications.value
|
|
1323
|
+
}).from(vulnerabilityRemediationVerifications).where(and2(eq2(vulnerabilityRemediationVerifications.tenant_id, requiredText(tenantId, "Tenant id")), eq2(vulnerabilityRemediationVerifications.verification_id, requiredText(verificationId, "Remediation verification id")))).limit(1);
|
|
1324
|
+
return row ? valid(RemediationVerificationSchema, row.value, "Stored remediation verification") : null;
|
|
1325
|
+
},
|
|
1326
|
+
list: async (tenantId, executionId) => {
|
|
1327
|
+
const rows = await db.select({
|
|
1328
|
+
value: vulnerabilityRemediationVerifications.value
|
|
1329
|
+
}).from(vulnerabilityRemediationVerifications).where(and2(eq2(vulnerabilityRemediationVerifications.tenant_id, requiredText(tenantId, "Tenant id")), eq2(vulnerabilityRemediationVerifications.execution_id, requiredText(executionId, "Remediation execution id")))).orderBy(desc2(vulnerabilityRemediationVerifications.observed_at), vulnerabilityRemediationVerifications.verification_id).limit(1000);
|
|
1330
|
+
return rows.map(({ value }) => valid(RemediationVerificationSchema, value, "Stored remediation verification"));
|
|
1331
|
+
},
|
|
1332
|
+
save: async (tenantId, verification) => {
|
|
1333
|
+
valid(RemediationVerificationSchema, verification, `Remediation verification ${verification.id}`);
|
|
1334
|
+
await db.insert(vulnerabilityRemediationVerifications).values({
|
|
1335
|
+
execution_id: verification.executionId,
|
|
1336
|
+
observed_at: new Date(verification.observedAt),
|
|
1337
|
+
plan_id: verification.planId,
|
|
1338
|
+
status: verification.status,
|
|
1339
|
+
tenant_id: requiredText(tenantId, "Tenant id"),
|
|
1340
|
+
value: encodedJsonb2(verification),
|
|
1341
|
+
verification_id: verification.id
|
|
1342
|
+
}).onConflictDoUpdate({
|
|
1343
|
+
set: {
|
|
1344
|
+
execution_id: verification.executionId,
|
|
1345
|
+
observed_at: new Date(verification.observedAt),
|
|
1346
|
+
plan_id: verification.planId,
|
|
1347
|
+
status: verification.status,
|
|
1348
|
+
updated_at: databaseNow2,
|
|
1349
|
+
value: encodedJsonb2(verification)
|
|
1350
|
+
},
|
|
1351
|
+
target: [
|
|
1352
|
+
vulnerabilityRemediationVerifications.tenant_id,
|
|
1353
|
+
vulnerabilityRemediationVerifications.verification_id
|
|
1354
|
+
]
|
|
1355
|
+
});
|
|
1356
|
+
}
|
|
1357
|
+
};
|
|
1358
|
+
const saveVexDecisions = async (tenantId, decisions) => {
|
|
1359
|
+
if (decisions.length === 0)
|
|
1360
|
+
return;
|
|
1361
|
+
const normalizedTenantId = requiredText(tenantId, "Tenant id");
|
|
1362
|
+
for (const decision of decisions)
|
|
1363
|
+
valid(VexDecisionSchema, decision, `VEX decision ${decision.id}`);
|
|
1364
|
+
await db.insert(vulnerabilityVexDecisions).values(decisions.map((decision) => ({
|
|
1365
|
+
created_at: new Date(decision.createdAt),
|
|
1366
|
+
decision_id: decision.id,
|
|
1367
|
+
expires_at: decision.expiresAt ? new Date(decision.expiresAt) : null,
|
|
1368
|
+
product_id: decision.productId,
|
|
1369
|
+
status: decision.status,
|
|
1370
|
+
tenant_id: normalizedTenantId,
|
|
1371
|
+
value: encodedJsonb2(decision),
|
|
1372
|
+
vulnerability_id: decision.vulnerabilityId
|
|
1373
|
+
}))).onConflictDoUpdate({
|
|
1374
|
+
set: {
|
|
1375
|
+
created_at: sql2`excluded.created_at`,
|
|
1376
|
+
expires_at: sql2`excluded.expires_at`,
|
|
1377
|
+
product_id: sql2`excluded.product_id`,
|
|
1378
|
+
status: sql2`excluded.status`,
|
|
1379
|
+
updated_at: databaseNow2,
|
|
1380
|
+
value: sql2`excluded.value`,
|
|
1381
|
+
vulnerability_id: sql2`excluded.vulnerability_id`
|
|
1382
|
+
},
|
|
1383
|
+
target: [
|
|
1384
|
+
vulnerabilityVexDecisions.tenant_id,
|
|
1385
|
+
vulnerabilityVexDecisions.decision_id
|
|
1386
|
+
]
|
|
1387
|
+
});
|
|
1388
|
+
};
|
|
1389
|
+
const vexDecisions = {
|
|
1390
|
+
get: async (tenantId, decisionId) => {
|
|
1391
|
+
const [row] = await db.select({ value: vulnerabilityVexDecisions.value }).from(vulnerabilityVexDecisions).where(and2(eq2(vulnerabilityVexDecisions.tenant_id, requiredText(tenantId, "Tenant id")), eq2(vulnerabilityVexDecisions.decision_id, requiredText(decisionId, "Decision id")))).limit(1);
|
|
1392
|
+
return row ? valid(VexDecisionSchema, row.value, "Stored VEX decision") : null;
|
|
1393
|
+
},
|
|
1394
|
+
list: async (filter) => {
|
|
1395
|
+
const rows = await db.select({ value: vulnerabilityVexDecisions.value }).from(vulnerabilityVexDecisions).where(and2(eq2(vulnerabilityVexDecisions.tenant_id, requiredText(filter.tenantId, "Tenant id")), filter.productId ? eq2(vulnerabilityVexDecisions.product_id, filter.productId.trim()) : undefined, filter.vulnerabilityId ? eq2(vulnerabilityVexDecisions.vulnerability_id, filter.vulnerabilityId.trim()) : undefined)).orderBy(desc2(vulnerabilityVexDecisions.created_at), vulnerabilityVexDecisions.decision_id).limit(boundedLimit3(filter.limit));
|
|
1396
|
+
return rows.map(({ value }) => valid(VexDecisionSchema, value, "Stored VEX decision"));
|
|
1397
|
+
},
|
|
1398
|
+
save: async (tenantId, decision) => saveVexDecisions(tenantId, [decision]),
|
|
1399
|
+
saveMany: saveVexDecisions
|
|
1400
|
+
};
|
|
1401
|
+
const saveVexApplications = async (applications) => {
|
|
1402
|
+
if (applications.length === 0)
|
|
1403
|
+
return;
|
|
1404
|
+
for (const application of applications)
|
|
1405
|
+
valid(VexFindingApplicationSchema, application, `VEX application ${application.findingId}`);
|
|
1406
|
+
await db.insert(vulnerabilityVexApplications).values(applications.map((application) => ({
|
|
1407
|
+
applied_at: new Date(application.appliedAt),
|
|
1408
|
+
decision_id: application.decisionId,
|
|
1409
|
+
ended_at: application.endedAt ? new Date(application.endedAt) : null,
|
|
1410
|
+
finding_id: application.findingId,
|
|
1411
|
+
tenant_id: application.tenantId,
|
|
1412
|
+
value: encodedJsonb2(application)
|
|
1413
|
+
}))).onConflictDoUpdate({
|
|
1414
|
+
set: {
|
|
1415
|
+
applied_at: sql2`excluded.applied_at`,
|
|
1416
|
+
decision_id: sql2`excluded.decision_id`,
|
|
1417
|
+
ended_at: sql2`excluded.ended_at`,
|
|
1418
|
+
updated_at: databaseNow2,
|
|
1419
|
+
value: sql2`excluded.value`
|
|
1420
|
+
},
|
|
1421
|
+
target: [
|
|
1422
|
+
vulnerabilityVexApplications.tenant_id,
|
|
1423
|
+
vulnerabilityVexApplications.finding_id
|
|
1424
|
+
]
|
|
1425
|
+
});
|
|
1426
|
+
};
|
|
1427
|
+
const vexApplications = {
|
|
1428
|
+
get: async (tenantId, findingId) => {
|
|
1429
|
+
const [row] = await db.select({ value: vulnerabilityVexApplications.value }).from(vulnerabilityVexApplications).where(and2(eq2(vulnerabilityVexApplications.tenant_id, requiredText(tenantId, "Tenant id")), eq2(vulnerabilityVexApplications.finding_id, requiredText(findingId, "Finding id")))).limit(1);
|
|
1430
|
+
return row ? valid(VexFindingApplicationSchema, row.value, "Stored VEX application") : null;
|
|
1431
|
+
},
|
|
1432
|
+
save: async (application) => saveVexApplications([application]),
|
|
1433
|
+
saveMany: saveVexApplications
|
|
1434
|
+
};
|
|
1435
|
+
const leases = {
|
|
1436
|
+
acquire: async (request) => {
|
|
1437
|
+
if (!Number.isFinite(request.ttlMs) || request.ttlMs <= 0)
|
|
1438
|
+
throw new Error("Feed lease ttlMs must be positive and finite");
|
|
1439
|
+
const now = request.now ?? new Date;
|
|
1440
|
+
const ownerId = requiredText(request.ownerId, "Feed lease owner id");
|
|
1441
|
+
const [row] = await db.insert(vulnerabilityFeedLeases).values({
|
|
1442
|
+
expires_at: new Date(now.getTime() + request.ttlMs),
|
|
1443
|
+
feed_id: requiredText(request.feedId, "Feed lease feed id"),
|
|
1444
|
+
owner_id: ownerId,
|
|
1445
|
+
updated_at: now
|
|
1446
|
+
}).onConflictDoUpdate({
|
|
1447
|
+
set: {
|
|
1448
|
+
expires_at: new Date(now.getTime() + request.ttlMs),
|
|
1449
|
+
owner_id: ownerId,
|
|
1450
|
+
updated_at: now
|
|
1451
|
+
},
|
|
1452
|
+
setWhere: or2(lte2(vulnerabilityFeedLeases.expires_at, now), eq2(vulnerabilityFeedLeases.owner_id, ownerId)),
|
|
1453
|
+
target: vulnerabilityFeedLeases.feed_id
|
|
1454
|
+
}).returning({ ownerId: vulnerabilityFeedLeases.owner_id });
|
|
1455
|
+
return row?.ownerId === ownerId;
|
|
1456
|
+
},
|
|
1457
|
+
release: async (feedId, ownerId) => {
|
|
1458
|
+
const rows = await db.delete(vulnerabilityFeedLeases).where(and2(eq2(vulnerabilityFeedLeases.feed_id, requiredText(feedId, "Feed lease feed id")), eq2(vulnerabilityFeedLeases.owner_id, requiredText(ownerId, "Feed lease owner id")))).returning({ feedId: vulnerabilityFeedLeases.feed_id });
|
|
1459
|
+
return rows.length > 0;
|
|
1460
|
+
}
|
|
1461
|
+
};
|
|
1462
|
+
return {
|
|
1463
|
+
alertIncidents: alertStores.alertIncidents,
|
|
1464
|
+
alertPolicies: alertStores.alertPolicies,
|
|
1465
|
+
ensureSchema: () => Promise.resolve(),
|
|
1466
|
+
findings,
|
|
1467
|
+
leases,
|
|
1468
|
+
observations,
|
|
1469
|
+
remediationExecutions,
|
|
1470
|
+
remediationPlans,
|
|
1471
|
+
remediationVerifications,
|
|
1472
|
+
riskAssessments,
|
|
1473
|
+
snapshots,
|
|
1474
|
+
syncRuns,
|
|
1475
|
+
vexApplications,
|
|
1476
|
+
vexDecisions
|
|
1477
|
+
};
|
|
1478
|
+
};
|
|
341
1479
|
|
|
342
1480
|
// src/index.ts
|
|
343
1481
|
var IDENTIFIER2 = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
|
|
@@ -347,7 +1485,7 @@ var SYNC_STATUSES = new Set([
|
|
|
347
1485
|
"stale",
|
|
348
1486
|
"updated"
|
|
349
1487
|
]);
|
|
350
|
-
var
|
|
1488
|
+
var requiredText2 = (value, label) => {
|
|
351
1489
|
const normalized = value.trim();
|
|
352
1490
|
if (normalized.length === 0)
|
|
353
1491
|
throw new Error(`${label} is required`);
|
|
@@ -359,7 +1497,7 @@ var limit = (value, fallback = 100) => {
|
|
|
359
1497
|
throw new Error("Postgres query limit must be an integer from 1 through 1000");
|
|
360
1498
|
return normalized;
|
|
361
1499
|
};
|
|
362
|
-
var
|
|
1500
|
+
var timestamp3 = (value, label) => {
|
|
363
1501
|
if (value instanceof Date)
|
|
364
1502
|
return value.toISOString();
|
|
365
1503
|
if (typeof value !== "string" || !Number.isFinite(Date.parse(value)))
|
|
@@ -565,7 +1703,7 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
565
1703
|
const tablePrefix = options.tablePrefix ?? "vulnerability";
|
|
566
1704
|
const ddl = vulnerabilityPostgresSchemaSql(tablePrefix);
|
|
567
1705
|
const table = prefixTables(tablePrefix);
|
|
568
|
-
const
|
|
1706
|
+
const sql3 = options.sql;
|
|
569
1707
|
const shouldEnsureSchema = options.ensureSchema ?? true;
|
|
570
1708
|
const alertStores = createPostgresVulnerabilityAlertStores({
|
|
571
1709
|
ensureSchema: shouldEnsureSchema,
|
|
@@ -578,7 +1716,7 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
578
1716
|
return Promise.resolve();
|
|
579
1717
|
if (schemaPromise)
|
|
580
1718
|
return schemaPromise;
|
|
581
|
-
schemaPromise = Promise.resolve(
|
|
1719
|
+
schemaPromise = Promise.resolve(sql3.unsafe(ddl)).then(() => {
|
|
582
1720
|
return;
|
|
583
1721
|
});
|
|
584
1722
|
return schemaPromise;
|
|
@@ -586,8 +1724,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
586
1724
|
const snapshots = () => ({
|
|
587
1725
|
load: async (feedId) => {
|
|
588
1726
|
await ensureSchema();
|
|
589
|
-
const id =
|
|
590
|
-
const rows = await
|
|
1727
|
+
const id = requiredText2(feedId, "Feed id");
|
|
1728
|
+
const rows = await sql3`
|
|
591
1729
|
SELECT
|
|
592
1730
|
snapshot.feed_id,
|
|
593
1731
|
snapshot.feed_name,
|
|
@@ -603,10 +1741,10 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
603
1741
|
'value', record.value
|
|
604
1742
|
) ORDER BY record.record_id
|
|
605
1743
|
)
|
|
606
|
-
FROM ${
|
|
1744
|
+
FROM ${sql3.unsafe(table.records)} record
|
|
607
1745
|
WHERE record.feed_id = snapshot.feed_id
|
|
608
1746
|
), '[]'::jsonb) AS records
|
|
609
|
-
FROM ${
|
|
1747
|
+
FROM ${sql3.unsafe(table.snapshots)} snapshot
|
|
610
1748
|
WHERE snapshot.feed_id = ${id}
|
|
611
1749
|
`;
|
|
612
1750
|
const row = rows[0];
|
|
@@ -622,10 +1760,10 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
622
1760
|
name: row.feed_name,
|
|
623
1761
|
url: row.feed_url
|
|
624
1762
|
},
|
|
625
|
-
fetchedAt:
|
|
1763
|
+
fetchedAt: timestamp3(row.fetched_at, "Feed fetchedAt"),
|
|
626
1764
|
records: records.map((record) => ({
|
|
627
|
-
id:
|
|
628
|
-
modifiedAt:
|
|
1765
|
+
id: requiredText2(record.id, "Feed record id"),
|
|
1766
|
+
modifiedAt: timestamp3(record.modifiedAt, "Feed record modifiedAt"),
|
|
629
1767
|
value: record.value
|
|
630
1768
|
})),
|
|
631
1769
|
revision: row.revision
|
|
@@ -634,21 +1772,21 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
634
1772
|
save: async (snapshot) => {
|
|
635
1773
|
await ensureSchema();
|
|
636
1774
|
const records = JSON.stringify(snapshot.records.map((record) => ({
|
|
637
|
-
id:
|
|
638
|
-
modified_at:
|
|
1775
|
+
id: requiredText2(record.id, "Feed record id"),
|
|
1776
|
+
modified_at: timestamp3(record.modifiedAt, "Feed record modifiedAt"),
|
|
639
1777
|
value: record.value
|
|
640
1778
|
})));
|
|
641
1779
|
const cursor = JSON.stringify(snapshot.cursor);
|
|
642
|
-
await
|
|
1780
|
+
await sql3`
|
|
643
1781
|
WITH saved_snapshot AS (
|
|
644
|
-
INSERT INTO ${
|
|
1782
|
+
INSERT INTO ${sql3.unsafe(table.snapshots)} (
|
|
645
1783
|
feed_id, feed_name, feed_url, cursor, fetched_at, revision, updated_at
|
|
646
1784
|
) VALUES (
|
|
647
|
-
${
|
|
648
|
-
${
|
|
649
|
-
${
|
|
1785
|
+
${requiredText2(snapshot.feed.id, "Feed id")},
|
|
1786
|
+
${requiredText2(snapshot.feed.name, "Feed name")},
|
|
1787
|
+
${requiredText2(snapshot.feed.url, "Feed URL")},
|
|
650
1788
|
${cursor}::jsonb,
|
|
651
|
-
${
|
|
1789
|
+
${timestamp3(snapshot.fetchedAt, "Feed fetchedAt")}::timestamptz,
|
|
652
1790
|
${snapshot.revision},
|
|
653
1791
|
now()
|
|
654
1792
|
)
|
|
@@ -665,14 +1803,14 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
665
1803
|
FROM jsonb_to_recordset(${records}::jsonb)
|
|
666
1804
|
AS item(id text, modified_at text, value jsonb)
|
|
667
1805
|
), removed AS (
|
|
668
|
-
DELETE FROM ${
|
|
1806
|
+
DELETE FROM ${sql3.unsafe(table.records)} record
|
|
669
1807
|
WHERE record.feed_id = ${snapshot.feed.id}
|
|
670
1808
|
AND NOT EXISTS (
|
|
671
1809
|
SELECT 1 FROM incoming WHERE incoming.id = record.record_id
|
|
672
1810
|
)
|
|
673
1811
|
RETURNING record_id
|
|
674
1812
|
), written AS (
|
|
675
|
-
INSERT INTO ${
|
|
1813
|
+
INSERT INTO ${sql3.unsafe(table.records)} (
|
|
676
1814
|
feed_id, record_id, modified_at, value
|
|
677
1815
|
)
|
|
678
1816
|
SELECT saved_snapshot.feed_id, incoming.id, incoming.modified_at, incoming.value
|
|
@@ -695,14 +1833,14 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
695
1833
|
throw new Error(`Unsupported feed sync status: ${run.status}`);
|
|
696
1834
|
if (!Number.isInteger(run.records) || run.records < 0)
|
|
697
1835
|
throw new Error("Feed sync records must be a non-negative integer");
|
|
698
|
-
await
|
|
699
|
-
INSERT INTO ${
|
|
1836
|
+
await sql3`
|
|
1837
|
+
INSERT INTO ${sql3.unsafe(table.runs)} (
|
|
700
1838
|
id, feed_id, started_at, completed_at, status, error, records, revision
|
|
701
1839
|
) VALUES (
|
|
702
|
-
${
|
|
703
|
-
${
|
|
704
|
-
${
|
|
705
|
-
${
|
|
1840
|
+
${requiredText2(run.id, "Feed sync run id")},
|
|
1841
|
+
${requiredText2(run.feedId, "Feed sync feed id")},
|
|
1842
|
+
${timestamp3(run.startedAt, "Feed sync startedAt")}::timestamptz,
|
|
1843
|
+
${timestamp3(run.completedAt, "Feed sync completedAt")}::timestamptz,
|
|
706
1844
|
${run.status}, ${run.error}, ${run.records}, ${run.revision}
|
|
707
1845
|
)
|
|
708
1846
|
ON CONFLICT (id) DO UPDATE SET
|
|
@@ -719,22 +1857,22 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
719
1857
|
await ensureSchema();
|
|
720
1858
|
const feedId = filter.feedId?.trim() || null;
|
|
721
1859
|
const status = filter.status ?? null;
|
|
722
|
-
const rows = await
|
|
1860
|
+
const rows = await sql3`
|
|
723
1861
|
SELECT id, feed_id, started_at, completed_at, status, error, records, revision
|
|
724
|
-
FROM ${
|
|
1862
|
+
FROM ${sql3.unsafe(table.runs)}
|
|
725
1863
|
WHERE (${feedId}::text IS NULL OR feed_id = ${feedId})
|
|
726
1864
|
AND (${status}::text IS NULL OR status = ${status})
|
|
727
1865
|
ORDER BY started_at DESC, id DESC
|
|
728
1866
|
LIMIT ${limit(filter.limit)}
|
|
729
1867
|
`;
|
|
730
1868
|
return rows.map((row) => ({
|
|
731
|
-
completedAt:
|
|
1869
|
+
completedAt: timestamp3(row.completed_at, "Feed sync completedAt"),
|
|
732
1870
|
error: row.error,
|
|
733
1871
|
feedId: row.feed_id,
|
|
734
1872
|
id: row.id,
|
|
735
1873
|
records: Number(row.records),
|
|
736
1874
|
revision: row.revision,
|
|
737
|
-
startedAt:
|
|
1875
|
+
startedAt: timestamp3(row.started_at, "Feed sync startedAt"),
|
|
738
1876
|
status: row.status
|
|
739
1877
|
}));
|
|
740
1878
|
}
|
|
@@ -745,7 +1883,7 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
745
1883
|
return;
|
|
746
1884
|
for (const finding of findings2) {
|
|
747
1885
|
const findingId = finding.id;
|
|
748
|
-
if (!
|
|
1886
|
+
if (!Value2.Check(ManagedVulnerabilityFindingSchema2, finding))
|
|
749
1887
|
throw new Error(`Managed finding ${findingId} is invalid`);
|
|
750
1888
|
}
|
|
751
1889
|
const payload = JSON.stringify(findings2.map((finding) => ({
|
|
@@ -759,8 +1897,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
759
1897
|
tenant_id: finding.tenantId,
|
|
760
1898
|
value: finding
|
|
761
1899
|
})));
|
|
762
|
-
await
|
|
763
|
-
INSERT INTO ${
|
|
1900
|
+
await sql3`
|
|
1901
|
+
INSERT INTO ${sql3.unsafe(table.findings)} (
|
|
764
1902
|
tenant_id, finding_id, asset_id, component_id, severity, status,
|
|
765
1903
|
first_seen_at, last_seen_at, value, updated_at
|
|
766
1904
|
)
|
|
@@ -778,36 +1916,36 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
778
1916
|
component_id = EXCLUDED.component_id,
|
|
779
1917
|
severity = EXCLUDED.severity,
|
|
780
1918
|
status = EXCLUDED.status,
|
|
781
|
-
first_seen_at = LEAST(${
|
|
782
|
-
last_seen_at = GREATEST(${
|
|
1919
|
+
first_seen_at = LEAST(${sql3.unsafe(table.findings)}.first_seen_at, EXCLUDED.first_seen_at),
|
|
1920
|
+
last_seen_at = GREATEST(${sql3.unsafe(table.findings)}.last_seen_at, EXCLUDED.last_seen_at),
|
|
783
1921
|
value = EXCLUDED.value,
|
|
784
1922
|
updated_at = now()
|
|
785
1923
|
`;
|
|
786
1924
|
};
|
|
787
1925
|
const parseFinding = (value) => {
|
|
788
1926
|
const finding = json(value, "Managed finding");
|
|
789
|
-
if (!
|
|
1927
|
+
if (!Value2.Check(ManagedVulnerabilityFindingSchema2, finding))
|
|
790
1928
|
throw new Error("Stored managed finding is invalid");
|
|
791
1929
|
return finding;
|
|
792
1930
|
};
|
|
793
1931
|
const findings = {
|
|
794
1932
|
get: async (tenantId, findingId) => {
|
|
795
1933
|
await ensureSchema();
|
|
796
|
-
const rows = await
|
|
797
|
-
SELECT value FROM ${
|
|
798
|
-
WHERE tenant_id = ${
|
|
799
|
-
AND finding_id = ${
|
|
1934
|
+
const rows = await sql3`
|
|
1935
|
+
SELECT value FROM ${sql3.unsafe(table.findings)}
|
|
1936
|
+
WHERE tenant_id = ${requiredText2(tenantId, "Tenant id")}
|
|
1937
|
+
AND finding_id = ${requiredText2(findingId, "Finding id")}
|
|
800
1938
|
`;
|
|
801
1939
|
return rows[0] ? parseFinding(rows[0].value) : null;
|
|
802
1940
|
},
|
|
803
1941
|
list: async (filter) => {
|
|
804
1942
|
await ensureSchema();
|
|
805
|
-
const tenantId =
|
|
1943
|
+
const tenantId = requiredText2(filter.tenantId, "Tenant id");
|
|
806
1944
|
const assetId = filter.assetId?.trim() || null;
|
|
807
1945
|
const severity = filter.severity ?? null;
|
|
808
1946
|
const status = filter.status ?? null;
|
|
809
|
-
const rows = await
|
|
810
|
-
SELECT value FROM ${
|
|
1947
|
+
const rows = await sql3`
|
|
1948
|
+
SELECT value FROM ${sql3.unsafe(table.findings)}
|
|
811
1949
|
WHERE tenant_id = ${tenantId}
|
|
812
1950
|
AND (${assetId}::text IS NULL OR asset_id = ${assetId})
|
|
813
1951
|
AND (${severity}::text IS NULL OR severity = ${severity})
|
|
@@ -822,18 +1960,18 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
822
1960
|
};
|
|
823
1961
|
const parseObservation = (value) => {
|
|
824
1962
|
const observation = json(value, "Vulnerability observation");
|
|
825
|
-
if (!
|
|
1963
|
+
if (!Value2.Check(VulnerabilityObservationSchema2, observation))
|
|
826
1964
|
throw new Error("Stored vulnerability observation is invalid");
|
|
827
1965
|
return observation;
|
|
828
1966
|
};
|
|
829
1967
|
const saveObservations = async (tenantId, observations2) => {
|
|
830
1968
|
await ensureSchema();
|
|
831
|
-
const normalizedTenantId =
|
|
1969
|
+
const normalizedTenantId = requiredText2(tenantId, "Tenant id");
|
|
832
1970
|
if (observations2.length === 0)
|
|
833
1971
|
return;
|
|
834
1972
|
for (const observation of observations2) {
|
|
835
1973
|
const observationId = observation.id;
|
|
836
|
-
if (!
|
|
1974
|
+
if (!Value2.Check(VulnerabilityObservationSchema2, observation))
|
|
837
1975
|
throw new Error(`Vulnerability observation ${observationId} is invalid`);
|
|
838
1976
|
}
|
|
839
1977
|
const payload = JSON.stringify(observations2.map((observation) => ({
|
|
@@ -843,8 +1981,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
843
1981
|
observed_at: observation.observedAt,
|
|
844
1982
|
value: observation
|
|
845
1983
|
})));
|
|
846
|
-
await
|
|
847
|
-
INSERT INTO ${
|
|
1984
|
+
await sql3`
|
|
1985
|
+
INSERT INTO ${sql3.unsafe(table.observations)} (
|
|
848
1986
|
tenant_id, observation_id, asset_id, component_id, observed_at, value,
|
|
849
1987
|
updated_at
|
|
850
1988
|
)
|
|
@@ -866,20 +2004,20 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
866
2004
|
const observations = {
|
|
867
2005
|
get: async (tenantId, observationId) => {
|
|
868
2006
|
await ensureSchema();
|
|
869
|
-
const rows = await
|
|
870
|
-
SELECT value FROM ${
|
|
871
|
-
WHERE tenant_id = ${
|
|
872
|
-
AND observation_id = ${
|
|
2007
|
+
const rows = await sql3`
|
|
2008
|
+
SELECT value FROM ${sql3.unsafe(table.observations)}
|
|
2009
|
+
WHERE tenant_id = ${requiredText2(tenantId, "Tenant id")}
|
|
2010
|
+
AND observation_id = ${requiredText2(observationId, "Observation id")}
|
|
873
2011
|
`;
|
|
874
2012
|
return rows[0] ? parseObservation(rows[0].value) : null;
|
|
875
2013
|
},
|
|
876
2014
|
list: async (filter) => {
|
|
877
2015
|
await ensureSchema();
|
|
878
|
-
const tenantId =
|
|
2016
|
+
const tenantId = requiredText2(filter.tenantId, "Tenant id");
|
|
879
2017
|
const assetId = filter.assetId?.trim() || null;
|
|
880
2018
|
const componentId = filter.componentId?.trim() || null;
|
|
881
|
-
const rows = await
|
|
882
|
-
SELECT value FROM ${
|
|
2019
|
+
const rows = await sql3`
|
|
2020
|
+
SELECT value FROM ${sql3.unsafe(table.observations)}
|
|
883
2021
|
WHERE tenant_id = ${tenantId}
|
|
884
2022
|
AND (${assetId}::text IS NULL OR asset_id = ${assetId})
|
|
885
2023
|
AND (${componentId}::text IS NULL OR component_id = ${componentId})
|
|
@@ -893,18 +2031,18 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
893
2031
|
};
|
|
894
2032
|
const parseRiskAssessment = (value) => {
|
|
895
2033
|
const assessment = json(value, "Vulnerability risk assessment");
|
|
896
|
-
if (!
|
|
2034
|
+
if (!Value2.Check(VulnerabilityRiskAssessmentSchema2, assessment))
|
|
897
2035
|
throw new Error("Stored vulnerability risk assessment is invalid");
|
|
898
2036
|
return assessment;
|
|
899
2037
|
};
|
|
900
2038
|
const saveRiskAssessments = async (tenantId, assessments) => {
|
|
901
2039
|
await ensureSchema();
|
|
902
|
-
const normalizedTenantId =
|
|
2040
|
+
const normalizedTenantId = requiredText2(tenantId, "Tenant id");
|
|
903
2041
|
if (assessments.length === 0)
|
|
904
2042
|
return;
|
|
905
2043
|
for (const assessment of assessments) {
|
|
906
2044
|
const findingId = assessment.findingId;
|
|
907
|
-
if (!
|
|
2045
|
+
if (!Value2.Check(VulnerabilityRiskAssessmentSchema2, assessment))
|
|
908
2046
|
throw new Error(`Vulnerability risk assessment ${findingId} is invalid`);
|
|
909
2047
|
}
|
|
910
2048
|
const payload = JSON.stringify(assessments.map((assessment) => ({
|
|
@@ -914,8 +2052,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
914
2052
|
remediate_by: assessment.remediateBy,
|
|
915
2053
|
value: assessment
|
|
916
2054
|
})));
|
|
917
|
-
await
|
|
918
|
-
INSERT INTO ${
|
|
2055
|
+
await sql3`
|
|
2056
|
+
INSERT INTO ${sql3.unsafe(table.riskAssessments)} (
|
|
919
2057
|
tenant_id, finding_id, priority, assessed_at, remediate_by, value,
|
|
920
2058
|
updated_at
|
|
921
2059
|
)
|
|
@@ -938,19 +2076,19 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
938
2076
|
const riskAssessments = {
|
|
939
2077
|
get: async (tenantId, findingId) => {
|
|
940
2078
|
await ensureSchema();
|
|
941
|
-
const rows = await
|
|
942
|
-
SELECT value FROM ${
|
|
943
|
-
WHERE tenant_id = ${
|
|
944
|
-
AND finding_id = ${
|
|
2079
|
+
const rows = await sql3`
|
|
2080
|
+
SELECT value FROM ${sql3.unsafe(table.riskAssessments)}
|
|
2081
|
+
WHERE tenant_id = ${requiredText2(tenantId, "Tenant id")}
|
|
2082
|
+
AND finding_id = ${requiredText2(findingId, "Finding id")}
|
|
945
2083
|
`;
|
|
946
2084
|
return rows[0] ? parseRiskAssessment(rows[0].value) : null;
|
|
947
2085
|
},
|
|
948
2086
|
list: async (filter) => {
|
|
949
2087
|
await ensureSchema();
|
|
950
|
-
const tenantId =
|
|
2088
|
+
const tenantId = requiredText2(filter.tenantId, "Tenant id");
|
|
951
2089
|
const priority = filter.priority ?? null;
|
|
952
|
-
const rows = await
|
|
953
|
-
SELECT value FROM ${
|
|
2090
|
+
const rows = await sql3`
|
|
2091
|
+
SELECT value FROM ${sql3.unsafe(table.riskAssessments)}
|
|
954
2092
|
WHERE tenant_id = ${tenantId}
|
|
955
2093
|
AND (${priority}::text IS NULL OR priority = ${priority})
|
|
956
2094
|
ORDER BY assessed_at DESC, finding_id
|
|
@@ -963,26 +2101,26 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
963
2101
|
};
|
|
964
2102
|
const parseRemediationPlan = (value) => {
|
|
965
2103
|
const plan = json(value, "Remediation plan");
|
|
966
|
-
if (!
|
|
2104
|
+
if (!Value2.Check(RemediationPlanSchema2, plan))
|
|
967
2105
|
throw new Error("Stored remediation plan is invalid");
|
|
968
2106
|
return plan;
|
|
969
2107
|
};
|
|
970
2108
|
const remediationPlans = {
|
|
971
2109
|
get: async (tenantId, planId) => {
|
|
972
2110
|
await ensureSchema();
|
|
973
|
-
const rows = await
|
|
974
|
-
SELECT value FROM ${
|
|
975
|
-
WHERE tenant_id = ${
|
|
976
|
-
AND plan_id = ${
|
|
2111
|
+
const rows = await sql3`
|
|
2112
|
+
SELECT value FROM ${sql3.unsafe(table.remediationPlans)}
|
|
2113
|
+
WHERE tenant_id = ${requiredText2(tenantId, "Tenant id")}
|
|
2114
|
+
AND plan_id = ${requiredText2(planId, "Remediation plan id")}
|
|
977
2115
|
`;
|
|
978
2116
|
return rows[0] ? parseRemediationPlan(rows[0].value) : null;
|
|
979
2117
|
},
|
|
980
2118
|
list: async (filter) => {
|
|
981
2119
|
await ensureSchema();
|
|
982
|
-
const tenantId =
|
|
2120
|
+
const tenantId = requiredText2(filter.tenantId, "Tenant id");
|
|
983
2121
|
const status = filter.status ?? null;
|
|
984
|
-
const rows = await
|
|
985
|
-
SELECT value FROM ${
|
|
2122
|
+
const rows = await sql3`
|
|
2123
|
+
SELECT value FROM ${sql3.unsafe(table.remediationPlans)}
|
|
986
2124
|
WHERE tenant_id = ${tenantId}
|
|
987
2125
|
AND (${status}::text IS NULL OR status = ${status})
|
|
988
2126
|
ORDER BY created_at DESC, plan_id
|
|
@@ -993,13 +2131,13 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
993
2131
|
save: async (tenantId, plan) => {
|
|
994
2132
|
await ensureSchema();
|
|
995
2133
|
const planId = plan.id;
|
|
996
|
-
if (!
|
|
2134
|
+
if (!Value2.Check(RemediationPlanSchema2, plan))
|
|
997
2135
|
throw new Error(`Remediation plan ${planId} is invalid`);
|
|
998
|
-
await
|
|
999
|
-
INSERT INTO ${
|
|
2136
|
+
await sql3`
|
|
2137
|
+
INSERT INTO ${sql3.unsafe(table.remediationPlans)} (
|
|
1000
2138
|
tenant_id, plan_id, status, created_at, value, updated_at
|
|
1001
2139
|
) VALUES (
|
|
1002
|
-
${
|
|
2140
|
+
${requiredText2(tenantId, "Tenant id")}, ${plan.id}, ${plan.status},
|
|
1003
2141
|
${plan.createdAt}::timestamptz, ${JSON.stringify(plan)}::jsonb, now()
|
|
1004
2142
|
)
|
|
1005
2143
|
ON CONFLICT (tenant_id, plan_id) DO UPDATE SET
|
|
@@ -1012,26 +2150,26 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1012
2150
|
};
|
|
1013
2151
|
const parseRemediationExecution = (value) => {
|
|
1014
2152
|
const execution = json(value, "Remediation execution");
|
|
1015
|
-
if (!
|
|
2153
|
+
if (!Value2.Check(RemediationExecutionSchema2, execution))
|
|
1016
2154
|
throw new Error("Stored remediation execution is invalid");
|
|
1017
2155
|
return execution;
|
|
1018
2156
|
};
|
|
1019
2157
|
const remediationExecutions = {
|
|
1020
2158
|
get: async (tenantId, executionId) => {
|
|
1021
2159
|
await ensureSchema();
|
|
1022
|
-
const rows = await
|
|
1023
|
-
SELECT value FROM ${
|
|
1024
|
-
WHERE tenant_id = ${
|
|
1025
|
-
AND execution_id = ${
|
|
2160
|
+
const rows = await sql3`
|
|
2161
|
+
SELECT value FROM ${sql3.unsafe(table.remediationExecutions)}
|
|
2162
|
+
WHERE tenant_id = ${requiredText2(tenantId, "Tenant id")}
|
|
2163
|
+
AND execution_id = ${requiredText2(executionId, "Remediation execution id")}
|
|
1026
2164
|
`;
|
|
1027
2165
|
return rows[0] ? parseRemediationExecution(rows[0].value) : null;
|
|
1028
2166
|
},
|
|
1029
2167
|
list: async (tenantId, planId) => {
|
|
1030
2168
|
await ensureSchema();
|
|
1031
|
-
const rows = await
|
|
1032
|
-
SELECT value FROM ${
|
|
1033
|
-
WHERE tenant_id = ${
|
|
1034
|
-
AND plan_id = ${
|
|
2169
|
+
const rows = await sql3`
|
|
2170
|
+
SELECT value FROM ${sql3.unsafe(table.remediationExecutions)}
|
|
2171
|
+
WHERE tenant_id = ${requiredText2(tenantId, "Tenant id")}
|
|
2172
|
+
AND plan_id = ${requiredText2(planId, "Remediation plan id")}
|
|
1035
2173
|
ORDER BY started_at DESC, execution_id
|
|
1036
2174
|
LIMIT 1000
|
|
1037
2175
|
`;
|
|
@@ -1040,14 +2178,14 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1040
2178
|
save: async (tenantId, execution) => {
|
|
1041
2179
|
await ensureSchema();
|
|
1042
2180
|
const executionId = execution.id;
|
|
1043
|
-
if (!
|
|
2181
|
+
if (!Value2.Check(RemediationExecutionSchema2, execution))
|
|
1044
2182
|
throw new Error(`Remediation execution ${executionId} is invalid`);
|
|
1045
|
-
await
|
|
1046
|
-
INSERT INTO ${
|
|
2183
|
+
await sql3`
|
|
2184
|
+
INSERT INTO ${sql3.unsafe(table.remediationExecutions)} (
|
|
1047
2185
|
tenant_id, execution_id, plan_id, status, started_at, completed_at,
|
|
1048
2186
|
value, updated_at
|
|
1049
2187
|
) VALUES (
|
|
1050
|
-
${
|
|
2188
|
+
${requiredText2(tenantId, "Tenant id")}, ${execution.id},
|
|
1051
2189
|
${execution.planId}, ${execution.status},
|
|
1052
2190
|
${execution.startedAt}::timestamptz,
|
|
1053
2191
|
${execution.completedAt}::timestamptz,
|
|
@@ -1065,26 +2203,26 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1065
2203
|
};
|
|
1066
2204
|
const parseRemediationVerification = (value) => {
|
|
1067
2205
|
const verification = json(value, "Remediation verification");
|
|
1068
|
-
if (!
|
|
2206
|
+
if (!Value2.Check(RemediationVerificationSchema2, verification))
|
|
1069
2207
|
throw new Error("Stored remediation verification is invalid");
|
|
1070
2208
|
return verification;
|
|
1071
2209
|
};
|
|
1072
2210
|
const remediationVerifications = {
|
|
1073
2211
|
get: async (tenantId, verificationId) => {
|
|
1074
2212
|
await ensureSchema();
|
|
1075
|
-
const rows = await
|
|
1076
|
-
SELECT value FROM ${
|
|
1077
|
-
WHERE tenant_id = ${
|
|
1078
|
-
AND verification_id = ${
|
|
2213
|
+
const rows = await sql3`
|
|
2214
|
+
SELECT value FROM ${sql3.unsafe(table.remediationVerifications)}
|
|
2215
|
+
WHERE tenant_id = ${requiredText2(tenantId, "Tenant id")}
|
|
2216
|
+
AND verification_id = ${requiredText2(verificationId, "Remediation verification id")}
|
|
1079
2217
|
`;
|
|
1080
2218
|
return rows[0] ? parseRemediationVerification(rows[0].value) : null;
|
|
1081
2219
|
},
|
|
1082
2220
|
list: async (tenantId, executionId) => {
|
|
1083
2221
|
await ensureSchema();
|
|
1084
|
-
const rows = await
|
|
1085
|
-
SELECT value FROM ${
|
|
1086
|
-
WHERE tenant_id = ${
|
|
1087
|
-
AND execution_id = ${
|
|
2222
|
+
const rows = await sql3`
|
|
2223
|
+
SELECT value FROM ${sql3.unsafe(table.remediationVerifications)}
|
|
2224
|
+
WHERE tenant_id = ${requiredText2(tenantId, "Tenant id")}
|
|
2225
|
+
AND execution_id = ${requiredText2(executionId, "Remediation execution id")}
|
|
1088
2226
|
ORDER BY observed_at DESC, verification_id
|
|
1089
2227
|
LIMIT 1000
|
|
1090
2228
|
`;
|
|
@@ -1093,14 +2231,14 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1093
2231
|
save: async (tenantId, verification) => {
|
|
1094
2232
|
await ensureSchema();
|
|
1095
2233
|
const verificationId = verification.id;
|
|
1096
|
-
if (!
|
|
2234
|
+
if (!Value2.Check(RemediationVerificationSchema2, verification))
|
|
1097
2235
|
throw new Error(`Remediation verification ${verificationId} is invalid`);
|
|
1098
|
-
await
|
|
1099
|
-
INSERT INTO ${
|
|
2236
|
+
await sql3`
|
|
2237
|
+
INSERT INTO ${sql3.unsafe(table.remediationVerifications)} (
|
|
1100
2238
|
tenant_id, verification_id, execution_id, plan_id, status,
|
|
1101
2239
|
observed_at, value, updated_at
|
|
1102
2240
|
) VALUES (
|
|
1103
|
-
${
|
|
2241
|
+
${requiredText2(tenantId, "Tenant id")}, ${verification.id},
|
|
1104
2242
|
${verification.executionId}, ${verification.planId},
|
|
1105
2243
|
${verification.status}, ${verification.observedAt}::timestamptz,
|
|
1106
2244
|
${JSON.stringify(verification)}::jsonb, now()
|
|
@@ -1117,18 +2255,18 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1117
2255
|
};
|
|
1118
2256
|
const parseVexDecision = (value) => {
|
|
1119
2257
|
const decision = json(value, "VEX decision");
|
|
1120
|
-
if (!
|
|
2258
|
+
if (!Value2.Check(VexDecisionSchema2, decision))
|
|
1121
2259
|
throw new Error("Stored VEX decision is invalid");
|
|
1122
2260
|
return decision;
|
|
1123
2261
|
};
|
|
1124
2262
|
const saveVexDecisions = async (tenantId, decisions) => {
|
|
1125
2263
|
await ensureSchema();
|
|
1126
|
-
const normalizedTenantId =
|
|
2264
|
+
const normalizedTenantId = requiredText2(tenantId, "Tenant id");
|
|
1127
2265
|
if (decisions.length === 0)
|
|
1128
2266
|
return;
|
|
1129
2267
|
for (const decision of decisions) {
|
|
1130
2268
|
const decisionId = decision.id;
|
|
1131
|
-
if (!
|
|
2269
|
+
if (!Value2.Check(VexDecisionSchema2, decision))
|
|
1132
2270
|
throw new Error(`VEX decision ${decisionId} is invalid`);
|
|
1133
2271
|
}
|
|
1134
2272
|
const payload = JSON.stringify(decisions.map((decision) => ({
|
|
@@ -1140,8 +2278,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1140
2278
|
value: decision,
|
|
1141
2279
|
vulnerability_id: decision.vulnerabilityId
|
|
1142
2280
|
})));
|
|
1143
|
-
await
|
|
1144
|
-
INSERT INTO ${
|
|
2281
|
+
await sql3`
|
|
2282
|
+
INSERT INTO ${sql3.unsafe(table.vexDecisions)} (
|
|
1145
2283
|
tenant_id, decision_id, product_id, vulnerability_id, status,
|
|
1146
2284
|
created_at, expires_at, value, updated_at
|
|
1147
2285
|
)
|
|
@@ -1166,20 +2304,20 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1166
2304
|
const vexDecisions = {
|
|
1167
2305
|
get: async (tenantId, decisionId) => {
|
|
1168
2306
|
await ensureSchema();
|
|
1169
|
-
const rows = await
|
|
1170
|
-
SELECT value FROM ${
|
|
1171
|
-
WHERE tenant_id = ${
|
|
1172
|
-
AND decision_id = ${
|
|
2307
|
+
const rows = await sql3`
|
|
2308
|
+
SELECT value FROM ${sql3.unsafe(table.vexDecisions)}
|
|
2309
|
+
WHERE tenant_id = ${requiredText2(tenantId, "Tenant id")}
|
|
2310
|
+
AND decision_id = ${requiredText2(decisionId, "Decision id")}
|
|
1173
2311
|
`;
|
|
1174
2312
|
return rows[0] ? parseVexDecision(rows[0].value) : null;
|
|
1175
2313
|
},
|
|
1176
2314
|
list: async (filter) => {
|
|
1177
2315
|
await ensureSchema();
|
|
1178
|
-
const tenantId =
|
|
2316
|
+
const tenantId = requiredText2(filter.tenantId, "Tenant id");
|
|
1179
2317
|
const productId = filter.productId?.trim() || null;
|
|
1180
2318
|
const vulnerabilityId = filter.vulnerabilityId?.trim() || null;
|
|
1181
|
-
const rows = await
|
|
1182
|
-
SELECT value FROM ${
|
|
2319
|
+
const rows = await sql3`
|
|
2320
|
+
SELECT value FROM ${sql3.unsafe(table.vexDecisions)}
|
|
1183
2321
|
WHERE tenant_id = ${tenantId}
|
|
1184
2322
|
AND (${productId}::text IS NULL OR product_id = ${productId})
|
|
1185
2323
|
AND (${vulnerabilityId}::text IS NULL OR vulnerability_id = ${vulnerabilityId})
|
|
@@ -1193,7 +2331,7 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1193
2331
|
};
|
|
1194
2332
|
const parseVexApplication = (value) => {
|
|
1195
2333
|
const application = json(value, "VEX application");
|
|
1196
|
-
if (!
|
|
2334
|
+
if (!Value2.Check(VexFindingApplicationSchema2, application))
|
|
1197
2335
|
throw new Error("Stored VEX application is invalid");
|
|
1198
2336
|
return application;
|
|
1199
2337
|
};
|
|
@@ -1203,7 +2341,7 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1203
2341
|
return;
|
|
1204
2342
|
for (const application of applications) {
|
|
1205
2343
|
const findingId = application.findingId;
|
|
1206
|
-
if (!
|
|
2344
|
+
if (!Value2.Check(VexFindingApplicationSchema2, application))
|
|
1207
2345
|
throw new Error(`VEX application ${findingId} is invalid`);
|
|
1208
2346
|
}
|
|
1209
2347
|
const payload = JSON.stringify(applications.map((application) => ({
|
|
@@ -1214,8 +2352,8 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1214
2352
|
tenant_id: application.tenantId,
|
|
1215
2353
|
value: application
|
|
1216
2354
|
})));
|
|
1217
|
-
await
|
|
1218
|
-
INSERT INTO ${
|
|
2355
|
+
await sql3`
|
|
2356
|
+
INSERT INTO ${sql3.unsafe(table.vexApplications)} (
|
|
1219
2357
|
tenant_id, finding_id, decision_id, applied_at, ended_at, value,
|
|
1220
2358
|
updated_at
|
|
1221
2359
|
)
|
|
@@ -1238,10 +2376,10 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1238
2376
|
const vexApplications = {
|
|
1239
2377
|
get: async (tenantId, findingId) => {
|
|
1240
2378
|
await ensureSchema();
|
|
1241
|
-
const rows = await
|
|
1242
|
-
SELECT value FROM ${
|
|
1243
|
-
WHERE tenant_id = ${
|
|
1244
|
-
AND finding_id = ${
|
|
2379
|
+
const rows = await sql3`
|
|
2380
|
+
SELECT value FROM ${sql3.unsafe(table.vexApplications)}
|
|
2381
|
+
WHERE tenant_id = ${requiredText2(tenantId, "Tenant id")}
|
|
2382
|
+
AND finding_id = ${requiredText2(findingId, "Finding id")}
|
|
1245
2383
|
`;
|
|
1246
2384
|
return rows[0] ? parseVexApplication(rows[0].value) : null;
|
|
1247
2385
|
},
|
|
@@ -1255,12 +2393,12 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1255
2393
|
throw new Error("Feed lease ttlMs must be positive and finite");
|
|
1256
2394
|
const now = request.now ?? new Date;
|
|
1257
2395
|
const expiresAt = new Date(now.getTime() + request.ttlMs);
|
|
1258
|
-
const rows = await
|
|
1259
|
-
INSERT INTO ${
|
|
2396
|
+
const rows = await sql3`
|
|
2397
|
+
INSERT INTO ${sql3.unsafe(table.leases)} (
|
|
1260
2398
|
feed_id, owner_id, expires_at, updated_at
|
|
1261
2399
|
) VALUES (
|
|
1262
|
-
${
|
|
1263
|
-
${
|
|
2400
|
+
${requiredText2(request.feedId, "Feed lease feed id")},
|
|
2401
|
+
${requiredText2(request.ownerId, "Feed lease owner id")},
|
|
1264
2402
|
${expiresAt.toISOString()}::timestamptz,
|
|
1265
2403
|
${now.toISOString()}::timestamptz
|
|
1266
2404
|
)
|
|
@@ -1268,18 +2406,18 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1268
2406
|
owner_id = EXCLUDED.owner_id,
|
|
1269
2407
|
expires_at = EXCLUDED.expires_at,
|
|
1270
2408
|
updated_at = EXCLUDED.updated_at
|
|
1271
|
-
WHERE ${
|
|
1272
|
-
OR ${
|
|
2409
|
+
WHERE ${sql3.unsafe(table.leases)}.expires_at <= ${now.toISOString()}::timestamptz
|
|
2410
|
+
OR ${sql3.unsafe(table.leases)}.owner_id = EXCLUDED.owner_id
|
|
1273
2411
|
RETURNING owner_id
|
|
1274
2412
|
`;
|
|
1275
2413
|
return rows[0]?.owner_id === request.ownerId.trim();
|
|
1276
2414
|
},
|
|
1277
2415
|
release: async (feedId, ownerId) => {
|
|
1278
2416
|
await ensureSchema();
|
|
1279
|
-
const rows = await
|
|
1280
|
-
DELETE FROM ${
|
|
1281
|
-
WHERE feed_id = ${
|
|
1282
|
-
AND owner_id = ${
|
|
2417
|
+
const rows = await sql3`
|
|
2418
|
+
DELETE FROM ${sql3.unsafe(table.leases)}
|
|
2419
|
+
WHERE feed_id = ${requiredText2(feedId, "Feed lease feed id")}
|
|
2420
|
+
AND owner_id = ${requiredText2(ownerId, "Feed lease owner id")}
|
|
1283
2421
|
RETURNING feed_id
|
|
1284
2422
|
`;
|
|
1285
2423
|
return rows.length > 0;
|
|
@@ -1303,10 +2441,30 @@ var createPostgresVulnerabilityStore = (options) => {
|
|
|
1303
2441
|
};
|
|
1304
2442
|
};
|
|
1305
2443
|
export {
|
|
2444
|
+
vulnerabilityVexDecisions,
|
|
2445
|
+
vulnerabilityVexApplications,
|
|
2446
|
+
vulnerabilityRiskAssessments,
|
|
2447
|
+
vulnerabilityRemediationVerifications,
|
|
2448
|
+
vulnerabilityRemediationPlans,
|
|
2449
|
+
vulnerabilityRemediationExecutions,
|
|
1306
2450
|
vulnerabilityPostgresSchemaSql,
|
|
2451
|
+
vulnerabilityObservations,
|
|
2452
|
+
vulnerabilityFindings,
|
|
2453
|
+
vulnerabilityFeedSyncRuns,
|
|
2454
|
+
vulnerabilityFeedSnapshots,
|
|
2455
|
+
vulnerabilityFeedRecords,
|
|
2456
|
+
vulnerabilityFeedLeases,
|
|
2457
|
+
vulnerabilityCoreDrizzleSchema,
|
|
1307
2458
|
vulnerabilityAlertPostgresSchemaSql,
|
|
2459
|
+
vulnerabilityAlertPolicyVersions,
|
|
2460
|
+
vulnerabilityAlertIncidents,
|
|
2461
|
+
vulnerabilityAlertEvents,
|
|
2462
|
+
vulnerabilityAlertDrizzleSchema,
|
|
2463
|
+
vulnerabilityAlertDeliveries,
|
|
1308
2464
|
createPostgresVulnerabilityStore,
|
|
1309
2465
|
createPostgresVulnerabilityAlertStores,
|
|
2466
|
+
createDrizzleVulnerabilityStore,
|
|
2467
|
+
createDrizzleVulnerabilityAlertStores,
|
|
1310
2468
|
VulnerabilityAlertValidationError,
|
|
1311
2469
|
VulnerabilityAlertNotFoundError,
|
|
1312
2470
|
VulnerabilityAlertConflictError
|