Commit Graph
331 Commits
Author SHA1 Message Date
Myasnikov Daniil 74ac18e042 feat(apps): mark objects whose children exclude each other atomic
The worker image of a node pool takes one of builtin and factory, a
vm-disk source one of disk, http, image and upload, and the oidc
customConfig of a kubernetes cluster and of a monitoring stack one of
config and secretRef, and each chart refuses a spec that sets two. An
installation default for one child merged into an application that
chose another built exactly that spec, and nothing warned at create
time. The x-kubernetes-map-type: atomic marker makes the defaults
merge replace the object whole. Nothing else reads it, so existing
applications render as before.

The marker stays off objects whose fields must be set together or sit
beside independent fields, where replacing the object whole would drop
a default the user did not mean to override. The chart guide says when
to use it and when not to.

The tests run the merge against the four real schemas, and one more
pins that a pair like resources cpu and memory still merges field by
field.

Assisted-by: LLM
Signed-off-by: Myasnikov Daniil <myasnikovdaniil2001@gmail.com>
2026-11-27 07:39:01 +00:00
Myasnikov Daniil 8ef5ad1324 feat(api): treat objects that cannot be completed as one value
The merge completes an object field by field only when its schema
declares properties. An atomic object (x-kubernetes-map-type: atomic), a
dictionary value, a free-form object and an object that also takes
arbitrary keys are stored as written, so nothing can complete them
later. A default osImage.builtin plus a user's osImage.factory gave a
spec the kubernetes-nodes chart refuses to render, and an entry such as
a RabbitMQ vhost without roles was accepted and stored the same way.

The merge now copies such an object whole or leaves the user's value
alone, and an entry is validated for it as a whole, like an array row.
A branch of an allOf, anyOf or oneOf that names a property is judged
like the property declared next to it. An entry that gets this wrong is
skipped with a warning like any other invalid entry.

Assisted-by: LLM
Signed-off-by: Myasnikov Daniil <myasnikovdaniil2001@gmail.com>
2026-11-27 07:39:01 +00:00
Myasnikov Daniil 77d8bf5001 feat(api): apply installation defaults when creating applications
Defaults set by the administrator have to reach every application
kind, including ones from external catalogs, and give the same result
for the dashboard, Terraform and kubectl, so the merge runs in the API
server on create instead of in each client.

User values win over installation defaults, which win over the
developer defaults of the chart. Only objects with declared properties
merge recursively. Arrays, dictionaries and free-form objects are
replaced whole, so a pool that sets its own registry mirrors never
receives the platform entries. The entry is checked against the
application's OpenAPI schema before merging. CEL rules are left out of
that check, since a rule such as an immutability test has no meaning
on a partial object.

The ConfigMap is read through a cache limited to that one object, so
the API does not hold a watch on every ConfigMap in the cluster. A
missing ConfigMap means no defaults. One that cannot be read, or an
invalid configuration or entry, skips the defaults and the create goes
on with a warning, because a configuration mistake must not stop
applications from being created. Updates never apply defaults. The
ConfigMap rule the API already has covers the read, and its comment
now names this second user.

Assisted-by: LLM
Signed-off-by: Myasnikov Daniil <myasnikovdaniil2001@gmail.com>
2026-11-26 14:20:05 +00:00
Timofei Larkin 94c79925f8 feat(api): add the credentials API with mint and revoke subresources (#4921)
## What this PR does

Tenants read application passwords from Secrets today, and a leaked
password can't be taken back. This PR adds the platform side of the user
secrets API design (cozystack/community#137, ADR 0002): a password comes
out once from a mint, the next mint replaces it, and a revoke kills it.
The engines are converted in the PRs stacked on top, starting with
Postgres in #4922.

How it works:

- A kind's chart renders one `CredentialTemplate`
(`cozystack.io/v1alpha1`) per account: the username, the stored format
(`scram-sha-256`, `mysql-native`, `sha256` or `plaintext`), labels for
the account Secret, and an optional `valuesPath` for an operator that
reads no Secret.
- cozystack-controller keeps the account Secret `<template>.account`. It
seeds it on a release the API marked for seeding, adopts an unowned
Secret with the same username, leaves a foreign one alone with a
`SecretConflict` condition, and mirrors the record (origin, time, actor,
history) into the template status. For a `valuesPath` template it
maintains an optional `valuesFrom` entry on the release.
- `core.cozystack.io/v1alpha1` serves `credentials` as a read-only view
of the templates, plus `mint` and `revoke` subresources. A mint checks
the caller's `resourceVersion` precondition against the mirrored status,
builds the whole Secret and writes it in one request, or answers 409. It
never reads the Secret back. One API request writes one object; the
best-effort Event is the only extra write.
- The Application API marks a new release for seeding, keeps the account
`valuesFrom` entries when it rewrites a release, and refuses to delete a
suspended release that still has accounts, since Flux would skip its
uninstall.
- The dashboard gets a Credentials tab on the application page. It lists
accounts with origin and history; an administrator can mint or revoke,
and a viewer sees no buttons.

The application charts are untouched here: a kind starts using this only
when its chart renders templates. The `CredentialFormat` webhooks that
ADR 0002 describes are not in this PR, so `format.name` accepts only the
four built-in names for now.

### Screenshots

<img width="1440" height="900" alt="01-admin-tab"
src="https://github.com/user-attachments/assets/8c48086c-8f6c-4908-82c1-40e9078afe57"
/>

<img width="1440" height="900" alt="02-mint-dialog"
src="https://github.com/user-attachments/assets/802b2963-3f57-4c0b-ab84-f74bad28c343"
/>

<img width="1440" height="900" alt="03-mint-result"
src="https://github.com/user-attachments/assets/0e9ae3cc-7a3c-4daf-9a09-d4abf53bf70b"
/>

<img width="1440" height="900" alt="04-viewer-tab"
src="https://github.com/user-attachments/assets/10e940f2-4ceb-469d-a0f9-6c9d20a62919"
/>

### Downstream repositories

- [ ] No downstream repository is affected by this change
- [ ] [cozystack/website](https://github.com/cozystack/website) -
follow-up: needed, cozystack/website#753 should document the
`Credential` mint/revoke flow and the dashboard tab
- [ ]
[cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack)
- follow-up: needed later, a way to mint from Terraform; nothing breaks
in this PR alone
- [ ]
[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: none, the design is cozystack/community#137

### Release note

```release-note
feat(api): Add the credentials API. Applications that support it expose their accounts as `credentials.core.cozystack.io`; an administrator mints a password once with the `mint` subresource, and `revoke` invalidates it without issuing a new one. The dashboard shows a Credentials tab for such applications. No application uses it in this release on its own; see the per-engine changes.
```
2026-11-26 12:37:20 +03:00
Andrei KvapilandTimofei Larkin d1c5bc6fe2 feat(api): mark created releases for seeding and keep account values
A release the Cozystack API creates has only new accounts, so it is
marked for the CredentialTemplate controller to seed. The mark sits
outside the apps.cozystack.io- prefix, so an update keeps it.

An update rebuilds the HelmRelease from the Application, which lists
only the platform values; it now carries over the account valuesFrom
entries of the live release, since dropping them would take every
account's stored value out of the chart until the controller put them
back.

Deleting an application whose release is suspended and carries accounts
is refused with a conflict. Flux skips the uninstall of a suspended
release, so the database would keep running with its last passwords
after the account Secrets went with the templates.

Co-authored-by: Timofei Larkin <lllamnyp@gmail.com>
Assisted-by: LLM
Signed-off-by: Andrei Kvapil <kvapss@gmail.com>
2026-11-24 23:06:02 +01:00
Andrei KvapilandTimofei Larkin d65f86277c feat(api): serve Credentials with mint and revoke
A Credential is a view over a CredentialTemplate's status, so a list or
a get never reads a Secret. A mint builds the whole account Secret from
the template and writes it under the Secret resourceVersion the
template's status mirrors, so a concurrent mint or a seed in between
fails with a conflict instead of silently replacing a password someone
just received, and returns the plaintext once. A revoke stores a random
password and discards it. A dry-run writes nothing.

Each mint and revoke records an Event on the application naming the
account and the caller, never the value, which needs create on events.
The API review gate now captures a subresource registration such as
credentials/mint as a resource of its own rather than dropping it.

Co-authored-by: Timofei Larkin <lllamnyp@gmail.com>
Assisted-by: LLM
Signed-off-by: Andrei Kvapil <kvapss@gmail.com>
2026-11-24 23:06:02 +01:00
Andrei KvapilandTimofei Larkin 3c547721fa feat(credentials): add the account package
The Cozystack API, the CredentialTemplate controller and the migration
tooling must agree on an account Secret's name, its labels, the record
of who set the password and when, and the valuesFrom entry that carries
a stored value into a chart that reads no Secret. One package holds all
of it so the three cannot drift apart.

The values key of an account is the SHA-256 of its user name, which fits
a valuesFrom targetPath whatever characters the name holds.

Co-authored-by: Timofei Larkin <lllamnyp@gmail.com>
Assisted-by: LLM
Signed-off-by: Andrei Kvapil <kvapss@gmail.com>
2026-11-24 23:06:02 +01:00
Timofei Larkin 0cd89dc1c8 feat(credentials): add the built-in password formats
The platform stores what an engine checks a password against, not the
password: a SCRAM-SHA-256 verifier for PostgreSQL, the
mysql_native_password hash for MariaDB, the SHA-256 hex for ClickHouse,
and the plaintext only for an engine whose operator computes its own
verifier. The migration tooling imports the same package, so a converted
release and a mint store the same form.

CodeQL flags the SHA-1 and SHA-256 of a password as weak hashing of
sensitive data. Both are the forms the engines store and check against
and accept in no other form, and the design relies on the 32-character
random password rather than on the digest for strength, so the code says
that where the hashing happens.

Assisted-by: LLM
Signed-off-by: Timofei Larkin <lllamnyp@gmail.com>
Signed-off-by: Andrei Kvapil <kvapss@gmail.com>
2026-11-24 23:06:02 +01:00
Timofei Larkin 0ab26f7a8e feat(api): add the Credential kinds
Cozystack generates managed application passwords at Helm render time
and keeps them in a Secret tenants can read again at any time, which a
deployment whose policy requires a credential shown once cannot accept.
The accepted design moves generation into the platform: each account of
a converted application gets a core.cozystack.io Credential, the record
of who set its password and when, never the value, and its mint and
revoke subresources take a TokenRequest-shaped CredentialRequest.

Design: https://github.com/cozystack/community/blob/main/design-proposals/user-secrets-api/README.md

Assisted-by: LLM
Signed-off-by: Timofei Larkin <lllamnyp@gmail.com>
Signed-off-by: Andrei Kvapil <kvapss@gmail.com>
2026-11-24 23:06:02 +01:00
Aleksei Sviridkin 1485122e04 test(reservation): drop the shipped-declaration test
The test read packages/system/*-rd/cozyrds/*.yaml as raw files and
required one document and one metadata.name per file, a layout rule
no requirement asks for: an -rd chart may keep one definition per
variant under the same name and render one of them, and such a chart
failed every shipped test with "ApplicationDefinition ... is declared
in both". It also parsed cozy-lib's preset template with a regexp
pinned to 47 rows, pinned some seventy figures the shipped
declarations compute, and required the IaaS kinds to declare their
consumption while nothing reads the declarations yet.

Compiling and evaluating the shipped declarations is now checked on
the rendered charts, and the evaluator's own properties on fixtures.
Whether a declaration matches what its chart requests is a question
for a check against the rendered application, not for literals.

Fixes: 9a2830badf ("feat(api, kubernetes, virtual-machine): declare the IaaS kinds' reservation")
Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-24 11:49:42 +03:00
Aleksei Sviridkin 62ab75b002 test(reservation): exercise the evaluator on fixtures, not chart sources
The evaluator and classifier tests read the kinds' schemas from
packages/system/<kind>-rd/cozyrds/<kind>.yaml and the instance type
catalog from the kubevirt-instancetypes templates. That ties unit
tests of CEL semantics, quantity arithmetic and classification to how
the charts lay out their sources, so a chart change unrelated to the
evaluator could fail them.

Give them schemas cut down to the keys the declarations read and
instance types in the shapes the classifier has to tell apart. The
expected figures are unchanged. The exact product past int64, pinned
until now only through the shipped vm-instance declaration, gets a
case of its own. The shipped-catalog reader moves next to its last
user, the shipped-declaration test.

Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-24 11:49:40 +03:00
Aleksei Sviridkin 7380828271 fix(api): validate workload memory before storing an application (#5348)
## What this PR does

The application API accepts `memory: 8` and stores an eight-byte
workload request. On main, #5009 catches it later when Helm renders the
chart. This patch returns HTTP 422 to the caller on create, upsert, or
an update that introduces such a value.

The check follows declared workload resource fields in the chart schema.
An unrelated edit to an existing application with a smaller value still
passes admission. Existing chart checks continue to apply at render
time. A tenant's zero memory quota and arbitrary chart configuration
keep their existing meaning.

The regression tests exercise the REST create and update paths and
verify that a rejected edit leaves storage untouched. The same change
passed the application registry package tests on main and on
release-1.7. Related to #5004 and #5009.

### Downstream repositories

- [x] No downstream repository is affected by this change
- [ ] [cozystack/website](https://github.com/cozystack/website) -
follow-up:
- [ ]
[cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack)
- follow-up:
- [ ]
[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
fix(api): reject new workload memory values below 1Mi before storing an application. Updates to unrelated fields on existing applications with smaller values still pass admission.
```


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

## Summary by CodeRabbit

* **Bug Fixes**
* Application creation and updates reject workload memory settings below
the supported minimum of 1 MiB. Values at or above the minimum are
accepted, and existing below-minimum values may remain unchanged.
* Memory settings in quotas and free-form configuration are not
affected. When concurrent updates occur, memory is rechecked against the
latest stored values, preserving repairs and preventing stale updates
from restoring below-minimum settings.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-23 15:51:34 +03:00
IvanHunters 69ba61547e fix(api): make monitor watch versions usable as delete preconditions (#5326)
## What this PR does

A resourceVersion from an Application watch event triggered by a
WorkloadMonitor can now be used as a delete precondition. Today such a
delete always gets 409, because the event carries the monitor's version
and it never matches the HelmRelease.

The event keeps the monitor's version. #2356 added it so a status-only
change reaches informer handlers: client-go's shared informer treats an
update with an unchanged resourceVersion as a resync and hides it from
handlers that are not resyncing. That reason still holds.

The event is now built from a release no older than the monitor. The
cached release is used when it is new enough, otherwise the release is
read live. Before this, the spec came from a cache that can lag behind
the monitor, so the version and the spec in one event could describe
different states. The event carries the newer of the two versions.

A delete precondition is checked against the live release, and only an
older value is a conflict. A newer value is safe to accept because
HelmReleases and WorkloadMonitors live in one etcd, so their versions
come from one sequence. If the live release is still not newer than the
value the client sent, it has not changed since the event's spec was
read. A malformed precondition now gets 400 instead of 409.

Update is not touched. On main it overwrites the caller's
resourceVersion on conflict. #5234 makes it strict with the same rule.

### Limitations

- Late or replayed monitor event. The two backing watches are not
ordered, and a resumed watch replays monitors. When an event would
repeat a version the client may already hold, it falls back to the
monitor's own version, and the object's version steps back. A delete
with that version gets 409 at least until the object's next release
event or monitor change. No write is lost.
- Watch start. An application whose monitors are older than its release
gets an extra MODIFIED event with the lower monitor version. The same
409 window applies.
- Cost. At start and on reconnect a watch reads the release live once
per monitor written after its release last changed. After that it is at
most one live read per monitor status change per open watch. A monitor
whose release is gone or not cached yet now costs a live 404 per event,
where main skipped the event.
- A release event that comes after a monitor event already carried its
version is hidden from informer handlers. Its spec already arrived, and
each monitor's own change still arrives. With several monitors per
application it no longer corrects another monitor's status taken from a
lagging cache. That problem exists on main too: #5325.
- A live read gets one minute, retries included. When it runs out, the
watch ends and the client reconnects. There is no fallback to the cache:
it would pair a stale spec with a newer version again.
- Resuming a watch can still skip an undelivered HelmRelease change of
another application, same as on main: #5324.

Checked consumers: the in-tree console, the Terraform provider (GET then
PUT, no watch), and a downstream UI. None of them filters events by
resourceVersion equality.

### Screenshots

Not a UI change.

### Downstream repositories

- [x] No downstream repository is affected by this change
- [ ] [cozystack/website](https://github.com/cozystack/website) -
follow-up:
- [ ]
[cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack)
- follow-up:
- [ ]
[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
fix(api): a resourceVersion from a WorkloadMonitor-triggered Application watch event now works as a delete precondition, and the event's spec matches its version.
```


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

## Summary by CodeRabbit

* **Bug Fixes**
* Application watch events now report consistent resource versions,
including when updates arrive out of order or are replayed after
reconnecting.
* Watch events use current release data when cached data is missing or
outdated, retry transient read failures, and stop promptly when the
watch is canceled or times out.
* Deletion requests validate supplied resource versions against the
latest release, preventing stale requests from deleting newer changes
and returning clear errors for invalid versions.
* **Tests**
* Added coverage for watch-event version handling, read retries and
cancellation, replay behavior, and deletion requests with current,
stale, or invalid versions.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-23 15:02:12 +03:00
Aleksei Sviridkin ec8088e54c fix(api): skip an invalid ApplicationDefinition instead of failing startup (#5357)
## What this PR does

Refs #4976. This covers the startup half of that issue. Admission-time
validation is left for a follow-up, so the issue should stay open.

`resourceConfigFrom` built one resource per ApplicationDefinition and
returned the first error from `buildResourceFromCRD`. A single
definition with an unparseable `release.cozystack.io/*` annotation
therefore stopped cozystack-api for every tenant. The definition
controller rolls cozystack-api when those annotations change, so the bad
definition also triggered the rollout that then failed. Since #4308 a
connected repository can install definitions, so this is no longer only
an operator's own mistake.

Changes:
- `resourceConfigFrom` no longer returns on the first error. It leaves
the definition out of the served kinds, logs `Skipping invalid
ApplicationDefinition "<name>": <reason>`, and returns the errors so
tests can check them. This matches how a definition that loses its kind
to an older one is already left out.
- `buildResourceFromCRD` now also rejects an `openAPISchema` that isn't
valid JSON. `BuildPostProcessV2/V3` parse every served kind's schema
with `patchSpec` and fail the whole OpenAPI spec on one that doesn't
parse. Rejecting it here leaves only that kind out.
- The comment that called a bad annotation "a loud startup failure" is
updated.

Things I deliberately left out:
- Platform and repository definitions are treated the same. The issue
left open whether a broken platform definition should still fail hard.
Skipping keeps the API up either way, and the log line names the
definition, but I'm happy to make platform definitions fatal if you
prefer.
- Nothing surfaces the problem on the definition itself (an event or
status condition). cozystack-api doesn't write to ApplicationDefinitions
today, and that seemed like a separate change.
- Admission validation in
`internal/lineagecontrollerwebhook/appdef_validator.go` (point 1 of the
suggested fix). Its `failurePolicy: Ignore` means it couldn't be the
only guard anyway.

### How I checked it

- Added `TestResourceConfigFromSkipsInvalidDefinition` next to
`TestResourceConfigFromRegistersOwnerOnly`. It uses two valid
definitions, one with `release.cozystack.io/helm-install-timeout: ten
minutes`, and one with a truncated `openAPISchema`. Only the two valid
kinds are served, and both broken ones are reported with their names.
- `go vet ./pkg/cmd/server/` and `go test ./pkg/cmd/server/` pass.
- I haven't run this against a cluster.

### Screenshots

Not a UI change.

### Downstream repositories

- [x] No downstream repository is affected by this change
- [ ] [cozystack/website](https://github.com/cozystack/website) -
follow-up:
- [ ]
[cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack)
- follow-up:
- [ ]
[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:

This only changes how cozystack-api starts up. No API, values or CRD
changes.

### Release note

```release-note
fix(api): an ApplicationDefinition with an unparseable release.cozystack.io/* annotation or an invalid openAPISchema is now skipped and logged instead of stopping cozystack-api from starting.
```


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

## Summary by CodeRabbit

* **Bug Fixes**
* The server can start when an application definition has an invalid
timeout setting, malformed OpenAPI schema JSON, or other
resource-construction error. Invalid definitions are skipped and
reported, while valid definitions continue to be loaded and served. This
prevents a single invalid definition from blocking startup or preventing
other valid application definitions from being available.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-23 14:55:02 +03:00
Aleksei Sviridkin e86ef94185 feat(api, kubernetes, virtual-machine): declare tenant quota reservations on ApplicationDefinitions (#5349)
<!-- Thank you for making a contribution! Here are some tips for you:
- Use Conventional Commits for the PR title: `type(scope): description`
- Types: feat, fix, security (a fix that comes through a security
advisory), docs, style, refactor, perf, test, build, ci, chore
- Scopes are not an exhaustive list — pick the most specific scope for
the change and extend the list when a genuinely new area appears.
Examples:
- System components: dashboard, platform, operator, cilium, kube-ovn,
linstor, fluxcd, cluster-api
- Managed apps: postgres, mariadb, redis, kafka, clickhouse,
virtual-machine, kubernetes
- Development and maintenance: api, hack, tests, ci, docs, maintenance
- Breaking changes: append `!` after type/scope (`feat(api)!: ...`) or
add a `BREAKING CHANGE:` footer
- If it's a work in progress, consider creating this PR as a draft.
- Don't hesistate to ask for opinion and review in the community chats,
even if it's still a draft.
- Fixes merged to `main` reach the release lines the backport batch runs
for automatically, so do not open backport PRs by hand:
https://github.com/cozystack/cozystack/blob/main/docs/release/backports.md
-->

## What this PR does

Second phase of the accepted [tenant quotas as reservation
limits](https://github.com/cozystack/community/pull/48) design, after
the evaluator in #4983. An `ApplicationDefinition` can now declare what
an application of its kind reserves from its tenant's budget, as CEL
over its defaulted values, and the four IaaS kinds (`vm-instance`,
`vm-disk`, `kubernetes`, `kubernetes-nodes`) declare theirs. Nothing
reads the declarations yet: the usage oracle and the generalized
admission gate are the next phase, behind a flag.

- `fix(api)`: the evaluator could not sum quantities. The Kubernetes CEL
library returns a pointer from `add` and `sub`, which the evaluator did
not recognize, so any declaration summing components failed. Found while
writing the `kubernetes` declaration, which sums four control-plane
components.
- `fix(api)`: the evaluator refused exact products.
`resource.Quantity.Mul` returns false once the product leaves an int64
coefficient, not when it is wrong, so any fractional binary size above
about 8.5Gi (`20.5Gi × 3`) failed as an overflow.
- `fix(api)`: a null value stayed present wherever the schema had no
default to replace it, so `has()` saw a key Helm deletes, and evaluation
failed on a spec the chart renders.
- `feat(api)`: `spec.consumption` on `ApplicationDefinition` (`exempt`,
ordered `let` bindings, `resources` per quota key), owned as a whole so
that a binding and the expressions reading it are replaced together. The
evaluator's `Declaration` is now an alias of the API type. The CRD
rejects an exempt declaration that still carries expressions and a
non-exempt one that names no resource.
- `refactor(extra)`: ComputePlane's default `md0` pool now writes its
ceiling, instance type and disk size into its release instead of relying
on the pool chart's schema defaults, so the release alone says what the
pool can reserve. The rendered pool does not change.
- `feat(api, kubernetes, virtual-machine)`: the four declarations, each
following its chart's own precedence, plus a test that evaluates the
shipped declarations against the shipped instance types and preset
table, with the failures that must stay errors.

Validated locally: `go test ./pkg/reservation/` with each commit built
and tested on its own, `helm unittest` on computeplane and the touched
`-rd` charts, the four definitions plus three invalid ones validated
against the generated CRD schema and its CEL rules, and `make generate`
in the touched packages left the tree unchanged (with `cozyvalues-gen`
v1.7.0, the version CI pins).

Decisions worth a reviewer's look:

- **Proxmox worker pools reserve nothing.** Their VMs and disks run on
the external hypervisor, so they draw nothing from this cluster's
capacity. The `kubernetes` kind reserves one `services.loadbalancers` on
Proxmox, for its published apiserver Service, and one on KubeVirt when
the ingress addon is exposed by a load balancer, which the tenant
cluster's cloud controller realizes in the tenant namespace.
- **GPUs are not declared.** Their quota key is the device name
(`nvidia.com/<model>`), and `resources` keys are fixed strings.
Expressing them needs either a dynamic-key form in the declaration or a
class key for GPUs; I would rather settle that in its own change than
guess here. Until then the namespace `ResourceQuota` keeps bounding
them.
- **A spec the chart refuses to render is refused, not estimated.** A
partial `resources` block on a VM or a worker pool, a non-whole core
count or a memory below 1M fails the evaluation with the declaration's
reason, through a `fail(reason)` function the evaluator now offers, so
the gate in the next phase can answer with the same reason the render
would give.

Two decisions left for the next phase, both about what values alone
cannot see:

- A `vm-disk` whose `storage` is lowered keeps its larger volume,
because the chart only ever grows it, while its declaration reads the
lowered value. The admission gate has to refuse a storage decrease on
Update before it relies on this declaration.
- A worker pool's rollout runs one surge worker and its disk next to the
old ones (`maxUnavailable: 0` by default), which `maxReplicas` does not
cover. Whether that overlap counts against the tenant's budget or is
platform margin decides whether a tenant at its ceiling can roll a pool
at all.

Refs: cozystack/community#48

### Screenshots

<!-- REQUIRED for UI changes: attach screenshots or screen recordings
demonstrating
the visual impact of your changes. PRs with UI changes without
screenshots will not be merged. -->

### Downstream repositories

I walked the trigger map against the diff. Two repositories are
affected, and each has a follow-up issue:

- `cozystack/website`: the map lists "Change `ApplicationDefinition`
semantics". This adds a field nothing reads yet; documenting it seems
more useful once the gate in the next phase gives it an effect.
- `cozystack/external-apps-example`: the map lists changes to the
`ApplicationDefinition` CRD. The field is optional, so nothing breaks
there now, but the next phase refuses orders of a kind that declares
neither its consumption nor an exemption, so out-of-tree catalogs will
need a declaration before that phase is switched on.

- [ ] No downstream repository is affected by this change
- [x] [cozystack/website](https://github.com/cozystack/website) -
follow-up: cozystack/website#820
- [ ]
[cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack)
- follow-up:
- [ ]
[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:
- [x]
[cozystack/external-apps-example](https://github.com/cozystack/external-apps-example)
- follow-up: cozystack/external-apps-example#6
- [ ] [cozystack/examples](https://github.com/cozystack/examples) -
follow-up:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:

### Release note

<!--  Write a release note:
- Explain what has changed internally and for users.
- Start with the same `type(scope):` prefix as in the PR title
- Follow the guidelines at
https://github.com/kubernetes/community/blob/master/contributors/guide/release-notes.md.
-->

```release-note
feat(api, kubernetes, virtual-machine): ApplicationDefinitions can declare the tenant quota reservation of their kind, and the VM, disk, Kubernetes and worker pool kinds declare theirs. Nothing enforces the declarations yet.
```


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

## Summary by CodeRabbit

* **New Features**
* Application definitions can declare resource consumption for CPU,
memory, storage, and load balancers, with reservations based on
configured sizing and substrate choices.
* Kubernetes worker-pool reservations reflect replica counts, resource
overrides, instance types, and disk size; control-plane reservations
reflect component sizing and replica counts.
* VM instance and disk definitions report resource and storage
consumption.
* Default compute clusters now specify a node-pool limit of 10, an
instance type, and a disk size.
* **Validation**
* Invalid or incomplete resource sizing and consumption declarations now
produce errors, including mismatched CPU and memory settings.
Consumption declarations also enforce limits on resource entries and
bindings.
* **Bug Fixes**
* Null values are treated as absent when calculating reservations, and
quantity calculations support larger and fractional results.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-23 14:16:14 +03:00
Aleksei Sviridkin 82f6cab63f feat(apps): per-app schedulingClass field for selective workload placement (#2622)
<!-- Thank you for making a contribution! Here are some tips for you:
- Use Conventional Commits for the PR title: `type(scope): description`
- Types: feat, fix, docs, style, refactor, perf, test, build, ci, chore
- Scopes are not an exhaustive list — pick the most specific scope for
the change and extend the list when a genuinely new area appears.
Examples:
- System components: dashboard, platform, operator, cilium, kube-ovn,
linstor, fluxcd, cluster-api
- Managed apps: postgres, mariadb, redis, kafka, clickhouse,
virtual-machine, kubernetes
- Development and maintenance: api, hack, tests, ci, docs, maintenance
- Breaking changes: append `!` after type/scope (`feat(api)!: ...`) or
add a `BREAKING CHANGE:` footer
- If it's a work in progress, consider creating this PR as a draft.
- Don't hesistate to ask for opinion and review in the community chats,
even if it's still a draft.
- Add the label `kind/backport` if it's a bugfix that needs to be
backported to a previous version.
-->

## What this PR does

Closes the per-application gap of the SchedulingClass system. Today a
SchedulingClass can only be attached to a `Tenant`, which propagates it
to every workload in the namespace through the namespace label. The
lineage webhook already prefers the owner Application's class over the
namespace label ("owner Application field takes priority, then fall back
to namespace label" in `applySchedulingClass`), but
`Application.SchedulingClass()` was a `TODO` that always returned `""`,
so that path was unreachable.

### Changes

1. `feat(api)`: `Application.SchedulingClass()` reads the top-level
`schedulingClass` key from `Spec.Raw`. A nil spec, an empty or missing
field, and invalid JSON all return `""`, so the webhook falls back to
the namespace class.
2. `feat(apps)`: every managed application whose pods go through the
webhook gets an optional `schedulingClass` field. Under
`packages/apps/`: bucket, clickhouse, foundationdb, harbor, kafka,
kubernetes, mariadb, mongodb, nats, openbao, opensearch, postgres,
qdrant, rabbitmq, redis, tcp-balancer, valkey, vm-disk, vm-instance,
vpn. Under `packages/extra/`: bootbox, etcd, external-dns, ingress,
monitoring, seaweedfs. Skipped: `tenant` (already has the field), `vpc`
and `info` (no pods), `gateway` (not an Application), `computeplane` (it
only wraps `kubernetes` and `kubernetes-nodes` releases), and
`kubernetes-nodes` itself, whose worker pods resolve to the parent
Kubernetes application, so a class set on a pool would be ignored.
3. `fix(apps)`: the field is capped at 63 characters (`maxLength: 63` in
the schemas, `+kubebuilder:validation:MaxLength=63` in the Go types),
because its value becomes a Pod label value while a SchedulingClass name
may be up to 253 characters. As defence in depth, `applySchedulingClass`
skips only the label when the resolved name is not a valid label value,
keeping `schedulerName` and the annotation, so a long-named class
degrades to annotation-only injection instead of having the apiserver
reject every Pod.
4. `test(lineage-webhook)`: covers the owner-Application path, which the
existing tests never exercised (they all pass a nil owner): the app
class overriding the namespace class, the fallback when the field is
absent, empty or the spec is missing, and the label guard for an
over-long name.
5. `feat(tenant)`: the tenant chart gains `allowedSchedulingClasses`,
empty by default, written to the
`namespace.cozystack.io/allowed-scheduling-classes` namespace
annotation. A parent tenant with a class or a non-empty list passes its
list down unchanged, so a child tenant cannot widen it.
6. `fix(lineage-webhook)`: an application class applies only when the
namespace allows it and the SchedulingClass exists. Otherwise the pod
keeps the tenant class, where it previously got no scheduler at all when
the named class did not exist.
7. `feat(api)`: a ValidatingAdmissionPolicy on `apps.cozystack.io`
(tenants excluded) refuses a `spec.schedulingClass` that is neither the
tenant's own class nor in its allowed list. An update that keeps the
class is not refused, so an application whose class was later removed
from the list stays editable; the webhook keeps its pods on the tenant
class.
8. `docs(apps)`: the field description names the tenant setting that
decides which classes are accepted.

### Precedence

The tenant class is the administrator's placement constraint, so an
application may replace it only with a class the tenant allows. The
administrator lists those classes in the tenant's
`allowedSchedulingClasses`, which is empty by default: per-application
placement stays off until it is enabled, and every application runs
under the tenant class. Naming the tenant's own class is accepted
without an entry, since it is the same as leaving the field empty. Any
other value is refused at admission, and the webhook enforces the same
rule at pod admission, falling back to the tenant class rather than
dropping it.

### Use case

The tenant administrator allows the class (`allowedSchedulingClasses:
[co-region-prod]` on the Tenant). Combined with the
`scheduler.cozystack.io/scheduling-class` Pod label added in #2621, a
class name can double as a co-affinity group:

```yaml
apiVersion: cozystack.io/v1alpha1
kind: SchedulingClass
metadata: { name: co-region-prod }
spec:
  podAffinity:
    requiredDuringSchedulingIgnoredDuringExecution:
    - labelSelector:
        matchLabels:
          scheduler.cozystack.io/scheduling-class: co-region-prod
      topologyKey: topology.kubernetes.io/region
---
apiVersion: apps.cozystack.io/v1alpha1
kind: Postgres
metadata: { name: db, namespace: tenant-acme }
spec:
  schedulingClass: co-region-prod
---
apiVersion: apps.cozystack.io/v1alpha1
kind: VMInstance
metadata: { name: app, namespace: tenant-acme }
spec:
  schedulingClass: co-region-prod
```

The Postgres pods and the virtual machine land in the same region,
without pinning a specific one.

### Out of scope

Placement per replica role (primary or standby of a clustered database).
The role is assigned by the operator after election, while the webhook
acts at pod creation, so the future primary is unknown at that point.

### Verification

- `go test ./pkg/apis/... ./pkg/registry/... ./pkg/cmd/server/...
./internal/lineagecontrollerwebhook/...` passes. The behavioural webhook
tests were checked against the reverted code: without the label guard,
with `SchedulingClass()` returning `""`, and with the previous
resolution that skipped injection for an unknown application class, each
fails.
- The admission policy's decisions are evaluated against the chart
template with the apiserver's CEL compiler
(`pkg/registry/apps/application/scheduling_class_policy_test.go`), and
on a lab cluster through the aggregated cozystack-api: a class outside
the list is refused, a listed class or the tenant's own class is
accepted, and an update that keeps a class removed from the list is
accepted while one that changes it is refused
(https://github.com/cozystack/cozystack/pull/2622#issuecomment-7042784997).
- The tenant chart's inheritance of the list is covered by
`packages/apps/tenant/tests/namespace_allowed_scheduling_classes_test.yaml`,
which fails when a child tenant may widen its parent's list.
- `make generate` at the root and in every touched package
(cozyvalues-gen v1.7.0, the CI pin) leaves no diff.
- `make helm-unit-tests` passes; `hack/check-rd-presets.sh` and
`hack/check-commit-trailers.sh` pass.

### Screenshots

<!-- REQUIRED for UI changes: attach screenshots or screen recordings
demonstrating
the visual impact of your changes. PRs with UI changes without
screenshots will not be merged. -->

No UI change.

### Downstream repositories

<!--
Cozystack is upstream for repositories that are NOT kept in sync with it
automatically, and nothing in CI compares the two sides, so a change
here can break them silently.

Which change forces what, and which file to touch, is the trigger map in
docs/agents/contributing.md under "Downstream Repositories". Walk it
before you tick anything.

IF YOU ARE AN AI AGENT OR AN LLM, THIS IS PART OF THE TASK, NOT A FORM
TO FILL IN:

1. Walk the trigger map against the actual diff of this PR, file by
file. Do not decide from the PR title or from your memory of what you
changed.
2. For every repository you tick, open the follow-up PR there and link
it on the same line. A ticked box with no link claims work that does not
exist, which is worse than an empty box. Search that repository for an
open PR or issue covering it first, and link that instead of filing a
duplicate.
3. When the follow-up is out of scope, or needs a decision that is not
yours to make, open an issue in that repository instead, link that, and
say so in the PR body.
4. Do not tick "No downstream repository is affected" to make the
checklist go away. If you are unsure, leave every box empty and say so
in the PR body, so a human decides.
-->

Two repositories are reached by this diff. Both follow-ups are issues
rather than PRs, because each one only applies once this PR is merged:
`terraform-provider-cozystack` needs the field on every application it
models and `allowedSchedulingClasses` on the tenant, and `website` needs
the hand-written SchedulingClass guide to cover the per-application
field, the tenant's allowed list that gates it, and the Pod label.

- [ ] No downstream repository is affected by this change
- [x] [cozystack/website](https://github.com/cozystack/website) -
follow-up: cozystack/website#749
- [x]
[cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack)
- follow-up: cozystack/terraform-provider-cozystack#69
- [ ]
[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(apps): managed applications (bucket, clickhouse, foundationdb, harbor, kafka, kubernetes, mariadb, mongodb, nats, openbao, opensearch, postgres, qdrant, rabbitmq, redis, tcp-balancer, valkey, vm-disk, vm-instance, vpn, plus the bootbox, etcd, external-dns, ingress, monitoring and seaweedfs extras) accept a top-level `spec.schedulingClass` field, capped at 63 characters, which applies the named SchedulingClass to that application's pods in place of the tenant-level class. Only the tenant's own class or one listed in the tenant's new `allowedSchedulingClasses` (empty by default) is accepted; any other value is refused. This lets applications in the same tenant be co-located through a SchedulingClass podAffinity on the `scheduler.cozystack.io/scheduling-class` Pod label. An application whose class does not exist now keeps the tenant class instead of losing it.
```



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

## Summary by CodeRabbit

* **New Features**
* Added `schedulingClass` configuration across applications to select an
eligible scheduling class for newly created pods. Empty settings inherit
the tenant’s class; existing pods keep their assigned class until
recreated.
* Added tenant-level controls for which scheduling classes applications
may select. Invalid selections are rejected, and new pods fall back to
the tenant’s class if permission is removed.
* Added scheduling-class settings to application configuration displays.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-23 14:15:08 +03:00
Timofei Larkin 5daa04ea6e feat(networking): cozyplane eBPF CNI + cozyplane-kpr networking variant (drops Cilium) (#3149)
## What this PR does

Adds an **opt-in** `bundles.system.networkingVariant: "cozyplane"` for
the `isp-full` (Talos) bundle: it replaces kube-ovn, Cilium and
kube-proxy with the [cozyplane](https://github.com/lllamnyp/cozyplane)
eBPF CNI, its aggregated `sdn.cozystack.io` API server, and the
`cozyplane-kpr` socket-LB kube-proxy replacement. The default
`kubeovn-cilium` path renders identically to main; the selector is
refused outright on every other bundle variant (slim variants included),
where it would half-apply.

Components: three wrapper charts around cozyplane's upstream charts —
the CNI (`packages/system/cozyplane`), the kube-proxy replacement
(`cozyplane-kpr`) and the aggregated apiserver with its
etcd-operator-managed, PVC-backed etcd (`cozyplane-apiserver`) — plus
the Cilium policy CRDs shipped inert so stock charts install
(`cozyplane-cilium-crds`), a `cozystackAPI.serveSDN` toggle in
cozystack-api, and the platform wiring. The wiring threads the
platform's `networking.podCIDR`/`serviceCIDR` (and `clusterDNS`, the
service network's address plus 10 when unset) into the cozyplane
component, drops the packages that assume the replaced stack
(kubeovn-webhook/-plunger, multus, securitygroup-controller, the
virtualprivatecloud app), refuses the default `cilium` gateway class and
`networking.encryption.enabled` on the variant, and turns off sdn
serving in cozystack-api.

Bootstrap ordering: the CNI installs first with the kube API as its only
dependency and ships only the LOCAL group's CRDs
(`local.sdn.cozystack.io`, underlay IPAM); the tenant kinds (VPC, Port,
SecurityGroup, …) have **no CRDs** and are served only by the aggregated
apiserver, which installs later behind cert-manager, etcd-operator and
storage. Until it lands, `sdn.cozystack.io` is simply not served; there
is no takeover. On Talos the agent and kpr bootstrap against KubePrism,
since with no kube-proxy the `kubernetes.default` ClusterIP is unserved
until kpr itself runs.

Each cozyplane package follows the umbrella pattern: the upstream chart
is vendored verbatim under `charts/<name>` by `make update` from a ref
pinned in the wrapper's Makefile, and everything Cozystack-specific
lives in the wrapper — the Talos overlays, the apiserver's etcd storage
class and replica count, and two ClusterRoles that carry cozyplane's own
tenant roles into the `cozy:tenant` tiers by aggregation, so the list of
tenant kinds stays upstream's to maintain. Image pins are the digests
upstream pins for that ref, with multi-arch legs verified there. The
wrappers carry helm-unittest suites pinning the platform contract, the
egress args the platform threads included, and the platform suite covers
the variant's package set, the guards and the CIDR threading.

The variant is experimental: it has no e2e lane yet and is not for
production clusters, which the operator-facing values comment says.
**CiliumNetworkPolicy objects apply but are not enforced on this
variant** — tenant network isolation on the default network, the Cilium
host firewall and the platform components' own Cilium policies (several
of them `ingressDeny` rules native NetworkPolicy cannot express) are not
in effect, as stated in the values comment, the networking source and
the threat model; rebuilding them on what cozyplane does enforce (native
NetworkPolicy, its operator-only HostFirewall) is a follow-up.
cozystack-api's SecurityGroup (a restricted interface over
CiliumNetworkPolicy) is not served on the variant; cozyplane's own
SecurityGroup is the first-class tenant instrument for traffic inside
and across VPCs. The tenant-facing VPC application lands in #4508,
stacked on this PR.

### Screenshots

Not a UI change.

### Downstream repositories

The trigger map fires for cozystack/website (a new platform variant and
new `platform.values` keys); cozystack/website#815 documents both. It
arguably fires for terraform-provider-cozystack too (the SecurityGroup
spec differs per variant); that box is left unticked so a human decides.

- [ ] No downstream repository is affected by this change
- [x] [cozystack/website](https://github.com/cozystack/website) -
follow-up: cozystack/website#815
- [ ]
[cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack)
- follow-up:
- [ ]
[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(platform): opt-in networkingVariant "cozyplane" for the Talos bundle — replaces kube-ovn, Cilium and kube-proxy with the cozyplane eBPF CNI, its aggregated sdn.cozystack.io API server and a socket-LB kube-proxy replacement; CiliumNetworkPolicy objects are not enforced on this variant
```

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

## Summary by CodeRabbit

* **New Features**
* Added an opt-in Cozyplane networking variant with cluster DNS
configuration, CNI, and service routing.
* Added a Cozyplane API service for tenant networking resources, with
tenant edit and view permissions.
  * Added control over whether the existing SDN API is served.
* Gateway configurations using an unavailable class are now rejected
with guidance.
* **Important Limitations**
* Cozyplane does not enforce existing Cilium network policies or
platform Cilium rules. Tenant traffic isolation may require native
NetworkPolicies; some platform rules require operator-managed
HostFirewall policies.
* Cozyplane networking does not support encryption or the default Cilium
Gateway class, and requires pod and service CIDRs.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-23 09:31:43 +00:00
Aleksei Sviridkin 02b8a26738 fix(securitygroups): reject port ranges and malformed FQDNs on the SecurityGroup path (#5134)
<!-- Thank you for making a contribution! Here are some tips for you:
- Use Conventional Commits for the PR title: `type(scope): description`
- Types: feat, fix, docs, style, refactor, perf, test, build, ci, chore
- Scopes are not an exhaustive list — pick the most specific scope for
the change and extend the list when a genuinely new area appears.
Examples:
- System components: dashboard, platform, operator, cilium, kube-ovn,
linstor, fluxcd, cluster-api
- Managed apps: postgres, mariadb, redis, kafka, clickhouse,
virtual-machine, kubernetes
- Development and maintenance: api, hack, tests, ci, docs, maintenance
- Breaking changes: append `!` after type/scope (`feat(api)!: ...`) or
add a `BREAKING CHANGE:` footer
- If it's a work in progress, consider creating this PR as a draft.
- Don't hesistate to ask for opinion and review in the community chats,
even if it's still a draft.
- Add the label `kind/backport` if it's a bugfix that needs to be
backported to a previous version.
-->

## What this PR does

Fixes #5130.

`validatePortRules` sent any non-numeric port to `IsValidPortName`, so
`"80-90"` came back as "must contain at least one letter (a-z)". A
`first-last` value now gets "port ranges are not supported; list each
port as its own entry" on the same field. `PortProtocol` carries a
single port and Cilium's `endPort` is not exposed, so the limit itself
is unchanged.

`validateFQDNs` only checked that a selector was not empty. A malformed
`matchName` or `matchPattern` passed, and the backing write then failed
on the CiliumNetworkPolicy CRD, which surfaced as an error about a
`cilium.io` object. The validator now applies the CRD's own rules for
`spec.egress[].toFQDNs[]`, with a field error on the SecurityGroup path:
`^([-a-zA-Z0-9_]+[.]?)+$` for `matchName`, `^([-a-zA-Z0-9_*]+[.]?)+$`
for `matchPattern`, `maxLength: 255` for both, and the `oneOf` that
allows only one of the two per selector. These are copied from the CRD
served by Cilium 1.19.5 and match the agent's `FQDNSelector.sanitize`,
which also refuses a selector that sets both fields.

`TestCreateRejectsInvalidPortOrFQDN` lists each rejected value and
checks that the error carries a single cause, on the expected field,
with the expected reason. All 13 cases fail on `main`.
`TestCreateAcceptsValidPortOrFQDN` lists accepted values (named port
`http-8080`, trailing dot, underscore labels, `**.` prefix, infix and
lone `*` patterns, 255 characters) and checks they project 1:1. `go test
./pkg/registry/sdn/...` passes.

As a cross-check, every FQDN value in both tables was also sent to the
CiliumNetworkPolicy CRD of a lab running Cilium 1.19.5, with `kubectl
create --dry-run=server`. The CRD rejects exactly the values the
validator rejects and accepts exactly the ones it accepts.

### Screenshots

<!-- REQUIRED for UI changes: attach screenshots or screen recordings
demonstrating
the visual impact of your changes. PRs with UI changes without
screenshots will not be merged. -->

### Downstream repositories

The diff touches `pkg/registry/sdn/securitygroup/validate.go` and its
tests only: the SecurityGroup schema does not change, and no package,
chart, CRD, `hack/` or convention is touched. Neither the website nor
the Terraform provider documents or models SecurityGroup fields.

<!--
Cozystack is upstream for repositories that are NOT kept in sync with it
automatically, and nothing in CI compares the two sides, so a change
here can break them silently.

Which change forces what, and which file to touch, is the trigger map in
docs/agents/contributing.md under "Downstream Repositories". Walk it
before you tick anything.

IF YOU ARE AN AI AGENT OR AN LLM, THIS IS PART OF THE TASK, NOT A FORM
TO FILL IN:

1. Walk the trigger map against the actual diff of this PR, file by
file. Do not decide from the PR title or from your memory of what you
changed.
2. For every repository you tick, open the follow-up PR there and link
it on the same line. A ticked box with no link claims work that does not
exist, which is worse than an empty box. Search that repository for an
open PR or issue covering it first, and link that instead of filing a
duplicate.
3. When the follow-up is out of scope, or needs a decision that is not
yours to make, open an issue in that repository instead, link that, and
say so in the PR body. Do not push a speculative PR into another
repository just to fill a line here.
4. Do not tick "No downstream repository is affected" to make the
checklist go away. If you are unsure, leave every box empty and say so
in the PR body, so a human decides.
-->

- [x] No downstream repository is affected by this change
- [ ] [cozystack/website](https://github.com/cozystack/website) -
follow-up:
- [ ]
[cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack)
- follow-up:
- [ ]
[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

<!--  Write a release note:
- Explain what has changed internally and for users.
- Start with the same `type(scope):` prefix as in the PR title
- Follow the guidelines at
https://github.com/kubernetes/community/blob/master/contributors/guide/release-notes.md.
-->

```release-note
fix(securitygroups): a port range now gets a clear "port ranges are not supported" error, and a malformed toFQDNs matchName or matchPattern is rejected on the SecurityGroup field instead of failing on the backing CiliumNetworkPolicy.
```


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

## Summary by CodeRabbit

* **Bug Fixes**
* Security group egress rules now reject port ranges with a clear
validation error; list each port separately.
* FQDN selectors are checked for supported name or pattern formats,
required selector fields, and a maximum length of 255 characters.
* Invalid egress settings are rejected without creating a policy, while
valid ports and FQDN selectors can be saved.
* **Documentation**
  * Updated guidance to reflect egress port and FQDN validation rules.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-23 11:51:46 +03:00
Yan Bondarenko 46c70422c4 fix(api): validate workload memory before storing an application
A memory quantity without a unit is measured in bytes. Reject new values
below 1Mi before storing them, while allowing unrelated API edits to
applications that already carry a smaller value. The check runs against
the live release right before the write, so a stale value read at the
start of Update cannot overwrite memory another writer has fixed since.

Assisted-by: LLM
Signed-off-by: Yan Bondarenko <202671653+yankawai@users.noreply.github.com>
2026-11-23 11:33:10 +03:00
Mattia Eleuteri d3804ebea9 feat(api): refuse an application scheduling class its tenant does not allow
The lineage webhook keeps a pod on the tenant class when the
application names a class the tenant does not allow, but it can only
log that, on a pod the user never looks at. Refusing the application
at admission puts the error where the field was set, with the list of
classes that would be accepted.

An update that keeps the class is not refused, so an application whose
class was removed from the list after admission stays editable; the
webhook already keeps its pods on the tenant class. Tenants are left
out, because their spec.schedulingClass is the child tenant's class,
which the tenant chart's inheritance governs.

Users read the field description in the dashboard form and the API
schema, so it names the tenant setting that decides which classes are
accepted, says that only setting another value is refused, and that a
pod gets its class when it is created, so running pods keep theirs. The
field sits in its own README section, since a reader looking for
placement would not look under the unrelated heading it was appended
to.

Assisted-by: LLM
Signed-off-by: Mattia Eleuteri <mattia@hidora.io>
2026-11-23 08:05:09 +01:00
Mattia Eleuteri e67a514903 fix(lineage-webhook): keep the tenant class when an application's is refused
The webhook fell back to the tenant class only when an application
left spec.schedulingClass empty. A value naming a class that does not
exist, or one the tenant does not allow, left the pod with no
scheduler at all, so a typo, or a deliberate bogus name, in any
application lifted the placement constraint the tenant administrator
had set.

Admission sees the application only once, so a class removed from the
allowed list afterwards has to be caught here as well. Naming the
tenant's own class needs no entry in the list, being the same as
leaving the field empty.

The application class is looked up once, so a class deleted between
deciding and injecting cannot leave the pod with neither class. A
lookup error fails the admission instead of counting as absence:
otherwise a timeout or a 5xx from the apiserver would admit the Pod on
the default scheduler, outside the tenant's constraint, until it was
recreated. Under failurePolicy Fail its controller retries. Only an
absent class, or an absent SchedulingClass CRD, means there is nothing
to inject.

Assisted-by: LLM
Signed-off-by: Mattia Eleuteri <mattia@hidora.io>
2026-11-23 08:05:08 +01:00
mattia-eleuteri a5717f61cd feat(api): implement Application.SchedulingClass() from spec.schedulingClass
The lineage webhook already prefers the owner Application's class over
the namespace label when it injects a scheduler, but SchedulingClass()
was a stub that always returned "". A class could therefore only be
chosen for a whole tenant, never for one application.

A spec that cannot be parsed yields no class, so its pods keep the
tenant class rather than failing admission.

Assisted-by: LLM
Signed-off-by: Mattia Eleuteri <mattia@hidora.io>
2026-11-23 08:04:59 +01:00
Mattia Eleuteri 9a2830badf feat(api, kubernetes, virtual-machine): declare the IaaS kinds' reservation
VMs, disks, Kubernetes control planes and worker pools are where the
virtualization overhead that breaks pod-unit quota accounting lives,
so they are the first kinds to state their reservation in the terms a
tenant buys: guest cores and memory by instance-type class, declared
disk sizes, and the load balancers a spec publishes.

Each declaration follows its chart's own precedence rather than one
rule for all: a VM is sized by resources only when cpu, sockets and
memory are all set, a worker pool when cpu and memory are non-zero,
and a control-plane component fills its preset per key. A worker pool
reserves maxReplicas because the cluster-autoscaler grows it without
writing the pool, and reserves nothing on Proxmox, whose workers run
on the external hypervisor. GPUs are not declared: their quota key is
the device name, which a fixed key cannot express.

The test evaluates the shipped declarations against the shipped
instance types and preset table, including the failures that must
stay errors rather than smaller figures.

Assisted-by: LLM
Signed-off-by: Mattia Eleuteri <mattia@hidora.io>
2026-11-23 08:03:52 +01:00
Mattia Eleuteri fa7c94507a feat(api): carry a consumption declaration on ApplicationDefinition
Tenant quotas are to be enforced against what an application declares
rather than against the pods it renders, and the apiserver must hold no
per-kind knowledge of how to compute that, so that a kind shipped from
an out-of-tree catalog can take part. The declaration therefore lives
on the kind's definition, next to the schema it is evaluated against.

The evaluator's Declaration becomes an alias of the API type, so a
definition is compiled exactly as it was read, with no conversion that
could drift from it. The CRD refuses an exempt declaration that still
carries expressions and a non-exempt one that names no resource, so an
omission cannot pass for a zero reservation.

Nothing reads the field yet.

Assisted-by: LLM
Signed-off-by: Mattia Eleuteri <mattia@hidora.io>
2026-11-23 08:03:50 +01:00
Mattia Eleuteri a069636a4e fix(api): read a null value as absent in a reservation declaration
Helm deletes a key its values set to null, so a chart treats
`resources: {cpu: null}` as if cpu were not set. The evaluator's
defaulting replaced a null only where the schema had a default to put
in its place, so elsewhere the key stayed present: has() reported it,
and an expression reading it failed, for instance with "no such
overload: matches", on a spec the chart renders.

Nulls are dropped after defaulting, so a schema default still fills a
nulled key the way it fills an absent one.

Tested with a nulled key that has no default.

Fixes: 89aba6e104 ("feat(api): add the reservation evaluator for tenant quotas")
Assisted-by: LLM
Signed-off-by: Mattia Eleuteri <mattia@hidora.io>
2026-11-23 08:03:49 +01:00
Timofei Larkin 7375196b8b test(cozystack-api): require core in OpenAPI v2
An empty v2 path set satisfied the check that no sdn path is listed.

Assisted-by: LLM
Signed-off-by: Timofei Larkin <lllamnyp@gmail.com>
2026-11-20 00:32:01 +01:00
Adham Kiwan 918a60462e fix(api): skip an invalid ApplicationDefinition instead of failing startup
cozystack-api built its resource config from every ApplicationDefinition
and returned the first error, so one definition with an unparseable
release.cozystack.io/* timeout annotation stopped the API for every
tenant. The definition controller rolls cozystack-api when those
annotations change, so the bad definition also triggered the failing
rollout. Since a connected repository can install definitions, this is
no longer limited to an operator's own mistake.

Leave such a definition out of the served kinds and log it, the same way
a definition that loses its kind to an older one is left out. An
openAPISchema that is not valid JSON is rejected at the same point:
the OpenAPI post-processors would otherwise fail the whole spec on it.

Refs: #4976
Assisted-by: LLM
Signed-off-by: Adham Kiwan <adhamkiwan@outlook.com>
2026-11-19 14:16:22 +02:00
Timofei Larkin 952e05836d fix(cozystack-api): stop serving sdn.cozystack.io when serveSDN is off
serveSDN=false removed only the sdn APIService. The binary still
installed the group, so its /openapi/v3 index kept listing
apis/sdn.cozystack.io/v1alpha1 beside the server that owns the group
(cozyplane-apiserver in the cozyplane variant). kube-aggregator merges
every APIService backend's index and serves a group-version from
whichever backend it meets first in map order, so the index hash and the
spec request often land on different backends. The backend answers the
stale hash with a 301, the aggregator refuses to forward it, and
`kubectl explain` fails for every kind in the group with "the backend
attempted to redirect this request, which is not permitted"; when the
two do match, kubectl gets cozystack-api's SecurityGroup-only spec and
reports the other kinds as missing.

The chart now passes --serve-sdn=false with serveSDN off, and the
server then leaves the group uninstalled.

Assisted-by: LLM
Signed-off-by: Timofei Larkin <lllamnyp@gmail.com>
2026-11-19 12:04:16 +01:00
Mattia Eleuteri 6f705fe0e9 fix(api): keep exact quantity products the int64 coefficient cannot hold
resource.Quantity.Mul returns false when the product no longer fits an
int64 coefficient, not when it is wrong: it carries on in arbitrary
precision. The evaluator read that as an overflow and failed with
"quantity 20992Mi * 3 overflows" for any fractional binary quantity
above about 8.5Gi, since such a quantity is stored at a scale whose
coefficient leaves int64 long before its value does. Declared sizes
like 20.5Gi are ordinary, so every pool or disk using one could not be
reserved.

Tested with fractional Gi and Ti quantities scaled directly and after a
sum.

Fixes: 89aba6e104 ("feat(api): add the reservation evaluator for tenant quotas")
Assisted-by: LLM
Signed-off-by: Mattia Eleuteri <mattia@hidora.io>
2026-11-18 15:58:55 +01:00
Mattia Eleuteri a9245ec165 fix(api): accept the quantities the CEL add and sub return
The Kubernetes CEL quantity library returns a pointer from add and sub,
while quantity() and the evaluator's own mul return a value. The
evaluator matched only the value form, so any declaration that summed
quantities failed with "expression returned kubernetes.Quantity,
expected an int, a double, a string or a quantity", or with "no such
overload" when the sum was then scaled with mul. A kind whose
reservation is a sum of components, such as a control plane, could not
be declared at all.

Both forms are matched by type rather than read through Value(), which
would first materialize any other result, a list included, outside the
expression's cost limit.

Tested with add, sub, add of an int, and mul on either side of a sum.

Fixes: 89aba6e104 ("feat(api): add the reservation evaluator for tenant quotas")
Assisted-by: LLM
Signed-off-by: Mattia Eleuteri <mattia@hidora.io>
2026-11-18 15:58:54 +01:00
Aleksei Sviridkin dff4553216 fix(api): bound live release reads in application watches
A stalled live release read holds the whole application watch event loop.
End the watch when a refresh runs out of time so clients can reconnect
without relying on stale cached release data.

Fixes: 0ccb3fead7 ("fix(api): retry the live release read behind a monitor event")
Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-18 17:29:29 +03:00
Aleksei Sviridkin d88322197f chore(deps): roll up Renovate updates and raise dependencies to latest stable (#4869)
## What this PR does

One PR instead of separate Renovate PRs. Go modules, Dockerfile base
images and GitHub Actions move to newer versions that build and pass the
tests. Where a newer version is known to break something, it stays
behind, and `.github/renovate.json` holds it with the reason in the rule
description.

The tests come first, in their own commits:

- `make go-unit-tests` runs the Go tests under `pkg/` and `cmd/`, except
the backport-batch suite, which keeps its own target. The apiserver
serializer and fuzz tests, the generated OpenAPI and applyconfiguration
suites, the apis packages and the controller, operator and
observability-proxy commands did not run in CI before.
- The apps API surface that apiserver libraries shape is pinned:
server-side apply, content negotiation, Table output on watch, the
served OpenAPI v2 and v3 documents, and building the server without
etcd. Two answers look wrong and are pinned as they are today: applies
from different field managers never conflict (#4857), and protobuf is
refused with 406 even when the client offers JSON as a fallback (#5297).
- New tests cover the kubeovn webhook patch, the token proxy session
cookie and the mount-utils behaviour the kubevirt CSI node service
relies on.
- `hack/image-smoke.bats` checks the tools the CSI, LINSTOR, multus,
Harbor and redis-backup images take from their base images or build
stages, and that the kubevirt CSI node plugin and its sidecars need no
more than x86-64-v2. Each PR build job runs it against the images it
pushed; forks and the unit lane run no container.

The tests found two bugs:

- The kubeovn webhook dereferenced a nil pointer on an admission review
without a request, so the caller got a dropped connection instead of a
400.
- The token proxy cookie refresh never fired: securecookie decodes the
session times as int64 and the refresh looked for float64, so the
`--cookie-refresh=1h` the chart sets did nothing. A refreshed cookie
keeps the token's expiry. A session too large to encode now shows an
error at sign-in and leaves the current cookie alone on refresh.

What moved:

- GitHub Actions to their Node 24 majors. The flux action stays on the
tag of the Flux CLI it installs. The release job's checkout no longer
persists credentials, so its staging branch push uses the App token.
- Go 1.27.2 for the toolchain and builders. Builds that reproduce an
upstream release keep the Go upstream uses: Harbor, cilium-operator,
SeaweedFS and the chainsaw stage of the e2e sandbox.
- controller-runtime v0.25.2, gateway-api v1.6.3 on the minor of the
installed v1.6.1 CRDs, cel-go v0.30.0, grpc v1.84.0, etcd v3.7.2,
cert-manager v1.21.2, kubevirt csi-driver f10ae94 on Kubernetes v0.37.1.
- Node 24 for the dashboard console.

Held back, each with its reason in the Renovate rule:

- cel-go stays below v0.31: the old repository has no tags past v0.30.0,
and v0.32 moves to cel.dev/cel-go, which k8s.io/apiserver does not
import.
- kube-openapi stays on the commit its dependencies require, and
structured-merge-diff stays on v6, because k8s.io/apimachinery v0.37
does not compile against v7.
- The Flux API modules stay on the Flux v2.8 line the platform installs.
- gomodules.xyz/jsonpatch stays on v2, which controller-runtime's
admission.Patched takes.
- jwx stays on v3: v4 removes jwk.Cache, which the token proxy's JWKS
refresh is built on.
- kubevirt.io/api and the CDI API stay where upstream csi-driver builds.
- The kubevirt CSI driver image stays on AlmaLinux 9, because AlmaLinux
10 builds its amd64 userland for x86-64-v3.
- shadowbox stays on node 18, which outline-server declares in its
engines.
- The e2e sandbox stays on Ubuntu 24.04. 26.04 ships uutils coreutils,
whose `date` costs about 4x per call, and the test harness forks it per
traced line, which adds about ten minutes to the install phase.
- clastix/kubectl stays on v1.32 for the cleanup hooks, within kubectl's
one-minor skew.

The cert-manager Go module (v1.21.2) is one minor ahead of the installed
chart (v1.20.2). The Certificate objects the gateway controller writes
serialize the same either way.

`api/apps/v1alpha1` now requires Go 1.27.2, which applies to every
module that imports the published types.

The Linux run with Go 1.27.2 was done before the rebase onto current
main, and the rebased head has not been through it yet. There the five
modules built, vetted, tested and tidied cleanly, and the repository
unit, controller and envtest lane passed. `go test -race` passed in four
modules. In the root module it failed only on a pre-existing data race
in the workload monitor tests (#5296), which main has too. The image
smoke checks run in this PR's CI.

### Screenshots

No UI change.

### Downstream repositories

`api/apps/v1alpha1` moves to `go 1.27.2`, and
cozystack/terraform-provider-cozystack imports it, so that repository is
affected but needs no action. Its box stays empty for that reason, and
so does the "not affected" one.

- [ ] No downstream repository is affected by this change
- [ ] [cozystack/website](https://github.com/cozystack/website) -
follow-up:
- [ ]
[cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack)
- follow-up: none needed, because its Renovate raises the go directive
together with the pin bump and its CI takes Go from `go.mod`; the only
effect is that the provider's minimum Go becomes 1.27.2.
- [ ]
[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
chore(deps): move the toolchain and builder images to Go 1.27.2 and raise Go modules, base images and GitHub Actions to newer working releases; the dashboard token proxy now refreshes its session cookie, and the kube-ovn webhook rejects an admission review without a request instead of dropping the connection.
```
2026-11-18 14:42:34 +03:00
Aleksei Sviridkin 48d83b5f77 test(api): cancel monitor live reads before retrying
FakeWatcher.Modify synchronizes event receipt, not processing. A test
that cancels after sending the event can lose the retry-delay window
and observe more reads even when cancellation works correctly.

Cancel at the first failed live read and wait for its context to end
before returning the error, so the exact read count does not depend
on which goroutine runs next.

Fixes: 0ccb3fead7 ("fix(api): retry the live release read behind a monitor event")
Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-17 23:02:58 +03:00
Aleksei Sviridkin 263407a73f fix(api): leave golden images whose importer keeps failing out of the image options
CDI moves an import to Failed only on a fatal error such as a checksum
mismatch, so the picker still offered a golden whose URL is unreachable:
its importer restarts with back-off while the DataVolume stays in
progress. Drop a golden whose importer restarted at least three times
and is not running, the test the kubernetes-nodes chart applies before
cloning.

Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-17 11:20:18 +03:00
Aleksei Sviridkin 0ccb3fead7 fix(api): retry the live release read behind a monitor event
When the cached release is older than the monitor revision, the watch
reads the release live so that an event never pairs a stale spec with
the monitor's version. A transient error on that read dropped the
monitor event. Both streams are plain API watches, so nothing replayed
it, and a client kept the old WorkloadsReady state until the next
change of either object.

Retry the live read a few times before giving the event up. This
covers a failure shorter than the retry window; a longer one still
drops the event, as a cache miss did before. A release that is gone is
not retried: the event is dropped after one read. The live reads run
under a context that Stop cancels, so a stopped watch does not wait on
the API server. The tests also pin the two paths that were untested: a
release the cache has not seen yet is read live and delivered, and a
release that is gone everywhere produces no event.

Fixes: f13362b0ee ("fix(api): make monitor watch versions usable as delete preconditions")

Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-16 13:56:06 +03:00
Aleksei Sviridkin c4388af9a3 test(make): run the pkg and cmd Go tests in go-unit-tests
go-unit-tests ran a hand-picked list of packages, so the apiserver
serializer and fuzz round-trip tests, the generated applyconfiguration
and openapi suites, the apis packages and the controller, operator and
observability-proxy commands never ran in CI. Those are the tests a
Kubernetes library bump can break. The backport-batch suite stays out:
it drives real git repositories for minutes and keeps its own target.

The apps API surface that apiserver libraries shape gets its own tests:
server-side apply, content negotiation, Table output on watch, the
served OpenAPI v2 and v3 documents and building the server without
etcd. They record today's answers, including two that look wrong:
applies from different field managers never conflict because the
storage keeps no managedFields, and protobuf is refused with 406 even
when the client offers JSON as a fallback.

Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-16 01:07:34 +03:00
myasnikovdaniil aa36d3fad6 fix(kubernetes)!: remove the talos block and other leftovers of the worker pool split (#5191)
## What this PR does

Cleanup after the Kubernetes app was split into `Kubernetes` (control
plane and addons) and `KubernetesNodes` (one release per worker pool):
what the split left behind in values, docs, templates and tests.

### Kubernetes

The `Kubernetes` application has no `talos` field any more. Worker pools
are `KubernetesNodes` resources and take their Talos release, image,
installer and registry mirrors from their own `talos` and `osImage`, so
the cluster's copies did nothing. The last one, `talos.version`, fed a
duplicate of the Talos to Kubernetes support-matrix check. The pool
chart already runs that check against the Talos release each pool
actually boots, including one picked through an `osImage` override; the
cluster's copy compared the Kubernetes version against a release no node
runs. A stored spec that still carries `talos.*` keeps rendering,
because the values schema does not close the object and the API does not
validate `spec` against it, and a unit test pins that.

The pool's check now has render coverage. Its own suite pins the
pairings it must accept, and a bats test renders the refusals through
`talos.version`, `osImage.factory.version` and `osImage.builtin.version`
with schema validation skipped, since the schema offers no Kubernetes
version the matrix refuses.

I fixed the README and field descriptions that described behavior the
chart no longer has, or never had: a dedicated etcd cluster, a
`blockSize.matchVolume` setting that does not exist, a default `md0`
pool, the host default, the substrate mismatch behavior, and rollout
phase names. The README's Breaking Changes section becomes a pointer to
the per-release upgrade notes on cozystack.io. Unused helpers and stale
comments are removed; the chart renders the same bytes.

### KubernetesNodes

Five field descriptions and the `talos` block told users to keep them in
sync with parent fields that do not exist. NOTES warned about colliding
with a parent-managed `md0` pool, although the parent renders no pools
and `md0` is the normal name of a pool. The installer image was credited
to an upgrade Job that never runs one. The values descriptions, README
intro and NOTES now say what the chart renders today, including which
fields have no effect on `substrate: proxmox`: `storageClass`,
`diskSize`, `instanceType`, `talos.imageFactoryURL` (beyond its format
check) and `talos.imageFactoryCA`.

The render error for a pool whose MachineDeployment belongs to another
release told users to remove the pool from the parent's `nodeGroups`,
which cannot clear the conflict. It now names a remedy that works.
Split-era history is gone from Helm and test comments, along with two
`storageClass` fallbacks that can only return the value they fall back
from, a constant variable, and two `.helmignore` rules that match
nothing.

The tenant pod and service CIDRs are literals in both charts, and
nothing checked that they agree. A new bats test renders both charts and
fails when they differ.

No rendered manifest of the pool chart changes. I rendered it for the
snapshot values, GPU, kubelet-override, factory/CA, storageClass
variants and three Proxmox variants on main and on every commit, and the
output is byte-identical. The snapshot and TalosConfigTemplate hash
tests pass unchanged, so no worker rolls. YAML comments inside the
hashed machine config and machine template are left as they are for that
reason.

### The rule

`docs/agents/overview.md` gains a rule so this does not come back with
the next change: app READMEs and field descriptions describe current
behavior, a change users must act on goes to the website's upgrade page,
and a description does not ask the reader to keep it in sync with
another chart.

```release-note
[kubernetes] The Kubernetes application no longer has a `talos` field. Talos settings for workers, and the Talos to Kubernetes compatibility check, live on each KubernetesNodes pool. Existing clusters that still store `talos` values keep working; the values are ignored. KubernetesNodes field descriptions, README and install notes now describe the worker pool as it works today, including which fields have no effect on Proxmox pools.
```

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

## Summary by CodeRabbit

* **Configuration**
* Worker OS image, installer, and registry-mirror settings are
configured per worker pool; these settings are no longer available at
the cluster level.
* Kubernetes and Talos version compatibility is checked for each worker
pool. A worker Kubernetes version cannot be ahead of its parent cluster.
* Worker pools support KubeVirt and Proxmox, with pool-specific sizing
and disk settings.
* Rendering is refused when a pool uses a different substrate from its
cluster or conflicts with an existing worker pool owned by another
release.
  * The default cluster hostname now includes the `kubernetes-` prefix.
* Existing cluster configurations that still include Talos settings
receive a warning; those settings are no longer used.

* **Documentation**
* Updated guidance for cluster and worker-pool settings, storage,
upgrades, and version compatibility.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-14 00:34:44 +05:00
Aleksei Sviridkin f13362b0ee fix(api): make monitor watch versions usable as delete preconditions
A watch event triggered by a WorkloadMonitor carries the monitor's
resourceVersion, so a monitor-only status change reaches informer
handlers: client-go treats an update with an unchanged resourceVersion
as a resync and hides it from them. That version never equals the
HelmRelease's, though, so a delete with it as a precondition always
failed, and its spec came from the informer cache, which can lag behind
the monitor revision.

The event now builds the Application from a release no older than the
monitor revision and carries the newer of the two versions. HelmReleases
and WorkloadMonitors are stored in the same etcd, so their versions are
revisions of one sequence, and a value this API hands out that is newer
than the live release names the current spec. A resourceVersion
precondition on delete is therefore checked against the live release and
only an older one is a conflict; the delete itself then carries the live
version.

The two backing watches are not ordered, so a monitor event can be
processed after a release event that is newer than the monitor, and a
resumed watch can replay a monitor before the release the client already
holds. When the event would carry the version the client may hold, which
without anything sent for the object yet means any release version, it
falls back to the monitor's own version and the object's version steps
back. A delete with that version from the client's cache gets a conflict
until the object's next release event or monitor change; no write is
lost.

The release is read live when the cache does not have it or has one
older than the monitor revision; otherwise the cached release already
pairs its spec with its own version. A watch start replays every
existing monitor as ADDED, so a watch that starts or reconnects reads
live once for each monitor written after its release last changed, and
each later monitor status change costs at most one read per open watch.

Fixes: 1bae0775be ("feat(application): add WorkloadsReady condition and Events tab")
Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-13 20:11:48 +03:00
Aleksei Sviridkin 29e8522f4b fix(cozystack-basics): refuse a direct delete of a tenant namespace (#5011)
## What this PR does

Fixes #5002. A DELETE of a tenant namespace is refused unless it comes
from the identities that remove it on the normal path, and the denial
says to delete the Tenant instead.

The new ValidatingAdmissionPolicy in cozystack-basics matches DELETE of
core namespaces, and its binding selects namespaces labelled
`tenant.cozystack.io/tenant-root`. The tenant chart puts that label on
every tenant namespace below tenant-root (`tenant.ancestorTenantLabels`,
and migration 49 backfilled older ones). tenant-root itself has no such
label and stays with `cozystack-no-delete-guardrail`. The `tenant-*`
probe namespaces of the e2e suites carry only
`namespace.cozystack.io/host` and are not selected either.

Two groups pass. `system:serviceaccounts:cozy-fluxcd`, because
helm-controller and its shards run as `flux` there, and a Tenant
uninstall is helm-controller deleting the namespace after the pre-delete
hook. `system:serviceaccounts:kube-system`, for the garbage collector
following the ownerReference of a child namespace once its parent is
gone. The namespace controller never sends a DELETE for a namespace, it
updates `finalize`, so it is not affected
(`pkg/controller/namespace/deletion` and
`pkg/registry/core/namespace/storage` at v1.33.12 and v1.34.1).
`system:masters` is not exempt, the same as with the no-delete
guardrail.

This is the denial kube-apiserver 1.35 returns.

```
namespaces "tenant-foo" is forbidden: ValidatingAdmissionPolicy 'cozystack-tenant-namespace-delete-policy' with binding 'cozystack-tenant-namespace-delete-policy' denied request: Namespace tenant-foo belongs to the Tenant foo in tenant-root. Delete the Tenant instead with kubectl delete tenants.apps.cozystack.io foo --namespace tenant-root. Deleting the namespace directly can remove the tenant etcd before the Kubernetes clusters that use it and leave the namespace stuck in Terminating. If the Tenant is already gone, remove the label first with kubectl label namespace tenant-foo tenant.cozystack.io/tenant-root-
```

There are a few limits.

- The bypass is removing the label, like with the guardrail. That also
takes the namespace out of the tenant-root egress policy and the
dashboard tree, which only matters for a namespace that is about to go.
- Migration 49 labelled every `tenant-*` namespace that existed when it
ran, so a non-tenant namespace with such a name is refused too and needs
the same label removal.
- Because the garbage collector is exempt, a parent namespace whose
label was removed and that is deleted with foreground propagation still
cascades into its children directly.
- A DELETE of a namespace that is already Terminating is answered before
admission, so the policy does not see it. It changes nothing either.
- A cluster that made helm-controller impersonate another account
(`--default-service-account`, or `spec.serviceAccountName` on Tenant
HelmReleases) would need that account allowed. Cozystack sets neither.
- It does not change how Kamaji cleans up once the order is broken,
which is the second idea in #5002.

The helper rename in `external_tls_policy_test.go` (`loadPolicy(t,
path)` and `compilePolicy`) is byte for byte the one in #2622, so the
two merge in either order.

Checked locally.

- `go test ./pkg/registry/apps/application/ -run
'TestTenantNamespaceDeletePolicy|TestDatabaseExternalTLSPolicy' -count=1
-v` passes 4 tests, the new `TestTenantNamespaceDeletePolicy_Decisions`
with 11 cases. `go test ./pkg/registry/... ./pkg/config/...
./pkg/cmd/server/...` passes in all 11 packages that have tests.
- `helm unittest` in `packages/system/cozystack-basics` with
helm-unittest 1.1.2 in docker passes 12 suites and 70 tests, against 11
and 66 on main. The new tests on main without the template fail, both Go
tests and 4 helm tests in 2 suites.
- 12 mutations of the template each fail a test. They exempt
`system:masters`, drop either exempt group, select on the no-delete
label, add UPDATE, always name tenant-root as the parent, drop the
capability gate, label tenant-root, switch to Warn, switch failurePolicy
to Ignore, drop the bypass from the message and drop the objectSelector.
- The rendered policy, the guardrail and namespaces rendered from the
tenant chart were applied to kube-apiserver v1.33.0, v1.35.0 and v1.36.2
from setup-envtest, 16 checks on each. Real and dry-run deletes by a
cluster admin, by an OIDC user bound to cluster-admin and by a
cozy-system and a tenant ServiceAccount are refused with 403. The flux
and garbage collector identities get their delete accepted. tenant-root
gets the guardrail's denial, and with the guardrail binding removed a
dry-run delete of it goes through, so this policy does not select it. A
`tenant-*` namespace without the label and a tenant namespace after its
label is removed are accepted for deletion. With this binding removed, a
dry-run delete by the cluster admin goes through. That harness is not
part of the PR.
- `hack/bats-no-negated-assert.bats`, `hack/bats-no-exit-trap.bats`,
`hack/bats-runner-coverage.bats`, `hack/helmrelease-readiness.bats` and
`hack/route-hostname-policy-version-coverage.bats` pass under
`hack/cozytest.sh`.

The new e2e case in `hack/e2e-install-cozystack.bats` creates an empty
Tenant, checks that a server dry-run delete of its namespace is refused
with the message, deletes the Tenant and waits for the namespace to go.
It was not run here, there is no Cozystack cluster at hand. Its kubectl
steps were run against the envtest apiserver 1.35, the selector and
field selector read, the refused dry-run with the exact strings it greps
for, and `kubectl wait --for=delete` on a namespace that is gone. The
Chainsaw suites that delete Tenants, the gateway inheritance ones among
them, go through the uninstall path as well.

The release-1.6 backport is #5012.

### Screenshots

Not a UI change.

### Downstream repositories

- [x] No downstream repository is affected by this change
- [ ] [cozystack/website](https://github.com/cozystack/website) -
follow-up:
- [ ]
[cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack)
- follow-up:
- [ ]
[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:

The trigger map was walked against the diff. It adds a policy and tests
to cozystack-basics and an e2e case, and no entry covers that. The
website docs do not tell users to delete a tenant namespace directly,
and terraform-provider-cozystack deletes Tenants through the apps API.

### Release note

```release-note
fix(cozystack-basics): refuse a direct DELETE of a tenant namespace unless it comes from helm-controller or the garbage collector, and point to deleting the Tenant instead, so a tenant namespace deleted by hand no longer gets stuck Terminating on Kamaji finalizers
```
2026-11-13 18:25:04 +03:00
Aleksei Sviridkin d089decab9 Merge branch 'main' into fix/tenant-namespace-direct-delete-guard
Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-13 14:20:44 +03:00
Myasnikov Daniil 0fed7c51d2 fix(api): warn when a Kubernetes spec still carries talos
The Kubernetes chart no longer reads talos, but a stored or
hand-edited spec that keeps the block is accepted without a word.
List it with the other keys the worker pool split made inert, so the
API answers with the same warning it gives for nodeGroups.

Assisted-by: LLM
Signed-off-by: Myasnikov Daniil <myasnikovdaniil2001@gmail.com>
2026-11-13 15:22:34 +05:00
Mattia Eleuteri 293503e048 docs(securitygroups): record the port-range and FQDN validation in the design
The design still listed FQDN matchName/matchPattern syntax as deferred
and passed through to Cilium. Create and update now reject a malformed
selector, a selector setting both fields and a port range on the
SecurityGroup path, so the deferred list keeps only cross-rule
consistency.

Assisted-by: LLM
Signed-off-by: Mattia Eleuteri <mattia@hidora.io>
2026-11-13 10:39:41 +01:00
Mattia Eleuteri a125b98cd7 fix(securitygroups): reject port ranges and malformed FQDNs on the SecurityGroup path
A port such as "80-90" fell through to the named-port check and was
refused because it "must contain at least one letter", which says
nothing about the actual limit: a SecurityGroup port carries one port,
and Cilium's endPort is not exposed.

FQDN selectors were only checked for being non-empty. A malformed
matchName or matchPattern passed validation and was then refused by the
CiliumNetworkPolicy CRD on the backing write, so the tenant got a schema
error about an object they never wrote. Apply the CRD's own rules
instead: its two patterns, its 255-character limit, and its oneOf
between matchName and matchPattern.

Fixes #5130

Assisted-by: LLM
Signed-off-by: Mattia Eleuteri <mattia@hidora.io>
2026-11-13 10:39:40 +01:00
Aleksei Sviridkin 939a1ec44b refactor: read managed fields through FieldsV1 accessors
Direct access to FieldsV1.Raw is deprecated; GetRawBytes returns the
same bytes and is nil-safe, and NewFieldsV1 builds the test fixtures.

The write-options test still covers a raw-only orphanDependents delete
option, now decoded from its wire form, and asserts that the converted
options keep it.

Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-13 12:35:03 +03:00
Aleksei Sviridkin 87b794a992 chore: handle errors dropped in cleanup paths and tests
The drain tests now assert that RunThenDrain returns the run's nil
error, the idle-tail test fails on any error other than the stream
ending or being cut, and a test fixture file fails the test when it
cannot be closed.

Removing a temporary directory and closing a response body that has
been read are best-effort: a failure leaves nothing for the caller to
act on and does not change any result, so those errors are discarded
explicitly. The same holds for the stub servers' response writes, whose
failure surfaces on the client side of the test.

Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-13 12:35:01 +03:00
Aleksei Sviridkin 238e85577e refactor(lineage): resolve a HelmRelease's application in a helper
The walk used a loop that always ended in its first pass to get
"break to the fallback" control flow. A function returning whether it
resolved the application says the same without the loop. A test pins
that each failure to resolve still falls back to the HelmRelease's own
label and that a resolved one ends the walk.

Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-13 11:37:41 +03:00
Aleksei Sviridkin 4c3a4b42cc style: clear unused code and style findings reported by staticcheck
Remove helpers and constants nothing references, escape format
characters in test literals, and take the simplifications staticcheck
suggests where they read the same. Error strings no longer start with a
capital: they keep their meaning, with the kind or component name moved
out of first position. Callers match errors by type, not text; the one
test that matches text, for Kafka, keeps the phrase it looks for.

Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-13 11:37:41 +03:00
Myasnikov Daniil fb8a7ef278 docs(kubernetes): describe the cluster as it is and drop the history
The README told users two things the chart does not do: that it
deploys a dedicated etcd cluster (the control plane uses the tenant's
etcd, which the Tenant deploys), and that worker disks match the
volume's block size through blockSize.matchVolume, a setting that
exists nowhere in the tree. It also described worker nodes as KubeVirt
VMs managed by this application, while they are KubernetesNodes pools
on KubeVirt or Proxmox, and offered "patch versions" where the user
picks a minor.

The Breaking Changes section was a release log: entries from several
releases, most of them about fields that live on KubernetesNodes now,
and each one written as a change rather than as the current behaviour.
What a user has to do on upgrade belongs on the per-release upgrade
page of the website, so the README points there and keeps only the
storageClass immutability note, rewritten as current behaviour.

The field descriptions are what the dashboard, the API schema and a
rejected name show the user, and several were written against how the
application used to work. The name limit was explained by a default
md0 pool that no longer exists, while the 32-character cap leaves room
for any three-character pool name. The host default left out the
kubernetes- prefix the release name carries. A substrate mismatch with
a pool was said to leave Machines unreconciled, while the pool refuses
to render. The OIDC type carried a roadmap phase in its title, and
extraArgs promised "no change to current behavior". The name-cap test
looked for "md0" in the rejection message as its sign that the chart's
explanation arrives; it looks for the release-name pattern the new
explanation gives.

Assisted-by: LLM
Signed-off-by: Myasnikov Daniil <myasnikovdaniil2001@gmail.com>
2026-11-12 17:21:15 +05:00
Myasnikov Daniil 90f0b043a6 fix(kubernetes)!: remove the talos block the chart no longer uses
The kubernetes chart declared a talos block (version, schematicID,
imageFactoryURL, installerRepository, registryMirrors). Workers are
KubernetesNodes pools and take every one of these from their own talos
values, so an operator who set them on the cluster got no error and no
effect. The only reader left was a copy of the Talos to Kubernetes
support-matrix check, and the pool chart already runs that check
itself, against the Talos release each pool actually boots, including
one an osImage override selects. The cluster's copy compared the
Kubernetes version against a Talos release no node runs.

The block leaves the API schema, hence the "!". Stored specs that still
carry it keep rendering: the values schema does not close the object
and the API does not validate spec against it. A helm-unittest case
pins that.

Readers outside the chart moved with it. The e2e install read
talos.schematicID from this chart's values.yaml in a best-effort block
that only warns, so removing the field would have stopped the image
cache being seeded without failing anything; it now reads the pool
chart, as the proxmox template script already does. The e2e no longer
writes a talos block into the Kubernetes CR, the spec test checks the
pool chart for the key it emits, the release checklist diffs the pool
chart's pins as well, and the catalog guard drops the two tests that
compared or read the parent's block. The null-normalization Go tests
used talos keys of the real Kubernetes schema as their fixtures; they
use oidc.mode, the same required-with-default shape under an optional
root section, and addons.cilium.valuesOverride for the free-form case.

Assisted-by: LLM
Signed-off-by: Myasnikov Daniil <myasnikovdaniil2001@gmail.com>
2026-11-12 16:51:38 +05:00
Aleksei Sviridkin 5e9c392352 feat(api): add the reservation evaluator for tenant quotas (#4983)
## What this PR does

First phase of the accepted [tenant quotas as reservation
limits](https://github.com/cozystack/community/pull/48) design: a
standalone, importable `pkg/reservation` package that computes what an
application consumes from a tenant's budget from its declared values.
Nothing calls it yet; the usage oracle, the generalized admission gate
and the per-kind declarations come in the following phases.

Today a tenant quota is declared in instance-type units but enforced
against `ResourceQuota.status.used`, which counts virt-launcher pods
with their additive virtualization overhead and drifts without
recomputation. The design makes the declared reservation the accounting
authority instead, and this package is the evaluator both the apiserver
and the controller will read.

- **Declarations are data, not Go.** A kind describes its consumption as
CEL over its values (`exempt`, ordered `let` bindings, one expression
per quota key), so the evaluator holds no per-kind knowledge and a kind
from an out-of-tree catalog participates without a change here. The
`Declaration` type is ready to be embedded in
`ApplicationDefinitionSpec` in phase 2. Environment functions are
`instanceType(name)`, `preset(name)` and `quantity(x)`, on top of the
Kubernetes CEL quantity library; scaling is `quantity.mul(n)`, because
the standard `_*_` cannot take a quantity overload.
- **Instance types resolve to scalars keyed by class**, read from the
type's spec and never from its name: `cpu`, `dedicated-cpu` (guest cores
plus the isolated emulator thread, the extra parity core when the type
itself carries the `EmulatorThreadCompleteToEvenParity` annotation, and
a supplemental I/O pool), `memory`, `hugepages-<size>`,
`overcommitted-memory`. The test pins the classification against every
`VirtualMachineClusterInstancetype` shipped in
`packages/system/kubevirt-instancetypes`.
- **Fail closed.** An unknown instance type or preset, a value of the
wrong type, an unguarded absent key, an unparseable quantity or a
negative figure is an error, and values are checked against the kind's
schema before defaulting, which would otherwise replace a mistyped value
with its default, never a smaller reservation. A definition that
declares neither its consumption nor an exemption yields
`ErrNoDeclaration`.
- **Stored values are defaulted first.** The aggregated apiserver
persists a tenant's spec without its schema defaults, so an evaluator
reading them raw would count zero for `kubernetes-nodes.maxReplicas` on
every pool created with defaults. The structural-schema defaulting moves
from `pkg/registry/apps/application` into `pkg/apis/apps/defaulting` so
the registry and the evaluator apply the same defaults; the registry now
only delegates to it, with no behaviour change.
- **Aggregation** sums reservations per namespace and returns the
applications that could not be evaluated separately, so a caller never
mistakes an incomplete sum for a complete one.

The evaluator tests run against the shipped OpenAPI schemas of
`postgres`, `vm-instance` and `kubernetes-nodes`: the cozy-lib per-key
preset fill, a `{cpu: 4, sockets: 2}` block reserving 8 vCPUs, the
autoscaling ceiling, `external: true` reserving a load balancer, and a
ComputePlane-shaped `KubernetesNodes` release carrying only `{roles,
minReplicas}` reserving exactly what the same pool with its defaults
written out reserves.

Left for the next phases on purpose: where presets are resolved from
(the design's direction is platform-shipped environment objects; here
they come through the `Environment` interface), the
`ApplicationDefinition` field itself, and any consumer.

### Screenshots

Not a UI change.

### Downstream repositories

The diff adds two Go packages and moves the defaulting helpers without
changing behaviour. It touches no package under `packages/`, no
`values.yaml`, no CRD and no `ApplicationDefinition` field, so none of
the triggers in the map is reached.

- [x] No downstream repository is affected by this change
- [ ] [cozystack/website](https://github.com/cozystack/website) -
follow-up:
- [ ]
[cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack)
- follow-up:
- [ ]
[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(api): add the reservation evaluator that computes an application's tenant-quota consumption from its declared values. Internal only, with no consumer yet and no change in behaviour.
```


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

## Summary by CodeRabbit

- **New Features**
- Added reservation evaluation for application resources, including CPU,
memory, hugepages, and overcommitted memory.
- Added support for instance types, resource presets, schema-based
defaults, and CEL expressions.
- Added namespace-level reservation aggregation with clear reporting for
applications that cannot be evaluated.
- Added validation for invalid, negative, unsupported, or excessive
resource values.
- Added classification of KubeVirt instance types, including dedicated
CPUs, emulator threads, supplemental I/O threads, and hugepages.

- **Bug Fixes**
- Schema defaults are applied consistently to nested application values.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-10 03:26:01 +03:00