Files
nvke/controller/internal/server/server_test.go
Davanum Srinivas bf25577b9f feat(controller): accept controlPlaneEndpoint on cluster create (#2515)
* refactor(controller): ask one cluster method at each control-plane endpoint gate

Each gate that scales, upgrades or replaces control-plane nodes tested
the control-plane VIP for an empty string by itself. The gates now call
db.Cluster.HasStableControlPlaneEndpoint, which is true when the cluster
has a VIP.

The gates are the count check at create and scale, the upgrade and
rollout checks of the cluster API, the node delete guard, the
control-plane controller (recycling, remediation, rebalance, stuck
pending nodes) and the node pool controller (surge, NodeSet
replacement).

No behavior changes. A later change adds a second kind of stable
endpoint to the method.

Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com>

* feat(controller): add controlPlaneEndpoint to the cluster API schema

A cluster can name an API server endpoint that NVKE does not manage,
for example a load balancer in front of the API servers. The create
request gets the optional object controlPlaneEndpoint. Its type says
who manages the endpoint, and the block named after the type carries
what that type needs. This change has one type, External, with a host
and an optional port in the external block. The port defaults to 6443.
The cluster response returns the type and the resolved host and port.
The update request has no such property, so the value is fixed at
creation.

The shape is the one of the proposal for a load balancer as the
control plane endpoint, and this change is its first part. The enum
of the type has only External. The other types of the proposal come
later. A new enum value passes the API compatibility check, and a
removed one does not, so the enum lists only what the code does.

The existing descriptions change only where the new field makes them
wrong or incomplete:

- The overview of the Clusters tag and the description of
  controlPlaneVIP say which address is the API server endpoint.
- Seven sentences that say an operation requires controlPlaneVIP now
  name both fields. Each is one changed line.
- The 400 list of the create operation gets the new reasons.
- The desiredNodeCount descriptions of the two node pool requests lose
  their sentence about control-plane pools. The node pool handlers
  refuse each create and each update of a control-plane node pool, so
  no request reaches a rule on that count.

This change is only api/openapi.yaml and the code that make generate
writes from it (models.gen.go, server.gen.go). The handler does not
read the field yet. The next changes store it, check it and use it.

Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com>

* feat(controller): store controlPlaneEndpoint in the clusters table

The clusters table gets three nullable columns for the API server
endpoint that a cluster was created with: control_plane_endpoint_type,
control_plane_endpoint_host and control_plane_endpoint_port. db.Cluster
gets the fields ControlPlaneEndpointType, ControlPlaneEndpointHost and
ControlPlaneEndpointPort. The type says who manages the endpoint. The
one type is External, an endpoint that NVKE does not manage. The host
and the port are the resolved endpoint.

A cluster without the field stores NULL in the three columns, which is
what each existing row has after the migration. An empty type marks
such a row. control_plane_vip does not change.

No handler writes the fields yet and no workflow reads them. The test
proves that the values come back from a read and stay in the row
through an update of the cluster.

Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com>

* feat(controller): count controlPlaneEndpoint as a stable endpoint at each gate

db.Cluster.HasStableControlPlaneEndpoint is now true for a cluster with
an endpoint of the type External, as it is for one with a VIP. Each
gate that scales, upgrades or replaces control-plane nodes asks this
method, so the one line opens them all: scale-up, upgrade and rollout
in the cluster API, node delete, recycling, remediation, rebalance,
stuck pending nodes, surge and NodeSet replacement.

The method reads the stored type and not the host. An empty type is a
cluster without the field, and a type that this controller does not
know is no stable endpoint.

The tests run each gate with such a cluster. Recycling, remediation,
rebalance and stuck pending nodes share one check,
controlPlaneReplacementBlocked, which gets its own test.

The 400 messages and the log warnings of the gates keep their text.
Each of them is given only for a cluster with no VIP and no
controlPlaneEndpoint. allowControlPlaneWithoutVIP keeps its meaning
and its default.

No cluster has the field yet, because the create request does not
store it. A later change adds that, with the count check at create.

Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com>

* feat(controller): check controlPlaneEndpoint on cluster create

The create request is now rejected with 400 when it has both
controlPlaneEndpoint and controlPlaneVIP, when the type is not
External, when the type External has no external block, and when the
host or the port is not valid.

The host is a DNS name or an IPv4 address. A DNS name is lowercase,
has at most 253 characters, no trailing dot and no wildcard. An IPv4
address must be unicast, not loopback and not link-local, and outside
the pod and service CIDRs. The port is a number from 1 to 65535, and
6443 when the request has none.

A host of only digits and dots must be a valid IPv4 address, so that
a mistyped address does not pass as a DNS name and skip the address
rules. A DNS name is not checked against the CIDRs, because NVKE
cannot tell which addresses it resolves to. The host is not trimmed.
NVKE does not resolve or dial the endpoint.

The CIDR rule of controlPlaneVIP moves into a helper that both fields
use. Its messages keep their text, and the checks of controlPlaneVIP
do not change.

The checks come before the change that stores the value, so that no
commit stores a value without them.

Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com>

* feat(controller): use controlPlaneEndpoint for kubeadm init

kubeadm init now takes its controlPlaneEndpoint from one function,
kubeadmControlPlaneEndpoint. For a cluster with an external endpoint
the value is host:port. Without one it is the kube-vip VIP, then the
IP of the initializing node, as before. The value goes into the
ClusterConfiguration and into the request to the node agent, as
before.

NVKE also names the host of an external endpoint in
apiServer.certSANs of the ClusterConfiguration. kubeadm adds the host
of its controlPlaneEndpoint to the API server certificate by itself.
The explicit entry keeps certificate renewal and control-plane joins
correct if that default changes. A cluster without an external
endpoint gets no certSANs entry, so its configuration does not change.

The step fails for a cluster row with an endpoint type that this
controller does not know, and for an external endpoint with no host
or no port. The address goes into each certificate and each
kubeconfig of the cluster, so the step does not guess.

The kube-vip step needs no change and gets no check for the new field.
It returns with no action for a cluster without a VIP, and a cluster
with a controlPlaneEndpoint has no VIP: the create request refuses the
two fields together, and no other request writes either of them to the
cluster row. One test keeps this true: for such a cluster the step
makes no kube-vip call and runs no script on the node.

Each later step reads the endpoint back from what kubeadm wrote: the
join string, admin.conf and the Cluster API endpoint. They need no
change.

No cluster has the field yet. The next change makes the create request
store it.

Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com>

* feat(controller): accept controlPlaneEndpoint on cluster create

The create request now stores controlPlaneEndpoint in the cluster row:
the type, the host and the resolved port, which is 6443 when the
request names none. The cluster response returns the type and the
resolved host and port. The response leaves the field out when the
cluster has none.

The count check at create asks HasStableControlPlaneEndpoint of the
fields that the request would store. So a request with an external
endpoint can ask for more than one control-plane node, as one with a
VIP can.

The tests go through the service and through the HTTP handler with the
OpenAPI validator: at each level requests that are accepted and
requests that are refused, then the bounds that only the schema
checks, and a PATCH with the field, which the schema refuses. One test
checks the JSON form of the field in the response. The full table of
refused values is in the test of the check itself.

This change comes after each part that reads the value, so that no
cluster can have the field before kubeadm init uses it.

Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com>

* docs: describe controlPlaneEndpoint for workload clusters

The pages that state the VIP rule now name controlPlaneEndpoint as the
second way to give a cluster a stable API address: the cluster spec
table and the count rule in the create guide, the API address in the
two access pages, the upgrade rule in the supported platforms, and the
installation plan.

The create guide shows the object with the type External, its host
and its port, and says what the response returns. It says what the
endpoint must do before the request, and that NVKE does not resolve
or call the endpoint when it accepts the request. The access page
says that NVKE does not take a node out of the endpoint before it
restarts the API server or etcd there, so the health check of the
endpoint must do it.

The pages come after the change that stores the value, so that each
sentence is true when it is added.

Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com>

* fix(controller): reject a DNS label over 63 characters in controlPlaneEndpoint

The host check of an external control plane endpoint used
IsDNS1123Subdomain, which checks the whole length and the form of a DNS
name and not the length of each label. So a name with a label of 64
characters passed the check, and DNS has no such name.

The check now also rejects a label of more than 63 characters. The text
of the field in the spec says so, and the generated code follows it.

Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com>

* docs: say that an endpoint health check acts after the failure

The access page said that the endpoint must stop traffic to a node
through its own health check. A health check sees a failure only after
it happens, so a call can fail between the restart of the API server or
of etcd and that check. The page says so now.

Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com>

---------

Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com>
2026-11-30 20:27:49 -05:00

992 lines
36 KiB
Go

// SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package server_test
import (
"bytes"
"context"
"encoding/json"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"github.com/dsx-ai-factory/nvke/controller/api"
"github.com/dsx-ai-factory/nvke/controller/internal/capi"
"github.com/dsx-ai-factory/nvke/controller/internal/config"
"github.com/dsx-ai-factory/nvke/controller/internal/db"
"github.com/dsx-ai-factory/nvke/controller/internal/server"
"github.com/dsx-ai-factory/nvke/controller/internal/testutil"
)
func ptrString(v string) *string { return &v }
// openAPIForgeCreateClusterRequest returns a Forge create-cluster body that
// passes OpenAPI validation, so each validator case can vary one field and
// attribute any rejection to that field.
func openAPIForgeCreateClusterRequest() api.CreateClusterRequest {
return api.CreateClusterRequest{
Name: "test-cluster",
Nico: &api.NicoClusterProvider{
OrgID: testOrgID,
SiteID: uuid.MustParse("550e8400-e29b-41d4-a716-446655440001"),
VpcID: uuid.MustParse("550e8400-e29b-41d4-a716-446655440002"),
},
CniPlugin: "ovn-kubernetes",
EtcdEncrypted: false,
ControlPlaneKubernetesVersion: "1.29.7",
ControlPlaneConfig: nicoCreateControlPlaneConfig(1, false),
}
}
// stubOpenAPICreateClusterTx stubs the tx methods a forge create reaches after
// OpenAPI validation. Forge network CIDR overlap is checked in forge-console
// now, so valid requests proceed into RunInTx and need these stubs.
func stubOpenAPICreateClusterTx(mockDB *testutil.MockDB) {
mockDB.MockTx.On("CreateCluster", mock.Anything, mock.Anything).Return(
db.Cluster{ID: uuid.New(), Name: "test-cluster", KubernetesVersion: "1.29.7"},
nil,
).Maybe()
mockDB.MockTx.On("CreateControlPlaneConfiguration", mock.Anything, mock.Anything).Return(
db.ControlPlaneConfiguration{ID: uuid.New()},
nil,
).Maybe()
mockDB.MockTx.On("UpdateCluster", mock.Anything, mock.Anything).Return(db.Cluster{}, nil).Maybe()
mockDB.MockTx.On("CreateWorkflowOutboxEntry", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(
db.WorkflowOutbox{},
nil,
).Maybe()
}
// TestOpenAPIValidator_CreateCluster verifies that the OpenAPI request validator
// middleware accepts or rejects create-cluster requests based on request schema.
func TestOpenAPIValidator_CreateCluster(t *testing.T) {
t.Run("kubernetesVersion", func(t *testing.T) {
mockDB := &testutil.MockDB{}
mockDB.MockTx = &testutil.MockTx{}
mockDB.GetTx = func() db.Tx { return mockDB.MockTx }
mockDB.On("RunInTx", mock.Anything, mock.Anything).Return(nil).Maybe()
stubOpenAPICreateClusterTx(mockDB)
handler := newTestServerWithValidator(t, mockDB)
// ControlPlaneKubernetesVersion is overridden per case.
baseBody := openAPIForgeCreateClusterRequest()
tests := []struct {
name string
version string
expectReject bool
}{
{"valid version", "1.30.14", false},
{"valid version alternate", "1.29.10", false},
{"empty version", "", true},
{"only major.minor", "1.30", true},
{"only major", "1", true},
{"too many parts", "1.30.14.1", true},
{"no dots", "130", true},
{"non-numeric major", "a.30.5", true},
{"non-numeric minor", "1.b.5", true},
{"non-numeric patch", "1.30.c", true},
{"leading v", "v1.29.7", true},
{"leading V uppercase", "V1.29.7", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
body := baseBody
body.ControlPlaneKubernetesVersion = tt.version
bodyBytes, err := json.Marshal(body)
require.NoError(t, err)
req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/api/clusters", bytes.NewReader(bodyBytes))
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if tt.expectReject {
assert.Equal(t, http.StatusBadRequest, rr.Code, "expected middleware to reject invalid version")
var errBody struct {
Message string `json:"message"`
}
_ = json.Unmarshal(rr.Body.Bytes(), &errBody)
assert.NotEmpty(t, errBody.Message, "expected validation error message")
} else {
bodyStr := rr.Body.String()
isValidationError := rr.Code == http.StatusBadRequest &&
(strings.Contains(bodyStr, "pattern") || strings.Contains(bodyStr, "does not match") || strings.Contains(bodyStr, "request body"))
assert.False(t, isValidationError, "valid version should not be rejected by OpenAPI validator; got %d: %s", rr.Code, bodyStr)
}
})
}
})
t.Run("cniVersion", func(t *testing.T) {
mockDB := &testutil.MockDB{}
mockDB.MockTx = &testutil.MockTx{}
mockDB.GetTx = func() db.Tx { return mockDB.MockTx }
mockDB.On("RunInTx", mock.Anything, mock.Anything).Return(nil).Maybe()
stubOpenAPICreateClusterTx(mockDB)
handler := newTestServerWithValidator(t, mockDB)
baseBody := openAPIForgeCreateClusterRequest()
tests := []struct {
name string
cniVersion *string
expectReject bool
}{
{"omitted version", nil, false},
{"valid version", ptrString("3.31.4"), false},
{"package revision", ptrString("3.30.1-1"), true},
{"leading v", ptrString("v3.31.4"), true},
{"missing patch", ptrString("3.31"), true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
body := baseBody
body.CniVersion = tt.cniVersion
bodyBytes, err := json.Marshal(body)
require.NoError(t, err)
req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/api/clusters", bytes.NewReader(bodyBytes))
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if tt.expectReject {
assert.Equal(t, http.StatusBadRequest, rr.Code, "expected middleware to reject invalid CNI version")
bodyStr := rr.Body.String()
assert.True(t,
strings.Contains(bodyStr, "cniVersion") ||
strings.Contains(bodyStr, "pattern") ||
strings.Contains(bodyStr, "does not match") ||
strings.Contains(bodyStr, "request body"),
"invalid CNI version rejection should reference the offending field or pattern; got %d: %s", rr.Code, bodyStr)
} else {
bodyStr := rr.Body.String()
isValidationError := rr.Code == http.StatusBadRequest &&
(strings.Contains(bodyStr, "cniVersion") || strings.Contains(bodyStr, "request body"))
assert.False(t, isValidationError, "valid CNI version should not be rejected by OpenAPI validator; got %d: %s", rr.Code, bodyStr)
}
})
}
})
t.Run("clusterName", func(t *testing.T) {
mockDB := &testutil.MockDB{}
mockDB.MockTx = &testutil.MockTx{}
mockDB.GetTx = func() db.Tx { return mockDB.MockTx }
mockDB.On("RunInTx", mock.Anything, mock.Anything).Return(nil).Maybe()
stubOpenAPICreateClusterTx(mockDB)
handler := newTestServerWithValidator(t, mockDB)
baseBody := openAPIForgeCreateClusterRequest()
tests := []struct {
name string
clusterName string
expectReject bool
}{
{"valid name", "test-cluster", false},
{"valid max length", strings.Repeat("a", capi.ClusterNameMaxLength), false},
{"contains dot", "test.cluster", true},
{"contains uppercase", "Test-cluster", true},
{"over max length", strings.Repeat("a", capi.ClusterNameMaxLength+1), true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
body := baseBody
body.Name = tt.clusterName
bodyBytes, err := json.Marshal(body)
require.NoError(t, err)
req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/api/clusters", bytes.NewReader(bodyBytes))
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if tt.expectReject {
assert.Equal(t, http.StatusBadRequest, rr.Code, "expected middleware to reject invalid cluster name")
var errBody struct {
Message string `json:"message"`
}
_ = json.Unmarshal(rr.Body.Bytes(), &errBody)
assert.NotEmpty(t, errBody.Message, "expected validation error message")
} else {
bodyStr := rr.Body.String()
isValidationError := rr.Code == http.StatusBadRequest &&
(strings.Contains(bodyStr, "pattern") || strings.Contains(bodyStr, "does not match") || strings.Contains(bodyStr, "request body"))
assert.False(t, isValidationError, "valid cluster name should not be rejected by OpenAPI validator; got %d: %s", rr.Code, bodyStr)
}
})
}
})
t.Run("controlPlaneVIP", func(t *testing.T) {
mockDB := &testutil.MockDB{}
mockDB.MockTx = &testutil.MockTx{}
mockDB.GetTx = func() db.Tx { return mockDB.MockTx }
mockDB.On("RunInTx", mock.Anything, mock.Anything).Return(nil).Maybe()
stubOpenAPICreateClusterTx(mockDB)
handler := newTestServerWithValidator(t, mockDB)
baseBody := openAPIForgeCreateClusterRequest()
tests := []struct {
name string
vip string
expectReject bool
}{
{"omitted VIP", "", false},
{"valid VIP", "172.31.0.10", false},
{"invalid VIP", "not-an-ip", true},
{"IPv6 VIP", "2001:db8::1", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
body := baseBody
body.ControlPlaneVIP = tt.vip
bodyBytes, err := json.Marshal(body)
require.NoError(t, err)
req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/api/clusters", bytes.NewReader(bodyBytes))
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if tt.expectReject {
assert.Equal(t, http.StatusBadRequest, rr.Code, "expected middleware to reject invalid controlPlaneVIP")
bodyStr := rr.Body.String()
assert.True(t,
strings.Contains(bodyStr, "controlPlaneVIP") ||
strings.Contains(bodyStr, "format") ||
strings.Contains(bodyStr, "request body"),
"invalid controlPlaneVIP rejection should reference the offending field or format; got %d: %s", rr.Code, bodyStr)
} else {
bodyStr := rr.Body.String()
isValidationError := rr.Code == http.StatusBadRequest &&
(strings.Contains(bodyStr, "controlPlaneVIP") || strings.Contains(bodyStr, "request body"))
assert.False(t, isValidationError, "valid controlPlaneVIP should not be rejected by OpenAPI validator; got %d: %s", rr.Code, bodyStr)
}
})
}
})
// The schema bounds the shape of controlPlaneEndpoint: the type, the host
// length and the port range. The handler checks the rest. Both answer 400,
// and a valid value creates the cluster.
t.Run("controlPlaneEndpoint", func(t *testing.T) {
mockDB := &testutil.MockDB{}
mockDB.MockTx = &testutil.MockTx{}
mockDB.GetTx = func() db.Tx { return mockDB.MockTx }
mockDB.On("RunInTx", mock.Anything, mock.Anything).Return(nil).Maybe()
stubOpenAPICreateClusterTx(mockDB)
handler := newTestServerWithValidator(t, mockDB)
baseBytes, err := json.Marshal(openAPIForgeCreateClusterRequest())
require.NoError(t, err)
// Four labels of 63, 63, 63 and 62 characters with three dots: 254 characters.
tooLongName := strings.Repeat(strings.Repeat("a", 63)+".", 3) + strings.Repeat("a", 62)
tests := []struct {
name string
// fields are raw JSON values set on top of the base request.
fields map[string]string
wantStatus int
wantContains string
}{
{
name: "an external endpoint with a DNS name and a port",
fields: map[string]string{"controlPlaneEndpoint": `{"type":"External","external":{"host":"api.tenant-a.example.internal","port":6443}}`},
wantStatus: http.StatusCreated,
},
{
name: "an external endpoint without a port",
fields: map[string]string{"controlPlaneEndpoint": `{"type":"External","external":{"host":"172.31.0.10"}}`},
wantStatus: http.StatusCreated,
},
{
name: "a string in place of the object",
fields: map[string]string{"controlPlaneEndpoint": `"lb.example.com:6443"`},
wantStatus: http.StatusBadRequest,
wantContains: "controlPlaneEndpoint",
},
{
name: "an object without a type",
fields: map[string]string{"controlPlaneEndpoint": `{"external":{"host":"lb.example.com"}}`},
wantStatus: http.StatusBadRequest,
wantContains: "type",
},
{
name: "a type that is not in the enum yet",
fields: map[string]string{"controlPlaneEndpoint": `{"type":"Infrastructure"}`},
wantStatus: http.StatusBadRequest,
wantContains: "controlPlaneEndpoint",
},
{
name: "a block of a type that is not in the schema yet",
fields: map[string]string{"controlPlaneEndpoint": `{"type":"External","external":{"host":"lb.example.com"},"kubeVIP":{"address":"172.31.0.10"}}`},
wantStatus: http.StatusBadRequest,
wantContains: "kubeVIP",
},
{
// The schema accepts this object. Only the handler refuses it.
name: "the type External without the external block",
fields: map[string]string{"controlPlaneEndpoint": `{"type":"External"}`},
wantStatus: http.StatusBadRequest,
wantContains: "controlPlaneEndpoint.external is required",
},
{
name: "an external block without a host",
fields: map[string]string{"controlPlaneEndpoint": `{"type":"External","external":{"port":6443}}`},
wantStatus: http.StatusBadRequest,
wantContains: "host",
},
{
name: "an explicit empty host",
fields: map[string]string{"controlPlaneEndpoint": `{"type":"External","external":{"host":""}}`},
wantStatus: http.StatusBadRequest,
wantContains: "host",
},
{
name: "a host above the length limit",
fields: map[string]string{"controlPlaneEndpoint": `{"type":"External","external":{"host":"` + tooLongName + `"}}`},
wantStatus: http.StatusBadRequest,
wantContains: "host",
},
{
name: "port zero",
fields: map[string]string{"controlPlaneEndpoint": `{"type":"External","external":{"host":"lb.example.com","port":0}}`},
wantStatus: http.StatusBadRequest,
wantContains: "port",
},
{
name: "a port above the range",
fields: map[string]string{"controlPlaneEndpoint": `{"type":"External","external":{"host":"lb.example.com","port":65536}}`},
wantStatus: http.StatusBadRequest,
wantContains: "port",
},
{
name: "a port as a string",
fields: map[string]string{"controlPlaneEndpoint": `{"type":"External","external":{"host":"lb.example.com","port":"6443"}}`},
wantStatus: http.StatusBadRequest,
wantContains: "port",
},
{
// The schema accepts this host. Only the handler refuses it.
name: "a loopback host",
fields: map[string]string{"controlPlaneEndpoint": `{"type":"External","external":{"host":"127.0.0.1"}}`},
wantStatus: http.StatusBadRequest,
wantContains: "loopback",
},
{
name: "together with controlPlaneVIP",
fields: map[string]string{
"controlPlaneEndpoint": `{"type":"External","external":{"host":"lb.example.com","port":6443}}`,
"controlPlaneVIP": `"172.31.0.10"`,
},
wantStatus: http.StatusBadRequest,
wantContains: "mutually exclusive",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var body map[string]json.RawMessage
require.NoError(t, json.Unmarshal(baseBytes, &body))
for field, value := range tt.fields {
body[field] = json.RawMessage(value)
}
bodyBytes, err := json.Marshal(body)
require.NoError(t, err)
req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/api/clusters", bytes.NewReader(bodyBytes))
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
assert.Equal(t, tt.wantStatus, rr.Code, "body: %s", rr.Body.String())
if tt.wantContains != "" {
assert.Contains(t, rr.Body.String(), tt.wantContains)
}
})
}
})
}
// TestOpenAPIValidator_UpdateCluster verifies that the OpenAPI request validator
// middleware accepts or rejects update-cluster (PATCH) requests based on request schema.
func TestOpenAPIValidator_UpdateCluster(t *testing.T) {
t.Run("rejects read-only network field", func(t *testing.T) {
handler := newTestServerWithValidator(t, &testutil.MockDB{})
clusterID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440000")
req := httptest.NewRequestWithContext(t.Context(),
http.MethodPatch,
"/api/clusters/"+clusterID.String(),
bytes.NewReader([]byte(`{"network":{"podCIDR":"10.233.64.0/18"}}`)),
)
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
assert.Equal(t, http.StatusBadRequest, rr.Code)
var errBody struct {
Message string `json:"message"`
}
require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &errBody))
// kin-openapi 0.151 reports the violation through its schema error,
// prefixed with the schema and the field; the reason is what matters.
assert.Contains(t, errBody.Message, "readOnly property \"network\" in request")
})
t.Run("kubernetesVersion", func(t *testing.T) {
mockDB := &testutil.MockDB{}
mockDB.MockTx = &testutil.MockTx{}
mockDB.GetTx = func() db.Tx { return mockDB.MockTx }
mockDB.On("RunInTx", mock.Anything, mock.Anything).Return(nil).Maybe()
mockDB.MockTx.On("GetClusterForUpdate", mock.Anything, mock.Anything).Return(
db.Cluster{}, db.ErrNotFound,
).Maybe()
handler := newTestServerWithValidator(t, mockDB)
clusterID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440000")
tests := []struct {
name string
version string
expectReject bool
}{
{"valid version", "1.30.14", false},
{"valid version alternate", "1.29.10", false},
{"leading v", "v1.29.7", true},
{"only major.minor", "1.30", true},
{"empty version", "", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
version := tt.version
body := api.UpdateClusterRequest{
ControlPlaneKubernetesVersion: &version,
}
bodyBytes, err := json.Marshal(body)
require.NoError(t, err)
req := httptest.NewRequestWithContext(context.Background(), http.MethodPatch, "/api/clusters/"+clusterID.String(), bytes.NewReader(bodyBytes))
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if tt.expectReject {
assert.Equal(t, http.StatusBadRequest, rr.Code, "expected middleware to reject invalid version")
var errBody struct {
Message string `json:"message"`
}
_ = json.Unmarshal(rr.Body.Bytes(), &errBody)
assert.NotEmpty(t, errBody.Message, "expected validation error message")
} else {
bodyStr := rr.Body.String()
isValidationError := rr.Code == http.StatusBadRequest &&
(strings.Contains(bodyStr, "pattern") || strings.Contains(bodyStr, "does not match") || strings.Contains(bodyStr, "request body"))
assert.False(t, isValidationError, "valid version should not be rejected by OpenAPI validator; got %d: %s", rr.Code, bodyStr)
}
})
}
})
t.Run("accepts enableEtcdEncryption field", func(t *testing.T) {
mockDB := &testutil.MockDB{}
mockDB.MockTx = &testutil.MockTx{}
mockDB.GetTx = func() db.Tx { return mockDB.MockTx }
mockDB.On("RunInTx", mock.Anything, mock.Anything).Return(nil).Maybe()
mockDB.MockTx.On("GetClusterForUpdate", mock.Anything, mock.Anything).Return(
db.Cluster{}, db.ErrNotFound,
).Maybe()
handler := newTestServerWithValidator(t, mockDB)
clusterID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440000")
req := httptest.NewRequestWithContext(context.Background(), http.MethodPatch, "/api/clusters/"+clusterID.String(), bytes.NewReader([]byte(`{"enableEtcdEncryption":true}`)))
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
assert.Equal(t, http.StatusNotFound, rr.Code, "enableEtcdEncryption should pass OpenAPI validation and reach the handler")
})
}
// TestOpenAPIValidator_UpdateNodePoolRejectsUnknownFields verifies that node-pool
// updates reject fields that are not part of the OpenAPI request schema.
func TestOpenAPIValidator_UpdateNodePoolRejectsUnknownFields(t *testing.T) {
handler := newTestServerWithValidator(t, &testutil.MockDB{})
nodePoolID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440000")
req := httptest.NewRequestWithContext(
t.Context(),
http.MethodPatch,
"/api/nodePools/"+nodePoolID.String(),
bytes.NewReader([]byte(`{"desiredNodeCounnt":2}`)),
)
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
assert.Equal(t, http.StatusBadRequest, rr.Code)
var errBody api.GenericError
require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &errBody))
assert.Contains(t, errBody.Message, "desiredNodeCounnt")
}
// TestOpenAPIValidator_CreateClusterControlPlaneConfig verifies that the control
// plane create schema carries only the settable Nico fields. diskSelectionStrategy
// is reported on read but is not an input in either direction, so it is absent from
// NicoControlPlaneProviderCreate and the validator rejects it before the handler runs.
func TestOpenAPIValidator_CreateClusterControlPlaneConfig(t *testing.T) {
body := func(nico string) []byte {
return []byte(`{
"name": "test-cluster",
"nico": {
"orgID": "` + testOrgID + `",
"siteID": "550e8400-e29b-41d4-a716-446655440001",
"vpcID": "550e8400-e29b-41d4-a716-446655440002"
},
"cniPlugin": "ovn-kubernetes",
"controlPlaneKubernetesVersion": "1.29.7",
"etcdEncrypted": false,
"controlPlaneConfig": {"desiredCount": 3, "nico": ` + nico + `}
}`)
}
tests := []struct {
name string
nico string
expectReject bool
}{
{
name: "settable nested fields are accepted",
nico: `{"release":"ubuntu","configProfile":"default"}`,
},
{
name: "nico.diskSelectionStrategy is rejected",
nico: `{"diskSelectionStrategy":"largest"}`,
expectReject: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequestWithContext(t.Context(),
http.MethodPost, "/api/clusters", bytes.NewReader(body(tt.nico)))
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
newTestServerWithValidator(t, &testutil.MockDB{}).ServeHTTP(rr, req)
// The accepted case may still fail in the handler; assert on the message
// rather than the status code.
if tt.expectReject {
assert.Contains(t, rr.Body.String(), "diskSelectionStrategy")
return
}
assert.NotContains(t, rr.Body.String(), "diskSelectionStrategy",
"settable fields should pass OpenAPI validation")
})
}
}
// TestOpenAPIValidator_CreateRequiresExactlyOneProvider verifies that the create
// schemas require exactly one provider shape, so a handler never sees an ambiguous
// provider. CreateClusterRequest, CreateClusterControlPlaneConfig and
// NodePoolCreateConfig each reject a body carrying both nico and capi as well as
// one carrying neither. A cluster create exercises all three, because it embeds
// the control plane config and the initial node pools.
func TestOpenAPIValidator_CreateRequiresExactlyOneProvider(t *testing.T) {
const (
clusterNico = `"nico":{"orgID":"` + testOrgID + `",` +
`"siteID":"550e8400-e29b-41d4-a716-446655440001",` +
`"vpcID":"550e8400-e29b-41d4-a716-446655440002"}`
clusterInfra = `"infra":{"cluster":{"apiVersion":"infrastructure.cluster.x-k8s.io/v1beta1",` +
`"kind":"DockerCluster","metadata":{"name":"test-cluster"}}}`
cpNico = `"nico":{"instanceTypePreference":["550e8400-e29b-41d4-a716-446655440003"],` +
`"release":"ubuntu","configProfile":"default"}`
cpInfra = `"infra":{"machineTemplate":{` +
`"apiVersion":"infrastructure.cluster.x-k8s.io/v1beta1",` +
`"kind":"DockerMachineTemplate","metadata":{"name":"cp"}}}`
poolNico = `"nico":{"instanceTypeID":"550e8400-e29b-41d4-a716-446655440004",` +
`"release":"ubuntu","configProfile":"default"}`
poolInfra = `"infra":{"machineTemplate":{"apiVersion":"infrastructure.cluster.x-k8s.io/v1beta1",` +
`"kind":"DockerMachineTemplate","metadata":{"name":"worker"}}}`
)
// Provider fragments are appended, so an empty fragment leaves the enclosing
// object valid apart from the missing provider.
field := func(fragment string) string {
if fragment == "" {
return ""
}
return "," + fragment
}
body := func(cluster, controlPlane, nodePool string) []byte {
return []byte(`{
"name": "test-cluster",
"cniPlugin": "ovn-kubernetes",
"controlPlaneKubernetesVersion": "1.29.7",
"etcdEncrypted": false` + field(cluster) + `,
"controlPlaneConfig": {"desiredCount": 3` + field(controlPlane) + `},
"nodePools": [
{"name":"worker","nodeNamePrefix":"worker","desiredNodeCount":1` + field(nodePool) + `}
]
}`)
}
tests := []struct {
name string
cluster string
controlPlane string
nodePool string
expectReject bool
}{
{
name: "cluster carrying both providers",
cluster: clusterNico + "," + clusterInfra,
controlPlane: cpNico,
nodePool: poolNico,
expectReject: true,
},
{
name: "cluster carrying neither provider",
controlPlane: cpNico,
nodePool: poolNico,
expectReject: true,
},
{
name: "control plane config carrying both providers",
cluster: clusterNico,
controlPlane: cpNico + "," + cpInfra,
nodePool: poolNico,
expectReject: true,
},
{
name: "control plane config carrying neither provider",
cluster: clusterNico,
nodePool: poolNico,
expectReject: true,
},
{
name: "node pool carrying both providers",
cluster: clusterNico,
controlPlane: cpNico,
nodePool: poolNico + "," + poolInfra,
expectReject: true,
},
{
name: "node pool carrying neither provider",
cluster: clusterNico,
controlPlane: cpNico,
expectReject: true,
},
{
name: "one provider shape per object is accepted",
cluster: clusterNico,
controlPlane: cpNico,
nodePool: poolNico,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequestWithContext(t.Context(),
http.MethodPost, "/api/clusters",
bytes.NewReader(body(tt.cluster, tt.controlPlane, tt.nodePool)))
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
newTestServerWithValidator(t, &testutil.MockDB{}).ServeHTTP(rr, req)
// Distinguish a schema rejection from a handler rejection by the validator's message.
if tt.expectReject {
assert.Equal(t, http.StatusBadRequest, rr.Code, "body: %s", rr.Body.String())
assert.Contains(t, rr.Body.String(), "request body has an error",
"should be rejected by schema validation rather than by the handler")
return
}
assert.NotContains(t, rr.Body.String(), "request body has an error",
"exactly one provider shape per object should pass schema validation")
})
}
}
// TestOpenAPIValidator_UpdateClusterControlPlaneConfig verifies that the control
// plane update schema carries only the configurable Nico fields. The control plane
// always installs to the smallest disk, so diskSelectionStrategy is absent from
// NicoControlPlaneProviderUpdate and the validator rejects it.
func TestOpenAPIValidator_UpdateClusterControlPlaneConfig(t *testing.T) {
clusterID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440000")
tests := []struct {
name string
body string
expectReject bool
}{
{
name: "configurable nested fields are accepted",
body: `{"controlPlaneConfig":{"nico":{"release":"ubuntu","configProfile":"default"}}}`,
expectReject: false,
},
{
name: "nico.diskSelectionStrategy is rejected",
body: `{"controlPlaneConfig":{"nico":{"diskSelectionStrategy":"largest"}}}`,
expectReject: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
mockDB := &testutil.MockDB{}
mockDB.MockTx = &testutil.MockTx{}
mockDB.GetTx = func() db.Tx { return mockDB.MockTx }
mockDB.On("RunInTx", mock.Anything, mock.Anything).Return(nil).Maybe()
mockDB.MockTx.On("GetClusterForUpdate", mock.Anything, clusterID).Return(db.Cluster{}, db.ErrNotFound).Maybe()
req := httptest.NewRequestWithContext(t.Context(),
http.MethodPatch,
"/api/clusters/"+clusterID.String(),
bytes.NewReader([]byte(tt.body)),
)
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
newTestServerWithValidator(t, mockDB).ServeHTTP(rr, req)
if tt.expectReject {
assert.Equal(t, http.StatusBadRequest, rr.Code, "body: %s", rr.Body.String())
return
}
assert.Equal(t, http.StatusNotFound, rr.Code,
"should pass OpenAPI validation and reach the handler, body: %s", rr.Body.String())
})
}
}
// TestOpenAPIValidator_UpdateNodePool verifies that the update-node-pool schema
// accepts only the mutable subset of the nested nico fields. The fields that are
// fixed at creation are absent from NicoNodePoolProviderUpdate, so the validator
// rejects them before the handler runs; nothing in the service layer re-checks them.
func TestOpenAPIValidator_UpdateNodePool(t *testing.T) {
nodePoolID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440010")
newHandler := func(t *testing.T) http.Handler {
t.Helper()
mockDB := &testutil.MockDB{}
mockDB.MockTx = &testutil.MockTx{}
mockDB.GetTx = func() db.Tx { return mockDB.MockTx }
mockDB.On("RunInTx", mock.Anything, mock.Anything).Return(nil).Maybe()
mockDB.On("GetNodePool", mock.Anything, nodePoolID).Return(db.NodePool{}, db.ErrNotFound).Maybe()
mockDB.MockTx.On("GetNodePool", mock.Anything, nodePoolID).Return(db.NodePool{}, db.ErrNotFound).Maybe()
return newTestServerWithValidator(t, mockDB)
}
tests := []struct {
name string
body string
expectReject bool
}{
{
name: "mutable nested fields are accepted",
body: `{"nico":{"subnetIDs":["550e8400-e29b-41d4-a716-446655440001"],"release":"ubuntu","configProfile":"default"}}`,
expectReject: false,
},
{
name: "nico.instanceTypeID is rejected",
body: `{"nico":{"instanceTypeID":"550e8400-e29b-41d4-a716-446655440002"}}`,
expectReject: true,
},
{
name: "nico.infinibandPartitionID is rejected",
body: `{"nico":{"infinibandPartitionID":"550e8400-e29b-41d4-a716-446655440003"}}`,
expectReject: true,
},
{
name: "nico.nvLinkLogicalPartitionID is accepted",
body: `{"nico":{"nvLinkLogicalPartitionID":"550e8400-e29b-41d4-a716-446655440004"}}`,
expectReject: false,
},
{
name: "nico.sshKeyGroupIDs is rejected",
body: `{"nico":{"sshKeyGroupIDs":["550e8400-e29b-41d4-a716-446655440005"]}}`,
expectReject: true,
},
{
name: "a full nico object echoed from GET is rejected",
body: `{"nico":{"subnetIDs":[],"vpcPrefixIDs":[],"instanceTypeID":"550e8400-e29b-41d4-a716-446655440002","sshKeyGroupIDs":[],"release":"ubuntu","configProfile":"default"}}`,
expectReject: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequestWithContext(t.Context(),
http.MethodPatch,
"/api/nodePools/"+nodePoolID.String(),
bytes.NewReader([]byte(tt.body)),
)
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
newHandler(t).ServeHTTP(rr, req)
if tt.expectReject {
assert.Equal(t, http.StatusBadRequest, rr.Code, "body: %s", rr.Body.String())
return
}
assert.Equal(t, http.StatusNotFound, rr.Code,
"should pass OpenAPI validation and reach the handler, body: %s", rr.Body.String())
})
}
}
// TestStdServerErrorStatus_MalformedPathUUID verifies that requests with a malformed
// UUID path parameter return HTTP 400 (client error) rather than HTTP 500.
func TestStdServerErrorStatus_MalformedPathUUID(t *testing.T) {
mockDB := &testutil.MockDB{}
mockDB.MockTx = &testutil.MockTx{}
mockDB.GetTx = func() db.Tx { return mockDB.MockTx }
handler := newTestServerWithValidator(t, mockDB)
cases := []struct {
name string
method string
path string
}{
{"DELETE cluster with trailing $", http.MethodDelete, "/api/clusters/a95a73b2-4ebc-4d36-946f-ee88dffe45d2$"},
{"GET cluster with non-uuid", http.MethodGet, "/api/clusters/not-a-uuid"},
{"PATCH cluster with non-uuid", http.MethodPatch, "/api/clusters/not-a-uuid"},
{"GET node pool with non-uuid", http.MethodGet, "/api/nodePools/not-a-uuid"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
var body *bytes.Reader
if tc.method == http.MethodPatch {
body = bytes.NewReader([]byte(`{}`))
} else {
body = bytes.NewReader(nil)
}
req := httptest.NewRequestWithContext(context.Background(), tc.method, tc.path, body)
if tc.method == http.MethodPatch {
req.Header.Set("Content-Type", "application/json")
}
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
assert.Equal(t, http.StatusBadRequest, rr.Code, "malformed UUID should return 400, got %d: %s", rr.Code, rr.Body.String())
})
}
}
// newTestServerWithValidator builds an HTTP handler with the same OpenAPI validator
// middleware as production. The caller must configure mockDB (GetTx, RunInTx, and
// any tx method mocks) as needed; invalid requests are rejected by the validator.
// When MockTx is set, CreateCluster path stubs are installed so valid forge
// creates (no longer blocked by controller Forge CIDR overlap checks) do not panic.
func newTestServerWithValidator(t *testing.T, mockDB *testutil.MockDB) http.Handler {
t.Helper()
if mockDB != nil && mockDB.MockTx != nil {
stubOpenAPICreateClusterTx(mockDB)
}
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelError}))
cfg := config.Config{
ManagedByK8sPlatform: false,
ProfilesDir: "./profiles",
}
srv, err := server.NewServer(cfg, logger, mockDB, nil, nil, nil)
require.NoError(t, err)
require.NotNil(t, srv)
return srv.Handler
}
func TestOpenAPIValidator_MachineMetadataIsCreateOnly(t *testing.T) {
for _, field := range []string{"machineAnnotations", "machineLabels"} {
t.Run(field, func(t *testing.T) {
handler := newTestServerWithValidator(t, &testutil.MockDB{})
req := httptest.NewRequestWithContext(t.Context(), http.MethodPatch,
"/api/nodePools/550e8400-e29b-41d4-a716-446655440000",
strings.NewReader(`{"`+field+`":{"example.com/key":"value"}}`))
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
require.Equal(t, http.StatusBadRequest, rr.Code, rr.Body.String())
require.Contains(t, rr.Body.String(), field)
})
}
}
// The controlPlaneEndpoint of a cluster is fixed at creation. PATCH does not
// have the field in its schema, so the validator rejects it before the handler
// runs.
func TestOpenAPIValidator_ControlPlaneEndpointIsCreateOnly(t *testing.T) {
handler := newTestServerWithValidator(t, &testutil.MockDB{})
req := httptest.NewRequestWithContext(t.Context(), http.MethodPatch,
"/api/clusters/550e8400-e29b-41d4-a716-446655440000",
strings.NewReader(`{"controlPlaneEndpoint":{"type":"External","external":{"host":"lb.example.com","port":6443}}}`))
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
require.Equal(t, http.StatusBadRequest, rr.Code, rr.Body.String())
require.Contains(t, rr.Body.String(), "controlPlaneEndpoint")
}
func TestOpenAPIValidator_ControlPlaneMachineMetadataIsCreateOnly(t *testing.T) {
for _, field := range []string{"machineAnnotations", "machineLabels"} {
t.Run(field, func(t *testing.T) {
handler := newTestServerWithValidator(t, &testutil.MockDB{})
req := httptest.NewRequestWithContext(t.Context(), http.MethodPatch,
"/api/clusters/550e8400-e29b-41d4-a716-446655440000",
strings.NewReader(`{"controlPlaneConfig":{"`+field+`":{"example.com/key":"value"}}}`))
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
require.Equal(t, http.StatusBadRequest, rr.Code, rr.Body.String())
require.Contains(t, rr.Body.String(), field)
})
}
}