Repository navigation
Sec a09 security logging #187
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
Merged
Changes from 11 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
81c2019
merge(dev): resolver conflicto SEC-A09 con cambios de sesión
DavidVillarM 9890dcf
test(SEC-A09): alinear tests de registro delivery con dev
DavidVillarM 2ccaca1
test: extraer helpers compartidos para bajar duplicación SonarQube
DavidVillarM 5e2b024
fix(delivery): unificar mensaje ZodError en status y perfil
DavidVillarM 3c3e9e0
test: reducir duplicacion Sonar bajo 3 por ciento
DavidVillarM b34f322
merge(dev): integrar SEC-A05 y fixes de validacion en SEC-A09
DavidVillarM d4278e1
fix(SEC-A09): aplicar sugerencias CodeRabbit de validacion
DavidVillarM 89356ec
fix(SEC-A09): auditar ORDER_STATUS_CHANGED y LOGIN_FAILED en login
DavidVillarM 48d5bc2
merge(dev): integrar OM-563 y SEC-A03 con SEC-A09
DavidVillarM 0616465
fix(product): validar tags CSV solo con digitos decimales
DavidVillarM 63ae65c
merge(dev): integrar banners, rate limiter y resolver conflicto deliv…
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,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 | ||
| .replaceAll(/([a-z0-9])([A-Z])/g, "$1_$2") | ||
| .replaceAll("-", "_") | ||
| .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 | ||
| .replaceAll(CONTROL_CHARS_PATTERN, "") | ||
| .replaceAll(JWT_PATTERN, "[REDACTED_JWT]") | ||
| .replaceAll(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
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
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.