fix(api): 服务器显示名称限 64 个可见字符,拒绝换行、控制符和不可见格式符

This commit is contained in:
Lemon-miaow committed 2026-09-27 13:30:28 +08:00
1 parent b8da4e2318
commit 67a7e27f8d
19 files changed
+197 -20

No files matched your search

+5 -1
View File
@@ -160,6 +160,10 @@ func buildMinecraftServerFromApplyRequest(req applyRequest, namespace string) (*
if err := naming.ValidateServerName(req.Subdomain); err != nil {
return nil, fmt.Errorf("invalid subdomain: %w", err)
}
displayName, err := naming.CleanDisplayName(req.DisplayName)
if err != nil {
return nil, fmt.Errorf("invalid displayName: %w", err)
}
if strings.TrimSpace(req.Image) == "" {
return nil, fmt.Errorf("image is required")
}
@@ -229,7 +233,7 @@ func buildMinecraftServerFromApplyRequest(req applyRequest, namespace string) (*
},
Spec: v1alpha1.MinecraftServerSpec{
Subdomain: req.Subdomain,
DisplayName: req.DisplayName,
DisplayName: displayName,
Image: req.Image,
JavaMemory: deriveApplyJavaHeap(memLim),
DesiredState: v1alpha1.DesiredStopped,
+14 -5
View File
@@ -140,11 +140,12 @@ func TestDeriveApplyJavaHeap(t *testing.T) {
func TestBuildMinecraftServerFromApplyRequest_Valid(t *testing.T) {
req := applyRequest{
Name: "test-server",
Subdomain: "test-server",
Image: "registry.felis.svc/paper:1.21",
Memory: "4Gi",
Storage: "20Gi",
Name: "test-server",
Subdomain: "test-server",
DisplayName: " Test Server ",
Image: "registry.felis.svc/paper:1.21",
Memory: "4Gi",
Storage: "20Gi",
}
ms, err := buildMinecraftServerFromApplyRequest(req, "minecraft")
if err != nil {
@@ -159,6 +160,9 @@ func TestBuildMinecraftServerFromApplyRequest_Valid(t *testing.T) {
if ms.Spec.Subdomain != "test-server" {
t.Errorf("Subdomain = %q", ms.Spec.Subdomain)
}
if ms.Spec.DisplayName != "Test Server" {
t.Errorf("DisplayName = %q, want it trimmed to Test Server", ms.Spec.DisplayName)
}
if ms.Spec.Image != "registry.felis.svc/paper:1.21" {
t.Errorf("Image = %q", ms.Spec.Image)
}
@@ -283,6 +287,11 @@ func TestBuildMinecraftServerFromApplyRequest_Errors(t *testing.T) {
applyRequest{Name: ok, Subdomain: "", Image: "x", Memory: "1Gi", Storage: "1Gi"},
"invalid subdomain",
},
{
"display name with a tab",
applyRequest{Name: ok, Subdomain: ok, DisplayName: "a" + string(rune(0x09)) + "b", Image: "x", Memory: "1Gi", Storage: "1Gi"},
"invalid displayName",
},
{
"empty image",
applyRequest{Name: ok, Subdomain: ok, Image: "", Memory: "1Gi", Storage: "1Gi"},
+11 -5
View File
@@ -1106,18 +1106,21 @@ paths:
properties:
name: { type: string }
subdomain: { type: string }
display_name: { type: string }
displayName:
type: string
maxLength: 64
description: Trimmed; at most 64 characters, all visible ones or spaces (400 bad_display_name otherwise).
image: { type: string }
memory: { type: string }
storage: { type: string }
autostart_policy: { type: string }
autostartPolicy: { type: string }
resources:
type: object
properties:
cpu: { type: string }
cpu_request: { type: string }
cpuRequest: { type: string }
memory: { type: string }
memory_request: { type: string }
memoryRequest: { type: string }
responses:
'201':
description: Created; starts Stopped.
@@ -6090,7 +6093,10 @@ paths:
properties:
displayName:
type: string
description: Trimmed. An empty name clears it, and the server goes by its name again.
maxLength: 64
description: >-
Trimmed. An empty name clears it, and the server goes by its name again. At
most 64 characters, all visible ones or spaces (400 bad_display_name otherwise).
autostartPolicy: { type: string }
image:
type: string
+30
View File
@@ -4,9 +4,11 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"felis.lolicon.best/internal/apis/felis/v1alpha1"
"felis.lolicon.best/internal/naming"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
)
@@ -43,6 +45,12 @@ const admittedImage = "registry.felis.svc:5000/mc:1"
const validCreateBody = `{"name":"survival","subdomain":"survival",` +
`"image":"registry.felis.svc:5000/mc:1","memory":"2Gi","storage":"10Gi"}`
// createBodyWithDisplayName is validCreateBody with a displayName, JSON-escaped.
func createBodyWithDisplayName(name string) string {
quoted, _ := json.Marshal(name)
return strings.TrimSuffix(validCreateBody, "}") + `,"displayName":` + string(quoted) + "}"
}
// TestCreateServerSuccess covers the happy path end-to-end: the form is
// validated, the business rows are seeded, the CRD is created cold and unowned,
// and the §22 memory ceiling is materialized on the created spec.
@@ -195,6 +203,16 @@ func TestCreateServerRejections(t *testing.T) {
body: `{"name":"survival","subdomain":"lobby","image":"registry.felis.svc:5000/mc:1","memory":"2Gi","storage":"10Gi"}`,
wantCode: http.StatusBadRequest, wantErr: "bad_subdomain",
},
{
name: "display name too long",
body: createBodyWithDisplayName(strings.Repeat("生", naming.MaxDisplayName+1)),
wantCode: http.StatusBadRequest, wantErr: "bad_display_name",
},
{
name: "display name with a line break",
body: createBodyWithDisplayName("Survival" + string(rune(0x0A)) + "Realm"),
wantCode: http.StatusBadRequest, wantErr: "bad_display_name",
},
{
name: "bad autostart policy",
body: `{"name":"survival","subdomain":"survival","image":"registry.felis.svc:5000/mc:1","memory":"2Gi","storage":"10Gi","autostartPolicy":"sometimes"}`,
@@ -330,3 +348,15 @@ func TestCreateServerWithoutBuilderIs503(t *testing.T) {
t.Error("no CRD may be created without a Builder")
}
}
// The display name is trimmed before it is written, like a patch does.
func TestCreateServerTrimsDisplayName(t *testing.T) {
api, _, cl, _ := newCreateAPI()
w := do(api.ExternalHandler(), "POST", "/api/v1/servers", createBodyWithDisplayName(" Survival Realm "), nil)
if w.Code != http.StatusCreated {
t.Fatalf("code = %d, want 201 (%s)", w.Code, w.Body.String())
}
if got := cl.created["survival"].DisplayName; got != "Survival Realm" {
t.Fatalf("created displayName = %q, want %q", got, "Survival Realm")
}
}
+10
View File
@@ -177,6 +177,16 @@ func TestPatchServerRejections(t *testing.T) {
body: `{"displayName":"x"}`,
wantCode: http.StatusBadRequest, wantErr: "bad_name",
},
{
name: "display name too long",
body: `{"displayName":"` + strings.Repeat("x", 65) + `"}`,
wantCode: http.StatusBadRequest, wantErr: "bad_display_name",
},
{
name: "display name with a right-to-left override",
body: `{"displayName":"abc` + string(rune(0x202E)) + `exe.txt"}`,
wantCode: http.StatusBadRequest, wantErr: "bad_display_name",
},
{
name: "empty autostart policy",
body: `{"autostartPolicy":""}`,
+11 -2
View File
@@ -455,6 +455,11 @@ func (a *API) handleCreateServer(w http.ResponseWriter, r *http.Request) {
writeError(w, r, newError(http.StatusBadRequest, "bad_subdomain", "invalid subdomain: %v", err))
return
}
displayName, err := naming.CleanDisplayName(body.DisplayName)
if err != nil {
writeError(w, r, newError(http.StatusBadRequest, "bad_display_name", "invalid display name: %v", err))
return
}
policy, err := parseAutostartPolicy(body.AutostartPolicy)
if err != nil {
@@ -569,7 +574,7 @@ func (a *API) handleCreateServer(w http.ResponseWriter, r *http.Request) {
in := CreateServerInput{
Name: body.Name,
Subdomain: body.Subdomain,
DisplayName: body.DisplayName,
DisplayName: displayName,
Image: image,
JavaMemory: javaMemory,
StorageSize: storage,
@@ -930,7 +935,11 @@ func (a *API) handlePatchServer(w http.ResponseWriter, r *http.Request) {
if body.DisplayName != nil {
// An empty name is allowed: the panel then shows the server's name.
displayName := strings.TrimSpace(*body.DisplayName)
displayName, err := naming.CleanDisplayName(*body.DisplayName)
if err != nil {
writeError(w, r, newError(http.StatusBadRequest, "bad_display_name", "invalid display name: %v", err))
return
}
patch.DisplayName = &displayName
changed = append(changed, "displayName")
}
+29
View File
@@ -9,6 +9,8 @@ import (
"fmt"
"regexp"
"strings"
"unicode"
"unicode/utf8"
)
var (
@@ -145,6 +147,33 @@ func ValidateSystemServerName(name string) error {
return nil
}
// zeroWidthJoiner (U+200D) glues emoji such as the rainbow flag into one picture.
const zeroWidthJoiner = 0x200D
// MaxDisplayName is the most characters a server's display name may have. The
// panel shows it on one line in the fleet grid and the server header.
const MaxDisplayName = 64
// CleanDisplayName trims a server's display name and checks what is left: at most
// MaxDisplayName characters, every one a visible character or a space. Control
// characters, line breaks and the invisible format characters (bidi overrides,
// zero-width spaces) are refused, since they would break the line the panel puts
// the name on or make it read as something else; the zero-width joiner stays,
// because emoji such as the rainbow flag are built with it. An empty result is
// valid: the server then goes by its name.
func CleanDisplayName(s string) (string, error) {
s = strings.TrimSpace(s)
if n := utf8.RuneCountInString(s); n > MaxDisplayName {
return "", fmt.Errorf("naming: display name has %d characters, at most %d are allowed", n, MaxDisplayName)
}
for _, r := range s {
if r == utf8.RuneError || !unicode.IsGraphic(r) && r != zeroWidthJoiner {
return "", fmt.Errorf("naming: display name contains %U, which is not a visible character", r)
}
}
return s, nil
}
// worldVolumeName mirrors operator.dataVolumeName: the per-server StatefulSet's
// volumeClaimTemplate is named "world", so a single-replica server's world PVC
// is "world-<name>-0". This is the one naming convention shared by the operator
+38
View File
@@ -149,3 +149,41 @@ func TestValidateHostname(t *testing.T) {
t.Error("ValidateHostname should reject an empty root domain")
}
}
func TestCleanDisplayName(t *testing.T) {
str := func(rs ...rune) string { return string(rs) }
rainbow := str(0x1F3F3, 0xFE0F, 0x200D, 0x1F308)
cjk := func(n int) string {
s := ""
for range n {
s += "生"
}
return s
}
for _, c := range []struct {
name, in, want string
ok bool
}{
{"trimmed", " Survival World ", "Survival World", true},
{"empty", "", "", true},
{"only spaces", " ", "", true},
{"cjk and punctuation", "生存服 · 第二季!", "生存服 · 第二季!", true},
{"emoji joined by zwj", "Pride " + rainbow, "Pride " + rainbow, true},
{"ideographic space inside", "生存" + str(0x3000) + "服", "生存" + str(0x3000) + "服", true},
{"64 characters of 3 bytes each", cjk(64), cjk(64), true},
{"65 characters", cjk(65), "", false},
{"tab", "a" + str(0x09) + "b", "", false},
{"newline", "a" + str(0x0A) + "b", "", false},
{"nul", "a" + str(0x00), "", false},
{"right-to-left override", "abc" + str(0x202E) + "exe.txt", "", false},
{"zero-width space", "ad" + str(0x200B) + "min", "", false},
{"line separator", "a" + str(0x2028) + "b", "", false},
{"private use", "a" + str(0xE000), "", false},
{"invalid utf-8", string([]byte{'a', 0xff}), "", false},
} {
got, err := naming.CleanDisplayName(c.in)
if (err == nil) != c.ok || got != c.want {
t.Errorf("%s: CleanDisplayName(%q) = %q, %v; want %q, ok=%v", c.name, c.in, got, err, c.want, c.ok)
}
}
}
+6 -1
View File
@@ -1,6 +1,7 @@
package naming
import (
"fmt"
"os"
"regexp"
"slices"
@@ -11,7 +12,8 @@ import (
// The panel's create form checks names as they are typed with its own copy of
// this rule (panel/src/lib/naming.ts). A name reserved or a length changed here
// without the panel would let the form send what the API refuses, or refuse what
// it takes, so the copy is compared to the source.
// it takes, so the copy is compared to the source. The copy also holds the display-name
// length the create and edit forms stop at.
func TestPanelMirrorsServerNameRule(t *testing.T) {
raw, err := os.ReadFile("../../panel/src/lib/naming.ts")
if err != nil {
@@ -40,4 +42,7 @@ func TestPanelMirrorsServerNameRule(t *testing.T) {
if want := "const SERVER_NAME_RE = /" + serverNameRE.String() + "/;"; !strings.Contains(src, want) {
t.Errorf("panel/src/lib/naming.ts lacks %q", want)
}
if want := fmt.Sprintf("export const DISPLAY_NAME_MAX = %d;", MaxDisplayName); !strings.Contains(src, want) {
t.Errorf("panel/src/lib/naming.ts lacks %q", want)
}
}
@@ -92,6 +92,16 @@ describe("CreateServerDialog request body", () => {
expect(screen.queryByRole("dialog")).toBeNull();
});
it("stops the display name at the length the API takes", async () => {
const user = await openDialog();
await fillValid(user);
await user.type(screen.getByLabelText("Display name (optional)"), "x".repeat(70));
await user.click(create());
expect(sent().displayName).toBe("x".repeat(64));
});
it("leaves a blank display name out, and sends the default sizes and policy", async () => {
const user = await openDialog();
+2 -1
View File
@@ -23,7 +23,7 @@ import { Label } from "@/components/ui/label";
import { api, humanizeError } from "@/lib/api";
import { useAsync } from "@/lib/hooks";
import { hostFor, type RuntimeConfig } from "@/lib/config";
import { serverNameIssue, type ServerNameIssue } from "@/lib/naming";
import { DISPLAY_NAME_MAX, serverNameIssue, type ServerNameIssue } from "@/lib/naming";
import type { AutostartPolicy, CreateServerRequest } from "@/lib/types";
import { InlineError } from "@/components/MessageLine";
@@ -164,6 +164,7 @@ export function CreateServerDialog({ cfg, onCreated }: Props) {
<Input
id="cs-display"
placeholder={t("create_server_display_name_placeholder")}
maxLength={DISPLAY_NAME_MAX}
value={form.displayName ?? ""}
onChange={(e) => set("displayName", e.target.value)}
/>
@@ -79,6 +79,15 @@ describe("EditServerDialog request body", () => {
expect(calls.patchServer).toHaveBeenCalledWith("survival", { displayName: "" });
});
it("stops the display name at the length the API takes", async () => {
const user = await openDialog();
await user.clear(screen.getByLabelText("Display name (optional)"));
await user.type(screen.getByLabelText("Display name (optional)"), "x".repeat(70));
await user.click(save());
expect(calls.patchServer).toHaveBeenCalledWith("survival", { displayName: "x".repeat(64) });
});
it("lifts the CPU limit when the field is emptied", async () => {
const user = await openDialog();
await user.clear(cpuInput());
@@ -21,6 +21,7 @@ import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { api, humanizeError } from "@/lib/api";
import { splitImageRef } from "@/lib/format";
import { DISPLAY_NAME_MAX } from "@/lib/naming";
import { useAsync } from "@/lib/hooks";
import type { AutostartPolicy } from "@/lib/types";
import { InlineError } from "@/components/MessageLine";
@@ -237,6 +238,7 @@ export function EditServerDialog({
<Input
id="es-display"
placeholder={t("create_server_display_name_placeholder")}
maxLength={DISPLAY_NAME_MAX}
value={form.displayName}
onChange={(e) => set("displayName", e.target.value)}
/>
@@ -52,6 +52,7 @@
"passkey_aborted": "Passkey registration was aborted.",
"bad_name": "That server name is invalid — use 3–32 lowercase letters, digits or dashes, and avoid reserved names.",
"bad_subdomain": "That subdomain is invalid — use 3–32 lowercase letters, digits or dashes, and avoid reserved names.",
"bad_display_name": "That display name is invalid — use at most 64 characters, all visible ones or spaces, with no line breaks, tabs or invisible control characters.",
"at_capacity": "The cluster is at its running-server cap — try again once a server stops.",
"storage_immutable": "Storage size can't be changed online.",
"bad_idle_stop": "Idle stop must be between 1 minute and 24 hours, or Never.",
@@ -52,6 +52,7 @@
"passkey_aborted": "Passkey 注册已被取消。",
"bad_name": "服务器名称不合法:需为 3–32 位小写字母、数字或连字符,且不能使用保留名。",
"bad_subdomain": "子域名不合法:需为 3–32 位小写字母、数字或连字符,且不能使用保留名。",
"bad_display_name": "显示名称最多 64 个字符,只能包含可见字符和空格,不能含换行、制表符或不可见的控制字符。",
"at_capacity": "集群的在线服务器已达上限——等一台服务器停止后再试。",
"storage_immutable": "存储容量不支持在线调整。",
"bad_idle_stop": "空闲停服时长须在 1 分钟到 24 小时之间,或选择“从不”。",
+6
View File
@@ -444,6 +444,12 @@ describe("api access-control wire shapes", () => {
);
});
it("says what a display name may hold when the server refuses one", () => {
expect(humanizeError({ status: 400, code: "bad_display_name" })).toBe(
"That display name is invalid — use at most 64 characters, all visible ones or spaces, with no line breaks, tabs or invisible control characters.",
);
});
it("says email codes are off when the install has no mail relay", async () => {
const { humanizeError } = await import("./api");
expect(humanizeError({ status: 503, code: "mail_unavailable" })).toBe(
+2
View File
@@ -1119,6 +1119,8 @@ export function humanizeError(e: unknown): string {
return t("bad_name");
case "bad_subdomain":
return t("bad_subdomain");
case "bad_display_name":
return t("bad_display_name");
case "at_capacity":
return t("at_capacity");
case "storage_immutable":
+4
View File
@@ -21,6 +21,10 @@ export const RESERVED_SERVER_NAMES: readonly string[] = [
const SERVER_NAME_RE = /^[a-z0-9-]{3,32}$/;
// DISPLAY_NAME_MAX mirrors naming.MaxDisplayName. The input counts UTF-16 units, so an
// emoji takes two of them there: the box may stop a little early, never late.
export const DISPLAY_NAME_MAX = 64;
export type ServerNameIssue = "shape" | "reserved";
/** serverNameIssue says why the API would refuse this name, or null if it takes it. */
+6 -5
View File
@@ -3143,16 +3143,17 @@ export interface operations {
"application/json": {
name: string;
subdomain: string;
display_name?: string;
/** @description Trimmed; at most 64 characters, all visible ones or spaces (400 bad_display_name otherwise). */
displayName?: string;
image?: string;
memory?: string;
storage?: string;
autostart_policy?: string;
autostartPolicy?: string;
resources?: {
cpu?: string;
cpu_request?: string;
cpuRequest?: string;
memory?: string;
memory_request?: string;
memoryRequest?: string;
};
};
};
@@ -8022,7 +8023,7 @@ export interface operations {
requestBody: {
content: {
"application/json": {
/** @description Trimmed. An empty name clears it, and the server goes by its name again. */
/** @description Trimmed. An empty name clears it, and the server goes by its name again. At most 64 characters, all visible ones or spaces (400 bad_display_name otherwise). */
displayName?: string;
autostartPolicy?: string;
/** @description Re-admitted against the whitelist (a pinned name:tag@sha256:… ref is admitted by its name:tag) and pinned like create does. A pin equal to the current image is no change; any other needs confirmImageChange. */