Как замаскировать адреса электронной почты перед выгрузкой или передачей данных?
Кому-то нужен список адресов клиентов для теста или отчёта, и настоящие адреса ему получать нельзя. Нужно a***e@example.com вместо alice@example.com, а остальные колонки вообще не должны покидать файл.
Маскирование — маленькая функция, а данные утекают через её крайние случаи: короткие имена, верхний регистр, значения, которые не являются адресами. Два пайпа, использованные здесь, обрабатывают эти случаи и приходят с собственными тестами.
Пайп — шаг обработки данных с объявленными входами и выходами; пайплайн соединяет пайпы.
Что понадобится
- Команда
openflange, релиз v0.0.1:bashgo install github.com/openflange/openflange-go/cmd/openflange@v0.0.1 - Пустой каталог. Создайте в нём файлы, приведённые ниже, точно под этими именами и выполняйте все команды из этого каталога.
- Больше ничего: все шаги рецепта выполняются в процессе раннера (программы, которая запускает пайпы). Ни сети, ни учётной записи, ни ключа.
Шаги
1. Сохраните входной файл
Четыре клиента. Один адрес в смешанном регистре, у одного имя из двух букв, одно значение — не адрес.
id,name,email,country
1,Ada Lovelace,Ada.Lovelace@Example.COM,GB
2,Bo Li,bo@example.org,CN
3,Grace Hopper,GRACE@navy.example,US
4,Linus,linus-at-example.net,FI2. Добавьте два пайпа
lowercase — одно выражение Starlark прямо в манифесте. mask-email — манифест и скрипт на Starlark. Оба скопированы из репозитория без изменений.
---
spec: openflange.org/pipe/v0.1
id: lowercase
version: 0.1.0
title: Lowercase
description: Lower-cases every string of a stream.
license: Apache-2.0
keywords: [text, string, lowercase, normalize]
maturity: experimental
scope: record
cardinality: one-to-one
deterministic: true
inputs:
text:
description: Strings, one JSON string per NDJSON line.
schema:
format: json-schema
definition: {type: string}
outputs:
text:
description: The same strings in lower case, in input order.
schema:
format: json-schema
definition: {type: string}
implementation:
type: expression
language: starlark
expression: text.lower()
---
# Lowercase
Implements the [OpenFlange](https://openflange.org/) specification.
Lower-cases every string it receives using Unicode case mapping
(`"Ünïcödé"` becomes `"ünïcödé"`). One string in, one string out, in order:
the pipe is one-to-one and deterministic, so hosts may also call it as a
scalar function.
```sh
printf '"Alice@Example.COM"\n' | openflange run ./pipes/lowercase
# "alice@example.com"
```
Items are scalar values: one JSON string per NDJSON line. A non-string item
fails the run with `E_RUNTIME`.Скопировано без изменений из examples/email/pipes/lowercase/OPENFLANGE.md в репозитории openflange-go.
---
spec: openflange.org/pipe/v0.1
id: mask-email
version: 0.1.0
title: Mask email
description: Masks the middle of the local part of e-mail addresses; routes invalid addresses to `rejected`.
license: Apache-2.0
keywords: [email, mask, privacy, pii]
maturity: experimental
scope: record
deterministic: true
inputs:
email:
description: E-mail addresses, one JSON string per NDJSON line.
schema:
format: json-schema
definition: {type: string}
outputs:
email:
description: Masked addresses, in input order (invalid inputs are not included).
schema:
format: json-schema
definition: {type: string}
rejected:
required: false
description: Inputs that are not valid addresses, as {"value", "reason"}. If this port is not connected an invalid input fails the run.
schema:
format: json-schema
definition:
type: object
properties:
value: {}
reason: {type: string}
required: [value, reason]
parameters:
character:
type: string
default: "*"
minLength: 1
maxLength: 1
description: Masking character; exactly one Unicode code point.
preserveFirst:
type: integer
default: 1
minimum: 0
maximum: 8
description: Number of leading characters of the local part to keep.
preserveLast:
type: integer
default: 1
minimum: 0
maximum: 8
description: Number of trailing characters of the local part to keep.
implementation:
type: script
language: starlark
path: mask.star
---
# Mask email
Implements the [OpenFlange](https://openflange.org/) specification.
Masks the middle of the local part of an e-mail address and keeps the domain:
`alice@example.com` becomes `a***e@example.com`.
> **Masking is not anonymisation.** The domain and the edge characters are
> preserved and can still identify a person, especially in small domains.
> Treat masked addresses as personal data.
## Semantics
All lengths are counted in Unicode code points.
- The address is split at the **last** `@`. It is valid when it is a string
with exactly one `@`, a non-empty local part, a non-empty domain and no
whitespace.
- Let `L` be the length of the local part, `f = preserveFirst`,
`l = preserveLast`.
- `L > f + l`: the first `f` characters, then `L − f − l` masking
characters, then the last `l` characters.
- `L ≤ f + l` (short local part): the whole local part is replaced by `L`
masking characters, so a short name is never revealed entirely
(`ab@x.io` → `**@x.io`).
- The domain is copied unchanged (this pipe does not change case; put
`lowercase` in front of it to normalise).
- **Invalid input is never masked and never silently dropped.** It is emitted
on the optional output `rejected` as `{"value": <input>, "reason": "..."}`.
If `rejected` is not connected, the first invalid item fails the run with
`E_RUNTIME`.
Because an item goes either to `email` or to `rejected`, the pipe is not
one-to-one.
## Parameters
| name | type | default | bounds |
|---|---|---|---|
| `character` | string | `*` | exactly one Unicode code point (otherwise `E_PARAM`) |
| `preserveFirst` | integer | 1 | 0 … 8 |
| `preserveLast` | integer | 1 | 0 … 8 |
## Examples
| input | output |
|---|---|
| `alice@example.com` | `a***e@example.com` |
| `ab@x.io` | `**@x.io` |
| `ünïcödé@example.com` | `ü*****é@example.com` |
| `not-an-address` | rejected: `expected exactly one @` |
```sh
printf '"alice@example.com"\n' | openflange run ./pipes/mask-email
# "a***e@example.com"
```Скопировано без изменений из examples/email/pipes/mask-email/OPENFLANGE.md в репозитории openflange-go.
# SPDX-License-Identifier: Apache-2.0
# mask-email: masks the local part of an email address (reference fixture,
# contract baseline section 10). All lengths are in Unicode code points.
def _invalid(item):
"""Returns the rejection reason, or None when the item is a valid address."""
if type(item) != "string":
return "not a string"
if item.count("@") != 1:
return "expected exactly one @"
local, _, domain = item.rpartition("@")
if local == "":
return "empty local part"
if domain == "":
return "empty domain"
for c in item.codepoints():
if c.isspace():
return "contains whitespace"
return None
def process(item, params):
character = params["character"]
if len(list(character.codepoints())) != 1:
fail("parameter character must be exactly one Unicode code point")
reason = _invalid(item)
if reason != None:
# Record-level errors are data. If `rejected` is not connected this
# emit fails the run (E_RUNTIME): invalid items are never dropped.
emit("rejected", {"value": item, "reason": reason})
return None
local, _, domain = item.rpartition("@")
cps = list(local.codepoints())
n = len(cps)
first = params["preserveFirst"]
last = params["preserveLast"]
if n > first + last:
masked = "".join(cps[:first]) + character * (n - first - last) + "".join(cps[n - last:])
else:
# Short local part: never reveal it entirely.
masked = character * n
emit("email", masked + "@" + domain)
return NoneСкопировано без изменений из examples/email/pipes/mask-email/mask.star в репозитории openflange-go.
3. Опишите пайплайн и его контракт
pick берёт из каждой строки только колонку email, поэтому ничто другое не может попасть на выход. Три параметра маскирования проброшены на уровень пайплайна.
# csv ─▶ decode ─▶ pick ─▶ lowercase ─▶ mask ─┬─▶ masked
# └─▶ rejected
spec: openflange.org/pipeline/v0.1
nodes:
decode:
pipe: std:csv-decode
inputs:
in: {from: inputs.csv}
pick:
pipe: std:map # only the address leaves the file: one JSON string per row
inputs:
in: {from: decode.outputs.out}
parameters:
expr: 'item["email"]'
lowercase:
pipe: ./pipes/lowercase
inputs:
text: {from: pick.outputs.out}
mask:
pipe: ./pipes/mask-email
inputs:
email: {from: lowercase.outputs.text}
parameters:
character: {$param: character}
preserveFirst: {$param: preserveFirst}
preserveLast: {$param: preserveLast}
outputs:
masked: {from: mask.outputs.email}
rejected: {from: mask.outputs.rejected}---
spec: openflange.org/pipe/v0.1
id: mask-personal-data
version: 0.1.0
title: Mask e-mail addresses before export
description: Reads a customers CSV and writes only the e-mail addresses, lower-cased and with the middle of the local part masked; values that are not addresses are routed to `rejected`.
license: Apache-2.0
keywords: [email, mask, privacy, pii, csv, recipe]
maturity: experimental
scope: record
inputs:
csv:
kind: text
mediaTypes: [text/csv]
description: 'Customers with a header row that has an `email` column.'
outputs:
masked:
description: Lower-cased, masked addresses, one JSON string per line (valid addresses only).
rejected:
required: false
description: 'Values that are not valid addresses, as {"value", "reason"}. If not connected, the first invalid value fails the run.'
parameters:
character: {type: string, default: "*", description: Masking character (one Unicode code point).}
preserveFirst: {type: integer, default: 1, minimum: 0, maximum: 8, description: Leading characters of the local part to keep.}
preserveLast: {type: integer, default: 1, minimum: 0, maximum: 8, description: Trailing characters of the local part to keep.}
implementation:
type: pipeline
path: pipeline.yaml
---
# Mask e-mail addresses before export
Implements the [OpenFlange](https://openflange.org/) specification.
Only the `email` column leaves the file; every other column is dropped by the
`pick` node. Masking is not anonymisation: the domain and the edge characters
are preserved and can still identify a person. Permissions: none.4. Проверьте и запустите
Замаскированные адреса идут в один файл, а значения, которые не являются адресами, — в другой.
openflange validate .valid: . (4 nodes, 6 edges)openflange run . --input csv=customers.csv --output masked=masked.ndjson --output rejected=rejected.ndjsoncompleted in 417µs — masked: 3 records, rejected: 1 record"a**********e@example.com"
"**@example.org"
"g***e@navy.example"{"value":"linus-at-example.net","reason":"expected exactly one @"}Имя из двух букв замаскировано целиком. Значение без @ не замаскировано и не потеряно: оно в rejected.ndjson вместе с причиной.
5. Замаскируйте сильнее
Не оставляйте ни одного символа имени и возьмите другой символ маски.
openflange run . --input csv=customers.csv --output masked=- --output rejected=rejected.ndjson --param preserveFirst=0 --param preserveLast=0 --param 'character=#'"############@example.com"
"##@example.org"
"#####@navy.example"
completed in 2ms — masked: 3 records, rejected: 1 record6. Посмотрите, что будет, если плохим значениям некуда идти
Если rejected не привязан, первое значение, которое не является адресом, останавливает запуск.
openflange run . --input csv=customers.csvE_RUNTIME: item 4: emit: output "rejected" of mask-email is not enabled (nothing consumes it); data is never dropped silently (node mask, port rejected)
at: mask.star:30:13 in process
hint: connect the output, set `outputs: {rejected: {discard: true}}` on the node, or guard the call with `if enabled("rejected"):`
failed in 1ms — masked: 0 records7. Протестируйте
Четыре теста пайплайна и восемнадцать тестов, которые приходят вместе с двумя пайпами.
spec: openflange.org/test/v0.1
pipe: ..
tests:
- name: addresses are lower-cased and masked; no other column is in the output
inputs:
csv:
text: |
id,name,email,country
1,Ada Lovelace,Ada.Lovelace@Example.COM,GB
2,Bo Li,bo@example.org,CN
expect:
outputs:
masked: {values: ["a**********e@example.com", "**@example.org"]}
rejected: {count: 0}
- name: a value that is not an address is routed to rejected, never masked
inputs:
csv:
text: |
id,name,email,country
4,Linus,linus-at-example.net,FI
expect:
outputs:
masked: {count: 0}
rejected:
values: [{value: "linus-at-example.net", reason: "expected exactly one @"}]
- name: masking character and kept characters are parameters
parameters: {character: "#", preserveFirst: 2, preserveLast: 0}
inputs:
csv: {text: "email\nalice@example.com\n"}
expect:
outputs:
masked: {values: ["al###@example.com"]}
- name: without a rejected consumer an invalid address fails the run
inputs:
csv: {text: "email\nlinus-at-example.net\n"}
expect:
status: failed
error: {code: E_RUNTIME}
outputs:
rejected: {disabled: true}spec: openflange.org/test/v0.1
pipe: ..
tests:
- name: lowercases mixed case
inputs:
text: {values: ["Alice@Example.COM"]}
expect:
outputs:
text: {values: ["alice@example.com"]}
- name: keeps order and handles Unicode
inputs:
text: {values: ["ÜNÏCÖDÉ", "already lower", ""]}
expect:
outputs:
text: {values: ["ünïcödé", "already lower", ""]}
- name: empty stream is valid
inputs:
text: {values: []}
expect:
outputs:
text: {count: 0}
- name: non-string input fails the run
inputs:
text: {values: [42]}
expect:
status: failed
error: {code: E_RUNTIME}Скопировано без изменений из examples/email/pipes/lowercase/tests/lowercase.test.yaml в репозитории openflange-go.
spec: openflange.org/test/v0.1
pipe: ..
tests:
- name: masks the middle of the local part
inputs:
email: {values: ["alice@example.com"]}
expect:
outputs:
email: {values: ["a***e@example.com"]}
rejected: {count: 0}
- name: short local parts are fully masked
inputs:
email: {values: ["ab@x.io", "a@x.io", "abc@x.io"]}
expect:
outputs:
email: {values: ["**@x.io", "*@x.io", "a*c@x.io"]}
rejected: {count: 0}
- name: counts Unicode code points, not bytes
inputs:
email: {values: ["ünïcödé@example.com", "日本語のアドレス@例.jp"]}
expect:
outputs:
email: {values: ["ü*****é@example.com", "日******ス@例.jp"]}
rejected: {count: 0}
- name: domain is preserved unchanged
inputs:
email: {values: ["Alice@Example.COM"]}
expect:
outputs:
email: {values: ["A***e@Example.COM"]}
rejected: {disabled: true}
- name: custom character and preserve counts
parameters: {character: "#", preserveFirst: 2, preserveLast: 0}
inputs:
email: {values: ["alice@example.com"]}
expect:
outputs:
email: {values: ["al###@example.com"]}
rejected: {disabled: true}
- name: a multi-byte masking character is one code point
parameters: {character: "•"}
inputs:
email: {values: ["alice@example.com"]}
expect:
outputs:
email: {values: ["a•••e@example.com"]}
rejected: {disabled: true}
- name: preserve nothing masks everything
parameters: {preserveFirst: 0, preserveLast: 0}
inputs:
email: {values: ["alice@example.com"]}
expect:
outputs:
email: {values: ["*****@example.com"]}
rejected: {disabled: true}
- name: invalid addresses are routed to rejected, valid ones still flow
inputs:
email:
values:
- "no-at-sign"
- "two@@example.com"
- "a@b@example.com"
- "@example.com"
- "alice@"
- "al ice@example.com"
- 42
- "bob@example.com"
expect:
outputs:
email: {values: ["b*b@example.com"]}
rejected:
values:
- {value: "no-at-sign", reason: "expected exactly one @"}
- {value: "two@@example.com", reason: "expected exactly one @"}
- {value: "a@b@example.com", reason: "expected exactly one @"}
- {value: "@example.com", reason: "empty local part"}
- {value: "alice@", reason: "empty domain"}
- {value: "al ice@example.com", reason: "contains whitespace"}
- {value: 42, reason: "not a string"}
schema:
type: object
required: [value, reason]
properties:
reason: {type: string}
- name: an invalid address fails the run when rejected is not connected
inputs:
email: {values: ["alice@example.com", "no-at-sign"]}
expect:
status: failed
error: {code: E_RUNTIME}
outputs:
rejected: {disabled: true}
- name: preserveFirst above the maximum is rejected
parameters: {preserveFirst: 9}
inputs:
email: {values: ["alice@example.com"]}
expect:
status: failed
error: {code: E_PARAM}
- name: negative preserveLast is rejected
parameters: {preserveLast: -1}
inputs:
email: {values: ["alice@example.com"]}
expect:
status: failed
error: {code: E_PARAM}
- name: character must be exactly one code point
parameters: {character: "**"}
inputs:
email: {values: ["alice@example.com"]}
expect:
status: failed
error: {code: E_PARAM}
- name: empty character is rejected
parameters: {character: ""}
inputs:
email: {values: ["alice@example.com"]}
expect:
status: failed
error: {code: E_PARAM}
- name: empty input stream
inputs:
email: {values: []}
expect:
outputs:
email: {count: 0}
rejected: {count: 0}Скопировано без изменений из examples/email/pipes/mask-email/tests/mask-email.test.yaml в репозитории openflange-go.
openflange test . ./pipes/lowercase ./pipes/mask-emailtests/mask-personal-data.test.yaml
ok addresses are lower-cased and masked; no other column is in the output
ok a value that is not an address is routed to rejected, never masked
ok masking character and kept characters are parameters
ok without a rejected consumer an invalid address fails the run
pipes/lowercase/tests/lowercase.test.yaml
ok lowercases mixed case
ok keeps order and handles Unicode
ok empty stream is valid
ok non-string input fails the run
pipes/mask-email/tests/mask-email.test.yaml
ok masks the middle of the local part
ok short local parts are fully masked
ok counts Unicode code points, not bytes
ok domain is preserved unchanged
ok custom character and preserve counts
ok a multi-byte masking character is one code point
ok preserve nothing masks everything
ok invalid addresses are routed to rejected, valid ones still flow
ok an invalid address fails the run when rejected is not connected
ok preserveFirst above the maximum is rejected
ok negative preserveLast is rejected
ok character must be exactly one code point
ok empty character is rejected
ok empty input stream
ok 22 tests passed in 3 files (36ms)Ограничения
- Маскирование — не анонимизация. Домен и крайние символы сохраняются и могут указывать на человека, особенно в небольшом домене. Обращайтесь с замаскированными адресами как с персональными данными.
- Выгружается только адрес. Эти два пайпа работают с потоком строк, поэтому остальные колонки с ними не едут. Чтобы замаскировать одно поле записи и сохранить остальные, нужен пайп, который работает с записями; здесь он не показан.
- Обрабатываются только адреса электронной почты: ни имена, ни телефоны, ни свободный текст.
- Адрес считается верным, если в нём ровно один
@, непустые имя и домен и нет пробельных символов. Это проверка на здравый смысл, а не полная проверка адреса. - Маска детерминирована и необратима. Два разных адреса могут дать одно замаскированное значение, поэтому ключом она служить не может.
- Разрешения не нужны: все узлы выполняются в процессе раннера.
Связанные страницы
- Стандартные пайпы в этом рецепте:
std:csv-decode,std:map - Концепции, на которых он построен: Пайплайны, Порты
- Примеры из репозитория: Замаскировать email, Ветвление без повторного запуска
- Собираете это с помощью ИИ-агента? Дайте ему руководство для агентов: правила, раскладку файлов и команды, которыми он проверит собственную работу.
Все команды на этой странице выполнены в Linux с openflange 0.0.1 (go1.27.1 linux/amd64), собранным из коммита 11cf8cc5378d70858724b16aa937d7f3b98c085d репозитория openflange-go. Файлы и записанный вывод хранятся в репозитории сайта в каталоге sites/dev/test/fixtures/recipes/mask-personal-data/, и тест побайтно сравнивает с ними эту страницу.