feat(rcon): provision per-server RCON so the console, player list and permissions work

A server created through the panel never had RCON. CreateServer built a
MinecraftServerSpec without a Rcon block at all, so the field took its zero value
and every downstream consumer read Enabled=false. Nothing failed loudly: the
operator skips the probe when RCON is off and marks the server Ready on pod
readiness alone, so the panel showed "运行中" for a server the control plane could
not talk to. Everything that rides the write channel (spec §8 写=RCON) was dead —
the online-player list returned nothing because Status.Players is only ever
sampled by the probe, and console writes answered 503 ErrConsoleUnavailable
because internal/api/console.go refuses when Enabled is false.

The whole RCON machinery already existed — builders gate the service port,
container port, preStop save-and-stop hook and the RCON_* env on Spec.Rcon,
the reconciler probes and reports, console.go dials, the NetworkPolicy opens
25575 to {api, operator}. The only thing missing was that nobody ever turned it
on or created a password. This wires the three layers that were absent.

Provisioning lives in the operator, not in felis-api. felis-api holds secrets:get
and not create, and giving it create solely to mint a password it immediately
stops caring about (console.go re-reads the Secret at command time) would widen
the API's powers for nothing. The operator already reads every Secret in the
namespace, so adding create there grants no read it did not have. It also makes
provisioning declarative: a Secret deleted by hand comes back on the next pass, a
controller reference garbage-collects it with the server so no delete path has to
remember it, and a server that predates RCON only needs spec.rcon filled in for
the password to appear. The name comes from naming.RconSecretName so felis-api,
`felis setup` and the operator cannot drift apart on it.

RCON is enabled per system service rather than by default, because enabling it on
a backend that serves no RCON listener is destructive rather than merely useless:
the operator gates readiness on the probe, so such a server never leaves Starting
and is eventually marked Failed. The login limbo is exactly that backend
(LOOHP/Limbo has no RCON) and it is the front door, so it stays off; the lobby
runs Paper and is administered through the panel like any other server, so it is
on.

Paper only reads RCON settings from server.properties, so the operator's injected
RCON_PASSWORD did nothing on its own — felis-lobby's entrypoint now writes the
three keys on every boot. Rewriting them each time makes the copy in the world
volume derived state rather than the source of truth, so an owner who edits them
through the panel's file editor cannot lock the control plane out of their own
server. Without a password it sets enable-rcon=false and warns rather than
refusing to start: unlike the forwarding secret, a missing RCON password degrades
the server rather than making it unsafe.

That password landing in server.properties is a §286 exposure (RCON 密码绝不下发
前端), since server.properties is readable through the file editor. It is redacted
on read rather than the file being denied outright the way config/paper-global.yml
is: the forwarding secret is cluster-wide material that merely happens to sit in
the volume, whereas server.properties is the single most-edited config an owner
has, and hiding one line should not cost them MOTD, difficulty and view-distance.
The write path is deliberately left alone — the boot-time rewrite restores the
real value, which is what makes redacting rather than denying safe here.

Also guards idle auto-stop on Rcon.Enabled. Status.Players is only meaningful
when the probe ran; with RCON off it keeps its zero value, which that branch would
have read as "empty" and used to stop a server full of people. AutoStopEnabled is
not currently settable through any path, so this is a latent footgun rather than a
live bug, but it is one line and the alternative is discovering it in production.

Checks: the operator provisions a missing Secret with a 32-hex-char password and a
controller reference, and does not rotate an existing one; idle auto-stop stays
inert without RCON; the editor redacts rcon.password from the world root's
server.properties while leaving the rest of the file (and a plugin's own nested
copy) intact; login has RCON off and lobby has it on with the shared secret name;
CreateServer sets the block. That last one departs from K8sCluster being
integration-tested against a live cluster: this defect was a struct literal
missing a field, it shipped, and a fake client is enough to pin a struct literal.

Existing servers are NOT migrated by this change — CreateServer only covers new
ones and ensureSystemServers is create-if-absent, so a `felis setup` re-run will
not touch an existing lobby. A deployed install additionally needs the
felis-lobby image rebuilt and re-imported for the entrypoint change, and its pods
recreated, before the RCON keys reach server.properties.
This commit is contained in:
flyemoji committed 2026-07-21 00:12:37 +09:00
1 parent b3989fa4af
commit 694e3cb800
11 files changed
+461 -6

No files matched your search

+96 -1
View File
@@ -6,6 +6,8 @@ package operator
import (
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"time"
@@ -84,6 +86,18 @@ func (r *Reconciler) reconcileRunning(ctx context.Context, server *v1alpha1.Mine
return ctrl.Result{}, err
}
// Before the StatefulSet, not after: buildEnv wires RCON_PASSWORD as a
// secretKeyRef, so a pod created ahead of its Secret never starts — it sits in
// CreateContainerConfigError, which reads like a broken image rather than a
// missing key.
if err := r.ensureRconSecret(ctx, server); err != nil {
r.markStarting(server, "RconSecretUnavailable", err.Error())
if perr := r.patchStatus(ctx, server); perr != nil {
return ctrl.Result{}, perr
}
return ctrl.Result{RequeueAfter: requeueSecret}, nil
}
desired, err := buildStatefulSet(server, 1)
if err != nil {
// A malformed spec (e.g. bad storage quantity) is terminal until edited.
@@ -151,7 +165,10 @@ func (r *Reconciler) reconcileRunning(ctx context.Context, server *v1alpha1.Mine
// player tally is zero, track the empty duration and auto-stop when the
// configured timeout expires. The existing RCON probe already supplies
// the player count — no extra network cost.
if server.Spec.Idle.AutoStopEnabled && server.Spec.Idle.EmptySecondsBeforeStop > 0 {
// Rcon.Enabled is part of the condition because `players` is only a real tally
// when the probe above ran: with RCON off it keeps its zero value, which this
// branch would read as "empty" and use to stop a server full of people.
if server.Spec.Rcon.Enabled && server.Spec.Idle.AutoStopEnabled && server.Spec.Idle.EmptySecondsBeforeStop > 0 {
if players.Online == 0 {
if server.Status.EmptySince == nil {
t := r.now()
@@ -228,6 +245,84 @@ func (r *Reconciler) ensureServices(ctx context.Context, server *v1alpha1.Minecr
return endpointAddress, nil
}
// ensureRconSecret creates the per-server RCON password Secret named by
// spec.rcon.secretRef the first time a server with RCON enabled reconciles, and
// leaves it alone afterwards. Provisioning lives here rather than in felis-api's
// CreateServer for three reasons: it is declarative (a server whose Secret was
// deleted heals on the next pass instead of staying permanently unreachable), the
// controller reference makes Kubernetes garbage-collect the Secret with the server
// so no delete path has to remember it, and it backfills — a server created before
// RCON existed only needs spec.rcon filled in, and the password appears without
// anyone handling it. felis-api never mints the password and never needs to: it
// reads the Secret at command time (internal/api/console.go rconPassword).
//
// The password is 32 hex chars from crypto/rand. It is generated once and never
// rotated here: rewriting it would leave the running server authenticating with
// the old value until its pod restarts, so rotation belongs to an explicit
// operation, not to a reconcile that runs every few seconds.
func (r *Reconciler) ensureRconSecret(ctx context.Context, server *v1alpha1.MinecraftServer) error {
if !server.Spec.Rcon.Enabled {
return nil
}
ref := server.Spec.Rcon.SecretRef
if ref.Name == "" || ref.Key == "" {
return fmt.Errorf("rcon.secretRef.name and .key are required when rcon is enabled")
}
var existing corev1.Secret
err := r.Get(ctx, types.NamespacedName{Namespace: server.Namespace, Name: ref.Name}, &existing)
if err == nil {
if _, ok := existing.Data[ref.Key]; ok {
return nil
}
return fmt.Errorf("secret %s exists but has no key %q", ref.Name, ref.Key)
}
if !apierrors.IsNotFound(err) {
return err
}
password, err := randomRconPassword()
if err != nil {
return err
}
secret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: ref.Name,
Namespace: server.Namespace,
Labels: map[string]string{v1alpha1.LabelServer: server.Name},
},
Type: corev1.SecretTypeOpaque,
// Data, not StringData: StringData is a write-only convenience the API server
// folds into Data, so anything reading the object back — including this
// package's own tests — would see an empty value. Encoding here keeps the
// object self-consistent the moment it is built.
Data: map[string][]byte{ref.Key: []byte(password)},
}
if err := controllerutil.SetControllerReference(server, secret, r.Scheme); err != nil {
return err
}
if err := r.Create(ctx, secret); err != nil {
// Another reconcile (or a racing replica) won: that Secret is as good as
// this one, so treat the collision as success rather than thrashing.
if apierrors.IsAlreadyExists(err) {
return nil
}
return err
}
return nil
}
// randomRconPassword returns 16 crypto/rand bytes as hex. Hex, not base64: the
// value is written verbatim into server.properties, whose parser treats the line
// as raw text to end-of-line, and hex avoids every character (=, :, \, whitespace)
// that a properties file or a shell round-trip could interpret.
func randomRconPassword() (string, error) {
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
return "", fmt.Errorf("generate rcon password: %w", err)
}
return hex.EncodeToString(b[:]), nil
}
func (r *Reconciler) rconPassword(ctx context.Context, server *v1alpha1.MinecraftServer) (string, error) {
ref := server.Spec.Rcon.SecretRef
if ref.Name == "" || ref.Key == "" {
+70
View File
@@ -640,3 +640,73 @@ func TestReconcileRunning_StartDurationObservedOnce(t *testing.T) {
t.Errorf("startRequestedAt = %v after Stop, want nil so the next start re-anchors", s.Status.StartRequestedAt)
}
}
// A server whose RCON Secret does not exist yet is the normal case on first
// reconcile — felis-api writes spec.rcon.secretRef but holds secrets:get, not
// create, so the name it points at is a promise the operator has to keep. Before
// this the server sat in Starting/RconSecretUnavailable forever.
func TestReconcileProvisionsMissingRconSecret(t *testing.T) {
r, c := newReconciler(t, fakeProber{}, runningServer())
reconcile(t, r, "survival")
var secret corev1.Secret
if err := c.Get(context.Background(),
types.NamespacedName{Namespace: "minecraft", Name: "survival-rcon"}, &secret); err != nil {
t.Fatalf("expected the operator to create the rcon Secret: %v", err)
}
pw := string(secret.Data["password"])
if pw == "" {
t.Fatal("rcon Secret was created with an empty password")
}
// 16 random bytes as hex. An assertion on the shape, not the value: a password
// short enough to guess is the failure this is guarding, and it cannot be
// checked by comparing against a fixture.
if len(pw) != 32 {
t.Fatalf("password = %d chars, want 32 hex chars", len(pw))
}
if strings.Trim(pw, "0123456789abcdef") != "" {
t.Fatalf("password %q is not hex; it is written verbatim into server.properties", pw)
}
// The controller reference is what makes Kubernetes delete the Secret with the
// server. Without it every deleted server leaves its password behind.
if len(secret.OwnerReferences) != 1 || secret.OwnerReferences[0].Name != "survival" {
t.Fatalf("owner references = %+v, want one referring to the server", secret.OwnerReferences)
}
}
// Reconcile runs every few seconds; regenerating the password on each pass would
// leave the running server authenticating with a value the control plane no longer
// has, breaking the console until the pod happened to restart.
func TestReconcileKeepsAnExistingRconPassword(t *testing.T) {
r, c := newReconciler(t, fakeProber{}, runningServer(), rconSecret())
reconcile(t, r, "survival")
reconcile(t, r, "survival")
var secret corev1.Secret
if err := c.Get(context.Background(),
types.NamespacedName{Namespace: "minecraft", Name: "survival-rcon"}, &secret); err != nil {
t.Fatalf("get rcon secret: %v", err)
}
if got := string(secret.Data["password"]); got != "hunter2" {
t.Fatalf("password = %q, want the original %q — the operator rotated it", got, "hunter2")
}
}
// The idle auto-stop reads Status.Players, which is only sampled by the RCON
// probe. With RCON off the tally stays at its zero value, and a bare
// "players == 0" test would read that as an empty server and stop one full of
// people.
func TestIdleAutoStopIsInertWithoutRcon(t *testing.T) {
server := runningServer()
server.Spec.Rcon = v1alpha1.RconSpec{Enabled: false}
server.Spec.Idle = v1alpha1.IdleSpec{AutoStopEnabled: true, EmptySecondsBeforeStop: 1}
r, c := newReconciler(t, fakeProber{}, server)
reconcile(t, r, "survival")
reconcile(t, r, "survival")
if got := getServer(t, c, "survival").Spec.DesiredState; got != v1alpha1.DesiredRunning {
t.Fatalf("desiredState = %q, want %q — idle auto-stop fired on an unprobed player count",
got, v1alpha1.DesiredRunning)
}
}