Compare languages | The user-authz module: FAQ

How do I create a user?

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

Creating a user.

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

How do I limit user rights to specific namespaces?

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

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….

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

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

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

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

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

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

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

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 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.
  1. jane.doe@example.com имеет право запрашивать и просматривать объекты среди всех пространств имён, помеченных env=review.
  2. Administrators могут запрашивать, редактировать, получать и удалять объекты на уровне кластера и из пространств имён, помеченных env=prod и env=stage.

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.

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

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

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.

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

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

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

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.

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

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:

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

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

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

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

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

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

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

yaml rbac.deckhouse.io/level: subsystem

yaml rbac.deckhouse.io/subsystem: custom

  • указывает подсистему, за которую отвечает роль:
  • the manage:all role can aggregate this role:

yaml rbac.deckhouse.io/subsystem: custom

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

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

Then there are selectors that implement aggregation:

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

  • this one aggregates the manager role from the deckhouse subsystem:

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

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

  • агрегирует роль менеджера из подсистемы deckhouse:
  • this one aggregates all the rules defined for the user-authn module:

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

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

  • агрегирует все правила от модуля user-authn:

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

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

Notes:

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

  • 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.

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

Extending the custom role

  • ограничений на имя роли нет, но для читаемости лучше использовать этот стиль;
  • use-роли будут созданы в пространстве имён агрегированных подсистем и модуля, тип роли выбран лейблом.

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.

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

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

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

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 rbac.deckhouse.io/kind: manage rbac.deckhouse.io/aggregate-to-custom-as: manager

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: 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: 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.

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

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

  • ограничений на имя роли нет, но для читаемости лучше использовать этот стиль.

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

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

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

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

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

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

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

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

Extending manage subsystem roles and adding a new namespace

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

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:

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

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

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

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

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

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

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

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.

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

Extending the existing use roles

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

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

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

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

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
 

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