Regulatory Compliance Checks (GDPR & SOC2)
Policy-as-Code & PII Scrubbing β Day 4
Audit application logs for plaintext PII, implement automated redaction middleware, and write Policy-as-Code compliance verification gates.
Security is not just about stopping external hackers; it is about guaranteeing regulatory privacy under GDPR, HIPAA, and SOC 2 Type II. In this lab, you will audit vulnerable-store-api for accidental logging of Personally Identifiable Information (PII), implement automated log masking middleware, and build an automated compliance gate.
The official reference codebase for Day 4 is hosted in the repository. Clone the repository and navigate to day-4-compliance-soc2-gdpr to run the working solution.
git clone https://github.com/letstrnsfrm-ai/security-compliance-roadmap.git
cd security-compliance-roadmap/day-4-compliance-soc2-gdprSimulate Insecure PII Logging in Checkout Flow
Inspect a realistic checkout endpoint in server.js that dumps complete payment payloads to console logs.
// Add to server.js
app.post('/api/checkout', (req, res) => {
const { userId, email, creditCard, cvv, amount } = req.body;
// β οΈ NON-COMPLIANT LOGGING: Writing raw PII to stdout/logs
console.log(`[AUDIT] Order processed for ${email}: Card=${creditCard}, CVV=${cvv}, Amount=$${amount}`);
res.status(200).json({
status: 'success',
transactionId: 'TX-' + Math.random().toString(36).substring(2, 9),
customerEmail: email,
receiptCard: creditCard // β οΈ NON-COMPLIANT RESPONSE: Exposing full card number
});
});Implement Automated PII Sanitization Middleware
Build a reusable sanitization layer that automatically intercepts logged strings and JSON payloads, masking credit card digits and stripping authentication tokens.
// lib/piiSanitizer.js
const CREDIT_CARD_REGEX = /\b(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13})\b/g;
const CVV_REGEX = /\b[0-9]{3,4}\b/g;
const SSN_REGEX = /\b\d{3}-\d{2}-\d{4}\b/g;
function maskCreditCard(cardNumber) {
const cleaned = String(cardNumber).replace(/\s|-/g, '');
if (cleaned.length < 10) return '***';
return '************' + cleaned.slice(-4);
}
function sanitizeLogMessage(message) {
if (typeof message !== 'string') return message;
return message
.replace(CREDIT_CARD_REGEX, (match) => maskCreditCard(match))
.replace(SSN_REGEX, '***-**-****');
}
function sanitizePayload(obj) {
if (!obj || typeof obj !== 'object') return obj;
const clone = Array.isArray(obj) ? [...obj] : { ...obj };
for (const key of Object.keys(clone)) {
const lowerKey = key.toLowerCase();
if (lowerKey.includes('card') || lowerKey.includes('pan')) {
clone[key] = maskCreditCard(clone[key]);
} else if (lowerKey.includes('cvv') || lowerKey.includes('password') || lowerKey.includes('secret')) {
clone[key] = '***REDACTED***';
} else if (typeof clone[key] === 'object') {
clone[key] = sanitizePayload(clone[key]);
}
}
return clone;
}
module.exports = { maskCreditCard, sanitizeLogMessage, sanitizePayload };const { sanitizeLogMessage, maskCreditCard } = require('./lib/piiSanitizer');
app.post('/api/checkout', (req, res) => {
const { email, creditCard, amount } = req.body;
// β
COMPLIANT: Log message sanitized before output
const rawLog = `[AUDIT] Order processed for ${email}: Card=${creditCard}, Amount=$${amount}`;
console.log(sanitizeLogMessage(rawLog));
res.status(200).json({
status: 'success',
transactionId: 'TX-' + Math.random().toString(36).substring(2, 9),
customerEmail: email,
receiptCard: maskCreditCard(creditCard) // β
Masked: ************1234
});
});Build Automated Compliance Gate Linter
Write an automated Policy-as-Code gate script (scripts/compliance-check.js) that exercises the checkout API, captures response headers and logs, and asserts zero PII leaks.
#!/usr/bin/env node
const { sanitizeLogMessage, sanitizePayload } = require('../lib/piiSanitizer');
console.log('π Running Automated GDPR & SOC2 Compliance Audit...');
// Test Case 1: Raw Log Scrubbing
const sampleLog = "Customer paid using 4111222233334444 with CVV 123";
const sanitized = sanitizeLogMessage(sampleLog);
if (sanitized.includes('4111222233334444')) {
console.error('π¨ GDPR VIOLATION: Unmasked credit card detected in log output!');
process.exit(1);
}
// Test Case 2: Payload Masking
const samplePayload = {
username: "testuser",
creditCard: "4111222233334444",
cvv: "999",
password: "PlaintextSecret!"
};
const masked = sanitizePayload(samplePayload);
if (masked.creditCard !== '************4444') {
console.error('π¨ SOC2 VIOLATION: Credit card failed to mask to last 4 digits.');
process.exit(1);
}
if (masked.password !== '***REDACTED***') {
console.error('π¨ SOC2 VIOLATION: Secret password was not redacted in payload.');
process.exit(1);
}
console.log('β
ALL COMPLIANCE CHECKS PASSED:');
console.log(' - GDPR Article 32 PII Data Minimization: Verified');
console.log(' - SOC 2 CC6.1 Audit Log Scrubbing: Verified');
process.exit(0);Execute Compliance Gate & Verify Zero Leaks
Run the compliance verification gate and confirm that all GDPR and SOC 2 checks pass with green exit status.
node scripts/compliance-check.jsπ Running Automated GDPR & SOC2 Compliance Audit...
β
ALL COMPLIANCE CHECKS PASSED:
- GDPR Article 32 PII Data Minimization: Verified
- SOC 2 CC6.1 Audit Log Scrubbing: Verified- Understood regulatory data compliance requirements under GDPR (Article 32) and SOC 2 (Trust Services Criteria CC6.1).
- Identified plaintext PII exposure risks in application stdout, error traces, and JSON response bodies.
- Implemented automated PII masking middleware (lib/piiSanitizer.js) with regex pattern matching.
- Authored an automated Policy-as-Code compliance test gate (scripts/compliance-check.js) that blocks PR merges upon PII leakage.
π§ Knowledge Check
Under SOC 2 Type II and GDPR regulations, what is the mandatory engineering standard for logging customer financial data?