29.11. Безопасность #

Роль, используемая для подключения репликации, должна иметь атрибут REPLICATION (или быть суперпользователем). Если у роли отсутствуют свойства SUPERUSER и BYPASSRLS, при репликации могут выполняться политики защиты строк, определённые на стороне публикации. Если эта роль не может доверять владельцам всех таблиц, добавьте в строку подключения options=-crow_security=off; если владелец таблицы добавит политику защиты строк позже, при таком значении параметра репликация остановится, но политика выполняться не будет. Доступ для этой роли должен быть настроен в pg_hba.conf, и эта роль также должна иметь атрибут LOGIN.

Имя модуля вывода, который используется для подключения репликации, должен быть включён в параметр output_plugin_libraries сервера. (Для подписок используется модуль с именем pgoutput.) Суперпользователи могут изменять список доверенных модулей на уровне отдельного соединения, добавив в строку подключения параметр options=-coutput_plugin_libraries=....

Чтобы иметь возможность скопировать исходные данные таблицы, роль, используемая для соединения репликации, должна иметь право SELECT в публикуемой таблице (или быть суперпользователем).

Чтобы создать публикацию, пользователь должен иметь право CREATE в базе данных.

Чтобы добавлять таблицы в публикацию, пользователь должен иметь права владельца для этих таблиц. Добавлять в публикацию все таблицы схемы может только суперпользователь. Также только суперпользователям разрешено создавать публикации, публикующие все таблицы или все таблицы в схеме автоматически.

На данный момент прав для публикаций нет. Любая подписка (имеющая возможность подключения) может получить доступ к любой публикации. Таким образом, если необходимо скрыть некоторую информацию от определённых подписчиков, например, используя фильтры строк или списки столбцов или не добавляя всю таблицу в публикацию, имейте в виду, что та же информация может раскрываться в других публикациях в той же базе данных. В будущем в PostgreSQL могут быть добавлены права для публикаций, чтобы обеспечить более детальный контроль доступа.

Чтобы создать подписку, пользователь должен иметь права роли pg_create_subscription, а также права CREATE для базы данных.

Процесс применения подписки на уровне сеанса будет выполняться с правами владельца подписки. Однако при выполнении операции вставки, изменения, удаления или усечения в конкретной таблице происходит переключение роли на владельца таблицы и выполнит операцию с правами владельца таблицы. Это означает, что владелец подписки должен иметь право SET ROLE для каждой роли, которой принадлежит реплицируемая таблица.

Если подписка сконфигурирована с run_as_owner = true, переключение пользователей не произойдёт. Вместо этого все операции будут выполняться с правами владельца подписки. В этом случае владельцу подписки нужны только права SELECT, INSERT, UPDATE и DELETE из целевой таблицы, но не SET ROLE для владельца таблицы. Однако это также означает, что любой пользователь, владеющий таблицей, в которую реплицируются данные, может выполнять произвольный код с правами владельца подписки. Например, это можно сделать, добавив триггер к одной из принадлежащих этому пользователю таблиц. Поскольку обычно нежелательно позволять одной роли свободно присваивать права другой, не рекомендуется использовать этот параметр, кроме случаев, когда безопасность пользователей в базе данных не вызывает сомнений.

На публикующем сервере права проверяются только один раз при установлении подключения для репликации и не перепроверяются при чтении каждой записи изменения.

На стороне подписки права владельца подписки перепроверяются для каждой транзакции, когда она применяется. Если рабочий процесс осуществляет применение транзакции, когда в параллельной транзакции меняется владелец подписки, применение текущей транзакции продолжается с правами старого владельца.

29.11. Security #

The role used for the replication connection must have the REPLICATION attribute (or be a superuser). If the role lacks SUPERUSER and BYPASSRLS, publisher row security policies can execute. If the role does not trust all table owners, include options=-crow_security=off in the connection string; if a table owner then adds a row security policy, that setting will cause replication to halt rather than execute the policy. Access for the role must be configured in pg_hba.conf and it must have the LOGIN attribute.

The name of the output plugin used by the replication connection must be included in the server's output_plugin_libraries. (For subscriptions, the plugin name that is used is pgoutput.) Superusers may modify the trusted list per-connection, by including options=-coutput_plugin_libraries=... in the connection string.

In order to be able to copy the initial table data, the role used for the replication connection must have the SELECT privilege on a published table (or be a superuser).

To create a publication, the user must have the CREATE privilege in the database.

To add tables to a publication, the user must have ownership rights on the table. To add all tables in schema to a publication, the user must be a superuser. To create a publication that publishes all tables or all tables in schema automatically, the user must be a superuser.

There are currently no privileges on publications. Any subscription (that is able to connect) can access any publication. Thus, if you intend to hide some information from particular subscribers, such as by using row filters or column lists, or by not adding the whole table to the publication, be aware that other publications in the same database could expose the same information. Publication privileges might be added to PostgreSQL in the future to allow for finer-grained access control.

To create a subscription, the user must have the privileges of the pg_create_subscription role, as well as CREATE privileges on the database.

The subscription apply process will, at a session level, run with the privileges of the subscription owner. However, when performing an insert, update, delete, or truncate operation on a particular table, it will switch roles to the table owner and perform the operation with the table owner's privileges. This means that the subscription owner needs to be able to SET ROLE to each role that owns a replicated table.

If the subscription has been configured with run_as_owner = true, then no user switching will occur. Instead, all operations will be performed with the permissions of the subscription owner. In this case, the subscription owner only needs privileges to SELECT, INSERT, UPDATE, and DELETE from the target table, and does not need privileges to SET ROLE to the table owner. However, this also means that any user who owns a table into which replication is happening can execute arbitrary code with the privileges of the subscription owner. For example, they could do this by simply attaching a trigger to one of the tables which they own. Because it is usually undesirable to allow one role to freely assume the privileges of another, this option should be avoided unless user security within the database is of no concern.

On the publisher, privileges are only checked once at the start of a replication connection and are not re-checked as each change record is read.

On the subscriber, the subscription owner's privileges are re-checked for each transaction when applied. If a worker is in the process of applying a transaction when the ownership of the subscription is changed by a concurrent transaction, the application of the current transaction will continue under the old owner's privileges.

FAQ