Security model#
What Bauta protects, how, and what it does not: for the security or privacy reviewer deciding whether its masked copies are fit for a purpose. To configure masking, see mask a table.
- Summary
- What is protected, and from whom
- Where unmasked data goes
- The masking constructions
- Two implementations
- What masking does not hide
- What stops a copy going out unmasked
- Keys
- The manifest
- Credentials and transport
- Trusted inputs
- Out of scope
- Checklist for a deployment
Summary#
- Masking is deterministic and keyed: the same value, in the same domain, under the same key, always gives the same mask. That is what keeps joins working, and it makes the output pseudonymized, not anonymized. Under GDPR and similar laws, a masked copy is still personal data.
- Protection rests on the masking key staying secret and being long and random. Anyone holding the key can confirm guesses; anyone with a weak key's fingerprint can search for it offline.
- Unmasked values exist only in the memory of the process running a job: never in the target, the stage table, logs, errors, the manifest, history or notifications. Values that database drivers quote in their errors are removed before an error is reported (see driver errors).
- The strategies differ in what they hide.
null,constantandredactremove information;key,fpe,hashandemailreplace it one-to-one or nearly so;number,dateShiftandshuffledeliberately keep some of it.
What is protected, and from whom#
The asset is the personal or confidential data in the source databases.
The adversary is anyone with access to a masked copy (developers, testers, analysts, a vendor, whoever compromises a non-production system) but not to production and not to the masking key. They may know some real values independently: their own customer record, public information about colleagues, a leaked list.
The goal is that such an adversary can't recover real values from the copy, beyond what the chosen strategies deliberately keep, and can't link masked rows to real people any better than those kept values allow.
Not in the adversary model: someone with the masking key, access to production, or control of the machine running the jobs. They already have what the masking protects.
Where unmasked data goes#
production --(TLS, if configured)--> job process memory --(masked)--> target stage/table
- In memory only. A job streams rows a chunk at a time (
chunkSize), transforms them, masks them, and only then writes them. Unmasked rows are never written to the target, not even to its stage table. - Logs and errors. Masking errors name the column and the value's type, never the value. Transform errors do the same and drop the transformer's own message, which often quotes the value. Run history, the manifest and notifications carry job names, counts and error text.
- Driver errors are scrubbed. Every server but SQLite quotes data in its errors: the duplicate key, the text that wasn't a number, PostgreSQL's
COPYcontext. From asourceQuery, those are unmasked production values. Before an error reaches a log, traceback, history, notification orauditreport, each quoted value becomes<redacted>, keeping the rest (which constraint, which column). The patterns cover the constraint, conversion and truncation messages of PostgreSQL 16, MySQL 8.4, MariaDB 11, Oracle 23ai, SQL Server 2022 and DuckDB 1.5, quotes and newlines in values included, tested against those servers. A statement a server quotes around an error (PostgreSQL'sLINE 1:, MySQL'snear '...') is removed whole. - A format no pattern knows fails closed. Any other foreign message loses every quoted part that the word before it doesn't mark as a name (
relation "orders",column 'email'), and everything to the end of the message where quotes don't pair up. A new format loses detail rather than leak a value. A value written without quotes in an unknown format still passes through (DuckDB'swith value 99999999999is covered; an unknown one like it would not be). The package's own messages never quote a value. - Drivers' own loggers. The drivers, PyIceberg and PyArrow log through loggers of their own; the command and every job process scrub their records as foreign messages. A program importing the package keeps its logging as it was, unless it builds a
Logor callsinstallDriverScrubbing(). - Process boundaries. Job processes send log records and outcomes to the main process over private pipes; neither carries row data. Masking threads run inside the job's own process and share its memory, so masking on several cores moves no data anywhere new.
- Transport. Connections are encrypted only if configured to be (see driver options and TLS).
run --dry-runandaudit --connectreport what each server says about its connection, andauditwarns when a masked job reads over an unencrypted one.requireEncryption: trueon a connection makes it a failure instead: a session the server doesn't report as encrypted is closed before a statement runs.
The masking constructions#
Everything keyed starts from the masking key K and the column's domain D (by default, the column name):
subkey(D) = HMAC-SHA256(K, "domain" || 0x00 || D)
digest(m, p) = HMAC-SHA256(subkey(D), p || 0x00 || m) purpose p separates uses
expand(m, n, p) = digest(m, p || "#" || counter), counter = 0, 1, ... truncated to n bytes
m is the value's canonical form: integers, whole decimals and whole floats as the same decimal text, dates as ISO 8601, text as UTF-8.
| Strategy | Construction | Output space |
|---|---|---|
hash |
first length hex characters of digest(m) |
48 to 256 bits |
email |
u + hex of digest(lowercased address) |
32 to 160 bits |
digits |
each digit replaced from expand(digits) |
the value's digit count; not one-to-one |
key |
a Feistel network, 10 rounds, round function expand over the right half, on the smallest even bit width covering the value's shape, cycle-walked into range |
a permutation of the value's shape: one-to-one |
fpe |
NIST SP 800-38G Rev. 1 FF1 with AES-256; the AES key is digest("", "ff1 key"); the tweak separates integers by sign, and text by charset and shape; checked against NIST's nine sample vectors |
a permutation of the value's shape: one-to-one |
fake* |
a list entry chosen by below(digest) |
a few dozen to a few thousand values: many-to-one |
number |
the value moved by up to variance, or placed within min–max, by unit(digest) |
keeps magnitude |
dateShift |
the date moved by a keyed number of days in ±maxDays, never zero, keyed on the day -- or, with shiftBy, on another column's value in the row |
keeps the date to within maxDays; with shiftBy, every interval of one subject exactly |
coordinate |
the value moved along its axis by meters × (½ + ½ unit(digest)), in a direction from another unit(digest), converted to degrees at the row's latitude where latitudeColumn gives one |
keeps the point to within meters |
shuffle |
the chunk's values permuted by a PRNG seeded from digest(chunk number) |
keeps every value, on another row |
redact |
identifiers found by pattern (and checksum, for cards and IBANs), replaced by labels or by email/digits/key masks |
the rest of the text is kept |
key versus fpe. Both are keyed permutations with the same shape rules. key uses HMAC-SHA256 as a Feistel round function. That's the same structure as FF1 and FF3-1, but it's this package's own construction, it hasn't been reviewed as a standard, and it adds no dependency. fpe is FF1 as NIST specifies it. Choose fpe where a policy must name a published algorithm.
Two implementations#
The same constructions exist twice: in Python, and in the optional bauta-rs extension, which computes them in Rust several times faster (see the native masker). Which one ran is recorded in the manifest as maskedBy.
They are required to agree byte for byte. A difference would look like a changed key, with masks that no longer match the target's and joins that silently stop matching, except that the key fingerprint wouldn't change.
How that is held:
- Recorded vectors.
mask-rs/vectors/reference.jsonholds Python's output for every strategy over a corpus chosen for boundaries (where a Feistel half stops fitting a machine word, domains of exactly 2**128,MAXIMUM_KEY_LENGTH, every refusal and its message). The Rust tests check against it, and a Python test fails if Python drifts from it, so changing a mask means changing the file, deliberately. - Both implementations, same corpus.
tests/masking/test_nativeMasking.pyruns each strategy and option combination through both and compares masks, types and error messages. - Both paths within the port. Where the native masker has a fast path --
key's Feistel network and FF1's rounds in machine integers, integers crossing from Python as 64-bit values -- the general path stays for everything wider, Rust's unit tests require the two to agree on every width the fast one takes, and the corpus has values either side of each boundary. - Any number of threads. The same tests mask columns large enough to be split across threads, on one thread and on eight, chunk after chunk with the cross-chunk cache warm, and require the same masks as pure Python.
- The whole suite, twice. CI runs it with the extension and with
BAUTA_NATIVE=0. - A trace if they ever didn't. Every masked job records the implementation beside its key fingerprint, and an upsert job run under a different one logs a warning naming both: the evidence an operator would need if rows masked before and after stopped joining.
- Published vectors. FF1 is checked against NIST's sample vectors on both sides, and the keyed hash against RFC 4231.
The Rust implementation is a port, not a second design: where the two could differ, Python is the reference and the port is the bug. Values whose handling depends on Python's Unicode rules (non-ASCII letters and digits, str.isspace()) are handed back to Python per value rather than reimplemented.
Small domains. Format-preserving encryption over small domains has known message-recovery attacks given enough real/masked pairs (Bellare, Hoang and Tessaro, 2016; Durak and Vaudenay, 2017), so NIST requires at least a million possible values for FF1. fpe follows that rule, masking shorter values with key instead, or refusing them under strict: true. key permutes domains of any size: a two-digit value has 90 possible masks, and enough known pairs in one domain reveal the whole mapping. That is inherent to one-to-one masking of short values; use hash, null or a longer key space where short identifiers are sensitive.
What masking does not hide#
These follow from masking being deterministic and shape-preserving. They are why the output is pseudonymized:
- Equality and frequency. Equal values get equal masks in a domain, so counts survive. In a low-cardinality column (a status, a department) or a skewed one (surnames), frequency analysis against known distributions can recover values. Every deterministic strategy keeps these frequencies,
fake*included; usenullorconstantwhere the distribution itself is sensitive. - Linkage across tables and runs. Masks agree across tables in a domain and across runs under one key; that's the purpose. A copy made for one audience can be joined to another copy made under the same key.
- Shape. Lengths, formats, sign and digit counts, and characters outside the charset are kept.
keyandfperefuse letters and digits outside ASCII rather than keep them. - Magnitude and dates.
numberwithvariance,coordinateanddateShiftreveal approximate values by design: a salary within 10%, a location withinmeters, a birth date withinmaxDays.dateShiftwithshiftBymoves every date of one subject by the same amount, so one real date and its mask reveal the rest of theirs. - Normalized values. Under
normalize, values a database compares as equal mask alike, and so do their masks:AB12,ab12andAB12are no longer told apart in the copy. - Kept columns.
keepcopies values as they are. Combinations of kept quasi-identifiers (postal code, birth year, gender) can identify people.auditflags kept columns whose names suggest personal data, but names can mislead. shuffle. Every real value remains in the table; a small chunk (the tail of a load, a small incremental run) barely moves them, and a one-row chunk not at all.redact. Only identifiers with a recognisable shape are found. Names, addresses written in words and other free-form details pass through.- Structure. Row counts, NULL patterns, relationships and timing are all kept.
What stops a copy going out unmasked#
Masking a column correctly is one problem. Not masking a table at all is the other, and it fails differently: nothing raises, and the copy looks finished.
Four checks stand between production and an unmasked copy, from the narrowest to the widest.
| Check | What it catches | When |
|---|---|---|
| Every column must be covered | A column the query returns that the policy doesn't name — including one production gained since the policy was written | The job fails before writing anything |
audit --connect --strict |
A job with no masking policy, a kept column that looks personal, references that stop matching once masked | Offline in CI, exit 1 |
bauta coverage |
A table in production that no job reads at all, which audit cannot see, because a table with no job has nothing to audit |
Exit 1 on anything uncovered |
requireMasking |
Any job reading from or writing to that database without a masking policy, or with a defaultStrategy that copies the columns it doesn't name as they are |
bauta validate, before anything connects |
The first three can be argued with; the fourth cannot. requireMasking: true on a target alias is the statement that this database can only ever hold masked data, and nothing overrides it — not a job's own unmasked: true, which records a reviewed decision about one job, and not a declaration in acknowledged.
Both of those exist so that a deliberate exception is written down rather than inferred from silence:
unmasked: trueon a job says its rows were reviewed and are copied as they stand. Without it,auditreports every unmasked job. A column that still looks like personal data is reported either way.acknowledgedinjobs.yamlsays a table is deliberately not copied, and why.coveragefails on any table that is neither copied nor declared, and reports a declaration for a table the database no longer has.
The watermark is not a way around masking. It is read before masking and kept in run state and logs, so a watermarkColumn the policy masks, whether it names the column or leaves it to defaultStrategy, is refused by validate and again by run.
A misspelled or repeated key is an error, not an exception. An unknown field (maskng: for masking:) is refused rather than dropped, and so is a key given twice in one mapping, which YAML would resolve silently by keeping the last (actor_email: email, then further down actor_email: keep). A key given again over a merge (<<: *defaults) overrides it, as YAML intends.
What none of this checks: whether the strategy chosen for a column is strong enough for the data in it. That is what what masking does not hide is about, and it is a review, not a check.
Keys#
- Strength. Keys must be at least 16 characters, of at least 8 different ones (
aaaa...is a pattern, not a secret). A key estimated at under 128 bits is warned about, by fingerprint; a future release will refuse it. Dictionary words aren't detected. The key is HMAC key material with no password-stretching, so a guessable key can be found offline from one real/masked pair or a fingerprint. Use 32 random bytes or more:python -c "import secrets; print(secrets.token_urlsafe(32))". The same rules apply to a manifest signing key. - Fingerprints. Logs, manifests and
auditshow a key fingerprint: the first 48 bits ofHMAC-SHA256(K, fixed text). It identifies which key was used without revealing it, provided the key is strong; it is exactly the kind of known pair that makes a weak key searchable. - Storage. Read keys from the environment or a mounted file (
${MASKING_KEY},${file:/run/secrets/masking-key}); never commit them. Keys are held as secrets in the configuration model, so they don't appear in itsrepr, logs or tracebacks. - Rotation. A new key changes every mask. Masked upsert jobs, and append jobs writing files or Iceberg, refuse to run when their key has changed until the change is acknowledged, since their targets would otherwise mix masks from two keys. See the key.
- Implementation. Each masked job also records which implementation masked it; a change is warned about, not refused. See two implementations.
- Separation. Use different keys for copies that must not be linkable to each other, and a separate key, never a masking key, to sign manifests.
The manifest#
- Contents. What was masked, how, under which key fingerprint, from which jobs file (with its SHA-256), with which tool version, and which masking implementation produced it (
maskedBy:python, or the extension and its version). Never a value, never a key. - Integrity. A SHA-256 digest of the manifest's content (canonical JSON) catches accidental changes. Anyone can recompute it, so it proves nothing about origin.
- Authenticity. With
BAUTA_MANIFEST_KEYset, the manifest is also signed with HMAC-SHA256, andverify-manifestrequires a signature, so removing one doesn't make an edited manifest pass. This is symmetric: anyone who can verify a manifest can also create one. It shows a manifest came from a holder of the signing key, not which holder. Where that distinction matters, keep the signing key with the auditors' process, not with the team running the jobs.
Credentials and transport#
- Passwords are held as secrets and never logged.
passwordCommandoutput is never logged, and the command is never run byvalidate. Driveroptionsare kept out of the configuration'srepr, since some (a wallet password) are secrets. A configuration that fails validation is reported without the validator's own error behind it, which quotes the input it was given, a key or a password among it. - Short-lived credentials.
passwordCommandruns at every connection, so cloud IAM tokens are always fresh; its failures are retried like connection errors. - TLS is configured per driver through
options. Settings express intent; the server's own report, shown byrun --dry-runandaudit --connect, is what to rely on. SQL Server encryption is configured through FreeTDS; pymssql's ownencryptionargument had no effect in testing. - Run state, history and manifests hold job names, times, watermarks and key fingerprints, never masked values. A watermark is a source value (usually an
updated_at), which is why a masked column can't be one. Protect them like the configuration.
Trusted inputs#
The configuration is trusted: whoever can change it controls what the tool does.
- SQL.
sourceQuery, subset--wherefilters, adhoc queries andcurrentSchemaare written into SQL as given (currentSchemamust be a plain identifier). Table and column names are quoted into the statements bauta builds, which makes them one identifier each but is not a defence: a name is configuration, not data. Data values are always bound as parameters. - Code. Transformer references and custom masking strategies import and run Python modules named in the configuration. Transformer arguments are limited to literals.
- Commands.
passwordCommandruns a program named in the configuration, without a shell. - Files.
${file:...}reads any file the process can read. A DuckDB connection's queries can reach no file outside its database unless itsoptionssetenable_external_access; see DuckDB. - Discovery rules.
discovery.yaml's regular expressions run against values sampled from production, in memory; like any regular expression, a badly written one can be slow. - YAML is parsed with PyYAML's safe loader, and run memory is written with its safe dumper, so neither can construct Python objects.
Keep the configuration directory writable only by the people who may run jobs against production.
Out of scope#
- Anonymization guarantees. No k-anonymity, l-diversity or differential-privacy checks are made, and none of the strategies provides them.
- Re-identification risk assessment of a particular dataset.
- Access control on the copies, and their retention and deletion.
- Protection from someone who holds the key, production access, or the machine running the jobs.
- Side channels such as timing, and the security of the database servers and drivers themselves.
- Hard deletes in production reaching incremental copies as they happen (see deletes): a deleted person stays in the copy until its next
run --full-refresh, so schedule one within the time your policy allows for erasure.
Checklist for a deployment#
- A random masking key of 32+ bytes, from a secret store, different per audience whose copies must not be linkable.
validatewarns about a weaker one. fpewithstrict: truewherever policy requires a published algorithm.- No
keepon quasi-identifiers without a documented reason;audit --connect --strictin CI, which also checks kept columns by their sampled values. bauta coveragein CI, so a table added to production later fails the build; every exception recorded inacknowledgedwith its reason.requireMasking: trueon every non-production target, so nothing can reach it unmasked whatever a job says.nullfor free text that may hold names;redactonly where the text is needed and names are acceptable.- Encrypted connections, confirmed by
run --dry-run. - Manifests signed with a key held apart from the operators, and checked with
verify-manifest. - Webhook notifications and run history treated as sensitive: driver error text is scrubbed of the values it quotes in known formats, not all formats.
- The configuration directory, run state and history writable only by the operators.
- Masked copies handled as personal data: pseudonymized, not anonymized.
bauta run --full-refreshscheduled for incremental jobs, often enough that a row deleted in production leaves the copy within your erasure deadline.