# Give every pull request preview an OIDC client

> Deploy each pull request as a preview with its own OIDCClient from an Argo CD ApplicationSet, and remove the client from Nauthera when the pull request closes.

This guide deploys every open pull request of an application as a preview environment
with its own OpenID Connect client, and takes both away when the pull request is merged or
closed. An Argo CD ApplicationSet creates one Application per pull request, the
application's preview chart declares an [`OIDCClient`](https://www.nauthera.io/docs/v1/oidc-client) named after the
pull request, and the [operator](https://www.nauthera.io/docs/v1/operator) registers it, delivers its secret into the
preview's namespace and removes it from the server when Argo CD deletes the resource. The
preview signs reviewers in through oauth2-proxy, so the application itself needs no
OpenID Connect code. You need a Nauthera release with its operator running, Argo CD with
the ApplicationSet controller, cert-manager with a DNS-01 issuer for a wildcard
certificate, an ingress controller, and an image built for each pull request's head
commit. At the end, a pull request labelled `preview` gets a URL its reviewers sign in to,
under a client nobody registered by hand, and merging it leaves no client behind on the
server. The main limit: access tokens issued to a preview's client stay valid until they
expire, so preview clients get short lifetimes.
{/* nauthera/nauthera-server#1878: deleting a client does not retire the access tokens it was issued */}

**Checked against:** Argo CD 3.6.0, oauth2-proxy 7.12.0, cert-manager 1.21 and Traefik 3.7
on Kubernetes 1.37, on November 23, 2026. Every manifest on this page was applied as
shown, but for the certificate's issuer, which was a private CA that oauth2-proxy was told
to trust; GitHub's pull request list and the repository were served by a local stand-in.
The screenshots are from that run.

The example application is `billing-web`, in the repository `example/billing-service`. Its
previews run at `https://pr-<number>.billing.preview.example.com`, and Nauthera's issuer is
`https://auth.example.com`.

```mermaid
flowchart TD
  PR["Pull request 42<br/>labelled preview"] --> AS["ApplicationSet<br/>pull request generator"]
  AS -->|"creates"| APP["Application<br/>billing-web-pr-42"]
  APP -->|"wave -1"| C
  APP -->|"wave 0"| D
  subgraph NS["Namespace billing-preview"]
    C["OIDCClient<br/>billing-web-pr-42"]
    S["Secret<br/>billing-web-pr-42"]
    D["Deployment: billing-web<br/>and oauth2-proxy"]
  end
  C --> OP["Operator"]
  OP -->|"registers"| SV["nauthera-server"]
  OP -->|"writes"| S
  S -->|"issuer, client-id,<br/>client-secret"| D
```

| Step | Repository | What it does |
|---|---|---|
| [Admit the preview namespace](#1-admit-the-preview-namespace) | Platform | One namespace, admitted once, holds every preview of the application |
| [Prepare the namespace](#2-prepare-the-namespace) | Platform | A [`Group`](https://www.nauthera.io/docs/v1/group-resource) of reviewers, the wildcard certificate, the cookie key, and a policy that holds every preview client to the group |
| [Write the preview chart](#3-write-the-preview-chart) | Application | A chart whose `OIDCClient` is named after the pull request and removed with it, with oauth2-proxy in front of the application |
| [Teach Argo CD the client's health](#4-teach-argo-cd-the-clients-health) | Platform | Argo CD waits for the client before it starts the preview |
| [Generate an Application per pull request](#5-generate-an-application-per-pull-request) | Platform | An AppProject and an ApplicationSet with the pull request generator |

The files, by repository:

```text
platform-gitops/
└── previews/billing/
    ├── namespace.yaml       # step 2
    ├── argocd-cm.yaml       # step 4
    └── argocd.yaml          # step 5

billing-service/
└── deploy/preview/          # step 3
    ├── Chart.yaml
    ├── values.yaml
    └── templates/
        ├── oidcclient.yaml
        ├── deployment.yaml
        ├── service.yaml
        └── ingress.yaml
```

## 1. Admit the preview namespace

An organization admits namespaces by name, so a namespace per pull request would need a
change to the `Organization` for every one. Put all of an application's previews in one
namespace instead, admitted once: each preview's resources carry its pull request's number
in their names, so they never collide. For the main organization, add it to the chart
value `operator.mainOrganizationNamespaces`, beside the namespaces it already lists:

```yaml
# nauthera-server chart values
operator:
  enabled: true
  mainOrganizationNamespaces: [nauthera, billing-preview]
```

For another organization, add `billing-preview` to its `Organization` resource's
`spec.namespaces`; its issuer is then `https://auth.example.com/orgs/<slug>`, and the
Secret the operator writes carries whichever applies, so the preview needs no change. The
operator's own namespaces (`operator.namespaces`) and its entry in
`certManager.grpcTLS.allowedClients` cover every namespace (`"*"`) by default; if yours
are narrowed, add `billing-preview` to both. See
[Which organization a resource configures](https://www.nauthera.io/docs/v1/operator#which-organization-a-resource-configures).

## 2. Prepare the namespace

A preview runs code nobody has reviewed yet, under a client of your organization. Admit
only the people reviewing it: a `Group` in the preview namespace, which every preview
client lists in [`allowedGroups`](https://www.nauthera.io/docs/v1/oidc-client#who-may-sign-in), so a user outside it
is refused by Nauthera before the preview sees them. Beside it go the wildcard certificate
every preview's Ingress serves, and a `ValidatingAdmissionPolicy`: a pull request can
change its own chart, `allowedGroups` and `deletionPolicy` included, and the policy holds
every client in the namespace to both whatever the pull request says.

```yaml
# platform-gitops/previews/billing/namespace.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: billing-preview
---
apiVersion: nauthera.io/v1alpha1
kind: Group
metadata:
  name: billing-reviewers
  namespace: billing-preview
spec:
  displayName: Billing reviewers
  description: Everyone who may sign in to a preview of billing-web.
---
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
  name: billing-preview
  namespace: billing-preview
spec:
  secretName: billing-preview-tls
  dnsNames:
    - "*.billing.preview.example.com"
  issuerRef:
    name: letsencrypt-dns          # your ClusterIssuer with a DNS-01 solver
    kind: ClusterIssuer
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
  name: billing-preview-clients
spec:
  failurePolicy: Fail
  matchConstraints:
    resourceRules:
      - apiGroups: [nauthera.io]
        apiVersions: ["*"]
        operations: [CREATE, UPDATE]
        resources: [oidcclients]
  validations:
    - expression: has(object.spec.deletionPolicy) && object.spec.deletionPolicy == 'Delete'
      message: A preview client is removed with its pull request (deletionPolicy Delete).
    - expression: has(object.spec.allowedGroups) && object.spec.allowedGroups == ['billing-reviewers']
      message: A preview client admits billing-reviewers and nobody else.
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
  name: billing-preview-clients
spec:
  policyName: billing-preview-clients
  validationActions: [Deny]
  matchResources:
    namespaceSelector:
      matchLabels:
        kubernetes.io/metadata.name: billing-preview
```

oauth2-proxy signs its session cookies with a key, which every preview in the namespace
shares; a cookie is held to its own preview's host. Create it once, outside Git, or from
your secret store:

```bash
kubectl -n billing-preview create secret generic billing-preview-cookie \
  --from-literal=cookie-secret="$(openssl rand -hex 16)"
```

Once applied, the group is on the server, and a client that would outlive its pull
request is refused:

```text
$ kubectl -n billing-preview get groups.nauthera.io
NAME                DISPLAY NAME        MEMBERS   PHASE   READY   REASON       AGE
billing-reviewers   Billing reviewers             Ready   True    Registered   16m

$ kubectl apply --dry-run=server -f client-without-delete-policy.yaml
The oidcclients "sneaky" is invalid: : ValidatingAdmissionPolicy 'billing-preview-clients' with binding 'billing-preview-clients' denied request: A preview client is removed with its pull request (deletionPolicy Delete).
```

Add reviewers on the group's page in the [admin dashboard](https://www.nauthera.io/docs/v1/admin-dashboard) (an
administrator adds other people, not their own account), or fill the group from a
directory group or an email domain with its [mappers](https://www.nauthera.io/docs/v1/group-resource#mappers).
oauth2-proxy refuses an ID token whose `email_verified` is `false`, so a reviewer's
address must be verified: by the [emailed link](https://www.nauthera.io/docs/v1/sign-in-flows/emailed-links#verify-an-address),
or by an administrator who creates the account as verified.

## 3. Write the preview chart

The application's repository holds a small Helm chart for its previews. Production keeps
its own `OIDCClient` under `deletionPolicy: Retain`, as in
[GitOps & Argo CD](https://www.nauthera.io/docs/v1/adoption/gitops#team-applications). The ApplicationSet sets three
values per pull request:

```yaml
# deploy/preview/Chart.yaml
apiVersion: v2
name: billing-web-preview
description: billing-web for one pull request, behind its own OIDC client
version: 0.1.0
```

```yaml
# deploy/preview/values.yaml
pr: ""        # the pull request's number
host: ""      # pr-<number>.billing.preview.example.com
image:
  repository: ghcr.io/example/billing-web
  tag: ""     # the pull request's head commit
```

The client is named after the pull request:

```yaml
# deploy/preview/templates/oidcclient.yaml
apiVersion: nauthera.io/v1alpha1
kind: OIDCClient
metadata:
  name: billing-web-pr-{{ .Values.pr }}
  annotations:
    argocd.argoproj.io/sync-wave: "-1"
spec:
  clientId: billing-web-pr-{{ .Values.pr }}
  displayName: "Billing preview {{ .Values.pr }}"
  redirectUris:
    - https://{{ .Values.host }}/oauth2/callback
  postLogoutRedirectUris:
    - https://{{ .Values.host }}/
  grantTypes: [authorization_code, refresh_token]
  responseTypes: [code]
  scopes: [openid, profile, email, offline_access]
  tokenEndpointAuthMethod: client_secret_basic
  pkcePolicy: required_s256
  allowRefresh: true
  accessTokenTtlSeconds: 300
  idTokenTtlSeconds: 300
  refreshTokenTtlSeconds: 28800
  allowedGroups: [billing-reviewers]
  deletionPolicy: Delete
  secret:
    generate: true
```

| Field | Why |
|---|---|
| `metadata.name`, `clientId` | One client per pull request, the same for every push to it. A push updates the preview and leaves the client as it is: re-applying a spec never registers a new client or rotates its secret. `clientId` is immutable, so it must not carry the commit. |
| `displayName` | How the client reads in the dashboard and on the consent screen. |
| `redirectUris` | Compared byte for byte, so each preview registers its own host; there are no wildcard redirect URIs. `/oauth2/callback` is oauth2-proxy's. |
| `deletionPolicy: Delete` | Removes the client from the server when the resource is deleted. The default, `Retain`, would leave every closed pull request's client registered. |
| `secret.generate` | The server mints the secret and the operator writes it into a Secret named after the resource, with the keys `issuer`, `client-id` and `client-secret`. It is never in Git. See [How secrets work](https://www.nauthera.io/docs/v1/oidc-client#how-secrets-work). |
| `accessTokenTtlSeconds: 300` | Bounds how long an access token issued to the preview works after its client is gone. `refreshTokenTtlSeconds` may not exceed the deployment's `issuer.refresh_token_ttl` (`720h` by default). |
| `argocd.argoproj.io/sync-wave: "-1"` | Argo CD applies the client first and waits for it to be healthy, so the Deployment starts with its Secret in place (step 4). |

The Deployment runs the application with oauth2-proxy in front of it. oauth2-proxy reads
the issuer, client id and secret from the Secret the operator wrote, signs the reviewer in
through Nauthera with PKCE, and passes the application the user in `X-Forwarded-User` and
`X-Forwarded-Email`. An application that signs users in itself reads the same three keys
instead.

```yaml
# deploy/preview/templates/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: billing-web-pr-{{ .Values.pr }}
spec:
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/instance: billing-web-pr-{{ .Values.pr }}
  template:
    metadata:
      labels:
        app.kubernetes.io/name: billing-web
        app.kubernetes.io/instance: billing-web-pr-{{ .Values.pr }}
    spec:
      containers:
        - name: billing-web
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          ports:
            - name: app
              containerPort: 8080
        - name: oauth2-proxy
          image: quay.io/oauth2-proxy/oauth2-proxy:v7.12.0
          args:
            - --provider=oidc
            - --redirect-url=https://{{ .Values.host }}/oauth2/callback
            - --upstream=http://127.0.0.1:8080
            - --http-address=0.0.0.0:4180
            - --reverse-proxy=true
            - --email-domain=*
            - --code-challenge-method=S256
            - --scope=openid profile email offline_access
            - --cookie-refresh=4m
            - --skip-provider-button=true
          env:
            - name: OAUTH2_PROXY_OIDC_ISSUER_URL
              valueFrom:
                secretKeyRef:
                  name: billing-web-pr-{{ .Values.pr }}
                  key: issuer
            - name: OAUTH2_PROXY_CLIENT_ID
              valueFrom:
                secretKeyRef:
                  name: billing-web-pr-{{ .Values.pr }}
                  key: client-id
            - name: OAUTH2_PROXY_CLIENT_SECRET
              valueFrom:
                secretKeyRef:
                  name: billing-web-pr-{{ .Values.pr }}
                  key: client-secret
            - name: OAUTH2_PROXY_COOKIE_SECRET
              valueFrom:
                secretKeyRef:
                  name: billing-preview-cookie
                  key: cookie-secret
          ports:
            - name: http
              containerPort: 4180
          readinessProbe:
            httpGet:
              path: /ping
              port: http
```

- `--email-domain=*` admits whoever Nauthera admitted: `allowedGroups` decides who may
  sign in, before oauth2-proxy sees anyone.
- `--code-challenge-method=S256` meets the client's `pkcePolicy: required_s256`.
- `--cookie-refresh=4m` refreshes the session before its five-minute access token expires.
- `--reverse-proxy=true` trusts the ingress's `X-Forwarded-*` headers, so oauth2-proxy
  sees the reviewer's address and the scheme and host they used.

```yaml
# deploy/preview/templates/service.yaml
apiVersion: v1
kind: Service
metadata:
  name: billing-web-pr-{{ .Values.pr }}
spec:
  selector:
    app.kubernetes.io/instance: billing-web-pr-{{ .Values.pr }}
  ports:
    - name: http
      port: 80
      targetPort: http
```

```yaml
# deploy/preview/templates/ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: billing-web-pr-{{ .Values.pr }}
spec:
  tls:
    - hosts:
        - {{ .Values.host }}
      secretName: billing-preview-tls
  rules:
    - host: {{ .Values.host }}
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: billing-web-pr-{{ .Values.pr }}
                port:
                  name: http
```

The Ingress takes the cluster's default IngressClass; set `ingressClassName` if yours has
none.

## 4. Teach Argo CD the client's health

Argo CD has no health check of its own for an `OIDCClient`, so without one it does not
wait for the client: it moves past wave `-1` at once and starts the Deployment before the
Secret it reads exists.
This check reads the operator's `status`: `Progressing` until the server has registered
the client, `Healthy` once it has, `Degraded` with the server's objection when it refuses
it.

```yaml
# platform-gitops/previews/billing/argocd-cm.yaml, merged into argocd-cm
apiVersion: v1
kind: ConfigMap
metadata:
  name: argocd-cm
  namespace: argocd
data:
  resource.customizations.health.nauthera.io_OIDCClient: |
    hs = { status = "Progressing", message = "Waiting for the operator" }
    if obj.status == nil then return hs end
    if obj.status.observedGeneration ~= nil and obj.metadata.generation ~= nil
       and obj.status.observedGeneration < obj.metadata.generation then
      return hs
    end
    local msg = ""
    if obj.status.conditions ~= nil then
      for _, c in ipairs(obj.status.conditions) do
        if c.type == "Ready" then msg = (c.reason or "") .. ": " .. (c.message or "") end
      end
    end
    if obj.status.phase == "Ready" then
      hs.status = "Healthy"
    elseif obj.status.phase == "Error" then
      hs.status = "Degraded"
    end
    hs.message = msg
    return hs
```

[GitOps & Argo CD](https://www.nauthera.io/docs/v1/adoption/gitops#health-checks-for-the-operators-resources) has
the same check for the other `nauthera.io` kinds.

## 5. Generate an Application per pull request

Argo CD's security notes keep ApplicationSets to its administrators, since one can create
Applications in any project, so this one lives in the platform repository, beside an
AppProject that lets the previews write to their namespace and nowhere else:

```yaml
# platform-gitops/previews/billing/argocd.yaml
apiVersion: argoproj.io/v1alpha1
kind: AppProject
metadata:
  name: billing-previews
  namespace: argocd
spec:
  description: One preview of billing-web per open pull request
  sourceRepos:
    - https://github.com/example/billing-service.git
  destinations:
    - server: https://kubernetes.default.svc
      namespace: billing-preview
  clusterResourceWhitelist: []
  namespaceResourceWhitelist:
    - { group: apps, kind: Deployment }
    - { group: "", kind: Service }
    - { group: networking.k8s.io, kind: Ingress }
    - { group: nauthera.io, kind: OIDCClient }
---
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: billing-web-previews
  namespace: argocd
spec:
  goTemplate: true
  goTemplateOptions: ["missingkey=error"]
  generators:
    - pullRequest:
        github:
          owner: example
          repo: billing-service
          tokenRef:
            secretName: github-token
            key: token
          labels:
            - preview
        requeueAfterSeconds: 300
  template:
    metadata:
      name: 'billing-web-pr-{{.number}}'
    spec:
      project: billing-previews
      source:
        repoURL: https://github.com/example/billing-service.git
        targetRevision: '{{.head_sha}}'
        path: deploy/preview
        helm:
          parameters:
            - name: pr
              value: '{{.number}}'
            - name: host
              value: 'pr-{{.number}}.billing.preview.example.com'
            - name: image.tag
              value: '{{.head_sha}}'
      destination:
        server: https://kubernetes.default.svc
        namespace: billing-preview
      syncPolicy:
        automated:
          prune: true
          selfHeal: true
```

The generator reads the repository's open pull requests with a GitHub token that can read
them (a fine-grained token with read access to the repository's pull requests). Keep it
out of Git:

```bash
kubectl -n argocd create secret generic github-token --from-literal=token=<token>
```

A private repository also needs a repository credential for Argo CD to clone it, as
[Argo CD's declarative setup](https://github.com/argoproj/argo-cd/blob/v3.6.0/docs/operator-manual/declarative-setup.md#repositories)
describes.

- **`Group` and `Secret` are not on the AppProject's list**, so a preview cannot declare
  who may sign in to it, and the Secret is the operator's to write, not Argo CD's.
- **`labels: [preview]`** builds a preview only for a pull request carrying the label.
  Removing the label removes the preview, as merging does.
- **`project` is a constant.** A templated `project` would let a pull request choose
  which AppProject governs it.
- **Deletion stays on.** The ApplicationSet controller deletes an Application whose pull
  request is no longer open, and puts `resources-finalizer.argocd.argoproj.io` on every
  Application it generates, so Argo CD deletes the Application's resources with it. Both
  hold under the defaults. Setting `preserveResourcesOnDeletion: true`, or a controller
  `--policy` of `create-only` or `create-update`, leaves the client registered after the
  pull request closes.
- **`requeueAfterSeconds`** is how often the generator asks GitHub for open pull requests,
  30 minutes when unset. For a preview the moment a pull request opens or closes, send
  GitHub's pull request events to the ApplicationSet controller's webhook (`/api/webhook`
  on the `argocd-applicationset-controller` Service's `webhook` port, not the API
  server's), as
  [the generator's docs](https://github.com/argoproj/argo-cd/blob/v3.6.0/docs/operator-manual/applicationset/Generators-Pull-Request.md#webhook-configuration)
  describe.

## When a pull request opens

```mermaid
sequenceDiagram
  autonumber
  participant GH as GitHub
  participant AS as ApplicationSet controller
  participant AC as Argo CD
  participant K as Namespace billing-preview
  participant OP as Operator
  participant SV as nauthera-server
  GH->>AS: pull request 42 opened, labelled preview
  AS->>AC: creates Application billing-web-pr-42
  AC->>K: applies OIDCClient billing-web-pr-42 (wave -1)
  K->>OP: a new OIDCClient
  OP->>SV: registers client billing-web-pr-42
  SV-->>OP: the client and its secret, returned once
  OP->>K: writes Secret billing-web-pr-42, status Ready
  K-->>AC: OIDCClient Healthy
  AC->>K: applies Deployment, Service, Ingress (wave 0)
  Note over K: oauth2-proxy reads issuer, client-id and client-secret
```

Two pull requests labelled `preview` give two Applications, each synced to its pull
request's head commit:

<Screenshot src="/docs/images/preview-environments/argocd-applications.webp" width={2880} height={1720} alt="Argo CD's application list with billing-web-pr-41 and billing-web-pr-42, both Healthy and Synced, in the billing-previews project, from https://github.com/example/billing-service.git" caption="Argo CD: one Application per open pull request labelled preview." />

Each preview's tree holds its `OIDCClient` beside the Deployment, Service and Ingress, and
the health check reads it as `Healthy` once the server has registered it:

<Screenshot src="/docs/images/preview-environments/argocd-resource-tree.webp" width={2880} height={1720} alt="Argo CD's resource tree of billing-web-pr-42: the Service, Deployment, OIDCClient and Ingress, all Healthy and Synced" caption="Preview 42's resources. The OIDCClient synced in wave -1, before the Deployment that reads its Secret." />

The clients sit beside each other in the namespace:

```text
$ kubectl -n billing-preview get oidcclients
NAME                CLIENTID            AUTHMETHOD            PHASE   READY   REASON       AGE
billing-web-pr-41   billing-web-pr-41   client_secret_basic   Ready   True    Registered   21m
billing-web-pr-42   billing-web-pr-42   client_secret_basic   Ready   True    Registered   21m
```

and in the organization's clients in the admin dashboard:

<Screenshot src="/docs/images/preview-environments/nauthera-clients.webp" width={2880} height={1720} alt="The admin dashboard's Clients page listing Billing preview 41 and Billing preview 42, confidential clients with a client secret, beside the organization's admin clients" caption="Nauthera's dashboard: each preview's client." />

A preview's client page shows that the operator registered it, its own redirect URIs, and
the `nauthera.io/deletion-policy` label the operator carries to the server for its
[sweep](#if-the-removal-fails):

<Screenshot src="/docs/images/preview-environments/nauthera-client.webp" width={2880} height={1720} alt="Billing preview 42's settings in the admin dashboard: confidential, managed by the operator, authorization code and refresh token, PKCE required, redirect URI https://pr-42.billing.preview.example.com/oauth2/callback, and the label nauthera.io/deletion-policy Delete" caption="Billing preview 42 in Nauthera: registered by the operator, removed with its pull request." />

A reviewer in `billing-reviewers` opens the preview, signs in on Nauthera's pages and
lands in the application as themselves:

<Screenshot src="/docs/images/preview-environments/preview-signed-in.webp" width={2200} height={1120} alt="The billing-web preview at pr-42.billing.preview.example.com, signed in as sam@example.com, with the user id oauth2-proxy passed to the application" caption="Preview 42, signed in through its own client." />

A user outside the group is sent back from the authorization endpoint with
`access_denied` and the description "the user may not sign in to this client", and
oauth2-proxy answers 403. A push to the pull request changes the image and syncs again;
the client keeps its revision and its secret's fingerprint.

## When a pull request merges or closes

```mermaid
sequenceDiagram
  autonumber
  participant GH as GitHub
  participant AS as ApplicationSet controller
  participant AC as Argo CD
  participant K as Namespace billing-preview
  participant OP as Operator
  participant SV as nauthera-server
  GH->>AS: pull request 42 merged
  AS->>AC: deletes Application billing-web-pr-42
  AC->>K: deletes Deployment, Service, Ingress, OIDCClient
  Note over K: the finalizer nauthera.io/oidcclient holds the OIDCClient
  K->>OP: the OIDCClient is being deleted
  OP->>SV: removes client billing-web-pr-42
  SV-->>OP: removed
  OP->>K: event Removed, finalizer released
  Note over K: Kubernetes deletes the Secret with the OIDCClient that owns it
```

Within seconds of the generator dropping the pull request, the Application, the client
and its Secret are gone, and the operator records the removal as a `Removed` event:

```text
$ kubectl -n billing-preview get events --field-selector reason=Removed
LAST SEEN   TYPE     REASON    OBJECT                         MESSAGE
1s          Normal   Removed   oidcclient/billing-web-pr-42   client billing-web-pr-42 removed from the server, as spec.deletionPolicy Delete asks
```

The server no longer knows the client: its credentials are refused at the token endpoint
with `invalid_client`, nobody signs in to it, and its refresh tokens no longer work. Access
tokens it was issued work until they expire, five minutes at most with the chart above.

<Screenshot src="/docs/images/preview-environments/nauthera-clients-after-merge.webp" width={2880} height={1720} alt="The admin dashboard's Clients page after pull request 42 merged: Billing preview 41 and the admin clients remain, Billing preview 42 is gone" caption="After pull request 42 merged: its client is gone from Nauthera." />

The client's life, from the operator's side:

```mermaid
stateDiagram-v2
  [*] --> Pending: Argo CD applies the OIDCClient
  Pending --> Ready: registered, Secret written
  Pending --> Error: refused by the server
  Error --> Ready: template fixed in the pull request
  Ready --> Ready: a push to the pull request
  Ready --> [*]: pull request closed, client removed
  Ready --> Deleting: pull request closed, removal failed
  Deleting --> [*]: removal retried until the server takes it
```

### If the removal fails

A removal the server does not take, because it does not answer or refuses it, keeps the
`OIDCClient` in phase `Deleting` with the reason `ClientNotRemoved`, and the client stays
registered:

```text
$ kubectl -n billing-preview get oidcclient billing-web-pr-41
NAME                CLIENTID            AUTHMETHOD            PHASE      READY   REASON             AGE
billing-web-pr-41   billing-web-pr-41   client_secret_basic   Deleting   False   ClientNotRemoved   22m
```

Argo CD keeps the Application, deleting, until the operator lets the client go, and names
the client as the reason:

<Screenshot src="/docs/images/preview-environments/argocd-removal-held.webp" width={2880} height={1720} alt="Argo CD's tree of billing-web-pr-41 while it is deleted with the server stopped: the Application Progressing, caused by its OIDCClient, the other resources already gone" caption="With the server stopped, the OIDCClient holds its Application until the removal goes through." />

The operator retries every five minutes, or about once a minute while the server does not
answer, and finishes the removal once it does. The
[`ClientNotRemoved` runbook](https://www.nauthera.io/docs/v1/runbooks/operator/ClientNotRemoved) says how to find the
cause. Alert on a client stuck there:

```text
nauthera_operator_resources{kind="OIDCClient", phase="Deleting"} > 0
```

for, say, 30 minutes. Removing the finalizer by hand lets the resource go but leaves the
client registered; the operator's hourly sweep then removes a `Delete` client whose
manifest is gone, once the server answers. A sweep that finds more than ten such clients
at once removes none and says so, since that is more likely a wrong listing than ten
manifests gone ([Deleting a manifest](https://www.nauthera.io/docs/v1/operator#deleting-a-manifest)).

## One preview per branch

The same chart serves a preview per branch with no pull request. The SCM Provider
generator with `allBranches: true` and a `branchMatch` filter yields one entry per branch,
and the ApplicationSet deletes the branch's Application, and with it the client, once the
branch is deleted. Name the resources after the generator's `branchNormalized` instead of
the pull request's number. It keeps dots and runs up to 253 characters, longer than the 63
a host name's label allows, so shorten it before it names the host and the client.

## Other clients a generator can own

The pattern is a generator, a template that names its client after what was generated,
and `deletionPolicy: Delete`. Each of these follows it:

- **A client per cluster.** The cluster generator renders an `OIDCClient` per cluster
  Argo CD manages, for that cluster's Grafana or Argo CD, with its redirect URI on that
  cluster's host. The template's destination is the cluster the operator runs in, wherever
  the application runs. Removing the cluster from Argo CD removes its client.
- **A client per team or tenant.** A list or Git generator over a file of teams, as in
  [GitOps & Argo CD](https://www.nauthera.io/docs/v1/adoption/gitops#team-applications), gives each entry its client.
  Onboarding is a pull request adding one entry, and offboarding one removing it.
- **A machine client per preview.** Add a second `OIDCClient` to the preview chart with
  the `client_credentials` grant for the preview's end-to-end tests. The test job reads its
  Secret, and it goes with the pull request like the rest.

## Checklist

- [ ] One preview namespace per application, admitted once by its organization.
- [ ] A `Group` of reviewers in it, with verified addresses, and a
      `ValidatingAdmissionPolicy` holding every client there to `deletionPolicy: Delete`
      and that group.
- [ ] The client's `metadata.name` and `clientId` carry the pull request's number, never
      the commit.
- [ ] Short access-token lifetimes on preview clients.
- [ ] The `OIDCClient` health check in `argocd-cm`, and the client in sync wave `-1`.
- [ ] The ApplicationSet's `project` is a constant, and nothing preserves resources on
      deletion.
- [ ] A webhook, or a short `requeueAfterSeconds`, so previews come and go with their pull
      requests.
- [ ] An alert on `OIDCClient`s in phase `Deleting`.
