mirror of
https://github.com/cozystack/cozystack.git
synced 2026-11-30 12:16:03 +09:00
A managed application's tenant-facing Services are its endpoints, and the only way to publish one externally has been the chart boolean `external`, which publishes one chart-chosen endpoint on one address from no particular pool through five different render paths. EndpointAttachment attaches one address, minted from an IPAddressClass or bound from a reserved IPAddressClaim, to one tenant-facing Service by rendering an additive LoadBalancer Service that mirrors the endpoint's selector and ports. The mechanism therefore needs no per-engine render knowledge and never touches the application's own objects, and a reserved address survives every attachment and moves between applications. The Service carries the loadBalancerClass the claim's class reports in status, so it reaches the load balancer that owns the class's pool; since a Service's loadBalancerClass is immutable, nothing new is rendered before the class's provisioner accepts the class for its current generation. The rendered Service asks for the claim's IP families, since one left to the cluster's primary family cannot be assigned an address of the other. The endpoint check requires both the lineage labels and the tenantresource marker: lineage alone also covers operator-internal Services. A LoadBalancer Service a tenant Kubernetes cluster's cloud-controller-manager creates carries the cluster's labels and the marker too, so the cluster.x-k8s.io/tenant-service-name label it writes excludes it. Identity is by owner reference throughout, so a Service carrying the ownership label without the reference is never adopted, and a same-name recreated application does not inherit the previous incarnation's attachments. The VM datapath modes render the cozy-proxy Service contract unchanged and are gated on a platform declaration rather than CNI detection: a proxy skips a Service delegated to a name it does not claim while the load balancer still attracts the address. Exclusivity is keyed on the backend pod in both modes because cozy-proxy's egress map holds one address per pod, and holds IPv4 only, so a method attachment off a VPC refuses an IPv6 or Dual claim. A delegation no attachment renders, such as a chart Service with external: true, always takes the pod, since nothing would ever withdraw it; between attachments the oldest wins. A whole-IP attachment with several ready backends keeps its address dark instead of picking one. A cozyplane VPC changes that for whole-IP: the VM's only interface is in the VPC, so the launcher pod address a cozy-proxy Service maps to never reaches it. Where a backend pod carries the VM chart's sdn.cozystack.io/vpc annotation and the cluster serves cozyplane's FloatingIP, the attachment owns a FloatingIP on the VM's VPC address wearing its claim instead, and mirrors its readiness once its status is for its current generation: a re-pointed FloatingIP keeps the old target's status until cozyplane observes the change. FloatingIP is read as unstructured and used only when served, so the controller keeps no dependency on cozyplane. A live migration's two launcher pods share the VM's VPC address and count as one target, and a stopped VM keeps its binding rather than flipping to a cozy-proxy Service. Only a backend pod says whether a VM is in a VPC, so a method attachment that has published nothing yet waits for one; otherwise an attachment created before its VM starts would pin the claim to a cozy-proxy Service first. PortList is refused there: a FloatingIP binds every port and cozy-proxy cannot reach the VPC address. So is a Dual claim, since a FloatingIP wears one address. The kube-ovn VPC keeps the pod-network interface and adds VPC subnets as secondary interfaces, so the cozy-proxy path still delivers to the VM there. The e2e suite is the only one that needs the address substrate, so it owns both of its optional packages in test selection: the e2e install enables them, a selection that leaves the suite out disables them, and post-install prep gives the sandbox a default IPAddressClass on a pool MetalLB does not auto-assign from. The cozyplane VPC suite stays parked, because no e2e lane installs that networking variant. The kind lives in local.sdn.cozystack.io, the CRD-served half of the sdn family the address substrate and cozyplane share, so stock ResourceQuota counts keep working. Assisted-by: LLM Signed-off-by: Timofei Larkin <lllamnyp@gmail.com>
291 lines
12 KiB
Go
291 lines
12 KiB
Go
/*
|
|
Copyright 2026 The Cozystack Authors.
|
|
|
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
you may not use this file except in compliance with the License.
|
|
You may obtain a copy of the License at
|
|
|
|
http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
Unless required by applicable law or agreed to in writing, software
|
|
distributed under the License is distributed on an "AS IS" BASIS,
|
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
See the License for the specific language governing permissions and
|
|
limitations under the License.
|
|
*/
|
|
|
|
package endpointattachment
|
|
|
|
import (
|
|
"context"
|
|
"os"
|
|
"testing"
|
|
|
|
apiextensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
|
|
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
|
|
apiextvalidation "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation"
|
|
"k8s.io/apiextensions-apiserver/pkg/apiserver/schema"
|
|
schemacel "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel"
|
|
"k8s.io/apiextensions-apiserver/pkg/apiserver/schema/listtype"
|
|
apiservervalidation "k8s.io/apiextensions-apiserver/pkg/apiserver/validation"
|
|
"k8s.io/apimachinery/pkg/util/validation/field"
|
|
celconfig "k8s.io/apiserver/pkg/apis/cel"
|
|
"sigs.k8s.io/yaml"
|
|
)
|
|
|
|
// crdPath is the generated CRD the controller ships. The rules under test
|
|
// are compiled from the XValidation markers on the API types, so reading
|
|
// the generated file is what detects a marker that silently failed to
|
|
// generate.
|
|
const crdPath = "../../../packages/system/cozystack-controller/definitions/local.sdn.cozystack.io_endpointattachments.yaml"
|
|
|
|
type admissionCheck struct {
|
|
cel *schemacel.Validator
|
|
structural *schema.Structural
|
|
schema apiservervalidation.SchemaValidator
|
|
}
|
|
|
|
// versionSchema returns the v1alpha1 schema of the shipped CRD, from the
|
|
// resource root.
|
|
func versionSchema(t *testing.T) *apiextensionsv1.JSONSchemaProps {
|
|
t.Helper()
|
|
raw, err := os.ReadFile(crdPath)
|
|
if err != nil {
|
|
t.Fatalf("read CRD: %v", err)
|
|
}
|
|
var crd apiextensionsv1.CustomResourceDefinition
|
|
if err := yaml.Unmarshal(raw, &crd); err != nil {
|
|
t.Fatalf("unmarshal CRD: %v", err)
|
|
}
|
|
for i := range crd.Spec.Versions {
|
|
v := &crd.Spec.Versions[i]
|
|
if v.Name == "v1alpha1" && v.Schema != nil && v.Schema.OpenAPIV3Schema != nil {
|
|
return v.Schema.OpenAPIV3Schema
|
|
}
|
|
}
|
|
t.Fatal("v1alpha1 schema not found in CRD")
|
|
return nil
|
|
}
|
|
|
|
// specValidator compiles the spec subtree alone, which is enough for the
|
|
// rules nested inside it.
|
|
func specValidator(t *testing.T) *admissionCheck {
|
|
t.Helper()
|
|
p, ok := versionSchema(t).Properties["spec"]
|
|
if !ok {
|
|
t.Fatal("v1alpha1 spec schema not found in CRD")
|
|
}
|
|
if len(p.XValidations) == 0 {
|
|
t.Fatal("spec schema carries no x-kubernetes-validations; the XValidation markers did not generate")
|
|
}
|
|
return compile(t, &p)
|
|
}
|
|
|
|
// rootValidator compiles the whole resource, which is what admission
|
|
// validates: a rule nested in spec never runs when spec itself is absent.
|
|
func rootValidator(t *testing.T) *admissionCheck {
|
|
t.Helper()
|
|
return compile(t, versionSchema(t))
|
|
}
|
|
|
|
func compile(t *testing.T, props *apiextensionsv1.JSONSchemaProps) *admissionCheck {
|
|
t.Helper()
|
|
var internal apiextensions.JSONSchemaProps
|
|
if err := apiextensionsv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(props, &internal, nil); err != nil {
|
|
t.Fatalf("convert schema: %v", err)
|
|
}
|
|
structural, err := schema.NewStructural(&internal)
|
|
if err != nil {
|
|
t.Fatalf("structural schema: %v", err)
|
|
}
|
|
schemaValidator, _, err := apiservervalidation.NewSchemaValidator(&internal)
|
|
if err != nil {
|
|
t.Fatalf("schema validator: %v", err)
|
|
}
|
|
return &admissionCheck{
|
|
cel: schemacel.NewValidator(structural, true, celconfig.PerCallLimit),
|
|
structural: structural,
|
|
schema: schemaValidator,
|
|
}
|
|
}
|
|
|
|
// rejects reports whether admission would refuse the object. old is nil for
|
|
// a create; on an update the transition rules (oldSelf) run as well.
|
|
func (a *admissionCheck) rejects(t *testing.T, obj, old map[string]interface{}) bool {
|
|
t.Helper()
|
|
if errs := apiservervalidation.ValidateCustomResource(nil, obj, a.schema); len(errs) > 0 {
|
|
return true
|
|
}
|
|
// Uniqueness in a listType=set is a structural check of its own, which
|
|
// neither the OpenAPI schema nor CEL performs.
|
|
if errs := listtype.ValidateListSetsAndMaps(nil, a.structural, obj); len(errs) > 0 {
|
|
return true
|
|
}
|
|
var oldObj interface{}
|
|
if old != nil {
|
|
oldObj = old
|
|
}
|
|
errs, _ := a.cel.Validate(context.TODO(), field.NewPath("root"), a.structural, obj, oldObj, celconfig.RuntimeCELCostBudget)
|
|
return len(errs) > 0
|
|
}
|
|
|
|
func spec(lb map[string]interface{}) map[string]interface{} {
|
|
s := map[string]interface{}{
|
|
"applicationRef": map[string]interface{}{"group": "apps.cozystack.io", "kind": "Postgres", "name": "mydb"},
|
|
"endpoint": map[string]interface{}{"serviceName": "postgres-mydb-ro"},
|
|
}
|
|
if lb != nil {
|
|
s["loadBalancer"] = lb
|
|
}
|
|
return s
|
|
}
|
|
|
|
func TestCreateAdmission(t *testing.T) {
|
|
a := specValidator(t)
|
|
tests := []struct {
|
|
name string
|
|
spec map[string]interface{}
|
|
wantReject bool
|
|
}{
|
|
{name: "minimal member mints from the default class", spec: spec(map[string]interface{}{})},
|
|
{name: "className alone", spec: spec(map[string]interface{}{"className": "public"})},
|
|
{name: "claimName alone", spec: spec(map[string]interface{}{"claimName": "held"})},
|
|
{name: "className and claimName together", spec: spec(map[string]interface{}{"className": "public", "claimName": "held"}), wantReject: true},
|
|
{name: "no mechanism member", spec: spec(nil), wantReject: true},
|
|
{name: "PortList with ports", spec: spec(map[string]interface{}{"method": "PortList", "ports": []interface{}{int64(22)}})},
|
|
{name: "PortList without ports", spec: spec(map[string]interface{}{"method": "PortList"}), wantReject: true},
|
|
{name: "PortList with one port", spec: spec(map[string]interface{}{"method": "PortList", "ports": []interface{}{int64(22)}})},
|
|
{name: "PortList with a duplicate port", spec: spec(map[string]interface{}{"method": "PortList", "ports": []interface{}{int64(22), int64(22)}}), wantReject: true},
|
|
{name: "WholeIP without ports", spec: spec(map[string]interface{}{"method": "WholeIP"})},
|
|
{name: "allowICMP with PortList", spec: spec(map[string]interface{}{"method": "PortList", "ports": []interface{}{int64(22)}, "allowICMP": true})},
|
|
{name: "allowICMP with WholeIP", spec: spec(map[string]interface{}{"method": "WholeIP", "allowICMP": true}), wantReject: true},
|
|
{name: "allowICMP without method", spec: spec(map[string]interface{}{"allowICMP": false}), wantReject: true},
|
|
{name: "unknown method", spec: spec(map[string]interface{}{"method": "Magic"}), wantReject: true},
|
|
{name: "unknown family", spec: spec(map[string]interface{}{"family": "IPv5"}), wantReject: true},
|
|
{name: "port out of range", spec: spec(map[string]interface{}{"ports": []interface{}{int64(70000)}}), wantReject: true},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
if got := a.rejects(t, tt.spec, nil); got != tt.wantReject {
|
|
t.Fatalf("rejects=%v, want %v", got, tt.wantReject)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestUpdateAdmission pins the immutability split: the fields that select
|
|
// the address (applicationRef, className, claimName, family, the member
|
|
// itself) are frozen, while the render knobs (ports, method, allowICMP and
|
|
// the endpoint) stay mutable.
|
|
func TestUpdateAdmission(t *testing.T) {
|
|
a := specValidator(t)
|
|
base := spec(map[string]interface{}{"className": "public", "family": "IPv4", "ports": []interface{}{int64(5432)}})
|
|
mutate := func(f func(s map[string]interface{})) map[string]interface{} {
|
|
s := spec(map[string]interface{}{"className": "public", "family": "IPv4", "ports": []interface{}{int64(5432)}})
|
|
f(s)
|
|
return s
|
|
}
|
|
lb := func(s map[string]interface{}) map[string]interface{} {
|
|
return s["loadBalancer"].(map[string]interface{})
|
|
}
|
|
tests := []struct {
|
|
name string
|
|
new map[string]interface{}
|
|
wantReject bool
|
|
}{
|
|
{name: "unchanged", new: mutate(func(map[string]interface{}) {})},
|
|
{name: "applicationRef name changes", new: mutate(func(s map[string]interface{}) {
|
|
s["applicationRef"].(map[string]interface{})["name"] = "other"
|
|
}), wantReject: true},
|
|
{name: "className changes", new: mutate(func(s map[string]interface{}) { lb(s)["className"] = "partner" }), wantReject: true},
|
|
{name: "className dropped", new: mutate(func(s map[string]interface{}) { delete(lb(s), "className") }), wantReject: true},
|
|
{name: "family changes", new: mutate(func(s map[string]interface{}) { lb(s)["family"] = "IPv6" }), wantReject: true},
|
|
{name: "claimName added beside className", new: mutate(func(s map[string]interface{}) { lb(s)["claimName"] = "held" }), wantReject: true},
|
|
{name: "ports change", new: mutate(func(s map[string]interface{}) { lb(s)["ports"] = []interface{}{int64(5432), int64(9187)} })},
|
|
{name: "ports dropped", new: mutate(func(s map[string]interface{}) { delete(lb(s), "ports") })},
|
|
{name: "endpoint retargets", new: mutate(func(s map[string]interface{}) {
|
|
s["endpoint"].(map[string]interface{})["serviceName"] = "postgres-mydb-rw"
|
|
})},
|
|
{name: "member removed", new: mutate(func(s map[string]interface{}) { delete(s, "loadBalancer") }), wantReject: true},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
if got := a.rejects(t, tt.new, base); got != tt.wantReject {
|
|
t.Fatalf("rejects=%v, want %v", got, tt.wantReject)
|
|
}
|
|
})
|
|
}
|
|
t.Run("claimName to className switch", func(t *testing.T) {
|
|
old := spec(map[string]interface{}{"claimName": "held"})
|
|
if !a.rejects(t, spec(map[string]interface{}{"className": "public"}), old) {
|
|
t.Fatal("switching from a referenced claim to a minted one must be refused")
|
|
}
|
|
})
|
|
}
|
|
|
|
// resource wraps a spec the way admission sees the whole object; a nil spec
|
|
// leaves the field out.
|
|
func resource(spec map[string]interface{}) map[string]interface{} {
|
|
obj := map[string]interface{}{
|
|
"apiVersion": "local.sdn.cozystack.io/v1alpha1",
|
|
"kind": "EndpointAttachment",
|
|
"metadata": map[string]interface{}{"name": "mydb-replicas", "namespace": "tenant-a"},
|
|
}
|
|
if spec != nil {
|
|
obj["spec"] = spec
|
|
}
|
|
return obj
|
|
}
|
|
|
|
// TestWholeResourceAdmission validates from the resource root. Removing spec
|
|
// would skip every rule nested inside it, and restoring it would run them
|
|
// with no old value, so spec must be refused as absent on create and on
|
|
// update, while the render knobs inside it stay mutable.
|
|
func TestWholeResourceAdmission(t *testing.T) {
|
|
a := rootValidator(t)
|
|
held := spec(map[string]interface{}{"claimName": "held", "ports": []interface{}{int64(5432)}})
|
|
tests := []struct {
|
|
name string
|
|
obj, old map[string]interface{}
|
|
wantReject bool
|
|
}{
|
|
{name: "create with spec", obj: resource(held)},
|
|
{name: "create without spec", obj: resource(nil), wantReject: true},
|
|
{name: "update removing spec", obj: resource(nil), old: resource(held), wantReject: true},
|
|
{name: "update switching claimName", obj: resource(spec(map[string]interface{}{"claimName": "other", "ports": []interface{}{int64(5432)}})), old: resource(held), wantReject: true},
|
|
{name: "update switching claimName to className", obj: resource(spec(map[string]interface{}{"className": "public", "ports": []interface{}{int64(5432)}})), old: resource(held), wantReject: true},
|
|
{name: "update changing ports", obj: resource(spec(map[string]interface{}{"claimName": "held", "ports": []interface{}{int64(5432), int64(9187)}})), old: resource(held)},
|
|
{name: "update retargeting the endpoint", obj: func() map[string]interface{} {
|
|
s := spec(map[string]interface{}{"claimName": "held", "ports": []interface{}{int64(5432)}})
|
|
s["endpoint"] = map[string]interface{}{"serviceName": "postgres-mydb-rw"}
|
|
return resource(s)
|
|
}(), old: resource(held)},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
if got := a.rejects(t, tt.obj, tt.old); got != tt.wantReject {
|
|
t.Fatalf("rejects=%v, want %v", got, tt.wantReject)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestCRDPassesInstallTimeValidation(t *testing.T) {
|
|
raw, err := os.ReadFile(crdPath)
|
|
if err != nil {
|
|
t.Fatalf("read CRD: %v", err)
|
|
}
|
|
var v1crd apiextensionsv1.CustomResourceDefinition
|
|
if err := yaml.Unmarshal(raw, &v1crd); err != nil {
|
|
t.Fatalf("unmarshal CRD: %v", err)
|
|
}
|
|
v1crd.Status.StoredVersions = []string{"v1alpha1"}
|
|
var internal apiextensions.CustomResourceDefinition
|
|
if err := apiextensionsv1.Convert_v1_CustomResourceDefinition_To_apiextensions_CustomResourceDefinition(&v1crd, &internal, nil); err != nil {
|
|
t.Fatalf("convert CRD: %v", err)
|
|
}
|
|
for _, e := range apiextvalidation.ValidateCustomResourceDefinition(context.TODO(), &internal) {
|
|
t.Errorf("apiserver would reject this CRD: %v", e)
|
|
}
|
|
}
|