Compare languages | Модуль user-authz: FAQ

Как создать пользователя?

How do I create a user?

Создание пользователя.

Creating a user.

Как ограничить права пользователю конкретными пространствами имён?

How do I limit user rights to specific namespaces?

Чтобы ограничить права пользователя конкретными пространствами имён в экспериментальной ролевой модели, используйте в RoleBinding use-роль с соответствующим уровнем доступа. Пример….

To limit a user’s rights to specific namespaces in the experimental role-based model, use RoleBinding with the use role that has the appropriate level of access. Example….

В текущей ролевой модули используйте параметры namespaceSelector или limitNamespaces (устарел) в кастомном ресурсе ClusterAuthorizationRule.

In the current role-based model, use the namespaceSelector or limitNamespaces (deprecated) parameters in the ClusterAuthorizationRule CR.

Что, если два ClusterAuthorizationRules подходят для одного пользователя?

What if there are two ClusterAuthorizationRules matching to a single user?

Представьте, что пользователь jane.doe@example.com состоит в группе administrators. Созданы два ClusterAuthorizationRules:

Imagine that the user jane.doe@example.com is in the administrators group. There are two cluster authorization rules:

yaml apiVersion: deckhouse.io/v1 kind: ClusterAuthorizationRule metadata: name: jane spec: subjects:

  • kind: User name: jane.doe@example.com accessLevel: User namespaceSelector: labelSelector: matchLabels: env: review — apiVersion: deckhouse.io/v1 kind: ClusterAuthorizationRule metadata: name: admin spec: subjects:
  • kind: Group name: administrators accessLevel: ClusterAdmin namespaceSelector: labelSelector: matchExpressions:
  • key: env operator: In values:
  • prod
  • stage

yaml apiVersion: deckhouse.io/v1 kind: ClusterAuthorizationRule metadata: name: jane spec: subjects:

  • kind: User name: jane.doe@example.com accessLevel: User namespaceSelector: labelSelector: matchLabels: env: review — apiVersion: deckhouse.io/v1 kind: ClusterAuthorizationRule metadata: name: admin spec: subjects:
  • kind: Group name: administrators accessLevel: ClusterAdmin namespaceSelector: labelSelector: matchExpressions:
  • key: env operator: In values:
  • prod
  • stage
  1. jane.doe@example.com имеет право запрашивать и просматривать объекты среди всех пространств имён, помеченных env=review.
  2. Administrators могут запрашивать, редактировать, получать и удалять объекты на уровне кластера и из пространств имён, помеченных env=prod и env=stage.
  1. jane.doe@example.com has the right to get and list any objects in the namespaces labeled env=review
  2. Administrators can get, edit, list, and delete objects on the cluster level and in the namespaces labeled env=prod and env=stage.

Так как для Jane Doe подходят два правила, необходимо провести вычисления:

  • Она будет иметь самый сильный accessLevel среди всех подходящих правил — ClusterAdmin.
  • Опции namespaceSelector будут объединены так, что Jane Doe будет иметь доступ в пространства имён, помеченные меткой env со значением review, stage или prod.

Because Jane Doe matches two rules, some calculations will be made:

  • She will have the most powerful accessLevel across all matching rules — ClusterAdmin.
  • The namespaceSelector options will be combined, so that Jane will have access to all the namespaces labeled with env label of the following values: review, stage, or prod.

Note! Если есть правило без опции namespaceSelector и без опции limitNamespaces (устаревшая), это значит, что доступ разрешён во все пространства имён, кроме системных, что повлияет на результат вычисления доступных пространств имён для пользователя.

Note! If there is a rule without the namespaceSelector option and limitNamespaces deprecated option, it means that all namespaces are allowed excluding system namespaces, which will affect the resulting limit namespaces calculation.

Как расширить роли или создать новую?

How do I extend a role or create a new one?

Экспериментальная ролевая модель построена на принципе агрегации, она собирает более мелкие роли в более обширные, тем самым предоставляя лёгкие способы расширения модели собственными ролями.

The experimental role model is based on the aggregation principle; it compiles smaller roles into larger ones, thus providing easy ways to enhance the model with custom roles.

Создание новой роли подсистемы

Creating a new role subsystem

Предположим, что текущие подсистемы не подходят под ролевое распределение в компании и требуется создать новую подсистему, которая будет включать в себя роли из подсистемы deckhouse, подсистемы kubernetes и модуля user-authn.

Suppose that the current subsystems do not fit the role distribution in the company. You need to create a new subsystem that includes roles from the deckhouse subsystem, the kubernetes subsystem and the user-authn module.

Для решения этой задачи создайте следующую роль:

To meet this need, create the following role:

yaml apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: custom:manage:mycustom:manager labels: rbac.deckhouse.io/use-role: admin rbac.deckhouse.io/kind: manage rbac.deckhouse.io/level: subsystem rbac.deckhouse.io/subsystem: custom rbac.deckhouse.io/aggregate-to-all-as: manager aggregationRule: clusterRoleSelectors:

  • matchLabels: rbac.deckhouse.io/kind: manage rbac.deckhouse.io/aggregate-to-deckhouse-as: manager
  • matchLabels: rbac.deckhouse.io/kind: manage rbac.deckhouse.io/aggregate-to-kubernetes-as: manager
  • matchLabels: rbac.deckhouse.io/kind: manage module: user-authn rules: []

yaml apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: custom:manage:mycustom:manager labels: rbac.deckhouse.io/use-role: admin rbac.deckhouse.io/kind: manage rbac.deckhouse.io/level: subsystem rbac.deckhouse.io/subsystem: custom rbac.deckhouse.io/aggregate-to-all-as: manager aggregationRule: clusterRoleSelectors:

  • matchLabels: rbac.deckhouse.io/kind: manage rbac.deckhouse.io/aggregate-to-deckhouse-as: manager
  • matchLabels: rbac.deckhouse.io/kind: manage rbac.deckhouse.io/aggregate-to-kubernetes-as: manager
  • matchLabels: rbac.deckhouse.io/kind: manage module: user-authn rules: []

В начале указаны лейблы для новой роли:

The labels for the new role listed at the top suggest that:

  • показывает, какую роль хук должен использовать при создании use ролей:
  • the hook will use this use role:

yaml rbac.deckhouse.io/use-role: admin

yaml rbac.deckhouse.io/use-role: admin

  • показывает, что роль должна обрабатываться как manage-роль:
  • the role must be treated as a managed one:

yaml rbac.deckhouse.io/kind: manage

yaml rbac.deckhouse.io/kind: manage

Этот лейбл должен быть обязательно указан!

Note that this label is mandatory!

  • the role is a subsystem one, and it shall be handled accordingly:
  • показывает, что роль является ролью подсистемы, и обрабатываться будет соответственно:

yaml rbac.deckhouse.io/level: subsystem

yaml rbac.deckhouse.io/level: subsystem

  • there is a subsystem for which the role is responsible:
  • указывает подсистему, за которую отвечает роль:

yaml rbac.deckhouse.io/subsystem: custom

yaml rbac.deckhouse.io/subsystem: custom

  • the manage:all role can aggregate this role:
  • позволяет manage:all-роли агрегировать эту роль в себя:

yaml rbac.deckhouse.io/aggregate-to-all-as: manager

yaml rbac.deckhouse.io/aggregate-to-all-as: manager

Then there are selectors that implement aggregation:

Далее указаны селекторы, именно они реализуют агрегацию:

  • this one aggregates the manager role from the deckhouse subsystem:
  • агрегирует роль менеджера из подсистемы deckhouse:

yaml rbac.deckhouse.io/kind: manage rbac.deckhouse.io/aggregate-to-deckhouse-as: manager

yaml rbac.deckhouse.io/kind: manage rbac.deckhouse.io/aggregate-to-deckhouse-as: manager

  • this one aggregates all the rules defined for the user-authn module:
  • агрегирует все правила от модуля user-authn:

yaml rbac.deckhouse.io/kind: manage module: user-authn

yaml rbac.deckhouse.io/kind: manage module: user-authn

This way, your role will combine permissions of the deckhouse subsystem, kubernetes subsystem, and the user-authn module.

Таким образом роль получает права от подсистем deckhouse, kubernetes и от модуля user-authn.

Notes:

Особенности:

  • there are no restrictions on role name, but we recommend following the same pattern for the sake of readability;
  • use-roles will be created in aggregate subsystems and the module namespace, the role type is specified by the label.
  • ограничений на имя роли нет, но для читаемости лучше использовать этот стиль;
  • use-роли будут созданы в пространстве имён агрегированных подсистем и модуля, тип роли выбран лейблом.

Extending the custom role

Расширение пользовательской роли

Suppose a new cluster CRD object, MySuperResource, has been created in the cluster (a manage role example), and you need to extend the custom role from the example above to include the permissions to interact with this resource.

Например, в кластере появился новый кластерный (пример для manage-роли) CRD-объект — MySuperResource, и нужно дополнить собственную роль из примера выше правами на взаимодействие с этим ресурсом.

First, you have to add a new selector to the role:

Первым делом нужно дополнить роль новым селектором:

yaml rbac.deckhouse.io/kind: manage rbac.deckhouse.io/aggregate-to-custom-as: manager

yaml rbac.deckhouse.io/kind: manage rbac.deckhouse.io/aggregate-to-custom-as: manager

This selector would enable roles to be aggregated to a new subsystem by specifying this label. After adding the new selector, the role will look as follows:

Этот селектор позволит агрегировать роли к новой подсистеме через указание этого лейбла. После добавления нового селектора роль будет выглядеть так:

yaml apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: custom:manage:mycustom:manager labels: rbac.deckhouse.io/use-role: admin rbac.deckhouse.io/kind: manage rbac.deckhouse.io/level: subsystem rbac.deckhouse.io/subsystem: custom rbac.deckhouse.io/aggregate-to-all-as: manager aggregationRule: clusterRoleSelectors:

  • matchLabels: rbac.deckhouse.io/kind: manage rbac.deckhouse.io/aggregate-to-deckhouse-as: manager
  • matchLabels: rbac.deckhouse.io/kind: manage rbac.deckhouse.io/aggregate-to-kubernetes-as: manager
  • matchLabels: rbac.deckhouse.io/kind: manage module: user-authn
  • matchLabels: rbac.deckhouse.io/kind: manage rbac.deckhouse.io/aggregate-to-custom-as: manager rules: []

yaml apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: custom:manage:mycustom:manager labels: rbac.deckhouse.io/use-role: admin rbac.deckhouse.io/kind: manage rbac.deckhouse.io/level: subsystem rbac.deckhouse.io/subsystem: custom rbac.deckhouse.io/aggregate-to-all-as: manager aggregationRule: clusterRoleSelectors:

  • matchLabels: rbac.deckhouse.io/kind: manage rbac.deckhouse.io/aggregate-to-deckhouse-as: manager
  • matchLabels: rbac.deckhouse.io/kind: manage rbac.deckhouse.io/aggregate-to-kubernetes-as: manager
  • matchLabels: rbac.deckhouse.io/kind: manage module: user-authn
  • matchLabels: rbac.deckhouse.io/kind: manage rbac.deckhouse.io/aggregate-to-custom-as: manager rules: []

Next, you need to create a new role and define permissions for the new resource, e. g., the read-only permission:

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

yaml apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: labels: rbac.deckhouse.io/aggregate-to-custom-as: manager rbac.deckhouse.io/kind: manage name: custom:manage:permission:mycustom:superresource:view rules:

  • apiGroups:
  • mygroup.io resources:
  • mysuperresources verbs:
  • get
  • list
  • watch

yaml apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: labels: rbac.deckhouse.io/aggregate-to-custom-as: manager rbac.deckhouse.io/kind: manage name: custom:manage:permission:mycustom:superresource:view rules:

  • apiGroups:
  • mygroup.io resources:
  • mysuperresources verbs:
  • get
  • list
  • watch

The role will update the subsystem role to include its rights, so that the role bearer will be able to view the new object.

Роль дополнит своими правами роль подсистемы, дав права на просмотр нового объекта.

Notes:

Особенности:

  • there are no restrictions on capability names, but we recommend following the same pattern for the sake of readability.
  • ограничений на имя роли нет, но для читаемости лучше использовать этот стиль.

Extending the existing manage subsystem roles

Расширение существующих manage subsystem-ролей

To extend an existing role, follow the procedure outlined in the section above. Be sure to change the labels and the role name!

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

For example, here’s how you can extend the manager role from the deckhouse(d8:manage:deckhouse:manager) subsystem:

Пример для расширения роли менеджера из подсистемы deckhouse(d8:manage:deckhouse:manager):

yaml apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: labels: rbac.deckhouse.io/aggregate-to-deckhouse-as: manager rbac.deckhouse.io/kind: manage name: custom:manage:permission:mycustom:superresource:view rules:

  • apiGroups:
  • mygroup.io resources:
  • mysuperresources verbs:
  • get
  • list
  • watch

yaml apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: labels: rbac.deckhouse.io/aggregate-to-deckhouse-as: manager rbac.deckhouse.io/kind: manage name: custom:manage:permission:mycustommodule:superresource:view rules:

  • apiGroups:
  • mygroup.io resources:
  • mysuperresources verbs:
  • get
  • list
  • watch

This way, the new role will extend the d8:manage:deckhouse:manager role.

Таким образом новая роль расширит роль d8:manage:deckhouse.

Extending manage subsystem roles and adding a new namespace

Расширение manage subsystem-ролей с добавлением нового пространства имён

If you need to create a new namespace (to create a use role in it by the hook), you only need to add one label:

Если необходимо добавить новое пространство имён (для создания в нём use-роли с помощью хука), потребуется добавить лишь один лейбл:

yaml “rbac.deckhouse.io/namespace”: namespace

yaml “rbac.deckhouse.io/namespace”: namespace

This label instructs the hook to create a use role in this namespace:

Этот лейбл сообщает хуку, что в этом пространстве имён нужно создать use-роль:

yaml apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: labels: rbac.deckhouse.io/aggregate-to-deckhouse-as: manager rbac.deckhouse.io/kind: manage rbac.deckhouse.io/namespace: namespace name: custom:manage:permission:mycustom:superresource:view rules:

  • apiGroups:
  • mygroup.io resources:
  • mysuperresources verbs:
  • get
  • list
  • watch

yaml apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: labels: rbac.deckhouse.io/aggregate-to-deckhouse-as: manager rbac.deckhouse.io/kind: manage rbac.deckhouse.io/namespace: namespace name: custom:manage:permission:mycustom:superresource:view rules:

  • apiGroups:
  • mygroup.io resources:
  • mysuperresources verbs:
  • get
  • list
  • watch

The hook monitors ClusterRoleBinding, and when creating a bindings, it loops through all the manage roles to find all the aggregated roles by checking the aggregation rule. It then fetches the namespace from the rbac.deckhouse.io/namespace label and creates a use role in that namespace.

Хук мониторит ClusterRoleBinding и при создании биндинга ходит по всем manage-ролям, чтобы найти все объединенные в них роли с помощью проверки правила агрегации. Затем он берёт пространство имён из лейбла rbac.deckhouse.io/namespace и создает use-роль в этом пространстве имён.

Extending the existing use roles

Расширение существующих use-ролей

If the resource belongs to a namespace, you need to extend the use role instead of the manage role. The only difference is the labels and the name:

Если ресурс принадлежит пространству имён, необходимо расширить use-роль вместо manage-роли. Разница лишь в лейблах и имени:

yaml apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: labels: rbac.deckhouse.io/aggregate-to-kubernetes-as: user rbac.deckhouse.io/kind: use name: custom:use:capability:mycustom:superresource:view rules:

  • apiGroups:
  • mygroup.io resources:
  • mysuperresources verbs:
  • get
  • list
  • watch

yaml apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: labels: rbac.deckhouse.io/aggregate-to-kubernetes-as: user rbac.deckhouse.io/kind: use name: custom:use:capability:mycustom:superresource:view rules:

  • apiGroups:
  • mygroup.io resources:
  • mysuperresources verbs:
  • get
  • list
  • watch

This role will be added to the d8:use:role:user:kubernetes role.

Эта роль дополнит роль d8:use:role:user:kubernetes.