Coder Social home page Coder Social logo

pg_stage's Introduction

pg_stage

A utility for generating a database dump, the data in which will be obfuscated. This dump can be used in development and stage servers without fear of their theft.

Content

How does it work?

The utility processes the output of the pg_dump command line by line and decides whether to obfuscate data at the level of comments to a table or column.

Usage example

  1. You need to create a file with approximately the following contents:
# main.py
from pg_stage.obfuscator import Obfuscator


obfuscator = Obfuscator(locale='ru_RU')
obfuscator.run()
  1. Add comments to a column or table:
COMMENT ON COLUMN table_1.first_name IS 'anon: [{"mutation_name": "first_name"}]';
  1. Run pg_dump and redirect the stream to the running script process:
pg_dump -d database | python3 main.py > dump.sql
  1. After that you will get the obfuscated data in the table

Supported types of obfuscation

You can see the current list here.

Why did I write my utility?

I also adhere to the rule that you do not need to place third-party plugins in the working database for its security (most utilities are in the form of database extensions).

Also, in similar utilities, I could not find the functionality for uniform obfuscation of data in related tables. This prompted me to write my own utility that will be able to obfuscate data in related tables with the same result by a foreign key.

Example:

COMMENT ON COLUMN table_1.first_name IS 'anon: [{"mutation_name": "first_name", "relations": [{"table_name": "table_1", "column_name": "last_name", "from_column_name": "id", "to_column_name": "id"}]}]';

where relations - links on tables where it is necessary to obfuscate fields according to the current field.

Thanks for the inspiration

pg_stage's People

Contributors

froozzy avatar ilyichumakov avatar

Stargazers

Ostaptsov Danil avatar Dmitry Svobodiannikov avatar  avatar  avatar  avatar  avatar Dmitriy Meshari avatar

Watchers

 avatar

Forkers

ilyichumakov

pg_stage's Issues

Добавить поддержку обработки чисел

Сейчас нет обработки для числовых полей, которые также могут быть приватными.

  • Добавить обработку числовых полей
  • Добавить условия min и max для числовых полей

Добавить поддержку проверки вхождения элемента в список

Сейчас возникла проблема, что необходимо удалить некоторые строки из рестора, но при этом в строках, которые не удаляются провести обфускацию. Для этого был разработан механизм условий обфускаций, но он сейчас проверяет всего три паттерна. Поэтому необходимо:

  • - добавить новое условие обфускация in, которое бы проверяло вхождение в список строк
  • - добавить мутатор mutation_delete_row, которое удаляет строку

Обфускация текста по паттерну

Встретился кейс, когда нужно обфусцировать текст, но по определенному шаблону, например:

ИНН: 0000000000000
ОГРН: 111111111111111111

где 0000000000000 и 111111111111111111 подлежат обфускации. Это могут быть любые символы, поэтому нужен метод, который на вход принимает паттерн, а на выходе уже готовый текст

Add the ability to set conditions

The transmission of conditions can be organized as follows:

COMMENT ON COLUMN auth_user_replace.email IS 'anon: {"mutation_name": "email", "conditions": [{"column_name": "is_staff", "operation": "equal", "value": "t"}]}';

Possible operation values:

  • equal
  • not equal
  • by pattern

The conditions in the list are checked using a logical or. In the future, you can also add a check for logical and

Обфускация поля по данным другого/других полей

  1. Есть поле ФИО, которое состоит из значения трех других полей: фамилии, имени, отчества.
    Хотелось бы заполнить его на основе уже обработанных полей.
    table.fio = table.first_name + table.second_name + table.last_name

  2. Аналогично для полей телефона, у нас есть телефон, который должен совпадать между таблицами.
    Мы храним его с маской и без, хотелось бы заполнять его на основе другого поля.
    table.phone_original = table.phone

Использование дат замедляет обфускацию

Фидбек от пользователя:

Передаю замедления по полям:

    past_date
    future_date
    MUTATION_KWARGS: {'start_date': '-80years'}

Мы отключили эти обфускации и стало заметно быстрее.
Это не срочно, низкоприоритетно, мы просто сделаем пустые поля для дат.
Замеряли с ними (было около 5 часов), закомментировал миграции по этим полям и стало быстрее.

Так же генерация уникальных значений со временем так же начинает замедлять процесс.

Баг при генерации уникальных значений

  • Обнаружили баг, что генерация уникальных значений не работает. Суть бага заключена в
            ...
            value = func(*args, **kwargs)
            if not set(value) & self._unique_values:  <----
                self._unique_values.add(value)
                break
            ....

set('123') == {'1', '2', '3'}

Add the ability to obfuscate values in related tables when there is no connection

For example, there are three tables that are interconnected:

изображение

If the name of the links is the same, then there will be no problems. But if the name of the links in Table 2 is different, for example, for Table 1 it is id, and for Table 3 it is uuid, then we will get a race of signals.

Therefore, it is necessary to think about how you can take into account several relationships in one table to other tables, which also need to be obfuscated and they all contain the same data

Добавить уникальность значений для полей

Столкнулись с проблемой, что необходимо уникальное новое значение для поля, но Faker генерирует псевдослучайное значение, что иногда приводит к коллизиям.

  • Необходимо опционально через mutation_kwargs добавить возможность генерировать уникальные значения

Add the ability to set choices

The transmission of choices can be organized as follows:

COMMENT ON COLUMN object.color IS 'anon: {"mutation_name": "random_choice", "choices": ["red", "green", "blue"]}';

Mutator will have to pick a random element from the list

Уход от поддержки faker

Mimesis показал себя очень хорошо в тестировании, поэтому можно уходить от поддежрки faker

Visual edits

Make visual edits to:

  • readme.md
  • docstrings
  • typing

JSONField: update, delete

Требуется добавить (мутатор ?) для частичного обновления JSONField.
Например в БД было:

{"key1": 1, "key2": 2}

Должно быть что-то вроде

{"mutation_name": "json_update", "mutation_kwargs": {"key1": {"mutation_name": "first_name"}}}

Т.е. в mutation_kwargs указывается список ключей, которые необходимо заменить, и то, на что их необходимо заменить, так же будет неплохо добавить возможность очистки конкретного ключа, например

{"mutation_name": "json_update", "mutation_kwargs": {"key1": {"mutation_name": "delete"}}}

Подробный пример для понимания:
В бд был json:

{"key1": "foo", "key2": "bar", "key3": 123}

После преобразования

{"mutation_name": "json_update", "mutation_kwargs": {"key2": {"mutation_name": "first_name"}}}

должно получиться что-то вроде

{"key1": "foo", "key2": "{Какое-нибудь сгенерированное faker-ом first_name}", "key3": 123}

upd:
поведение для случая когда ключа в словаре нет: просто добавляем ключ. При удалении: просто пропускаем

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.