diff --git a/content/dictionary.txt b/content/dictionary.txt index 753a538..5739fec 100644 --- a/content/dictionary.txt +++ b/content/dictionary.txt @@ -232,6 +232,7 @@ cta docsy's navbar viewport +TokenRequest CIDRs GatewayClass GatewayClasses @@ -247,3 +248,16 @@ ResourceClaims ResourceClaimTemplate ResourceClaimTemplates FPGA +ClusterRoleBinding +GlobalTenantResources +TenantResources +UID +kstatus +rollout +rollouts +KiB +MiB +cooldown +lookups +oversized +resyncs diff --git a/content/en/docs/operating/best-practices/_index.md b/content/en/docs/operating/best-practices/_index.md index 9b23524..927f218 100644 --- a/content/en/docs/operating/best-practices/_index.md +++ b/content/en/docs/operating/best-practices/_index.md @@ -36,3 +36,51 @@ If no external secret store is available, there should at least be a secure way In our ecosystem, we provide a solution based on SOPS (Secrets OPerationS) for this use case; called the [sops-operator](https://github.com/peak-scale/sops-operator). [👉 Demonstration](https://killercoda.com/peakscale/course/playgrounds/sops-secrets) + +### Block Static ServiceAccount Tokens + +Use the TokenRequest API or projected ServiceAccount token volumes for Kubernetes +API access. Kubernetes recommends these credentials over legacy +`kubernetes.io/service-account-token` Secrets, which hold tokens that do not +expire automatically. See the Kubernetes [ServiceAccount token +documentation](https://kubernetes.io/docs/concepts/security/service-accounts/#manually-retrieve-serviceaccount-credentials). + +Prevent new legacy token Secrets in Tenant namespaces with a +[metadata rule](/docs/rules/enforcement/metadata/) that denies the +`kubernetes.io/service-account.name` annotation required by that Secret type: + +```yaml +apiVersion: capsule.clastix.io/v1beta2 +kind: Tenant +metadata: + name: solar +spec: + owners: + - kind: User + name: solar-owner + rules: + - enforce: + action: deny + metadata: + - apiGroups: [v1] + kinds: [Secret] + annotations: + 'kubernetes\.io/service-account\.name': {} +``` + +The escaped dots match the exact annotation key. With `action: deny`, the empty +policy `{}` rejects any value, including an empty string. Secrets without this +annotation remain unaffected by this rule. TokenRequest and projected volumes +use a different API path and remain available under their existing permissions. +Setting `automountServiceAccountToken: false` alone does not prevent someone +from creating a legacy token Secret. + +Merge this rule into the Tenant's existing `spec.rules`, preserving other +configuration. With no namespace selector, it covers every namespace of that +Tenant. The [combined Tenant baseline](/docs/operating/best-practices/tenants/#reference) +already includes it. Keep later metadata rules from overriding the denial. + +This is an admission policy, not credential revocation: unchanged annotations +are skipped on updates, and existing tokens are not removed. Review and remove +existing legacy token Secrets separately. The rule also cannot identify token +strings copied into ordinary Secret data. diff --git a/content/en/docs/operating/best-practices/admission-policies.md b/content/en/docs/operating/best-practices/admission-policies.md index 60f3cd2..a6f28c7 100644 --- a/content/en/docs/operating/best-practices/admission-policies.md +++ b/content/en/docs/operating/best-practices/admission-policies.md @@ -6,302 +6,7 @@ description: Recommended Admission Policies to enforce best practices in multi-t As Capsule we try to provide a secure multi-tenant environment out of the box, there are however some additional Admission Policies you should consider to enforce best practices in your cluster. Since Capsule only covers the core multi-tenancy features, such as Namespaces, Resource Quotas, Network Policies, and Container Registries, Classes, you should consider using an additional Admission Controller to enforce best practices on workloads and other resources. -## Custom - -Create custom Policies and reuse data provided via Tenant Status to enforce your own rules. - -### Owner Validation - - -### Class Validation - -Let's say we have the following namespaced [`ObjectBucketClaim`](https://rook.io/docs/rook/v1.12/Storage-Configuration/Object-Storage-RGW/object-storage/#create-a-bucket) resource: - -```yaml -apiVersion: objectbucket.io/v1alpha1 -kind: ObjectBucketClaim -metadata: - name: admission-class - namespace: solar-production - finalizers: - - objectbucket.io/finalizer - labels: - bucket-provisioner: openshift-storage.ceph.rook.io-bucket -spec: - additionalConfig: - maxSize: 2G - bucketName: test-some-uid - generateBucketName: test - objectBucketName: obc-test-test - storageClassName: ocs-storagecluster-ceph-rgw -``` - -However since we are allowing Tenant Users to create these [`ObjectBucketClaims`](https://rook.io/docs/rook/v1.12/Storage-Configuration/Object-Storage-RGW/object-storage/#create-a-bucket) we might want to consider validating the `storageClassName` field to ensure that only allowed StorageClasses are used. - - -{{% tabpane lang="yaml" %}} - {{% tab header="**Engines**:" disabled=true /%}} - {{< tab header="Kyverno" >}} ---- -apiVersion: kyverno.io/v1 -kind: ClusterPolicy -metadata: - name: restrict-tenant-class -spec: - validationFailureAction: Enforce - rules: - - name: restrict-storage-class - context: - - name: classes - apiCall: - urlPath: "/apis/capsule.clastix.io/v1beta2/tenants" - jmesPath: "items[?contains(status.namespaces, '{{ request.namespace }}')].status.classes | [0]" - - - name: storageClass - variable: - jmesPath: "request.object.spec.storageClassName || 'NONE'" - match: - resources: - kinds: - - ObjectBucketClaim - namespaceSelector: - matchExpressions: - - key: capsule.clastix.io/tenant - operator: Exists - validate: - message: "storageclass {{ storageClass }} is not allowed in tenant ({{classes.storage}})" - deny: - conditions: - - key: "{{classes.storage}}" - operator: AnyNotIn - value: "{{ storageClass }}"{{< /tab >}} -{{% /tabpane %}} - -## Workloads - -Policies to harden workloads running in a multi-tenant environment. - -### Pod Disruption Budgets - -[Pod Disruption Budgets](https://kubernetes.io/docs/tasks/run-application/configure-pdb/) (PDBs) are a way to limit the number of concurrent disruptions to your Pods. In multi-tenant environments, it is recommended to enforce the usage of PDBs to ensure that tenants do not accidentally or maliciously block cluster operations. - -#### MaxUnavailable - - A PodDisruptionBudget which sets its maxUnavailable value to zero prevents all voluntary evictions including Node drains which may impact maintenance tasks. This policy enforces that if a PodDisruptionBudget specifies the maxUnavailable field it must be greater than zero. - -{{% tabpane lang="yaml" %}} - {{% tab header="**Engines**:" disabled=true /%}} - {{< tab header="Kyverno" >}} ---- -# Source: https://kyverno.io/policies/other/pdb-maxunavailable/pdb-maxunavailable/ -apiVersion: kyverno.io/v1 -kind: ClusterPolicy -metadata: - name: pdb-maxunavailable - annotations: - policies.kyverno.io/title: PodDisruptionBudget maxUnavailable Non-Zero - policies.kyverno.io/category: Other - kyverno.io/kyverno-version: 1.9.0 - kyverno.io/kubernetes-version: "1.24" - policies.kyverno.io/subject: PodDisruptionBudget - policies.kyverno.io/description: >- - A PodDisruptionBudget which sets its maxUnavailable value to zero prevents - all voluntary evictions including Node drains which may impact maintenance tasks. - This policy enforces that if a PodDisruptionBudget specifies the maxUnavailable field - it must be greater than zero. -spec: - validationFailureAction: Enforce - background: false - rules: - - name: pdb-maxunavailable - match: - any: - - resources: - kinds: - - PodDisruptionBudget - namespaceSelector: - matchExpressions: - - key: capsule.clastix.io/tenant - operator: Exists - validate: - message: "The value of maxUnavailable must be greater than zero." - pattern: - spec: - =(maxUnavailable): ">0"{{< /tab >}} - {{< tab header="VAP" >}} -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingAdmissionPolicy -metadata: - name: pdb-maxunavailable -spec: - failurePolicy: Fail - matchConstraints: - resourceRules: - - apiGroups: ["policy"] - apiVersions: ["v1"] - operations: ["CREATE", "UPDATE"] - resources: ["poddisruptionbudgets"] - namespaceSelector: - matchExpressions: - - key: capsule.clastix.io/tenant - operator: Exists - validations: - - expression: | - !has(object.spec.maxUnavailable) || - string(object.spec.maxUnavailable).contains('%') || - object.spec.maxUnavailable > 0 - message: "The value of maxUnavailable must be greater than zero or a percentage." - reason: Invalid ---- -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingAdmissionPolicyBinding -metadata: - name: pdb-maxunavailable-binding -spec: - policyName: pdb-maxunavailable - validationActions: ["Deny"]{{< /tab >}} -{{% /tabpane %}} - -#### MinAvailable - -When a Pod controller which can run multiple replicas is subject to an active PodDisruptionBudget, if the replicas field has a value equal to the minAvailable value of the PodDisruptionBudget it may prevent voluntary disruptions including Node drains which may impact routine maintenance tasks and disrupt operations. This policy checks incoming Deployments and StatefulSets which have a matching PodDisruptionBudget to ensure these two values do not match. - -{{% tabpane lang="yaml" %}} - {{% tab header="**Engines**:" disabled=true /%}} - {{< tab header="Kyverno" >}} ---- -# Source: https://kyverno.io/policies/other/pdb-minavailable/pdb-minavailable/ -apiVersion: kyverno.io/v1 -kind: ClusterPolicy -metadata: - name: pdb-minavailable-check - annotations: - policies.kyverno.io/title: Check PodDisruptionBudget minAvailable - policies.kyverno.io/category: Other - kyverno.io/kyverno-version: 1.9.0 - kyverno.io/kubernetes-version: "1.24" - policies.kyverno.io/subject: PodDisruptionBudget, Deployment, StatefulSet - policies.kyverno.io/description: >- - When a Pod controller which can run multiple replicas is subject to an active PodDisruptionBudget, - if the replicas field has a value equal to the minAvailable value of the PodDisruptionBudget - it may prevent voluntary disruptions including Node drains which may impact routine maintenance - tasks and disrupt operations. This policy checks incoming Deployments and StatefulSets which have - a matching PodDisruptionBudget to ensure these two values do not match. -spec: - validationFailureAction: Enforce - background: false - rules: - - name: pdb-minavailable - match: - any: - - resources: - kinds: - - Deployment - - StatefulSet - namespaceSelector: - matchExpressions: - - key: capsule.clastix.io/tenant - operator: Exists - preconditions: - all: - - key: "{{`{{ request.operation | 'BACKGROUND' }}`}}" - operator: AnyIn - value: - - CREATE - - UPDATE - - key: "{{`{{ request.object.spec.replicas | '1' }}`}}" - operator: GreaterThan - value: 0 - context: - - name: minavailable - apiCall: - urlPath: "/apis/policy/v1/namespaces/{{`{{ request.namespace }}`}}/poddisruptionbudgets" - jmesPath: "items[?label_match(spec.selector.matchLabels, `{{`{{ request.object.spec.template.metadata.labels }}`}}`)] | [0].spec.minAvailable | default(`0`)" - validate: - message: >- - The matching PodDisruptionBudget for this resource has its minAvailable value equal to the replica count - which is not permitted. - deny: - conditions: - any: - - key: "{{`{{ request.object.spec.replicas }}`}}" - operator: Equals - value: "{{`{{ minavailable }}`}}"{{< /tab >}} -{{% /tabpane %}} - -#### Deployment Replicas higher than PDB - -PodDisruptionBudget resources are useful to ensuring minimum availability is maintained at all times.Introducing a PDB where there are already matching Pod controllers may pose a problem if the author is unaware of the existing replica count. This policy ensures that the minAvailable value is not greater or equal to the replica count of any matching existing Deployment. If other Pod controllers should also be included in this check, additional rules may be added to the policy which match those controllers. - -{{% tabpane lang="yaml" %}} - {{% tab header="**Engines**:" disabled=true /%}} - {{< tab header="Kyverno" >}} ---- -# Source: https://kyverno.io/policies/other/deployment-replicas-higher-than-pdb/deployment-replicas-higher-than-pdb/ -apiVersion: kyverno.io/v1 -kind: ClusterPolicy -metadata: - name: deployment-replicas-higher-than-pdb - annotations: - policies.kyverno.io/title: Ensure Deployment Replicas Higher Than PodDisruptionBudget - policies.kyverno.io/category: Other - policies.kyverno.io/subject: PodDisruptionBudget, Deployment - kyverno.io/kyverno-version: 1.11.4 - kyverno.io/kubernetes-version: "1.27" - policies.kyverno.io/description: >- - PodDisruptionBudget resources are useful to ensuring minimum availability is maintained at all times. - Introducing a PDB where there are already matching Pod controllers may pose a problem if the author - is unaware of the existing replica count. This policy ensures that the minAvailable value is not - greater or equal to the replica count of any matching existing Deployment. If other Pod controllers - should also be included in this check, additional rules may be added to the policy which match those - controllers. -spec: - validationFailureAction: Enforce - background: true - rules: - - name: deployment-replicas-greater-minAvailable - match: - any: - - resources: - kinds: - - PodDisruptionBudget - operations: - - CREATE - - UPDATE - namespaceSelector: - matchExpressions: - - key: capsule.clastix.io/tenant - operator: Exists - context: - - name: deploymentreplicas - apiCall: - jmesPath: items[?label_match(`{{`{{ request.object.spec.selector.matchLabels }}`}}`, spec.template.metadata.labels)] || `[]` - urlPath: /apis/apps/v1/namespaces/{{`{{request.namespace}}`}}/deployments - preconditions: - all: - - key: '{{`{{ length(deploymentreplicas) }}`}}' - operator: GreaterThan - value: 0 - - key: '{{`{{ request.object.spec.minAvailable || "" }}`}}' - operator: NotEquals - value: '' - validate: - message: >- - PodDisruption budget minAvailable ({{`{{ request.object.spec.minAvailable }}`}}) cannot be - greater than or equal to the replica count of any matching existing Deployment. - There are {{`{{ length(deploymentreplicas) }}`}} Deployments which match this labelSelector - having {{`{{ deploymentreplicas[*].spec.replicas }}`}} replicas. - foreach: - - list: deploymentreplicas - deny: - conditions: - all: - - key: "{{`{{ request.object.spec.minAvailable }}`}}" - operator: GreaterThanOrEquals - value: "{{`{{ element.spec.replicas }}`}}"{{< /tab >}} -{{% /tabpane %}} - -#### CNPG Cluster +## CNPG Cluster When a Pod controller which can run multiple replicas is subject to an active PodDisruptionBudget, if the replicas field has a value equal to the minAvailable value of the PodDisruptionBudget it may prevent voluntary disruptions including Node drains which may impact routine maintenance tasks and disrupt operations. This policy checks incoming CNPG Clusters and their `.spec.enablePDB` setting. @@ -394,138 +99,6 @@ spec: validationActions: ["Deny"]{{< /tab >}} {{% /tabpane %}} -### Enforce EmptDir Requests/Limits - -By Defaults `emptyDir` Volumes do not have any limits. This could lead to a situation, where a tenant fills up the node disk. To avoid this, you can enforce limits on `emptyDir` volumes. You may also consider restricting the usage of `emptyDir` with the `medium: Memory` option, as this could lead to memory exhaustion on the node. - -{{% tabpane lang="yaml" %}} - {{% tab header="**Engines**:" disabled=true /%}} - {{< tab header="Kyverno" >}} ---- -apiVersion: kyverno.io/v1 -kind: ClusterPolicy -metadata: - name: tenant-workload-restrictions -spec: - rules: - - name: default-emptydir-sizelimit - match: - any: - - resources: - kinds: - - Pod - namespaceSelector: - matchExpressions: - - key: capsule.clastix.io/tenant - operator: Exists - mutate: - foreach: - - list: "request.object.spec.volumes[]" - preconditions: - all: - - key: "{{element.keys(@)}}" - operator: AnyIn - value: emptyDir - - key: "{{element.emptyDir.sizeLimit || ''}}" - operator: Equals - value: '' - patchesJson6902: |- - - path: "/spec/volumes/{{elementIndex}}/emptyDir/sizeLimit" - op: add - value: 250Mi{{< /tab >}} -{{% /tabpane %}} - -### Block Ephemeral Containers - -Ephemeral containers, enabled by default in Kubernetes 1.23, allow users to use the `kubectl debug` functionality and attach a temporary container to an existing Pod. This may potentially be used to gain access to unauthorized information executing inside one or more containers in that Pod. This policy blocks the use of ephemeral containers. - -{{% tabpane lang="yaml" %}} - {{% tab header="**Engines**:" disabled=true /%}} - {{< tab header="VAP" >}} ---- -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingAdmissionPolicy -metadata: - name: block-ephemeral-containers -spec: - failurePolicy: Fail - matchConstraints: - resourceRules: - # 1) Regular Pods (ensure spec doesn't carry ephemeralContainers) - - apiGroups: [""] - apiVersions: ["v1"] - resources: ["pods"] - operations: ["CREATE","UPDATE"] - scope: "Namespaced" - # 2) Subresource used by `kubectl debug` to inject ephemeral containers - - apiGroups: [""] - apiVersions: ["v1"] - resources: ["pods/ephemeralcontainers"] - operations: ["UPDATE","CREATE"] # UPDATE is typical, CREATE included for future-proofing - scope: "Namespaced" - validations: - # Deny any request that targets the pods/ephemeralcontainers subresource - - expression: request.subResource != "ephemeralcontainers" - message: "Ephemeral (debug) containers are not permitted (subresource)." - # For direct Pod create/update, allow only if the field is absent or empty - - expression: > - !has(object.spec.ephemeralContainers) || - size(object.spec.ephemeralContainers) == 0 - message: "Ephemeral (debug) containers are not permitted in Pod specs." ---- -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingAdmissionPolicyBinding -metadata: - name: block-ephemeral-containers-binding -spec: - policyName: block-ephemeral-containers - validationActions: ["Deny"] - matchResources: - namespaceSelector: - matchExpressions: - - key: capsule.clastix.io/tenant - operator: Exists{{< /tab >}} - {{< tab header="Kyverno" >}} -# Source: https://kyverno.io/policies/other/block-ephemeral-containers/block-ephemeral-containers/ ---- -apiVersion: kyverno.io/v1 -kind: ClusterPolicy -metadata: - name: block-ephemeral-containers - annotations: - policies.kyverno.io/title: Block Ephemeral Containers - policies.kyverno.io/category: Other - policies.kyverno.io/severity: medium - kyverno.io/kyverno-version: 1.6.0 - policies.kyverno.io/minversion: 1.6.0 - kyverno.io/kubernetes-version: "1.23" - policies.kyverno.io/subject: Pod - policies.kyverno.io/description: >- - Ephemeral containers, enabled by default in Kubernetes 1.23, allow users to use the - `kubectl debug` functionality and attach a temporary container to an existing Pod. - This may potentially be used to gain access to unauthorized information executing inside - one or more containers in that Pod. This policy blocks the use of ephemeral containers. -spec: - validationFailureAction: Enforce - background: true - rules: - - name: block-ephemeral-containers - match: - any: - - resources: - kinds: - - Pod - namespaceSelector: - matchExpressions: - - key: capsule.clastix.io/tenant - operator: Exists - validate: - message: "Ephemeral (debug) containers are not permitted." - pattern: - spec: - X(ephemeralContainers): "null"{{< /tab >}} -{{% /tabpane %}} - ## Certificates ### Deny ClusterIssuer in Certificates diff --git a/content/en/docs/operating/best-practices/tenants.md b/content/en/docs/operating/best-practices/tenants.md index 6833f15..2cea2cf 100644 --- a/content/en/docs/operating/best-practices/tenants.md +++ b/content/en/docs/operating/best-practices/tenants.md @@ -3,12 +3,13 @@ title: Tenants weight: 1 aliases: - /docs/operating/best-practices/images/ -description: A complete Tenant combining the workload and networking best-practice baseline +description: A complete Tenant combining workload, networking, and credential best practices --- Use this complete Tenant as a starting point for application namespaces. It -combines the compatible baseline policies from [Workloads](/docs/operating/best-practices/workloads/) -and [Networking](/docs/operating/best-practices/networking/) into one ordered +combines the compatible baseline policies from [Workloads](/docs/operating/best-practices/workloads/), +[Networking](/docs/operating/best-practices/networking/), and +[ServiceAccount credentials](/docs/operating/best-practices/#block-static-serviceaccount-tokens) into one ordered `spec.rules` list. All namespaces in this Tenant receive the same baseline. ## Included Policies @@ -25,6 +26,7 @@ and [Networking](/docs/operating/best-practices/networking/) into one ordered | Priority | Default to and allow only `tenant-standard`. | | Services | Allow only `ClusterIP` and deny every external IP. | | Namespace trust | Deny adding or changing `company.com/system` on Tenant namespaces. | +| Credentials | Deny the annotation required to create legacy ServiceAccount token Secrets. | | DRA admin access | Keep administrative device access disabled by denying `resource.kubernetes.io/admin-access: "true"` on Tenant namespaces. | ## Before Applying @@ -98,6 +100,9 @@ PriorityClass settings. - comment: "Reserve this trusted-platform label for administrator-managed namespaces." title: Protect platform trust labels url: /docs/rules/enforcement/metadata/#deny-metadata-values +- comment: "Prevent creation of legacy ServiceAccount token Secrets." + title: Block static ServiceAccount tokens + url: /docs/operating/best-practices/#block-static-serviceaccount-tokens - comment: "Keep DRA administrative access disabled in application namespaces." title: Disable DRA admin access url: /docs/operating/best-practices/tenants/#dra-administrative-access diff --git a/content/en/docs/operating/best-practices/tenants.yaml b/content/en/docs/operating/best-practices/tenants.yaml index df7fd62..8867476 100644 --- a/content/en/docs/operating/best-practices/tenants.yaml +++ b/content/en/docs/operating/best-practices/tenants.yaml @@ -196,6 +196,15 @@ spec: values: - exp: ".*" + # Prevent creation of legacy ServiceAccount token Secrets. + - enforce: + action: deny + metadata: + - apiGroups: [v1] + kinds: [Secret] + annotations: + kubernetes.io/service-account.name: {} + # Keep DRA administrative access disabled in application namespaces. - enforce: action: deny diff --git a/content/en/docs/operating/concepts/_index.md b/content/en/docs/operating/concepts/_index.md index 6b22427..c94c43c 100644 --- a/content/en/docs/operating/concepts/_index.md +++ b/content/en/docs/operating/concepts/_index.md @@ -6,6 +6,9 @@ description: Key design decisions, personas, templating, and metadata reference Concept references explain reusable behavior shared across Capsule APIs: +- [Audiences](./audiences/): select request identities for namespace rules and + replication admission triggers, including Capsule users, administrators, tenant + owners, and the Capsule controller. - [Parameter Schemas and Dynamic Forms](./parameter-schema/): validate parameterized APIs with JSON Schema and Kubernetes CEL, and populate client forms from arbitrary Kubernetes resources. diff --git a/content/en/docs/operating/concepts/audiences.md b/content/en/docs/operating/concepts/audiences.md new file mode 100644 index 0000000..a1f3e37 --- /dev/null +++ b/content/en/docs/operating/concepts/audiences.md @@ -0,0 +1,111 @@ +--- +title: Audiences +weight: 7 +description: > + Select request identities for namespace rules. +--- + +An `audience` selects the request identities to which a +[namespace rule](/docs/rules/#audience) applies. +[Replication resource watches](/docs/replications/#resource-watches) do not carry request +identities and cannot use audiences. + +## Matching + +An audience is a list of `kind` and `name` entries: + +```yaml +audience: + - kind: User + name: alice@example.com + - kind: Group + name: oidc:engineering + - kind: ServiceAccount + name: system:serviceaccount:delivery:deployer +``` + +An omitted or empty audience matches every request selected by the containing +rule. A nonempty audience matches when **at least one entry** matches: +entries use logical **OR**. In this example, Alice, members of +`oidc:engineering`, and the `delivery/deployer` service account all qualify. + +Namespace selection, resource selection, conditions, and other feature-specific +checks must also qualify. An audience does not grant Kubernetes RBAC permissions, +change tenant ownership, or bypass managed-resource protection. + +| Used by | Field | Effect when the audience does not match | +| --- | --- | --- | +| Namespace rules | `Tenant.spec.rules[].audience` | Skip that rule's admission mutation and enforcement. Other applicable rules still apply. | + +## Standard audiences + +| Kind | Matching behavior | Example `name` | +| --- | --- | --- | +| `User` | Exact match against the requesting username. | `alice@example.com` | +| `Group` | Match when the request includes the named group. | `oidc:engineering` | +| `ServiceAccount` | Exact match against the service account's canonical Kubernetes username. | `system:serviceaccount:delivery:deployer` | + +Names are literal, case-sensitive values. They do not support wildcards or +regular expressions. A service account name includes both its namespace and name: + +```text +system:serviceaccount:: +``` + +## Custom audiences + +Use `kind: Custom` with one of these supported names: + +| Name | Matching behavior | +| --- | --- | +| `CapsuleUser` | Capsule's effective user membership, including configured and aggregated subjects and service accounts in tenant namespaces. Ignored groups are excluded. | +| `Administrator` | A subject matching `CapsuleConfiguration.spec.administrators`. | +| `TenantOwner` | An owner of the tenant resolved for this request, from `Tenant.spec.owners` or effective `Tenant.status.owners`. It does not match when no tenant is resolved. | +| `Controller` | The service account used by the Capsule controller. Other Kubernetes controllers do not match this category. | + +`CapsuleUser` follows Capsule's membership checks. The Capsule controller service +account and service accounts in `kube-system` are excluded from this category. +See [Capsule Users](/docs/operating/concepts/architecture/#capsule-users) and +[administrator configuration](/docs/operating/setup/configuration/#administrators) +for the underlying identity configuration. + +Custom and standard entries can be combined. This audience matches either a +tenant owner or a member of `platform-operators`: + +```yaml +audience: + - kind: Custom + name: TenantOwner + - kind: Group + name: platform-operators +``` + +OR semantics also apply when combining custom entries. For example, combining +`CapsuleUser` and `TenantOwner` includes any matching Capsule user, even if that +subject is not an owner of the current tenant. + +### Tenant context + +`TenantOwner` uses the tenant associated with the request being evaluated: + +| Used by | Tenant checked | +| --- | --- | +| Namespace rules | The tenant resolved for the namespace being evaluated. | + +## Request identity + +Audience matching uses the authenticated identity carried by the Kubernetes +admission request. For example, when a workload controller creates a Pod, the +request normally comes from that controller's service account. An audience +matching the user who created the Deployment or Job will not automatically match +that subsequent Pod request. + +Account for this distinction when selecting audiences for workload mutation +or enforcement. `Controller` identifies Capsule's own +service account; it does not match every actor creating resources through a +controller. + +Capsule evaluates audiences in its admission handlers. + +Unknown kinds, unsupported `Custom` names, and empty names are rejected when the +containing rule is admitted. diff --git a/content/en/docs/operating/setup/installation.md b/content/en/docs/operating/setup/installation.md index 3e7db55..99b4d7b 100644 --- a/content/en/docs/operating/setup/installation.md +++ b/content/en/docs/operating/setup/installation.md @@ -90,6 +90,39 @@ podDisruptionBudget: The chart defaults `minAvailable` to `1`. If you want to customize these values, use either `minAvailable` or `maxUnavailable` (a number or a percentage). The PodDisruptionBudget and the default anti-affinity are only applied when `manager.kind` is `Deployment`. +### Controller workloads + +The chart always installs separate workloads for the `core` and `replications` +commands of the same Capsule binary. Upgrades add the replication Deployment +alongside the existing core workload; there is no replication enable switch. +The core controller handles admission and namespace profiling. The replication +controller handles TenantResources, GlobalTenantResources, source watches and +health checks. + +Existing `manager.*` settings configure the core controller, whose kind remains +controlled by `manager.kind`. The replication controller runs as a Deployment and +has independent pod settings under `controllers.replications`: + +```yaml +controllers: + replications: + replicaCount: 2 + resources: + requests: + cpu: 250m + memory: 256Mi + limits: + memory: 1Gi + options: + workers: 8 + clientConnectionQPS: 100 + clientConnectionBurst: 200 +``` + +Replication workers use their own leader-election lease. Increasing their +resources or API request budget does not change the core controller's settings. +Installations with `crds.exclusive: true` continue to omit workloads. + ### Scalability For large clusters you might need to consider adjusting values for the Capsule controller. @@ -424,7 +457,6 @@ webhooks: - "controller" ``` - ## GitOps There are no specific requirements for using Capsule with GitOps tools like ArgoCD or FluxCD. You can manage Capsule resources as you would with any other Kubernetes resource. diff --git a/content/en/docs/reference.md b/content/en/docs/reference.md index 8b6537b..55f0f6d 100644 --- a/content/en/docs/reference.md +++ b/content/en/docs/reference.md @@ -1419,6 +1419,8 @@ GlobalTenantResourceSpec defines the desired state of GlobalTenantResource. | **scope** | enum | Resource Scope, Can either be
- Tenant: Create Resources for each tenant in selected Tenants
- Namespace: Create Resources for each namespace in selected Tenants
*Enum*: Namespace, Tenant, None
*Default*: Namespace
| false | | **[serviceAccount](#globaltenantresourcespecserviceaccount)** | object | Local ServiceAccount which will perform all the actions defined in the TenantResource
You must provide permissions accordingly to that ServiceAccount | false | | **[tenantSelector](#globaltenantresourcespectenantselector)** | object | Defines the Tenant selector used target the tenants on which resources must be propagated. | false | +| **triggerMinInterval** | string | TriggerMinInterval bounds triggered reconciliation frequency across all triggers
on this resource. Events within the interval coalesce into one pending reconcile.
Spec changes, deletion, manual requests, and periodic resyncs retain their behavior.
*Default*: 10s
| false | +| **[triggers](#globaltenantresourcespectriggersindex)** | []object | Triggers request reconciliation on matching namespaced admission attempts.
Capsule-managed resources never trigger reconciliation. Delivery is best effort;
resyncPeriod remains the recovery mechanism for missed or pre-persistence events. | false | ### GlobalTenantResource.spec.resources[index] @@ -1676,6 +1678,111 @@ Defines the Tenant selector used target the tenants on which resources must be p +A label selector requirement is a selector that contains values, a key, and an operator that +relates the key and values. + + +| **Name** | **Type** | **Description** | **Required** | +| :---- | :---- | :----------- | :-------- | +| **key** | string | key is the label key that the selector applies to. | true | +| **operator** | string | operator represents a key's relationship to a set of values.
Valid operators are In, NotIn, Exists and DoesNotExist. | true | +| **values** | []string | values is an array of string values. If the operator is In or NotIn,
the values array must be non-empty. If the operator is Exists or DoesNotExist,
the values array must be empty. This array is replaced during a strategic
merge patch. | false | + + +### GlobalTenantResource.spec.triggers[index] + + + +TenantResourceTrigger requests best-effort reconciliation on matching admission attempts. +Resource behavior and replication destinations remain defined by resources. + + +| **Name** | **Type** | **Description** | **Required** | +| :---- | :---- | :----------- | :-------- | +| **name** | string | Name uniquely identifies this trigger. | true | +| **apiGroups** | []string | apiGroups is the API groups the resources belong to. '*' is all groups.
If '*' is present, the length of the slice must be one.
Required. | false | +| **apiVersions** | []string | apiVersions is the API versions the resources belong to. '*' is all versions.
If '*' is present, the length of the slice must be one.
Required. | false | +| **[audience](#globaltenantresourcespectriggersindexaudienceindex)** | []object | Audience uses the same identity matching as namespace rules. Empty matches everyone. | false | +| **[matchConditions](#globaltenantresourcespectriggersindexmatchconditionsindex)** | []object | MatchConditions are native admission CEL conditions. All must match. | false | +| **[namespaceSelector](#globaltenantresourcespectriggersindexnamespaceselector)** | object | NamespaceSelector selects event source namespaces for GlobalTenantResources.
TenantResources always observe only their own namespace and cannot set this field. | false | +| **[objectSelector](#globaltenantresourcespectriggersindexobjectselector)** | object | ObjectSelector matches the labels of either the old or new admission object. | false | +| **operations** | []string | operations is the operations the admission hook cares about - CREATE, UPDATE, DELETE, CONNECT or *
for all of those operations and any future admission operations that are added.
If '*' is present, the length of the slice must be one.
Required. | false | +| **resources** | []string | resources is a list of resources this rule applies to.

For example:
'pods' means pods.
'pods/log' means the log subresource of pods.
'*' means all resources, but not subresources.
'pods/*' means all subresources of pods.
'*/scale' means all scale subresources.
'*/*' means all resources and their subresources.

If wildcard is present, the validation rule will ensure resources do not
overlap with each other.

Depending on the enclosing object, subresources might not be allowed.
Required. | false | +| **scope** | string | scope specifies the scope of this rule.
Valid values are "Cluster", "Namespaced", and "*"
"Cluster" means that only cluster-scoped resources will match this rule.
Namespace API objects are cluster-scoped.
"Namespaced" means that only namespaced resources will match this rule.
"*" means that there are no scope restrictions.
Subresources match the scope of their parent resource.
Default is "*". | false | + + +### GlobalTenantResource.spec.triggers[index].audience[index] + + + + + + +| **Name** | **Type** | **Description** | **Required** | +| :---- | :---- | :----------- | :-------- | +| **kind** | enum |
*Enum*: User, Group, ServiceAccount, Custom
| true | +| **name** | string | | true | + + +### GlobalTenantResource.spec.triggers[index].matchConditions[index] + + + +MatchCondition represents a condition which must by fulfilled for a request to be sent to a webhook. + + +| **Name** | **Type** | **Description** | **Required** | +| :---- | :---- | :----------- | :-------- | +| **expression** | string | expression represents the expression which will be evaluated by CEL. Must evaluate to bool.
CEL expressions have access to the contents of the AdmissionRequest and Authorizer, organized into CEL variables:

'object' - The object from the incoming request. The value is null for DELETE requests.
'oldObject' - The existing object. The value is null for CREATE requests.
'request' - Attributes of the admission request(/pkg/apis/admission/types.go#AdmissionRequest).
'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request.
See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz
'authorizer.requestResource' - A CEL ResourceCheck constructed from the 'authorizer' and configured with the
request resource.
Documentation on CEL: https://kubernetes.io/docs/reference/using-api/cel/

Required. | true | +| **name** | string | name is an identifier for this match condition, used for strategic merging of MatchConditions,
as well as providing an identifier for logging purposes. A good name should be descriptive of
the associated expression.
Name must be a qualified name consisting of alphanumeric characters, '-', '_' or '.', and
must start and end with an alphanumeric character (e.g. 'MyName', or 'my.name', or
'123-abc', regex used for validation is '([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]') with an
optional DNS subdomain prefix and '/' (e.g. 'example.com/MyName')

Required. | true | + + +### GlobalTenantResource.spec.triggers[index].namespaceSelector + + + +NamespaceSelector selects event source namespaces for GlobalTenantResources. +TenantResources always observe only their own namespace and cannot set this field. + + +| **Name** | **Type** | **Description** | **Required** | +| :---- | :---- | :----------- | :-------- | +| **[matchExpressions](#globaltenantresourcespectriggersindexnamespaceselectormatchexpressionsindex)** | []object | matchExpressions is a list of label selector requirements. The requirements are ANDed. | false | +| **matchLabels** | map[string]string | matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels
map is equivalent to an element of matchExpressions, whose key field is "key", the
operator is "In", and the values array contains only "value". The requirements are ANDed. | false | + + +### GlobalTenantResource.spec.triggers[index].namespaceSelector.matchExpressions[index] + + + +A label selector requirement is a selector that contains values, a key, and an operator that +relates the key and values. + + +| **Name** | **Type** | **Description** | **Required** | +| :---- | :---- | :----------- | :-------- | +| **key** | string | key is the label key that the selector applies to. | true | +| **operator** | string | operator represents a key's relationship to a set of values.
Valid operators are In, NotIn, Exists and DoesNotExist. | true | +| **values** | []string | values is an array of string values. If the operator is In or NotIn,
the values array must be non-empty. If the operator is Exists or DoesNotExist,
the values array must be empty. This array is replaced during a strategic
merge patch. | false | + + +### GlobalTenantResource.spec.triggers[index].objectSelector + + + +ObjectSelector matches the labels of either the old or new admission object. + + +| **Name** | **Type** | **Description** | **Required** | +| :---- | :---- | :----------- | :-------- | +| **[matchExpressions](#globaltenantresourcespectriggersindexobjectselectormatchexpressionsindex)** | []object | matchExpressions is a list of label selector requirements. The requirements are ANDed. | false | +| **matchLabels** | map[string]string | matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels
map is equivalent to an element of matchExpressions, whose key field is "key", the
operator is "In", and the values array contains only "value". The requirements are ANDed. | false | + + +### GlobalTenantResource.spec.triggers[index].objectSelector.matchExpressions[index] + + + A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values. @@ -1702,6 +1809,8 @@ GlobalTenantResourceStatus defines the observed state of GlobalTenantResource. | **[processedItems](#globaltenantresourcestatusprocesseditemsindex)** | []object | List of resources managed by the API object. | false | | **selectedTenants** | []string | List of Tenants addressed by the GlobalTenantResource. | false | | **[serviceAccount](#globaltenantresourcestatusserviceaccount)** | object | Serviceaccount used for impersonation | false | +| **nextResyncAt** | string | NextResyncAt is the next periodic resync deadline for trigger-enabled replications.
*Format*: date-time
| false | +| **[trigger](#globaltenantresourcestatustrigger)** | object | Trigger records the last admission notification handled by this controller. | false | ### GlobalTenantResource.status.conditions[index] @@ -1789,6 +1898,18 @@ Serviceaccount used for impersonation | **name** | string | Name of the referent. | true | | **namespace** | string | Namespace of the referent. | true | +### GlobalTenantResource.status.trigger + + + +Trigger records the last admission notification handled by this controller. + + +| **Name** | **Type** | **Description** | **Required** | +| :---- | :---- | :----------- | :-------- | +| **lastTriggeredAt** | string | LastTriggeredAt is the start of the last triggered reconcile, including failed attempts.
*Format*: date-time
| true | +| **observedRequest** | string | ObservedRequest identifies the notification included in the last triggered reconcile. | true | + ## QuantityLedger @@ -9136,6 +9257,8 @@ TenantResourceSpec defines the desired state of TenantResource. | **[dependsOn](#tenantresourcespecdependsonindex)** | []object | DependsOn may contain a meta.NamespacedObjectReference slice
with references to TenantResource resources that must be ready before this
TenantResource can be reconciled. | false | | **pruningOnDelete** | boolean | When the replicated resource manifest is deleted, all the objects replicated so far will be automatically deleted.
Disable this to keep replicated resources although the deletion of the replication manifest.

Deprecated: use resources[].policy.deletion instead. Retained for blocks without a policy.

*Default*: true
| false | | **[serviceAccount](#tenantresourcespecserviceaccount)** | object | Local ServiceAccount which will perform all the actions defined in the TenantResource
You must provide permissions accordingly to that ServiceAccount | false | +| **triggerMinInterval** | string | TriggerMinInterval bounds triggered reconciliation frequency across all triggers
on this resource. Events within the interval coalesce into one pending reconcile.
Spec changes, deletion, manual requests, and periodic resyncs retain their behavior.
*Default*: 10s
| false | +| **[triggers](#tenantresourcespectriggersindex)** | []object | Triggers request reconciliation on matching namespaced admission attempts.
Capsule-managed resources never trigger reconciliation. Delivery is best effort;
resyncPeriod remains the recovery mechanism for missed or pre-persistence events. | false | ### TenantResource.spec.resources[index] @@ -9375,6 +9498,111 @@ You must provide permissions accordingly to that ServiceAccount | **name** | string | Name of the referent. | true | +### TenantResource.spec.triggers[index] + + + +TenantResourceTrigger requests best-effort reconciliation on matching admission attempts. +Resource behavior and replication destinations remain defined by resources. + + +| **Name** | **Type** | **Description** | **Required** | +| :---- | :---- | :----------- | :-------- | +| **name** | string | Name uniquely identifies this trigger. | true | +| **apiGroups** | []string | apiGroups is the API groups the resources belong to. '*' is all groups.
If '*' is present, the length of the slice must be one.
Required. | false | +| **apiVersions** | []string | apiVersions is the API versions the resources belong to. '*' is all versions.
If '*' is present, the length of the slice must be one.
Required. | false | +| **[audience](#tenantresourcespectriggersindexaudienceindex)** | []object | Audience uses the same identity matching as namespace rules. Empty matches everyone. | false | +| **[matchConditions](#tenantresourcespectriggersindexmatchconditionsindex)** | []object | MatchConditions are native admission CEL conditions. All must match. | false | +| **[namespaceSelector](#tenantresourcespectriggersindexnamespaceselector)** | object | NamespaceSelector selects event source namespaces for GlobalTenantResources.
TenantResources always observe only their own namespace and cannot set this field. | false | +| **[objectSelector](#tenantresourcespectriggersindexobjectselector)** | object | ObjectSelector matches the labels of either the old or new admission object. | false | +| **operations** | []string | operations is the operations the admission hook cares about - CREATE, UPDATE, DELETE, CONNECT or *
for all of those operations and any future admission operations that are added.
If '*' is present, the length of the slice must be one.
Required. | false | +| **resources** | []string | resources is a list of resources this rule applies to.

For example:
'pods' means pods.
'pods/log' means the log subresource of pods.
'*' means all resources, but not subresources.
'pods/*' means all subresources of pods.
'*/scale' means all scale subresources.
'*/*' means all resources and their subresources.

If wildcard is present, the validation rule will ensure resources do not
overlap with each other.

Depending on the enclosing object, subresources might not be allowed.
Required. | false | +| **scope** | string | scope specifies the scope of this rule.
Valid values are "Cluster", "Namespaced", and "*"
"Cluster" means that only cluster-scoped resources will match this rule.
Namespace API objects are cluster-scoped.
"Namespaced" means that only namespaced resources will match this rule.
"*" means that there are no scope restrictions.
Subresources match the scope of their parent resource.
Default is "*". | false | + + +### TenantResource.spec.triggers[index].audience[index] + + + + + + +| **Name** | **Type** | **Description** | **Required** | +| :---- | :---- | :----------- | :-------- | +| **kind** | enum |
*Enum*: User, Group, ServiceAccount, Custom
| true | +| **name** | string | | true | + + +### TenantResource.spec.triggers[index].matchConditions[index] + + + +MatchCondition represents a condition which must by fulfilled for a request to be sent to a webhook. + + +| **Name** | **Type** | **Description** | **Required** | +| :---- | :---- | :----------- | :-------- | +| **expression** | string | expression represents the expression which will be evaluated by CEL. Must evaluate to bool.
CEL expressions have access to the contents of the AdmissionRequest and Authorizer, organized into CEL variables:

'object' - The object from the incoming request. The value is null for DELETE requests.
'oldObject' - The existing object. The value is null for CREATE requests.
'request' - Attributes of the admission request(/pkg/apis/admission/types.go#AdmissionRequest).
'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request.
See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz
'authorizer.requestResource' - A CEL ResourceCheck constructed from the 'authorizer' and configured with the
request resource.
Documentation on CEL: https://kubernetes.io/docs/reference/using-api/cel/

Required. | true | +| **name** | string | name is an identifier for this match condition, used for strategic merging of MatchConditions,
as well as providing an identifier for logging purposes. A good name should be descriptive of
the associated expression.
Name must be a qualified name consisting of alphanumeric characters, '-', '_' or '.', and
must start and end with an alphanumeric character (e.g. 'MyName', or 'my.name', or
'123-abc', regex used for validation is '([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]') with an
optional DNS subdomain prefix and '/' (e.g. 'example.com/MyName')

Required. | true | + + +### TenantResource.spec.triggers[index].namespaceSelector + + + +NamespaceSelector selects event source namespaces for GlobalTenantResources. +TenantResources always observe only their own namespace and cannot set this field. + + +| **Name** | **Type** | **Description** | **Required** | +| :---- | :---- | :----------- | :-------- | +| **[matchExpressions](#tenantresourcespectriggersindexnamespaceselectormatchexpressionsindex)** | []object | matchExpressions is a list of label selector requirements. The requirements are ANDed. | false | +| **matchLabels** | map[string]string | matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels
map is equivalent to an element of matchExpressions, whose key field is "key", the
operator is "In", and the values array contains only "value". The requirements are ANDed. | false | + + +### TenantResource.spec.triggers[index].namespaceSelector.matchExpressions[index] + + + +A label selector requirement is a selector that contains values, a key, and an operator that +relates the key and values. + + +| **Name** | **Type** | **Description** | **Required** | +| :---- | :---- | :----------- | :-------- | +| **key** | string | key is the label key that the selector applies to. | true | +| **operator** | string | operator represents a key's relationship to a set of values.
Valid operators are In, NotIn, Exists and DoesNotExist. | true | +| **values** | []string | values is an array of string values. If the operator is In or NotIn,
the values array must be non-empty. If the operator is Exists or DoesNotExist,
the values array must be empty. This array is replaced during a strategic
merge patch. | false | + + +### TenantResource.spec.triggers[index].objectSelector + + + +ObjectSelector matches the labels of either the old or new admission object. + + +| **Name** | **Type** | **Description** | **Required** | +| :---- | :---- | :----------- | :-------- | +| **[matchExpressions](#tenantresourcespectriggersindexobjectselectormatchexpressionsindex)** | []object | matchExpressions is a list of label selector requirements. The requirements are ANDed. | false | +| **matchLabels** | map[string]string | matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels
map is equivalent to an element of matchExpressions, whose key field is "key", the
operator is "In", and the values array contains only "value". The requirements are ANDed. | false | + + +### TenantResource.spec.triggers[index].objectSelector.matchExpressions[index] + + + +A label selector requirement is a selector that contains values, a key, and an operator that +relates the key and values. + + +| **Name** | **Type** | **Description** | **Required** | +| :---- | :---- | :----------- | :-------- | +| **key** | string | key is the label key that the selector applies to. | true | +| **operator** | string | operator represents a key's relationship to a set of values.
Valid operators are In, NotIn, Exists and DoesNotExist. | true | +| **values** | []string | values is an array of string values. If the operator is In or NotIn,
the values array must be non-empty. If the operator is Exists or DoesNotExist,
the values array must be empty. This array is replaced during a strategic
merge patch. | false | + + ### TenantResource.status @@ -9389,6 +9617,8 @@ TenantResourceStatus defines the observed state of TenantResource. | **observedGeneration** | integer | ObservedGeneration is the most recent generation the controller has observed.
*Format*: int64
| false | | **[processedItems](#tenantresourcestatusprocesseditemsindex)** | []object | List of resources managed by the API object. | false | | **[serviceAccount](#tenantresourcestatusserviceaccount)** | object | Serviceaccount used for impersonation | false | +| **nextResyncAt** | string | NextResyncAt is the next periodic resync deadline for trigger-enabled replications.
*Format*: date-time
| false | +| **[trigger](#tenantresourcestatustrigger)** | object | Trigger records the last admission notification handled by this controller. | false | ### TenantResource.status.conditions[index] @@ -9476,6 +9706,18 @@ Serviceaccount used for impersonation | **name** | string | Name of the referent. | true | | **namespace** | string | Namespace of the referent. | true | +### TenantResource.status.trigger + + + +Trigger records the last admission notification handled by this controller. + + +| **Name** | **Type** | **Description** | **Required** | +| :---- | :---- | :----------- | :-------- | +| **lastTriggeredAt** | string | LastTriggeredAt is the start of the last triggered reconcile, including failed attempts.
*Format*: date-time
| true | +| **observedRequest** | string | ObservedRequest identifies the notification included in the last triggered reconcile. | true | + ## Tenant diff --git a/content/en/docs/replications/_index.md b/content/en/docs/replications/_index.md index ca4161a..d0b371a 100644 --- a/content/en/docs/replications/_index.md +++ b/content/en/docs/replications/_index.md @@ -1,6 +1,8 @@ --- title: Replications weight: 6 +aliases: + - /docs/replications/triggers/ description: > Replicate resources across tenants or namespaces --- @@ -12,6 +14,628 @@ Capsule provides two dedicated Custom Resource Definitions for propagating Kuber Both CRDs follow the same structure: resources are defined in `spec.resources` blocks, reconciled on a configurable `resyncPeriod`, and support [Go-template-based generators](/docs/operating/concepts/templating/) for dynamic resource creation. +Replications always run in a dedicated Deployment alongside the core controller. +Configure their pod resources, replicas and API request budget with the chart's +`controllers.replications` values; see +[controller workloads](/docs/operating/setup/installation/#controller-workloads). + +## Resource watches + +`TenantResource` and `GlobalTenantResource` support optional resource watch +triggers. Capsule observes persisted namespaced resources and requests +reconciliation when a matching object is added, updated, or deleted. + +`spec.resources` continues to define resource behavior and destination namespace +profiles. Triggers control when reconciliation is requested. Replications without +triggers retain their existing behavior. + +### Trigger example + +This GlobalTenantResource refreshes a Secret summary when selected inputs change. +Its source namespaces and destination namespaces are selected independently. + +```yaml +apiVersion: capsule.clastix.io/v1beta2 +kind: GlobalTenantResource +metadata: + name: production-secret-summary +spec: + scope: Namespace + tenantSelector: + matchLabels: + environment: production + resyncPeriod: 1h + triggerMinInterval: 10s + triggers: + - name: secret-changes + operations: [CREATE, UPDATE, DELETE] + apiGroups: [""] + apiVersions: [v1] + resources: [secrets] + namespaceSelector: + matchLabels: + environment: production + objectSelector: + matchExpressions: + - key: example.com/summary-source + operator: In + values: ["true"] + matchConditions: + - name: content-changed + expression: >- + operation != 'UPDATE' || + has(object.data) != has(oldObject.data) || + (has(object.data) && object.data != oldObject.data) + resources: + - namespaceSelector: + matchLabels: + environment: production + context: + resources: + - index: sources + apiVersion: v1 + kind: Secret + namespace: "{{namespace}}" + selector: + matchLabels: + example.com/summary-source: "true" + generators: + - template: | + apiVersion: v1 + kind: ConfigMap + metadata: + name: secret-summary + data: + count: '{{ if $.sources }}{{ len $.sources }}{{ else }}0{{ end }}' +``` + +For a TenantResource, omit `namespaceSelector` from the trigger. Its sources are +restricted to the namespace containing that TenantResource. This does not change +its replication destinations within the tenant. + +For a GlobalTenantResource, the trigger `namespaceSelector` selects the namespaces +that provide events. `spec.tenantSelector` and each resource's `namespaceSelector` select +destinations. If source namespace metadata is unavailable or the namespace is +terminating, only triggers requiring namespace labels are skipped. Other triggers +without a namespace restriction remain eligible. Administrators can intentionally +select a shared source namespace +outside the destination tenants. + +### Matching changes + +Every trigger has a unique DNS label `name` and requires `operations`, `apiGroups`, +`apiVersions`, and `resources`. + +| Field | Behavior | +| --- | --- | +| `operations` | `CREATE`, `UPDATE`, `DELETE`, or `"*"` for these three observed changes. | +| `apiGroups` | Explicit API groups; use `""` for core resources. | +| `apiVersions` | Explicit versions, such as `v1`. | +| `resources` | Explicit plural resource names, such as `configmaps`. Wildcards and subresource paths are unsupported. | +| `scope` | Optional; only `Namespaced` is accepted. Cluster-scoped resources cannot be watched by triggers. | +| `namespaceSelector` | Source namespace label selector; GlobalTenantResources only. | +| `objectSelector` | Label selector with `matchLabels` and `matchExpressions`; a match on either observed object qualifies. | +| `matchConditions` | Named boolean CEL expressions. All conditions in one trigger must match. Any matching trigger can notify the replication. | + +Groups, versions, and resources form explicit combinations, with at most 16 +combinations per trigger and eight entries per field. There are at most 32 +triggers per replication and 60 conditions per trigger. Expressions are limited to +4096 bytes and have a runtime cost limit. Capsule validates expressions in its replication controllers and prepares immutable +programs when subscriptions change. An invalid specification reports `Ready=False` +with its error and current `observedGeneration`; correcting it lets reconciliation +resume. Validation results are reused for the unchanged resource generation, +including valid subscriptions omitted by preparation limits. Invalid specifications +do not schedule fast application retries. Trigger validation does not depend on +a policy-conversion webhook. + +Only watchable top-level resources are supported. For example, a write through +`deployments/scale` can appear as an UPDATE of the watched Deployment, but watches +do not identify which subresource or API operation caused that change. An explicit +API version selects that version's watch; there is no admission equivalent-version +matching contract. + +#### CEL inputs + +Conditions can use: + +| Variable | Value | +| --- | --- | +| `object` | The current observed object; null on DELETE. | +| `oldObject` | The previous observed object; null on CREATE. | +| `operation` | `CREATE`, `UPDATE`, or `DELETE`. | + +Conditions describe observed state changes. They are not admission conditions. +Watches do not include the requesting user, groups, impersonation information, or +an admission `request` or `authorizer` value. The API schema rejects nonempty `audience` fields. CEL expressions using +admission-only variables produce a validation error in replication status. The shared +[audience model](/docs/operating/concepts/audiences/) remains available for namespace +rules. + +Condition errors skip that trigger. Another matching trigger can still notify +the same replication. Namespace and resource selectors must also qualify. + +### Managed resources and bookkeeping + +Capsule-managed resources, including objects adopted or co-managed by +TenantResources or GlobalTenantResources, never trigger reconciliation. The filter +checks both observed states, management metadata, Capsule owner references, and +replication field managers. Removing a management marker does not make that +particular update eligible. The legacy `capsule.clastix.io/managed-by` assignment +label is not a management marker; tenants named `controller`, `resources`, and +`replications` remain eligible. + +A watch can observe a new UID under an existing name after a relist. Capsule +treats this as DELETE for the previous object and CREATE for its replacement. +Selectors and management checks apply independently to each object. + +Watches have no writer identity. To avoid feedback when a TenantResource watches +its own kind, Capsule ignores parent status, finalizer, and internal +reconciliation-token changes. Spec, label, non-Capsule owner-reference, and other +annotation changes remain eligible, including transitions that set +`deletionTimestamp`. Ownership changes remain subject to the managed-resource +exclusion above. Ordinary spec changes +already reconcile through the resource controller. + +### Scheduling and recovery + +`spec.triggerMinInterval` is shared across the triggers on one replication. Its +default is `10s`, with values from `1s` to `24h`. + +The elected replica shares watch streams by resource/version, namespace scope, and +replication execution identity. A GlobalTenantResource can require a cluster-wide +stream; a TenantResource uses its own namespace. Streams belonging to different +execution identities are independent. A global impersonated stream does not +replace a local stream that may have different namespace-scoped permissions. +It queues matching targets through the existing asynchronous notification +mechanism. A short 250 ms window coalesces bursts; the first event does not wait +for the full interval. Events during a cooldown remain pending for a later +reconcile and do not continually postpone it. Shortening the interval shortens an +existing queued cooldown. Persisted attempt timing preserves the interval across +leadership changes. + +Dependency, namespace, tenant and configuration changes, spec edits, deletion, +manual requests, and periodic resyncs retain their existing paths. Failed resource +reconciliation does not acknowledge the outstanding notification and retries at +a bounded interval. + +Triggers are **best effort**. Initial paginated lists establish a baseline without +replaying every existing object as a CREATE. Changes during initial +synchronization, disconnection, leader replacement, or saturation can be missed or +coalesced. A relist restores the observed state, not a complete audit history. +Keep `resyncPeriod` as the recovery mechanism. A replication's Ready condition +reports resource application and, when enabled, [health checks](#health-checks). +It does not assert watch synchronization. + +The notification queue is bounded to 4096 targets. The watch event queue is bounded +to 256 events and 8 MiB of accounted object memory, including in-flight work, +with two workers and a 100 ms processing deadline per event. Excess +or expired work is skipped and periodic reconciliation provides recovery. Up to +64 watch streams across all resource/version and namespace combinations, +4096 prepared replications, 8192 condition references, and validation results for +up to 4096 additional replication generations are retained per leader. Prepared +subscriptions supply their own validation result. Results contain no source data +or condition programs and are retired on preparation, deletion, or a newer generation. +Beyond the validation-result bound, omitted subscriptions still validate on each +reconcile; periodic resource application remains active. +Preparation and stream opportunities are shared round-robin by the owning Tenant. +GlobalTenantResources and resources outside Tenant namespaces share a separate +system group. Namespace ownership uses Tenant owner-reference UID checks. When +all tenants cannot fit, priority rotates on the 30-second planning refresh; +ordinary events do not continually replace healthy streams. Multiple identities +or large subscriptions in one tenant cannot reserve every opportunity ahead of +another tenant. The limits apply to planning candidates, so invalid resources or +forbidden LIST/WATCH requests cannot force unbounded discovery or stream initialization. +Within a tenant, sources and stream candidates retain deterministic ordering. + +Valid subscriptions omitted by discovery or capacity limits are reported in logs +and metrics and rely on periodic reconciliation. Invalid trigger specifications +report `Ready=False` and stop replication until corrected. + +### Watch permissions and performance + +Source LIST/WATCH requests run under the same execution identity as replication: +`spec.serviceAccount`, the configured default ServiceAccount, or the controller +identity when impersonation is explicitly not configured. That identity needs +`list` and `watch` access to the selected resource and namespace scope. A global +stream requires cluster-wide access; a local stream needs access only within its +namespace scope. A `get` alone cannot establish a watch. + +Object selectors and CEL only receive objects read by that execution identity. +A privileged stream or a stream for another ServiceAccount cannot supply data to an +unprivileged subscription, including through observable trigger tokens. Identity +or impersonation-transport changes retire the old streams and exclude stale +queued events. Each stream uses the endpoint and TLS settings captured for its +execution identity throughout its lifetime. Missing permissions and client-construction errors retry without +falling back to controller credentials. Replication Ready reports application +and validation status; it does not assert that source watches are authorized. +Kubernetes authorizes LIST/WATCH requests using its normal watch semantics. +The controller still reads subscription and namespace metadata for selection. +These background failures cannot block Kubernetes writes. + +Capsule checks the selected CA bundle during its 30-second watch-planning refresh. +Updating the referenced Secret's CA data replaces affected streams; unrelated +metadata or data keys do not restart them. A missing Secret or CA key stops those +streams until it is restored. An explicitly configured CA Secret with empty CA +data also stops affected watches; it cannot fall back to system trust. Explicit +`skipTLSVerify` retains its configured behavior. Trust rotation does not require +editing the replication or CapsuleConfiguration. Cached impersonated replication +clients also check the current transport and CA contents on each load, so template +reads and resource applies recover with the source watch. A changed trust snapshot +replaces the cached client for that ServiceAccount; it does not reuse the older transport +or fall back to the controller identity. + +Each stream retains at most 1024 object snapshots and 1 MiB of accounted memory. +Across 64 streams, the snapshot budget is at most 64 MiB. Accounting includes +strings, maps, slices, metadata, and bookkeeping; it is not the serialized object +size or an exact measure of process memory. Objects whose accounted size exceeds +512 KiB are skipped. Streams never share object contents across execution identities. + +Capsule consumes LIST responses a page at a time, with at most two pages being +decoded concurrently. Pages request 32 objects; responses exceeding 4 MiB retry +with smaller pages. Each page has a 15-second deadline. A baseline stops after +2048 objects, 4 MiB of accounted objects, or 64 pages and then watches from that +snapshot's resource version. It does not accumulate the entire resource collection. + +An UPDATE without a retained previous snapshot is skipped and warms that object's +snapshot for a later change. Capsule does not invent a CREATE or set `oldObject` +to null for that UPDATE. A partial relist cannot infer deletions outside its +baseline. Keep `resyncPeriod` short enough to recover changes to cold or oversized +inputs, including objects that change only once between evictions. Resource +application and template reads still run periodically for those inputs. + +Share resource types between subscriptions and avoid watching noisy types unless +their changes are needed. Matching uses indexed subscription lookups and prepared +selectors/programs rather than scanning all replications or compiling conditions +for every event. + +There is no trigger admission webhook, delivery endpoint, or signing Secret. +Dry-run and rejected writes do not persist changes and therefore produce no watch +notification. Existing Capsule admission checks, including managed-resource +protection, retain their behavior. + +### Observe triggers + +The `projectcapsule.dev/replication-trigger` annotation identifies queued internal +work. The API status records: + +- `status.trigger.lastTriggeredAt`: start of the last triggered attempt. +- `status.trigger.observedRequest`: last notification handled by a completed + attempt. A notification arriving during reconciliation is not acknowledged by + the older attempt. +- `status.nextResyncAt`: earliest outstanding periodic recovery deadline; a trigger + does not postpone it. + +The existing Ready condition and processed-item status report application errors. +Metrics use bounded labels: + +- `capsule_replication_trigger_notifications_total`: `queued`, `saturated`, `retry`. +- `capsule_replication_trigger_watches`: active watch streams on this replica, + including streams still initializing or retrying. +- `capsule_replication_trigger_watches_omitted`: subscriptions or resources omitted + by validation, discovery, or capacity limits. +- `capsule_replication_trigger_events_total`: `queued`, `dropped`, `watch-error`, + `condition-error`, `unprepared`, `timed-out`, `baseline-limited`, + `object-too-large`, and `old-object-unavailable`. +- `capsule_replication_trigger_snapshot_bytes`: accounted snapshot memory. +- `capsule_replication_trigger_queued_bytes`: accounted memory in queued and + processing events. + +## Health checks + +[TenantResources](/docs/replications/tenant/) and +[GlobalTenantResources](/docs/replications/global/) can wait for their applied +resources to become healthy. Set `spec.healthChecks.wait: true` to require both +successful application and successful health checks across all selected +destinations before reporting `Ready=True`. + +With `healthChecks` omitted or `healthChecks.wait` false, readiness keeps its +existing meaning: resources were successfully applied. Capsule performs no +health-check reads in this mode. +Namespace and tenant selectors continue to determine where resources are applied. + +### Enable health checks + +This TenantResource creates a Deployment in each namespace of its tenant labelled +`projectcapsule.dev/profile: application`, then waits for the rollouts to complete: + +```yaml +apiVersion: capsule.clastix.io/v1beta2 +kind: TenantResource +metadata: + name: health-example + namespace: wind-system +spec: + serviceAccount: + name: tenant-replicator + healthChecks: + wait: true + timeout: 5m + resyncPeriod: 10m + resources: + - namespaceSelector: + matchLabels: + projectcapsule.dev/profile: application + rawItems: + - apiVersion: apps/v1 + kind: Deployment + metadata: + name: health-example + spec: + replicas: 1 + selector: + matchLabels: + projectcapsule.dev/app: health-example + template: + metadata: + labels: + projectcapsule.dev/app: health-example + spec: + containers: + - name: workload + image: registry.k8s.io/pause:3.10.1 +``` + +The tenant, source namespace and ServiceAccount must already exist. Grant the +ServiceAccount the existing replication permissions and the target read access +described under [Health-check permissions](#health-check-permissions). + +The same `healthChecks` block works on a GlobalTenantResource. Keep its `scope`, +`tenantSelector` and resource namespace selectors configured for the intended +destinations. An explicit `serviceAccount` +reference on a GlobalTenantResource includes both its name and namespace. + +| Field | Behavior | +| --- | --- | +| `healthChecks.wait` | Defaults to `false`. When `true`, checks all successfully applied targets before reporting readiness. | +| `healthChecks.timeout` | Time allowed for an incomplete health assessment. Defaults to `5m`; must be positive and at most `1h`. | +| `healthChecks.expressions` | Optional custom CEL checks for specific API groups and kinds. Requires `healthChecks.wait: true`; ignored when waiting is disabled. | + +Capsule finishes applying and pruning the selected resources before starting the +health phase. It uses Flux's kstatus evaluation for kinds without a custom check. +This includes rollout checks for supported workloads such as Deployments. +Resources without a recognized readiness signal can be considered current as +soon as they exist. Define a custom check when a resource's own controller exposes +readiness differently. + +Only targets successfully applied by this replication participate. Objects skipped +by a resource block's conditional-apply policy do not introduce a health check for +that skipped application. If no targets are selected, a successful application +has no health checks to wait for. + +### Custom health expressions + +Use `healthChecks.expressions` to define readiness for a custom resource. For +example, suppose a `Workload` custom resource reports `Pending`, `Progressing`, `Failed` or +`Ready` in `status.phase`: + +```yaml +spec: + healthChecks: + wait: true + timeout: 3m + expressions: + - apiVersion: workloads.projectcapsule.dev/v1 + kind: Workload + inProgress: >- + !has(object.status) || !has(object.status.phase) || + object.status.phase in ['Pending', 'Progressing'] + failed: >- + has(object.status) && has(object.status.phase) && + object.status.phase == 'Failed' + current: >- + has(object.status) && has(object.status.phase) && + object.status.phase == 'Ready' +``` + +Each entry replaces the default check for that API **group and kind**. The version +in `apiVersion` is ignored when matching targets, so the example also matches +other served versions of the same Workload kind. Duplicate entries for the same +group and kind are rejected. Use `apiVersion: v1` for a core API kind. + +Checks run in this order, stopping at the first expression that returns `true`: + +1. `inProgress`: the target is still progressing. +2. `failed`: the target has failed. +3. `current`: the target is healthy. + +`current` is required; `inProgress` and `failed` are optional. If none returns +`true`, the target remains in progress. All expressions must return a boolean. +There can be at most 32 entries, with at most 4096 characters per expression. +Invalid expressions report an application error before any resources are applied. + +Expressions receive the persisted target object: + +| Variable | Value | +| --- | --- | +| `object` | The complete target object. | +| `apiVersion`, `kind`, `metadata`, `spec`, `status` | Aliases for the corresponding top-level target fields, when present. | + +Admission request variables, users, audiences, `oldObject`, `operation` and +`authorizer` are unavailable. Guard optional fields with `has(object.status)` and +similar checks: a missing field can otherwise cause an evaluation error. +Evaluation errors keep the replication unready and are retried until the target +recovers or the health timeout is reported. + +Capsule also checks that each target still has the applied UID and generation. +When present, `status.observedGeneration` and a successful Ready condition's +`observedGeneration` must match the target generation. A custom expression cannot +make an older rollout satisfy these checks. + +### Readiness, timeouts and dependencies + +With waiting enabled, inspect the `Healthy` and `Ready` conditions: + +| Healthy condition | Meaning | +| --- | --- | +| `Unknown`, reason `HealthChecking` | Applied targets are still progressing or the current scan is incomplete. | +| `Unknown`, reason `HealthCheckError` | The health execution client or check preparation failed. The message identifies the error. | +| `True`, reason `Succeeded` | All applied targets are healthy; the replication can report `Ready=True`. | +| `False`, reason `HealthCheckFailed` | A target reported a failed state. | +| `False`, reason `HealthCheckTimeout` | Targets have not become healthy before the deadline. | + +`Ready` remains false while application fails, health is pending, or health fails. +An application error can also leave `Healthy=Unknown` with reason +`ApplicationIncomplete`. Conditions report their `observedGeneration`; after +editing a replication, compare this with `metadata.generation` before relying on +readiness from a previous revision. + +```bash +kubectl get tenantresource health-example -n wind-system -o yaml +kubectl wait tenantresource/health-example -n wind-system \ + --for=condition=Ready --timeout=6m +``` + +For a GlobalTenantResource, use `globaltenantresource` and omit the `-n` flag. +`kubectl wait` tests the condition currently stored on the object; check generation +freshness separately when waiting immediately after an update. + +The timeout starts after a successful application. Its deadline is stored in +`status.health`, so retries, controller restarts and leader changes retain it. +An unchanged application while health is pending does not extend the deadline. +A new source generation, changed applied content or changed target identity +starts a new assessment. A completed healthy assessment can also be checked again +after a subsequent application. + +Failures and timeouts do not roll back or delete successfully applied resources. +Capsule continues health checks and can recover to `Healthy=True` without applying +the resources again. Once all targets are healthy, polling stops until another +application requests an assessment. Use `resyncPeriod` and +[resource watches](/docs/replications/#resource-watches) to control further applications. + +Existing `dependsOn` references honor the dependency's readiness. If a dependency +uses `healthChecks.wait: true`, dependents wait for its successful application +and health checks for the current source generation. Dependencies that do not enable waiting keep +their existing apply-only readiness behavior. + +### Health-check metrics + +The replication controller exposes the `Healthy` condition through the existing +condition gauges: + +```promql +capsule_resource_condition{condition="Healthy",name="health-example",target_namespace="wind-system"} 1 +capsule_global_resource_condition{condition="Healthy",name="health-example-global"} 1 +``` + +The value is `1` for `Healthy=True` and `0` for `False` or `Unknown`, including +failed checks, timeouts and checks still in progress. Inspect the object's +conditions to distinguish those states and read their reasons. For TenantResources, +`target_namespace` identifies the namespace containing the TenantResource. + +The series is absent when there is no Healthy condition. Disabling +`healthChecks.wait` removes it after reconciliation; deleting the replication +removes all its condition +series. Other replications keep their own metrics. + +Scrape these gauges from the replication controller's metrics endpoint. Health-only +observations update them after publishing status, without waiting for the next +resource application. `Ready` and `Cordoned` keep their existing metric names and +labels. Existing alerts on `Ready` also reflect health failures when waiting is +enabled. + +The chart's default Prometheus rule list includes +`CapsuleGlobalTenantResourceNotHealthy` and `CapsuleTenantResourceNotHealthy`. +Each raises a warning when its `Healthy` gauge remains `0` for ten minutes. +Healthy resources and replications without a Healthy condition do not match. +Because `False` and `Unknown` both map to `0`, prolonged pending checks also match; +adjust the rule's `for` duration if normal rollouts can take longer. + +With the Prometheus Operator installed, enable the existing chart settings to +scrape both controller workloads and install the default alert rules: + +```yaml +monitoring: + serviceMonitor: + enabled: true + prometheusRules: + enabled: true +``` + +### Health-check permissions + +Health checks read targets using the **same execution identity as replication**: +the explicit `spec.serviceAccount`, the configured default ServiceAccount, or the +controller identity when impersonation is not configured. See the +[TenantResource](/docs/replications/tenant/#impersonation) and +[GlobalTenantResource](/docs/replications/global/#impersonation) impersonation +settings. + +Review existing Roles and ClusterRoles before enabling health checks or resource +watches. These features need different read verbs: + +| Operation | Permission on the execution ServiceAccount | +| --- | --- | +| Health checks | `get` on every applied target's main resource, in every destination namespace or cluster scope where it is applied. | +| Resource-watch triggers | `list` and `watch` on the selected source resource and namespace scope; see [watch permissions](/docs/replications/#watch-permissions-and-performance). | +| Replication and template reads | Existing apply, cleanup and input-read permissions still apply; health checks do not replace them. | + +A normal `get` returns the object's status too. Health checks do not require +`get` on `deployments/status`, permission to update status, or additional +`list`/`watch` permissions. If the ServiceAccount already has `get` on every target, +health checks require no new verb. Resource watches may still require adding +`list` and `watch` to existing read permissions. + +For example, this **additional read-only grant** lets the example's existing +`wind-system/tenant-replicator` ServiceAccount check its Deployment in `wind-test`: + +```yaml +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: replication-health-reader + namespace: wind-test +rules: + - apiGroups: [apps] + resources: [deployments] + resourceNames: [health-example] + verbs: [get] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: replication-health-reader + namespace: wind-test +subjects: + - kind: ServiceAccount + name: tenant-replicator + namespace: wind-system +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: replication-health-reader +``` + +This supplements the permissions needed to create, apply and clean up the +Deployment. Grant the corresponding read access in every selected destination. +For multiple namespaces, a reusable ClusterRole with a RoleBinding in each +destination can keep the grant scoped. Cluster-scoped targets need an appropriate +ClusterRoleBinding. + +An administrator allowed to impersonate the ServiceAccount can verify the grant: + +```bash +kubectl auth can-i get deployments.apps/health-example -n wind-test \ + --as=system:serviceaccount:wind-system:tenant-replicator +``` + +Missing read access leaves the replication unready; the health condition reports +the permission error and eventually the timeout if access is not restored. +Capsule retries with the same identity and does not fall back to controller +credentials. The `status.serviceAccount` field identifies the execution account. + +### Scheduling and scale + +Health checks run in the background replication controller, with a queue separate +from resource application. Pending checks normally poll every five seconds in +batches of at most 64 target reads. Larger inventories continue across batches. +Choose a timeout that covers both rollout time and the time needed to observe +all selected targets under your API-server limits. + +Health retries do not render templates or apply resources, and +`triggerMinInterval` does not delay them. These checks do not introduce an admission +webhook or block Kubernetes writes. Existing managed-resource protection remains +in effect. + ## Per-resource policies Each `spec.resources[]` block accepts a resource policy in both replication APIs. diff --git a/content/en/docs/replications/global.md b/content/en/docs/replications/global.md index 92fd957..e58268a 100644 --- a/content/en/docs/replications/global.md +++ b/content/en/docs/replications/global.md @@ -5,6 +5,11 @@ description: > Replicate resources across tenants or namespaces as Cluster Administrator. --- +Use [resource watches](/docs/replications/#resource-watches) to reconcile source changes +between periodic resyncs. +Enable [health checks](/docs/replications/#health-checks) to wait for applied +resources to become healthy before reporting readiness. + ## Overview `GlobalTenantResource` is a cluster-scoped CRD designed for cluster administrators. It lets you automatically replicate Kubernetes resources - such as Secrets, ConfigMaps, or custom resources - into the Namespaces of selected Tenants. Tenant owners cannot create `GlobalTenantResource` objects; for tenant-scoped replication, see [TenantResource](/docs/replications/tenant/). @@ -608,7 +613,7 @@ missing-key 6 False error running generator: template: tpl:8:7: execut #### Period -`GlobalTenantResources` reconcile on the interval defined by `resyncPeriod`. The default is `60s`. Capsule does not watch source resources for changes; it reconciles periodically. A very short interval on large clusters with many Tenants and Namespaces can cause performance issues - tune this value accordingly. +`GlobalTenantResources` reconcile on the interval defined by `resyncPeriod`. The default is `60s`. Optional [resource watches](/docs/replications/#resource-watches) can request earlier reconciliation when selected source resources change. A very short interval on large clusters with many Tenants and Namespaces can cause performance issues - tune this value accordingly. ```yaml apiVersion: capsule.clastix.io/v1beta2 @@ -627,6 +632,16 @@ spec: tenant: renewable ``` +#### Health checks + +Set `spec.healthChecks.wait: true` to require healthy applied resources before `Ready=True`. +`spec.healthChecks.timeout` sets the deadline, and `spec.healthChecks.expressions` can define +custom CEL checks. Waiting is disabled by default. + +See [Health checks](/docs/replications/#health-checks) for examples, readiness and +dependency behavior, and the target read permissions required by the execution +ServiceAccount. + #### Manual To trigger an immediate reconciliation, add the `reconcile.projectcapsule.dev/requestedAt` annotation. The annotation is removed once reconciliation completes, making the process repeatable. @@ -760,13 +775,17 @@ roleRef: The following permissions are required for each resource type managed by the replication feature: - * `get` (always required) + * `get` (always required, including reads of targets for health checks) * `create` (always required) * `patch` (always required) * `delete` (always required) - * `list` (required for [Namespaced Items](#namespaceditems) and [Context](#context)) + * `list` (required for [Namespaced Items](#namespaceditems), [Context](#context), and resource-watch sources) + * `watch` (required for [resource-watch sources](/docs/replications/#watch-permissions-and-performance)) -Missing any of these will cause replication to fail. +Grant the verbs needed by the operations you enable. Health checks reuse `get` on +every target resource; source watches need both `list` and `watch`. See +[health-check permissions](/docs/replications/#health-check-permissions) for a +scoped target-read example and guidance on status reads. #### Default ServiceAccount @@ -1367,13 +1386,17 @@ namespace: ### Monitoring -Currently mainly the conditions of `GlobalTenantResources` are exposed as metrics: +The conditions of `GlobalTenantResources` are exposed as gauges. With health checks enabled, +`Healthy` is exported alongside `Ready` and `Cordoned`. See +[health-check metrics](/docs/replications/#health-check-metrics) for values and +lifecycle behavior: ``` # HELP capsule_global_resource_condition The current condition status of a global tenant resource. # TYPE capsule_global_resource_condition gauge capsule_global_resource_condition{condition="Cordoned",name="templated-forbidden-namespace"} 0 capsule_global_resource_condition{condition="Ready",name="templated-forbidden-namespace"} 1 +capsule_global_resource_condition{condition="Healthy",name="templated-forbidden-namespace"} 1 ``` ## Examples diff --git a/content/en/docs/replications/tenant.md b/content/en/docs/replications/tenant.md index fb2222e..2274841 100644 --- a/content/en/docs/replications/tenant.md +++ b/content/en/docs/replications/tenant.md @@ -5,6 +5,11 @@ description: > Replicate resources across a Tenant's Namespaces as Tenant Owner --- +Use [resource watches](/docs/replications/#resource-watches) to reconcile source changes +between periodic resyncs. +Enable [health checks](/docs/replications/#health-checks) to wait for applied +resources to become healthy before reporting readiness. + ## Overview `TenantResource` is a namespace-scoped CRD that lets Tenant owners automatically replicate Kubernetes resources across all Namespaces in their Tenant - without manual distribution or custom automation. It is the tenant-level counterpart to [GlobalTenantResource](/docs/replications/global/), which is reserved for cluster administrators. @@ -632,7 +637,7 @@ missing-key 6 False error running generator: template: tpl:7:13: execu #### Period -`TenantResources` reconcile on the interval defined by `resyncPeriod`. The default is `60s`. Capsule does not watch source resources for changes; it reconciles periodically. A very short interval on large clusters with many Tenants and Namespaces can cause performance issues - tune this value accordingly. +`TenantResources` reconcile on the interval defined by `resyncPeriod`. The default is `60s`. Optional [resource watches](/docs/replications/#resource-watches) can request earlier reconciliation when selected source resources change. A very short interval on large clusters with many Tenants and Namespaces can cause performance issues - tune this value accordingly. ```yaml apiVersion: capsule.clastix.io/v1beta2 @@ -652,6 +657,16 @@ spec: tenant: renewable ``` +#### Health checks + +Set `spec.healthChecks.wait: true` to require healthy applied resources before `Ready=True`. +`spec.healthChecks.timeout` sets the deadline, and `spec.healthChecks.expressions` can define +custom CEL checks. Waiting is disabled by default. + +See [Health checks](/docs/replications/#health-checks) for examples, readiness and +dependency behavior, and the target read permissions required by the execution +ServiceAccount. + #### Manual To trigger an immediate reconciliation, add the `reconcile.projectcapsule.dev/requestedAt` annotation. The annotation is removed once reconciliation completes, making the process repeatable. @@ -750,13 +765,17 @@ spec: The following permissions are required for each resource type managed by the replication feature: - * `get` (always required) + * `get` (always required, including reads of targets for health checks) * `create` (always required) * `patch` (always required) * `delete` (always required) - * `list` (required for [Namespaced Items](#namespaceditems) and [Context](#context)) + * `list` (required for [Namespaced Items](#namespaceditems), [Context](#context), and resource-watch sources) + * `watch` (required for [resource-watch sources](/docs/replications/#watch-permissions-and-performance)) -Missing any of these will cause replication to fail. +Grant the verbs needed by the operations you enable. Health checks reuse `get` on +every target resource; source watches need both `list` and `watch`. See +[health-check permissions](/docs/replications/#health-check-permissions) for a +scoped target-read example and guidance on status reads. #### Default ServiceAccount @@ -1208,11 +1227,15 @@ namespace: ### Monitoring -Currently mainly the conditions of `TenantResources` are exposed as metrics: +The conditions of `TenantResources` are exposed as gauges. With health checks enabled, +`Healthy` is exported alongside `Ready` and `Cordoned`. See +[health-check metrics](/docs/replications/#health-check-metrics) for values and +lifecycle behavior: ``` # HELP capsule_resource_condition The current condition status of a tenant resource. # TYPE capsule_resource_condition gauge capsule_resource_condition{condition="Cordoned",name="templated-forbidden-namespace",target_namespace="e2e-tenantresource-ssa-system"} 0 capsule_resource_condition{condition="Ready",name="templated-forbidden-namespace",target_namespace="e2e-tenantresource-ssa-system"} 1 +capsule_resource_condition{condition="Healthy",name="templated-forbidden-namespace",target_namespace="e2e-tenantresource-ssa-system"} 1 ``` diff --git a/content/en/docs/rules/_index.md b/content/en/docs/rules/_index.md index 9e645e8..a877de6 100644 --- a/content/en/docs/rules/_index.md +++ b/content/en/docs/rules/_index.md @@ -29,7 +29,7 @@ subject. A Tenant rule's `namespaceSelector` selects its namespaces; omitting it selects all namespaces in that Tenant. Matching Tenant rules retain their declaration order in the namespace's effective RuleStatus, including rules containing only -`mutate`. Tenant/Namespace templating and [audience](#audience) filtering apply +`mutate`. Tenant/Namespace templating and [audience](/docs/operating/concepts/audiences/) filtering apply to both mutation and enforcement. ### Admission order @@ -98,9 +98,9 @@ can narrow a policy's scope but cannot expand its supported operations. ## Audience -Use `audience` to restrict a rule to requests made by specific users, groups, -service accounts, or Capsule-defined subject categories. The property belongs to -the root of a rule, alongside `mutate` and `enforce`: +Use the shared [audience model](/docs/operating/concepts/audiences/) to select the +request identities to which a rule applies. The property belongs to the root of +a rule, alongside `mutate` and `enforce`: ```yaml spec: @@ -120,148 +120,15 @@ spec: - exp: "^INV-[0-9]{4}$" ``` -When `audience` is omitted or empty, the rule applies to every request selected -by the rule. +Audience filtering applies to both mutation and enforcement. A subject excluded +from a rule is neither mutated nor validated by that rule; other applicable +rules still apply. Namespace selection continues to determine where the rule is +available. -When an audience is configured, the rule applies if the requesting subject -matches **at least one** entry. In other words, entries are combined with logical -OR semantics. Audience matching is performed consistently for both validation -and mutation, so a subject excluded from a rule is neither validated nor mutated -by that rule. - -Audience filtering uses the actual identity on the Pod admission request. Pods -created by a workload controller are normally submitted by that controller's -service account, not by the user who originally created the Deployment or Job. -Account for that distinction when combining `audience` with mutation or enforcement. - -The supported standard audience kinds are `User`, `Group`, and -`ServiceAccount`: - -```yaml -spec: - rules: - - audience: - # Match one exact Kubernetes username. - - kind: User - name: alice@example.com - - # Match any request carrying this group. - - kind: Group - name: oidc:engineering - - # Match one Kubernetes service account. - - kind: ServiceAccount - name: system:serviceaccount:delivery:deployer - enforce: - action: deny - metadata: - - apiGroups: - - v1 - kinds: - - Namespace - labels: - pod-security.kubernetes.io/enforce: - managed: restricted -``` - -For `User`, `Group`, and `ServiceAccount`, `name` is compared with the identity -information provided in the Kubernetes admission request. A service account is -represented by its canonical Kubernetes username: - -```text -system:serviceaccount:: -``` - -For example, a request from the `deployer` service account in the `delivery` -namespace has the username -`system:serviceaccount:delivery:deployer`. - -### Custom - -The `Custom` kind exposes audiences based on Capsule's internal identity and -tenant resolution. Its `name` must be one of the supported values below. - -| **name** | **description** | -|:---|:---| -| `CapsuleUser` | Matches subjects listed by `configuration.Users()`. | -| `Administrator` | Matches subjects listed by `configuration.Administrators()`. | -| `TenantOwner` | Matches an owner of the tenant resolved for the current request. A request cannot match when no tenant can be resolved. | -| `Controller` | Matches the service account used by the Capsule controller. | - -Custom audiences can be combined with standard audiences. The following rule -applies to Capsule users, Capsule administrators, tenant owners, the Capsule -controller, or members of the Kubernetes `system:masters` group: - -```yaml -spec: - rules: - - audience: - - kind: Custom - name: CapsuleUser - - kind: Custom - name: Administrator - - kind: Custom - name: TenantOwner - - kind: Custom - name: Controller - - kind: Group - name: system:masters - enforce: - action: allow - metadata: - - apiGroups: - - v1 - kinds: - - Namespace - annotations: - example.corp/cost-center: - default: II-1 -``` - -`TenantOwner` is request-scoped. Capsule first resolves the tenant associated -with the admission request and then checks the requesting subject against that -tenant's owners. This makes it suitable for rules that should affect tenant -owners but not unrelated Capsule users: - -```yaml -spec: - rules: - - audience: - - kind: Custom - name: TenantOwner - enforce: - action: allow - metadata: - - kinds: - - ConfigMap - labels: - owner-managed: - default: "true" -``` - -`Controller` specifically identifies the Capsule controller service account. It -is useful when internal reconciliation requests need different policy behavior -from requests made by ordinary users: - -```yaml -spec: - rules: - - audience: - - kind: Custom - name: Controller - enforce: - action: allow - metadata: - - kinds: - - Secret - labels: - capsule.clastix.io/reconciled: - managed: "true" -``` - -Unknown audience kinds and unsupported `Custom` names are rejected when the -rule is admitted. This catches spelling mistakes and prevents a rule from being -silently configured with an audience that can never match. +See [Audiences](/docs/operating/concepts/audiences/) for standard and custom kinds, +OR matching, and tenant context. For controller-created Pods, account for the +[identity on the admission request](/docs/operating/concepts/audiences/#request-identity) +when choosing an audience. ## Match expressions @@ -344,7 +211,7 @@ Check absent fields with `has(...)` and map membership with `in`. The [missing-value example](#set-a-value-only-when-it-is-missing) demonstrates both. The Pod node selector is at `object.spec.nodeSelector`; it is not a container property. Use `request.userInfo` for request identity, while keeping existing -[audience](#audience) settings for straightforward subject selection. +[audience](/docs/operating/concepts/audiences/) settings for straightforward subject selection. ### Evaluation diff --git a/content/en/docs/rules/enforcement/_index.md b/content/en/docs/rules/enforcement/_index.md index 5003155..bbbe32c 100644 --- a/content/en/docs/rules/enforcement/_index.md +++ b/content/en/docs/rules/enforcement/_index.md @@ -16,8 +16,8 @@ limits**. Policy sections explain configuration and examples. The final See [Order and scope](/docs/rules/#order-and-scope) for how mutation precedes enforcement, and [Conditions](/docs/rules/#enforcement-conditions) for conditional enforcement. -[Audience](/docs/rules/#audience) and [match expressions](/docs/rules/#match-expressions) -are documented under Rules. +See [Audiences](/docs/operating/concepts/audiences/) for request identity matching +and [match expressions](/docs/rules/#match-expressions) for value matching. ## Rule Composition @@ -141,7 +141,7 @@ When audit rules are used together with allow rules, the matching value must sti ### Admission scope and limits Enforcement runs during admission for resources in the namespaces selected by -the rule. [Audience](/docs/rules/#audience) filters the caller, and +the rule. [Audience](/docs/operating/concepts/audiences/) filters the caller, and [conditions](/docs/rules/#enforcement-conditions) decide whether an enforcement block participates. Each policy chapter lists its supported resources, operations, subresources, and handling of missing values. diff --git a/content/en/docs/rules/enforcement/metadata.md b/content/en/docs/rules/enforcement/metadata.md index 3ef72af..4b33938 100644 --- a/content/en/docs/rules/enforcement/metadata.md +++ b/content/en/docs/rules/enforcement/metadata.md @@ -12,7 +12,7 @@ values, required keys, and value validation. [Migration](#migration) covers the legacy Namespace, Pod, and Service metadata options. Rules use the shared [namespace selection](/docs/tenants/rules/), -[audiences](/docs/rules/#audience), +[audiences](/docs/operating/concepts/audiences/), [conditions](/docs/rules/#enforcement-conditions), and [actions and order](/docs/rules/enforcement/#action). See [Reference](#reference) for a complete Tenant example. diff --git a/content/en/docs/rules/enforcement/network.md b/content/en/docs/rules/enforcement/network.md index 778dfc5..a448f24 100644 --- a/content/en/docs/rules/enforcement/network.md +++ b/content/en/docs/rules/enforcement/network.md @@ -21,7 +21,7 @@ and hostnames and class references on ingress resources. [Reference](#reference) Tenant example for each policy group. Rules use the shared [namespace selection](/docs/tenants/rules/), -[audiences](/docs/rules/#audience), +[audiences](/docs/operating/concepts/audiences/), [conditions](/docs/rules/#enforcement-conditions), and [actions and order](/docs/rules/enforcement/#action). @@ -2242,4 +2242,3 @@ Each routing, TLS, or listener hostname is checked independently: Every hostname on a resource must pass. For example, an Ingress with an allowed routing host and a disallowed TLS host is denied. If you narrow the `types` lists, omitted resource kinds remain unaffected by these rules. - diff --git a/content/en/docs/rules/enforcement/storage.md b/content/en/docs/rules/enforcement/storage.md index 406a120..b781c66 100644 --- a/content/en/docs/rules/enforcement/storage.md +++ b/content/en/docs/rules/enforcement/storage.md @@ -10,7 +10,7 @@ Storage enforcement is configured under `spec.rules[].enforce.storage`. [additional volume access](#volumes) for PVs without a Tenant label. Rules use the shared [namespace selection](/docs/tenants/rules/), -[audiences](/docs/rules/#audience), +[audiences](/docs/operating/concepts/audiences/), [conditions](/docs/rules/#enforcement-conditions), and [actions and order](/docs/rules/enforcement/#action). See [Reference](#reference) for a complete Tenant example. diff --git a/content/en/docs/rules/enforcement/workloads.md b/content/en/docs/rules/enforcement/workloads.md index ab483a0..b78a0c1 100644 --- a/content/en/docs/rules/enforcement/workloads.md +++ b/content/en/docs/rules/enforcement/workloads.md @@ -15,7 +15,7 @@ policies are present, targets scope those policies: [resource management](#resou [PodDisruptionBudgets](#pod-disruption-budgets). Rules use the shared [namespace selection](/docs/tenants/rules/), -[audiences](/docs/rules/#audience), +[audiences](/docs/operating/concepts/audiences/), [conditions](/docs/rules/#enforcement-conditions), and [actions and order](/docs/rules/enforcement/#action). See [Reference](#reference) for a complete Tenant example. @@ -66,7 +66,7 @@ each policy takes effect. A controller write and the Pods it later creates are separate admissions, often with different callers. Include the required targets and -[audiences](/docs/rules/#audience) for both paths. Conditions inspect the actual +[audiences](/docs/operating/concepts/audiences/) for both paths. Conditions inspect the actual incoming resource, which can also be a PDB or a Scale object. Kubernetes validation, LimitRanges, ResourceQuotas, and other admission policies @@ -222,7 +222,7 @@ for the policy. For registry checks, use `pod/containers`, `pod/initcontainers`, `pod/ephemeralcontainers`, and/or `pod/volumes` for the image locations you want to cover; `pod` alone does not select images. Controller-created Jobs and Pods can have different callers, so include those identities in any -[audience filter](/docs/rules/#audience). +[audience filter](/docs/operating/concepts/audiences/). With **no workload policies**, `targets: [cronjob]` instead acts on the kind: `deny` rejects CronJobs, while `allow` establishes a workload-kind allow-list. @@ -994,7 +994,7 @@ an explicit excessive limit or a limit without a positive request. ##### Rule order and policy overrides Rules are processed in declaration order after `namespaceSelector` and -[audience](/docs/rules/#audience) filtering. Resource policies are resolved independently for every +[audience](/docs/operating/concepts/audiences/) filtering. Resource policies are resolved independently for every combination of target, resource name, and field (`request` or `limit`). This allows CPU and memory, or requests and limits, to be managed independently. @@ -1043,7 +1043,7 @@ are still evaluated. This makes `Preserve` useful as a namespace-specific escape hatch and `Default` useful when switching from enforcement back to fill-only behavior. -For the request identity of controller-created Pods, see [Audience](/docs/rules/#audience). +For the request identity of controller-created Pods, see [Audiences](/docs/operating/concepts/audiences/#request-identity). ##### Configuration validation @@ -2335,7 +2335,7 @@ wins. Allowing one property does not bypass a failure of another. Audit rules emit events without changing the admission decision. Omitted properties never override an earlier rule. -[Namespace selection, audiences](/docs/rules/), and +[Namespace selection](/docs/rules/#order-and-scope), [audiences](/docs/operating/concepts/audiences/), and [enforcement conditions](/docs/rules/#enforcement-conditions) use the usual rules scope. Conditions inspect the actual incoming object: a PDB during a PDB write, a controller during a controller write, and an `autoscaling/v1` Scale during a diff --git a/content/en/docs/rules/mutate/ingress.md b/content/en/docs/rules/mutate/ingress.md index 3696f64..bfb7d5f 100644 --- a/content/en/docs/rules/mutate/ingress.md +++ b/content/en/docs/rules/mutate/ingress.md @@ -313,7 +313,7 @@ order. The first matching merge fills a missing reference; later merges preserve it. A later replacement can override it. Put specific merge defaults before a shared fallback when their selectors overlap. -Use [audience](/docs/rules/#audience) to select requesting subjects and +Use [audience](/docs/operating/concepts/audiences/) to select requesting subjects and [mutation conditions](/docs/rules/#mutation-conditions) to select individual ListenerSets. This fragment supplies a private Gateway for objects labeled `exposure: private`, then a public fallback for other objects without a parent: diff --git a/content/en/docs/rules/mutate/workloads.md b/content/en/docs/rules/mutate/workloads.md index 7394525..6e0259c 100644 --- a/content/en/docs/rules/mutate/workloads.md +++ b/content/en/docs/rules/mutate/workloads.md @@ -108,7 +108,7 @@ created directly or by a Deployment, StatefulSet, DaemonSet, Job, CronJob, or another controller. Stored controller templates remain unchanged. **The resulting Pods still receive applicable mutations when they are created.** -Namespace selection, mutation targets, conditions, and [audience](/docs/rules/#audience) +Namespace selection, mutation targets, conditions, and [audience](/docs/operating/concepts/audiences/) still determine which mutations apply. Audience matching uses the identity creating the Pod, usually the controller's service account. {{% /alert %}} diff --git a/content/en/docs/tenants/rules.md b/content/en/docs/tenants/rules.md index ae6fc2a..4091bdb 100644 --- a/content/en/docs/tenants/rules.md +++ b/content/en/docs/tenants/rules.md @@ -8,7 +8,8 @@ description: > {{% alert title="Rules documentation" color="info" %}} **The [Rules documentation](/docs/rules/) is the main reference for the rules API.** Find all [mutation](/docs/rules/mutate/) and [enforcement](/docs/rules/enforcement/) -properties there, together with conditions, audiences, and rule evaluation order. +properties there, together with conditions, [audiences](/docs/operating/concepts/audiences/), +and rule evaluation order. This page covers Tenant-specific configuration through `Tenant.spec.rules`: namespace selection, templating, and quota generation. @@ -131,7 +132,7 @@ Every quota entry requires a DNS label-compatible `name` which must be unique ac Generated resource names use `-`. -Quota accounting is independent of a rule's request audience. An audience can limit other rule behavior but does not partition the shared resource budget. Quota definitions are not copied into namespace `RuleStatus` objects. They are reconciled directly from the Tenant into cluster-scoped `GlobalResourceQuota` objects, which remain the authoritative source for admission and accounting. +Quota accounting is independent of a rule's request [audience](/docs/operating/concepts/audiences/). An audience can limit other rule behavior but does not partition the shared resource budget. Quota definitions are not copied into namespace `RuleStatus` objects. They are reconciled directly from the Tenant into cluster-scoped `GlobalResourceQuota` objects, which remain the authoritative source for admission and accounting. Existing `Tenant.spec.resourceQuotas` behavior remains available for compatibility. Use rule-generated or directly managed `GlobalResourceQuota` objects when an atomic shared limit across namespaces is required. @@ -321,7 +322,7 @@ spec: - List selector: matchLabels: - projectcapsule.dev/tenant: {{ $.tenant.metadata.name }} + projectcapsule.dev/tenant: {{ $.tenant.metadata.name }} ```