Skip to main content

CloakData - Data Anonymizer

PyPI Python CI License

A flexible data anonymization library built on Polars, designed for privacy, compliance, and testing with low overhead.


Current Highlights

  • Built-in methods are organized by domain under src/cloakdata/native_methods/
  • Native methods are registered automatically with @native_method
  • Practical support for masking, replacement, generalization, randomization, and data cleanup
  • Config-driven anonymization with conditional rules
  • Runnable examples for the main built-in methods
  • Built on Polars for fast vectorized execution

Features

  • Masking:
    • full_mask
    • mask_email
    • mask_number
    • mask_credit_card
    • mask_cpf
    • mask_partial
  • Replacement and pseudonymization:
    • replace_with_value
    • replace_exact
    • replace_by_contains
    • replace_with_random_digits
    • hash_value
    • hmac_value
    • replace_with_hash_bucket
    • redact_regex
  • Generalization:
    • generalize_age
    • generalize_date
    • generalize_number_range
    • generalize_zip_code
    • top_k_bucket
    • coarsen_datetime
  • Randomization and transforms:
    • random_choice
    • shuffle
    • noise_numeric
    • date_offset
    • round_number
    • round_date
    • clip_range
  • Utilities:
    • coalesce_cols
    • null_if_matches
  • Sequential pseudonyms:
    • sequential_numeric
    • sequential_alpha
  • Conditional rules with nested logic
  • Custom runtime methods with register_method(...)

How It Works

  1. Load data into a Polars DataFrame
  2. Define rules in a config dictionary
  3. Call anonymize(df, config)
  4. Receive a transformed DataFrame

The engine validates the configuration and gets a snapshot of the method registry. Built-in and custom methods return Polars expressions. Independent columns are evaluated against the input, and each chain uses a lazy projection per rule. Custom methods keep the (df, col, params) -> pl.Expr signature. When a custom method runs inside a chain, its input includes the current target column and the original values for other available columns.


Quickstart

import polars as pl

from cloakdata import anonymize

df = pl.DataFrame(
    {
        "name": ["Alice Smith", "Bob Jones"],
        "email": ["alice@example.com", "bob@example.com"],
        "age": [25, 42],
    }
)

config = {
    "columns": {
        "name": {"method": "initials_only"},
        "email": {"method": "mask_email"},
        "age": {"method": "generalize_age"},
    }
}

out = anonymize(df, config)
print(out)

Example Config

Apply this configuration to a DataFrame containing all the listed columns. Each target refers to an existing column unless it has a conditional rule.

{
  "columns": {
    "name": { "method": "initials_only" },
    "email": { "method": "mask_email" },
    "email_hash": {
      "method": "hash_value",
      "params": { "salt": "public-example-salt" }
    },
    "phone": { "method": "mask_number", "params": { "keep": 3 } },
    "cpf": {
      "method": "mask_cpf",
      "params": { "keep_last": 2 }
    },
    "status": {
      "method": "replace_exact",
      "params": { "mapping": { "active": "A", "inactive": "I" } }
    },
    "notes": {
      "method": "redact_regex",
      "params": {
        "pattern": "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}",
        "replacement": "[EMAIL]"
      }
    },
    "id_seq": { "method": "sequential_numeric", "params": { "prefix": "ID" } },
    "ref_code": { "method": "sequential_alpha", "params": { "prefix": "REF" } },
    "comments": { "method": "truncate", "params": { "length": 5 } },
    "age": { "method": "generalize_age" },
    "birth_date": { "method": "generalize_date", "params": { "mode": "month" } },
    "zip_code": { "method": "generalize_zip_code", "params": { "visible_prefix": 3 } },
    "state": { "method": "random_choice", "params": { "choices": ["SP", "RJ", "MG", "BA"] } },
    "last_access": { "method": "date_offset", "params": { "min_days": -2, "max_days": 2 } },
    "event_time": { "method": "coarsen_datetime", "params": { "mode": "part_of_day" } },
    "feedback": { "method": "shuffle" },
    "score": { "method": "clip_range", "params": { "min": 0, "max": 100 } }
  }
}

Conditional Rules

Single condition:

"cpf": {
  "method": "mask_cpf",
  "params": { "keep_last": 2 },
  "condition": {
    "column": "status",
    "operator": "equals",
    "value": "active"
  }
}

Multiple rules per column run in list order. Each method reads the previous result for its target. Conditions use the original values for every column, including the target. A false or null predicate keeps the previous result.

"email": [
  { "method": "mask_email" },
  {
    "method": "truncate",
    "params": { "length": 5 },
    "condition": { "column": "share_domain", "operator": "is_false" }
  }
]

Nested conditions:

"age": {
  "method": "generalize_age",
  "condition": {
    "all": [
      { "column": "country", "operator": "equals", "value": "BR" },
      {
        "any": [
          { "column": "status", "operator": "equals", "value": "active" },
          { "column": "status", "operator": "equals", "value": "archived" }
        ]
      }
    ]
  }
}

Supported operators: equals, not_equals, in, not_in, gt, gte, lt, lte, between, contains, not_contains, startswith, endswith, is_null, not_null, is_true, and is_false. The contains operators use regex patterns. For compatibility, is_false also matches null input flags. This preserves policies that redact when a flag is missing.

Supported groups include all, any, not, non-empty lists (implicit AND), and {"conditions": [...], "logical": "and" | "or"}.


Example Input to Output

Input:

name email age status cpf
Alice Smith alice@example.com 25 active 00000000001
Bob Jones bob@example.com 42 inactive null

Config:

{
  "columns": {
    "name": { "method": "initials_only" },
    "email": { "method": "mask_email" },
    "age": { "method": "generalize_age" },
    "cpf": {
      "method": "mask_cpf",
      "params": { "keep_last": 2 },
      "condition": {
        "column": "status",
        "operator": "equals",
        "value": "active"
      }
    }
  }
}

Output:

name email age status cpf
A.S. xxxxx@example.com 20-29 active *********01
B.J. xxxxx@example.com 40-49 inactive null

Examples

Runnable scripts live under examples/.


Supported Methods

Method Description
full_mask Fixed mask or literal
mask_email Masks the local part of an email
mask_number Keeps leading characters and masks the rest
mask_credit_card Masks card digits while preserving the last visible digits
mask_cpf Masks Brazilian CPF values while preserving the final visible digits
mask_partial Masks the middle while preserving visible edges
truncate Truncates strings to a fixed length
initials_only Converts names to initials
replace_with_value Replaces all values with a static value
hash_value Generates deterministic hashes, with optional salt
hmac_value Creates deterministic HMAC-SHA256 pseudonyms using secret key bytes
redact_regex Redacts regex matches inside free text
replace_with_hash_bucket Replaces values with deterministic hash buckets
replace_exact Replaces exact values using a mapping
replace_by_contains Replaces values that contain substrings
replace_with_random_digits Generates deterministic digit strings
sequential_numeric Sequential numeric pseudonyms
sequential_alpha Sequential alphabetic pseudonyms
generalize_age Groups ages into ranges
generalize_date Reduces date and datetime granularity
generalize_number_range Buckets numeric values into fixed intervals
generalize_zip_code Preserves a visible postal-code prefix and masks the rest
coarsen_datetime Coarsens timestamps into buckets, minute-of-day buckets (time-only or full datetime), hour, part-of-day, weekday, weekend/weekday, or configurable business-hours labels
top_k_bucket Keeps the top-k most frequent categories and buckets the rest
random_choice Picks deterministic values from a fixed set
noise_numeric Adds deterministic numeric noise within configured bounds
shuffle Shuffles values while keeping row count
date_offset Applies deterministic date offsets
clip_range Constrains numeric values to configured min/max bounds
round_number Rounds numeric values
round_date Rounds dates to month or year start
coalesce_cols Returns the first non-null value across columns
null_if_matches Converts known placeholders or regex matches into null

Privacy and threat model

  • Masking hides selected characters or values. Partial masks expose some characters, and length-preserving masks reveal length. CPF and card masks recognize specific formats and may leave unrecognized inputs unchanged.
  • Hashing creates a deterministic digest. hash_value preserves its legacy digest for non-null values. With preserve_nulls=False, null hashes like the empty string. An observer who knows the salt can test guesses for predictable emails, phone numbers, and identifiers.
  • Keyed pseudonymization reduces offline guessing when the recipient lacks the secret and cannot query a service that produces tokens for chosen inputs. Identical strings under the same key produce identical tokens, which expose equality and frequency. Other columns can still identify people.
  • Anonymization is a property of the released dataset in context. Review auxiliary data, rare combinations, access controls, and residual linkage. Using these methods alone does not establish compliance with GDPR or LGPD.

Seeded random choices, numeric noise, and date offsets can depend on row position. Hash buckets can collide. Polars does not guarantee Expr.hash stability across versions. Sequential labels are local to the input, and shuffle keeps the original set of values. These methods offer no cryptographic protection.

Keyed pseudonyms

hmac_value casts inputs to Polars strings, hashes their UTF-8 bytes using HMAC-SHA256, and leaves nulls unchanged. Supply at least 32 random bytes from a secret store. Use separate keys for datasets that should not be linkable. Keep keys, configs containing keys, and source records out of logs and version control.

import os

from cloakdata import anonymize
from cloakdata.validate import validate

key = bytes.fromhex(os.environ["CLOAKDATA_HMAC_KEY_HEX"])
config = {"columns": {"email": {"method": "hmac_value", "params": {"key": key}}}}
validate(config)
out = anonymize(df, config)

Generate the key once with a cryptographic generator such as secrets.token_bytes(32) and store its hex encoding securely. Rotating the key changes all tokens. Normalize input explicitly if equivalent identifiers should produce the same token.

Validation and troubleshooting

  • validate(config) raises ValueError for invalid rule structure, conditions, and native parameters that can be checked without the data. This includes malformed regex patterns in conditions and native methods. Use Polars regex syntax. Validation does not run custom methods or check the input schema.
  • anonymize(df, config) also checks target and predicate columns. Unknown methods, malformed conditions, empty rule lists, and missing unconditional targets now fail. A missing conditional target still starts as null.
  • Use "drop" or {"method": "drop"} as the sole rule for a column. It is safe to drop an absent column. Dropped columns cannot be used by other rules.
  • anonymize raises ValueError or TypeError for invalid settings. For a valid config that fails on the data, catch cloakdata.TransformationError and inspect its chained cause privately. Polars exceptions can include input values. Missing columns used inside method expressions still raise Polars ColumnNotFoundError.
  • Polars calculates both sides of conditional expressions. A transformation must accept the column data types even where its predicate is false.

Project Structure

src/
  cloakdata/
    native_methods/  # Built-in methods organized by domain
tests/               # Pytest suite
examples/            # Runnable examples
README.md
pyproject.toml

Built-in methods live under src/cloakdata/native_methods/ and are registered automatically with @native_method.


Installation

pip install cloakdata

Or with uv:

uv add cloakdata

Development

git clone https://github.com/Jeferson-Peter/cloakdata
cd cloakdata
uv sync --locked --extra dev
uv run ruff check .
uv run coverage run -m pytest
uv run coverage report
uv build

Choosing Methods

  • Use hmac_value for stable pseudonyms of predictable identifiers when you can protect a key.
  • Use hash_value when you need to reproduce existing unkeyed digests.
  • Use replace_with_hash_bucket when you need deterministic grouping and collisions are acceptable.
  • Use generalize_date when you want period-style date abstraction such as month, quarter, or year.
  • Use round_date when you want canonical rounded dates such as month-start or year-start.
  • Use coarsen_datetime when you want timestamp abstraction such as hour buckets, part-of-day labels, weekdays, or business-hours labels.
  • Use null_if_matches before anonymization when your source data contains placeholders such as N/A, unknown, or regex-shaped junk values.

Contributing

See CONTRIBUTING.md for setup, coding standards, how to add a new anonymization method, and the PR checklist.

See the engineering assessment, benchmarks, and portfolio case study for the design decisions and measurements. See the 4.0.0 release notes for compatibility changes.

Notice

See NOTICE for attribution details.

License

MIT Copyright Jeferson Peter

Metadata

Release files for cloakdata 4.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for cloakdata 4.0.0
File Size Uploaded Provenance Actions
cloakdata-4.0.0.tar.gz 21.0 kB Without provenance Details for cloakdata-4.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for cloakdata 4.0.0
File Interpreter ABI Platform Actions
cloakdata-4.0.0-py3-none-any.whl Python 3 none any Details for cloakdata-4.0.0-py3-none-any.whl

Total release size: 49.3 kB

Release files / cloakdata-4.0.0.tar.gz

Download URL cloakdata-4.0.0.tar.gz
Size 21.0 kB
Tags Source
SHA-256 checksum
How to use checksums
d754dd312c6a256f27c91245b6daad3a61cd9e4611587dde73d3193eb329810a
BLAKE2b-256 checksum
How to use checksums
d1e2f70e95a50e325129de77fe3ef2d6b076e279ccd0ab2a290a7be6ed5bc1fa
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.30 {"installer":{"name":"uv","version":"0.9.30","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"12","id":"bookworm","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / cloakdata-4.0.0-py3-none-any.whl

Download URL cloakdata-4.0.0-py3-none-any.whl
Size 28.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
15df78fd03f637b79f84d192d1417b195190b235b4667f0c4c6fa3f8521bd88c
BLAKE2b-256 checksum
How to use checksums
f314f88b92fc5e01688be754bf01e21879b3c66fb4d0a9da3ba52a1d59889b35
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.30 {"installer":{"name":"uv","version":"0.9.30","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"12","id":"bookworm","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for cloakdata 4.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page