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 -->
This commit is contained in:
Aleksei Sviridkin authored and GitHub committed 2026-11-23 14:55:02 +03:00
commit ec8088e54c
2 files changed
+82 -14

No files matched your search

+32 -11
View File
@@ -25,6 +25,7 @@ import (
"io"
"net"
"slices"
"strings"
"time"
v1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
@@ -44,6 +45,7 @@ import (
utilfeature "k8s.io/apiserver/pkg/util/feature"
basecompatibility "k8s.io/component-base/compatibility"
baseversion "k8s.io/component-base/version"
"k8s.io/kube-openapi/pkg/validation/spec"
netutils "k8s.io/utils/net"
"sigs.k8s.io/controller-runtime/pkg/client"
k8sconfig "sigs.k8s.io/controller-runtime/pkg/client/config"
@@ -276,10 +278,7 @@ func (o *CozyServerOptions) Complete() error {
delay = min(time.Duration(float64(delay)*1.5), maxDelay)
}
resourceConfig, err := resourceConfigFrom(crdList.Items, hrFlags)
if err != nil {
return err
}
resourceConfig, _ := resourceConfigFrom(crdList.Items, hrFlags)
o.ResourceConfig = resourceConfig
return nil
@@ -289,20 +288,29 @@ func (o *CozyServerOptions) Complete() error {
// cozystack-api serves. A kind declared by more than one definition is
// registered once, for the definition that owns it, rather than as two
// resources for one GVK; the definitions left out are logged.
func resourceConfigFrom(defs []v1alpha1.ApplicationDefinition, hrFlags helmReleaseFlagValues) (*config.ResourceConfig, error) {
//
// A definition that cannot be turned into a resource (an unparseable
// release.cozystack.io/* annotation, an openAPISchema that is not valid JSON)
// is left out and logged too, and returned in the error list. Failing startup
// on it would let one definition take cozystack-api down for every tenant, and
// definitions can come from a connected repository, not only from an operator.
func resourceConfigFrom(defs []v1alpha1.ApplicationDefinition, hrFlags helmReleaseFlagValues) (*config.ResourceConfig, []error) {
owned, skipped := ownedDefinitions(defs)
for _, msg := range skipped {
fmt.Printf("Skipping %s\n", msg)
}
resourceConfig := &config.ResourceConfig{}
var invalid []error
for _, crd := range owned {
resource, err := buildResourceFromCRD(crd, hrFlags)
if err != nil {
return nil, err
fmt.Printf("Skipping invalid ApplicationDefinition %q: %v\n", crd.Name, err)
invalid = append(invalid, err)
continue
}
resourceConfig.Resources = append(resourceConfig.Resources, resource)
}
return resourceConfig, nil
return resourceConfig, invalid
}
// ownedDefinitions returns the definitions that own their application kind
@@ -362,10 +370,10 @@ func buildResourceFromCRD(crd v1alpha1.ApplicationDefinition, hrFlags helmReleas
// Kamaji-provisioned admin-kubeconfig Secret for Kubernetes tenants) need a
// longer wait budget than the Flux default. Consumed by the REST storage
// layer when building the HelmRelease Spec. The parser rejects
// units Flux would reject at webhook time, so a bad annotation
// surfaces as a loud startup failure instead of a silent drop to
// defaults. helm-install-timeout covers both install and upgrade;
// helm-upgrade-timeout overrides only the upgrade side for kinds
// units Flux would reject at webhook time, so a bad annotation leaves
// this kind out of cozystack-api (see resourceConfigFrom) instead of a
// silent drop to defaults. helm-install-timeout covers both install and
// upgrade; helm-upgrade-timeout overrides only the upgrade side for kinds
// that need an asymmetric budget.
installTimeout, err := config.ParseHelmTimeoutAnnotation(
crd.Annotations[config.HelmInstallTimeoutAnnotation],
@@ -408,6 +416,19 @@ func buildResourceFromCRD(crd v1alpha1.ApplicationDefinition, hrFlags helmReleas
)
}
release.HelmServerSideApply = serverSideApply
// The OpenAPI post-processors parse this schema for every served kind and
// fail the whole spec on one that does not parse, so reject it here, where
// only this definition is left out.
if raw := crd.Spec.Application.OpenAPISchema; strings.TrimSpace(raw) != "" {
var schema spec.Schema
if err := json.Unmarshal([]byte(raw), &schema); err != nil {
return config.Resource{}, fmt.Errorf(
"ApplicationDefinition %q has invalid spec.application.openAPISchema: %w",
crd.Name, err,
)
}
}
return config.Resource{
Application: config.ApplicationConfig{
Kind: crd.Spec.Application.Kind,
+50 -3
View File
@@ -1,6 +1,7 @@
package server
import (
"strings"
"testing"
"time"
@@ -8,6 +9,7 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/cozystack/cozystack/api/v1alpha1"
"github.com/cozystack/cozystack/pkg/config"
)
// TestOwnedDefinitionsDropsKindDuplicate pins that cozystack-api registers one
@@ -51,14 +53,59 @@ func TestResourceConfigFromRegistersOwnerOnly(t *testing.T) {
d.Spec.Release.ChartRef = &helmv2.CrossNamespaceSourceReference{Kind: "ExternalArtifact", Name: artifact, Namespace: "cozy-system"}
return d
}
rc, err := resourceConfigFrom([]v1alpha1.ApplicationDefinition{
rc, invalid := resourceConfigFrom([]v1alpha1.ApplicationDefinition{
mk("a-redis-shadow", "shadow-artifact", base.Add(time.Hour)),
mk("redis", "redis-artifact", base),
}, helmReleaseFlagValues{})
if err != nil {
t.Fatal(err)
if len(invalid) != 0 {
t.Fatal(invalid)
}
if len(rc.Resources) != 1 || rc.Resources[0].Release.ChartRef.Name != "redis-artifact" {
t.Fatalf("resources = %+v, want the owner's redis-artifact only", rc.Resources)
}
}
// TestResourceConfigFromSkipsInvalidDefinition pins that one broken
// ApplicationDefinition no longer stops cozystack-api from starting: it is left
// out and reported, and every valid definition is still served.
func TestResourceConfigFromSkipsInvalidDefinition(t *testing.T) {
mk := func(name, kind string) v1alpha1.ApplicationDefinition {
d := v1alpha1.ApplicationDefinition{ObjectMeta: metav1.ObjectMeta{Name: name}}
d.Spec.Application.Kind = kind
d.Spec.Release.ChartRef = &helmv2.CrossNamespaceSourceReference{Kind: "ExternalArtifact", Name: name, Namespace: "cozy-system"}
return d
}
badTimeout := mk("bad-timeout", "BadTimeout")
badTimeout.Annotations = map[string]string{config.HelmInstallTimeoutAnnotation: "ten minutes"}
badSchema := mk("bad-schema", "BadSchema")
badSchema.Spec.Application.OpenAPISchema = `{"type": "object",`
// A valid, nonblank schema must still be accepted.
redis := mk("redis", "Redis")
redis.Spec.Application.OpenAPISchema = `{"type": "object", "properties": {"replicas": {"type": "integer"}}}`
rc, invalid := resourceConfigFrom([]v1alpha1.ApplicationDefinition{
redis,
badTimeout,
badSchema,
mk("postgres", "Postgres"),
}, helmReleaseFlagValues{})
kinds := map[string]bool{}
for _, r := range rc.Resources {
kinds[r.Application.Kind] = true
}
if len(rc.Resources) != 2 || !kinds["Redis"] || !kinds["Postgres"] {
t.Fatalf("served kinds = %v, want Redis and Postgres only", kinds)
}
if len(invalid) != 2 {
t.Fatalf("invalid = %v, want one error each for bad-timeout and bad-schema", invalid)
}
for i, want := range []string{
`ApplicationDefinition "bad-timeout" has invalid ` + config.HelmInstallTimeoutAnnotation + ` annotation`,
`ApplicationDefinition "bad-schema" has invalid spec.application.openAPISchema`,
} {
if !strings.Contains(invalid[i].Error(), want) {
t.Errorf("invalid[%d] = %q, want it to contain %q", i, invalid[i], want)
}
}
}