diff --git a/CLAUDE.md b/CLAUDE.md index 9e3c05a..50924f2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -126,7 +126,13 @@ in `docs/adr/0001-event-bus-and-alerts.md`. - Names: `..`, snake_case, past participle (`code_report.analysis.completed`, `vault.secret.created`, `access.granted`). Declare each type - and its payload in `DomainEventMap` (`src/lib/server/events/types.ts`). + and its payload in `DomainEventMap` (`src/lib/events/domain-events.ts`, shared with the client). +- Every event needs an `EventDefinition` in the catalog (`src/lib/events/catalog/`, one + `.events.ts` per module): scope, `readPermission`, `alertable` and its filterable fields. + `EVENT_CATALOG` is exhaustive and field keys without `derive` are checked against the payload at + compile time. Labels are i18n keys (`events..label`, `.description`, + `.fields.`, `events.options..`) and must exist in `es.json` and `en.json` + (enforced by a test). - Publish only **after** the GitDB write succeeded, with the right `scope` (`organizationId` / `projectId`). `publish()` returns immediately; handlers run asynchronously, in order per subscriber, and a failing handler is only logged. diff --git a/src/lib/events/catalog/catalog.test.ts b/src/lib/events/catalog/catalog.test.ts new file mode 100644 index 0000000..4e155a9 --- /dev/null +++ b/src/lib/events/catalog/catalog.test.ts @@ -0,0 +1,184 @@ +import { describe, expect, it } from 'vitest'; +import es from '#lib/i18n/locales/es.json'; +import en from '#lib/i18n/locales/en.json'; +import type { CodeReportAnalysisCompletedPayload } from '../domain-events'; +import { + EVENT_CATALOG, + defineEventCatalog, + getEventDefinition, + getFieldValue, + isEventType, + listAlertableEvents, + type EventCatalog, + type EventDefinition, + type EventFieldDefinition, +} from './index'; + +function completedPayload( + overrides: Partial = {}, +): CodeReportAnalysisCompletedPayload { + return { + analysisId: 'analysis-1', + serviceId: 'service-1', + tool: 'trivy', + gitInfo: { repositoryUrl: null, branch: 'main', commit: 'abc', version: null }, + summary: { critical: 2, high: 1, medium: 0, low: 0, unknown: 0, total: 3, secrets: 0 }, + policies: { status: 'compliant', totalViolations: 0, blockingFailures: 0, failedPolicyIds: [] }, + ...overrides, + }; +} + +describe('event catalog: compile-time checks', () => { + it('rejects a field key that is not a path of the payload', () => { + const valid: EventFieldDefinition = { + key: 'gitInfo.branch', + label: 'x', + type: 'string', + operators: ['eq'], + }; + // @ts-expect-error 'gitInfo.tag' is not a path of the payload (and there is no `derive`) + const invalid: EventFieldDefinition = { + key: 'gitInfo.tag', + label: 'x', + type: 'string', + operators: ['eq'], + }; + const derived: EventFieldDefinition = { + key: 'anything', + label: 'x', + type: 'boolean', + operators: ['is_true'], + derive: (payload) => payload.summary.total > 0, + }; + + expect([valid.key, invalid.key, derived.key]).toHaveLength(3); + }); + + it('requires a definition for every event of DomainEventMap', () => { + const incomplete: Partial = { ...EVENT_CATALOG }; + delete incomplete['code_report.analysis.failed']; + // @ts-expect-error 'code_report.analysis.failed' is missing + const catalog: EventCatalog = incomplete; + + expect(Object.keys(catalog)).not.toContain('code_report.analysis.failed'); + }); +}); + +describe('defineEventCatalog', () => { + it('rejects an entry whose type does not match its key', () => { + const completed = EVENT_CATALOG['code_report.analysis.completed']; + expect(() => + defineEventCatalog({ + ...EVENT_CATALOG, + 'code_report.analysis.failed': { + ...completed, + } as unknown as EventDefinition<'code_report.analysis.failed'>, + }), + ).toThrow(/declares type/); + }); + + it('rejects duplicated field keys', () => { + const failed = EVENT_CATALOG['code_report.analysis.failed']; + expect(() => + defineEventCatalog({ + ...EVENT_CATALOG, + 'code_report.analysis.failed': { ...failed, fields: [...failed.fields, failed.fields[0]] }, + }), + ).toThrow(/twice/); + }); +}); + +describe('catalog helpers', () => { + it('looks up definitions and event types', () => { + expect(getEventDefinition('code_report.analysis.completed').readPermission).toBe( + 'project:codereport:reports:read', + ); + expect(isEventType('code_report.analysis.completed')).toBe(true); + expect(isEventType('code_report.analysis.unknown')).toBe(false); + expect(isEventType('toString')).toBe(false); + }); + + it('lists alertable events filtered by scope and module', () => { + const projectEvents = listAlertableEvents({ scope: 'project', module: 'code_report' }); + + expect(projectEvents.map((definition) => definition.type)).toContain( + 'code_report.analysis.completed', + ); + expect(listAlertableEvents({ scope: 'organization', module: 'code_report' })).toEqual([]); + }); + + it('reads nested payload paths', () => { + const event = { type: 'code_report.analysis.completed' as const, payload: completedPayload() }; + + expect(getFieldValue(event, 'gitInfo.branch')).toBe('main'); + expect(getFieldValue(event, 'summary.critical')).toBe(2); + expect(getFieldValue(event, 'serviceId')).toBe('service-1'); + }); + + it('computes derived fields', () => { + const clean = completedPayload({ + summary: { critical: 0, high: 0, medium: 0, low: 0, unknown: 0, total: 0, secrets: 0 }, + }); + const violated = completedPayload({ + policies: { + status: 'violated', + totalViolations: 2, + blockingFailures: 1, + failedPolicyIds: ['p'], + }, + }); + const type = 'code_report.analysis.completed' as const; + + expect(getFieldValue({ type, payload: completedPayload() }, 'hasVulnerabilities')).toBe(true); + expect(getFieldValue({ type, payload: clean }, 'hasVulnerabilities')).toBe(false); + expect(getFieldValue({ type, payload: clean }, 'policiesViolated')).toBe(false); + expect(getFieldValue({ type, payload: violated }, 'policiesViolated')).toBe(true); + }); + + it('returns undefined for unknown fields and missing paths', () => { + const type = 'code_report.analysis.completed' as const; + const payload = completedPayload({ gitInfo: null as never }); + + expect(getFieldValue({ type, payload }, 'gitInfo.branch')).toBeUndefined(); + // a real payload path that is not exposed in the catalog is not filterable + expect(getFieldValue({ type, payload }, 'analysisId')).toBeUndefined(); + }); +}); + +describe('catalog translations', () => { + function lookup(messages: unknown, key: string): unknown { + // keys may contain dots both as nesting and inside event types / field paths, so walk the + // object tree trying the longest matching segment first + if (key === '') return messages; + if (messages === null || typeof messages !== 'object') return undefined; + const record = messages as Record; + const segments = key.split('.'); + for (let length = segments.length; length > 0; length -= 1) { + const head = segments.slice(0, length).join('.'); + if (head in record) { + const found = lookup(record[head], segments.slice(length).join('.')); + if (found !== undefined) return found; + } + } + return undefined; + } + + function catalogKeys(): string[] { + return (Object.values(EVENT_CATALOG) as EventDefinition[]).flatMap((definition) => [ + definition.label, + definition.description, + ...definition.fields.flatMap((field) => [ + field.label, + ...(field.options ?? []).map((option) => option.label), + ]), + ]); + } + + it.each([ + ['es', es], + ['en', en], + ])('has a %s translation for every event, field and option', (_locale, messages) => { + const missing = catalogKeys().filter((key) => typeof lookup(messages, key) !== 'string'); + expect(missing).toEqual([]); + }); +}); diff --git a/src/lib/events/catalog/code-report.events.ts b/src/lib/events/catalog/code-report.events.ts new file mode 100644 index 0000000..29dc018 --- /dev/null +++ b/src/lib/events/catalog/code-report.events.ts @@ -0,0 +1,184 @@ +import { + SECURITY_POLICY_ENFORCEMENTS, + SECURITY_POLICY_TYPES, +} from '#lib/code-report/security-policy'; +import { OPERATORS, enumOptions, eventText, fieldLabel } from './fields'; +import type { EventDefinitions } from './types'; + +/** Tools that report analyses: scanners plus the manual upload and the CI/CD API defaults. */ +export const CODE_REPORT_TOOLS = [ + 'trivy', + 'grype', + 'semgrep', + 'gitleaks', + 'trufflehog', + 'sbom', + 'syft', + 'coverage', + 'manual-upload', + 'api', +] as const; + +const READ_REPORTS = 'project:codereport:reports:read'; + +const COMPLETED = 'code_report.analysis.completed'; +const FAILED = 'code_report.analysis.failed'; +const POLICY_VIOLATED = 'code_report.policy.violated'; +const SERVICE_CREATED = 'code_report.service.created'; +const SERVICE_DELETED = 'code_report.service.deleted'; + +function serviceField(type: typeof COMPLETED | typeof FAILED | typeof POLICY_VIOLATED) { + return { + key: 'serviceId', + label: fieldLabel(type, 'serviceId'), + type: 'reference', + reference: 'code_report_service', + operators: OPERATORS.reference, + } as const; +} + +function toolField(type: typeof COMPLETED | typeof FAILED | typeof POLICY_VIOLATED) { + return { + key: 'tool', + label: fieldLabel(type, 'tool'), + type: 'enum', + options: enumOptions('tool', CODE_REPORT_TOOLS), + operators: ['eq', 'neq', 'in'], + } as const; +} + +function branchField(type: typeof COMPLETED | typeof FAILED) { + return { + key: 'gitInfo.branch', + label: fieldLabel(type, 'gitInfo.branch'), + type: 'string', + operators: OPERATORS.string, + } as const; +} + +function countField( + key: K, +) { + return { + key, + label: fieldLabel(COMPLETED, key), + type: 'number', + operators: OPERATORS.number, + } as const; +} + +export const codeReportEvents: EventDefinitions< + | typeof COMPLETED + | typeof FAILED + | typeof POLICY_VIOLATED + | typeof SERVICE_CREATED + | typeof SERVICE_DELETED +> = { + [COMPLETED]: { + ...eventText(COMPLETED), + module: 'code_report', + scope: 'project', + readPermission: READ_REPORTS, + alertable: true, + fields: [ + serviceField(COMPLETED), + toolField(COMPLETED), + branchField(COMPLETED), + countField('summary.critical'), + countField('summary.high'), + countField('summary.medium'), + countField('summary.low'), + countField('summary.total'), + { + key: 'hasVulnerabilities', + label: fieldLabel(COMPLETED, 'hasVulnerabilities'), + type: 'boolean', + operators: OPERATORS.boolean, + derive: (payload) => payload.summary.total > 0, + }, + { + key: 'policiesViolated', + label: fieldLabel(COMPLETED, 'policiesViolated'), + type: 'boolean', + operators: OPERATORS.boolean, + derive: (payload) => payload.policies.status === 'violated', + }, + ], + }, + [FAILED]: { + ...eventText(FAILED), + module: 'code_report', + scope: 'project', + readPermission: READ_REPORTS, + alertable: true, + fields: [serviceField(FAILED), toolField(FAILED), branchField(FAILED)], + }, + [POLICY_VIOLATED]: { + ...eventText(POLICY_VIOLATED), + module: 'code_report', + scope: 'project', + readPermission: READ_REPORTS, + alertable: true, + fields: [ + serviceField(POLICY_VIOLATED), + { + key: 'policyId', + label: fieldLabel(POLICY_VIOLATED, 'policyId'), + type: 'reference', + reference: 'code_report_policy', + operators: OPERATORS.reference, + }, + { + key: 'policyType', + label: fieldLabel(POLICY_VIOLATED, 'policyType'), + type: 'enum', + options: enumOptions('policyType', SECURITY_POLICY_TYPES), + operators: OPERATORS.enum, + }, + { + key: 'enforcement', + label: fieldLabel(POLICY_VIOLATED, 'enforcement'), + type: 'enum', + options: enumOptions('enforcement', SECURITY_POLICY_ENFORCEMENTS), + operators: OPERATORS.enum, + }, + ], + }, + [SERVICE_CREATED]: { + ...eventText(SERVICE_CREATED), + module: 'code_report', + scope: 'project', + readPermission: READ_REPORTS, + alertable: true, + fields: [ + { + key: 'name', + label: fieldLabel(SERVICE_CREATED, 'name'), + type: 'string', + operators: OPERATORS.string, + }, + ], + }, + [SERVICE_DELETED]: { + ...eventText(SERVICE_DELETED), + module: 'code_report', + scope: 'project', + readPermission: READ_REPORTS, + alertable: true, + fields: [ + { + key: 'serviceId', + label: fieldLabel(SERVICE_DELETED, 'serviceId'), + type: 'reference', + reference: 'code_report_service', + operators: OPERATORS.reference, + }, + { + key: 'name', + label: fieldLabel(SERVICE_DELETED, 'name'), + type: 'string', + operators: OPERATORS.string, + }, + ], + }, +}; diff --git a/src/lib/events/catalog/fields.ts b/src/lib/events/catalog/fields.ts new file mode 100644 index 0000000..1ed6d7b --- /dev/null +++ b/src/lib/events/catalog/fields.ts @@ -0,0 +1,31 @@ +import type { EventType } from '../domain-events'; +import type { Operator } from './types'; + +/** Operator sets offered by the alert builder, per field type. */ +export const OPERATORS = { + reference: ['eq', 'neq', 'in', 'not_in'], + enum: ['eq', 'neq', 'in', 'not_in'], + string: ['eq', 'neq', 'contains', 'starts_with'], + number: ['eq', 'gt', 'gte', 'lt', 'lte'], + boolean: ['is_true', 'is_false'], + list: ['in', 'not_in'], +} as const satisfies Record; + +/** `label` and `description` i18n keys of an event. */ +export function eventText(type: K) { + return { + type, + label: `events.${type}.label`, + description: `events.${type}.description`, + } as const; +} + +/** i18n key of a field label. */ +export function fieldLabel(type: EventType, key: string): string { + return `events.${type}.fields.${key}`; +} + +/** Enum options whose labels live under `events.options..`. */ +export function enumOptions(group: string, values: readonly string[]) { + return values.map((value) => ({ value, label: `events.options.${group}.${value}` })); +} diff --git a/src/lib/events/catalog/index.ts b/src/lib/events/catalog/index.ts new file mode 100644 index 0000000..ec1379e --- /dev/null +++ b/src/lib/events/catalog/index.ts @@ -0,0 +1,85 @@ +import type { DomainEventMap, EventType } from '../domain-events'; +import { codeReportEvents } from './code-report.events'; +import type { + EventCatalog, + EventDefinition, + EventDefinitionScope, + EventFieldDefinition, + EventModule, +} from './types'; + +export type * from './types'; +export { OPERATORS } from './fields'; +export { CODE_REPORT_TOOLS } from './code-report.events'; + +/** + * Builds the catalog. The parameter type makes it exhaustive (every `DomainEventMap` entry needs a + * definition) and checks each field `key` without `derive` against its payload. + */ +export function defineEventCatalog(catalog: C): C { + for (const [type, definition] of Object.entries(catalog) as [string, EventDefinition][]) { + if (definition.type !== type) { + throw new Error(`Event catalog entry "${type}" declares type "${definition.type}"`); + } + const keys = definition.fields.map((field) => field.key); + const duplicate = keys.find((key, index) => keys.indexOf(key) !== index); + if (duplicate) { + throw new Error(`Event "${type}" declares field "${duplicate}" twice`); + } + } + return catalog; +} + +export const EVENT_CATALOG: EventCatalog = defineEventCatalog({ + ...codeReportEvents, +}); + +export function isEventType(value: string): value is EventType { + return Object.hasOwn(EVENT_CATALOG, value); +} + +export function getEventDefinition(type: K): EventDefinition { + return EVENT_CATALOG[type] as EventDefinition; +} + +/** Events offered in the alert builder, optionally narrowed by scope and module. */ +export function listAlertableEvents( + filter: { scope?: EventDefinitionScope; module?: EventModule } = {}, +): EventDefinition[] { + return (Object.values(EVENT_CATALOG) as EventDefinition[]).filter( + (definition) => + definition.alertable && + (!filter.scope || definition.scope === filter.scope) && + (!filter.module || definition.module === filter.module), + ); +} + +export function getFieldDefinition( + type: K, + fieldKey: string, +): EventFieldDefinition | undefined { + return getEventDefinition(type).fields.find((field) => field.key === fieldKey); +} + +/** + * Value of a catalog field for an event: `derive(payload)` for computed fields, the dotted path + * otherwise. `undefined` when the field is not in the catalog or the path is missing. + */ +export function getFieldValue( + event: { type: EventType; payload: unknown }, + fieldKey: string, +): unknown { + const field = getFieldDefinition(event.type, fieldKey) as EventFieldDefinition | undefined; + if (!field) return undefined; + if (field.derive) return field.derive(event.payload); + return readPath(event.payload, field.key as string); +} + +function readPath(source: unknown, path: string): unknown { + let current = source; + for (const segment of path.split('.')) { + if (current === null || typeof current !== 'object') return undefined; + current = (current as Record)[segment]; + } + return current; +} diff --git a/src/lib/events/catalog/types.ts b/src/lib/events/catalog/types.ts new file mode 100644 index 0000000..2ac06ff --- /dev/null +++ b/src/lib/events/catalog/types.ts @@ -0,0 +1,92 @@ +import type { PermissionGrant } from '#lib/permissions'; +import type { DomainEventMap, EventType } from '../domain-events'; + +export type FieldType = 'string' | 'number' | 'boolean' | 'enum' | 'date' | 'reference'; + +export type Operator = + // string, enum, reference + | 'eq' + | 'neq' + | 'in' + | 'not_in' + // string + | 'contains' + | 'starts_with' + // number, date + | 'gt' + | 'gte' + | 'lt' + | 'lte' + // boolean + | 'is_true' + | 'is_false' + | 'exists'; + +export type FieldReference = + | 'code_report_service' + | 'code_report_policy' + | 'project' + | 'user' + | 'role' + | 'vault_environment' + | 'api_key'; + +export type EventModule = 'code_report' | 'vault' | 'projects' | 'organization' | 'access'; + +export type EventDefinitionScope = 'organization' | 'project'; + +type Leaf = string | number | boolean | bigint | symbol | null | undefined | Date; + +/** + * Dotted paths to the fields of `T` (`'serviceId' | 'gitInfo' | 'gitInfo.branch' | ...`). Arrays + * are leaves (filtered with `in` / `not_in`). Limited depth keeps the type cheap. + */ +export type PayloadPath = Depth['length'] extends 4 + ? never + : T extends Leaf | readonly unknown[] + ? never + : { + [K in Extract]: NonNullable extends Leaf | readonly unknown[] + ? K + : K | `${K}.${PayloadPath, [...Depth, 1]>}`; + }[Extract]; + +type FieldCommon = { + /** i18n key, `events..fields.` */ + label: string; + type: FieldType; + /** Operators offered by the alert builder for this field. */ + operators: readonly Operator[]; + /** For `enum` fields; `label` is an i18n key. */ + options?: readonly { value: string; label: string }[]; + /** For `reference` fields: the UI lists these entities in the alert's scope; the id is stored. */ + reference?: FieldReference; +}; + +/** + * A filterable field. Without `derive`, `key` must be a path of the payload (checked at compile + * time). With `derive`, `key` is a computed name and the value comes from `derive(payload)`. + */ +export type EventFieldDefinition

= FieldCommon & + ({ key: PayloadPath

; derive?: undefined } | { key: string; derive: (payload: P) => unknown }); + +export type EventDefinition = { + type: K; + module: EventModule; + scope: EventDefinitionScope; + /** i18n key, `events..label` */ + label: string; + /** i18n key, `events..description` */ + description: string; + /** Needed to create alerts on this event and to receive them. */ + readPermission: PermissionGrant; + fields: readonly EventFieldDefinition[]; + /** `false`: internal use or system notifications only, not offered in the alert builder. */ + alertable: boolean; +}; + +/** Definitions for a subset of events (one module's file). */ +export type EventDefinitions = { [P in K]: EventDefinition

}; + +/** Every event of `DomainEventMap` must have a definition. */ +export type EventCatalog = EventDefinitions; diff --git a/src/lib/events/domain-events.ts b/src/lib/events/domain-events.ts new file mode 100644 index 0000000..b5a802a --- /dev/null +++ b/src/lib/events/domain-events.ts @@ -0,0 +1,78 @@ +/** + * Domain event payloads, shared by the server (bus, services, alert engine) and the client (alert + * builder UI). Type-only: keep this file free of server imports. + * + * Rules (docs/adr/0001-event-bus-and-alerts.md): names are `..` in + * snake_case with a past participle, and payloads never contain secrets (vault values, invitation + * or reset tokens/URLs, hashes, API keys). + */ + +export type CodeReportVulnerabilityCounts = { + critical: number; + high: number; + medium: number; + low: number; + unknown: number; + total: number; + /** Secrets detected by the scan (a count, never the matches). */ + secrets: number; +}; + +export type CodeReportEventGitInfo = { + repositoryUrl: string | null; + branch: string | null; + commit: string | null; + version: string | null; +}; + +export type CodeReportPolicyStatus = 'no_policies' | 'not_applicable' | 'compliant' | 'violated'; + +export type CodeReportAnalysisCompletedPayload = { + analysisId: string; + serviceId: string; + tool: string; + gitInfo: CodeReportEventGitInfo; + /** Counts computed server-side from the stored result. */ + summary: CodeReportVulnerabilityCounts; + policies: { + status: CodeReportPolicyStatus; + totalViolations: number; + blockingFailures: number; + failedPolicyIds: string[]; + }; +}; + +export type CodeReportAnalysisFailedPayload = { + analysisId: string; + serviceId: string; + tool: string; + gitInfo: CodeReportEventGitInfo; + error: string; +}; + +export type CodeReportPolicyViolatedPayload = { + analysisId: string; + serviceId: string; + tool: string; + policyId: string; + policyName: string; + policyType: string; + enforcement: 'warn' | 'block'; + violations: number; +}; + +export type CodeReportServicePayload = { + serviceId: string; + name: string; + slug: string; +}; + +export interface DomainEventMap { + 'code_report.analysis.completed': CodeReportAnalysisCompletedPayload; + 'code_report.analysis.failed': CodeReportAnalysisFailedPayload; + 'code_report.policy.violated': CodeReportPolicyViolatedPayload; + 'code_report.service.created': CodeReportServicePayload; + 'code_report.service.deleted': CodeReportServicePayload; +} + +export type EventType = Extract; diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index 355f7af..e214aab 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -948,5 +948,95 @@ "defaultRootLabel": "Projects", "select": "Select", "notAvailable": "N/A" + }, + "events": { + "code_report": { + "analysis": { + "completed": { + "label": "Analysis completed", + "description": "A scan tool finished analyzing a service.", + "fields": { + "serviceId": "Service", + "tool": "Tool", + "gitInfo": { + "branch": "Branch" + }, + "summary": { + "critical": "Critical vulnerabilities", + "high": "High vulnerabilities", + "medium": "Medium vulnerabilities", + "low": "Low vulnerabilities", + "total": "Total vulnerabilities" + }, + "hasVulnerabilities": "Has vulnerabilities", + "policiesViolated": "Violates security policies" + } + }, + "failed": { + "label": "Analysis failed", + "description": "A scan tool could not complete the analysis of a service.", + "fields": { + "serviceId": "Service", + "tool": "Tool", + "gitInfo": { + "branch": "Branch" + } + } + } + }, + "policy": { + "violated": { + "label": "Security policy violated", + "description": "A completed analysis violates a project security policy.", + "fields": { + "serviceId": "Service", + "policyId": "Policy", + "policyType": "Policy type", + "enforcement": "Enforcement" + } + } + }, + "service": { + "created": { + "label": "Service created", + "description": "A Code Report service was created.", + "fields": { + "name": "Name" + } + }, + "deleted": { + "label": "Service deleted", + "description": "A Code Report service was deleted.", + "fields": { + "serviceId": "Service", + "name": "Name" + } + } + } + }, + "options": { + "tool": { + "trivy": "Trivy", + "grype": "Grype", + "semgrep": "Semgrep", + "gitleaks": "Gitleaks", + "trufflehog": "TruffleHog", + "sbom": "SBOM", + "syft": "Syft", + "coverage": "Coverage", + "manual-upload": "Manual upload", + "api": "API" + }, + "policyType": { + "vulnerabilities": "Vulnerabilities", + "license": "Licenses", + "code_coverage": "Code coverage", + "secrets": "Secrets" + }, + "enforcement": { + "warn": "Warning", + "block": "Blocking" + } + } } } diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json index 6427c05..c5c0147 100644 --- a/src/lib/i18n/locales/es.json +++ b/src/lib/i18n/locales/es.json @@ -948,5 +948,95 @@ "defaultRootLabel": "Proyectos", "select": "Seleccionar", "notAvailable": "N/D" + }, + "events": { + "code_report": { + "analysis": { + "completed": { + "label": "Análisis completado", + "description": "Una herramienta de análisis ha terminado de analizar un servicio.", + "fields": { + "serviceId": "Servicio", + "tool": "Herramienta", + "gitInfo": { + "branch": "Rama" + }, + "summary": { + "critical": "Vulnerabilidades críticas", + "high": "Vulnerabilidades altas", + "medium": "Vulnerabilidades medias", + "low": "Vulnerabilidades bajas", + "total": "Total de vulnerabilidades" + }, + "hasVulnerabilities": "Tiene vulnerabilidades", + "policiesViolated": "Incumple políticas de seguridad" + } + }, + "failed": { + "label": "Análisis fallido", + "description": "Una herramienta de análisis no ha podido completar el análisis de un servicio.", + "fields": { + "serviceId": "Servicio", + "tool": "Herramienta", + "gitInfo": { + "branch": "Rama" + } + } + } + }, + "policy": { + "violated": { + "label": "Política de seguridad incumplida", + "description": "Un análisis completado incumple una política de seguridad del proyecto.", + "fields": { + "serviceId": "Servicio", + "policyId": "Política", + "policyType": "Tipo de política", + "enforcement": "Aplicación" + } + } + }, + "service": { + "created": { + "label": "Servicio creado", + "description": "Se ha creado un servicio en Code Report.", + "fields": { + "name": "Nombre" + } + }, + "deleted": { + "label": "Servicio eliminado", + "description": "Se ha eliminado un servicio de Code Report.", + "fields": { + "serviceId": "Servicio", + "name": "Nombre" + } + } + } + }, + "options": { + "tool": { + "trivy": "Trivy", + "grype": "Grype", + "semgrep": "Semgrep", + "gitleaks": "Gitleaks", + "trufflehog": "TruffleHog", + "sbom": "SBOM", + "syft": "Syft", + "coverage": "Cobertura", + "manual-upload": "Subida manual", + "api": "API" + }, + "policyType": { + "vulnerabilities": "Vulnerabilidades", + "license": "Licencias", + "code_coverage": "Cobertura de código", + "secrets": "Secretos" + }, + "enforcement": { + "warn": "Aviso", + "block": "Bloqueante" + } + } } } diff --git a/src/lib/server/events/types.ts b/src/lib/server/events/types.ts index f1168bd..dc0cea7 100644 --- a/src/lib/server/events/types.ts +++ b/src/lib/server/events/types.ts @@ -1,3 +1,5 @@ +import type { DomainEventMap } from '#lib/events/domain-events'; + /** * Domain event types. See `docs/adr/0001-event-bus-and-alerts.md` for the design and rules. * @@ -18,14 +20,10 @@ export type EventScope = { }; /** - * Event type → payload. Each module adds its events here (declaration merging is not used: add - * the entries directly so the whole catalog stays in one place). - * - * Payloads must never contain secrets: no vault values, invitation or reset tokens, hashes or - * API keys. + * Event type → payload. Declared in `#lib/events/domain-events` so the alert builder UI can share + * it without importing server code. */ -// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- filled in by #78 -export interface DomainEventMap {} +export type { DomainEventMap }; /** Event names of an event map. */ export type EventTypeOf = Extract; diff --git a/src/modules/code-report/application/code-report-analysis.service.test.ts b/src/modules/code-report/application/code-report-analysis.service.test.ts new file mode 100644 index 0000000..e406c6b --- /dev/null +++ b/src/modules/code-report/application/code-report-analysis.service.test.ts @@ -0,0 +1,260 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { runWithActor } from '#lib/server/request-context'; +import { RecordingEventBus } from '#lib/server/events/testing'; +import type { SecurityPolicy } from '#lib/code-report/security-policy'; +import { CodeReportAnalysisDomain } from '../domain/code-report-analysis.domain'; +import { CodeReportAnalysisService } from './code-report-analysis.service'; + +class FakeAnalysisRepository { + rows = new Map>(); + failUpdates = false; + + async findById(id: string) { + const row = this.rows.get(id); + return row ? new CodeReportAnalysisDomain(row) : null; + } + + async create(input: Record & { id: string }) { + this.rows.set(input.id, { ...input, createdAt: new Date(), updatedAt: new Date() }); + } + + async update(id: string, changes: Record) { + if (this.failUpdates) throw new Error('GitDB write failed'); + const defined = Object.fromEntries( + Object.entries(changes).filter(([, value]) => value !== undefined), + ); + this.rows.set(id, { ...this.rows.get(id), ...defined }); + } +} + +const SERVICE = { id: 'service-1', projectId: 'project-1', tags: [] }; + +const trivyResult = { + Results: [ + { + Target: 'package-lock.json', + Vulnerabilities: [ + { VulnerabilityID: 'CVE-1', PkgName: 'a', Severity: 'CRITICAL' }, + { VulnerabilityID: 'CVE-2', PkgName: 'b', Severity: 'HIGH' }, + { VulnerabilityID: 'CVE-3', PkgName: 'c', Severity: 'LOW' }, + ], + Secrets: [{ RuleID: 'aws-key', Match: 'AKIAIOSFODNN7EXAMPLE' }], + }, + ], +}; + +function policy(overrides: Partial = {}): SecurityPolicy { + return { + id: 'policy-1', + projectId: 'project-1', + slug: 'no-critical', + name: 'No critical', + description: null, + type: 'vulnerabilities', + enabled: true, + enforcement: 'block', + scope: { mode: 'all', services: [], tags: [] }, + rules: { + maxCritical: 0, + maxHigh: null, + maxMedium: null, + maxLow: null, + minCvssScore: null, + ignoreUnfixed: false, + maxAgeDays: null, + ignoredCves: [], + }, + createdAt: '2026-01-01', + updatedAt: '2026-01-01', + ...overrides, + }; +} + +describe('CodeReportAnalysisService events', () => { + let repository: FakeAnalysisRepository; + let events: RecordingEventBus; + let policies: SecurityPolicy[]; + let service: CodeReportAnalysisService; + + beforeEach(() => { + repository = new FakeAnalysisRepository(); + events = new RecordingEventBus(); + policies = []; + service = new CodeReportAnalysisService( + repository as never, + { findById: async (id) => (id === SERVICE.id ? SERVICE : null) }, + { listByProject: async () => policies }, + { + events, + projects: { getProject: async () => ({ organization: { id: 'org-1' } }) }, + }, + ); + }); + + it('publishes analysis.completed with server-side counts and the project scope', async () => { + const { id } = await service.startAnalysis({ + serviceId: SERVICE.id, + tool: 'trivy', + gitInfo: { branch: 'main', commit: 'abc123', commitMessage: 'fix', author: 'ana' }, + }); + + await service.completeAnalysis(id, { result: trivyResult }); + + expect(events.types()).toEqual(['code_report.analysis.completed']); + const [event] = events.ofType('code_report.analysis.completed'); + expect(event.scope).toEqual({ organizationId: 'org-1', projectId: 'project-1' }); + expect(event.payload).toEqual({ + analysisId: id, + serviceId: SERVICE.id, + tool: 'trivy', + gitInfo: { repositoryUrl: null, branch: 'main', commit: 'abc123', version: null }, + summary: { critical: 1, high: 1, medium: 0, low: 1, unknown: 0, total: 3, secrets: 1 }, + policies: { + status: 'no_policies', + totalViolations: 0, + blockingFailures: 0, + failedPolicyIds: [], + }, + }); + }); + + it('publishes one policy.violated per failed policy after analysis.completed', async () => { + policies = [ + policy(), + policy({ + id: 'policy-2', + slug: 'warn-high', + name: 'Warn high', + enforcement: 'warn', + rules: { ...policy().rules, maxCritical: null, maxHigh: 0 } as SecurityPolicy['rules'], + }), + policy({ + id: 'policy-3', + slug: 'ok', + name: 'Lenient', + rules: { ...policy().rules, maxCritical: 10 } as SecurityPolicy['rules'], + }), + ]; + const { id } = await service.startAnalysis({ serviceId: SERVICE.id, tool: 'trivy' }); + + await service.completeAnalysis(id, { result: trivyResult }); + + expect(events.types()).toEqual([ + 'code_report.analysis.completed', + 'code_report.policy.violated', + 'code_report.policy.violated', + ]); + expect(events.ofType('code_report.analysis.completed')[0].payload.policies).toEqual({ + status: 'violated', + totalViolations: 2, + blockingFailures: 1, + failedPolicyIds: ['policy-1', 'policy-2'], + }); + expect(events.ofType('code_report.policy.violated').map((event) => event.payload)).toEqual([ + { + analysisId: id, + serviceId: SERVICE.id, + tool: 'trivy', + policyId: 'policy-1', + policyName: 'No critical', + policyType: 'vulnerabilities', + enforcement: 'block', + violations: 1, + }, + expect.objectContaining({ policyId: 'policy-2', enforcement: 'warn', violations: 1 }), + ]); + }); + + it('publishes analysis.failed with the reason', async () => { + const { id } = await service.startAnalysis({ + serviceId: SERVICE.id, + tool: 'gitleaks', + gitInfo: { branch: 'feature/x' }, + }); + + await service.failAnalysis(id, { error: 'scanner crashed' }); + + expect(events.types()).toEqual(['code_report.analysis.failed']); + expect(events.ofType('code_report.analysis.failed')[0].payload).toEqual({ + analysisId: id, + serviceId: SERVICE.id, + tool: 'gitleaks', + gitInfo: { repositoryUrl: null, branch: 'feature/x', commit: null, version: null }, + error: 'scanner crashed', + }); + }); + + it('attributes CI/CD reports to the API key', async () => { + await runWithActor( + { + name: 'apikey:ci', + email: 'apikey+key-1@gitops.local', + apiKeyId: 'key-1', + apiKeyProjectId: 'project-1', + }, + () => + service.reportAnalysis({ serviceId: SERVICE.id, status: 'completed', result: trivyResult }), + ); + + expect(events.ofType('code_report.analysis.completed')[0].actor).toEqual({ + kind: 'api_key', + apiKeyId: 'key-1', + projectId: 'project-1', + }); + }); + + it('does not publish for in_progress reports', async () => { + await service.reportAnalysis({ serviceId: SERVICE.id, status: 'in_progress' }); + + expect(events.events).toEqual([]); + }); + + it('publishes nothing when the analysis does not exist or input is invalid', async () => { + await expect(service.completeAnalysis('missing', { result: {} })).rejects.toThrow(); + const { id } = await service.startAnalysis({ serviceId: SERVICE.id, tool: 'trivy' }); + await expect(service.completeAnalysis(id, { result: null })).rejects.toThrow(); + await expect(service.failAnalysis(id, { error: ' ' })).rejects.toThrow(); + + expect(events.events).toEqual([]); + }); + + it('publishes nothing when the GitDB write fails', async () => { + const { id } = await service.startAnalysis({ serviceId: SERVICE.id, tool: 'trivy' }); + repository.failUpdates = true; + + await expect(service.completeAnalysis(id, { result: trivyResult })).rejects.toThrow(); + await expect(service.failAnalysis(id, { error: 'boom' })).rejects.toThrow(); + + expect(events.events).toEqual([]); + }); + + it('never fails the request when publishing fails', async () => { + const throwing = new CodeReportAnalysisService( + repository as never, + { findById: async () => SERVICE }, + undefined, + { + events: { + publish: () => { + throw new Error('bus down'); + }, + }, + }, + ); + const { id } = await throwing.startAnalysis({ serviceId: SERVICE.id, tool: 'trivy' }); + + await expect(throwing.completeAnalysis(id, { result: trivyResult })).resolves.toMatchObject({ + status: 'completed', + }); + }); + + it('never includes the scan result or secret matches in the payload', async () => { + const { id } = await service.startAnalysis({ serviceId: SERVICE.id, tool: 'trivy' }); + + await service.completeAnalysis(id, { result: trivyResult }); + + const serialized = JSON.stringify(events.events); + expect(serialized).not.toContain('AKIAIOSFODNN7EXAMPLE'); + expect(serialized).not.toContain('CVE-1'); + }); +}); diff --git a/src/modules/code-report/application/code-report-analysis.service.ts b/src/modules/code-report/application/code-report-analysis.service.ts index 623317c..986f08b 100644 --- a/src/modules/code-report/application/code-report-analysis.service.ts +++ b/src/modules/code-report/application/code-report-analysis.service.ts @@ -2,11 +2,21 @@ import crypto from 'crypto'; import { CodeReportAnalysisRepository } from '../infrastructure/repositories/code-report-analysis.repository'; import type { CodeReportAnalysisDomain } from '../domain/code-report-analysis.domain'; import type { CodeReportGitInfo } from '../domain/code-report-analysis.domain'; -import { extractSecrets, extractVulnerabilities } from '#lib/code-report/analysis-summary'; +import { + extractSecrets, + extractVulnerabilities, + summarizeAnalysisResult, +} from '#lib/code-report/analysis-summary'; import { evaluatePolicies, type PolicyComplianceReport } from '#lib/code-report/policy-evaluation'; import type { SecurityPolicy } from '#lib/code-report/security-policy'; import { TOOL_POLICY_TYPES, DEFAULT_POLICY_TYPES } from '../domain/tool-policy-types.data'; import { createLogger } from '#lib/server/logger'; +import { + eventGitInfo, + resolveProjectScope, + type CodeReportEventPublisher, + type ProjectScopeLookup, +} from './code-report-events'; const log = createLogger('code-report-analysis'); @@ -18,12 +28,24 @@ type PolicyLookup = { listByProject(projectId: string): Promise; }; +type AnalysisEventsOptions = { + events?: CodeReportEventPublisher; + projects?: ProjectScopeLookup; +}; + export class CodeReportAnalysisService { + private readonly events?: CodeReportEventPublisher; + private readonly projects?: ProjectScopeLookup; + constructor( private readonly repository: CodeReportAnalysisRepository, private readonly serviceLookup: ServiceLookup, private readonly policyLookup?: PolicyLookup, - ) {} + options: AnalysisEventsOptions = {}, + ) { + this.events = options.events; + this.projects = options.projects; + } async listByService(serviceId: string) { const analyses = await this.repository.findByServiceId(serviceId); @@ -112,18 +134,116 @@ export class CodeReportAnalysisService { throw new Error('Result is required to complete an analysis'); } + const securityPolicies = await this.evaluateSecurityPolicies( + analysis.serviceId, + analysis.tool, + input.result, + ); + const gitInfo = this.resolveGitInfo(analysis.gitInfo, input.gitInfo, input.result); + await this.repository.update(id, { status: 'completed', result: input.result, summary: input.summary, - securityPolicies: await this.evaluateSecurityPolicies(analysis.serviceId, analysis.tool, input.result), - gitInfo: this.resolveGitInfo(analysis.gitInfo, input.gitInfo, input.result), + securityPolicies, + gitInfo, error: null, }); + await this.publishCompleted( + { id, serviceId: analysis.serviceId, tool: analysis.tool }, + input.result, + gitInfo, + securityPolicies, + ); + return this.getById(id); } + // events never break the write that already succeeded: failures are only logged + private async publishCompleted( + analysis: { id: string; serviceId: string; tool: string }, + result: unknown, + gitInfo: CodeReportGitInfo | undefined, + report: PolicyComplianceReport | null, + ) { + if (!this.events) return; + try { + const scope = await this.scopeForService(analysis.serviceId); + const counts = summarizeAnalysisResult(result); + + this.events.publish( + 'code_report.analysis.completed', + { + analysisId: analysis.id, + serviceId: analysis.serviceId, + tool: analysis.tool, + gitInfo: eventGitInfo(gitInfo), + summary: { + ...counts.vulnerabilities, + total: counts.totalVulnerabilities, + secrets: counts.exposedSecrets, + }, + policies: { + status: report?.status ?? 'no_policies', + totalViolations: report?.totalViolations ?? 0, + blockingFailures: report?.blockingFailures ?? 0, + failedPolicyIds: report?.failed.map((evaluation) => evaluation.policyId) ?? [], + }, + }, + { scope }, + ); + + for (const evaluation of report?.failed ?? []) { + this.events.publish( + 'code_report.policy.violated', + { + analysisId: analysis.id, + serviceId: analysis.serviceId, + tool: analysis.tool, + policyId: evaluation.policyId, + policyName: evaluation.policyName, + policyType: evaluation.type, + enforcement: evaluation.enforcement, + violations: evaluation.violations.length, + }, + { scope }, + ); + } + } catch (error) { + log.error({ err: error, analysisId: analysis.id }, 'failed to publish analysis events'); + } + } + + private async publishFailed( + analysis: { id: string; serviceId: string; tool: string }, + gitInfo: CodeReportGitInfo | null | undefined, + error: string, + ) { + if (!this.events) return; + try { + const scope = await this.scopeForService(analysis.serviceId); + this.events.publish( + 'code_report.analysis.failed', + { + analysisId: analysis.id, + serviceId: analysis.serviceId, + tool: analysis.tool, + gitInfo: eventGitInfo(gitInfo), + error, + }, + { scope }, + ); + } catch (publishError) { + log.error({ err: publishError, analysisId: analysis.id }, 'failed to publish analysis events'); + } + } + + private async scopeForService(serviceId: string) { + const service = await this.serviceLookup.findById(serviceId); + return resolveProjectScope(service?.projectId, this.projects); + } + private resolveGitInfo( current: CodeReportGitInfo | null | undefined, incoming: CodeReportGitInfo | null | undefined, @@ -232,6 +352,8 @@ export class CodeReportAnalysisService { gitInfo: input.gitInfo, }); + await this.publishFailed(analysis, input.gitInfo ?? analysis.gitInfo, error); + return this.getById(id); } diff --git a/src/modules/code-report/application/code-report-events.ts b/src/modules/code-report/application/code-report-events.ts new file mode 100644 index 0000000..2f60b2e --- /dev/null +++ b/src/modules/code-report/application/code-report-events.ts @@ -0,0 +1,32 @@ +import type { EventBus, EventScope } from '#lib/server/events'; +import type { CodeReportEventGitInfo } from '#lib/events/domain-events'; +import type { CodeReportGitInfo } from '../domain/code-report-analysis.domain'; + +/** What the code-report services need from the bus. */ +export type CodeReportEventPublisher = Pick; + +/** Project lookup used to add the organization to the event scope. */ +export type ProjectScopeLookup = { + getProject(id: string): Promise<{ organization?: { id: string } | null }>; +}; + +export async function resolveProjectScope( + projectId: string | null | undefined, + projects: ProjectScopeLookup | undefined, +): Promise { + if (!projectId) return { organizationId: null, projectId: null }; + const project = projects ? await projects.getProject(projectId).catch(() => null) : null; + return { organizationId: project?.organization?.id ?? null, projectId }; +} + +/** Only the identifying git fields travel in events (no commit messages or author emails). */ +export function eventGitInfo( + gitInfo: CodeReportGitInfo | null | undefined, +): CodeReportEventGitInfo { + return { + repositoryUrl: gitInfo?.repositoryUrl ?? null, + branch: gitInfo?.branch ?? null, + commit: gitInfo?.commit ?? null, + version: gitInfo?.version ?? null, + }; +} diff --git a/src/modules/code-report/application/code-report.service.test.ts b/src/modules/code-report/application/code-report.service.test.ts new file mode 100644 index 0000000..e986b2c --- /dev/null +++ b/src/modules/code-report/application/code-report.service.test.ts @@ -0,0 +1,91 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { RecordingEventBus } from '#lib/server/events/testing'; +import { CodeReportServiceDomain } from '../domain/code-report-service.domain'; +import { CodeReportService } from './code-report.service'; + +class FakeServiceRepository { + rows: CodeReportServiceDomain[] = []; + + async findById(id: string) { + return this.rows.find((row) => row.id === id) ?? null; + } + + async findBySlug(projectId: string, slug: string) { + return this.rows.find((row) => row.projectId === projectId && row.slug === slug) ?? null; + } + + async create(input: Record) { + this.rows.push(new CodeReportServiceDomain(input)); + } + + async deleteById(id: string) { + this.rows = this.rows.filter((row) => row.id !== id); + } +} + +const PROJECT = { id: 'project-1', slug: 'shop', organization: { id: 'org-1' } }; + +const projectService = { + getProjectBySlug: async (slug: string) => (slug === PROJECT.slug ? PROJECT : null), + getProject: async (id: string) => { + if (id !== PROJECT.id) throw new Error('Project not found'); + return PROJECT; + }, +}; + +describe('CodeReportService events', () => { + let repository: FakeServiceRepository; + let events: RecordingEventBus; + let service: CodeReportService; + + beforeEach(() => { + repository = new FakeServiceRepository(); + events = new RecordingEventBus(); + service = new CodeReportService( + repository as never, + projectService as never, + { deleteAllByService: async () => {} }, + events, + ); + }); + + it('publishes service.created with the project scope', async () => { + const created = await service.createService({ project: 'shop', name: 'API Gateway' }); + + expect(events.types()).toEqual(['code_report.service.created']); + const [event] = events.ofType('code_report.service.created'); + expect(event.payload).toEqual({ + serviceId: created.id, + name: 'API Gateway', + slug: 'api-gateway', + }); + expect(event.scope).toEqual({ organizationId: 'org-1', projectId: 'project-1' }); + }); + + it('publishes service.deleted after deleting', async () => { + const created = await service.createService({ project: 'shop', name: 'API Gateway' }); + events.clear(); + + await service.deleteService(created.id); + + expect(events.ofType('code_report.service.deleted').map((event) => event.payload)).toEqual([ + { serviceId: created.id, name: 'API Gateway', slug: 'api-gateway' }, + ]); + expect(events.ofType('code_report.service.deleted')[0].scope).toEqual({ + organizationId: 'org-1', + projectId: 'project-1', + }); + }); + + it('publishes nothing when creation or deletion is rejected', async () => { + await expect(service.createService({ project: 'missing', name: 'API' })).rejects.toThrow(); + await service.createService({ project: 'shop', name: 'API' }); + events.clear(); + await expect(service.createService({ project: 'shop', name: 'API' })).rejects.toThrow( + /already exists/, + ); + await expect(service.deleteService('missing')).rejects.toThrow(); + + expect(events.events).toEqual([]); + }); +}); diff --git a/src/modules/code-report/application/code-report.service.ts b/src/modules/code-report/application/code-report.service.ts index 7c867e4..49df39e 100644 --- a/src/modules/code-report/application/code-report.service.ts +++ b/src/modules/code-report/application/code-report.service.ts @@ -2,6 +2,10 @@ import crypto from 'crypto'; import { CodeReportServiceRepository } from '../infrastructure/repositories/code-report-service.repository'; import { ProjectService } from '../../projects/application/project.service'; import { DEFAULT_RISK_WEIGHTS, type RiskWeights } from '../domain/risk-weights.data'; +import { createLogger } from '#lib/server/logger'; +import { resolveProjectScope, type CodeReportEventPublisher } from './code-report-events'; + +const log = createLogger('code-report'); export type VulnerabilityTotals = { critical: number; @@ -19,6 +23,7 @@ export class CodeReportService { private readonly repository: CodeReportServiceRepository, private readonly projectService: ProjectService, private readonly analysisCleanup?: AnalysisCleanup, + private readonly events?: CodeReportEventPublisher, ) {} async listByProject(projectId: string) { @@ -122,6 +127,12 @@ export class CodeReportService { throw new Error('Failed to create service'); } + this.events?.publish( + 'code_report.service.created', + { serviceId: created.id, name: created.name, slug: created.slug }, + { scope: { organizationId: project.organization?.id ?? null, projectId } }, + ); + return created.toJson(); } @@ -176,6 +187,19 @@ export class CodeReportService { } await this.analysisCleanup?.deleteAllByService(id); await this.repository.deleteById(id); + + if (this.events) { + try { + const scope = await resolveProjectScope(service.projectId, this.projectService); + this.events.publish( + 'code_report.service.deleted', + { serviceId: service.id, name: service.name, slug: service.slug }, + { scope }, + ); + } catch (error) { + log.error({ err: error, serviceId: id }, 'failed to publish service deleted event'); + } + } } private normalizeTags(tags?: string[]): string[] { diff --git a/src/modules/code-report/index.ts b/src/modules/code-report/index.ts index 5b129fd..59356f9 100644 --- a/src/modules/code-report/index.ts +++ b/src/modules/code-report/index.ts @@ -6,6 +6,7 @@ import { CodeReportServiceRepository } from './infrastructure/repositories/code- import { CodeReportAnalysisRepository } from './infrastructure/repositories/code-report-analysis.repository'; import { CodeReportSecurityPolicyRepository } from './infrastructure/repositories/code-report-security-policy.repository'; import { projectService } from '../projects'; +import { eventBus } from '#lib/server/events'; const codeReportServiceRepository = new CodeReportServiceRepository(); const codeReportAnalysisRepository = new CodeReportAnalysisRepository(); @@ -18,11 +19,13 @@ export const codeReportAnalysisService = new CodeReportAnalysisService( codeReportAnalysisRepository, codeReportServiceRepository, codeReportSecurityPolicyService, + { events: eventBus, projects: projectService }, ); export const codeReportService = new CodeReportService( codeReportServiceRepository, projectService, codeReportAnalysisService, + eventBus, ); export const codeReportCveService = new CodeReportCveService( codeReportService,