← All case studies

// analysis

Designing a Defense in Depth Validation Layer for Webhook Ingestion

PythonPydanticInput Validation

Overview

A multi tenant ingestion platform was built to accept untrusted incoming payloads from user submitted reports and third party vendor webhooks. The goal was to establish a perimeter validation layer that protected downstream storage and query engines from malicious input, without dropping valid operational data due to minor formatting quirks.

The Problem

Ingestion pipelines face a constant conflict between strict security and high availability. Overly permissive validation lets dangerous payloads penetrate deep into the system where they can exploit downstream services. Overly aggressive validation drops legitimate incoming business data whenever a vendor slightly shifts their payload format or includes dirty characters. The challenge was building an edge layer that rejected actual security threats outright while safely normalising minor data defects automatically.

Investigation

Reviewing ingress payload failures and running fuzz tests against the existing validation logic revealed two main issues. Legitimate vendor payloads were frequently failing due to non malicious noise, such as untrimmed whitespace in domain strings or non standard character encoding. Separately, fuzz testing showed that the existing validation relied heavily on complex regular expressions, and that nested, unbounded regex patterns were vulnerable to catastrophic backtracking, where a single crafted long string could spike CPU usage and freeze the validation layer entirely.

validation_pipeline.txt
Incoming Payload
      |
      v
Unicode Normalisation (NFKC)
      |
      v
Structural Check ---- fails ----> Reject (HTTP 400)
      |
    passes
      |
      v
Threat Pattern Check ---- fails ----> Reject (HTTP 400)
      |
    passes
      |
      v
Formatting Check ---- noisy ----> Sanitise + Flag (audit_sanitised=true)
      |
    clean
      |
      v
Persisted

The Solution

The fix split validation into a two tier policy at the API entry point, executing before any database calls, and replaced fragile regex patterns with deterministic standard library parsing.

Deterministic parsing replaced regex-heavy validation specifically to remove the catastrophic backtracking risk, the snippet below checks structure using standard library functions rather than pattern matching.

validate_indicator.pyimport unicodedata
import ipaddress
from pydantic import BaseModel, validator, Field

class IncomingReportModel(BaseModel):
    indicator: str = Field(..., max_length=253)
    description: str = Field(..., max_length=5000)

    @validator('indicator', pre=True)
    def normalize_and_validate_indicator(cls, value: str) -> str:
        # Step 1: Prevent Unicode bypass techniques
        normalized = unicodedata.normalize('NFKC', str(value)).strip()

        # Step 2: Deterministic IP check (prevents ReDoS backtracking)
        try:
            ipaddress.ip_address(normalized)
            return normalized
        except ValueError:
            pass

        # Fallback length/format check
        if len(normalized) > 253 or " " in normalized:
            raise ValueError("Malformed indicator string")

        return normalized

Engineering Trade-offs

The core decision was choosing a reject versus flag and sanitise strategy rather than a binary pass or fail rule. Hard failing every payload with trailing spaces or casing errors shifts the burden onto upstream partners and creates constant operational friction. Cleaning acceptable noise at the boundary while strictly blocking structural threats preserved both perimeter security and ingestion reliability.

Challenges

The primary difficulty was handling edge case encoding bypasses without introducing performance bottlenecks. Attackers often use full width Unicode variants or homoglyphs to bypass naive string blacklists. Implementing Unicode normalisation resolved the security gap, but required careful placement in the parsing pipeline so it did not add unnecessary overhead to clean, high volume payloads.

Outcome

Reflection

A good validation layer should not be a rigid wall that breaks at the first sign of dirty data. Real world vendor integrations are messy, and anticipating that noise while designing clean normalisation pathways is just as important as blocking actual malicious payloads.