This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: gdpr-hipaa-pii-masking

PII Data Sanitization & Log Masking Compliance Standard

GDPR, HIPAA, and SOC2 compliant data sanitization discipline. Forbids logging plaintext Personally Identifiable Information (PII) including passwords, credit card numbers, national IDs, and JWT tokens; mandates deep recursive redaction.

Prohibited Anti-Pattern: AI logs raw request bodies, database entities, or error dumps containing cleartext passwords and user PII.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PII Data Sanitization & Log Masking Compliance Standard - GDPR, HIPAA, and SOC2 compliant data sanitization discipline. Forbids logging plaintext Personally Identifiable Information (PII) including passwords, credit card numbers, national IDs, and JWT tokens; mandates deep recursive redaction.
globs: **/*logger*.ts, **/*audit*.ts, **/*logging*.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/gdpr-hipaa-pii-masking"
---

# PII Data Sanitization & Log Masking Compliance Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: AI logs raw request bodies, database entities, or error dumps containing cleartext passwords and user PII.

## System Constraints
You are a regulatory compliance and data privacy specialist. When writing logging or telemetry code, NEVER dump raw request payloads or error objects to stdout or external APMs without deep PII redaction. Passwords, auth headers, credit cards, SSNs, and private tokens must be redacted with [REDACTED].

## Strict Guidelines
- Never log raw request bodies (e.g. logger.info(req.body)); filter through a recursive PII sanitizer before serialization.
- Redact high-risk fields: password, token, secret, authorization, creditCard, ssn, nationalId, and apiKey.
- Ensure Sentry and third-party error trackers enable `beforeSend` hooks to scrub user emails and IPs from crash reports.
- Apply AES-256 field-level encryption for sensitive PII columns stored in relational and NoSQL databases.

## Bad vs Good Implementations
### Recursive PII Redaction Logger vs Hazardous Plaintext Logging

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Plaintext credentials and PII logged to disk or external APMs expose user accounts to log-monitoring breaches and severe regulatory fines.
```typescript
// ANTI-PATTERN: Cleartext payload dumping (Major GDPR / SOC2 Violation!)
app.post("/api/users/login", async (req, res) => {
  // CRITICAL AUDIT FAILURE: Writes plaintext passwords directly to CloudWatch / Datadog!
  console.log("Incoming login request payload:", req.body);
  // ...
});
```

#### Production Standard (Correct)
> **Standard**: Automatically and recursively replaces sensitive keys with [REDACTED], ensuring log records remain 100% compliant with privacy regulations.
```typescript
// PRODUCTION STANDARD: Recursive Deep Redaction Middleware & Logger
import pino from "pino";

const PII_DENYLIST = [
  "password",
  "passwordConfirmation",
  "secret",
  "token",
  "authorization",
  "creditCard",
  "cardNumber",
  "cvv",
  "ssn",
];

export function maskPii(obj: any): any {
  if (obj === null || typeof obj !== "object") return obj;
  if (Array.isArray(obj)) return obj.map(maskPii);

  const sanitized: Record<string, any> = {};
  for (const [key, val] of Object.entries(obj)) {
    if (PII_DENYLIST.some((deny) => key.toLowerCase().includes(deny.toLowerCase()))) {
      sanitized[key] = "[REDACTED]";
    } else if (typeof val === "object") {
      sanitized[key] = maskPii(val);
    } else {
      sanitized[key] = val;
    }
  }
  return sanitized;
}

export const logger = pino({
  formatters: {
    log(obj) {
      return maskPii(obj);
    },
  },
});
```

### Sentry beforeSend PII Scrubbing

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Sentry error breadcrumbs capture HTTP headers including Authorization: Bearer tokens.
```typescript
// ANTI-PATTERN: Default Sentry config sending full user IP and headers
Sentry.init({ dsn: "..." }); // Sends cleartext auth headers in breadcrumbs!
```

#### Production Standard (Correct)
> **Standard**: Strips authorization tokens and client IPs from error crash traces before sending to Sentry servers.
```typescript
// PRODUCTION STANDARD: Sentry beforeSend Header & IP Stripping
Sentry.init({
  dsn: process.env.SENTRY_DSN,
  sendDefaultPii: false,
  beforeSend(event) {
    if (event.request?.headers) {
      delete event.request.headers["authorization"];
      delete event.request.headers["cookie"];
    }
    if (event.user) {
      delete event.user.ip_address;
    }
    return event;
  },
});
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: PII Data Sanitization & Log Masking Compliance Standard

PII Data Sanitization & Log Masking Compliance Standard defines an industrial-grade behavioral standard for security engineering. GDPR, HIPAA, and SOC2 compliant data sanitization discipline. Forbids logging plaintext Personally Identifiable Information (PII) including passwords, credit card numbers, national IDs, and JWT tokens; mandates deep recursive redaction. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: AI logs raw request bodies, database entities, or error dumps containing cleartext passwords and user PII. Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftAI logs raw request bodies, database entities, or error dumps containing cleartext passwords and user PII.Critical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Never log raw request bodies (e.g. logger.info(req.body))

Never log raw request bodies (e.g. logger.info(req.body)); filter through a recursive PII sanitizer before serialization.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Redact high-risk fields

Redact high-risk fields: password, token, secret, authorization, creditCard, ssn, nationalId, and apiKey.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Ensure Sentry and third-party error trackers enable `beforeSend` hooks to scrub user emails and IPs from crash reports.

Ensure Sentry and third-party error trackers enable `beforeSend` hooks to scrub user emails and IPs from crash reports.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Apply AES-256 field-level encryption for sensitive PII columns stored in relational and NoSQL databases.

Apply AES-256 field-level encryption for sensitive PII columns stored in relational and NoSQL databases.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is PII Data Sanitization & Log Masking Compliance Standard critical for AI coding assistants?

GDPR, HIPAA, and SOC2 compliant data sanitization discipline. Forbids logging plaintext Personally Identifiable Information (PII) including passwords, credit card numbers, national IDs, and JWT tokens; mandates deep recursive redaction. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (AI logs raw request bodies, database entities, or error dumps containing cleartext passwords and user PII.) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

PII