diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 9007a34..5dcd655 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -55,6 +55,9 @@ jobs: - name: Test validate.py directory layout rules run: ./test-validate-py.sh + - name: Test validate.py security rules + run: ./test-validate-py-security.sh + - name: Check Palworld frame rate against an engine response run: python3 test-palworld-performance.py diff --git a/.schema/gametemplate.schema.json b/.schema/gametemplate.schema.json index 009cab8..deee133 100644 --- a/.schema/gametemplate.schema.json +++ b/.schema/gametemplate.schema.json @@ -941,10 +941,28 @@ "configSchema": { "description": "ConfigSchema declares user-tunable fields surfaced in the Create\nServer wizard. The operator resolves GameServer.spec.config\nagainst this schema (applying defaults, validating types/enums)\nand sets each resolved value as an env var on the game container.\nFields with target=file are consumed by ConfigFiles templates\ninstead of becoming env vars.", "items": { + "anyOf": [ + { + "properties": { + "applyOnRestart": { + "enum": [ + false + ] + } + } + }, + { + "properties": { + "name": { + "pattern": "^[-._a-zA-Z0-9]+$" + } + } + } + ], "description": "ConfigField is a single user-tunable setting surfaced in the wizard.", "properties": { "applyOnRestart": { - "description": "ApplyOnRestart stages this environment value for the next container start.\nEdits and clears update the config Secret without rolling the game Pod.\nConfig files that reference the field are refreshed by their init container\non the next Pod start. Other fields keep their usual rollout behavior.", + "description": "ApplyOnRestart stages this environment value for the next container start.\nEdits and clears update the config Secret without rolling the game Pod.\nConfig files that reference the field are refreshed by their init container\non the next Pod start. Other fields keep their usual rollout behavior.\nName must be a valid Kubernetes Secret key. Admission enforces this rule,\nand the reconciler checks keys from previously admitted template revisions.", "type": "boolean" }, "autoFromMemoryLimit": { @@ -982,6 +1000,12 @@ }, "type": "array" }, + "envName": { + "description": "EnvName, when set, is the env var name the value is exported as\ninstead of Name (Target \"env\" only). It lets a module keep a stable\nconfig key while pointing it at the variable the game image reads.", + "maxLength": 253, + "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", + "type": "string" + }, "max": { "description": "Max is the maximum numeric value for int-typed fields. Bounds are\ninclusive. Ignored for non-int field types.", "format": "int64", @@ -1003,7 +1027,7 @@ "type": "integer" }, "name": { - "description": "Name is the field identifier (also used as an env var when\nTarget is \"env\").", + "description": "Name is the field identifier and the key in GameServer.spec.config.\nIt is also the env var name when Target is \"env\" and EnvName is\nempty.", "minLength": 1, "type": "string" }, @@ -1039,9 +1063,17 @@ ], "type": "object", "x-kubernetes-validations": [ + { + "message": "envName applies only to target env fields", + "rule": "!has(self.envName) || !has(self.target) || self.target == 'env'" + }, { "message": "applyOnRestart requires an environment field", "rule": "!has(self.applyOnRestart) || !self.applyOnRestart || !has(self.target) || self.target == 'env'" + }, + { + "message": "applyOnRestart requires a Secret key name of at most 253 characters that is not '.' and does not start with '..'", + "rule": "!has(self.applyOnRestart) || !self.applyOnRestart || (size(self.name) <= 253 && self.name != '.' && !self.name.startsWith('..'))" } ] }, @@ -1444,7 +1476,19 @@ "type": "integer" } }, - "type": "object" + "type": "object", + "x-kubernetes-validations": [ + { + "fieldPath": ".httpGet.host", + "message": "omit httpGet.host to probe the game pod", + "rule": "!has(self.httpGet) || !has(self.httpGet.host) || self.httpGet.host == ''" + }, + { + "fieldPath": ".tcpSocket.host", + "message": "omit tcpSocket.host to probe the game pod", + "rule": "!has(self.tcpSocket) || !has(self.tcpSocket.host) || self.tcpSocket.host == ''" + } + ] }, "readiness": { "description": "Probe describes a health check to be performed against a container to determine whether it is\nalive or ready to receive traffic.", @@ -1602,7 +1646,19 @@ "type": "integer" } }, - "type": "object" + "type": "object", + "x-kubernetes-validations": [ + { + "fieldPath": ".httpGet.host", + "message": "omit httpGet.host to probe the game pod", + "rule": "!has(self.httpGet) || !has(self.httpGet.host) || self.httpGet.host == ''" + }, + { + "fieldPath": ".tcpSocket.host", + "message": "omit tcpSocket.host to probe the game pod", + "rule": "!has(self.tcpSocket) || !has(self.tcpSocket.host) || self.tcpSocket.host == ''" + } + ] }, "startup": { "description": "Probe describes a health check to be performed against a container to determine whether it is\nalive or ready to receive traffic.", @@ -1760,7 +1816,19 @@ "type": "integer" } }, - "type": "object" + "type": "object", + "x-kubernetes-validations": [ + { + "fieldPath": ".httpGet.host", + "message": "omit httpGet.host to probe the game pod", + "rule": "!has(self.httpGet) || !has(self.httpGet.host) || self.httpGet.host == ''" + }, + { + "fieldPath": ".tcpSocket.host", + "message": "omit tcpSocket.host to probe the game pod", + "rule": "!has(self.tcpSocket) || !has(self.tcpSocket.host) || self.tcpSocket.host == ''" + } + ] } }, "type": "object" @@ -1911,6 +1979,56 @@ "minimum": 0, "type": "integer" }, + "risky": { + "description": "Risky marks the settings whose override a server owner should only\nmake with care (the image works only with that id, or must start as\nroot). Presence of a member means \"overriding this is risky\"; the\ndashboard shows the reason before saving. It never forbids an override.", + "properties": { + "fsGroup": { + "description": "FSGroup marks the volume filesystem group as risky to override.", + "properties": { + "reason": { + "description": "Reason is shown to the server owner before they save the override.", + "maxLength": 200, + "type": "string" + } + }, + "type": "object" + }, + "runAsGroup": { + "description": "RunAsGroup marks the game container gid as risky to override.", + "properties": { + "reason": { + "description": "Reason is shown to the server owner before they save the override.", + "maxLength": 200, + "type": "string" + } + }, + "type": "object" + }, + "runAsUser": { + "description": "RunAsUser marks the game container uid as risky to override.", + "properties": { + "reason": { + "description": "Reason is shown to the server owner before they save the override.", + "maxLength": 200, + "type": "string" + } + }, + "type": "object" + }, + "volumeOwnershipCheck": { + "description": "VolumeOwnershipCheck marks the ownership check policy as risky to override.", + "properties": { + "reason": { + "description": "Reason is shown to the server owner before they save the override.", + "maxLength": 200, + "type": "string" + } + }, + "type": "object" + } + }, + "type": "object" + }, "runAsGroup": { "description": "RunAsGroup is the gid the GAME container runs as.", "format": "int64", @@ -1924,10 +2042,22 @@ "maximum": 4294967295, "minimum": 0, "type": "integer" + }, + "volumeOwnershipCheck": { + "description": "VolumeOwnershipCheck selects how the kubelet re-applies FSGroup to the\nmounted volume. EveryStart re-owns every file on each start (Kubernetes\nfsGroupChangePolicy Always); OnlyWhenWrong skips the walk when the\nvolume root already has the right group (OnRootMismatch). Omitted means\nOnlyWhenWrong. Has an effect only when FSGroup is set.", + "enum": [ + "EveryStart", + "OnlyWhenWrong" + ], + "type": "string" } }, "type": "object" }, + "sentinelIsolation": { + "description": "SentinelIsolation restricts a wake sentinel to its own server's advertised\nports. Templates opt in after module connectivity validation; absent or\nfalse retains the legacy namespace-wide sentinel allowances.", + "type": "boolean" + }, "storage": { "description": "Storage describes the default persistent storage layout.", "properties": { @@ -1960,6 +2090,14 @@ "items": { "description": "ExtraVolumeSpec declares one additional persistent volume beyond a\nGameTemplate's primary data volume (see GameStorageSpec.Extra). The\noperator provisions one PVC per entry using the same mechanism as the\nprimary data PVC (create-if-absent, ReadWriteOnce, owned by the\nGameServer) under its own \"-extra-\" PVC name, and mounts it\ndirectly at MountPath on the game container \u2014 never nested under the\nprimary Storage.MountPath, since these exist precisely for directories\nthat share no safe common parent with it.", "properties": { + "backupRole": { + "description": "BackupRole declares recovery scope. all-data Restic backups include data\nextras and report rebuildable extras as excluded reconstruction prerequisites.\nUnset is unclassified and rejects all-data admission. Default primary-only\nbackups and CSI snapshots still capture only the primary data claim.", + "enum": [ + "data", + "rebuildable" + ], + "type": "string" + }, "mountPath": { "description": "MountPath is the absolute in-container path this volume is mounted at.", "maxLength": 255, @@ -2243,14 +2381,69 @@ "rule": "!has(self.capabilities) || !has(self.capabilities.mods) || !has(self.capabilities.mods.loaders) || size(self.capabilities.mods.loaders) == 0 || (has(self.versions) && size(self.versions) > 0)" }, { - "message": "backupFlush requires the Minecraft Java adapter", - "rule": "!has(self.capabilities) || !has(self.capabilities.backupFlush) || self.game == 'minecraft-java'" + "message": "backupFlush requires Minecraft Java with RCON enabled", + "rule": "!has(self.capabilities) || !has(self.capabilities.backupFlush) || (self.game == 'minecraft-java' && has(self.rcon) && (!has(self.rcon.protocol) || self.rcon.protocol != 'none'))" } ] }, "status": { "description": "GameTemplateStatus is intentionally minimal \u2014 templates are mostly\nstatic configuration. The operator populates ObservedGeneration so\ncontrollers reading templates can detect spec updates.", "properties": { + "conditions": { + "description": "Conditions carry detailed state. LocalesValid reports whether the\ntranslations shipped with the module bundle were all valid.", + "items": { + "description": "Condition contains details for one aspect of the current state of this API Resource.", + "properties": { + "lastTransitionTime": { + "description": "lastTransitionTime is the last time the condition transitioned from one status to another.\nThis should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable.", + "format": "date-time", + "type": "string" + }, + "message": { + "description": "message is a human readable message indicating details about the transition.\nThis may be an empty string.", + "maxLength": 32768, + "type": "string" + }, + "observedGeneration": { + "description": "observedGeneration represents the .metadata.generation that the condition was set based upon.\nFor instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date\nwith respect to the current state of the instance.", + "format": "int64", + "minimum": 0, + "type": "integer" + }, + "reason": { + "description": "reason contains a programmatic identifier indicating the reason for the condition's last transition.\nProducers of specific condition types may define expected values and meanings for this field,\nand whether the values are considered a guaranteed API.\nThe value should be a CamelCase string.\nThis field may not be empty.", + "maxLength": 1024, + "minLength": 1, + "pattern": "^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$", + "type": "string" + }, + "status": { + "description": "status of the condition, one of True, False, Unknown.", + "enum": [ + "True", + "False", + "Unknown" + ], + "type": "string" + }, + "type": { + "description": "type of condition in CamelCase or in foo.example.com/CamelCase.", + "maxLength": 316, + "pattern": "^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$", + "type": "string" + } + }, + "required": [ + "lastTransitionTime", + "message", + "reason", + "status", + "type" + ], + "type": "object" + }, + "type": "array" + }, "inUseCount": { "description": "InUseCount is the number of GameServers currently referencing\nthis template.", "format": "int32", diff --git a/palworld/module.yaml b/palworld/module.yaml index 4307cea..3b23dc7 100644 --- a/palworld/module.yaml +++ b/palworld/module.yaml @@ -2,7 +2,7 @@ apiVersion: gameplane.local/module/v1 name: palworld displayName: Palworld (Dedicated) -version: 1.3.0 +version: 1.4.0 game: palworld categories: [Survival, Sandbox, Co-op] summary: Palworld dedicated server (thijsvanloef/palworld-server-docker) with a REST-API console (RCON is deprecated upstream), save-aware graceful stop, and a .pak mod volume with archive install. First boot downloads the server via steamcmd. diff --git a/palworld/specs.md b/palworld/specs.md index 4d0c0bc..ffde33f 100644 --- a/palworld/specs.md +++ b/palworld/specs.md @@ -80,6 +80,8 @@ Declared ports under `spec.ports`: - **User Matching**: Image starts as root to perform chown before dropping privileges to UID `1000`. Therefore, `runAsUser` must remain unset in `spec.security`. - **Filesystem Permissions**: `spec.security.fsGroup: 1000` ensures that the dropped-privilege user can write and execute files in `/palworld`. +- **Ownership check**: `spec.security.volumeOwnershipCheck: EveryStart` keeps the kubelet re-owning every file at each start, as before the `OnlyWhenWrong` default. +- **Risky override**: `spec.security.risky.runAsUser` carries the reason the dashboard shows before a server forces a user: the image must start as root to drop privileges. --- diff --git a/palworld/template.yaml b/palworld/template.yaml index f09cc29..53e5f7f 100644 --- a/palworld/template.yaml +++ b/palworld/template.yaml @@ -36,7 +36,7 @@ spec: displayName: Palworld (Dedicated) game: palworld # Kept in lockstep with module.yaml's bundle version. - version: 1.3.0 + version: 1.4.0 categories: [Survival, Sandbox, Co-op] # Brand color the dashboard tints this game's icon/accents with. accentColor: "#3d9dd9" @@ -60,8 +60,15 @@ spec: # SteamCMD's resume finally clawed through). fsGroup makes the kubelet chown # the volume to gid 1000 so the dropped user owns its own install. # Do NOT set runAsUser here — the image must START as root in order to drop. + # A server override of runAsUser breaks that start, so it is marked risky. + # The ownership check stays EveryStart: SteamCMD rewrites the install on + # each update, so every file must be re-owned at each start. security: fsGroup: 1000 + volumeOwnershipCheck: EveryStart + risky: + runAsUser: + reason: "The image must start as root to drop privileges; forcing a user breaks its start." env: - name: REST_API_ENABLED diff --git a/test-validate-py-security.sh b/test-validate-py-security.sh new file mode 100755 index 0000000..c3c2115 --- /dev/null +++ b/test-validate-py-security.sh @@ -0,0 +1,147 @@ +#!/usr/bin/env bash +# test-validate-py-security.sh — regression tests for validate.py's template +# security rules (spec.security.risky and spec.security.volumeOwnershipCheck). +# +# The rules are template-only, so they are exercised directly against parsed +# template specs. No image pull or network access is needed. +# +# Run: modules/test-validate-py-security.sh + +set -uo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +pass=0 fail=0 + +check() { # check + if [[ "$2" == "$3" ]]; then + echo "ok - $1"; pass=$((pass + 1)) + else + echo "FAIL - $1"; echo " expected: '$2'"; echo " actual: '$3'"; fail=$((fail + 1)) + fi +} + +TMPDIR=$(mktemp -d) +trap 'rm -rf "$TMPDIR"' EXIT + +# security_findings : prints "LEVEL [rule] message" for every +# template-only security finding the three new rules produce for that spec. +security_findings() { + python3 -c ' +import sys +sys.path.insert(0, sys.argv[1]) +import yaml +import validate + +with open(sys.argv[2]) as fh: + doc = yaml.safe_load(fh) or {} +spec = doc.get("spec") or {} +findings = [] +findings += validate.rule_risky_key_known(spec) +findings += validate.rule_risky_reason_length(spec) +findings += validate.rule_ownership_check_needs_fsgroup(spec) +for f in findings: + print(f"{f.level} [{f.rule}] {f.message}") +' "$HERE" "$1" +} + +write_template() { # write_template + cat > "$1" < "$T" <<'EOF' +apiVersion: gameplane.local/v1alpha1 +kind: GameTemplate +metadata: + name: test-module +spec: + displayName: Test Module + game: test-game + version: 1.0.0 + image: alpine:latest +EOF +out=$(security_findings "$T") +check "template without security block has no security findings" "" "$out" + +echo "" +echo "Summary: $pass passed, $fail failed." +if [ "$fail" -gt 0 ]; then + exit 1 +fi +exit 0 diff --git a/validate.py b/validate.py index 6e9033e..8e6debe 100644 --- a/validate.py +++ b/validate.py @@ -878,6 +878,69 @@ def rule_rcon_protocol(spec: dict) -> list[Finding]: return [] +# Security settings a template can mark risky (spec.security.risky). Keep in +# sync with SecurityRiskSpec in operator/api/v1alpha1/gametemplate_types.go. +RISKY_SECURITY_KEYS = ("runAsUser", "runAsGroup", "fsGroup", "volumeOwnershipCheck") +RISKY_REASON_MAX_LEN = 200 + + +def rule_risky_key_known(spec: dict) -> list[Finding]: + """spec.security.risky may only name the four overridable settings.""" + risky = get_path(spec, "security.risky") + if not isinstance(risky, dict): + return [] + findings: list[Finding] = [] + for key in risky: + if key not in RISKY_SECURITY_KEYS: + findings.append( + Finding( + ERROR, + "risky-unknown-key", + f"spec.security.risky.{key} is not one of " + f"{'/'.join(RISKY_SECURITY_KEYS)} — only those settings can be marked risky.", + ) + ) + return findings + + +def rule_risky_reason_length(spec: dict) -> list[Finding]: + """Each spec.security.risky..reason is at most 200 characters.""" + risky = get_path(spec, "security.risky") + if not isinstance(risky, dict): + return [] + findings: list[Finding] = [] + for key, note in risky.items(): + if not isinstance(note, dict): + continue + reason = note.get("reason") + if isinstance(reason, str) and len(reason) > RISKY_REASON_MAX_LEN: + findings.append( + Finding( + ERROR, + "risky-reason-too-long", + f"spec.security.risky.{key}.reason is {len(reason)} characters; " + f"the limit is {RISKY_REASON_MAX_LEN}.", + ) + ) + return findings + + +def rule_ownership_check_needs_fsgroup(spec: dict) -> list[Finding]: + """volumeOwnershipCheck without fsGroup has no effect (warn only).""" + if get_path(spec, "security.volumeOwnershipCheck") is None: + return [] + if get_path(spec, "security.fsGroup") is not None: + return [] + return [ + Finding( + WARN, + "ownership-check-without-fsgroup", + "spec.security.volumeOwnershipCheck is set but spec.security.fsGroup is not; " + "the ownership check has no effect without a filesystem group.", + ) + ] + + def rule_mods_loaders_requires_versions(spec: dict) -> list[Finding]: """Rule 7: capabilities.mods.loaders needs a non-empty spec.versions.""" mods = get_path(spec, "capabilities.mods") @@ -1150,6 +1213,9 @@ def validate_module(spec: dict, cache: dict[str, dict], module_dir: Path | None findings += rule_puid_image_needs_fsgroup(spec, cfg, ref) findings += rule_rcon_protocol(spec) + findings += rule_risky_key_known(spec) + findings += rule_risky_reason_length(spec) + findings += rule_ownership_check_needs_fsgroup(spec) findings += rule_mods_loaders_requires_versions(spec) findings += rule_credential_fields_must_be_password(spec) findings += rule_images_pinned(spec)