Files
cozystack/hack/e2e-install-cozystack.bats
T
Aleksei Sviridkin 442768abb7 feat(kubernetes): give each tenant Kubernetes cluster its own etcd (#4817)
## What this PR does

A tenant Kubernetes cluster could not start until an ancestor `Tenant`
had `spec.etcd: true`. The chart read the datastore name from
`_namespace.etcd` and, with none, rendered only a
`<release>-awaiting-etcd` ConfigMap. Every cluster below that tenant
then shared one etcd, one CA and one disk, separated by key prefix only.
Whoever creates a cluster usually may not edit the `Tenant`, so anything
ordering clusters on a tenant's behalf (the portal's controller, for
one) had to flip `etcd: true` first.

This PR makes the `Kubernetes` application carry its own etcd. It
implements phases 1 and 2 of the per-cluster etcd design proposal,
[cozystack/community#25](https://github.com/cozystack/community/pull/25),
as three commits that can be split later:

1. `refactor(etcd)`: the etcd chart's `EtcdCluster`, cert-manager PKI,
`DataStore`, `WorkloadMonitor`, defrag `CronJob`, VPA and `VMPodScrape`
move into named templates in `cozy-lib`
(`packages/library/cozy-lib/templates/_etcd.tpl`), parameterised by the
cluster name. `packages/extra/etcd` calls them with `"etcd"`, and its
rendered output is byte-identical before and after (see Verification).
2. `feat(kubernetes)`: a new cluster renders its own `EtcdCluster` and
`DataStore` from those templates, and a cluster that already runs on a
shared tenant etcd keeps it.
3. `feat(platform)`: migration 63 → 64 reports which clusters stay on a
shared etcd and changes nothing.

Phases 3 and 4 (deprecating, then removing `Tenant.spec.etcd`,
`_namespace.etcd` and `cozy-lib.ns-etcd`) are left for later.

### Design

**Names.** For release `kubernetes-<name>` in namespace `<ns>`:

| Object | Name |
|---|---|
| `EtcdCluster`, its headless Service, members `<…>-xxxxx`, `<…>-client`
Service | `kubernetes-<name>-etcd` |
| Secrets | `kubernetes-<name>-etcd-{ca,client,server,peer,peer-ca}-tls`
|
| `DataStore` (cluster-scoped) | `<ns>.kubernetes-<name>` |
| DataStore endpoint | `kubernetes-<name>-etcd.<ns>.svc:2379` |

**Shared templates.** `cozy-lib.etcd.cluster` takes optional `labels`
and `annotations` and renders them into the `EtcdCluster`'s
`spec.additionalMetadata`, which etcd-operator copies onto every member
Pod and PVC. With neither set, it renders no `additionalMetadata` at
all.

**Values.** One new field, `etcd.replicas`: `3` (default) or `1`. The
schema bounds it to 1..3 and the chart refuses 2 at render time. Size
(4Gi), resources (1000m / 512Mi limits to start with) and the etcd
version (3.6.11, the etcd chart's default) are chart-internal. Where a
VerticalPodAutoscaler runs, it sizes each member's requests as it is
recreated, up to 5000m CPU / 8Gi memory divided by the platform's CPU
and memory allocation ratios (500m / 8Gi at the default ratios of 10 and
1), with the limits scaled in proportion; NOTES.txt and the README say
so.

**StorageClass.** Two new platform values,
`kubernetesEtcd.storageClassLocal` and
`kubernetesEtcd.storageClassReplicated`, reach the chart as
`_cluster.etcd-storage-class-local` (used with 3 members) and
`_cluster.etcd-storage-class-replicated` (used with 1 member). Empty
keys fall back to the namespace default StorageClass.
`spec.storage.storageClassName` is immutable on an `EtcdCluster`, so the
chart reads the live object's class on every render after the first and
never re-derives it; scaling 1 → 3 keeps the class the cluster started
with. Dropping from 3 members to 1 is refused at render time when the
etcd is on the class the platform names for 3 members, or off the class
it names for 1, because a single member would then hold the only copy of
the control-plane state on storage that does not replicate it. An etcd
that was created with one member keeps rendering whatever its class.

**New clusters vs existing ones.** The chart decides from the live
`KamajiControlPlane`, looked up by release name:

- no `KamajiControlPlane`, or one whose `spec.dataStoreName` is the
cluster's own name: own etcd;
- one that names any other `DataStore`: that `DataStore` is kept, and
the chart renders no etcd of its own.

Clusters stuck in the old awaiting-etcd state have no
`KamajiControlPlane`, so they get their own etcd on their next
reconcile. `_namespace.etcd` is deliberately not the signal.
`packages/system/cozystack-basics/templates/cozystack-values-secret.yaml`
hardcodes `etcd: tenant-root`, and
`packages/apps/tenant/templates/namespace.yaml` passes it down, so every
tenant publishes a value whether or not an etcd runs behind it.
Honouring it for new clusters would change nothing for anyone. Following
it for existing clusters is also wrong: today, switching on `spec.etcd`
for a mid-level tenant silently moves every cluster below it to a new
datastore, which is a Kamaji datastore migration. With this PR, the live
binding sticks.

An existing cluster renders exactly what it rendered before, pre-delete
hook included, apart from randomly generated Talos tokens, so the
upgrade rolls no control-plane pods. New clusters carry
`policy.cozystack.io/allow-to-etcd-cluster` instead of
`policy.cozystack.io/allow-to-etcd`, which only admits a cluster to its
tenant's shared etcd.

Both lookups the decision rests on read the chart's own live objects:
the binding its `KamajiControlPlane` already records, and the immutable
`storageClassName` of its `EtcdCluster`. Each gives the same output on
every render, and their empty branch is the new-cluster render offline
`helm template` sees, which is the kind of `lookup` the chart guidelines
allow.

**What goes away.** The `awaiting-etcd` beacon goes, along with the
`_namespace.etcd` gate on the ~25 addon and satellite templates
(`helmreleases/*`, `csi/deploy.yaml`, `kccm/manager.yaml`,
`cluster-autoscaler/deployment.yaml`, `ingress.yaml`, the Proxmox CCM
and CSI). A datastore now always exists, so these gates were always
true.

**Deletion.** The pre-delete hook deletes the `TenantControlPlane` and
waits up to 120s, and it exits 0 whatever is left, because a failing
pre-delete hook keeps the release and retries the same teardown; the one
exception is below. Kamaji's `finalizer.kamaji.clastix.io` drops the
tenant's etcd role, prefix and user and the datastore-config Secret's
finalizer, and it runs only while the `DataStore` is Ready and answers,
so a `TenantControlPlane` whose own etcd never came up or has lost
quorum would never finish deleting. On a cluster that owns its etcd,
those three objects live in the etcd this uninstall deletes next. So
when such a `TenantControlPlane` outlives the wait, the hook (Step 4a)
removes that one finalizer with a JSON patch that tests it at the index
it was read at, waits another 60s, and lets Step 4b clear the Secret's
finalizer as before. A `TenantControlPlane` on a shared `DataStore` is
left to Kamaji, since that etcd outlives the cluster. The hook also
deletes the etcd's five Certificates and then their Secrets (Step 8),
which cert-manager issues without an owner, in the same order and for
the same reason as Step 7 deletes the Talos PKI. Then:

- Helm removes the `EtcdCluster`, `DataStore` and the remaining objects;
- the member PVCs go by garbage collection, because the operator owns
them through the `EtcdMember`s.

If Step 4a's patch is rejected, or the `TenantControlPlane` cannot be
read, the hook prints its residue summary and fails before Step 8: Helm
would otherwise delete the etcd while Kamaji's finalizer still waits on
it, so the uninstall is retried with the etcd and its PKI in place.
Steps 4a and 8, that check and their RBAC (a `patch` on this release's
`TenantControlPlane`, and `delete` on the etcd Certificates and Secrets
by name) render only for a cluster that owns its etcd.

### Deviations from cozystack/community#25

- **DataStore name** is `<namespace>.<release>`, not
`<namespace>-<release>`. Tenant names are alphanumeric and nest with
dashes, so the dashed form collides: Kubernetes `foo` in `tenant-a`
gives `tenant-a-kubernetes-foo`, which is also the namespace, and
therefore the shared `DataStore` name, of tenant `foo` under tenant
`kubernetes` under `tenant-a`. A namespace cannot contain a dot. Kamaji
copies the `DataStore` name into the pod label
`component.kamaji.clastix.io/datastore`, so the name is capped at 63
characters, truncated with an 8-character hash past that.
- **No truncate-and-hash for `kubernetes.etcdName`.** The app name is
now capped at 32 characters (`@maxLength 32`, added with the nodes
split), so `kubernetes-<name>-etcd` is at most 48 characters. That is
inside the 56 the operator needs: the `<name>-client` Service and the
generated member names must fit in 63. The helper fails the render past
56 rather than rename anything.
- **"Honour an explicit `_namespace.etcd`"** means keeping a cluster on
the `DataStore` its live control plane names, for the reason above. It
does not mean following `_namespace.etcd` for new clusters.
- **`etcd.replicas` validation** is a schema range of 1..3 plus a
render-time refusal of 2, rather than a schema enum. `cozyvalues-gen`
v1.7.0, the version CI pins and the latest release, emits string members
for an integer enum, which would reject the default `3`. The aggregated
API does not validate an application's spec against its schema at all,
so neither an enum nor a CEL rule would refuse 2 at admission; Helm's
`values.schema.json` check and the render are where it is refused.
- **The delete-hook branch** keys on the same live-`KamajiControlPlane`
condition as the render, as #25 asks, and additionally checks at run
time that the `TenantControlPlane` names this cluster's own `DataStore`
before touching Kamaji's finalizer. Helm deletes release resources only
after the pre-delete hook, so the etcd outlives Kamaji's normal
finalization without any ordering inside the hook.
- **TLS** reuses the etcd chart's `secretRef` shape (chart-issued
certificates) rather than the operator's `certManager` mode. Kamaji's
`DataStore` needs the CA private key to sign each tenant's client
certificate, and `secretRef` keeps that key in a Secret the chart
controls. The server certificate also carries the operator's
`<name>-client` Service names, which the etcd chart's does not.
- **Satellites.** The `PrometheusRule` stays in the etcd chart only, so
a cluster's own etcd has no alert rules. `VMPodScrape`, VPA and the
`CiliumNetworkPolicy` render only where their APIs are served. The etcd
chart's `VMPodScrape` now selects `app.kubernetes.io/instance: etcd`
instead of `app.kubernetes.io/name: etcd`: etcd-operator stamps the
latter on every member it runs, so a tenant etcd would otherwise also
scrape the cluster etcds in its namespace and count their members as its
own.
- **Name budget.** The defrag `CronJob` is `<etcd name>-defrag`, which
reaches 55 characters for a 32-character app name while the apiserver
caps CronJob names at 52; past 52 the template truncates it and appends
an 8-character hash. The etcd chart's `etcd-defrag` is unaffected.
- **Defrag image.** The defrag container pulls
`ghcr.io/ahrtr/etcd-defrag:v0.13.0` through `cozy-lib.image`, pinned to
the multi-architecture index digest, so a configured registry mirror
applies; `_etcd.tpl` is tracked by Renovate and listed in
`IMAGE_REF_EXTRA_FILES`. This changes the etcd chart's CronJob too,
after the extraction commit. Contributed by @yankawai in #5387 and
folded in.
- **Migration.** The opt-in migration runbook is not implemented here
(see below), and no `talosconfig` is issued. The numbered migration only
reports, as #25 suggests.

### Gaps #25 did not cover

- **Backups.** Covered through the `Kubernetes` backup strategy (#4931),
which `cozy-default` routes `apps.cozystack.io/Kubernetes` to. It
resolves the datastore from the `TenantControlPlane`, so it dumps the
cluster's key prefix from its own etcd or a shared one alike. Its dump
Job runs in the application namespace, and the deny policy below would
refuse it, so the strategy's pod template now carries
`policy.cozystack.io/allow-to-etcd-cluster: {{ .Release.Prefix }}{{
.Release.Name }}-etcd`, which is inert for a cluster on a shared etcd.
The strategy's Velero half does not select the etcd's PVCs or TLS
Secrets and does not need to: the dump restores into whatever etcd the
control plane runs on.
- **Per-cluster network policy.** A `CiliumNetworkPolicy` named after
the etcd selects its member pods with `ingressDeny` on 2379/2380 against
two sets of pods and one entity. The first is pods in the tenant
namespace that are neither members nor carry
`policy.cozystack.io/allow-to-etcd-cluster: <etcd name>`, a label set on
the control-plane pods, the defrag Job and the backup dump Job. The
second is pods in any other namespace except `kube-system` and
namespaces labelled `cozystack.io/system: "true"`, which is where
Kamaji, its migrate Job and etcd-operator run. The entity is `world`,
which the tenant's `allow-external-communication` admits to every
endpoint, so sources off the cluster, such as Proxmox workers, are
denied too. The node's own `host` and `remote-node` traffic is not. Deny
rules are needed because the tenant's own policies allow all traffic
within a namespace and from ancestor tenants, and allow rules only add.
Metrics on 2381 stay open. The pods also carry `cozystack.io/service:
kubernetes-etcd` rather than `cozystack.io/service: etcd`, so the
tenant-wide `<tenant>-ingress-etcd` policy does not admit child tenants'
control planes to them. The policy renders only where Cilium serves
`cilium.io/v2/CiliumNetworkPolicy`.
- **Platform ordering.** `cozystack.kubernetes-application` now
`dependsOn` `cozystack.etcd-operator`. Both come with the isp-full
variants, the only ones the iaas bundle allows. The selective-install
fixture is unchanged (`hack/select-install.sh --disabled postgres`
produces the same set). The same edge makes an etcd-operator change
select the `kubernetes-latest`, `kubernetes-previous` and `computeplane`
e2e suites besides `etcd`, and `hack/select-e2e_test.bats` now expects
that.
- **e2e.**
- `hack/e2e-install-cozystack.bats` no longer turns on tenant-root's
etcd, which only Kubernetes clusters used, and no longer waits for it. A
cluster that fell back on a shared etcd would therefore not come up.
- `run_kubernetes_test` asserts the control plane names
`tenant-test.kubernetes-<name>` and that `kubernetes-<name>-etcd`
reaches `Available`.
- `kubernetes-latest` runs the shipped defrag CronJob once and asserts
the Job completes (from #5387), then probes the etcd client port with
`nc -z`: an unlabelled Pod in `tenant-test` and a labelled Pod in
`tenant-root` must be refused, and a labelled Pod in `tenant-test` must
connect as the control. Each Pod ends `Succeeded` only when its verdict
matches, so a probe that cannot run fails the step.
- `cozy_cleanup` waits up to 3m until the `EtcdCluster`, `DataStore`,
member PVCs and Secrets are gone, each read bounded by that deadline;
both Kubernetes suites' teardown op grows from 22m to 25m to cover it.
- The Proxmox suite's tenant drops `etcd: true` and the comment calling
it mandatory.
  - The ComputePlane suite's comment no longer cites #4726.
- `hack/admin-kubeconfig-invariant.bats` drops its two awaiting-etcd
cases, and the now-unused `tests/values-ci-no-etcd.yaml` goes with them.
- **Generated artifacts** come from the tooling. `make -C
packages/apps/kubernetes generate` produced `values.schema.json`, the
README table, `api/apps/v1alpha1/kubernetes/types.go` and
`packages/system/kubernetes-rd/cozyrds/kubernetes.yaml`. Root `make
generate` regenerated `zz_generated.deepcopy.go`, and
`pkg/generated/openapi` did not change. `make generate` in every touched
package leaves the tree clean.
- **Existing clusters.** Migration 63 → 64 lists every
`KamajiControlPlane` whose `DataStore` its own release did not render,
judged by Helm's release annotations on the `DataStore`, with that
`DataStore`'s endpoints. It writes nothing but the version stamp. Slot
check on 2026-11-23:
  - `main` ships through 62 (#5239) with `targetVersion: 63`;
- `release-1.7` ships through 60 (target 61), and `release-1.6` through
53 (target 54);
  - so this PR takes 63 and sets `targetVersion: 64`.
- **README.** `packages/apps/kubernetes/README.md` now describes the
cluster's own etcd, the case of a cluster that keeps its tenant's shared
one, the VPA sizing and the backup path. The ComputePlane README no
longer lists a tenant etcd as a prerequisite.

### Migrating an existing cluster (designed, not implemented)

Nothing here moves a cluster, and nothing should until the runbook below
has an e2e. It combines #25's runbook with SerjioTT's Talos measurements
of 2026-09-03 (about 20s copy, 43s from patch to Ready, reads
uninterrupted) and with what Kamaji 26.9.4-edge's code does.

1. **Opt-in.** The opt-in has to make the chart render the cluster's own
etcd beside the shared one, without switching `dataStoreName`. The
likely shape is a chart-internal value, or an annotation the chart
reads, that the operator sets. Wait for `Available=True`.
2. **Snapshot the source etcd.** This is the rollback path.
3. **Pre-flight reachability from the cluster's namespace, not
Kamaji's** (SerjioTT finding 1). Kamaji's migrate Job runs in Kamaji's
namespace and can reach any etcd, so the copy "succeeds" toward a target
the control-plane pods cannot dial; the new apiserver generation then
crash-loops and the cluster stays write-frozen. Run `nc -zv <target>
2379` from a pod carrying the control plane's labels in the cluster
namespace. For the per-cluster target this holds by construction (same
namespace, and the deny policy admits the control plane), but the check
stays because rollback goes the other way.
4. **Switch.** Point `KamajiControlPlane.spec.dataStoreName` at
`<ns>.<release>`, with the CAPI provider re-projecting it onto the
`TenantControlPlane`. `kamaji.clastix.io/migration-timeout` can go on
the `KamajiControlPlane`, because the provider copies annotations to the
`TenantControlPlane`. Before switching, delete any leftover
`migrate-<TCP UID>` Job in Kamaji's namespace:
- a leftover with identical arguments is taken as success and switches
the datastore without copying;
- one with different arguments is deleted and recreated, with the freeze
already installed.
5. **Verify writes, not status** (SerjioTT finding 2). Kamaji installs a
`kamaji-freeze` ValidatingWebhookConfiguration in the guest, and only
its soot controller removes it, only when the `TenantControlPlane`
status is exactly `Ready`. A paused `TenantControlPlane`, or one sitting
in `WriteLimited`, `Sleeping` or `Upgrading`, keeps the freeze. Node
leases are exempt and reads are untouched, so nodes and `kubectl get`
look healthy. The success criterion is a canary write through the guest
API; if `kamaji-freeze` is still in the guest after the
`TenantControlPlane` is `Ready`, delete it.
6. **Restart every worker kubelet, one node at a time** (SerjioTT
finding 3). Until it restarts, a kubelet keeps running existing pods but
never starts a newly bound one, so the cluster looks healthy and
silently stops starting workloads. The per-node check is a new pod
starting on that node.
- On Talos there is no operator path to the workers' API today: the
chart has a per-cluster `talos-ca` Issuer but issues no client
credentials from it, so the fallback is `virtctl restart` per VM.
- Issuing an operator `talosconfig` from that CA alongside the admin
kubeconfig is the follow-up that makes this step cheap. It is not in
this PR: it is a separate credential with its own exposure question.
- Any pod-based restarter must be deployed before the switch, because a
deaf kubelet will not start it.
7. Retain the source prefix and the snapshot for a cool-off period, then
reclaim. Kamaji does not clean the old prefix after a migration.
Rollback is the same procedure in reverse, against the retained
snapshot.

### Test plan

Done here, on today's `main`, no cluster involved:

- [x] `helm template` of `packages/extra/etcd` before and after the
extraction (commit 1) is byte-identical: 14 renders (default; 1 member +
local SC + 10Gi; resources with CPU and memory allocation ratios +
another version; a global topology spread; a hard affinity with 5
members and 512Mi; leftover `backup.*` values with 0 members; 1 member
at 8Gi with a CPU allocation ratio, for the defrag quota flag), each in
`tenant-root` and `tenant-abc`, all identical by sha256. After commit 2
the one difference in each is the `VMPodScrape` selector.
- [x] `helm template` of `packages/apps/kubernetes` with Cilium served.
With `_namespace.etcd` set to `tenant-root`, or empty, both with 3
members: `EtcdCluster/kubernetes-demo-etcd` replicas=3 on the namespace
default StorageClass, and `DataStore/tenant-demo.kubernetes-demo`
pointing at `kubernetes-demo-etcd.tenant-demo.svc:2379`. The
`KamajiControlPlane` names that `DataStore`, and the policy renders.
- [x] With the platform StorageClass keys set: 1 member uses
`replicated` and 3 members use `local`. 2 members is refused at render
time; 5 is refused by the schema.
- [x] An existing cluster (live-`KamajiControlPlane` lookup stubbed to
return `tenant-root`) renders identically to `main` with
`values-ci.yaml`, pre-delete hook included, apart from random Talos
tokens. A new cluster's render differs from `main` only by the old
shared `dataStoreName`, the shared-etcd pod label and the added etcd
objects.
- [x] helm-unittest:
- `packages/apps/kubernetes`: 392 tests. The 28-case
`tests/etcd_test.yaml` covers names, the second cluster in one
namespace, the 63-character `DataStore` cap, the 52-character defrag
`CronJob` cap at the longest app name, the defrag quota for a 4Gi etcd,
StorageClass choice and stickiness, the refused and the allowed drops to
one member, refusal of 2, the policy with its `world` deny, and the
hook's Step 4a/8 RBAC. For an existing cluster it covers staying on the
shared `DataStore`, ignoring a changed `_namespace.etcd`, keeping the
shared-etcd label, no own etcd and no Step 4a/8.
- `packages/extra/etcd`: 29, including the new scrape-selector case.
`packages/core/platform`: 335. `cozy-lib-tests`: 90.
`packages/system/backupstrategy-controller`: 67, now asserting the dump
Job's label. `packages/apps/tenant`: 89. `packages/extra/computeplane`:
18.
- [x] bats, 867 cases, all passing (`helmrelease-readiness` and
`bats-runner-coverage` included): every `hack/run-kubernetes*_test.bats`
(including two new cases pinning the teardown reads to their deadline),
`kubernetes-pre-delete-hook` (13, split into the shared and the own-etcd
branch, including the fail-closed exit before Step 8),
`check-render-matrix`, `chainsaw-op-budgets`,
`migration-62-shared-etcd-report` (new, 4),
`admin-kubeconfig-invariant`, `check-hook-request-timeout`,
`app-cleanup-hooks_test`, `bats-no-negated-assert`, `bats-no-exit-trap`,
`select-install_test`, `select-e2e_test`, `linstor-storage-mode_test`,
`cozystack-version-stamp` and `md-no-hardwrap`.
- [x] `go build ./...` and `go vet` on the `api/apps/v1alpha1`
Kubernetes package.
- [x] `make generate` in every touched package and at the root leaves no
diff; `hack/check-commit-trailers.sh origin/main..HEAD` passes.

Needs a live cluster:

- [ ] The e2e lanes: `kubernetes-latest`, `kubernetes-previous` and
`computeplane`, now without tenant-root's etcd. The Proxmox lane on its
self-hosted runner.
- [ ] Upgrade from `main` with an existing cluster on tenant-root's
etcd. It must stay on `tenant-root` with no control-plane rollout, and
migration 63 must list it. No CI lane runs a cluster on a shared etcd,
because the chart no longer creates one; an upgrade lane that installs
the previous release first is a follow-up.
- [ ] The deny policy beyond what `kubernetes-latest` now probes: from a
guest worker VM and from outside the cluster, `nc -zv
kubernetes-<name>-etcd.<ns>.svc 2379` must be refused. The control
plane, the defrag Job, a `Kubernetes` backup dump Job, an `EtcdSnapshot`
Job, Kamaji and etcd-operator must still connect, including a freshly
started control-plane pod (Cilium can briefly classify a new pod IP as
`world`).
- [ ] Delete a cluster whose own etcd never became Available (for
example, the quota case below). Step 4a must release the
`TenantControlPlane` and the uninstall must finish without manual work.
- [ ] A tenant whose `ResourceQuota` cannot fit 3 × 1000m/512Mi limits
and 3 × 4Gi requests must surface the quota error on the etcd member
pods.
- [ ] A backup and a restore through the `Kubernetes` strategy of a
cluster that owns its etcd, including the rebuild of a deleted cluster.

### Follow-ups, not opened

These are listed here at the maintainer's request rather than filed:

- **cozystack/website**:
- `content/en/docs/next/operations/configuration/platform-package.md`
gains `kubernetesEtcd.storageClassLocal` and
`kubernetesEtcd.storageClassReplicated`;
- `content/en/docs/next/kubernetes/relocate-etcd.md` describes the
shared tenant etcd as what a cluster uses;
- tenant and Kubernetes docs telling users to set `etcd: true` for a
cluster, which is now an obsolete workaround;
- the Kubernetes app reference is regenerated from the README on the
next stable tag.
- **cozystack/terraform-provider-cozystack**:
`internal/provider/kubernetes_schema.go` and `kubernetes_model.go` need
`etcd.replicas`, with the default of 3, a 1..3 range and the
expand/flatten pair.
- **cozystack/cozystack**, after this lands:
- an upgrade e2e lane that keeps a cluster on a shared etcd across the
upgrade;
  - alert rules for a cluster's own etcd;
  - the opt-in migration path and its e2e;
  - an operator `talosconfig`;
  - phases 3 and 4.

### Screenshots

Not a UI change.

### Downstream repositories

Follow-ups are listed above under "Follow-ups, not opened". By the
maintainer's decision they are not filed from this draft, so no box is
ticked.

- [ ] No downstream repository is affected by this change
- [ ] [cozystack/website](https://github.com/cozystack/website) -
follow-up: listed above, not yet filed
- [ ]
[cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack)
- follow-up: listed above, not yet filed
- [ ]
[cozystack/ansible-cozystack](https://github.com/cozystack/ansible-cozystack)
- follow-up:
- [ ] [cozystack/ccp](https://github.com/cozystack/ccp) - follow-up:
- [ ] [cozystack/talm](https://github.com/cozystack/talm) - follow-up:
- [ ] [cozystack/cozyhr](https://github.com/cozystack/cozyhr) -
follow-up:
- [ ] [cozystack/cozy-proxy](https://github.com/cozystack/cozy-proxy) -
follow-up:
- [ ]
[cozystack/cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server)
- follow-up:
- [ ]
[cozystack/external-apps-example](https://github.com/cozystack/external-apps-example)
- follow-up:
- [ ] [cozystack/examples](https://github.com/cozystack/examples) -
follow-up:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:

### Release note

```release-note
feat(kubernetes): each new tenant Kubernetes cluster now gets its own etcd (EtcdCluster `kubernetes-<name>-etcd` and Kamaji DataStore `<namespace>.kubernetes-<name>`), created and deleted with the cluster, so no ancestor Tenant needs `etcd: true` and the `awaiting-etcd` state is gone. The new `etcd.replicas` field chooses 3 members (default) or 1. Each member starts at 1000m CPU and 512Mi memory limits with a 4Gi volume, counted against the tenant's quota, and a VerticalPodAutoscaler may resize it as it is recreated. The platform values `kubernetesEtcd.storageClassLocal` and `kubernetesEtcd.storageClassReplicated` choose the StorageClass for 3 members and 1 member respectively. Existing clusters keep the shared tenant etcd they run on, unchanged; the upgrade lists them in the migration log. The `Kubernetes` backup strategy covers a cluster's own etcd as it covers a shared one. The tenant etcd's metrics scrape now selects only its own members.
```



<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **New Features**
* New Kubernetes clusters now use dedicated etcd by default, with one-
or three-replica configurations and platform-selected storage.
* Clusters already using shared etcd continue to use it. Installation
notes show where control-plane state is stored and summarize resource
limits.
* Kubernetes add-ons can render independently of tenant-shared etcd
settings.
* **Bug Fixes**
* Cluster removal now waits for dedicated etcd resources to be
reclaimed.
* Platform upgrades report clusters still using shared etcd without
modifying them.
* **Documentation**
* Updated Kubernetes and ComputePlane guidance on dedicated etcd,
storage options, and migration considerations.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-24 15:04:49 +03:00

719 lines
39 KiB
Bash
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env bats
@test "Deploy cilium-leak-healer watchdog (best-effort)" {
# Interim mitigation for the Cilium in-memory endpoint leak (cilium/cilium#38313
# class): a deleted pod's endpoint is orphaned in the agent's registry, IPAM
# re-hands its IP to a new pod, and the agent then rejects the new sandbox with
# "IP <X> is already in use" until an agent restart. The watchdog runs as an
# in-cluster Job that first surgically evicts only the orphaned endpoint and,
# if the leaked IP keeps recurring (the leak is in agent in-memory state that
# endpoint-disconnect/delete-reschedule cannot reach), escalates to restarting
# that node's cilium-agent — bounded by a per-node cap. It covers install and
# (the Job outlives this file) the whole app suite.
#
# This is a real @test, NOT a bats setup_file hook: the e2e runner
# (hack/cozytest.sh) only executes @test functions — it never invokes
# setup_file/teardown_file — so a hook would silently never run. It is placed
# first so the watchdog is up before the install churn. Best-effort: the leak's
# primary trigger (VPA Auto eviction) is removed separately by the
# monitoring/etcd VPA->Initial fixes, so this is only the reactive net for
# residual churn and must never fail the suite. The heal logic stays in
# hack/e2e-cilium-endpoint-leak-healer.sh (single source of truth), shipped to
# the pod via a ConfigMap built here. Remove this test, that script, and
# hack/e2e-cilium-leak-healer.yaml once a fixed Cilium ships.
kubectl create configmap cilium-leak-healer -n kube-system \
--from-file=heal.sh=hack/e2e-cilium-endpoint-leak-healer.sh \
--dry-run=client -o yaml | kubectl apply -f - || true
kubectl apply -f hack/e2e-cilium-leak-healer.yaml || true
# Confirm it landed (visible in the cozytest.sh trace); never fail on a band-aid.
if kubectl -n kube-system get job cilium-leak-healer >/dev/null 2>&1; then
echo "cilium-leak-healer Job created"
else
echo "WARNING: cilium-leak-healer Job NOT created — watchdog inactive this run"
fi
}
@test "Deploy Talos image factory cache (best-effort e2e mirror)" {
# Tenant Kubernetes worker VMs boot from a Talos raw disk image that CDI
# streams over HTTP from the public Talos Image Factory. That endpoint has no
# byte-range support and intermittently stream-resets/stalls mid-transfer from
# the CI runner, so a worker DataVolume import can hang past the chart's
# 12-minute node-join deadline and fail (or merely make) the kubernetes-* tests
# (see cozystack/cozystack#3231). This Deployment fetches the image ONCE with a
# hard curl retry loop and serves it locally; tenant CRs then point
# spec.talos.imageFactoryURL at its Service. Deployed here (before the long
# install) so the seed download overlaps the install churn — readiness is gated
# at point-of-use in hack/e2e-chainsaw/_lib/talos-image-cache.sh, called from
# run-kubernetes.sh, which falls back to the public factory if the mirror never
# becomes Available, so this can only help.
# Best-effort: never fail the suite on the band-aid. Remove once tenant workers
# no longer bulk-pull the OS image from the public internet in CI.
local sid ver
sid=$(yq '.talos.schematicID' packages/apps/kubernetes-nodes/values.yaml 2>/dev/null)
ver=$(yq '.talos.version' packages/apps/kubernetes-nodes/values.yaml 2>/dev/null)
if [ -z "$sid" ] || [ "$sid" = "null" ] || [ -z "$ver" ] || [ "$ver" = "null" ]; then
echo "WARNING: could not read talos.schematicID/version from packages/apps/kubernetes-nodes/values.yaml — skipping mirror (fallback to public factory)"
return 0
fi
# The CiliumClusterwideNetworkPolicy in the manifest is intentionally NOT applied
# here: Cilium's CRDs do not exist until Cozystack is installed (below), so
# applying it now would error. It is applied at point-of-use by
# hack/e2e-chainsaw/_lib/talos-image-cache.sh once Cilium is up.
sed -e "s|__SCHEMATIC_ID__|${sid}|g" -e "s|__TALOS_VERSION__|${ver}|g" hack/e2e-talos-image-cache.yaml \
| yq 'select(.kind != "CiliumClusterwideNetworkPolicy")' \
| kubectl apply -f - || echo "WARNING: failed to apply talos-image-cache (fallback to public factory)"
if kubectl -n kube-system get deploy talos-image-cache >/dev/null 2>&1; then
echo "talos-image-cache Deployment created (seeding ${sid}/${ver} in background)"
else
echo "WARNING: talos-image-cache Deployment NOT created — tenant workers will use public factory.talos.dev"
fi
}
@test "Required installer chart exists" {
if [ ! -f packages/core/installer/Chart.yaml ]; then
echo "Missing: packages/core/installer/Chart.yaml" >&2
exit 1
fi
}
@test "Pre-pull platform images" {
# Cluster-member workloads (OVN raft, LINSTOR) fail if replicas start at
# different times due to image-pull stagger across nodes. Pre-pull these
# images to every node so all replicas start with images already cached.
#
# Source images directly from the rendered charts so version bumps stay in
# sync automatically. yq walks every PodSpec-shaped object and emits the
# images of each container — this scopes the result to images the kubelet
# actually pulls (skips configmap fields and CRD examples that happen to
# contain an `image:` key). Add a chart here when a new peer-sensitive
# workload is found.
#
# `select(. != null)` drops container entries that carry no image. The pod
# templates embedded in a LinstorCluster CR are strategic-merge fragments,
# so one that overrides only `args` has no image of its own to pull.
# Without the filter yq emits a bare `null`, which reaches the prepull
# DaemonSet as a container with an empty image and fails apply with a
# message naming a container index rather than the chart behind it.
# Stage each render AND the yq filter through tmp files instead of
# piping. Two constraints stack here: `set -x` would expand any
# `var=$(helm ...)` capture into the trace and balloon CI logs, and
# `set -o pipefail` is unavailable because hack/cozytest.sh runs under
# /bin/sh which is dash on Ubuntu CI. Redirection keeps each step as a
# standalone command — set -e catches a failure at any stage (helm
# render, yq filter, prepull) without needing pipefail and without
# leaking rendered YAML into the trace.
local kubeovn_yaml linstor_yaml certmanager_yaml images_list
kubeovn_yaml=$(mktemp)
linstor_yaml=$(mktemp)
certmanager_yaml=$(mktemp)
images_list=$(mktemp)
helm template packages/system/kubeovn > "$kubeovn_yaml"
helm template packages/system/linstor > "$linstor_yaml"
helm template packages/system/cert-manager > "$certmanager_yaml"
yq -N '
(..|select(has("containers"))|.containers[]|.image|select(. != null)),
(..|select(has("initContainers"))|.initContainers[]|.image|select(. != null))
' "$kubeovn_yaml" "$linstor_yaml" "$certmanager_yaml" > "$images_list"
# The failure-only Talos diagnostics Pod can land on any node. The sandbox's
# upstream talosctl binary is static, so cache its pinned Alpine base on every
# node while the cluster is healthy instead of cold-pulling on a failure path.
printf '%s\n' 'docker.io/alpine/k8s:1.36.2@sha256:44ef4942e171939b9c665a4a84beb80e2dcdb9a24330d4651cfdfd2e9deecc47' \
>> "$images_list"
hack/e2e-prepull-images.sh < "$images_list"
rm -f "$kubeovn_yaml" "$linstor_yaml" "$certmanager_yaml" "$images_list"
}
@test "Install Cozystack" {
# Install cozy-installer chart (operator installs CRDs on startup via --install-crds)
helm upgrade installer packages/core/installer \
--install \
--namespace cozy-system \
--create-namespace \
--set cozystackOperator.helmReleaseInterval=30s \
--timeout 2m
# The pre-install hook (cozy-system-labeler) must have stamped the PSA and
# cozystack identity labels onto cozy-system. Operator pods need
# enforce=privileged for hostNetwork=true; a silent regression in the hook
# would let helm install succeed but break operator admission downstream.
kubectl get ns cozy-system -o jsonpath='{.metadata.labels.pod-security\.kubernetes\.io/enforce}' | grep -qx privileged
kubectl get ns cozy-system -o jsonpath='{.metadata.labels.cozystack\.io/system}' | grep -qx true
# Wait for the ROLLOUT, not for condition=Available: once maxUnavailable
# reaches replicas the minimum available replica count is 0, so Available
# reports True with no pod running and a broken operator image passes in
# milliseconds, surfacing minutes later as a CRD timeout that blames the wrong
# component. `rollout status` reads updated and available replicas directly,
# and stays correct whatever strategy the chart carries.
#
# It still only proves a container started, not that the operator is healthy:
# there is no readiness probe, so one that starts and then dies mid-install
# passes here and is caught by the CRD waits below instead.
#
# This is the only readiness gate for the operator, since the helm step above
# drops --wait, so the timeout must cover scheduling and a cold pull of an
# image that is not in the prepull set.
kubectl rollout status deployment/cozystack-operator -n cozy-system --timeout=5m || {
echo "=== deployment/cozystack-operator rollout did not complete ==="
kubectl get deployment/cozystack-operator -n cozy-system -o yaml 2>&1 || true
echo "=== cozy-system pods ==="
kubectl get pods -n cozy-system -o wide 2>&1 || true
# The two shapes this gate exists to catch need different evidence, and
# neither is in `get pods -o wide`. ImagePullBackOff produces no logs at
# all, and CrashLoopBackOff puts the stack trace in the container that
# already died, so describe carries the first and --previous the second.
echo "=== cozystack-operator pod detail ==="
kubectl describe pod -n cozy-system -l app=cozystack-operator 2>&1 || true
echo "=== cozystack-operator logs ==="
kubectl logs -n cozy-system -l app=cozystack-operator --all-containers --tail=50 2>&1 || true
echo "=== cozystack-operator logs, previous container ==="
kubectl logs -n cozy-system -l app=cozystack-operator --all-containers --previous --tail=50 2>&1 || true
echo "=== cozy-system events ==="
kubectl get events -n cozy-system --sort-by=.lastTimestamp 2>&1 | tail -30 || true
false
}
# Wait for operator to install CRDs (happens at startup before reconcile loop).
# kubectl wait fails immediately if the CRD does not exist yet, so poll until it appears first.
timeout 120 sh -ec 'until kubectl wait crd/packages.cozystack.io --for=condition=Established --timeout=10s 2>/dev/null; do sleep 2; done'
timeout 120 sh -ec 'until kubectl wait crd/packagesources.cozystack.io --for=condition=Established --timeout=10s 2>/dev/null; do sleep 2; done'
# Wait for operator to create the platform PackageSource
timeout 120 sh -ec 'until kubectl get packagesource cozystack.cozystack-platform >/dev/null 2>&1; do sleep 2; done'
# Stage the generated manifest instead of piping it into kubectl: cozytest
# runs under /bin/sh without pipefail, so a generator failure in a pipeline
# could be hidden by kubectl successfully applying empty input.
local platform_packages
platform_packages=$(mktemp)
hack/e2e-platform-packages.sh > "$platform_packages"
kubectl apply -f "$platform_packages"
rm -f "$platform_packages"
# Launch storage + LB configuration in the background. It waits for its own
# prerequisites while the platform controllers reconcile HelmReleases, so
# the costs overlap even though the authoritative readiness gate starts only
# after prep has finished.
hack/e2e-post-install-prep.sh > /tmp/post-install-prep.log 2>&1 &
POST_PREP_PID=$!
echo "Waiting for post-install-prep to complete"
if ! wait "$POST_PREP_PID"; then
cat /tmp/post-install-prep.log >&2
echo "post-install-prep failed" >&2
exit 1
fi
cat /tmp/post-install-prep.log
# One authoritative gate, on fresh lists. A bare `kubectl wait --all` takes
# one snapshot and can miss releases created a moment later; it also waits
# the full timeout after Flux has already declared Stalled=True. The helper
# re-lists, requires the all-Ready name set to stay stable for 5s, and fails
# immediately on Stalled. The 11-release floor preserves the old >10
# existence backstop without the masked pacing wait.
. hack/e2e-wait-helmreleases.sh
cozy_wait_all_helmreleases_ready 900 11 5 2
}
@test "Wait for Cluster‑API provider deployments" {
# Wait for Cluster‑API provider deployments
timeout 120 sh -ec 'until kubectl get deploy -n cozy-cluster-api capi-controller-manager capi-kamaji-controller-manager capi-kubeadm-bootstrap-controller-manager capi-operator-cluster-api-operator capk-controller-manager >/dev/null 2>&1; do sleep 1; done'
kubectl wait deployment/capi-controller-manager deployment/capi-kamaji-controller-manager deployment/capi-kubeadm-bootstrap-controller-manager deployment/capi-operator-cluster-api-operator deployment/capk-controller-manager -n cozy-cluster-api --timeout=2m --for=condition=available
}
@test "Check Cozystack API service" {
timeout 60 sh -ec 'until kubectl get apiservices/v1alpha1.apps.cozystack.io apiservices/v1alpha1.core.cozystack.io >/dev/null 2>&1; do sleep 2; done'
kubectl wait --for=condition=Available apiservices/v1alpha1.apps.cozystack.io apiservices/v1alpha1.core.cozystack.io --timeout=2m
}
@test "Configure Tenant and wait for applications" {
# Patch root tenant and wait for its releases
# cozystack-api can report its APIService Available while a freshly-rolled pod
# has not yet loaded the requestheader client-CA — it then drops the
# front-proxy identity and answers as system:anonymous (403). The Available
# wait in the previous test does not cover that. Prove an AUTHENTICATED
# request against the actual resource succeeds before the patch's own GET.
timeout 120 sh -ec 'until kubectl get tenants.apps.cozystack.io root -n tenant-root >/dev/null 2>&1; do sleep 2; done'
local storage_class
storage_class="${COZY_E2E_STORAGE_CLASS:-replicated}"
case "$storage_class" in
replicated) ;;
local)
# The Tenant patch below leaves root monitoring off, so VictoriaLogs does
# not render in this run; the override is here for a run that turns it
# on. VictoriaLogs is the only root-tenant workload that explicitly
# defaults to replicated instead of inheriting the cluster's default
# StorageClass, and the container lane has no DRBD and intentionally
# exposes only local. The override goes into the values Secret before the
# Tenant patch, so the monitoring HelmRelease's first render creates local
# claims. Patching that HelmRelease after creation races the operator: a
# replicated PVC can be created first, and storageClassName is immutable.
# Flux drift detection is disabled, so the owning cozystack-basics release
# does not rewrite this E2E-only live override on its ordinary interval.
local root_values_b64_file root_values_file root_values_patch_file
root_values_b64_file=$(mktemp)
root_values_file=$(mktemp)
root_values_patch_file=$(mktemp)
kubectl get secret cozystack-values -n tenant-root -o jsonpath='{.data.values\.yaml}' > "$root_values_b64_file"
base64 -d "$root_values_b64_file" > "$root_values_file"
COZY_E2E_STORAGE_CLASS="$storage_class" yq -i \
'.logsStorages = [{"name":"generic","retentionPeriod":"1","storage":"10Gi","storageClassName":strenv(COZY_E2E_STORAGE_CLASS)}]' \
"$root_values_file"
jq -Rs '{"stringData":{"values.yaml":.}}' < "$root_values_file" > "$root_values_patch_file"
kubectl patch secret cozystack-values -n tenant-root --type merge --patch-file "$root_values_patch_file"
rm -f "$root_values_b64_file" "$root_values_file" "$root_values_patch_file"
;;
*)
echo "COZY_E2E_STORAGE_CLASS must be local or replicated, got '$storage_class'" >&2
return 1
;;
esac
# Root monitoring stays off: no suite inspects the tenant-root instance, and
# its bring-up (VictoriaMetrics, VictoriaLogs, Grafana and its CNPG database)
# competes with the rest of the install for node capacity, so a slow start
# could fail a pull request that never touched monitoring. The monitoring
# package itself stays installed, because tenant-application declares
# dependsOn cozystack.monitoring-application. Turning it on also means
# flipping monitoring.rootEnabled in hack/e2e-platform-packages.sh.
#
# The root etcd stays off as well: every tenant Kubernetes cluster brings its
# own, and leaving the shared one off is what proves a cluster comes up with
# no tenant etcd anywhere above it.
kubectl patch tenants/root --namespace tenant-root --type merge --patch '{"spec":{"host":"example.org","ingress":true,"monitoring":false,"etcd":false,"isolated":true, "seaweedfs": true}}'
timeout 60 sh -ec 'until kubectl get hr --namespace tenant-root ingress seaweedfs tenant-root >/dev/null 2>&1; do sleep 1; done'
# tenant-root parent HR only flips Ready after every child HR is Ready,
# so listing the children this patch enables plus the parent gives precise
# failure messages without redundant separate waits. seaweedfs now
# installs as a serial chain seaweedfs-db (CNPG bootstrap) ->
# seaweedfs-system (master raft quorum) -> seaweedfs wrapper, which
# pushes the parent's Ready flip to ~5-6 min on an idle runner. On a loaded
# runner the tenant stack only starts creating pods ~9-10 min in, so the
# parent's Ready can land past the HR's single 15m timeout window; the HR
# re-reconciles every 1m until it converges, so this wait is 20m to observe
# that eventual Ready rather than expiring first.
kubectl wait hr/ingress hr/seaweedfs hr/tenant-root \
-n tenant-root --timeout=20m --for=condition=ready
# Expose Cozystack services through ingress
kubectl patch package cozystack.cozystack-platform --type merge -p '{"spec":{"components":{"platform":{"values":{"publishing":{"exposedServices":["api","dashboard","cdi-uploadproxy","vm-exportproxy","keycloak"]}}}}}}'
# NGINX ingress controller
timeout 60 sh -ec 'until kubectl get deploy root-ingress-controller -n tenant-root >/dev/null 2>&1; do sleep 1; done'
kubectl wait deploy/root-ingress-controller -n tenant-root --timeout=10m --for=condition=available
}
@test "Keycloak OIDC stack is healthy" {
# Only oidc.enabled is set here: keycloakInternalUrl defaults to the in-cluster
# keycloak Service, which makes oauth2-proxy skip OIDC discovery and route the
# backend calls (token/jwks/userinfo/logout) through that Service.
kubectl patch package cozystack.cozystack-platform --type merge -p '{"spec":{"components":{"platform":{"values":{"authentication":{"oidc":{"enabled":true}}}}}}}'
timeout 120 sh -ec 'until kubectl get hr -n cozy-keycloak keycloak keycloak-configure keycloak-operator >/dev/null 2>&1; do sleep 1; done'
kubectl wait hr/keycloak hr/keycloak-configure hr/keycloak-operator -n cozy-keycloak --timeout=20m --for=condition=ready
# Enabling OIDC swaps the dashboard's token-proxy container for oauth2-proxy,
# so the dashboard is the consumer that proves the internal-URL default works.
# The install-time all-HelmRelease gate ran before this test flipped the flag
# and only ever saw the token-proxy shape, so nothing has re-checked the
# dashboard on the OIDC path.
#
# Waiting on hr/dashboard directly would be vacuous: it is still Ready=True
# from the token-proxy install, so `--for=condition=ready` returns instantly
# against the stale condition, before Flux has even consumed the patched
# values. Gate on an observable that exists ONLY on the OIDC path instead --
# the auth-proxy container appearing in the gatekeeper Deployment -- which is
# reached only after the new values are rendered.
timeout 600 sh -ec 'until kubectl get deploy/incloud-web-gatekeeper -n cozy-dashboard -o jsonpath="{.spec.template.spec.containers[*].name}" 2>/dev/null | grep -qw auth-proxy; do sleep 5; done' || {
echo "=== gatekeeper never re-rendered with the auth-proxy container after enabling OIDC ==="
echo "=== the patched values likely never reached the dashboard HelmRelease ==="
kubectl get package cozystack.cozystack-platform -o yaml 2>&1 || true
kubectl get hr/dashboard -n cozy-dashboard -o yaml 2>&1 || true
kubectl get deploy/incloud-web-gatekeeper -n cozy-dashboard -o yaml 2>&1 || true
false
}
# Then wait for the ROLLOUT, not for condition=available. The Deployment has
# replicas: 1 and maxUnavailable: 25%, which rounds down to 0, so Kubernetes
# keeps the old token-proxy pod up while the new one starts: Available stays
# True on the strength of the OLD ReplicaSet even as the new auth-proxy pod
# crashloops. `rollout status` is the check that only succeeds once the
# UPDATED pod is available.
#
# That is what gives this case teeth: were the default to regress to the
# external hostname, oauth2-proxy would do OIDC discovery against
# keycloak.example.org -- the e2e host placeholder does not resolve -- and
# crashloop, failing the rollout instead of shipping the regression.
kubectl rollout status deploy/incloud-web-gatekeeper -n cozy-dashboard --timeout=10m || {
echo "=== deploy/incloud-web-gatekeeper rollout did not complete after enabling OIDC ==="
kubectl get deploy/incloud-web-gatekeeper -n cozy-dashboard -o yaml 2>&1 || true
echo "=== cozy-dashboard pods ==="
kubectl get pods -n cozy-dashboard -o wide 2>&1 || true
echo "=== auth-proxy logs ==="
kubectl logs -n cozy-dashboard -l app.kubernetes.io/name=gatekeeper --all-containers --tail=50 2>&1 || true
false
}
# Not the vacuous wait described above: past the rollout gate the HelmRelease
# has necessarily been re-reconciled, so Ready here means the whole upgrade
# converged -- not just the one Deployment this test watched.
kubectl wait hr/dashboard -n cozy-dashboard --timeout=10m --for=condition=ready
# The login redirect oauth2-proxy builds from the alpha config: the realm path
# must reach the browser-facing auth URL, an allowed kc_idp_hint must be passed
# through to Keycloak, and a value outside the allow pattern must be dropped.
# Asserted after the port-forward is gone: on failure set -e would skip a kill
# placed after the assertion, and a trap would hide the TAP line.
pf_log=$(mktemp)
kubectl -n cozy-dashboard port-forward deploy/incloud-web-gatekeeper 18000:8000 >"$pf_log" 2>&1 &
pf_pid=$!
hinted=""
rejected=""
if timeout 30 sh -ec 'until nc -z localhost 18000; do sleep 0.2; done'; then
hinted=$(curl -sS -o /dev/null -w '%{redirect_url}' 'http://localhost:18000/oauth2/start?kc_idp_hint=e2e-idp') || true
rejected=$(curl -sS -o /dev/null -w '%{redirect_url}' 'http://localhost:18000/oauth2/start?kc_idp_hint=e2e%26prompt%3Dnone') || true
fi
kill "$pf_pid" 2>/dev/null || true
wait "$pf_pid" 2>/dev/null || true
case "$hinted" in
https://keycloak.example.org/realms/cozy/protocol/openid-connect/auth\?*\&kc_idp_hint=e2e-idp\&*|https://keycloak.example.org/realms/cozy/protocol/openid-connect/auth\?*\&kc_idp_hint=e2e-idp) ;;
*)
echo "=== /oauth2/start?kc_idp_hint=e2e-idp did not redirect to the cozy realm with the hint ==="
echo "Location: ${hinted:-<none>}"
cat "$pf_log"
false
;;
esac
case "$rejected" in
https://keycloak.example.org/realms/cozy/protocol/openid-connect/auth\?*kc_idp_hint*|https://keycloak.example.org/realms/cozy/protocol/openid-connect/auth\?*prompt=none*)
echo "=== a kc_idp_hint outside the allow pattern reached the Keycloak URL ==="
echo "Location: $rejected"
false
;;
https://keycloak.example.org/realms/cozy/protocol/openid-connect/auth\?*) ;;
*)
echo "=== /oauth2/start with a rejected kc_idp_hint did not redirect to Keycloak ==="
echo "Location: ${rejected:-<none>}"
cat "$pf_log"
false
;;
esac
rm -f "$pf_log"
}
@test "Aggregated API rejects Tenant name with dashes" {
# Regression guard: the tenant Helm chart's tenant.name helper splits the
# Release.Name on "-" and fails unless the result is exactly
# ["tenant", "<name>"]. The aggregated API must catch tenant names
# containing dashes up-front with a tenant-specific error, instead of
# silently accepting the Application and letting Flux fail later.
# Defensive cleanup: if a prior regression left foo-bar in the cluster,
# remove it before exercising the validation so we are not observing
# stale state. Safe even in the happy path because of --ignore-not-found.
kubectl delete tenants.apps.cozystack.io foo-bar -n tenant-root --ignore-not-found
# Preflight: tenant-root is created by earlier tests in this suite. Fail
# loudly if it is missing so this test does not silently trigger an
# unrelated "namespace not found" error and misreport as a pass.
kubectl get namespace tenant-root
# --validate=ignore forces kubectl to skip client-side OpenAPI validation
# and send the payload straight to the aggregated API. This guarantees the
# server-side name check runs and the error we grep for is the tenant
# contract error, not a kubectl schema rejection. (--validate=false is the
# deprecated alias.)
local output rc
# Run the apply in its own subshell so we can capture BOTH stdout+stderr
# AND the exit code explicitly, without `|| true` swallowing a real failure
# mode (e.g. network error, auth failure) that should also fail the test.
output=$(
kubectl apply --validate=ignore -f - 2>&1 <<EOF
apiVersion: apps.cozystack.io/v1alpha1
kind: Tenant
metadata:
name: foo-bar
namespace: tenant-root
spec: {}
EOF
) && rc=0 || rc=$?
echo "kubectl apply exit=$rc, output=$output"
# kubectl MUST have failed: success would mean validation regressed.
[ "$rc" -ne 0 ]
# Assert the tenant-specific message is present (distinguishes from
# generic DNS-1035 errors and from network/auth failures).
echo "$output" | grep -q "tenant names must"
# And assert kubectl did NOT report creation — if validation regressed
# into a "warn" variant, the server could still accept the object. A bare
# `! echo | grep` is vacuous under cozytest's `set -e` (suppressed for any
# command whose status is inverted with `!`), so the regression would slip
# through; assert via `if ...; false`.
if echo "$output" | grep -qi "created"; then echo "FAIL: kubectl reported the tenant as created — validation must reject it, not warn"; false; fi
# Post-condition cleanup: even though we expect validation to reject the
# create, removing foo-bar unconditionally keeps the cluster clean for
# subsequent tests in case validation regresses and the object is created.
kubectl delete tenants.apps.cozystack.io foo-bar -n tenant-root --ignore-not-found
}
@test "Create tenant with isolated mode enabled" {
kubectl -n tenant-root get tenants.apps.cozystack.io test ||
kubectl apply -f - <<EOF
apiVersion: apps.cozystack.io/v1alpha1
kind: Tenant
metadata:
name: test
namespace: tenant-root
spec:
etcd: false
host: ""
ingress: false
isolated: true
monitoring: false
resourceQuotas:
cpu: "60"
memory: "128Gi"
# 200Gi so back-to-back tenant Kubernetes tests
# (kubernetes-latest, kubernetes-previous) don't run into
# ResourceQuota during CDI's second-phase scratch PVC allocation.
# Each tenant provisions 2 worker VMs × 20Gi disk + 21Gi CDI scratch
# during import; when kubernetes-latest teardown's DRBD detach lags
# past cozy_wait_tenant_drained, the leftover 40Gi of latest's worker
# PVCs stays counted against tenant-quota while kubernetes-previous
# is already asking for its own 40Gi + ~21Gi scratch: the scratch
# PVC create call trips the 100Gi ceiling and the second worker's
# DataVolume stalls in ImportInProgress indefinitely.
storage: "200Gi"
seaweedfs: false
EOF
timeout 60 sh -ec 'until kubectl get hr/tenant-test -n tenant-root >/dev/null 2>&1; do sleep 2; done'
kubectl wait hr/tenant-test -n tenant-root --timeout=1m --for=condition=ready
timeout 60 sh -ec 'until kubectl get namespace tenant-test >/dev/null 2>&1; do sleep 2; done'
kubectl wait namespace tenant-test --timeout=20s --for=jsonpath='{.status.phase}'=Active
# Wait for ResourceQuota to appear and assert values
timeout 60 sh -ec 'until [ "$(kubectl get quota -n tenant-test --no-headers 2>/dev/null | wc -l)" -ge 1 ]; do sleep 1; done'
kubectl get quota -n tenant-test \
-o jsonpath='{range .items[*]}{.spec.hard.requests\.memory}{" "}{.spec.hard.requests\.storage}{"\n"}{end}' \
| grep -qx '137438953472 200Gi'
# Assert LimitRange defaults for containers
kubectl get limitrange -n tenant-test \
-o jsonpath='{range .items[*].spec.limits[*]}{.default.cpu}{" "}{.default.memory}{" "}{.defaultRequest.cpu}{" "}{.defaultRequest.memory}{"\n"}{end}' \
| grep -qx '250m 128Mi 25m 128Mi'
}
@test "Tenant super-admin holds no write verb outside the allowlist" {
# cozy:tenant:super-admin is aggregated from every ClusterRole labelled for
# it or for a level below, across several packages, so a write path into a
# tenant namespace can arrive without touching the role that names it. The
# raw kubevirt.io VirtualMachine grant did: a '*' that let a tenant size a VM
# outside any application. The effective rules are read back from the
# apiserver, after aggregation, and any write verb the allowlist does not
# name fails the test; adding a line there is the statement that the write
# is accounted for.
#
# The bare system:authenticated identity is subtracted first, so what
# Kubernetes grants every user (the selfsubject* reviews) does not tie the
# list to a Kubernetes version. An allowlisted line the cluster does not
# grant is reported without failing: a lane with COZY_DISABLED_PACKAGES set
# lacks the tenant roles those packages ship.
#
# Rules and status come from the same SelfSubjectRulesReview response, so
# a partial list cannot pass on the strength of a later, complete one.
# can-i --list hides both failure modes behind exit 0: it only warns on
# incomplete, and says nothing when RBAC reports an evaluationError with
# incomplete left false. The jq rendering keeps can-i's resource column,
# which the allowlist is written in.
#
# Lines covered by a wildcard grant are folded into it, so a '*' on a whole
# group (apps.cozystack.io, the gated API) does not make every new kind an
# allowlist edit. Staged through files rather than pipes: /bin/sh here has
# no pipefail, and a failed kubectl must not pass as an empty grant list.
local complete normalize subsume review allowlist granted baseline effective unexpected missing f
complete='.status.incomplete == false and (.status.evaluationError // "") == ""'
normalize='.status.resourceRules[] | . as $r
| ($r.resourceNames // [] | if length == 0 then ["-"] else . end)[] as $name
| $r.apiGroups[] as $group | $r.resources[] as $resource | $r.verbs[] as $verb
| select($verb != "get" and $verb != "list" and $verb != "watch")
| ($resource | split("/")) as $part
| $part[0] + (if $group == "" then "" else "." + $group end)
+ (if ($part | length) > 1 then "/" + ($part[1:] | join("/")) else "" end)
+ " " + $name + " " + $verb'
subsume='NR == FNR { have[$0] = 1; next }
{
dot = index($1, ".")
if (dot > 1 && $1 !~ /^\*\./ && (("*" substr($1, dot) " - *") in have)) next
if ($3 != "*" && (($1 " " $2 " *") in have)) next
print
}'
review=$(mktemp); allowlist=$(mktemp); granted=$(mktemp); baseline=$(mktemp)
effective=$(mktemp); unexpected=$(mktemp); missing=$(mktemp)
echo '{"apiVersion":"authorization.k8s.io/v1","kind":"SelfSubjectRulesReview","spec":{"namespace":"tenant-test"}}' > "$review"
# --validate=false: client-side validation would run as the impersonated
# identity, which cannot list CRDs.
timeout -k 5 30 kubectl create --validate=false -f "$review" -o json \
--as=e2e-rbac-probe --as-group=system:authenticated --as-group=tenant-test-super-admin > "$granted"
timeout -k 5 30 kubectl create --validate=false -f "$review" -o json \
--as=e2e-rbac-probe --as-group=system:authenticated > "$baseline"
for f in "$granted" "$baseline"; do
if jq -e "$complete" "$f" > /dev/null; then :; else
echo "FAIL: the apiserver could not enumerate the tenant-test rules completely:" >&2
jq -c '.status | {incomplete, evaluationError}' "$f" >&2
false
fi
done
jq -r "$normalize" "$granted" > "$granted.n"
jq -r "$normalize" "$baseline" > "$baseline.n"
yq '.writeVerbs[]' hack/e2e-tenant-super-admin-write-verbs.yaml > "$allowlist"
LC_ALL=C sort -u -o "$granted.n" "$granted.n"
LC_ALL=C sort -u -o "$baseline.n" "$baseline.n"
LC_ALL=C sort -u -o "$allowlist" "$allowlist"
LC_ALL=C comm -23 "$granted.n" "$baseline.n" > "$effective.n"
awk "$subsume" "$effective.n" "$effective.n" > "$effective"
LC_ALL=C comm -23 "$effective" "$allowlist" > "$unexpected"
LC_ALL=C comm -13 "$effective" "$allowlist" > "$missing"
if [ -s "$missing" ]; then
echo "allowlisted but not granted on this cluster:"
cat "$missing"
fi
if [ -s "$unexpected" ]; then
echo "FAIL: tenant-test-super-admin holds write verbs hack/e2e-tenant-super-admin-write-verbs.yaml does not allow:" >&2
cat "$unexpected" >&2
false
fi
rm -f "$review" "$allowlist" "$granted" "$granted.n" "$baseline" "$baseline.n" "$effective" "$effective.n" "$unexpected" "$missing"
}
@test "Deletion-protection VAP denies delete on labeled cozystack-version ConfigMap" {
# Locks down the contract delivered by packages/core/platform/templates/
# deletion-protection.yaml: a DELETE on any object carrying
# platform.cozystack.io/no-delete=true is rejected by the
# ValidatingAdmissionPolicy with the documented message, and the bypass
# path (remove the label, then delete) succeeds.
#
# This covers every regression the PR is meant to prevent in a single
# pass: capability gate inverted, binding objectSelector mistyped,
# validationActions flipped Deny→Warn, expression flipped false→true,
# label-key drift between the binding and the manifests.
# Preflight: VAP requires Kubernetes 1.30+. Skip on older clusters so
# the suite stays green where the capability gate intentionally elides
# the policy. Detect by attempting to fetch the policy by name; if the
# API is present, the resource will be retrievable, otherwise kubectl
# exits non-zero on an unknown resource type.
if ! kubectl api-resources --api-group=admissionregistration.k8s.io \
2>/dev/null | grep -qw validatingadmissionpolicies; then
skip "ValidatingAdmissionPolicy API not available on this cluster"
fi
kubectl get validatingadmissionpolicy cozystack-no-delete-guardrail
# The cozystack-version ConfigMap is created with the no-delete label
# baked in by the chart (templates/cozystack-version.yaml) and is
# backfilled by the migration on upgrades. Asserting the label is the
# precondition for the deny check below: if the label is gone the deny
# will not fire and the test would misreport as a pass on a regressed
# binding.
kubectl get configmap cozystack-version -n cozy-system \
-o jsonpath='{.metadata.labels.platform\.cozystack\.io/no-delete}' \
| grep -qx 'true'
# The actual deny check. Capture both stdout+stderr and exit code so a
# network/auth failure does not silently look like a deny success.
local output rc
output=$(kubectl delete configmap cozystack-version -n cozy-system 2>&1) \
&& rc=0 || rc=$?
echo "kubectl delete exit=$rc, output=$output"
# Delete MUST have failed: success means the VAP regressed.
[ "$rc" -ne 0 ]
# Assert the user-facing deny message is the one this PR ships — guards
# against expression flipped to "true" or message reworded away from the
# documented bypass. The CEL message is on one line in the api-server
# response, so grep for the literal substring with the --namespace flag.
echo "$output" | grep -q 'Deletion blocked: object carries platform.cozystack.io/no-delete=true'
echo "$output" | grep -q -- '--namespace'
# And confirm the ConfigMap is still there — a partial deny that races
# tombstone creation would also be a regression.
kubectl get configmap cozystack-version -n cozy-system >/dev/null
# Bypass path: remove the label, delete must succeed. Re-stamp the label
# afterward so the cluster ends the test in the same state it started.
kubectl label configmap cozystack-version -n cozy-system \
platform.cozystack.io/no-delete- --overwrite
# Stash the data so we can reconstruct after delete.
local version
version=$(kubectl get configmap cozystack-version -n cozy-system \
-o jsonpath='{.data.version}')
kubectl delete configmap cozystack-version -n cozy-system
# A bare `! kubectl get` is vacuous under cozytest's `set -e` (errexit is
# suppressed for any command whose status is inverted with `!`), so a
# delete that silently failed would not fail the test. Nor may the absence
# rest on the exit status alone: `kubectl get` exits 1 for a NotFound and 1
# for a connection, auth or discovery failure, so an api-server the test
# cannot reach would read as proof the delete worked. `--ignore-not-found`
# collapses the NotFound alone into success with empty output, leaving the
# status free to mean a failed read.
if ! still_there=$(kubectl get configmap cozystack-version -n cozy-system --ignore-not-found -o name); then
echo "FAIL: reading the cozystack-version configmap did not answer"; false
fi
if [ -n "$still_there" ]; then echo "FAIL: cozystack-version configmap must be gone after delete with the no-delete label removed"; false; fi
# Reconstruct: declarative apply matches the chart template at
# packages/core/platform/templates/cozystack-version.yaml — same label set
# AND the helm.sh/resource-policy: keep annotation that pins the ConfigMap
# across helm uninstall.
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: ConfigMap
metadata:
name: cozystack-version
namespace: cozy-system
labels:
platform.cozystack.io/no-delete: "true"
annotations:
helm.sh/resource-policy: keep
data:
version: "${version}"
EOF
}
@test "Tenant namespace delete policy refuses a direct delete and keeps the Tenant uninstall" {
if ! kubectl api-resources --api-group=admissionregistration.k8s.io \
2>/dev/null | grep -qw validatingadmissionpolicies; then
skip "ValidatingAdmissionPolicy API not available on this cluster"
fi
kubectl get validatingadmissionpolicy cozystack-tenant-namespace-delete-policy
kubectl get validatingadmissionpolicybinding cozystack-tenant-namespace-delete-policy
kubectl apply -f - <<EOF
apiVersion: apps.cozystack.io/v1alpha1
kind: Tenant
metadata:
name: deleteprobe
namespace: tenant-root
spec: {}
EOF
timeout 60 sh -ec 'until kubectl get hr/tenant-deleteprobe -n tenant-root >/dev/null 2>&1; do sleep 2; done'
kubectl wait hr/tenant-deleteprobe -n tenant-root --timeout=1m --for=condition=ready
local selected output rc still_there
selected=$(kubectl get namespaces --selector tenant.cozystack.io/tenant-root --field-selector metadata.name=tenant-deleteprobe -o name)
[ "$selected" = "namespace/tenant-deleteprobe" ]
output=$(kubectl delete namespace tenant-deleteprobe --dry-run=server 2>&1) && rc=0 || rc=$?
echo "kubectl delete exit=$rc, output=$output"
[ "$rc" -ne 0 ]
echo "$output" | grep -qF "ValidatingAdmissionPolicy 'cozystack-tenant-namespace-delete-policy'"
echo "$output" | grep -qF 'kubectl delete tenants.apps.cozystack.io deleteprobe --namespace tenant-root.'
kubectl delete tenants.apps.cozystack.io deleteprobe -n tenant-root --timeout=5m
kubectl wait namespace/tenant-deleteprobe --for=delete --timeout=5m
if ! still_there=$(kubectl get namespace tenant-deleteprobe --ignore-not-found -o name); then
echo "FAIL: reading the tenant-deleteprobe namespace did not answer"; false
fi
if [ -n "$still_there" ]; then echo "FAIL: deleting the Tenant must remove its namespace"; false; fi
}