Repository navigation
[SEC-A03] npm audit en CI (backend) #189
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
9e02802
SEC-A09: agregar logging de eventos de seguridad
DavidVillarM 3735c23
fix(SEC-A09): endurecer security logger tras review
DavidVillarM db5dbe5
fix(SEC-A09): resolver hallazgos SonarQube en security-logger
DavidVillarM e778b64
SEC-A03: enforce npm audit policy in backend CI
DavidVillarM 9373f61
fix(SEC-A03): apply backend CodeRabbit follow-ups
DavidVillarM 5691072
Merge branch 'dev' into OM-563
DavidVillarM c9440d2
Corregir merge de params en validate y alinear tests con dev
DavidVillarM File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| # Excepciones de npm audit | ||
|
|
||
| Este archivo documenta las excepciones permitidas para el control de seguridad en CI. | ||
|
|
||
| - Política activa: el pipeline falla con vulnerabilidades `high` o `critical`. | ||
| - Estado actual: no hay excepciones aprobadas. | ||
|
|
||
| Si en el futuro se requiere una excepción, debe: | ||
|
|
||
| 1. Agregarse en `security/audit-ci.json` dentro de `allowlist`. | ||
| 2. Documentarse aquí con: | ||
| - advisory/module afectado | ||
| - justificación | ||
| - fecha de aprobación | ||
| - fecha de expiración | ||
| - responsable |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| { | ||
| "$schema": "https://raw.githubusercontent.com/IBM/audit-ci/main/docs/schema.json", | ||
| "high": true, | ||
| "allowlist": [] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,147 @@ | ||
| const SENSITIVE_KEY_NAMES = [ | ||
| "password", | ||
| "password_hash", | ||
| "token", | ||
| "user_token", | ||
| "authorization", | ||
| "cookie", | ||
| "cookies", | ||
| "secret", | ||
| "jwt", | ||
| "refresh_token", | ||
| "access_token", | ||
| ]; | ||
|
|
||
| const JWT_PATTERN = /eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*/g; | ||
| const BEARER_PATTERN = /Bearer\s+\S+/gi; | ||
| const CONTROL_CHARS_PATTERN = /[\u0000-\u001F\u007F]/g; | ||
| const MAX_LOG_LINE_LENGTH = 8192; | ||
|
|
||
| /** | ||
| * Normaliza nombres de clave (camelCase, kebab-case) a snake_case en minúsculas. | ||
| */ | ||
| export function normalizeKey(key) { | ||
| if (typeof key !== "string") return ""; | ||
| return key | ||
| .replace(/([a-z0-9])([A-Z])/g, "$1_$2") | ||
| .replace(/-/g, "_") | ||
|
Check warning on line 27 in src/lib/security-logger.js
|
||
| .toLowerCase(); | ||
| } | ||
|
|
||
| const SENSITIVE_KEYS = new Set(SENSITIVE_KEY_NAMES.map(normalizeKey)); | ||
|
|
||
| function isSensitiveKey(key) { | ||
| return SENSITIVE_KEYS.has(normalizeKey(key)); | ||
| } | ||
|
|
||
| function sanitizeLogString(str) { | ||
| return str | ||
| .replace(CONTROL_CHARS_PATTERN, "") | ||
| .replace(JWT_PATTERN, "[REDACTED_JWT]") | ||
| .replace(BEARER_PATTERN, "Bearer [REDACTED]"); | ||
| } | ||
|
|
||
| /** | ||
| * Elimina datos sensibles antes de escribir en logs (tokens, passwords, etc.). | ||
| */ | ||
| export function sanitizeForLog(value, depth = 0) { | ||
| if (depth > 6) return "[MaxDepth]"; | ||
| if (value == null) return value; | ||
|
|
||
| if (typeof value === "string") { | ||
| return sanitizeLogString(value); | ||
| } | ||
|
|
||
| if (typeof value === "number" || typeof value === "boolean") { | ||
| return value; | ||
| } | ||
|
|
||
| if (Array.isArray(value)) { | ||
| return value.map((item) => sanitizeForLog(item, depth + 1)); | ||
| } | ||
|
|
||
| if (typeof value === "object") { | ||
| const sanitized = {}; | ||
| for (const [key, val] of Object.entries(value)) { | ||
| if (isSensitiveKey(key)) { | ||
| sanitized[key] = "[REDACTED]"; | ||
| } else { | ||
| sanitized[key] = sanitizeForLog(val, depth + 1); | ||
| } | ||
| } | ||
| return sanitized; | ||
| } | ||
|
|
||
| return String(value); | ||
| } | ||
|
|
||
| function stripReservedDetailKeys(details) { | ||
| if (details == null || typeof details !== "object" || Array.isArray(details)) { | ||
| return {}; | ||
| } | ||
|
|
||
| const safe = { ...details }; | ||
| delete safe.event; | ||
| delete safe.timestamp; | ||
| return safe; | ||
| } | ||
|
|
||
| /** | ||
| * Construye la línea JSON del evento tras sanitizar y validar el contenido. | ||
| */ | ||
| export function buildSecurityLogLine(eventType, details = {}) { | ||
| const payload = sanitizeForLog({ | ||
| ...stripReservedDetailKeys(details), | ||
| timestamp: new Date().toISOString(), | ||
| event: eventType, | ||
| }); | ||
|
|
||
| return JSON.stringify(payload); | ||
| } | ||
|
|
||
| function isValidSecurityLogLine(line) { | ||
| if (typeof line !== "string" || line.length === 0 || line.length > MAX_LOG_LINE_LENGTH) { | ||
| return false; | ||
| } | ||
|
|
||
| if (CONTROL_CHARS_PATTERN.test(line)) { | ||
| return false; | ||
| } | ||
|
|
||
| try { | ||
| JSON.parse(line); | ||
| return true; | ||
| } catch { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| function writeSecurityLogLine(line) { | ||
| process.stdout.write(`[SECURITY] ${line}\n`); | ||
| } | ||
|
|
||
| /** | ||
| * Registra un evento de seguridad en stdout (JSON). Nunca incluir passwords ni tokens. | ||
| * No lanza errores: fallos de logging no afectan el flujo de negocio. | ||
| */ | ||
| export function logSecurityEvent(eventType, details = {}) { | ||
| try { | ||
| if (typeof eventType !== "string" || eventType.length === 0) { | ||
| return; | ||
| } | ||
|
|
||
| const line = buildSecurityLogLine(eventType, details); | ||
| if (!isValidSecurityLogLine(line)) { | ||
| console.error("[SECURITY] Discarded invalid log line for event:", eventType); | ||
| return; | ||
| } | ||
|
|
||
| writeSecurityLogLine(line); | ||
| } catch (err) { | ||
| console.error( | ||
| "[SECURITY] Failed to log security event:", | ||
| eventType, | ||
| err?.message ?? err | ||
| ); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| import { logSecurityEvent } from "../lib/security-logger.js"; | ||
|
|
||
| /** | ||
| * Registra respuestas HTTP 403 al finalizar la petición (cubre AppError y errores legacy en controllers). | ||
| */ | ||
| export const securityResponseLogger = (req, res, next) => { | ||
| res.on("finish", () => { | ||
| if (res.statusCode !== 403) return; | ||
|
|
||
| try { | ||
| logSecurityEvent("FORBIDDEN", { | ||
| method: req.method, | ||
| path: req.originalUrl || req.path, | ||
| userId: req.user?.id_user ?? null, | ||
| role: req.user?.role ?? null, | ||
| }); | ||
| } catch (err) { | ||
| console.error("[SECURITY] Failed to log FORBIDDEN event:", err?.message ?? err); | ||
| } | ||
| }); | ||
|
|
||
| next(); | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.