🐛 fix: harden operator reconciliation and install

This commit is contained in:
2026-08-13 03:29:29 +07:00
parent ab662a4fa4
commit e90dc8382b
28 changed files with 800 additions and 71 deletions
+17 -4
View File
@@ -96,19 +96,32 @@ func JVMEnv(jvm v1alpha1.JVMOptions, limitMB int32) []corev1.EnvVar {
return env
}
func UserEnv(base []corev1.EnvVar, extra []v1alpha1.EnvVar) []corev1.EnvVar {
func UserEnv(base []corev1.EnvVar, extra []v1alpha1.EnvVar, protected ...string) []corev1.EnvVar {
index := make(map[string]int, len(base))
reserved := make(map[string]struct{}, len(protected))
for _, name := range protected {
reserved[name] = struct{}{}
}
for i, env := range base {
index[env.Name] = i
}
for _, e := range extra {
if _, ok := reserved[e.Name]; ok {
continue
}
var valueFrom *corev1.EnvVarSource
value := e.Value
if e.ValueFrom != nil {
valueFrom = e.ValueFrom.DeepCopy()
value = ""
}
if i, ok := index[e.Name]; ok {
base[i].Value = e.Value
base[i].ValueFrom = nil
base[i].Value = value
base[i].ValueFrom = valueFrom
continue
}
index[e.Name] = len(base)
base = append(base, corev1.EnvVar{Name: e.Name, Value: e.Value})
base = append(base, corev1.EnvVar{Name: e.Name, Value: value, ValueFrom: valueFrom})
}
return base
}
@@ -125,6 +125,35 @@ func TestUserEnvClearsValueFromOnOverride(t *testing.T) {
}
}
func TestUserEnvSupportsValueFrom(t *testing.T) {
extra := []v1alpha1.EnvVar{{
Name: "FROM_SECRET",
Value: "ignored",
ValueFrom: &corev1.EnvVarSource{SecretKeyRef: &corev1.SecretKeySelector{
LocalObjectReference: corev1.LocalObjectReference{Name: "settings"},
Key: "value",
}},
}}
got := UserEnv(nil, extra)
if len(got) != 1 || got[0].ValueFrom == nil || got[0].ValueFrom.SecretKeyRef == nil {
t.Fatalf("valueFrom was not preserved: %+v", got)
}
if got[0].ValueFrom.SecretKeyRef.Name != "settings" {
t.Errorf("secret name = %q", got[0].ValueFrom.SecretKeyRef.Name)
}
if got[0].Value != "" {
t.Errorf("literal value = %q, want empty with valueFrom", got[0].Value)
}
}
func TestUserEnvDoesNotOverrideProtectedValues(t *testing.T) {
base := []corev1.EnvVar{{Name: "MINIKURA_API_KEY", Value: "managed"}}
got := UserEnv(base, []v1alpha1.EnvVar{{Name: "MINIKURA_API_KEY", Value: "user"}}, "MINIKURA_API_KEY")
if got[0].Value != "managed" {
t.Errorf("protected value = %q, want managed", got[0].Value)
}
}
func TestUserEnvAppendsUnknownKeys(t *testing.T) {
base := []corev1.EnvVar{{Name: "TYPE", Value: "PAPER"}}
got := UserEnv(base, []v1alpha1.EnvVar{{Name: "EXTRA", Value: "1"}})
@@ -84,13 +84,12 @@ func minecraftEnv(mc *v1alpha1.MinecraftServer) []corev1.EnvVar {
SecretKeyRef: &corev1.SecretKeySelector{
LocalObjectReference: corev1.LocalObjectReference{Name: mc.Spec.APIKeySecretRef},
Key: "api-key",
Optional: ptr(true),
},
},
})
}
return UserEnv(env, mc.Spec.Env)
return UserEnv(env, mc.Spec.Env, "EULA", "MINIKURA_API_KEY")
}
func minecraftPodSpec(mc *v1alpha1.MinecraftServer, stateful bool) corev1.PodSpec {
@@ -195,6 +195,9 @@ func TestMinecraftAPIKeyAndOptionalEnv(t *testing.T) {
if e.ValueFrom.SecretKeyRef.Name != "minikura-key" || e.ValueFrom.SecretKeyRef.Key != "api-key" {
t.Errorf("secret ref = %+v", e.ValueFrom.SecretKeyRef)
}
if e.ValueFrom.SecretKeyRef.Optional != nil {
t.Error("API key Secret must be required")
}
}
}
if !found {
@@ -202,6 +205,21 @@ func TestMinecraftAPIKeyAndOptionalEnv(t *testing.T) {
}
}
func TestMinecraftProtectedEnvCannotBeOverridden(t *testing.T) {
mc := testServer()
mc.Spec.APIKeySecretRef = "minikura-key"
mc.Spec.Env = []v1alpha1.EnvVar{{Name: "EULA", Value: "FALSE"}, {Name: "MINIKURA_API_KEY", Value: "inline"}}
env := minecraftEnv(mc)
if got, _ := envValue(env, "EULA"); got != "TRUE" {
t.Errorf("EULA = %q", got)
}
for _, item := range env {
if item.Name == "MINIKURA_API_KEY" && (item.ValueFrom == nil || item.ValueFrom.SecretKeyRef == nil) {
t.Error("API key secret reference was overridden")
}
}
}
func TestStatefulSetDefaultStorage(t *testing.T) {
mc := testServer()
mc.Spec.StorageSize = ""
+21 -5
View File
@@ -1,23 +1,39 @@
package resources
import (
"crypto/sha256"
"fmt"
"strings"
v1alpha1 "github.com/YuzuZensai/Minikura/operator/api/v1alpha1"
)
func ServerName(name string) string { return fmt.Sprintf("minecraft-%s", name) }
const dnsLabelMaxLength = 63
func ServerName(name string) string { return limitedName("minecraft-"+name, dnsLabelMaxLength) }
func ProxyName(kind v1alpha1.ProxyKind, name string) string {
return fmt.Sprintf("%s-%s", strings.ToLower(string(kind)), name)
return limitedName(fmt.Sprintf("%s-%s", strings.ToLower(string(kind)), name), dnsLabelMaxLength)
}
func ConfigMapName(base string) string { return limitedName(base+"-config", dnsLabelMaxLength) }
func limitedName(name string, limit int) string {
if len(name) <= limit {
return name
}
sum := sha256.Sum256([]byte(name))
suffix := fmt.Sprintf("-%x", sum[:4])
return strings.TrimRight(name[:limit-len(suffix)], "-") + suffix
}
func labelValue(value string) string {
return limitedName(value, dnsLabelMaxLength)
}
func ConfigMapName(base string) string { return base + "-config" }
func ServerLabels(mc *v1alpha1.MinecraftServer) map[string]string {
return map[string]string{
"app": ServerName(mc.Name),
v1alpha1.LabelServerType: strings.ToLower(string(mc.Spec.Type)),
v1alpha1.LabelServerID: mc.Name,
v1alpha1.LabelServerID: labelValue(mc.Name),
v1alpha1.LabelManagedBy: v1alpha1.ManagerName,
}
}
@@ -26,7 +42,7 @@ func ProxyLabels(rp *v1alpha1.ReverseProxyServer) map[string]string {
return map[string]string{
"app": ProxyName(rp.Spec.Type, rp.Name),
v1alpha1.LabelServerType: strings.ToLower(string(rp.Spec.Type)),
v1alpha1.LabelProxyID: rp.Name,
v1alpha1.LabelProxyID: labelValue(rp.Name),
v1alpha1.LabelManagedBy: v1alpha1.ManagerName,
}
}
@@ -1,6 +1,7 @@
package resources
import (
"strings"
"testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@@ -23,6 +24,36 @@ func TestServerAndProxyNames(t *testing.T) {
}
}
func TestGeneratedNamesFitDNSLabelsAndRemainDistinct(t *testing.T) {
name := strings.Repeat("a", 63)
server := ServerName(name)
config := ConfigMapName(server)
proxy := ProxyName(v1alpha1.ProxyBungeeCord, name)
for kind, got := range map[string]string{"server": server, "config": config, "proxy": proxy} {
if len(got) > 63 {
t.Errorf("%s name length = %d: %q", kind, len(got), got)
}
if strings.HasSuffix(got, "-") {
t.Errorf("%s name has invalid suffix: %q", kind, got)
}
}
if ServerName(name) == ServerName(strings.Repeat("a", 62)+"b") {
t.Error("different long names collided")
}
}
func TestLongResourceNamesProduceValidLabelValues(t *testing.T) {
name := strings.Repeat("a", 63)
mc := &v1alpha1.MinecraftServer{ObjectMeta: metav1.ObjectMeta{Name: name}}
if got := ServerLabels(mc)[v1alpha1.LabelServerID]; len(got) > 63 {
t.Errorf("server-id label length = %d", len(got))
}
rp := &v1alpha1.ReverseProxyServer{ObjectMeta: metav1.ObjectMeta{Name: name}}
if got := ProxyLabels(rp)[v1alpha1.LabelProxyID]; len(got) > 63 {
t.Errorf("proxy-id label length = %d", len(got))
}
}
func TestServerLabels(t *testing.T) {
mc := &v1alpha1.MinecraftServer{
ObjectMeta: metav1.ObjectMeta{Name: "smp"},
@@ -1,6 +1,8 @@
package resources
import (
"strings"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@@ -60,13 +62,36 @@ func proxyEnv(rp *v1alpha1.ReverseProxyServer) []corev1.EnvVar {
SecretKeyRef: &corev1.SecretKeySelector{
LocalObjectReference: corev1.LocalObjectReference{Name: rp.Spec.APIKeySecretRef},
Key: "api-key",
Optional: ptr(true),
},
},
})
}
protected := []string{"MINIKURA_API_KEY"}
if rp.Spec.BackendURL != "" {
apiURL := strings.TrimRight(rp.Spec.BackendURL, "/")
env = append(env,
corev1.EnvVar{Name: "MINIKURA_API_URL", Value: apiURL},
corev1.EnvVar{Name: "MINIKURA_WEBSOCKET_URL", Value: websocketURL(apiURL)},
)
protected = append(protected, "MINIKURA_API_URL", "MINIKURA_WEBSOCKET_URL")
}
if rp.Spec.Type == v1alpha1.ProxyVelocity && rp.Spec.PluginURL != "" {
env = append(env, corev1.EnvVar{Name: "PLUGINS", Value: rp.Spec.PluginURL})
protected = append(protected, "PLUGINS")
}
return UserEnv(env, rp.Spec.Env)
return UserEnv(env, rp.Spec.Env, protected...)
}
func websocketURL(apiURL string) string {
url := strings.TrimRight(apiURL, "/") + "/servers/ws"
if strings.HasPrefix(url, "https://") {
return "wss://" + strings.TrimPrefix(url, "https://")
}
if strings.HasPrefix(url, "http://") {
return "ws://" + strings.TrimPrefix(url, "http://")
}
return url
}
func ProxyDeployment(rp *v1alpha1.ReverseProxyServer) *appsv1.Deployment {
@@ -105,9 +105,58 @@ func TestProxyAPIKeyEnv(t *testing.T) {
if e.ValueFrom == nil || e.ValueFrom.SecretKeyRef.Name != "proxy-key" {
t.Errorf("secret ref = %+v", e.ValueFrom)
}
if e.ValueFrom.SecretKeyRef.Optional != nil {
t.Error("API key Secret must be required")
}
}
}
if !found {
t.Error("MINIKURA_API_KEY missing")
}
}
func TestProxyPluginBackendWiring(t *testing.T) {
rp := testProxy()
rp.Spec.APIKeySecretRef = "proxy-key"
rp.Spec.BackendURL = "https://backend.example.com/api/"
rp.Spec.PluginURL = "https://downloads.example.com/minikura.jar"
rp.Spec.Env = []v1alpha1.EnvVar{
{Name: "MINIKURA_API_URL", Value: "http://attacker"},
{Name: "PLUGINS", Value: "http://attacker/plugin.jar"},
}
env := proxyEnv(rp)
want := map[string]string{
"MINIKURA_API_URL": "https://backend.example.com/api",
"MINIKURA_WEBSOCKET_URL": "wss://backend.example.com/api/servers/ws",
"PLUGINS": "https://downloads.example.com/minikura.jar",
}
for name, value := range want {
if got, ok := envValue(env, name); !ok || got != value {
t.Errorf("%s = %q, %v; want %q", name, got, ok, value)
}
}
}
func TestBungeeCordDoesNotInstallVelocityPlugin(t *testing.T) {
rp := testProxy()
rp.Spec.Type = v1alpha1.ProxyBungeeCord
rp.Spec.PluginURL = "https://downloads.example.com/minikura.jar"
if _, ok := envValue(proxyEnv(rp), "PLUGINS"); ok {
t.Error("Velocity plugin must not be installed on BungeeCord")
}
}
func TestProxyLegacyEnvWiringRemainsAvailableWhenFieldsAreUnset(t *testing.T) {
rp := testProxy()
rp.Spec.Env = []v1alpha1.EnvVar{
{Name: "MINIKURA_API_URL", Value: "http://legacy-backend/api"},
{Name: "PLUGINS", Value: "http://legacy/plugin.jar"},
}
env := proxyEnv(rp)
if got, _ := envValue(env, "MINIKURA_API_URL"); got != "http://legacy-backend/api" {
t.Errorf("legacy API URL = %q", got)
}
if got, _ := envValue(env, "PLUGINS"); got != "http://legacy/plugin.jar" {
t.Errorf("legacy plugin URL = %q", got)
}
}