Masking strategies#
A NULL stays NULL under every strategy except constant and null.
| Strategy | Result | Options |
|---|---|---|
keep |
Unchanged. The explicit way to say a column was reviewed. | none |
null |
NULL. The right choice for free text. | none |
constant |
value in every row, NULLs included. |
value (required) |
hash |
An opaque hex token, e.g. cust_9f86d081884c7d65. |
length (12–64, default 16), prefix; normalize: strip, lower (below) |
email |
Still an email address, e.g. u9f86d081884c@example.test. Keyed on the lower-cased address. |
length (12–40, default 12), mailDomain (default example.test), keepDomain |
digits |
Each digit replaced, everything else kept: +1 (555) 010-9999 → +1 (831) 402-5517. Keyed on the digits alone, so formatting doesn't matter; integers keep their digit count; digits in any script are masked and written back in it. A value the keeps cover entirely fails the job rather than being copied through. |
keepLeading, keepTrailing (e.g. 4 for a card number) |
number |
A number of the same type and precision, either within variance of the original (default 0.1) or within min–max. A value the variance would round back to itself, such as a small integer, moves one step instead; zero stays zero. |
min + max, or variance (0–1); decimals |
dateShift |
Moved by a keyed number of whole days, never zero, keyed on the day: everything on one day moves alike, and two days move by unrelated amounts, so a start and an end can change order (shiftBy avoids that). Times of day, and ISO text's own spelling, are kept. 0001-01-01 and 9999-12-31 are kept, since they mean "no date" or "forever". |
maxDays (default 30); shiftBy: a column of the row |
key |
A one-to-one mapping, safe for primary and foreign keys. See below. | charset: alphanumeric (default), digits, hex; normalize: strip, lower, integer |
fpe |
Like key, but using NIST's FF1 format-preserving encryption, for policies that must name a standard. See below. |
charset: alphanumeric (default), digits, hex; strict; normalize: strip, lower, integer |
fakeName, fakeFirstName, fakeLastName, fakeCity, fakeCompany, fakeStreetAddress |
Realistic values from bundled lists. Not unique. | maxLength; locale; lists (1 or 2), and matchGender for the name strategies; below |
ip |
An IP address as another of its family, one-to-one: IPv4 to IPv4, IPv6 to IPv6, always valid, so an inet or cidr column takes it. See below. |
keepPrefix (0–128): leading bits kept |
coordinate |
A latitude or longitude moved along its axis by a keyed distance on the ground, between half of meters and all of it, wherever the point is. See below. |
axis (required): latitude or longitude; meters (default 1000); latitudeColumn, for a longitude; scale, for degrees stored multiplied |
redact |
Free text with each recognisable identifier replaced: emails, phone numbers, US SSNs, card numbers and IBANs (both checksum-verified), IPv4 addresses. Names aren't found. See below. | replacement: label (default) or mask; detect: a list of email, phone, ssn, card, iban, ip; patterns: extra regular expressions |
json |
A JSON document with each path fields names masked by its own policy, and every other value by otherwise. See below. |
fields (required): path → column policy; otherwise: a policy, default redact with replacement: mask |
shuffle |
The column's values rearranged among rows in the same chunk. Not anonymization: every real value is still in the table, and a small chunk barely moves them. It breaks a key and its references even where both are shuffled; audit warns. See limits. |
none |
A value a strategy can't handle fails the job, for example text given to number. The error names the column and the value's type, never the value itself.
key#
key guarantees different inputs give different outputs, as a primary key needs, where a hash cut to a column's width would eventually collide. It is a keyed permutation, a Feistel network with HMAC-SHA256 rounds: the structure of NIST's FF1 and FF3-1, but not a certified implementation of either.
The output has the same shape as the input:
- An integer keeps its sign and number of digits.
- Text keeps its length, and every character that isn't masked stays put. With
alphanumeric, digits map to digits and letters to letters of the same case.digitsmasks only digits.hexmasks hex characters the same way — digits to digits,a-ftoa-f,A-FtoA-F— which suits UUIDs and hex tokens, and keeps two spellings of one value apart. - A UUID object stays a UUID. Its version digit isn't preserved.
charset is set once per column rather than detected from each value, because detection could give two different shapes the same output.
Only ASCII letters and digits are masked, so a value with letters or digits in another script (José, 王伟, ١٢٣) fails the job rather than being copied through. Other characters (spaces, punctuation, €) are kept. Use hash, a fake* strategy or null for names in any script, and digits for numbers in other digits.
Values are limited to 256 characters, or 256 digits, since key's cost grows with the square of a value's length; a longer one fails the job, suggesting hash, redact or null. The same limits apply to fpe.
(number, for ordinary numeric columns, computes to 60 significant digits; a value needing more fails the job.)
A mask can be wider than the column. Keeping a value's shape is not the same as fitting where it came from:
keykeeps an integer's digit count, but a column's range doesn't stop at a digit boundary: a 10-digit value in anINTmasks to another 10-digit value, most of which exceed 2147483647, and the load fails "out of range" (aBIGINTlikewise at 19 digits). Use a wider column, orhashwhere it need not stay a number.numbervaries a value that may already be at its column's limit:9999999999.99in aDECIMAL(12,2)overflows about half the time. Bound it withminandmax. SQLite ignores declared precision and stores the wider value.
A mask can't be narrowed to fit one column without breaking the joins it keeps. A job that fails this way logs which is likely responsible.
fpe#
fpe is key's alternative for when a security review asks for a published algorithm: FF1 from NIST SP 800-38G Rev. 1, with AES-256. It is checked against NIST's sample vectors, and needs the cryptography package (pip install "bauta[fpe]"; the oracle extra already brings it).
- It keeps shapes the way
keydoes: integers keep sign and digit count, text keeps its length and every character outsidecharset. FF1 needs one alphabet for every position, so withalphanumerica letter may become a digit, and withhexa masked value may mix cases (2cAB74Ce);keykeeps each character's class and case. - The masking key is turned into an AES key per domain, and the domain goes into FF1's tweak.
- FF1 needs at least a million possible values: six digits, five hex characters or four alphanumerics. Shorter values are masked with
keyinstead, never colliding with longer ones since lengths are kept, or, understrict: true, fail the job.auditnotes eachfpecolumn withoutstrict. - Slower than
keyin pure Python, faster with the native masker: twofpecolumns among six run at 254,000 rows a second, against 129,000 withkey(see speed).
Only encryption is implemented. Nothing in the package can reverse a mask.
Values held more than one way: normalize#
Masks agree when values are equal byte for byte, and a database's idea of equal is often looser. Three cases break joins in a copy without anything failing:
- Padding. A
CHAR(10)column holdsAB12asAB12. SQL Server, MySQL and Oracle compare the two as equal, and aVARCHARkey elsewhere holdsAB12; masked, they differ. - Case. A case-insensitive collation joins
AB12toab12;hashmasks them differently. - Type. One table holds a customer id as an integer, another as text.
hashkeys both on the same digits, butkeyandfpekeep a value's type, so42and'42'mask differently.
normalize lists the steps to apply to text before it is masked, always in this order whatever order they are written in:
| Step | Takes | For |
|---|---|---|
strip |
hash, key, fpe |
leading and trailing spaces removed |
lower |
hash, key, fpe |
lower-cased |
integer |
key, fpe |
text that spells an integer one way only (42, -7, not 042 or +7) masked as that integer, and written back as text |
columns:
customer_ref: { strategy: key, domain: customers, normalize: [strip, integer] } # '42 ' masks as customers.id 42 does
account_code: { strategy: hash, domain: accounts, normalize: [strip, lower] }
Normalize every column of a domain the same way, or none: a padded value masks as the unpadded one only where both are stripped. Values that aren't text are masked as they are. audit --connect samples each query and warns about a domain holding ids as numbers in one column and as text in another, or padded in one and not another. email already strips and lower-cases an address.
dateShift by a column: shiftBy#
Keyed on the day, an admission on the 1st and a discharge on the 2nd move by unrelated amounts and can come out a month apart in either order, failing a CHECK (discharged >= admitted) in the copy.
shiftBy names a column of the row whose value the shift is keyed on instead, usually the person the row is about:
columns:
patient_id: { strategy: key, domain: patients }
admitted: { strategy: dateShift, shiftBy: patient_id, maxDays: 180 }
discharged: { strategy: dateShift, shiftBy: patient_id, maxDays: 180 }
- Every date of one person moves by the same number of days, in every column and table that shifts by a column of that name, so their order and the time between them are kept. The shift is keyed on the
shiftBycolumn's value as read from the source, before it is masked. - The domain is the
shiftBycolumn's name, lower-cased, unless the policy names one, so the dates of one person agree across tables whatever each date column is called. Give columns that should move together the samemaxDays, or they agree in direction only. - A row whose
shiftByvalue is NULL is shifted by the day. - What it gives away: knowing one real date of a person and its mask reveals the shift for all of theirs. That is the price of keeping intervals, and why
maxDaysmatters more here.
The column must be one sourceQuery returns, other than the date column itself, or the job fails before writing anything.
coordinate#
number with a variance moves a value by a share of itself, so a coordinate near the equator or the prime meridian barely moves: 1% of London's longitude is about 60 metres. coordinate moves a point by a distance on the ground instead, between half of meters and all of it, in a keyed direction along its axis, wherever the point is:
columns:
lat: { strategy: coordinate, axis: latitude, meters: 2000 }
lng: { strategy: coordinate, axis: longitude, meters: 2000, latitudeColumn: lat }
- A degree of longitude spans fewer metres away from the equator.
latitudeColumnnames the row's latitude, read before it is masked, so a longitude moves bymetersat that latitude. Without it a longitude moves bymetersas measured at the equator: half that at 60°. - The move is keyed on the value, so equal coordinates mask alike. A latitude that would pass a pole moves the other way, and a longitude wraps at 180°.
- Floats come back as floats. A
Decimalkeeps its scale and moves at least one step of it; a column of two decimal places (about a kilometre) can't hold a smaller move. - A value outside its axis (beyond 90° for a latitude, 180° for a longitude) fails the job, naming the column, never the value.
scalereads a column of degrees stored multiplied, as integers or decimals:scale: 1000000for microdegrees (40712776for 40.712776°),10000000for the E7 of many GPS formats. The value is moved in degrees and comes back at its own type, an integer as an integer, moved at least one step.latitudeColumnis read at the same scale.
lat: { strategy: coordinate, axis: latitude, scale: 1000000 }
discover proposes coordinate for columns named like a latitude or a longitude, with latitudeColumn where the table has one latitude, and with scale where the sampled values are larger than degrees can be: check it, since their size alone suggested it. Sampled values no usual scale brings into range are proposed null.
ip#
digits and key on an address can make 589.439.074.458, and hash a hex token, none of which an inet column takes. ip maps every IPv4 address to an IPv4 address and every IPv6 address to an IPv6 address by key's keyed permutation over all 232 or 2128 of them, so it never collides and every mask is an address:
client_ip: ip # 192.168.1.10 -> 47.44.170.239
office_ip: { strategy: ip, keepPrefix: 16 } # 192.168.1.10 -> 192.168.217.255
keepPrefixkeeps that many leading bits, so the copy still says which /16 or /24 an address was in, and permutes the rest, keyed on the bits kept, so one host in two subnets lands apart. Keeping more bits leaves fewer to hide in:keepPrefix: 24leaves 256 possible masks for each address.- Values come back as they came: text as text, PostgreSQL's
inetandcidras addresses, interfaces and networks, with a mask's prefix length kept (10.1.2.3/24stays a /24, acidr's host bits stay zero), 4 or 16 bytes as bytes, and an integer below 232, as MySQL'sINET_ATONstores one, as an integer. - Text that isn't an address fails the job, naming the column, never the value.
- A MAC address needs no strategy of its own:
keywithcharset: hexkeeps it valid -- hex digits for hex digits, separators where they were -- and one-to-one.
Fake data by country#
The fake* strategies draw from an international mix of names and places by default. locale picks one country's names, cities and address layout instead: en_US, en_GB, de_DE, fr_FR, es_ES, it_IT, nl_NL or pt_BR.
columns:
full_name: { strategy: fakeName, locale: de_DE } # Lukas Schneider
street: { strategy: fakeStreetAddress, locale: fr_FR } # 12 rue des Lilas
Leaving locale out keeps the original lists, so existing masks don't change.
The larger lists: lists: 2#
The default lists are short: a few dozen first names and surnames per locale, so a million customers share a few hundred full names, and a search or de-duplication feature tested on them sees an unrealistic world. lists: 2 picks from longer ones: about 250 first names, 160 to 300 surnames and 70 to 90 cities in each locale, and every locale's together without locale. Masks made without it are unchanged.
With lists: 2 the name strategies also agree with one another:
- A full name masks part by part: its given names as
fakeFirstNamemasks them, its surname asfakeLastNamedoes, with a particle (de Jong,van der Berg,da Silva) kept with the surname, andSurname, Givenkept in that order. SoJohn Smithin afull_namecolumn agrees withJohnandSmithinfirst_nameandlast_name. - They mask in one domain,
fake name, rather than each column's own, so the agreement holds across tables too. Adomainon the policy overrides it, as for any strategy. - Names are matched as a person writes them, whatever their case or spacing, and written back in the original's case:
JOHNbecomes, say,JORGEwhereJohnbecomesJorge. matchGender: truereplaces a first name with one of the same gender, where the lists know the name as a woman's or a man's in any locale; a name they don't know, or know as both, gets one of either. That keeps a gender column and the names beside it plausible together — and so keeps the gender a name suggests, which is a reason to leave it off.
columns:
first_name: { strategy: fakeFirstName, lists: 2, matchGender: true }
last_name: { strategy: fakeLastName, lists: 2 }
full_name: { strategy: fakeName, lists: 2, matchGender: true } # agrees with the two above
lists: 2 gives fakeCity the longer city lists; fakeCompany and fakeStreetAddress are the same in both. It is masked in Python: the native masker covers lists: 1.
redact#
redact is for free text worth keeping, like support tickets, where null would lose too much:
columns:
ticket_body: { strategy: redact }
# Called Ann at [PHONE], card [CARD] was declined, reply to [EMAIL]
agent_notes: { strategy: redact, replacement: mask, patterns: ['ACC-\d{6}'] }
# Called Ann at +7 (362) 248-5677, card 4095 9565 2378 1111 was declined, account redacted-b934cf4da0a9
labelwrites[EMAIL],[PHONE],[SSN],[CARD],[IBAN],[IP], or[REDACTED]for your ownpatterns.maskwrites keyed values of the same shape instead: the same address always becomes the same masked address, a card keeps its last four digits, an IP becomes10.x.x.x.- Phone detection is broad on purpose: any run of 7–15 digits that isn't a date counts, order numbers included. Leave
phoneout ofdetectwhere that removes too much. - It can't recognise names, addresses written in words, or anything else without a fixed shape. "Call Maria about her divorce" passes through unchanged. Where text may hold that, use
null.auditnotes everyredactcolumn for this reason.
json#
json masks inside a JSON document -- PostgreSQL's json and jsonb, Oracle's JSON, MySQL's JSON, or text holding one -- field by field:
columns:
preferences:
strategy: json
fields:
contact.alt_email: email
contact.owner_id: { strategy: key, domain: customers } # matches customers.id masked in domain customers
family[].first_name: fakeFirstName
address: 'null' # an object, dropped whole
# no otherwise: values masked by what their key names, else redacted
- Paths join keys with dots, and name every element of an array with
[]:orders[].card, or[].emailfor a document that is an array. - A field's policy is any column policy but
shuffleand those naming another column (shiftBy,latitudeColumn). It masks in thedomainit names, else its path's last key. A policy on an object or array applies to it whole. - Without
otherwise, a value is masked by what its key names, asdiscoverreads a column's name: undername,dob,address,phone,email,ssnand the like (plurals too), it is masked as that kind (fakeName,dateShift,key...) in its key's domain, so{"ssn": ...}masks as anssncolumn does. Arrays and objects under such a key are masked element by element. A value that kind can't mask ("dob": "sometime in 1984") fails the job, naming its path. Matching is by words, soproduct.nameis masked as a person's name too: name it infieldsto keep it. - Every other value goes to
otherwise, by defaultredact, which masks identifiers it finds by shape (in text, and in whole numbers long enough to be a phone or card number) and leaves other values as they are. A name under a key that doesn't say so ("contact": "Ann Smith") passes through;auditnotes each suchjsoncolumn. Settingotherwiseturns key matching off:otherwise: 'null'removes every value no field names. - Keys are data too in a document keyed by, say, email address: identifiers
redactfinds in keys are masked, unlessotherwiseiskeep. Paths infieldsmatch keys as they came. - The document comes back in the form it came: an object as an object, JSON text as JSON text, keys in their order.
discover proposes a json policy for a JSON column whose sampled documents hold personal data, naming each path it found.
email, digits, key, fpe and redact also take a JSON document or an IP address -- a document as its JSON text, an inet value as it is written -- and return masked text, which a JSON or inet column loads as it would the literal.
Your own strategies#
A policy can name a class of your own as module.path:ClassName:
# acme/masks.py
from bauta.masking import Strategy, canonical
class Initials(Strategy):
OPTIONS = {'separator': str} # option name -> check that returns the value
def mask(self, value): # called for each non-NULL value
separator = self.options.get('separator', '.')
suffix = self.keyedHash.digest(canonical(value)).hex()[:4]
return separator.join(word[0] for word in value.split()) + separator + suffix
columns:
full_name: { strategy: "acme.masks:Initials", separator: "-" }
Derive anything random from self.keyedHash (digest, below, unit, permute), so the mask stays keyed, consistent within its domain, and reproducible. Key it on canonical(value), the bytes the built-in strategies key on, so the same id masks the same way whether a driver returned it as a number or as text. validate imports the class and checks its options; the module must also be importable wherever jobs run. The manifest records the strategy by the name the policy used.
If mask() depends on nothing but the value, set CACHEABLE = True on the class, and repeated values are remembered rather than masked again. It's off by default, since a strategy could depend on something else. A strategy that returns every value exactly as it was given, as keep does, sets PASSTHROUGH = True: its columns are carried through untouched, and checks that refuse a masked watermark column or a masked primary key treat them as unmasked.
A strategy that masks parts of a value in domains other than its column's, as json masks its fields, overrides bindKey(self, key): a masking plan calls it once, after building the strategy, with the masking key, to build a KeyedHash(key, domain) for each. The rest need only self.keyedHash.
Limits#
- Free text can hold personal data anywhere in it.
nullorconstantremove it all.redactkeeps the text and removes identifiers with a recognisable shape, but not names.hashwould only replace the text with an opaque token, andkeepwould copy it as it is. - Scripts other than Latin.
keyandfperefuse letters and digits outside ASCII rather than copy them;digitsandredacthandle digits in any script.redactfinds only email addresses written in ASCII. - Unique columns need
keyor enough bits.emailandhashcut a keyed hash tolengthhex characters, so two values can collide, and a unique column fails the load. The odds over distinct values: at 12 characters (email's default), one in 550 for a million rows and one in six for ten million; at 16 (hash's default), one in 3,600 for a hundred million; at 24, one in 1013. Givelength: 24to a unique email column.keynever collides, but on an email address scrambles the domain too, rather than using one that can't receive mail.fake*values are never unique. numberwithvariancekeeps magnitudes realistic, which also reveals them roughly. Usemin/maxif the magnitude itself is sensitive.dateShiftis keyed on the date, so people born on the same day still share a birthday: dates are shifted, not randomized. Two dates in a row move independently; useshiftBywhere their order matters.shuffleneeds large chunks. A row keeps its own value with probability 1/chunk size, and a one-row chunk isn't shuffled at all, so the last chunk of a load and a small incremental run barely move. Don't shuffle in incremental jobs:auditwarns, andrequireMaskingrefuses one.- Masking hides values, not patterns. Row counts, NULL rates and relationships are all preserved, which is the point, and a combination of kept columns (zip code, birth year and gender) can still identify someone. Review what you
keep. - Hard deletes aren't propagated by incremental loads, masked or not. See deletes.