import type { CatalogColumn, CatalogTable, WorkspaceDatabase } from "./types.js"; import { findPhoneNumbersInText } from "libphonenumber-js/max"; import validator from "validator"; export type SensitivityAssessment = "sensitive" | "non_sensitive"; export interface SensitivityEvidence { kind: "metadata" | "content" | "length" | "ner" | "coverage" | "type"; ruleId: string; label?: string; confidence?: number; } export interface SensitivityValueObservation { columnId: string; value: string | null; characterLength: number | null; } export interface SensitivityScanCoverage { kind: "complete" | "sampled"; observedValues: number; } export interface SensitivityTableScan { batches: readonly (readonly SensitivityValueObservation[])[]; coverage: SensitivityScanCoverage; } export interface SensitivityScanRequest { database: WorkspaceDatabase; table: CatalogTable; columns: readonly CatalogColumn[]; valuesPerColumn: number; sampleOffset: number; sampleSeed: number; queryTimeoutMs: number; fullScanThreshold?: number; } export interface SensitivityValueSource { scanTable( request: SensitivityScanRequest, consume: (batch: readonly SensitivityValueObservation[]) => void | Promise, signal: AbortSignal, ): Promise; } export interface LocalNerCandidate { columnId: string; text: string; } export interface LocalNerEvidence { columnId: string; label: string; confidence: number; } export interface SensitivityNerBudget { remainingMs: number; } /** Optional local detector. It returns evidence only; it never decides a column assessment. */ export interface LocalNerDetector { warmup?(): Promise; isReady?(): boolean; detect( candidates: readonly LocalNerCandidate[], signal: AbortSignal, deadline: number, ): Promise; close?(): Promise; } export interface SensitivityColumnAssessment { columnId: string; assessment: SensitivityAssessment; proposedSensitive: boolean; evidence: readonly SensitivityEvidence[]; observedValues: number; coverage: "metadata" | "complete" | "sampled" | "no_values"; } export interface SensitivityTableTarget { database: WorkspaceDatabase; table: CatalogTable; columns: readonly CatalogColumn[]; } const EMAIL = /(? = { "0": 1, "1": 0, "2": 5, "3": 7, "4": 9, "5": 13, "6": 15, "7": 17, "8": 19, "9": 21, A: 1, B: 0, C: 5, D: 7, E: 9, F: 13, G: 15, H: 17, I: 19, J: 21, K: 2, L: 4, M: 18, N: 20, O: 11, P: 3, Q: 6, R: 8, S: 12, T: 14, U: 16, V: 10, W: 22, X: 25, Y: 24, Z: 23, }; function validItalianFiscalCode(candidate: string): boolean { const value = candidate.toUpperCase(); if (value.length !== 16) return false; let sum = 0; for (let index = 0; index < 15; index += 1) { const character = value[index]!; if (index % 2 === 0) sum += FISCAL_ODD[character] ?? -1000; else sum += /\d/u.test(character) ? Number(character) : character.charCodeAt(0) - 65; } return String.fromCharCode(65 + (sum % 26)) === value[15]; } function validIban(candidate: string): boolean { const value = candidate.replace(/\s+/gu, "").toUpperCase(); if (!/^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$/u.test(value)) return false; const rearranged = value.slice(4) + value.slice(0, 4); let remainder = 0; for (const character of rearranged) { const digits = /\d/u.test(character) ? character : String(character.charCodeAt(0) - 55); for (const digit of digits) remainder = (remainder * 10 + Number(digit)) % 97; } return remainder === 1; } function validPaymentCard(candidate: string): boolean { const digits = candidate.replace(/[ -]/gu, ""); if (!/^\d{13,19}$/u.test(digits) || /^(\d)\1+$/u.test(digits)) return false; let sum = 0; let double = false; for (let index = digits.length - 1; index >= 0; index -= 1) { let digit = Number(digits[index]); if (double) { digit *= 2; if (digit > 9) digit -= 9; } sum += digit; double = !double; } return sum % 10 === 0; } function jsonHasSensitiveKey(value: string): boolean { const trimmed = value.trim(); if (!(trimmed.startsWith("{") || trimmed.startsWith("["))) return false; try { const pending: Array<{ value: unknown; depth: number }> = [{ value: JSON.parse(trimmed), depth: 0 }]; let visited = 0; while (pending.length > 0 && visited < 1_000) { const item = pending.pop()!; visited += 1; if (item.depth > 8 || item.value === null || typeof item.value !== "object") continue; if (Array.isArray(item.value)) { for (const child of item.value) pending.push({ value: child, depth: item.depth + 1 }); continue; } for (const [key, child] of Object.entries(item.value)) { if (sensitiveNameRule(key)) return true; pending.push({ value: child, depth: item.depth + 1 }); } } } catch { return false; } return false; } function contentEvidence(value: string): SensitivityEvidence | undefined { if (/-----BEGIN (?:[A-Z0-9]+ )?PRIVATE KEY-----/u.test(value)) { return { kind: "content", ruleId: "credential.private_key" }; } if (/(?:^|[^A-Z0-9])AKIA[A-Z0-9]{16}(?![A-Z0-9])/u.test(value) || /(?:^|[^A-Za-z0-9_])gh[pousr]_[A-Za-z0-9_]{30,}(?![A-Za-z0-9_])/u.test(value) || /(?:^|[^A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}(?![A-Za-z0-9_-])/u.test(value)) { return { kind: "content", ruleId: "credential.access_key" }; } if (/(?:^|[^\p{L}\p{N}_])(?:api[_ -]?key|access[_ -]?token|password|passwd|pwd|secret)\s*[:=]\s*[^\s,;]{4,}/iu.test(value)) { return { kind: "content", ruleId: "credential.key_value" }; } if (CLINICAL_TERM.test(value)) return { kind: "content", ruleId: "health.clinical_term" }; for (const match of value.matchAll(EMAIL)) { if (validator.isEmail(match[0])) return { kind: "content", ruleId: "pii.email" }; } for (const match of value.matchAll(ITALIAN_FISCAL_CODE)) { if (validItalianFiscalCode(match[0])) { return { kind: "content", ruleId: "pii.italian_fiscal_code" }; } } for (const match of value.matchAll(/\b(?:passaporto|passport)(?:\s+(?:numero|number|n\.?))?\s*[:#-]?\s*([A-Z0-9]{9})\b/giu)) { if (validator.isPassportNumber(match[1]!, "IT")) { return { kind: "content", ruleId: "pii.passport_number" }; } } for (const match of value.matchAll(/\bC[A-Z]\d{5}[A-Z]{2}\b/giu)) { if (validator.isIdentityCard(match[0], "IT")) { return { kind: "content", ruleId: "pii.identity_card" }; } } if (/\b(?:patente(?:\s+di\s+guida)?|driving\s+licen[cs]e)(?:\s+(?:numero|number|n\.?))?\s*[:#-]?\s*[A-Z0-9]{8,12}\b/iu.test(value)) { return { kind: "content", ruleId: "pii.drivers_license_number" }; } for (const match of value.matchAll(/(?"']+/giu)) { const candidate = match[0].replace(/[.,;:!?\])}]+$/u, ""); if (validator.isURL(candidate, { require_protocol: true })) { return { kind: "content", ruleId: "network.url" }; } } if (findPhoneNumbersInText(value, "IT").some((match) => match.number.isValid())) { return { kind: "content", ruleId: "pii.phone_number" }; } if (jsonHasSensitiveKey(value)) { return { kind: "content", ruleId: "pii.json_sensitive_key" }; } return undefined; } interface ColumnState { column: CatalogColumn; evidence: SensitivityEvidence[]; nonSensitiveEvidence?: SensitivityEvidence; observedValues: number; nerCandidates: string[]; coverage: "metadata" | "complete" | "sampled" | "no_values"; sampledTarget: number; } /** Sole decision module for local column-level sensitivity assessments. */ export class SensitivityClassifier { constructor( private readonly values: SensitivityValueSource, private readonly detector?: LocalNerDetector, private readonly options: { queryTimeoutMs?: number; nerConfidenceThreshold?: number; maxNerValuesPerColumn?: number; maxNerCandidatesPerTable?: number; now?: () => number; } = {}, ) {} async assess( targets: readonly SensitivityTableTarget[], signal: AbortSignal, sharedNerBudget?: SensitivityNerBudget, onActivity?: (message: string) => void | Promise, ): Promise { const now = this.options.now ?? Date.now; const maxNerValuesPerColumn = boundedCount(this.options.maxNerValuesPerColumn, 8, 8); const states = new Map(); for (const target of targets) { for (const column of target.columns) { const nonSensitiveEvidence = nonSensitiveStructuralEvidence(column); const metadataMatch = nonSensitiveEvidence ? undefined : metadataEvidence(column); const binary = !nonSensitiveEvidence && UNSUPPORTED_BINARY_TYPE.test(column.dataType); states.set(column.id, { column, evidence: metadataMatch ? [metadataMatch] : binary ? [{ kind: "type", ruleId: "type.binary_uninspectable" }] : [], ...(nonSensitiveEvidence ? { nonSensitiveEvidence } : {}), observedValues: 0, nerCandidates: [], coverage: nonSensitiveEvidence || metadataMatch || binary ? "metadata" : "no_values", sampledTarget: 0, }); } } const completeTables = new Set(); for (const [phaseIndex, phase] of SENSITIVITY_SAMPLE_PHASES.entries()) { for (let offset = 0; offset < targets.length; offset += MAX_CONCURRENT_TABLE_SCANS) { signal.throwIfAborted(); const batchNumber = Math.floor(offset / MAX_CONCURRENT_TABLE_SCANS) + 1; const batchCount = Math.ceil(targets.length / MAX_CONCURRENT_TABLE_SCANS); await onActivity?.( `Scanning source data: pass ${phaseIndex + 1} of ${SENSITIVITY_SAMPLE_PHASES.length}, table batch ${batchNumber} of ${batchCount}.`, ); signal.throwIfAborted(); const peerController = new AbortController(); const scanSignal = AbortSignal.any([signal, peerController.signal]); try { await Promise.all(targets.slice(offset, offset + MAX_CONCURRENT_TABLE_SCANS).map(async (target) => { if (completeTables.has(target.table.id)) return; const columns = target.columns.filter((column) => { const state = states.get(column.id)!; return state.evidence.length === 0 && !state.nonSensitiveEvidence && (!phase.deepTextOnly || DEEP_TEXT_TYPE.test(column.dataType)); }); if (columns.length === 0) return; const coverage = await this.values.scanTable({ ...target, columns, valuesPerColumn: phase.additionalValuesPerColumn, sampleOffset: phase.targetValuesPerColumn - phase.additionalValuesPerColumn, sampleSeed: phase.sampleSeed, queryTimeoutMs: this.options.queryTimeoutMs ?? 5_000, ...(phaseIndex === 0 ? { fullScanThreshold: 1_000 } : {}), }, (batch) => { for (const item of batch) { if (item.value === null) continue; const state = states.get(item.columnId); if (!state || state.evidence.length > 0) continue; state.observedValues += 1; if ((item.characterLength ?? item.value.length) > 500) { state.evidence.push({ kind: "length", ruleId: "text.over_500_characters" }); continue; } const match = contentEvidence(item.value); if (match) { state.evidence.push(match); continue; } if (state.nerCandidates.length < maxNerValuesPerColumn && !state.nerCandidates.includes(item.value)) { state.nerCandidates.push(item.value); } } }, scanSignal); for (const column of columns) { const state = states.get(column.id)!; state.sampledTarget = Math.max(state.sampledTarget, phase.targetValuesPerColumn); state.coverage = coverage.kind === "complete" ? "complete" : state.observedValues === 0 ? "no_values" : "sampled"; } if (coverage.kind === "complete") completeTables.add(target.table.id); })); } catch (error) { peerController.abort(error); throw error; } } } const nerBudget = sharedNerBudget ?? { remainingMs: 10_000 }; if (this.detector && (this.detector.isReady?.() ?? true) && !signal.aborted && nerBudget.remainingMs > 0) { const maxCandidates = boundedCount(this.options.maxNerCandidatesPerTable, 2, 1_024); const threshold = this.options.nerConfidenceThreshold ?? 0.8; for (const [targetIndex, target] of targets.entries()) { signal.throwIfAborted(); if (nerBudget.remainingMs <= 0) break; const candidates: LocalNerCandidate[] = []; candidateSelection: for (let valueIndex = 0; valueIndex < maxNerValuesPerColumn; valueIndex += 1) { for (const column of target.columns) { const state = states.get(column.id)!; if (state.evidence.length > 0 || state.nonSensitiveEvidence) continue; const text = state.nerCandidates[valueIndex]; if (text === undefined) continue; candidates.push({ columnId: column.id, text }); if (candidates.length >= maxCandidates) break candidateSelection; } } if (candidates.length === 0) continue; await onActivity?.( `Running local entity detection: table ${targetIndex + 1} of ${targets.length}.`, ); signal.throwIfAborted(); const startedAt = now(); const deadline = startedAt + nerBudget.remainingMs; try { for (let offset = 0; offset < candidates.length; offset += MAX_NER_CANDIDATES_PER_REQUEST) { if (signal.aborted || now() >= deadline) break; try { const detected = await this.detector.detect( candidates.slice(offset, offset + MAX_NER_CANDIDATES_PER_REQUEST), signal, deadline, ); for (const item of detected) { const state = states.get(item.columnId); if (!state || state.evidence.length > 0 || !Number.isFinite(item.confidence) || item.confidence < threshold || item.confidence > 1) continue; const label = normalizedName(item.label).slice(0, 80); if (!label) continue; state.evidence.push({ kind: "ner", ruleId: "ner.entity", label, confidence: item.confidence, }); } } catch { // NER is optional: deterministic findings and scan coverage remain authoritative. break; } } } finally { nerBudget.remainingMs = Math.max(0, nerBudget.remainingMs - Math.max(1, now() - startedAt)); } } } return targets.flatMap((target) => target.columns.map((column) => { const state = states.get(column.id)!; const sensitive = state.evidence.length > 0; const coverage = state.nonSensitiveEvidence ? "metadata" : state.observedValues === 0 && !sensitive ? "no_values" : state.coverage; const coverageEvidence: SensitivityEvidence[] = sensitive ? state.evidence : state.nonSensitiveEvidence ? [state.nonSensitiveEvidence] : [{ kind: "coverage", ruleId: coverage === "complete" ? "coverage.complete" : coverage === "no_values" ? "coverage.no_values" : `coverage.sampled_${state.sampledTarget}`, }]; return { columnId: column.id, assessment: sensitive ? "sensitive" : "non_sensitive", proposedSensitive: sensitive, evidence: coverageEvidence, observedValues: state.observedValues, coverage, }; })); } /** Convenience for focused callers and rule-level tests. Production orchestration uses assess(). */ async assessTable( target: SensitivityTableTarget, signal: AbortSignal, _retiredRunDeadline?: number, nerBudget?: SensitivityNerBudget, ): Promise { return await this.assess([target], signal, nerBudget); } }