Masking Email Addresses in Logs with Open Policy Agent

A single leaked email address in your logs can burn trust and break compliance. You need control at the policy layer, before sensitive data escapes. Open Policy Agent (OPA) makes it possible to mask email addresses in logs at runtime, without rewriting application code.

With OPA, you define policies in Rego that inspect log output and replace any value matching an email pattern. This approach works across microservices, sidecars, and CI/CD pipelines—anywhere your services ship logs. The key is to intercept the log event as structured data and run it through OPA before it’s written or exported.

A simple masking rule in Rego might look like this:

package logfilter

default mask = input

mask = modified {
 modified := input
 modified.message := regex.replace_n("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}", "[masked]", input.message)
}

This rule scans input.message for any email address and replaces it with [masked]. Use regex tuned for your data formats and logging patterns. Applying this at the logging gateway or collector ensures sensitive data is removed no matter which service produced it.

Integrating OPA for email masking involves three main steps:

  1. Send structured log data to OPA as input.
  2. Apply masking policies using regex or string operations in Rego.
  3. Return sanitized output for storage or downstream processing.

You can load these policies dynamically into OPA, allowing rapid updates without redeploying services. This makes it easy to tighten masking rules, add new patterns, or enforce organization-wide compliance requirements across all environments.

Masking email addresses in logs with Open Policy Agent is more than a best practice—it’s a safeguard that enforces compliance before the data leaves your control. When policies live at the infrastructure level, developers keep moving fast without risking leaks.

See this live on hoop.dev and get OPA-powered data masking running in minutes.