HomeRoadmapsSecurity Day 4
Security Track Β· Day 4 Compliance Β· 20 min

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.

✨ Agent: Claude 3.7 Sonnet / Gemini 3.5 Β· 200K contextπŸ›‘οΈ AI SecOps & Red-Teaming Architect
ComplianceGDPRSOC2PII RedactionPolicy-as-CodeAudit Trails
About this lab

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.

πŸ“¦Sample Codebase & Working Solution (Day 4)Available Now
View on GitHub

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 β€” Working Solution
git clone https://github.com/letstrnsfrm-ai/security-compliance-roadmap.git
cd security-compliance-roadmap/day-4-compliance-soc2-gdpr
🏭Production Context & Enterprise Implementation
πŸ’‘ Why We Are Doing This: Plaintext PII logged to Datadog or CloudWatch violates GDPR Article 32 (security of processing) and incurs regulatory fines up to €20M or 4% of global turnover. SOC2 CC6.1 requires audit trails without exposing secret data.
🏒 Real-World Production Usecase: Automating CI/CD checks that parse mock production telemetry and assert that zero Credit Card numbers, Social Security numbers, or raw passwords leak into stdout or log aggregators.
βš™οΈ How Implemented in Production: Custom Winston/Pino logger transforms stripping regex-matched PII coupled with pre-merge compliance test assertions.
Phase 1

Simulate Insecure PII Logging in Checkout Flow

Inspect a realistic checkout endpoint in server.js that dumps complete payment payloads to console logs.

Step 1.1: Add Insecure Checkout Handler
server.js (Insecure Checkout Handler)
// 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
  });
});
Phase 2

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.

Step 2.1: Create lib/piiSanitizer.js
lib/piiSanitizer.js
// 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 };
Step 2.2: Refactor Checkout Handler
server.js (Compliant Checkout Handler)
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
  });
});
Phase 3

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.

Step 3.1: Write scripts/compliance-check.js
scripts/compliance-check.js
#!/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);
Phase 4

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.

Step 4.1: Run Compliance Gate
Terminal β€” Run Compliance Gate
node scripts/compliance-check.js
Step 4.2: Verify Telemetry Output
Compliance Gate Green Output
πŸ“‹ 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
Day 4 Key Learnings & Outcomes
  • 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?