# Group

> Reference for the nauthera.io/v1alpha1 Group resource: an organization's group of users, with the directory-group and email-domain mappers that fill it.

A `Group` declares one of an organization's groups of users from git. It names the group
and its **mappers**, never its members: the mappers add a user when a sign-in matches one
and withdraw them when none does any more. A mapper follows a group in an
[LDAP directory or Active Directory](https://www.nauthera.io/docs/v1/ldap-directory-resource), nested groups
included, or a verified email domain, and an owner can add and remove members by hand.
Applications read a user's groups from the [`groups` claim](#groups-in-tokens) and map
their own roles from it. The [admin dashboard](https://www.nauthera.io/docs/v1/admin-dashboard) and the
[admin API](https://www.nauthera.io/docs/v1/user-management#groups) show each group, its mappers and who added each
member; only a `Group` creates, renames or deletes one.

| Property | Value |
|---|---|
| API group / version | `nauthera.io/v1alpha1` |
| Kind | `Group` |
| Plural / short name | `groups` / `ngrp` |
| Scope | Namespaced |
| Definition | `deploy/crds/group-crd.yaml` in nauthera-server |

## Example

The main organization's engineering group: the members of the Active Directory group
Engineers, nested groups included, join it when the `LDAPDirectory` `corp` signs them in,
and so does anyone whose verified address is at `corp.example`. `description`, up to 500
characters with no control character, says what the group is for: the dashboard shows it
beside the group, and the admin API returns it as `description`. Leaving it out removes
the group's description, and a server older than control-plane contract 20 leaves a
`Group` that sets one `Unsupported`.

```yaml
apiVersion: nauthera.io/v1alpha1
kind: Group
metadata:
  name: engineering
  namespace: nauthera
spec:
  displayName: Engineering
  description: Everyone who builds and runs the product.   # optional
  externalId: 0f3c9a1e-7d2b-4c8a-9e1f-2b3c4d5e6f70   # optional
  directoryGroups:
    - directory: corp
      dn: CN=Engineers,OU=Groups,DC=corp,DC=example
  emailDomains:
    - corp.example
  deletionPolicy: Retain                            # the default
```

The directory reads its users' groups only when its own resource says how, in
[`spec.groups`](https://www.nauthera.io/docs/v1/ldap-directory-resource#reading-a-users-groups):

```yaml
apiVersion: nauthera.io/v1alpha1
kind: LDAPDirectory
metadata:
  name: corp
  namespace: nauthera
spec:
  url: ldaps://dc1.corp.example:636
  userBaseDn: OU=Staff,DC=corp,DC=example
  userFilter: (objectClass=user)
  usernameAttribute: sAMAccountName
  groups:
    lookup: inChain
    baseDn: OU=Groups,DC=corp,DC=example
```

`kubectl get ngrp -A` shows each group's member count as of its last reconcile:

```text
NAMESPACE   NAME          DISPLAY NAME   MEMBERS   PHASE   READY   REASON       AGE
nauthera    engineering   Engineering    42        Ready   True    Registered   5m
```

## Mappers

A group has at most 32 mappers, `directoryGroups` and `emailDomains` together. They act
when a session is established for a user, after every factor, so a refused sign-in
changes no membership. Each membership records the mapper that added it, and a member
whose mapper stops matching passes to another mapper of the group that still matches
before being withdrawn. Every change is recorded as `group.member_added` or
`group.member_removed`, with the mapper's kind (`directory_group` or `email_domain`) and
its directory and DN or domain.

- **Directory groups.** `directoryGroups` lists `{directory, dn}` pairs; `directory` is
  an `LDAPDirectory`'s slug in the group's organization. When that directory signs a user
  in, the groups it read are judged in the session the sign-in establishes, and only
  there: the user joins while the read puts them in one of these groups, and is withdrawn
  once a complete read no longer does, their last group included. A cut read only adds,
  and a failed one changes nothing. A session established any other way leaves directory
  memberships as they are, so membership is as of the user's last sign-in through the
  directory: a user the directory disables, or who stops signing in through it, keeps
  what that read gave until the mapping is removed.
- **What a DN matches.** A DN is compared ignoring case and the spacing around
  separators only, so spell it as the directory does. Nothing matches an Active Directory
  user's primary group (usually Domain Users), which no lookup reports, nor anything
  through a directory whose `spec.groups` is unset. A deleted directory keeps its
  mappings and their members, and one applied again under the same slug picks them up.
- **Email domains.** `emailDomains` lists lower-case domains, an internationalized one in
  its A-label form. A user whose verified address is at one is a member, and is withdrawn
  once it is at none. A subdomain is another domain. Any domain is accepted; with an
  [`IdentityProvider`](https://www.nauthera.io/docs/v1/identity-provider-resource) that has `trustEmail`,
  "verified" is that provider's word.
- **The manifest is the whole set.** Leaving both fields out removes the group's
  mappers. Removing a mapper withdraws every member it added, and `group.updated` counts
  them. Mappers need a server of control-plane contract 11 or later.

## Groups in tokens

A client granted the `groups` scope (list it in the `OIDCClient`'s `spec.scopes`) gets
the display names of the user's groups as the `groups` claim, an array, in the ID token,
the access token and UserInfo. A client without the scope gets no claim.

```yaml
apiVersion: nauthera.io/v1alpha1
kind: OIDCClient
metadata:
  name: grafana
  namespace: grafana
spec:
  clientId: grafana
  redirectUris: [https://grafana.example.com/login/generic_oauth]
  scopes: [openid, profile, email, groups]
  secret:
    generate: true
```

The application maps its roles from the claim. In Grafana, for example:

```ini
[auth.generic_oauth]
scopes = openid profile email groups
role_attribute_path = contains(groups[*], 'Grafana Admins') && 'Admin' || 'Viewer'
```

- **Read at every mint.** The claim is read when each token is issued, refresh included,
  so a membership a mapper or an owner changed reaches the next token. A mint whose read
  of the groups fails is refused rather than issued without the claim, since an
  application cannot tell a failed read from no groups.
- **At most 100 in a token.** A user in more groups gets tokens without the claim, and
  the server logs a warning; UserInfo, which has no bound, carries the whole list.
- **Names, not ids.** The claim carries display names: renaming a group renames the
  value, and a group created or renamed into a deleted group's name inherits every role
  an application maps from it.
- **Through a broker.** An [identity broker](https://www.nauthera.io/docs/v1/identity-broker)'s linked account
  carries the groups the user holds at their member organization, and a display name is
  unique only within one organization. A broker's client never maps a role from `groups`
  alone: it pairs the name with `member_org`, the member organization's id, as in
  `member_org == '<id>' && contains(groups[*], 'Grafana Admins') && 'Admin' || 'Viewer'`.

## Admitting only certain groups to an application

**On the client.** List the groups in the client's
[`spec.allowedGroups`](https://www.nauthera.io/docs/v1/oidc-client#who-may-sign-in), by `Group` resource name, and
the server lets only their members sign in to it. Everyone else is refused with
`access_denied` after signing in, and at the token endpoint, a refresh included, with
`invalid_grant`:

```yaml
apiVersion: nauthera.io/v1alpha1
kind: OIDCClient
metadata:
  name: internal-tools
  namespace: nauthera
spec:
  clientId: internal-tools
  redirectUris: [https://tools.example.com/oauth2/callback]
  scopes: [openid, profile, email, groups]
  allowedGroups: [engineering, support]
  secret:
    generate: true
```

The Groups must be in the client's namespace and organization and declared on the
server; until they are, the client reports `GroupNotFound` and nothing is sent. The guide
[Let only chosen groups sign in to an app](https://www.nauthera.io/docs/v1/guides/group-access) walks through it
end to end, from the directory to the application's roles.

**In the application.** The application can also check the `groups` claim itself, to
map roles or to narrow access further than the client does. Grant the client the
`groups` scope, then have the application refuse anyone whose claim names none of the
groups it allows. Each check below admits a user in any one of the listed groups.

**Grafana** refuses the sign-in itself with `allowed_groups`:

```ini
[auth.generic_oauth]
scopes = openid profile email groups
groups_attribute_path = groups
allowed_groups = "Grafana Admins", "Grafana Users"
role_attribute_path = contains(groups[*], 'Grafana Admins') && 'Admin' || 'Viewer'
```

**Any web application** can sit behind [oauth2-proxy](https://oauth2-proxy.github.io/oauth2-proxy/),
which signs users in through the client and passes only the members of the groups it
allows:

```bash
oauth2-proxy \
  --provider=oidc \
  --oidc-issuer-url=https://auth.example.com \
  --client-id=internal-tools \
  --scope="openid profile email groups" \
  --oidc-groups-claim=groups \
  --allowed-group="Engineering" \
  --allowed-group="Support"
```

**Your own code** verifies the ID token or access token as usual (signature, `iss`, `aud`,
`exp`), then checks the claim:

```ts
const allowed = new Set(["Engineering", "Support"]);
const groups: string[] = Array.isArray(claims.groups) ? claims.groups : [];
if (!groups.some((g) => allowed.has(g))) {
  return new Response("Forbidden", { status: 403 });
}
```

- **Prefer `allowedGroups` for access.** The server refuses at sign-in and at every
  refresh whatever the application does; a check in the application is only as good as
  the application.
- **Treat a missing claim as no group.** A token leaves the claim out for a user in more
  than 100 groups, and a client without the `groups` scope never gets it. Refusing then
  fails closed; read UserInfo when you need the whole list.
- **Check again on refresh.** The claim is read at every mint, so an application that
  checks each new access token stops a user removed from the group at their next
  refresh, without waiting for a new sign-in.
- **Guard the groups.** Whoever may create or rename a `Group` in your cluster, or add
  members by hand (`groups.manage`), decides who gets in, through `allowedGroups` and the
  claim alike; a check in the application matches display names, which a rename
  changes. Keep `Group` manifests where the identity team reviews them (see
  [GitOps](https://www.nauthera.io/docs/v1/adoption/gitops)).
- **Behind a broker**, pair the name with `member_org`, as above, so a member
  organization's group of the same name does not get in.

## Behavior

- **The only writer of the group.** Changing a group's name, external id or mappers is a
  change to its resource, recorded as `group.created` or `group.updated`; the dashboard
  and the admin API change only its members.
- **Members by hand.** An owner (`groups.manage`) adds and removes members on the
  group's page in the dashboard or through the
  [admin API](https://www.nauthera.io/docs/v1/user-management#groups). A member added by hand is never withdrawn
  by a mapper, and adding one a mapper holds takes the membership over. A removal by hand
  lasts until the user's next sign-in when a mapper still matches them. Nobody changes
  their own memberships or a more privileged account's.
- **Display names are unique** in the organization, compared case-insensitively. A
  resource whose name another resource declares is `Refused` with `MANAGED_ELSEWHERE`.
- **The external id** is what the directory that provisions the group calls it
  (RFC 7643 §3.1), unique in the organization. Omitted, the group's stays as it is, so a
  provisioning client may own it; an empty one removes it.
- **One organization.** The organization follows from the resource's namespace (see
  [Which organization a resource configures](https://www.nauthera.io/docs/v1/operator#which-organization-a-resource-configures));
  `spec.organization` names it where several admit the namespace, and cannot be changed.
  A resource whose group the server holds in another organization is `Refused`: delete
  and recreate it to move it.
- **Who may write one.** The operator's grant needs the `groups` operation (see
  [the grant](https://www.nauthera.io/docs/v1/operator#who-may-change-what)), and the chart's
  `nauthera-identity-admin` role may write `Group` in the namespaces it is bound in. A
  server older than control-plane contract 9 leaves the resource `Unsupported`.

### Deleting a resource

`spec.deletionPolicy` decides. With `Retain`, the default, the group, its members and its
last mappers stay, read-only, and the mappers go on adding and withdrawing members
(`group.released`). With `Delete`, the group and every membership in it go
(`group.deleted`). A finalizer (`nauthera.io/group`) holds the resource until the server
has done either; a call that fails keeps it in phase `Deleting` with reason
`GroupNotRemoved`, and is retried. Deleting a resource the server never accepted (one
without `status.groupId`) completes even when the operator's grant no longer reaches it.

### Taking a retained group over

A `Group` that declares no group yet takes over a retained group of the same display
name rather than creating a second one (`group.declared`), but only from the namespace
whose resource retained it. From any other namespace it is `Refused` with
`MANAGED_ELSEWHERE`. A takeover with a refused display name, external id or mapper is
refused whole, and the group stays undeclared.

A resource that already declares a group and is renamed to a retained group's name is
`Refused` with `GROUP_NAME_TAKEN`. To free the name, declare the retained group from its
namespace with a `Group` of that name and `deletionPolicy: Delete`, then delete that
resource.

### Changing the operator's identity

The server keys each declaration on the identity that made it, so after the operator
certificate's SAN changes (a renamed release, `dns:` to `uri:`) every existing `Group` is
`Refused` with `MANAGED_ELSEWHERE`. Before the change, delete each with
`deletionPolicy: Retain` while the old identity is still granted. The groups stay, and
the same manifests applied under the new identity take them over from their namespaces.

## Spec

{/* AUTO-GENERATED-SPEC-START */}

### `spec.deletionPolicy`

**Type:** `string` | **Optional**

What deleting this resource does to the group. Retain ends the
declaration: the group and its members stay, read-only, until a Group
of the same display name in the same namespace takes it over. Delete
deletes the group and every membership in it. A deletion that fails
keeps the resource, in phase Deleting, until it succeeds.

Defaults to `"Retain"`.

One of: `Retain`, `Delete`.

### `spec.description`

**Type:** `string` | **Optional**

What the group is for, as the dashboard shows it beside the group:
up to 500 characters, with no control character. Omitted removes the
group's description. Needs control-plane contract 20.

### `spec.directoryGroups`

**Type:** `[]object` | **Optional**

The directory groups the group follows: a user one of these
directory connections signs in is a member while the directory puts
them in the group, and is withdrawn at the first sign-in after it no
longer does. A member another mapper added passes to it rather than
leaving. Nothing matches an Active Directory user's primary group,
which no lookup reports, nor anything through a directory whose
spec.groups is unset.

| Field | Type | Required | Default | Description |
|---|---|---|---|---|
| `directory` | `string` | Yes | `—` | The slug of an LDAPDirectory of the group's organization: its spec.slug, or its name when that is left out. |
| `dn` | `string` | Yes | `—` | The group's distinguished name (RFC 4514) in that directory, such as cn=engineers,ou=groups,dc=corp,dc=example. Compared ignoring case and the spacing around separators only, so spell it as the directory does. |

### `spec.displayName`

**Type:** `string` | **Required**

The group's name, unique in the organization compared
case-insensitively. A group of this name that a deleted resource of
this namespace retained is taken over by a resource that declares no
group yet; one another resource declares, or one retained in another
namespace, is refused. Renaming onto a retained group's name is
refused too.

### `spec.emailDomains`

**Type:** `[]string` | **Optional**

The email domains the group follows: a user whose verified address is
at one of them is a member once a session is established for them, and
is withdrawn at the first one after their address is at none. A
domain is lower-case, an internationalized one in its A-label form, and
compared whole: a subdomain is another domain. At most 32 together
with directoryGroups.

### `spec.externalId`

**Type:** `string` | **Optional**

What the directory that provisions the group calls it (RFC 7643
§3.1), unique in the organization. Omitted leaves the group's
external id as it is, so a provisioning client may own it; empty
removes it.

### `spec.organization`

**Type:** `string` | **Optional**

The slug of the organization the group belongs to. Needed only where
more than one organization admits the namespace in its
spec.namespaces; otherwise the one that does is taken. The main
organization is "default". Immutable.

{/* AUTO-GENERATED-SPEC-END */}

## Status

`status.groupId` is the group's id on the server and `status.memberCount` its member
count when it was last declared; the operator declares it again periodically to keep the
count fresh. `phase` is one of `Pending`, `Ready`, `Error` or `Deleting`. Beside the
connection reasons every resource shares (`Refused`, `Unreachable`, `Unsupported`,
`CredentialUnavailable`, `TrustAnchorUnavailable`; see the
[OIDCClient reference](https://www.nauthera.io/docs/v1/oidc-client#status)) and the namespace reasons
(`NamespaceNotCovered`, `NamespaceNotAdmitted`, `OrganizationAmbiguous`,
`OrganizationNotReady`, `OrganizationChanged`), the `Ready` condition's reason is one of:

| Reason | Phase | Meaning |
|---|---|---|
| `Registered` | `Ready` | The group is declared as the spec says. |
| `GroupNotRemoved` | `Deleting` | The resource is being deleted and the server has not released or deleted the group. |

Each failure reason has a [runbook](https://www.nauthera.io/docs/v1/runbooks).

{/* AUTO-GENERATED-STATUS-START */}

| Field | Type | Description |
|---|---|---|
| `conditions` | `[]object` | Standard Kubernetes conditions (Ready, ...). |
| `groupId` | `string` | The group's id on the server. |
| `lastReconciledTime` | `string` | When the operator last reconciled the resource, whatever the outcome. A stale value means the operator is not running, not the leader, or cannot see the resource. |
| `memberCount` | `integer` | How many members the group had when it was last declared. |
| `observedGeneration` | `integer` | .metadata.generation last reconciled by the server. |
| `organization` | `string` | The slug of the organization the group was declared in. Once set, a namespace that comes to configure another organization is refused rather than moving the group. |
| `phase` | `string` | High-level lifecycle phase. |

{/* AUTO-GENERATED-STATUS-END */}

## Related

- [LDAPDirectory](https://www.nauthera.io/docs/v1/ldap-directory-resource#reading-a-users-groups): how a sign-in reads a user's groups
- [Admin API & Users](https://www.nauthera.io/docs/v1/user-management#groups): reading groups and their members
- [Audit events](https://www.nauthera.io/docs/v1/audit-events): the `group.*` actions
- [Operator](https://www.nauthera.io/docs/v1/operator#who-may-change-what): the grant and the team roles
