diff --git a/.github/workflows/design-export.yaml b/.github/workflows/design-export.yaml index 08d114d65..fb80ce70d 100644 --- a/.github/workflows/design-export.yaml +++ b/.github/workflows/design-export.yaml @@ -80,7 +80,7 @@ jobs: working-directory: gameplane run: | git add -A assets/design-export telemetry-receiver/design-export - git diff --cached --binary > "$RUNNER_TEMP/design-export.patch" + git diff --cached --binary --no-renames > "$RUNNER_TEMP/design-export.patch" if [ -s "$RUNNER_TEMP/design-export.patch" ]; then git diff --cached --stat echo "changed=true" >> "$GITHUB_OUTPUT" @@ -126,13 +126,15 @@ jobs: exit 0 fi # The patch comes from a run of the PR's own script: push nothing outside the export folders. - outside=$(git apply --numstat "$RUNNER_TEMP/design-export.patch" | cut -f3 | + # Check what the applied patch staged, not the patch's own path list: a rename lists + # only its destination there, so it could delete any file outside the export folders. + git apply --index "$RUNNER_TEMP/design-export.patch" + outside=$(git diff --cached --name-only --no-renames | grep -vE '^(assets/design-export|telemetry-receiver/design-export)/' || true) if [ -n "$outside" ]; then echo "::error::The export patch touches files outside the export folders: $outside" exit 1 fi - git apply --index "$RUNNER_TEMP/design-export.patch" git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" git commit -s -q -m "design: regenerate the design export" diff --git a/agent/internal/archive/unpack.go b/agent/internal/archive/unpack.go index 44b5f42bd..539ae8b39 100644 --- a/agent/internal/archive/unpack.go +++ b/agent/internal/archive/unpack.go @@ -462,6 +462,7 @@ func (x *extractor) mkdir(dst string, mode fs.FileMode) error { return err } _ = unix.Close(fd) + delete(x.files, dst) x.dirs[dst] = mode return nil } @@ -604,6 +605,9 @@ func (x *extractor) symlink(dst, target string) error { if err != nil { return fmt.Errorf("create symlink: %w", err) } + // The name now holds a symlink: a later hard link must not reuse the + // regular file recorded earlier under the same name. + delete(x.files, dst) return nil } @@ -644,6 +648,13 @@ func (x *extractor) hardlink(dst, rawTarget string, lay layout) error { } defer func() { _ = unix.Close(pfd) }() tbase := path.Base(td) + var st unix.Stat_t + if err := unix.Fstatat(tfd, tbase, &st, unix.AT_SYMLINK_NOFOLLOW); err != nil { + return fmt.Errorf("hard link target %q is not a regular file: %w", rawTarget, err) + } + if st.Mode&unix.S_IFMT != unix.S_IFREG { + return fmt.Errorf("hard link target %q is not a regular file", rawTarget) + } err = unix.Linkat(tfd, tbase, pfd, base, 0) if errors.Is(err, unix.EEXIST) { if err := unix.Unlinkat(pfd, base, 0); err != nil { @@ -756,6 +767,22 @@ func (s *tarStream) next() (rawEntry, error) { for { h, err := s.tr.Next() if errors.Is(err, io.EOF) { + // Read the gzip stream to its end so the CRC32 and size + // trailer are verified, and refuse non-zero trailing data. + // The drain is capped: zero runs compress about 1000:1, so an + // unbounded drain would let a small upload cost gigabytes of + // decompression before extraction even starts. + var zc zeroChecker + n, derr := io.Copy(&zc, io.LimitReader(s.gz, maxTarTrailerBytes+1)) + if derr != nil { + return rawEntry{}, fmt.Errorf("read archive: %w", derr) + } + if n > maxTarTrailerBytes { + return rawEntry{}, fmt.Errorf("read archive: more than %d bytes after tar end marker", maxTarTrailerBytes) + } + if zc.dirty { + return rawEntry{}, errors.New("read archive: unexpected data after tar end marker") + } return rawEntry{}, io.EOF } if err != nil { @@ -785,6 +812,24 @@ func (s *tarStream) next() (rawEntry, error) { return e, nil } +// maxTarTrailerBytes caps the zero padding accepted after the tar end +// marker. tar writers pad to their record size (10 KiB by default); 1 MiB +// leaves room for large blocking factors. +const maxTarTrailerBytes = 1 << 20 + +// zeroChecker discards writes and records whether any byte was non-zero. +type zeroChecker struct{ dirty bool } + +func (z *zeroChecker) Write(p []byte) (int, error) { + for _, b := range p { + if b != 0 { + z.dirty = true + break + } + } + return len(p), nil +} + func (s *tarStream) body() (io.Reader, error) { return s.tr, nil } diff --git a/agent/internal/archive/unpack_integrity_test.go b/agent/internal/archive/unpack_integrity_test.go new file mode 100644 index 000000000..9101c89b7 --- /dev/null +++ b/agent/internal/archive/unpack_integrity_test.go @@ -0,0 +1,132 @@ +package archive + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "io/fs" + "os" + "path" + "path/filepath" + "strings" + "testing" + + "golang.org/x/sys/unix" +) + +func TestUnpackHardLinkToReplacedSymlinkRefused(t *testing.T) { + ents := []tarEnt{ + {name: "d/f", body: "x"}, + {name: "d/f", typ: tar.TypeSymlink, link: "../x"}, + {name: "top", typ: tar.TypeLink, link: "d/f"}, + } + _, _, err := unpackTar(t, ents, UnpackOptions{}) + if err == nil { + t.Fatal("Unpack accepted a hard link to a name replaced by a symlink") + } + // symlink() forgets the replaced regular file, so the hard link is + // refused by the x.files lookup; the Fstatat check is a second guard. + if msg := err.Error(); !strings.Contains(msg, "not yet extracted") && !strings.Contains(msg, "not a regular file") { + t.Fatalf("error %q did not come from the hard link check", err) + } +} + +func TestUnpackDirOverRegularFileRefused(t *testing.T) { + ents := []tarEnt{ + {name: "f", body: "x"}, + {name: "f", typ: tar.TypeDir}, + } + if _, _, err := unpackTar(t, ents, UnpackOptions{}); err == nil { + t.Fatal("Unpack accepted a directory entry over a regular file") + } +} + +func TestUnpackTarGzBadCRCRefused(t *testing.T) { + data := makeTarGzBytes(t, []tarEnt{{name: "f", body: "hello"}}) + data[len(data)-8] ^= 0xff + _, err := Unpack(writeArchive(t, data), t.TempDir(), UnpackOptions{Format: "tar.gz", MaxBytes: 1 << 20}) + if err == nil { + t.Fatal("Unpack accepted an archive with a bad gzip CRC") + } +} + +func TestUnpackTarGzMissingTrailerRefused(t *testing.T) { + data := makeTarGzBytes(t, []tarEnt{{name: "f", body: "hello"}}) + data = data[:len(data)-8] + _, err := Unpack(writeArchive(t, data), t.TempDir(), UnpackOptions{Format: "tar.gz", MaxBytes: 1 << 20}) + if err == nil { + t.Fatal("Unpack accepted an archive with a missing gzip trailer") + } +} + +// tarGzWithTrailer builds a tar.gz whose gzip stream carries extra bytes +// after the tar end marker. +func tarGzWithTrailer(t *testing.T, trailer []byte) []byte { + t.Helper() + var tarBuf bytes.Buffer + tw := tar.NewWriter(&tarBuf) + if err := tw.WriteHeader(&tar.Header{Name: "f", Typeflag: tar.TypeReg, Mode: 0o644, Size: 5}); err != nil { + t.Fatal(err) + } + if _, err := tw.Write([]byte("hello")); err != nil { + t.Fatal(err) + } + if err := tw.Close(); err != nil { + t.Fatal(err) + } + var out bytes.Buffer + gz := gzip.NewWriter(&out) + if _, err := gz.Write(append(tarBuf.Bytes(), trailer...)); err != nil { + t.Fatal(err) + } + if err := gz.Close(); err != nil { + t.Fatal(err) + } + return out.Bytes() +} + +func TestUnpackTarGzTrailingDataRefused(t *testing.T) { + data := tarGzWithTrailer(t, []byte("junk after the end marker")) + _, err := Unpack(writeArchive(t, data), t.TempDir(), UnpackOptions{Format: "tar.gz", MaxBytes: 1 << 20}) + if err == nil || !strings.Contains(err.Error(), "unexpected data after tar end marker") { + t.Fatalf("err = %v, want trailing data refusal", err) + } +} + +func TestUnpackTarGzZeroPaddingAccepted(t *testing.T) { + data := tarGzWithTrailer(t, make([]byte, 4096)) + if _, err := Unpack(writeArchive(t, data), t.TempDir(), UnpackOptions{Format: "tar.gz", MaxBytes: 1 << 20}); err != nil { + t.Fatalf("Unpack refused zero padding after the end marker: %v", err) + } +} + +// The x.files bookkeeping normally keeps a hard link off anything but a +// regular file; this checks the on-disk guard behind it on its own. +func TestHardlinkRefusesNonRegularTarget(t *testing.T) { + root := t.TempDir() + vol := filepath.Join(root, "volumes", plainVolume) + if err := os.MkdirAll(vol, 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink("/etc/passwd", filepath.Join(vol, "s")); err != nil { + t.Fatal(err) + } + fd, err := unix.Open(root, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) + if err != nil { + t.Fatal(err) + } + defer func() { _ = unix.Close(fd) }() + x := &extractor{rootFD: fd, max: 1 << 20, files: map[string]int64{path.Join("volumes", plainVolume, "s"): 0}, dirs: map[string]fs.FileMode{}} + err = x.hardlink(path.Join("volumes", plainVolume, "top"), "s", layout{plain: true}) + if err == nil || !strings.Contains(err.Error(), "not a regular file") { + t.Fatalf("err = %v, want not a regular file", err) + } +} + +func TestUnpackTarGzOversizedPaddingRefused(t *testing.T) { + data := tarGzWithTrailer(t, make([]byte, maxTarTrailerBytes+1024)) + _, err := Unpack(writeArchive(t, data), t.TempDir(), UnpackOptions{Format: "tar.gz", MaxBytes: 1 << 20}) + if err == nil || !strings.Contains(err.Error(), "after tar end marker") { + t.Fatalf("err = %v, want oversized padding refusal", err) + } +} diff --git a/agent/specs.md b/agent/specs.md index 68b5e8b3a..5bde8a336 100644 --- a/agent/specs.md +++ b/agent/specs.md @@ -253,6 +253,7 @@ All endpoints on the `--addr` control mux, except `/healthz`, return `401 Unauth - **Partial uploads never linger, and never destroy an existing file**: `files.savePart` writes to a temp file in the destination directory and renames it over the final name only once the copy succeeds. A save that fails after the temp file is opened — a source read error, an `io.ErrUnexpectedEOF` from a truncated multipart body, or an over-the-limit part — removes only the temp file, so a client abort mid-upload can't leave a half-written file where a later `/files/read` or `/files/download` would serve it as complete, and can't delete a file that already existed at that name. `/files/stream` follows the same temp-and-rename rule, including resumed uploads. - **Symlink confinement on upload**: `files.savePart` confines the upload destination the same way as other file operations: an existing symlink at the destination name (pointing inside the root, outside it, or dangling) is rejected with HTTP 400 (`errLinkTraversal`, which wraps `errPathOutOfRoot`), leaving the symlink and its target untouched. Regular (non-symlink) files are overwritten by a successful upload through an atomic `renameat` in the same directory descriptor. - **Extracted mod files stay world-readable**: `mods.moduleFileMode` is `0o644`, not a tighter `0o600`, because the mods volume is shared with the game container, which runs as whatever uid its image needs — a different uid than the agent's own. At `0o600` the game process couldn't read its own mods. This is the rationale behind the `.golangci.yml` gosec G302 exclusion scoped to `agent/internal/mods/mods.go`. +- **Uploaded backup archives are checked end to end**: the archive worker (`archive.Unpack`, spec 041) reads a tar.gz to its gzip trailer, so a bad CRC32 or size, a missing trailer, or non-zero data after the tar end marker refuses the archive; zero padding after the end marker is accepted up to 1 MiB (`maxTarTrailerBytes`), so trailing padding cannot cost more decompression than that. A hard link entry must name an already extracted regular file: a name later replaced by a symlink or directory is forgotten, and the on-disk target is checked with `fstatat` before `linkat`. - **Resource usage is in-pod**: The `usage` package reads from `/proc` or cgroups; no external metrics pipeline required. Cgroup mode is a fallback for older clusters; proc mode (default in production) requires the operator to set `ShareProcessNamespace: true`. - **Module capabilities drive commands**: Game-specific commands (players, quiesce, lifecycle, status, actions) read their config from `--capabilities` (JSON unmarshaled into `caps.Spec`). New games using the supported command protocols require no agent code change. Player-list format parsers and the read-only Minecraft Java operator-file reader are built-in protocol adapters. - **Minecraft Java operator identities:** the built-in `ops.json` protocol reader is enabled only for the trusted game identifier `minecraft-java` and an agent data root. Player snapshots advertise `capabilities.operators` even when RCON is disabled; other moderation remains template-driven. Reads reuse the file browser's descriptor-relative confinement, reject symlinks and non-regular files, and are capped at 1 MiB. Only names and UUIDs leave the agent, not permission levels or player-limit overrides. diff --git a/api/cmd/health.go b/api/cmd/health.go index 56aa9ec39..014e09292 100644 --- a/api/cmd/health.go +++ b/api/cmd/health.go @@ -21,6 +21,13 @@ func mountHealthRoutes(r chi.Router, store *db.Store) { }) pingSlot := make(chan struct{}, 1) ready := func(w http.ResponseWriter, req *http.Request) { + // Kubelet probes reach the API directly and never carry proxy headers; + // every ingress or proxy hop adds one. Refuse proxied requests so + // public traffic cannot take the readiness slot. + if req.Header.Get("X-Forwarded-For") != "" || req.Header.Get("Forwarded") != "" { + http.NotFound(w, req) + return + } select { case pingSlot <- struct{}{}: defer func() { <-pingSlot }() diff --git a/api/cmd/health_forwarded_test.go b/api/cmd/health_forwarded_test.go new file mode 100644 index 000000000..58fa9d84f --- /dev/null +++ b/api/cmd/health_forwarded_test.go @@ -0,0 +1,36 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/go-chi/chi/v5" + + "github.com/GameplanePanel/gameplane/api/internal/db" +) + +func TestReadinessRefusesProxiedRequests(t *testing.T) { + store, err := db.Open(t.Context(), "sqlite", ":memory:") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = store.Close() }) + r := chi.NewRouter() + mountHealthRoutes(r, store) + + for _, header := range []string{"X-Forwarded-For", "Forwarded"} { + req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/readyz", nil) + req.Header.Set(header, "203.0.113.7") + rr := httptest.NewRecorder() + r.ServeHTTP(rr, req) + if rr.Code != http.StatusNotFound { + t.Fatalf("%s: status=%d, want 404", header, rr.Code) + } + } + rr := httptest.NewRecorder() + r.ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/readyz", nil)) + if rr.Code != http.StatusOK { + t.Fatalf("direct probe: status=%d, want 200", rr.Code) + } +} diff --git a/api/cmd/main.go b/api/cmd/main.go index 4d4def1b6..614bb4c29 100644 --- a/api/cmd/main.go +++ b/api/cmd/main.go @@ -357,6 +357,10 @@ func main() { r.Use(requestTimeout(60 * time.Second)) r.Use(bodyLimit(1 << 20)) // 1 MiB default; upload proxy raises its own ceiling r.Use(audit.Middleware(auditor)) + // Unrouted requests (unknown paths, wrong methods) are not audited. Set + // before any Mount/Route: chi subrouters inherit these handlers. + r.NotFound(audit.NotFound) + r.MethodNotAllowed(audit.MethodNotAllowed) mountHealthRoutes(r, store) // Prometheus metrics are served by the separate metrics listener below, diff --git a/api/internal/audit/audit.go b/api/internal/audit/audit.go index b8814373a..03c42f1e2 100644 --- a/api/internal/audit/audit.go +++ b/api/internal/audit/audit.go @@ -22,7 +22,9 @@ import ( "strings" "sync/atomic" "time" + "unicode/utf8" + "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" @@ -636,6 +638,65 @@ func MarkRecorded(ctx context.Context) { } } +// unroutedKey is the context key for the per-request "no route matched" flag. +type unroutedKey struct{} + +// MarkUnrouted tells Middleware that the router found no route for this +// request, so no audit row is written for it. It is a no-op on a context that +// did not pass through Middleware. +func MarkUnrouted(ctx context.Context) { + if f, ok := ctx.Value(unroutedKey{}).(*atomic.Bool); ok { + f.Store(true) + } +} + +// NotFound is the router's NotFound handler: it answers 404 and marks the +// request unrouted. Set it with r.NotFound before mounting subrouters, which +// inherit it. +func NotFound(w http.ResponseWriter, req *http.Request) { + MarkUnrouted(req.Context()) + http.NotFound(w, req) +} + +// MethodNotAllowed is the router's MethodNotAllowed handler: it answers 405 +// and marks the request unrouted. Set it with r.MethodNotAllowed before +// mounting subrouters, which inherit it. +func MethodNotAllowed(w http.ResponseWriter, req *http.Request) { + MarkUnrouted(req.Context()) + // chi's default 405 handler lists the allowed methods; keep that (RFC + // 9110 15.5.6) by asking the root router which methods match the path. + if rctx := chi.RouteContext(req.Context()); rctx != nil && rctx.Routes != nil { + for _, m := range allowCandidates { + if rctx.Routes.Match(chi.NewRouteContext(), m, req.URL.Path) { + w.Header().Add("Allow", m) + } + } + } + w.WriteHeader(http.StatusMethodNotAllowed) +} + +var allowCandidates = []string{ + http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut, + http.MethodPatch, http.MethodDelete, http.MethodOptions, +} + +// Bounds on attacker-influenced strings stored in one middleware audit row. +const ( + maxAuditPathBytes = 512 + maxAuditTargetBytes = 512 +) + +// truncateUTF8 cuts s to at most max bytes without splitting a UTF-8 rune. +func truncateUTF8(s string, limit int) string { + if len(s) <= limit { + return s + } + for limit > 0 && !utf8.RuneStart(s[limit]) { + limit-- + } + return s[:limit] +} + // Middleware logs every mutating request after the handler returns. // Reads and health probes are skipped to keep the audit log signal-dense. // A request whose handler called MarkRecorded is skipped too: its own @@ -651,12 +712,24 @@ func Middleware(a *Auditor) func(http.Handler) http.Handler { ctx, holder := auth.WithActorHolder(req.Context()) recorded := new(atomic.Bool) ctx = context.WithValue(ctx, recordedKey{}, recorded) + unrouted := new(atomic.Bool) + ctx = context.WithValue(ctx, unroutedKey{}, unrouted) req = req.WithContext(ctx) rw := &responseRecorder{ResponseWriter: w, status: 200} next.ServeHTTP(rw, req) if !shouldLog(req) || recorded.Load() { return } + // Requests the router did not route (404/405 from NotFound or + // MethodNotAllowed, at the root or in a mounted subrouter) carry + // attacker-chosen paths and no business action; skip them so a + // flood of unknown paths cannot fill the audit table. An + // unauthenticated request under an authenticated group is + // answered 401 by Authenticate before routing and is still + // recorded as an anonymous attempt. + if unrouted.Load() { + return + } actor := "anonymous" if name := holder.Name(); name != "" { actor = name @@ -699,7 +772,8 @@ func Middleware(a *Auditor) func(http.Handler) http.Handler { // Redact share link tokens from the path for audit logging. // Share tokens are credentials; record the request structure without the token. - path := redactShareToken(req.URL.Path) + path := truncateUTF8(redactShareToken(req.URL.Path), maxAuditPathBytes) + target = truncateUTF8(target, maxAuditTargetBytes) // The handler has already run. Keep its audit attempt on client // disconnect, but never extend the request's original deadline. diff --git a/api/internal/audit/audit_unrouted_test.go b/api/internal/audit/audit_unrouted_test.go new file mode 100644 index 000000000..c82a87e98 --- /dev/null +++ b/api/internal/audit/audit_unrouted_test.go @@ -0,0 +1,111 @@ +package audit + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/go-chi/chi/v5" + + "github.com/GameplanePanel/gameplane/api/internal/db" +) + +func TestTruncateUTF8(t *testing.T) { + if got := truncateUTF8("abc", 10); got != "abc" { + t.Fatalf("got %q", got) + } + if got := truncateUTF8(strings.Repeat("a", 600), 512); len(got) != 512 { + t.Fatalf("len = %d, want 512", len(got)) + } + // "é" is 2 bytes; cutting at 3 would split the second rune. + if got := truncateUTF8("ééé", 3); got != "é" { + t.Fatalf("got %q, want %q", got, "é") + } +} + +func routerWithAudit(t *testing.T) (*db.Store, http.Handler) { + t.Helper() + s := newStore(t) + r := chi.NewRouter() + r.Use(Middleware(New(s))) + r.NotFound(NotFound) + r.MethodNotAllowed(MethodNotAllowed) + r.Post("/known", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }) + r.Post("/known/*", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }) + r.Route("/sub", func(sr chi.Router) { + sr.Post("/ok", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }) + }) + return s, r +} + +func serve(h http.Handler, method, target string) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequestWithContext(context.Background(), method, target, nil)) + return rec +} + +func TestRouterUnknownRootPathWritesNoRow(t *testing.T) { + s, h := routerWithAudit(t) + if rec := serve(h, http.MethodPost, "/nope"); rec.Code != http.StatusNotFound { + t.Fatalf("status = %d", rec.Code) + } + if n := countEvents(t, s); n != 0 { + t.Fatalf("rows = %d, want 0", n) + } +} + +func TestRouterUnknownSubrouterPathWritesNoRow(t *testing.T) { + s, h := routerWithAudit(t) + if rec := serve(h, http.MethodPost, "/sub/garbage"); rec.Code != http.StatusNotFound { + t.Fatalf("status = %d", rec.Code) + } + if rec := serve(h, http.MethodDelete, "/sub/ok"); rec.Code != http.StatusMethodNotAllowed { + t.Fatalf("status = %d", rec.Code) + } + if n := countEvents(t, s); n != 0 { + t.Fatalf("rows = %d, want 0", n) + } +} + +func TestRouterRoutedAnonymousPostWritesOneRow(t *testing.T) { + s, h := routerWithAudit(t) + serve(h, http.MethodPost, "/known") + serve(h, http.MethodPost, "/sub/ok") + if n := countEvents(t, s); n != 2 { + t.Fatalf("rows = %d, want 2", n) + } + var actor string + if err := s.DB.QueryRowContext(context.Background(), + `SELECT actor FROM audit_events WHERE path = '/known'`).Scan(&actor); err != nil { + t.Fatalf("query: %v", err) + } + if actor != "anonymous" { + t.Fatalf("actor = %q", actor) + } +} + +func TestRouterTruncationReachesStoredRow(t *testing.T) { + s, h := routerWithAudit(t) + serve(h, http.MethodPost, "/known/"+strings.Repeat("a", 600)+"?name="+strings.Repeat("b", 600)) + var path, target string + if err := s.DB.QueryRowContext(context.Background(), + `SELECT path, COALESCE(target,'') FROM audit_events`).Scan(&path, &target); err != nil { + t.Fatalf("query: %v", err) + } + if len(path) != 512 || len(target) != 512 { + t.Fatalf("path=%d target=%d, want 512 each", len(path), len(target)) + } +} + +func TestRouterMethodNotAllowedKeepsAllowHeader(t *testing.T) { + _, h := routerWithAudit(t) + rec := serve(h, http.MethodDelete, "/sub/ok") + if rec.Code != http.StatusMethodNotAllowed { + t.Fatalf("status = %d", rec.Code) + } + if got := rec.Header().Values("Allow"); len(got) != 1 || got[0] != http.MethodPost { + t.Fatalf("Allow = %v, want [POST]", got) + } +} diff --git a/api/internal/auth/argon_busy_test.go b/api/internal/auth/argon_busy_test.go new file mode 100644 index 000000000..c22f3590c --- /dev/null +++ b/api/internal/auth/argon_busy_test.go @@ -0,0 +1,114 @@ +package auth + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestLimiterSourceKey(t *testing.T) { + cases := map[string]string{ + "203.0.113.7": "203.0.113.7", + "2001:db8:1:2:aaaa::1": "2001:db8:1:2::/64", + "2001:db8:1:2:bbbb:cccc::9": "2001:db8:1:2::/64", + "2001:db8:1:3::1": "2001:db8:1:3::/64", + "not-an-ip": "not-an-ip", + "::ffff:203.0.113.7": "::ffff:203.0.113.7", + } + for in, want := range cases { + if got := LimiterSourceKey(in); got != want { + t.Errorf("LimiterSourceKey(%q) = %q, want %q", in, got, want) + } + } +} + +func TestAcquireArgon_FailsFastWhenQueueFull(t *testing.T) { + SaturateArgonQueue(t) + + if err := acquireArgon(context.Background()); !errors.Is(err, ErrPasswordBusy) { + t.Fatalf("err = %v, want ErrPasswordBusy", err) + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if err := acquireArgon(ctx); !errors.Is(err, context.Canceled) { + t.Fatalf("err = %v, want context.Canceled", err) + } +} + +func TestLogin_Busy_IdenticalForKnownAndUnknownUser(t *testing.T) { + s := newAuthDB(t) + seedUser(t, s, "alice", "rightpw-123456", "admin") + // Compute the dummy hash before the queue is saturated. + dummyHash() + SaturateArgonQueue(t) + + post := func(user string) *httptest.ResponseRecorder { + body := strings.NewReader(`{"username":"` + user + `","password":"whatever"}`) + rr := httptest.NewRecorder() + req := httptest.NewRequestWithContext(context.Background(), "POST", "/login", body) + req.Header.Set("Content-Type", "application/json") + NewLocal(s).HandleLogin(NewSessionStore(s), nil).ServeHTTP(rr, req) + return rr + } + known, unknown := post("alice"), post("ghost") + for name, rr := range map[string]*httptest.ResponseRecorder{"known": known, "unknown": unknown} { + if rr.Code != http.StatusServiceUnavailable { + t.Fatalf("%s: code=%d", name, rr.Code) + } + if got := rr.Header().Get("Retry-After"); got != "5" { + t.Fatalf("%s: Retry-After=%q", name, got) + } + } + if known.Body.String() != unknown.Body.String() { + t.Fatalf("bodies differ: %q vs %q", known.Body.String(), unknown.Body.String()) + } +} + +func TestVerifyDummy_FailsFastWhileQueueFullThenRecovers(t *testing.T) { + SetFastHashParams(t) + // Hold the slot and fill the waiter queue, as during a flood. The deny + // path must fail fast (not block on the lazy dummy hash), and work again + // once the slot frees. + release := SaturateArgonQueue(t) + done := make(chan error, 1) + go func() { done <- VerifyDummy(context.Background(), "x") }() + select { + case err := <-done: + if !errors.Is(err, ErrPasswordBusy) { + t.Fatalf("err = %v, want ErrPasswordBusy", err) + } + case <-time.After(10 * time.Second): + t.Fatal("VerifyDummy blocked while the queue was full") + } + release() + if err := VerifyDummy(context.Background(), "x"); err != nil { + t.Fatalf("VerifyDummy after release: %v", err) + } + if h := computeDummyHash(); !strings.HasPrefix(h, "$argon2id$") { + t.Fatalf("dummy hash = %q", h) + } +} + +func TestMiddleware_SharesBucketAcrossIPv6Prefix(t *testing.T) { + tb := newTokenBucket(0.0001, 1) + h := tb.Middleware(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + })) + send := func(remote string) int { + req := httptest.NewRequestWithContext(context.Background(), "GET", "/x", nil) + req.RemoteAddr = remote + rr := httptest.NewRecorder() + h.ServeHTTP(rr, req) + return rr.Code + } + if c := send("[2001:db8:1:2:aaaa::1]:1000"); c != http.StatusOK { + t.Fatalf("first=%d", c) + } + if c := send("[2001:db8:1:2:bbbb::9]:2000"); c != http.StatusTooManyRequests { + t.Fatalf("second=%d, want 429", c) + } +} diff --git a/api/internal/auth/local.go b/api/internal/auth/local.go index 199b2c1d3..5eecc7488 100644 --- a/api/internal/auth/local.go +++ b/api/internal/auth/local.go @@ -153,11 +153,18 @@ func (l *Local) HandleLogin(sessions *SessionStore, reg *Registry) http.HandlerF // is a username-enumeration oracle. u, hash, err := l.fetchUser(req.Context(), body.Username) if err != nil || hash == "" { - VerifyDummy(req.Context(), body.Password) + if derr := VerifyDummy(req.Context(), body.Password); errors.Is(derr, ErrPasswordBusy) { + writePasswordBusy(w, req) + return + } httperr.WriteMessage(w, req, messages.New("server.auth.invalid_credentials", nil)) return } ok, err := VerifyPassword(req.Context(), body.Password, hash) + if errors.Is(err, ErrPasswordBusy) { + writePasswordBusy(w, req) + return + } if err != nil || !ok { httperr.WriteMessage(w, req, messages.New("server.auth.invalid_credentials", nil)) return diff --git a/api/internal/auth/mcptokens.go b/api/internal/auth/mcptokens.go index de9ac2b56..fa8874f86 100644 --- a/api/internal/auth/mcptokens.go +++ b/api/internal/auth/mcptokens.go @@ -358,13 +358,13 @@ func bearerMCPToken(req *http.Request) (string, bool) { // mcpClientIP returns the client IP the same way the rate limiter does. func mcpClientIP(req *http.Request) string { if ip := middleware.GetClientIP(req.Context()); ip != "" { - return ip + return LimiterSourceKey(ip) } host, _, err := net.SplitHostPort(req.RemoteAddr) if err != nil { - return req.RemoteAddr + return LimiterSourceKey(req.RemoteAddr) } - return host + return LimiterSourceKey(host) } // serveMCPToken authenticates a bearer MCP token and serves the request diff --git a/api/internal/auth/password.go b/api/internal/auth/password.go index 130f744cc..4b2c15e76 100644 --- a/api/internal/auth/password.go +++ b/api/internal/auth/password.go @@ -18,6 +18,7 @@ import ( "fmt" "strings" "sync" + "sync/atomic" "golang.org/x/crypto/argon2" "golang.org/x/sync/semaphore" @@ -43,6 +44,34 @@ var ( argonSem = semaphore.NewWeighted(argonConcurrency) ) +// maxArgonWaiters bounds how many callers may queue for argonSem. Beyond it a +// caller fails fast with ErrPasswordBusy instead of waiting out the request +// timeout behind a flood. +const maxArgonWaiters = 64 + +// ErrPasswordBusy reports that too many password operations are already +// queued; callers answer with 503 and a Retry-After header. +var ErrPasswordBusy = errors.New("password hashing busy") + +var argonWaiters atomic.Int64 + +// acquireArgon takes the argon slot. A cancelled context returns its error +// first; a full wait queue returns ErrPasswordBusy. +func acquireArgon(ctx context.Context) error { + if err := ctx.Err(); err != nil { + return err + } + if argonSem.TryAcquire(1) { + return nil + } + if argonWaiters.Add(1) > maxArgonWaiters { + argonWaiters.Add(-1) + return ErrPasswordBusy + } + defer argonWaiters.Add(-1) + return argonSem.Acquire(ctx, 1) +} + // argonConcurrency is the number of argon2 operations allowed to run at once. const argonConcurrency = 1 @@ -71,34 +100,51 @@ const MinPasswordLen = 12 // merely links this package — most notably test binaries that lower the // cost via SetFastHashParams — doesn't pay a full-cost 64 MiB hash at // startup. -var dummyHash = sync.OnceValue(func() string { +var dummyHash = sync.OnceValue(computeDummyHash) + +// computeDummyHash builds the hash behind dummyHash. The caller holds the +// argon2 slot (VerifyDummy does), so this never queues and never runs a +// second argon2 operation beside another one. +func computeDummyHash() string { r := make([]byte, 32) if _, err := rand.Read(r); err != nil { // rand.Read only fails if the OS CSPRNG is broken; in that case // we can't safely serve auth anyway. panic("crypto/rand: " + err.Error()) } - h, err := HashPassword(context.Background(), string(r)) + h, err := hashLocked(string(r)) if err != nil { panic("init dummy hash: " + err.Error()) } return h -}) +} // VerifyDummy runs an argon2id compare against a hash nobody can match. // Use it on login paths where the outcome is already "deny" but you // want the time envelope to match a real verify. pw is discarded. -func VerifyDummy(ctx context.Context, pw string) { - _, _ = VerifyPassword(ctx, pw, dummyHash()) +// It returns ErrPasswordBusy (or the context error) when no slot was obtained. +// The slot is taken before the lazy dummy hash is built, so a flood fails +// fast here too instead of piling up behind the first computation. +func VerifyDummy(ctx context.Context, pw string) error { + if err := acquireArgon(ctx); err != nil { + return fmt.Errorf("verify password: %w", err) + } + defer argonSem.Release(1) + _, err := verifyLocked(pw, dummyHash()) + return err } // HashPassword hashes a password using argon2id. func HashPassword(ctx context.Context, pw string) (string, error) { - if err := argonSem.Acquire(ctx, 1); err != nil { + if err := acquireArgon(ctx); err != nil { return "", fmt.Errorf("hash password: %w", err) } defer argonSem.Release(1) + return hashLocked(pw) +} +// hashLocked hashes pw; the caller must hold the argon2 slot. +func hashLocked(pw string) (string, error) { salt := make([]byte, argonSaltLen) if _, err := rand.Read(salt); err != nil { return "", err @@ -115,11 +161,15 @@ func HashPassword(ctx context.Context, pw string) (string, error) { // VerifyPassword verifies a password against an argon2id hash. func VerifyPassword(ctx context.Context, pw, encoded string) (bool, error) { // Acquire semaphore before parsing to ensure timing parity on all paths. - if err := argonSem.Acquire(ctx, 1); err != nil { + if err := acquireArgon(ctx); err != nil { return false, fmt.Errorf("verify password: %w", err) } defer argonSem.Release(1) + return verifyLocked(pw, encoded) +} +// verifyLocked checks pw against encoded; the caller must hold the argon2 slot. +func verifyLocked(pw, encoded string) (bool, error) { parts := strings.Split(encoded, "$") if len(parts) != 6 || parts[1] != "argon2id" { return false, errors.New("unsupported hash format") diff --git a/api/internal/auth/password_busy.go b/api/internal/auth/password_busy.go new file mode 100644 index 000000000..960983e27 --- /dev/null +++ b/api/internal/auth/password_busy.go @@ -0,0 +1,27 @@ +package auth + +import ( + "errors" + "net/http" + + "github.com/GameplanePanel/gameplane/api/internal/httperr" + "github.com/GameplanePanel/gameplane/api/internal/messages" +) + +// writePasswordBusy answers the generic 503 with Retry-After when the argon2 +// queue is full. The response is identical whatever the username, so it leaks +// nothing on the unauthenticated login path. +func writePasswordBusy(w http.ResponseWriter, req *http.Request) { + w.Header().Set("Retry-After", "5") + httperr.WriteMessage(w, req, messages.New("server.generic.503", nil)) +} + +// WriteIfPasswordBusy answers the generic 503 with Retry-After and returns +// true when err is ErrPasswordBusy; otherwise it writes nothing. +func WriteIfPasswordBusy(w http.ResponseWriter, req *http.Request, err error) bool { + if !errors.Is(err, ErrPasswordBusy) { + return false + } + writePasswordBusy(w, req) + return true +} diff --git a/api/internal/auth/ratelimit.go b/api/internal/auth/ratelimit.go index 2526c1115..33e39b243 100644 --- a/api/internal/auth/ratelimit.go +++ b/api/internal/auth/ratelimit.go @@ -3,6 +3,7 @@ package auth import ( "net" "net/http" + "net/netip" "strconv" "sync" "time" @@ -106,7 +107,7 @@ func (t *TokenBucket) Middleware(next http.Handler) http.Handler { clientIP = host } } - if !t.requestBudget(w, req, clientIP) { + if !t.requestBudget(w, req, LimiterSourceKey(clientIP)) { return } next.ServeHTTP(w, req) @@ -188,3 +189,19 @@ var ShareLimiter = namedBucket("public_share", 20.0/60.0, 20) // than the IP (e.g. username). Returns the same bool as Middleware's // check but lets callers produce custom 429 responses. func (t *TokenBucket) AllowUser(key string) bool { return t.Allow(key) } + +// LimiterSourceKey maps a client address to its per-IP limiter key: IPv4 +// addresses are used as is, IPv6 addresses collapse to their /64 so one +// allocation cannot mint a fresh bucket per address. Only limiter keys use +// it; audit records keep the full address. +func LimiterSourceKey(ip string) string { + a, err := netip.ParseAddr(ip) + if err != nil || a.Is4() || a.Is4In6() { + return ip + } + p, err := a.Prefix(64) + if err != nil { + return ip + } + return p.String() +} diff --git a/api/internal/auth/sftp.go b/api/internal/auth/sftp.go index 7ba88cc2e..a4c1bbb81 100644 --- a/api/internal/auth/sftp.go +++ b/api/internal/auth/sftp.go @@ -169,7 +169,9 @@ func (s *SessionStore) VerifySFTPPassword(ctx context.Context, username, pw stri WHERE u.username = ?`, username, ).Scan(&id, &ep, &hash) if errors.Is(err, sql.ErrNoRows) || (err == nil && !hash.Valid) { - VerifyDummy(ctx, pw) + if derr := VerifyDummy(ctx, pw); errors.Is(derr, ErrPasswordBusy) { + return 0, 0, false, fmt.Errorf("verify sftp password: %w", derr) + } return 0, 0, false, nil } if err != nil { diff --git a/api/internal/auth/testparams.go b/api/internal/auth/testparams.go index 56819d69a..00ffcc57a 100644 --- a/api/internal/auth/testparams.go +++ b/api/internal/auth/testparams.go @@ -1,5 +1,10 @@ package auth +import ( + "context" + "sync" +) + // SetFastHashParams drops the argon2id cost parameters to the cheapest // sensible values for the duration of a test and restores them via // tb.Cleanup. Hashing at production cost is tens of milliseconds plus a @@ -23,3 +28,26 @@ func SetFastHashParams(tb interface{ Cleanup(func()) }) { argonTime, argonMemory = prevTime, prevMemory }) } + +// SaturateArgonQueue holds the argon2 slot and fills the waiter queue so the +// next password operation fails fast with ErrPasswordBusy. It is for tests of +// the busy path in other packages; the returned func (also registered with +// Cleanup) undoes it. Not safe to call from parallel tests. +func SaturateArgonQueue(tb interface { + Cleanup(func()) + Fatalf(string, ...any) +}) func() { + if err := argonSem.Acquire(context.Background(), argonConcurrency); err != nil { + tb.Fatalf("saturate argon: %v", err) + } + argonWaiters.Add(maxArgonWaiters) + var once sync.Once + release := func() { + once.Do(func() { + argonWaiters.Add(-maxArgonWaiters) + argonSem.Release(argonConcurrency) + }) + } + tb.Cleanup(release) + return release +} diff --git a/api/internal/handlers/cluster_actions.go b/api/internal/handlers/cluster_actions.go index ed598c2a6..33fb17af1 100644 --- a/api/internal/handlers/cluster_actions.go +++ b/api/internal/handlers/cluster_actions.go @@ -10,11 +10,13 @@ import ( "crypto/x509/pkix" "encoding/base64" "encoding/hex" + "encoding/json" "encoding/pem" "errors" "fmt" "net/http" "os" + "regexp" "strings" "time" @@ -244,7 +246,15 @@ func (h *clusterActions) kubeconfig(w http.ResponseWriter, req *http.Request) { // signClientCert creates a CertificateSigningRequest for the kube-apiserver // client signer, approves it, and waits briefly for the issued cert. func (h *clusterActions) signClientCert(ctx context.Context, username string, csrPEM []byte) ([]byte, error) { - name := "gameplane-" + username + "-" + time.Now().UTC().Format("20060102150405") + // The username can hold characters that are not valid in an object name + // (uppercase, '@', '+', '_'), so the name carries a hash of it instead. The + // username stays in the certificate subject. + sum := sha256.Sum256([]byte(username)) + var suffix [4]byte + if _, err := rand.Read(suffix[:]); err != nil { + return nil, fmt.Errorf("generate CSR name: %w", err) + } + name := "gameplane-" + hex.EncodeToString(sum[:8]) + "-" + hex.EncodeToString(suffix[:]) expSeconds := int32(3600) // 1h short-lived csr := &certv1.CertificateSigningRequest{ ObjectMeta: metav1.ObjectMeta{Name: name}, @@ -294,9 +304,29 @@ func (h *clusterActions) signClientCert(ctx context.Context, username string, cs } } +// yamlPlainName matches usernames that are safe as a plain YAML scalar. +var yamlPlainName = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9._@-]*$`) + +// yamlName renders a username as a YAML string scalar. SSO usernames are not +// character-checked, so anything outside yamlPlainName, or a word YAML 1.1 +// reads as a bool or null, is double-quoted (JSON string syntax is valid +// YAML). +func yamlName(username string) string { + switch strings.ToLower(username) { + case "y", "n", "yes", "no", "on", "off", "true", "false", "null": + default: + if yamlPlainName.MatchString(username) { + return username + } + } + q, _ := json.Marshal(username) + return string(q) +} + // renderKubeconfig assembles a minimal client-cert kubeconfig. func renderKubeconfig(server string, caPEM, certPEM, keyPEM []byte, username string) string { b64 := base64.StdEncoding.EncodeToString + name := yamlName(username) return fmt.Sprintf(`apiVersion: v1 kind: Config clusters: @@ -315,5 +345,5 @@ users: user: client-certificate-data: %s client-key-data: %s -`, server, b64(caPEM), username, username, b64(certPEM), b64(keyPEM)) +`, server, b64(caPEM), name, name, b64(certPEM), b64(keyPEM)) } diff --git a/api/internal/handlers/cluster_actions_yamlname_test.go b/api/internal/handlers/cluster_actions_yamlname_test.go new file mode 100644 index 000000000..214394851 --- /dev/null +++ b/api/internal/handlers/cluster_actions_yamlname_test.go @@ -0,0 +1,24 @@ +package handlers + +import ( + "testing" + + "sigs.k8s.io/yaml" +) + +func TestYamlNameRoundTrips(t *testing.T) { + for _, name := range []string{"alice", "alice@example.com", "Alice: admin", "yes", "NULL", "123", "-x", "a\"b\\c", "#tag", "名前"} { + var got struct { + User string `json:"user"` + } + if err := yaml.Unmarshal([]byte("user: "+yamlName(name)+"\n"), &got); err != nil { + t.Fatalf("%q: %v", name, err) + } + if got.User != name { + t.Fatalf("%q round-tripped as %q", name, got.User) + } + } + if yamlName("alice") != "alice" { + t.Fatalf("plain name was quoted: %s", yamlName("alice")) + } +} diff --git a/api/internal/handlers/config.go b/api/internal/handlers/config.go index bb54d27ac..aee65f28e 100644 --- a/api/internal/handlers/config.go +++ b/api/internal/handlers/config.go @@ -229,13 +229,17 @@ func (h *configHandler) resetRoleMapping(w http.ResponseWriter, req *http.Reques return } - // Parse the auth config. If the row doesn't exist, start with an empty config. + // Parse the auth config. A missing row means nothing is stored, so there is nothing to reset. var c authCfg - if err == nil { - if err := json.Unmarshal([]byte(authJSON), &c); err != nil { - httperr.Write(w, req, err) - return - } + if errors.Is(err, sql.ErrNoRows) { + // Nothing stored, nothing to reset. Writing a zero authCfg would store + // {"providers":null}, which disables every login method on PostgreSQL. + writeJSON(w, map[string]any{"section": "auth", "value": nil}) + return + } + if err := json.Unmarshal([]byte(authJSON), &c); err != nil { + httperr.Write(w, req, err) + return } // Check if the role had an override before removal (for audit event). diff --git a/api/internal/handlers/config_reset_norow_test.go b/api/internal/handlers/config_reset_norow_test.go new file mode 100644 index 000000000..394134247 --- /dev/null +++ b/api/internal/handlers/config_reset_norow_test.go @@ -0,0 +1,24 @@ +package handlers + +import ( + "database/sql" + "errors" + "net/http" + "testing" +) + +// A role-mapping reset with no stored auth row must not write one: a zero +// auth config ({"providers":null}) would turn off every login method. +func TestConfig_ResetRoleMapping_NoAuthRowWritesNothing(t *testing.T) { + srv, store := newConfigServer(t) + + status, body := doReq(t, http.MethodDelete, srv.URL+"/admin/config/auth/role-mappings/operator", nil) + if status != http.StatusOK { + t.Fatalf("status = %d, want 200; body=%s", status, body) + } + var v string + err := store.DB.QueryRowContext(t.Context(), `SELECT value FROM config WHERE key = 'auth'`).Scan(&v) + if !errors.Is(err, sql.ErrNoRows) { + t.Fatalf("auth row after reset: value=%q err=%v, want no row", v, err) + } +} diff --git a/api/internal/handlers/ownership_protect_test.go b/api/internal/handlers/ownership_protect_test.go new file mode 100644 index 000000000..b4763faee --- /dev/null +++ b/api/internal/handlers/ownership_protect_test.go @@ -0,0 +1,188 @@ +package handlers + +import ( + "context" + "net/http" + "regexp" + "testing" + + certv1 "k8s.io/api/certificates/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/kubernetes/fake" + "k8s.io/client-go/rest" + k8stesting "k8s.io/client-go/testing" + + "github.com/GameplanePanel/gameplane/api/internal/kube" +) + +func dangling() []any { + return []any{map[string]any{ + "apiVersion": "v1", "kind": "ConfigMap", "name": "x", "uid": "00000000-0000-0000-0000-000000000000", + }} +} + +func TestResources_Update_GameServerKeepsLiveOwnership(t *testing.T) { + live := newServerObj("gameplane-games", "alpha") + live.SetFinalizers([]string{"gameplane.local/keep"}) + k := fakeKubeClient(live) + r := mountResourcesRouter(k) + body := map[string]any{ + "apiVersion": "gameplane.local/v1alpha1", + "kind": "GameServer", + "metadata": map[string]any{ + "name": "alpha", "namespace": "gameplane-games", + "ownerReferences": dangling(), "finalizers": []any{"evil/x"}, + }, + "spec": map[string]any{"templateRef": map[string]any{"name": "minecraft"}}, + } + rr := do(t, r, "PUT", "/servers/alpha", body) + if rr.Code != http.StatusOK { + t.Fatalf("put: %d %s", rr.Code, rr.Body) + } + got, err := k.Dynamic.Resource(kube.GVRs["servers"]).Namespace("gameplane-games").Get(context.Background(), "alpha", metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + if len(got.GetOwnerReferences()) != 0 { + t.Errorf("ownerReferences = %v, want none", got.GetOwnerReferences()) + } + if f := got.GetFinalizers(); len(f) != 1 || f[0] != "gameplane.local/keep" { + t.Errorf("finalizers = %v, want live value", f) + } +} + +func TestResources_Create_ClearsClientOwnership(t *testing.T) { + for _, tc := range []struct{ path, kind string }{ + {"/servers", "GameServer"}, + {"/backups", "Backup"}, + } { + k := fakeKubeClient() + r := mountResourcesRouter(k) + body := map[string]any{ + "apiVersion": "gameplane.local/v1alpha1", + "kind": tc.kind, + "metadata": map[string]any{ + "name": "n1", "ownerReferences": dangling(), "finalizers": []any{"evil/x"}, + }, + "spec": map[string]any{"templateRef": map[string]any{"name": "minecraft"}, "serverRef": map[string]any{"name": "alpha"}}, + } + rr := do(t, r, "POST", tc.path, body) + if rr.Code != http.StatusCreated { + t.Fatalf("%s create: %d %s", tc.path, rr.Code, rr.Body) + } + got, err := k.Dynamic.Resource(kube.GVRs[tc.path[1:]]).Namespace("gameplane-games").Get(context.Background(), "n1", metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + if len(got.GetOwnerReferences()) != 0 || len(got.GetFinalizers()) != 0 { + t.Errorf("%s: ownerReferences=%v finalizers=%v, want none", tc.path, got.GetOwnerReferences(), got.GetFinalizers()) + } + } +} + +func TestProtectOwnership(t *testing.T) { + obj := &unstructured.Unstructured{Object: map[string]any{"metadata": map[string]any{ + "ownerReferences": dangling(), "finalizers": []any{"evil/x"}, + }}} + protectOwnership(obj, nil) + if len(obj.GetOwnerReferences()) != 0 || len(obj.GetFinalizers()) != 0 { + t.Fatal("nil live must clear ownership") + } +} + +func TestProtectOwnership_KeepsLiveValues(t *testing.T) { + live := &unstructured.Unstructured{Object: map[string]any{"metadata": map[string]any{ + "ownerReferences": []any{map[string]any{ + "apiVersion": "gameplane.local/v1alpha1", "kind": "GameServer", "name": "alpha", + "uid": "u1", "controller": true, + }}, + "finalizers": []any{"gameplane.local/keep"}, + }}} + obj := &unstructured.Unstructured{Object: map[string]any{"metadata": map[string]any{ + "ownerReferences": dangling(), "finalizers": []any{"evil/x"}, + }}} + protectOwnership(obj, live) + refs := obj.GetOwnerReferences() + if len(refs) != 1 || refs[0].Name != "alpha" || refs[0].Kind != "GameServer" { + t.Errorf("ownerReferences = %v, want the live reference", refs) + } + if f := obj.GetFinalizers(); len(f) != 1 || f[0] != "gameplane.local/keep" { + t.Errorf("finalizers = %v, want live value", f) + } +} + +func TestResources_Update_ScheduleKeepsLiveOwnership(t *testing.T) { + live := &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "gameplane.local/v1alpha1", + "kind": "BackupSchedule", + "metadata": map[string]any{ + "name": "alpha-auto", "namespace": "gameplane-games", + "ownerReferences": []any{map[string]any{ + "apiVersion": "gameplane.local/v1alpha1", "kind": "GameServer", "name": "alpha", + "uid": "u1", "controller": true, + }}, + "finalizers": []any{"gameplane.local/keep"}, + }, + "spec": map[string]any{"serverRef": map[string]any{"name": "alpha"}}, + }} + k := fakeKubeClient(live) + r := mountResourcesRouter(k) + body := map[string]any{ + "apiVersion": "gameplane.local/v1alpha1", + "kind": "BackupSchedule", + "metadata": map[string]any{ + "name": "alpha-auto", "namespace": "gameplane-games", + "ownerReferences": dangling(), "finalizers": []any{"evil/x"}, + }, + "spec": map[string]any{"serverRef": map[string]any{"name": "alpha"}}, + } + rr := do(t, r, "PUT", "/schedules/alpha-auto", body) + if rr.Code != http.StatusOK { + t.Fatalf("put: %d %s", rr.Code, rr.Body) + } + got, err := k.Dynamic.Resource(kube.GVRs["schedules"]).Namespace("gameplane-games").Get(context.Background(), "alpha-auto", metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + refs := got.GetOwnerReferences() + if len(refs) != 1 || refs[0].Name != "alpha" || refs[0].Kind != "GameServer" || refs[0].UID != "u1" { + t.Errorf("ownerReferences = %v, want exactly the live reference", refs) + } + if f := got.GetFinalizers(); len(f) != 1 || f[0] != "gameplane.local/keep" { + t.Errorf("finalizers = %v, want exactly the live finalizer", f) + } +} + +func TestConfig_ResetRoleMapping_NoAuthRow_WritesNothing(t *testing.T) { + srv, store := newConfigServer(t) + status, body := doReq(t, "DELETE", srv.URL+"/admin/config/auth/role-mappings/admin", nil) + if status != http.StatusOK { + t.Fatalf("status = %d; body=%s", status, body) + } + var n int + if err := store.DB.QueryRowContext(context.Background(), `SELECT COUNT(*) FROM config WHERE key = 'auth'`).Scan(&n); err != nil { + t.Fatal(err) + } + if n != 0 { + t.Fatalf("auth row count = %d, want 0", n) + } +} + +func TestSignClientCert_NameIsDNSSafeForAnyUsername(t *testing.T) { + cs := fake.NewSimpleClientset() + var created string + cs.PrependReactor("create", "certificatesigningrequests", func(a k8stesting.Action) (bool, runtime.Object, error) { + created = a.(k8stesting.CreateAction).GetObject().(*certv1.CertificateSigningRequest).Name + return false, nil, nil + }) + cs.PrependReactor("get", "certificatesigningrequests", signedCSRReactor) + h := &clusterActions{k: &kube.Client{Typed: cs, Config: &rest.Config{}}, enabled: true} + if _, err := h.signClientCert(t.Context(), "Alice+ab12@Example.com", []byte("csr")); err != nil { + t.Fatalf("sign: %v", err) + } + if !regexp.MustCompile(`^[a-z0-9]([-a-z0-9]*[a-z0-9])?$`).MatchString(created) { + t.Fatalf("CSR name %q is not DNS-safe", created) + } +} diff --git a/api/internal/handlers/password_busy_test.go b/api/internal/handlers/password_busy_test.go new file mode 100644 index 000000000..0fe62a1ae --- /dev/null +++ b/api/internal/handlers/password_busy_test.go @@ -0,0 +1,62 @@ +package handlers + +import ( + "bytes" + "net/http" + "strconv" + "testing" + + "github.com/GameplanePanel/gameplane/api/internal/auth" +) + +// assertPasswordBusy checks the generic 503 + Retry-After answer for a full +// argon2 queue. +func assertPasswordBusy(t *testing.T, code int, retryAfter string) { + t.Helper() + if code != http.StatusServiceUnavailable { + t.Fatalf("status = %d, want 503", code) + } + if retryAfter != "5" { + t.Fatalf("Retry-After = %q, want 5", retryAfter) + } +} + +// busyPost posts body and returns the status code and Retry-After header. +func busyPost(t *testing.T, url, body string) (int, string) { + t.Helper() + req, err := http.NewRequestWithContext(t.Context(), http.MethodPost, url, bytes.NewBufferString(body)) + if err != nil { + t.Fatalf("request: %v", err) + } + req.Header.Set("Content-Type", "application/json") + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("post: %v", err) + } + defer func() { _ = resp.Body.Close() }() + return resp.StatusCode, resp.Header.Get("Retry-After") +} + +func TestUsers_CreatePasswordQueueFullAnswers503(t *testing.T) { + srv, _, _ := newUsersServer(t, &auth.User{ID: 1, Role: "admin"}) + auth.SaturateArgonQueue(t) + code, retryAfter := busyPost(t, srv.URL+"/users", `{"username":"busyuser","password":"longenoughpw1","role":"viewer"}`) + assertPasswordBusy(t, code, retryAfter) +} + +func TestUsers_ResetPasswordQueueFullAnswers503(t *testing.T) { + srv, store, _ := newUsersServer(t, &auth.User{ID: 1, Role: "admin"}) + id := seedUser(t, store, "busyreset", "viewer", "") + auth.SaturateArgonQueue(t) + code, retryAfter := busyPost(t, srv.URL+"/users/"+strconv.FormatInt(id, 10)+"/reset-password", `{"password":"longenoughpw1"}`) + assertPasswordBusy(t, code, retryAfter) +} + +func TestSFTPPassword_GenerateQueueFullAnswers503(t *testing.T) { + env := newSFTPLoginEnv(t) + uid, _ := insertSFTPUser(t, env, "busy.sftp@example.com", "busysftp") + self := sftpSelfRouter(env.sessions, env.store, uid, false) + auth.SaturateArgonQueue(t) + rr := sftpSelfDo(t, self, http.MethodPost, "/me/sftp/password", `{"length":`+strconv.Itoa(auth.SFTPPasswordMinLen)+`}`) + assertPasswordBusy(t, rr.Code, rr.Header().Get("Retry-After")) +} diff --git a/api/internal/handlers/resources.go b/api/internal/handlers/resources.go index 7dae9b4ef..136ccd69d 100644 --- a/api/internal/handlers/resources.go +++ b/api/internal/handlers/resources.go @@ -247,6 +247,10 @@ func createHandler(reg *kube.Registry, gvr schema.GroupVersionResource, auditor httperr.Write(w, req, err) return } + // A client-set ownerReference can make the Kubernetes garbage collector + // delete the object, and client finalizers can block deletion. Neither + // is ever taken from the client. + protectOwnership(obj, nil) // Record the creating user as the server's owner (informational). if gvr.Resource == "gameservers" { if !validServerName(obj.GetName()) { @@ -356,6 +360,7 @@ func updateHandler(reg *kube.Registry, gvr schema.GroupVersionResource, auditor return } protectServerAnnotations(obj, live) + protectOwnership(obj, live) // The dashboard sends spec back wholesale, so password config values // arrive as the redaction marker: keep the stored value for those. cfgRules = newConfigRuleCache(k) @@ -377,6 +382,25 @@ func updateHandler(reg *kube.Registry, gvr schema.GroupVersionResource, auditor } changeReason = securityChangeReason(req.Context(), k, obj, live) } + if gvr.Resource != "gameservers" { + // Other kinds: keep the stored ownerReferences and finalizers too. + var liveOther *unstructured.Unstructured + var getErr error + if cluster(gvr) { + liveOther, getErr = k.Dynamic.Resource(gvr).Get(req.Context(), name, metav1.GetOptions{}) + } else { + ns, ok := resolveNS(w, req) + if !ok { + return + } + liveOther, getErr = k.Dynamic.Resource(gvr).Namespace(ns).Get(req.Context(), name, metav1.GetOptions{}) + } + if getErr != nil && !apierrors.IsNotFound(getErr) { + httperr.Write(w, req, getErr) + return + } + protectOwnership(obj, liveOther) + } var updated *unstructured.Unstructured if cluster(gvr) { updated, err = k.Dynamic.Resource(gvr).Update(req.Context(), obj, metav1.UpdateOptions{}) @@ -883,3 +907,16 @@ func isServerOwnedConfigMap(ctx context.Context, k *kube.Client, ns, serverName } return false } + +// protectOwnership never takes metadata.ownerReferences or metadata.finalizers +// from the client: it keeps the live object's values, or clears them when +// there is no live object (create, or a PUT that creates). +func protectOwnership(obj, live *unstructured.Unstructured) { + if live == nil { + obj.SetOwnerReferences(nil) + obj.SetFinalizers(nil) + return + } + obj.SetOwnerReferences(live.GetOwnerReferences()) + obj.SetFinalizers(live.GetFinalizers()) +} diff --git a/api/internal/handlers/sftp.go b/api/internal/handlers/sftp.go index e063f693f..4b0c57afa 100644 --- a/api/internal/handlers/sftp.go +++ b/api/internal/handlers/sftp.go @@ -251,6 +251,9 @@ func (h *sftpSelfHandler) generatePassword(w http.ResponseWriter, req *http.Requ } pw, err := h.sessions.GenerateAndStoreSFTPPassword(req.Context(), uid, body.Length) if err != nil { + if auth.WriteIfPasswordBusy(w, req, err) { + return + } writeSFTPErr(w, req, err) return } diff --git a/api/internal/handlers/sftp_login.go b/api/internal/handlers/sftp_login.go index 548c0ca26..c84a0fc2d 100644 --- a/api/internal/handlers/sftp_login.go +++ b/api/internal/handlers/sftp_login.go @@ -3,6 +3,7 @@ package handlers import ( "context" "encoding/json" + "errors" "fmt" "log/slog" "net" @@ -111,7 +112,7 @@ func (h *sftpLoginHandler) login(w http.ResponseWriter, req *http.Request) { // long SSO email names that share a 64-rune prefix do not share a budget. The key is capped one rune // past the longest valid name, so an oversized name cannot grow the limiter's keys. auth.SetActor(ctx, actor) - if !auth.LoginLimiter.RequestBudget(w, req, sftpSourceKey(body.RemoteAddr, req)) { + if !auth.LoginLimiter.RequestBudget(w, req, auth.LimiterSourceKey(sftpSourceKey(body.RemoteAddr, req))) { return } if !auth.LoginUserLimiter.RequestBudget(w, req, truncateRunes(base, sftpUsernameMaxRunes+1)) { @@ -151,6 +152,12 @@ func (h *sftpLoginHandler) login(w http.ResponseWriter, req *http.Request) { ) if body.Password != "" { uid, ep, good, err := h.sessions.VerifySFTPPassword(ctx, base, body.Password) + if errors.Is(err, auth.ErrPasswordBusy) { + // Queue full: not a failed login, so no audit row. + w.Header().Set("Retry-After", "5") + httperr.WriteMessage(w, req, messages.New("server.generic.503", nil)) + return + } if err != nil || !good { refuse("credential") return diff --git a/api/internal/handlers/sftp_login_busy_test.go b/api/internal/handlers/sftp_login_busy_test.go new file mode 100644 index 000000000..d47212dc9 --- /dev/null +++ b/api/internal/handlers/sftp_login_busy_test.go @@ -0,0 +1,26 @@ +package handlers + +import ( + "net/http" + "testing" + + "github.com/GameplanePanel/gameplane/api/internal/auth" +) + +func TestSFTPLogin_PasswordQueueFullAnswers503(t *testing.T) { + env := newSFTPLoginEnv(t) + h := sftpLoginRouter(env) + name, _ := env.seedUser(t, "x") + + auth.SaturateArgonQueue(t) + rr := env.login(t, h, map[string]any{"username": name, "password": "whatever-123"}) + if rr.Code != http.StatusServiceUnavailable { + t.Fatalf("code=%d body=%s", rr.Code, rr.Body.String()) + } + if got := rr.Header().Get("Retry-After"); got != "5" { + t.Fatalf("Retry-After=%q, want 5", got) + } + if id := sftpProblemID(t, rr); id != "server.generic.503" { + t.Fatalf("messageId=%q", id) + } +} diff --git a/api/internal/handlers/users.go b/api/internal/handlers/users.go index c65d0a1fe..f06f7d402 100644 --- a/api/internal/handlers/users.go +++ b/api/internal/handlers/users.go @@ -151,6 +151,9 @@ func (h *userHandler) create(w http.ResponseWriter, req *http.Request) { } h2, err := auth.HashPassword(req.Context(), body.Password) if err != nil { + if auth.WriteIfPasswordBusy(w, req, err) { + return + } httperr.Write(w, req, err) return } @@ -834,6 +837,9 @@ func (h *userHandler) resetPassword(w http.ResponseWriter, req *http.Request) { } hash, err := auth.HashPassword(req.Context(), body.Password) if err != nil { + if auth.WriteIfPasswordBusy(w, req, err) { + return + } httperr.Write(w, req, err) return } diff --git a/api/internal/kube/stdin.go b/api/internal/kube/stdin.go index 9573be857..1ebd0a448 100644 --- a/api/internal/kube/stdin.go +++ b/api/internal/kube/stdin.go @@ -93,12 +93,26 @@ func (c *Client) WriteStdinLines(ctx context.Context, ns, pod, container string, Stdout: io.Discard, Tty: true, }) - // We end the session deliberately once the write has flushed, so a - // context cancel/deadline is the expected success path, not a failure. - if err != nil && !errors.Is(err, context.DeadlineExceeded) && !errors.Is(err, context.Canceled) { + return stdinResult(drained, err, ns, pod) +} + +// stdinResult maps the stream outcome to WriteStdinLines' result. A context +// cancel/deadline is the deliberate success path only once the stdin buffer +// has been fully drained; otherwise the attach ended (timeout, cancelled +// request) before anything was written and must not be reported as sent. +func stdinResult(drained <-chan struct{}, err error, ns, pod string) error { + select { + case <-drained: + if err != nil && !errors.Is(err, context.DeadlineExceeded) && !errors.Is(err, context.Canceled) { + return fmt.Errorf("write stdin to pod %s/%s: %w", ns, pod, err) + } + return nil + default: + if err == nil { + err = errors.New("attach ended before stdin was written") + } return fmt.Errorf("write stdin to pod %s/%s: %w", ns, pod, err) } - return nil } // notifyOnEOF wraps a reader and closes drained the first time the underlying diff --git a/api/internal/kube/stdin_result_test.go b/api/internal/kube/stdin_result_test.go new file mode 100644 index 000000000..550cbca3d --- /dev/null +++ b/api/internal/kube/stdin_result_test.go @@ -0,0 +1,33 @@ +package kube + +import ( + "context" + "errors" + "testing" +) + +func TestStdinResult(t *testing.T) { + closed := make(chan struct{}) + close(closed) + open := make(chan struct{}) + + if err := stdinResult(closed, context.Canceled, "ns", "p"); err != nil { + t.Fatalf("drained + canceled = %v, want nil", err) + } + if err := stdinResult(closed, context.DeadlineExceeded, "ns", "p"); err != nil { + t.Fatalf("drained + deadline = %v, want nil", err) + } + boom := errors.New("boom") + if err := stdinResult(closed, boom, "ns", "p"); !errors.Is(err, boom) { + t.Fatalf("drained + real error = %v, want wrapped boom", err) + } + if err := stdinResult(open, context.DeadlineExceeded, "ns", "p"); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("undrained + deadline = %v, want wrapped deadline error", err) + } + if err := stdinResult(open, context.Canceled, "ns", "p"); err == nil { + t.Fatal("undrained + canceled = nil, want error") + } + if err := stdinResult(open, nil, "ns", "p"); err == nil { + t.Fatal("undrained + nil = nil, want error") + } +} diff --git a/api/specs.md b/api/specs.md index fe746f989..ebb79394e 100644 --- a/api/specs.md +++ b/api/specs.md @@ -120,7 +120,7 @@ The HTTP server listens on `:8000` (configurable) with these route groups. Prome - `/auth/oidc/start` (legacy) — GET: single helm-provider start - `/auth/oidc/callback` (legacy) — GET: single helm-provider callback - `/healthz` — GET: liveness probe -- `/readyz` — GET: database readiness, a `PingContext` with a two-second deadline. At most one ping runs at once; concurrent probes return a generic 503 without queueing more database work. Success returns `ok`; unavailable or busy returns only `not ready`. The chart probes every five seconds with a three-second timeout; three consecutive failed probes remove readiness, tolerating brief SQLite connection contention. `/healthz` remains independent of the database, so outages do not trigger liveness restarts. +- `/readyz` — GET: database readiness, a `PingContext` with a two-second deadline. At most one ping runs at once; concurrent probes return a generic 503 without queueing more database work. Success returns `ok`; unavailable or busy returns only `not ready`. Requests carrying an `X-Forwarded-For` or `Forwarded` header (anything that came through a proxy or ingress) get 404, so public traffic cannot take the slot; kubelet probes send neither. The chart probes every five seconds with a three-second timeout; three consecutive failed probes remove readiness, tolerating brief SQLite connection contention. `/healthz` remains independent of the database, so outages do not trigger liveness restarts. **Protected (authenticated + RBAC):** - All six `/fleet/*` reads share a per-authenticated-user token bucket: 60 requests/minute sustained, burst 10. Exhausted requests receive 429 with `Retry-After: 1` before cluster discovery or resource listing. Sessions and routes share the account's budget; users behind the same IP do not. The SQLite API keeps the budget in memory. PostgreSQL replicas share the same account budget and still enforce owner/collaborator checks. @@ -152,6 +152,7 @@ The HTTP server listens on `:8000` (configurable) with these route groups. Prome - `/servers/{name}:capture-file` — GET: download completed PCAPNG file from the capture sidecar; query param `id={captureId}` (proxied to sidecar over mTLS; 409 if still running) - `/templates` — GET, POST: list and create GameTemplate CRDs - `/templates/{name}` — GET, PUT, DELETE: manage GameTemplate CRDs (cluster-scoped) +- Generic POST/PUT never take `metadata.ownerReferences` or `metadata.finalizers` from the client: POST clears them and PUT keeps the stored values, so a caller cannot make the garbage collector delete an object or block its deletion. This applies to servers, templates, backups, schedules and restores. - `/backups` — GET, POST: list and create Backup CRDs. POST drops any client-supplied `spec.origin`: only the operator's BackupSchedule controller records a Backup's provenance, which retention prunes by (#960). - `/backups/{name}` — GET, PUT, DELETE: manage Backup CRDs (namespaced, cluster-dispatch) - `/schedules` — GET, POST: list and create BackupSchedule CRDs @@ -261,6 +262,10 @@ unknown/missing routes never fall back locally. HTTP/WebSocket agent operations, RCON module actions and internal mod-update reads use the versioned gateway protocol. Stdin actions use the selected Kubernetes client with workload ownership preflight. Existing installations retain their direct local adapter. +A stdin action succeeds only once its input has drained into the attach: an +attach that ends first (cancelled, past its deadline, or closed without an error) +reports an error instead of "sent", and input that drained before a +cancellation or deadline still counts as sent. See [remote agent access](../docs/multicluster-agent-gateway.md) for registration, trust assumptions, rotation behavior and surfaces outside this protocol. @@ -586,7 +591,7 @@ audit:read, config:read, config:manage (cluster-scoped) 3. **Three-role baseline RBAC:** admin/operator/viewer roles reproduce historical permission matrix exactly 4. **Multi-dimensional RBAC:** namespace + cluster + owner/collaborator dimensions; cluster gating prevents cross-cluster privilege escalation 5. **Append-only migrations:** database schema mutations are irreversible (migrations 001-027); no down-migrations -6. **Login rate limiting:** `/auth/login` is per-IP (burst 10, 5/min, `LoginLimiter`) plus a per-username throttle layered on top (burst 6, 3/min, `LoginUserLimiter` in `auth/ratelimit.go`, applied from `auth/local.go`), which a browser carrying a valid `gameplane_login_device` cookie for that username (set on a successful login, HMAC using a process-local SQLite key or a shared PostgreSQL key with a signed expiry) skips; the OIDC callback routes (`/auth/oidc/{provider}/callback`, legacy `/auth/oidc/callback`) are per-IP only (burst 10, 10/min via `OIDCCallbackLimiter`), no per-user dimension +6. **Login rate limiting:** `/auth/login` is per-IP (burst 10, 5/min, `LoginLimiter`) plus a per-username throttle layered on top (burst 6, 3/min, `LoginUserLimiter` in `auth/ratelimit.go`, applied from `auth/local.go`), which a browser carrying a valid `gameplane_login_device` cookie for that username (set on a successful login, HMAC using a process-local SQLite key or a shared PostgreSQL key with a signed expiry) skips; the OIDC callback routes (`/auth/oidc/{provider}/callback`, legacy `/auth/oidc/callback`) are per-IP only (burst 10, 10/min via `OIDCCallbackLimiter`), no per-user dimension. The per-IP limiter buckets (login, OIDC callback, share, MCP/SFTP token-fail, SFTP login) key on the IPv6 /64 prefix via `auth.LimiterSourceKey`; IPv4 (and IPv4-mapped) addresses stay per address, and audit records keep the full address. 7. **Audit hash-chain:** each audit_events row includes hash of previous row (prev_hash) + its own content hash (hash); detects DB-level UPDATE/DELETE tampering 8. **Audit pagination is bounded:** The `Auditor.Page(ctx, limit)` method clamps the untrusted `limit` parameter to a maximum of 500 entries (`MaxAuditPageSize`). Clamping occurs at both the API handler layer (api/internal/handlers/audit.go line 25) and the store layer (api/internal/audit/audit.go line 910) so untrusted input is bounded at the earliest opportunity and again at use time. The allocated slice is always created with capacity within the bound (`make([]Event, 0, limit)` after clamping), guaranteeing that no untrusted client input can cause unbounded memory allocation regardless of how the limit value flows through the system. 9. **Session CSRF protection:** CSRF token paired with session token; validated on state-changing requests. The CSRF cookie is deliberately **not** `HttpOnly` — the SPA reads it via JS and echoes it back as the `X-Gameplane-CSRF` header (double-submit pattern); making it `HttpOnly` would break the protection it's providing. The session cookie itself stays `HttpOnly`. Cookie *clearing* (logout) always sends `HttpOnly` regardless of the original cookie, since a delete carries no value for a script to read and the browser matches the clear on Name/Domain/Path alone. This is why the `.golangci.yml` gosec G124 exclusion is scoped narrowly to `api/internal/auth/sessions.go`. @@ -712,12 +717,12 @@ Foreign keys are enforced only on Postgres (modernc-sqlite runs with FK OFF); th ## Security considerations ### Authentication -- **Local:** argon2id (Argon2id13, m=64MiB, t=3, p=2) with per-user random salt; ~200ms per check; operations are bounded by a 1-slot weighted semaphore (`argonConcurrency`) that honours request context, so client disconnects abort pending argon2 operations and prevent stalling under concurrent login attempts. Each operation allocates a 64 MiB block that is garbage on return, so at startup `api/cmd/memlimit.go` also sets the Go soft memory limit to 80% of the cgroup memory limit (256Mi chart default -> ~204 MiB) unless `GOMEMLIMIT` is set, making the GC reclaim those blocks before a burst of concurrent failed logins can OOM-kill the container +- **Local:** argon2id (Argon2id13, m=64MiB, t=3, p=2) with per-user random salt; ~200ms per check; operations are bounded by a 1-slot weighted semaphore (`argonConcurrency`) that honours request context, so client disconnects abort pending argon2 operations and prevent stalling under concurrent login attempts. At most 64 callers (`maxArgonWaiters`) queue for the slot; beyond that the operation fails fast with `ErrPasswordBusy`, and `/auth/login` and the SFTP login answer 503 `server.generic.503` with `Retry-After: 5` (identical for known and unknown usernames, no failed-login audit row). The lazily computed dummy hash bypasses that cap. Each operation allocates a 64 MiB block that is garbage on return, so at startup `api/cmd/memlimit.go` also sets the Go soft memory limit to 80% of the cgroup memory limit (256Mi chart default -> ~204 MiB) unless `GOMEMLIMIT` is set, making the GC reclaim those blocks before a burst of concurrent failed logins can OOM-kill the container - **OIDC:** `coreos/go-oidc/v3` discovery + `go-jose/v4` JWT validation; claims mapping (email, groups, roles). Groups map to roles through an ordered rule list (first match wins, any role, built-in or custom); each user carries a role source (`sso`, `sso_pending`, `manual`) so a role set by hand is kept at sign-in. See "SSO role rules and role source" under "OIDC role mapping" above. - **Sessions:** cryptographically random token + paired CSRF token; only the SHA-256 digest (hex) of the token is persisted (the cookie carries the raw value, so a database copy cannot be replayed as a cookie; lookup, logout and cleanup hash the presented value first); DB-only persistence (no in-memory store), 12-hour TTL from creation, garbage-collected on an interval (`SessionStore.StartGC`) - **CSRF cookie is JS-readable by design:** unlike the session cookie (`HttpOnly`), the CSRF cookie is set `HttpOnly: false` so the SPA can read its value and echo it back as `X-Gameplane-CSRF` on mutating requests — the standard double-submit pattern (see `docs/security.md`). Logout's cookie-clear always sends `HttpOnly: true` regardless, since a MaxAge<0 delete carries no value and the browser matches it on Name/Domain/Path alone. - **Bootstrap:** `bootstrap-admin` subcommand hashes password same way as API -- **Client IP:** `auth.ClientIPFromTrustedProxies` (`internal/auth/clientip.go`) records the client IP that the rate limiters and audit key on. A TCP peer outside `--trusted-proxies` is the client and its `X-Forwarded-For` is ignored. Behind a trusted peer the header is read right to left up to the first address outside the list, or to the leftmost address when every hop is trusted; an entry that isn't an IP address ends the walk at the last address reached. An empty list makes the peer the client. Tests: `internal/auth/clientip_test.go`. +- **Client IP:** `auth.ClientIPFromTrustedProxies` (`internal/auth/clientip.go`) records the client IP that the rate limiters and audit key on. A TCP peer outside `--trusted-proxies` is the client and its `X-Forwarded-For` is ignored. Behind a trusted peer the header is read right to left up to the first address outside the list, or to the leftmost address when every hop is trusted; an entry that isn't an IP address ends the walk at the last address reached. An empty list makes the peer the client. Tests: `internal/auth/clientip_test.go`. The per-IP limiter buckets (login, OIDC callback, share, MCP/SFTP token-fail, SFTP login) key on the IPv6 /64 prefix via `auth.LimiterSourceKey`; IPv4 (and IPv4-mapped) addresses stay per address, and audit records keep the full address. - **Login audit attribution:** a successful local login records the signed-in username as the audit actor (`SetActor` in `internal/auth/local.go`), so the `/auth/login` audit row names who signed in; a failed login stays anonymous. Tests: `TestLogin_Success_AttributesAuditActor`, `TestLogin_WrongPassword_LeavesAuditActorAnonymous` (`internal/auth/local_test.go`). ### Authorization @@ -749,7 +754,7 @@ Foreign keys are enforced only on Postgres (modernc-sqlite runs with FK OFF); th - **Clones:** cloning drops the source's server-specific pin. Before creating the clone, the API checks that its current catalog schema still marks every copied, non-empty source password as a password. If those fields were removed/retyped, or their protection cannot be verified, cloning returns `409` without creating anything. Safe clones copy config verbatim and atomically record the inherited password key names in `gameplane.local/protected-config-keys`. This reserved annotation joins the effective schema for redaction and PUT preservation, including before the clone's first pin and after catalog changes. Cache identity includes this metadata. Clones of clones carry the classification forward. Generic POST/PUT cannot forge or remove it, and owner/lifecycle patches preserve it. Malformed metadata fails closed. The operator rejects unsafe admission/pin changes before value validation and retires protection only for empty/absent stored values during a successful pin update. Clear or remove a protected value before adopting a template that retypes it, then set the new ordinary value after admission. ### Audit -- **Scope:** every mutating request (POST/PATCH/DELETE); reads excluded +- **Scope:** every routed mutating request (POST/PUT/PATCH/DELETE); reads and requests no route matched (404/405 from the router's NotFound/MethodNotAllowed handlers, including unknown paths under mounted subrouters) are excluded, while an unauthenticated request under an authenticated group is answered 401 by `Authenticate` before routing and is still recorded as an anonymous attempt; the stored path and target are truncated to 512 bytes on a UTF-8 boundary - **Sinks:** database (table audit_events) + webhook (POST JSON) + S3 (object storage) + syslog bridge (HTTP->syslog relay) + stdout (structured logs) - **Hash-chain:** prev_hash + hash computed at insert time; Verify tool detects tampering - **Retention:** optional daily prune (--audit-retention-days) diff --git a/bundlefetch/oci/bundle.go b/bundlefetch/oci/bundle.go index bb1a1cdd2..f47974de1 100644 --- a/bundlefetch/oci/bundle.go +++ b/bundlefetch/oci/bundle.go @@ -37,6 +37,39 @@ const ( LayerNameIcon = "icon.png" ) +// Per-layer size caps for the non-locale layers. Pull checks the size the +// manifest declares before it reads a layer, so a hostile registry cannot make +// the operator allocate an arbitrary amount of memory (the check runs before +// any signature verification). +const ( + MaxMetadataLayerSize = 256 * 1024 + MaxTemplateLayerSize = 4 * 1024 * 1024 + MaxReadmeLayerSize = 1024 * 1024 + MaxIconLayerSize = 1024 * 1024 + + // MaxBundleSize bounds the declared size of every layer Pull reads, locale + // layers included. It is the sum of the per-layer caps plus + // MaxLocaleTotalSize, so a bundle within every individual cap and the + // locale budget always fits. + MaxBundleSize = MaxMetadataLayerSize + MaxTemplateLayerSize + MaxReadmeLayerSize + + MaxIconLayerSize + MaxLocaleTotalSize +) + +// layerSizeLimit returns the size cap of a known non-locale layer title. +func layerSizeLimit(title string) (int64, bool) { + switch title { + case LayerNameMetadata: + return MaxMetadataLayerSize, true + case LayerNameTemplate: + return MaxTemplateLayerSize, true + case LayerNameReadme: + return MaxReadmeLayerSize, true + case LayerNameIcon: + return MaxIconLayerSize, true + } + return 0, false +} + // Locale layers carry module translations. Each is titled // "locales/.json" and typed MediaTypeLocale. const ( diff --git a/bundlefetch/oci/client.go b/bundlefetch/oci/client.go index 7b7ac9f16..1dbf84605 100644 --- a/bundlefetch/oci/client.go +++ b/bundlefetch/oci/client.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "io" "net/http" "sort" "time" @@ -183,6 +184,11 @@ func (c *Client) Pull(ctx context.Context, ref, reference string) (string, map[s return layers[i].Annotations[AnnotationTitle] < layers[j].Annotations[AnnotationTitle] }) var budget LocaleBudget + // The per-title caps and MaxBundleSize describe module bundles. Other + // artifact types (theme packages) define their own files and are bounded + // by WithMaxLayerBytes and WithMaxTotalBytes instead. + moduleBundle := c.artifactType == ArtifactType + var total int64 var totalBytes int64 for _, layer := range layers { title := layer.Annotations[AnnotationTitle] @@ -201,6 +207,24 @@ func (c *Client) Pull(ctx context.Context, ref, reference string) (string, map[s files[title] = OversizedLocale continue } + } else if moduleBundle { + // Only the layers the module bundle format defines are read; each + // is size-checked before any byte is fetched. + limit, known := layerSizeLimit(title) + if !known { + continue + } + if layer.Size > limit { + return "", nil, fmt.Errorf("layer %s is %d bytes, over the %d-byte limit", title, layer.Size, limit) + } + } + if layer.Size < 0 { + return "", nil, fmt.Errorf("layer %s declares a negative size", title) + } + if moduleBundle { + if total += layer.Size; total > MaxBundleSize { + return "", nil, fmt.Errorf("bundle layers exceed the %d-byte limit", int64(MaxBundleSize)) + } } if c.maxLayerBytes > 0 && layer.Size > c.maxLayerBytes { return "", nil, fmt.Errorf("layer %s is %d bytes; limit is %d", title, layer.Size, c.maxLayerBytes) @@ -228,7 +252,9 @@ func readBlob(ctx context.Context, r *remote.Repository, desc ocispec.Descriptor return nil, err } defer func() { _ = rc.Close() }() - data, err := content.ReadAll(rc, desc) + // The declared size was bounded by the caller; the LimitReader keeps a + // server that sends more than it declared from growing the read. + data, err := content.ReadAll(io.LimitReader(rc, desc.Size+1), desc) if err != nil { return nil, fmt.Errorf("check blob %s: %w", desc.Digest, err) } diff --git a/bundlefetch/oci/layer_caps_scope_test.go b/bundlefetch/oci/layer_caps_scope_test.go new file mode 100644 index 000000000..13111999c --- /dev/null +++ b/bundlefetch/oci/layer_caps_scope_test.go @@ -0,0 +1,94 @@ +package oci + +import ( + "bytes" + "context" + "encoding/json" + "strings" + "testing" + + ocispec "github.com/opencontainers/image-spec/specs-go/v1" +) + +// pushDeclared pushes a manifest of artifactType whose layers declare the +// given titles and sizes. Blobs are stored only for layers whose data is +// non-nil, so a size check that runs before any fetch can be exercised with +// declared sizes far larger than the test stores. +func pushDeclared(t *testing.T, reg *fakeRegistry, repo, artifactType string, layers []ocispec.Descriptor, data map[string][]byte) { + t.Helper() + emptyConfig := []byte(`{}`) + reg.putBlob(emptyConfig) + manifest := ocispec.Manifest{ + MediaType: ocispec.MediaTypeImageManifest, + ArtifactType: artifactType, + Config: ocispec.Descriptor{ + MediaType: MediaTypeConfig, + Digest: digestFor(emptyConfig), + Size: int64(len(emptyConfig)), + }, + } + for _, l := range layers { + title := l.Annotations[AnnotationTitle] + if b, ok := data[title]; ok { + l.Digest = digestFromString(reg.putBlob(b)) + l.Size = int64(len(b)) + } else if l.Digest == "" { + l.Digest = digestFor([]byte(title)) + } + manifest.Layers = append(manifest.Layers, l) + } + mb, err := json.Marshal(manifest) + if err != nil { + t.Fatalf("marshal manifest: %v", err) + } + reg.pushManifest(repo, "1.0.0", mb) +} + +func titled(title, mediaType string, size int64) ocispec.Descriptor { + return ocispec.Descriptor{MediaType: mediaType, Size: size, Annotations: map[string]string{AnnotationTitle: title}} +} + +func TestPull_RejectsNegativeLayerSize(t *testing.T) { + reg := newFakeRegistry(t) + pushDeclared(t, reg, "gameplane/negative", "application/vnd.example.theme", + []ocispec.Descriptor{titled("theme.yaml", "text/yaml", -1)}, nil) + _, _, err := New(nil, true).WithArtifactType("application/vnd.example.theme"). + Pull(context.Background(), reg.host()+"/gameplane/negative", "1.0.0") + if err == nil || !strings.Contains(err.Error(), "negative size") { + t.Fatalf("Pull err = %v, want a negative size error", err) + } +} + +func TestPull_RejectsModuleBundleOverTotal(t *testing.T) { + // Repeated template.yaml layers each stay within their own cap but + // together exceed MaxBundleSize. + reg := newFakeRegistry(t) + var layers []ocispec.Descriptor + for range MaxBundleSize/MaxTemplateLayerSize + 1 { + layers = append(layers, titled(LayerNameTemplate, MediaTypeTemplate, MaxTemplateLayerSize)) + } + pushDeclared(t, reg, "gameplane/overtotal", ArtifactType, layers, map[string][]byte{LayerNameTemplate: bytes.Repeat([]byte("t"), MaxTemplateLayerSize)}) + _, _, err := New(nil, true).Pull(context.Background(), reg.host()+"/gameplane/overtotal", "1.0.0") + if err == nil || !strings.Contains(err.Error(), "bundle layers exceed") { + t.Fatalf("Pull err = %v, want a bundle total error", err) + } +} + +func TestPull_OtherArtifactTypeReadsItsOwnFiles(t *testing.T) { + // The module per-title caps must not skip theme package files. + reg := newFakeRegistry(t) + data := map[string][]byte{"theme.yaml": []byte("name: x"), "theme.css": []byte(":root{}")} + pushDeclared(t, reg, "gameplane/theme", "application/vnd.example.theme", []ocispec.Descriptor{ + titled("theme.yaml", "text/yaml", 0), + titled("theme.css", "text/css", 0), + }, data) + _, files, err := New(nil, true).WithArtifactType("application/vnd.example.theme"). + WithMaxLayerBytes(1024).WithMaxTotalBytes(1024). + Pull(context.Background(), reg.host()+"/gameplane/theme", "1.0.0") + if err != nil { + t.Fatalf("Pull: %v", err) + } + if string(files["theme.yaml"]) != "name: x" || string(files["theme.css"]) != ":root{}" { + t.Fatalf("theme files = %q / %q, want both read", files["theme.yaml"], files["theme.css"]) + } +} diff --git a/bundlefetch/oci/layer_caps_test.go b/bundlefetch/oci/layer_caps_test.go new file mode 100644 index 000000000..42dc3ff6a --- /dev/null +++ b/bundlefetch/oci/layer_caps_test.go @@ -0,0 +1,67 @@ +package oci + +import ( + "bytes" + "context" + "strings" + "testing" +) + +func TestPull_RejectsOversizedKnownLayer(t *testing.T) { + reg := newFakeRegistry(t) + repo := "gameplane/bigtemplate" + reg.pushBundle(repo, "1.0.0", map[string][]byte{ + LayerNameTemplate: bytes.Repeat([]byte("a"), MaxTemplateLayerSize+1), + }) + _, _, err := New(nil, true).Pull(context.Background(), reg.host()+"/"+repo, "1.0.0") + if err == nil || !strings.Contains(err.Error(), "over the") { + t.Fatalf("Pull err = %v, want a layer size error", err) + } +} + +func TestPull_RejectsOversizedMetadataLayer(t *testing.T) { + reg := newFakeRegistry(t) + repo := "gameplane/bigmeta" + reg.pushBundle(repo, "1.0.0", map[string][]byte{ + LayerNameMetadata: bytes.Repeat([]byte("a"), MaxMetadataLayerSize+1), + }) + _, _, err := New(nil, true).Pull(context.Background(), reg.host()+"/"+repo, "1.0.0") + if err == nil { + t.Fatal("Pull accepted an oversized module.yaml layer") + } +} + +func TestPull_SkipsUnknownLayerTitles(t *testing.T) { + reg := newFakeRegistry(t) + repo := "gameplane/unknown" + reg.pushBundle(repo, "1.0.0", map[string][]byte{ + LayerNameTemplate: []byte("apiVersion: x"), + "surprise.bin": bytes.Repeat([]byte("z"), 8<<20), + }) + _, files, err := New(nil, true).Pull(context.Background(), reg.host()+"/"+repo, "1.0.0") + if err != nil { + t.Fatalf("Pull: %v", err) + } + if _, ok := files["surprise.bin"]; ok || len(files) != 1 { + t.Fatalf("unknown layer was read: %d files", len(files)) + } +} + +func TestLayerSizeLimit(t *testing.T) { + for title, want := range map[string]int64{ + LayerNameMetadata: MaxMetadataLayerSize, + LayerNameTemplate: MaxTemplateLayerSize, + LayerNameReadme: MaxReadmeLayerSize, + LayerNameIcon: MaxIconLayerSize, + } { + if got, ok := layerSizeLimit(title); !ok || got != want { + t.Errorf("layerSizeLimit(%q) = %d, %v; want %d", title, got, ok, want) + } + } + if _, ok := layerSizeLimit("other"); ok { + t.Error("unknown title reported as known") + } + if MaxBundleSize < MaxLocaleTotalSize+MaxTemplateLayerSize { + t.Error("MaxBundleSize below the locale budget plus the template cap") + } +} diff --git a/bundlefetch/specs.md b/bundlefetch/specs.md index 27f9f96c6..59f98ca7a 100644 --- a/bundlefetch/specs.md +++ b/bundlefetch/specs.md @@ -10,7 +10,7 @@ The shared code that gets a bundle (a module or a theme) from where it lives and ## Responsibilities -1. `oci`: list the semver tags of a repository and pull an artifact. Every byte returned is checked against a digest (the manifest against the returned digest, each layer against the digest the manifest lists), so a signature check on the returned digest covers all returned content. Locale layers (`locales/.json`) are size-capped per file (`MaxLocaleLayerSize`) and per bundle (`MaxLocaleTotalSize`); a layer over a bound is not read and is recorded with the `OversizedLocale` marker so the caller can report the language. +1. `oci`: list the semver tags of a repository and pull an artifact. Every byte returned is checked against a digest (the manifest against the returned digest, each layer against the digest the manifest lists), so a signature check on the returned digest covers all returned content. Locale layers (`locales/.json`) are size-capped per file (`MaxLocaleLayerSize`) and per bundle (`MaxLocaleTotalSize`); a layer over a bound is not read and is recorded with the `OversizedLocale` marker so the caller can report the language. For module bundles (the default artifact type) only the known files are read (`module.yaml`, `template.yaml`, `README.md`, `icon.png`, plus locales), each under its own cap, and all layers together under `MaxBundleSize`; a known layer over its cap fails the pull before any byte is fetched. Other artifact types (theme packages) are bounded by `WithMaxLayerBytes` and `WithMaxTotalBytes`. A negative declared size always fails. 2. `verify`: a `Verifier` that checks the cosign signature of `ref@digest` under a keyed policy (`NewKeyed`: a PEM public key, optional Rekor inclusion) or a keyless one (`NewKeyless`: Fulcio issuer and identity, trust material from the Sigstore TUF root). `Nop` accepts everything and stands for "no policy". Keys and registry credentials are resolved by the caller and passed in. 3. `source`: fetch the raw files of a bundle source and return them as a filesystem (`Loader`) or a map of file name to bytes, never as CRD types. Git (`GitLoader`, `GitClone`, `CheckGitURL`), HTTP(S) archive (`ArchiveLoader`, `ExtractArchive`, `CheckHTTPURL`), local directory (`LocalLoader`), directory scanning (`FindDirs`, `ReadDir`, `ReadLocaleFiles`, `ContentDigest`, `DigestFiles`, `Allowed`) and OCI listing (`OCIClient`, `OCIRef`, `ListVersions`, `SortVersionsDesc`, `PullFiles`). @@ -32,7 +32,7 @@ The shared code that gets a bundle (a module or a theme) from where it lives and ## netguard at dial time -Every outbound dial goes through `netguard` with the permissive `IsAllowed` policy: the OCI client's HTTP transport, the git HTTPS transport (plus a host pre-flight for ssh), and the archive download client. Cloud-metadata, link-local and multicast addresses are refused at dial time, so a DNS name that rebinds to one is caught too; loopback and private registries stay reachable. +Every outbound dial goes through `netguard` with the permissive `IsAllowed` policy: the OCI client's HTTP transport, the cosign signature fetches in `verify` (registry and token realm), the git HTTPS transport (plus a host pre-flight for ssh), and the archive download client. Cloud-metadata, link-local and multicast addresses are refused at dial time, so a DNS name that rebinds to one is caught too; loopback and private registries stay reachable. ## Non-goals / boundaries diff --git a/bundlefetch/verify/verify.go b/bundlefetch/verify/verify.go index e3930e3f6..bef9ac425 100644 --- a/bundlefetch/verify/verify.go +++ b/bundlefetch/verify/verify.go @@ -13,7 +13,9 @@ import ( "errors" "fmt" "log/slog" + "net/http" "os" + "time" "github.com/go-logr/logr" "github.com/google/go-containerregistry/pkg/authn" @@ -24,6 +26,8 @@ import ( cosignsig "github.com/sigstore/cosign/v3/pkg/signature" "github.com/sigstore/sigstore-go/pkg/root" sgtuf "github.com/sigstore/sigstore-go/pkg/tuf" + + "github.com/GameplanePanel/gameplane/netguard" ) // Verifier checks that the OCI artifact at ref@digest carries a valid cosign @@ -61,6 +65,13 @@ func (cv *cosignVerifier) Verify(ctx context.Context, ref, digest string) error return nil } +// guardedTransport is shared by every signature fetch: registry and token-realm +// dials go through the same netguard guard as oci.Client, so a hostile registry +// cannot aim the verifier at metadata or link-local addresses. +var guardedTransport http.RoundTripper = &http.Transport{ + DialContext: netguard.Dialer(30*time.Second, netguard.IsAllowed).DialContext, +} + func baseCheckOpts(ctx context.Context, auth authn.Authenticator) *cosign.CheckOpts { return &cosign.CheckOpts{ ClaimVerifier: cosign.SimpleClaimVerifier, @@ -68,6 +79,7 @@ func baseCheckOpts(ctx context.Context, auth authn.Authenticator) *cosign.CheckO ociremote.WithRemoteOptions( ggcrremote.WithAuth(auth), ggcrremote.WithContext(ctx), + ggcrremote.WithTransport(guardedTransport), ), }, } diff --git a/bundlefetch/verify/verify_transport_test.go b/bundlefetch/verify/verify_transport_test.go new file mode 100644 index 000000000..59c9c38c2 --- /dev/null +++ b/bundlefetch/verify/verify_transport_test.go @@ -0,0 +1,30 @@ +package verify + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/GameplanePanel/gameplane/netguard" + "github.com/google/go-containerregistry/pkg/authn" +) + +// TestKeyedVerify_SignatureFetchIsNetguarded proves signature fetches use the +// guarded transport: a registry at a metadata address must be refused at dial time. +func TestKeyedVerify_SignatureFetchIsNetguarded(t *testing.T) { + v, err := newKeyed(context.Background(), testPubPEM(t), authn.Anonymous, false, false) + if err != nil { + t.Fatalf("newKeyed: %v", err) + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + err = v.Verify(ctx, "169.254.169.254/x/y", "sha256:"+strings.Repeat("0", 64)) + if err == nil { + t.Fatal("expected an error for a metadata-address registry") + } + if !errors.Is(err, netguard.ErrBlockedAddr) && !strings.Contains(err.Error(), netguard.ErrBlockedAddr.Error()) { + t.Fatalf("expected netguard block error, got: %v", err) + } +} diff --git a/changelog/unreleased/1126-security-bug-audit.md b/changelog/unreleased/1126-security-bug-audit.md new file mode 100644 index 000000000..a5f83a392 --- /dev/null +++ b/changelog/unreleased/1126-security-bug-audit.md @@ -0,0 +1,3 @@ +# Breaking: security and bug fixes from the November code audit + +The API no longer lets a user with servers:write delete another person's server through a forged ownerReference, keys login throttling on the IPv6 /64 and answers 503 instead of stalling when too many sign-ins queue, refuses readiness probes that arrive through a proxy, stops writing audit rows for unknown routes, and no longer turns off every sign-in method when an SSO role mapping is reset before any auth settings were saved. The operator no longer adopts a `-rcon` Secret it did not create (delete or rename such a Secret so a new password is generated), uses the RCON or admin password a user typed into the server settings (Farming Simulator 25, Left 4 Dead 2, Squad, The Isle) instead of silently replacing it, backs up servers with long names, caps module layer sizes and checks signatures through the SSRF guard. Dashboard file uploads now follow `files.maxUploadSize`, leaving the Files tab saves pending edits, archive restores refuse corrupted or crafted tar.gz files, SFTP no longer empties an existing file that a client opens without write or truncate flags, Minecraft transfer joins wake sleeping servers, and the FiveM, Farming Simulator 25 and Euro Truck Simulator 2 images install and start their server. [PR #1126](https://github.com/GameplanePanel/Gameplane/pull/1126) diff --git a/charts/gameplane/templates/ingress.yaml b/charts/gameplane/templates/ingress.yaml index c1b680670..ccea91e4a 100644 --- a/charts/gameplane/templates/ingress.yaml +++ b/charts/gameplane/templates/ingress.yaml @@ -28,6 +28,39 @@ spec: - hosts: [{{ .Values.ingress.host }}] secretName: gameplane-tls {{- end }} +--- +# Dashboard file uploads send one whole file as the PUT body of +# /servers//files/stream. This Ingress carries only that route so the +# body-size limit can follow files.maxUploadSize without raising it for every +# other (including unauthenticated) route. ingress-nginx merges it into the +# same server as the Ingress above; the regex path needs use-regex, which +# ingress-nginx applies to every path of this host (plain prefixes keep +# matching). +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: gameplane-files-stream + namespace: {{ .Release.Namespace }} + labels: {{- include "gameplane.labels" . | nindent 4 }} + annotations: + {{- toYaml (merge (dict "nginx.ingress.kubernetes.io/proxy-body-size" (include "gameplane.quantityBytes" ((.Values.files | default dict).maxUploadSize | default "20Gi")) "nginx.ingress.kubernetes.io/proxy-request-buffering" "off" "nginx.ingress.kubernetes.io/use-regex" "true") (omit .Values.ingress.annotations "nginx.ingress.kubernetes.io/proxy-body-size")) | nindent 4 }} +spec: + ingressClassName: {{ .Values.ingress.className }} + rules: + - host: {{ .Values.ingress.host }} + http: + paths: + - path: /servers/[^/]+/files/stream + pathType: ImplementationSpecific + backend: + service: + name: {{ if .Values.web.enabled }}gameplane-web{{ else }}gameplane-api{{ end }} + port: { name: http } + {{- if .Values.ingress.tls }} + tls: + - hosts: [{{ .Values.ingress.host }}] + secretName: gameplane-tls + {{- end }} {{- /* dig: values reused from a release before shareLinks existed lack the key. */}} {{- if dig "shareLinks" "disableAccessLog" true .Values.ingress }} --- diff --git a/charts/gameplane/templates/web.yaml b/charts/gameplane/templates/web.yaml index 736fd7136..2da98334b 100644 --- a/charts/gameplane/templates/web.yaml +++ b/charts/gameplane/templates/web.yaml @@ -39,6 +39,9 @@ spec: # The in-cluster API service nginx proxies non-HTML requests to. - name: API_UPSTREAM value: {{ printf "http://gameplane-api.%s.svc.cluster.local" .Release.Namespace | quote }} + # Dashboard file upload limit; follows files.maxUploadSize. + - name: FILES_MAX_UPLOAD_BYTES + value: {{ include "gameplane.quantityBytes" ((.Values.files | default dict).maxUploadSize | default "20Gi") | quote }} ports: - { name: http, containerPort: 8080 } livenessProbe: { httpGet: { path: /nginx-health, port: http }, initialDelaySeconds: 5 } diff --git a/containers/games/euro-truck-simulator-2/Dockerfile b/containers/games/euro-truck-simulator-2/Dockerfile index 650472958..521f6ebbb 100644 --- a/containers/games/euro-truck-simulator-2/Dockerfile +++ b/containers/games/euro-truck-simulator-2/Dockerfile @@ -1,49 +1,31 @@ -FROM debian:bookworm-slim +# Gameplane game server image for Euro Truck Simulator 2 (dedicated server). +# +# Builds on the shared SteamCMD base (containers/common/steamcmd/). The server +# (Steam app 1948160, anonymous login) is installed at container start by +# steam-install.sh into GP_DATA_DIR (set by the template; the GameServer's persistent +# volume). No game files are baked into the image. + +# CI passes: --build-arg STEAMCMD_BASE_IMAGE=ghcr.io/gameplanepanel/gameplane/common-steamcmd@sha256:... +ARG STEAMCMD_BASE_IMAGE=gameplane-steamcmd-base:latest +FROM ${STEAMCMD_BASE_IMAGE} LABEL org.opencontainers.image.title="Gameplane Euro Truck Simulator 2 Dedicated Server" \ org.opencontainers.image.description="Dedicated server container for Euro Truck Simulator 2 with diagnostic idle support for missing logon tokens" \ org.opencontainers.image.authors="Gameplane Maintainers" \ org.opencontainers.image.source="https://github.com/GameplanePanel/Gameplane" -ENV DEBIAN_FRONTEND=noninteractive - -RUN dpkg --add-architecture i386 && \ - apt-get update && \ - apt-get install -y --no-install-recommends \ - bash=5.2.15-2+b13 \ - curl=7.88.1-10+deb12u15 \ - ca-certificates=20250419~deb12u2 \ - tini=0.19.0-1+b3 \ - procps=2:4.0.2-3 \ - lib32gcc-s1=12.2.0-14+deb12u1 \ - libstdc++6=12.2.0-14+deb12u1 \ - libstdc++6:i386=12.2.0-14+deb12u1 \ - locales=2.36-9+deb12u14 && \ - sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen && \ - locale-gen && \ - apt-get clean && \ +USER root +RUN apt-get update && \ + apt-get install -y --no-install-recommends tini=0.19.0-6 && \ rm -rf /var/lib/apt/lists/* +USER gameserver:gameserver -# Create gameplane runtime user with fixed UID/GID 1000 -RUN groupadd -g 1000 gameplane && \ - useradd -u 1000 -g gameplane -m -s /bin/bash gameplane - -# Prepare directories -RUN mkdir -p /serverdata /home/gameplane/.local/share/Euro\ Truck\ Simulator\ 2 && \ - ln -s /home/gameplane /home/steam && \ - chown -R gameplane:gameplane /serverdata /home/gameplane - -COPY --chown=gameplane:gameplane entrypoint.sh /entrypoint.sh -RUN chmod +x /entrypoint.sh +COPY --chmod=0755 entrypoint.sh /entrypoint.sh -USER 1000:1000 -WORKDIR /serverdata -ENV HOME=/home/gameplane \ - USER=gameplane \ - LANG=en_US.UTF-8 \ - GAME_PORT=27015 \ +WORKDIR /data +ENV GAME_PORT=27015 \ QUERY_PORT=27016 EXPOSE 27015/udp 27016/udp -ENTRYPOINT ["/usr/bin/tini", "--", "/entrypoint.sh"] +ENTRYPOINT ["/usr/bin/tini", "-g", "--", "/entrypoint.sh"] diff --git a/containers/games/euro-truck-simulator-2/entrypoint.sh b/containers/games/euro-truck-simulator-2/entrypoint.sh index 8a8e8f3ed..2a1bd1cf5 100755 --- a/containers/games/euro-truck-simulator-2/entrypoint.sh +++ b/containers/games/euro-truck-simulator-2/entrypoint.sh @@ -28,7 +28,7 @@ if [ -z "$LOGON_TOKEN" ]; then echo "Step-by-step instructions to obtain and configure your logon token:" echo "1. Visit the Steam Game Server Account Management page:" echo " https://steamcommunity.com/dev/managegameservers" - echo "2. Enter App ID '1948400' (Euro Truck Simulator 2 Dedicated Server)." + echo "2. Enter App ID '227300' (Euro Truck Simulator 2)." echo "3. Enter a memo/label for your server and click 'Create'." echo "4. Copy the generated Login Token." echo "5. Configure the token in your GameServer specification:" @@ -41,15 +41,59 @@ if [ -z "$LOGON_TOKEN" ]; then echo "Update your manifest and restart the server once configured." echo "========================================================================" + # Startup-probe marker: lets the probe accept this idle (never Ready). + touch /tmp/gp-diagnostic-idle while true; do sleep 3600 & wait $! done fi -SERVER_BIN="/serverdata/bin/linux_x64/eurotrucks2_server" -CONFIG_DIR="/home/gameplane/.local/share/Euro Truck Simulator 2" -mkdir -p "$CONFIG_DIR" +# Persistent volume: the GameTemplate mounts the PVC at /data (GP_DATA_DIR); +# older templates mount it at the default below. +DATA="${GP_DATA_DIR:-/home/steam/.local/share/Euro Truck Simulator 2}" +SERVER_BIN="${DATA}/bin/linux_x64/eurotrucks2_server" + +# Install (or update) the dedicated server into the volume. +# SteamCMD keeps its state under $HOME; fall back to a writable directory when +# the template overrides HOME to a path this image does not have. +if ! mkdir -p "$HOME" 2>/dev/null || [ ! -w "$HOME" ]; then + export HOME=/tmp/gp-home + mkdir -p "$HOME" +fi + +# ETS2 Dedicated Server (free tool, anonymous login). +STEAM_APPID="1948160" \ +STEAM_INSTALL_DIR="$DATA" \ +STEAM_SKIP_IF_INSTALLED="${STEAM_SKIP_IF_INSTALLED:-true}" \ +STEAM_SENTINEL_FILE="$SERVER_BIN" \ + steam-install.sh + +if [ ! -f "$SERVER_BIN" ]; then + echo "[gameplane-ets2] ERROR: server binary missing after install: $SERVER_BIN" >&2 + exit 1 +fi + +# Keep the profile (server_config.sii, logs, packages) on the volume: the +# game reads it from ~/.local/share/Euro Truck Simulator 2. +PROFILE_DIR="${DATA}/profile" +# Volumes from older templates keep the profile at the volume root: keep +# using it there so an existing server_config.sii is not ignored. +if [ -f "${DATA}/server_config.sii" ] && [ ! -f "${PROFILE_DIR}/server_config.sii" ]; then + PROFILE_DIR="$DATA" +fi +CONFIG_DIR="${HOME}/.local/share/Euro Truck Simulator 2" +mkdir -p "$PROFILE_DIR" "$(dirname "$CONFIG_DIR")" +case "$(realpath -m "$DATA")/" in + "$(realpath -m "$CONFIG_DIR")"/*) + # The volume is the profile folder itself (or inside it): never + # replace it with a link. + PROFILE_DIR="$CONFIG_DIR" ;; +esac +if [ "$PROFILE_DIR" != "$CONFIG_DIR" ] && [ ! -L "$CONFIG_DIR" ]; then + rm -rf "$CONFIG_DIR" + ln -s "$PROFILE_DIR" "$CONFIG_DIR" +fi # Configure server_config.sii if token is available if [ -f "$CONFIG_DIR/server_config.sii" ]; then @@ -58,15 +102,7 @@ fi echo "[gameplane-ets2] Starting Euro Truck Simulator 2 dedicated server..." -if [ -f "$SERVER_BIN" ]; then - "$SERVER_BIN" -server "$@" & - PID_GAME=$! - wait "$PID_GAME" 2>/dev/null || true -else - echo "[gameplane-ets2] Server binary not yet installed at $SERVER_BIN." - echo "[gameplane-ets2] Entering diagnostic wait mode..." - while true; do - sleep 60 & - wait $! - done -fi +cd "$DATA/bin/linux_x64" +"$SERVER_BIN" -server "$@" & +PID_GAME=$! +wait "$PID_GAME" 2>/dev/null || true diff --git a/containers/games/farming-simulator-25/entrypoint.sh b/containers/games/farming-simulator-25/entrypoint.sh index e2d3082f7..c93b1c2af 100755 --- a/containers/games/farming-simulator-25/entrypoint.sh +++ b/containers/games/farming-simulator-25/entrypoint.sh @@ -26,6 +26,11 @@ term_handler() { trap term_handler SIGTERM SIGINT +# Persistent volume: the GameTemplate mounts the PVC at +# "/data/My Games/FarmingSimulator2025". The user uploads the server files +# (a licensed Windows install) into this volume. +DATA="${GP_DATA_DIR:-/data/My Games/FarmingSimulator2025}" + echo "[gameplane-fs25] Initializing headless Wine environment..." # Initialize Wine prefix if needed @@ -48,31 +53,28 @@ for i in $(seq 1 10); do done # Look for GIANTS dedicated server or web management portal -DEDICATED_SERVER_EXE="/serverdata/FarmingSimulator2025.exe" -WEB_SERVER_EXE="/serverdata/dedicatedServer.exe" +DEDICATED_SERVER_EXE="${DATA}/FarmingSimulator2025.exe" +WEB_SERVER_EXE="${DATA}/dedicatedServer.exe" -# If neither executable is found, provide diagnostic instructions +# If neither executable is found, there is nothing to run: log how to fix it +# and exit non-zero so the failure surfaces instead of idling forever. if [ ! -f "$DEDICATED_SERVER_EXE" ] && [ ! -f "$WEB_SERVER_EXE" ]; then - echo "========================================================================" - echo "DIAGNOSTIC: Farming Simulator 25 server files not detected in /serverdata" - echo "The dedicated server requires the official FS25 server files to run." - echo "" - echo "Step-by-step instructions:" - echo "1. Install or copy the Farming Simulator 25 Dedicated Server files into" - echo " the persistent volume mounted at /serverdata." - echo "2. Ensure the directory contains FarmingSimulator2025.exe and" - echo " dedicatedServer.exe." - echo "3. Configure your server settings in dedicatedServer.xml." - echo "" - echo "Entering graceful idle mode. The server will not crash-loop." - echo "========================================================================" - - while true; do - sleep 3600 & - wait $! - done + echo "========================================================================" >&2 + echo "ERROR: Farming Simulator 25 server files not found in ${DATA}" >&2 + echo "The dedicated server requires the official FS25 server files, which" >&2 + echo "Gameplane cannot download for you." >&2 + echo "" >&2 + echo "1. Upload your licensed Farming Simulator 25 server install" >&2 + echo " (FarmingSimulator2025.exe, dedicatedServer.exe and the game data)" >&2 + echo " to the server's volume with the Files tab or SFTP." >&2 + echo "2. Configure your server settings in dedicatedServer.xml." >&2 + echo "3. Start the server again." >&2 + echo "========================================================================" >&2 + exit 1 fi +cd "$DATA" + # FR-012: Start web management portal alongside the dedicated server if [ -f "$WEB_SERVER_EXE" ]; then echo "[gameplane-fs25] Starting GIANTS web management portal on port ${WEB_PORT:-8080}..." diff --git a/containers/games/fivem/Dockerfile b/containers/games/fivem/Dockerfile index 18eef95e9..820852a24 100644 --- a/containers/games/fivem/Dockerfile +++ b/containers/games/fivem/Dockerfile @@ -25,8 +25,8 @@ RUN addgroup -g 1000 gameplane && \ adduser -u 1000 -G gameplane -h /home/gameplane -s /bin/bash -D gameplane # Prepare directories -RUN mkdir -p /opt/cfx-server /server-data && \ - chown -R gameplane:gameplane /opt/cfx-server /server-data /home/gameplane +RUN mkdir -p /server-data && \ + chown -R gameplane:gameplane /server-data /home/gameplane # Copy entrypoint script COPY --chown=gameplane:gameplane entrypoint.sh /entrypoint.sh diff --git a/containers/games/fivem/entrypoint.sh b/containers/games/fivem/entrypoint.sh index 7787baa10..0f14c4849 100755 --- a/containers/games/fivem/entrypoint.sh +++ b/containers/games/fivem/entrypoint.sh @@ -22,6 +22,50 @@ term_handler() { trap term_handler SIGTERM SIGINT +# Persistent volume: the GameTemplate mounts the PVC at /server-data. +DATA="${GP_DATA_DIR:-/server-data}" + +# Pinned FXServer artifact (recommended build 38435). Override FXSERVER_URL and +# FXSERVER_SHA256 together to move to another build; the sha256 is always verified. +FXSERVER_URL="${FXSERVER_URL:-https://runtime.fivem.net/artifacts/fivem/build_proot_linux/master/38435-5c3065c261fb3ba82032fee6803f247198fec221/fx.tar.xz}" +FXSERVER_SHA256="${FXSERVER_SHA256:-1b58507f68086ca3578c187f31e7b4a2259b7192d76b0c80cfc1af682fdf2be9}" +FXSERVER_DIR="${DATA}/fxserver" + +# install_fxserver downloads the pinned artifact into the volume, verifies its +# sha256 and extracts it. Failures are fatal so the pod surfaces them. +install_fxserver() { + local archive="${DATA}/.fx.tar.xz.part" + echo "[gameplane-fivem] Downloading FXServer artifact into ${FXSERVER_DIR}..." + local staging="${DATA}/.fxserver.tmp" + mkdir -p "$DATA" + rm -rf "$staging" + mkdir -p "$staging" + if ! curl -fsSL --retry 3 --retry-delay 5 -o "$archive" "$FXSERVER_URL"; then + rm -f "$archive" + echo "[gameplane-fivem] ERROR: failed to download FXServer from $FXSERVER_URL" >&2 + exit 1 + fi + if ! echo "${FXSERVER_SHA256} ${archive}" | sha256sum -c - >/dev/null 2>&1; then + rm -f "$archive" + echo "[gameplane-fivem] ERROR: FXServer artifact sha256 mismatch (expected ${FXSERVER_SHA256})" >&2 + exit 1 + fi + if ! tar -xJf "$archive" -C "$staging"; then + rm -rf "$archive" "$staging" + echo "[gameplane-fivem] ERROR: failed to extract FXServer artifact" >&2 + exit 1 + fi + rm -f "$archive" + # Publish only a complete extract, so a crash mid-extract never leaves a + # truncated tree that looks installed. + rm -rf "$FXSERVER_DIR" + if ! mv "$staging" "$FXSERVER_DIR"; then + rm -rf "$staging" + echo "[gameplane-fivem] ERROR: failed to move FXServer into ${FXSERVER_DIR}" >&2 + exit 1 + fi +} + # Resolve CFX license key from possible environment variables LICENSE_KEY="${CFX_LICENSE_KEY:-${SV_LICENSEKEY:-${LICENSE_KEY:-}}}" @@ -54,7 +98,7 @@ fi # FR-012: Supervise embedded MariaDB database if enabled if [ "${ENABLE_EMBEDDED_DB:-true}" = "true" ]; then - DB_DIR="/server-data/mysql" + DB_DIR="${DATA}/mysql" if [ ! -d "$DB_DIR" ]; then echo "[gameplane-fivem] Initializing embedded MariaDB in $DB_DIR..." mkdir -p "$DB_DIR" @@ -92,34 +136,26 @@ if [ "${ENABLE_EMBEDDED_DB:-true}" = "true" ]; then fi # Ensure txAdmin data directory exists -mkdir -p /server-data/txData +mkdir -p "${DATA}/txData" + +# Install FXServer into the mounted volume when missing. +if [ ! -f "${FXSERVER_DIR}/run.sh" ]; then + install_fxserver +fi +if [ ! -f "${FXSERVER_DIR}/run.sh" ]; then + echo "[gameplane-fivem] ERROR: FXServer binary not found at ${FXSERVER_DIR}/run.sh after install" >&2 + exit 1 +fi echo "[gameplane-fivem] Starting FiveM dedicated server with txAdmin on port ${TXADMIN_PORT:-40120}..." -# If fxserver binaries are mounted or installed at /opt/cfx-server -if [ -f "/opt/cfx-server/run.sh" ]; then - /opt/cfx-server/run.sh \ - +set serverProfile default \ - +set txAdminPort "${TXADMIN_PORT:-40120}" \ - +set sv_licenseKey "$LICENSE_KEY" \ - +set net_tcpConnLimit 64 \ - "$@" & - PID_FX=$! -elif [ -f "/opt/cfx-server/FXServer" ]; then - /opt/cfx-server/FXServer \ - +set serverProfile default \ - +set txAdminPort "${TXADMIN_PORT:-40120}" \ - +set sv_licenseKey "$LICENSE_KEY" \ - "$@" & - PID_FX=$! -else - echo "[gameplane-fivem] Note: fxserver binary not found at /opt/cfx-server/run.sh." - echo "[gameplane-fivem] Running in managed txAdmin supervisor mode..." - # Keep supervisor running and monitoring - while true; do - sleep 60 & - wait $! - done -fi +bash "${FXSERVER_DIR}/run.sh" \ + +set serverProfile default \ + +set txDataPath "${DATA}/txData" \ + +set txAdminPort "${TXADMIN_PORT:-40120}" \ + +set sv_licenseKey "$LICENSE_KEY" \ + +set net_tcpConnLimit 64 \ + "$@" & +PID_FX=$! wait "$PID_FX" 2>/dev/null || true diff --git a/docs/install.md b/docs/install.md index 487df9408..afda771a5 100644 --- a/docs/install.md +++ b/docs/install.md @@ -325,7 +325,11 @@ Top-level knobs (see `values.yaml` for the full list): fit; the agent defaults to 256 MiB per mod file. When upgrading with reused values or custom annotations, replace an existing `64m` limit with `512m` to permit those uploads. Other ingress controllers need - their equivalent body-size setting. + their equivalent body-size setting. Dashboard file uploads + (`/servers//files/stream`) follow `files.maxUploadSize` instead: the + dashboard nginx and a separate `gameplane-files-stream` Ingress raise the + limit for that route only. Other ingress controllers need an equivalent + per-route body-size setting. - `ingress.shareLinks.disableAccessLog` — default `true`. Share links carry their token in the URL path (`/share/`, `/shares/`), so an ingress access log would hold working tokens. The chart routes those two diff --git a/docs/module-authoring.md b/docs/module-authoring.md index e27b0e0eb..b35420cab 100644 --- a/docs/module-authoring.md +++ b/docs/module-authoring.md @@ -1122,6 +1122,13 @@ game container via `passwordEnv`, and mounts the same value for the agent — the dashboard's console tab (and every RCON-backed capability) then works automatically. +If the template's `configSchema` also has an env field that exports the +same variable as `passwordEnv` (for example a `RCON_PASSWORD` password +field), a value the user types there becomes the server's RCON password: +the operator stores it in the `-rcon` Secret, so the game and the +agent still agree. The field's `default` is never used for this, and +clearing the field switches back to a freshly generated password. + #### Password source precedence When the game image manages its own RCON password file (e.g., Factorio's diff --git a/docs/security.md b/docs/security.md index ec4b07b28..180c69c13 100644 --- a/docs/security.md +++ b/docs/security.md @@ -138,7 +138,7 @@ same way a dashboard password reset does. ### Client IP extraction from forwarded headers The API records a client IP for every request. Login rate limiting -(per-IP caps) and audit records key on it. The IP comes from the TCP peer +(per-IP caps) and audit records key on it. The per-IP limiter buckets key on the IPv6 /64 prefix (`auth.LimiterSourceKey`) while IPv4 stays per address; audit records keep the full address. The IP comes from the TCP peer and, only when that peer is a trusted proxy, from the `X-Forwarded-For` header. Trusted proxies are set by `api.trustedProxies` (default: loopback and private ranges `127.0.0.0/8`, `10.0.0.0/8`, `172.16.0.0/12`, @@ -210,8 +210,8 @@ api: trustedProxies: "203.0.113.1/32" ``` -The client IP is used for login rate limiting (per-IP caps) and audit -records, so misconfiguring this can either record a proxy instead of the +The client IP is used for login rate limiting (per-IP caps, grouped by IPv6 /64) and audit +records (full address), so misconfiguring this can either record a proxy instead of the client in audit logs or group legitimate users behind one proxy address in a single rate-limit bucket. @@ -296,7 +296,11 @@ transfer, and collaborator list edits. Only the server's owner or an admin (a role holding `*` in the server's cluster and namespace) can perform owner-only operations. The namespace `servers:write` permission alone does not grant them, and a server with no recorded owner (for example one created with kubectl or -GitOps) can be transferred, wiped or deleted only by an admin. The transfer, +GitOps) can be transferred, wiped or deleted only by an admin. Generic POST/PUT never take +`metadata.ownerReferences` or `metadata.finalizers` from the client (POST clears +them, PUT keeps the stored values), so the owner-only delete rule cannot be +bypassed by planting a dangling ownerReference that makes the garbage collector +delete the object, or a finalizer that blocks its deletion. The transfer, collaborator-edit and wipe patches are conditional on the server's `resourceVersion` as read by the ownership check: if the server changes in between (for example its ownership is transferred), the API re-reads it and diff --git a/gameproto/classifier.go b/gameproto/classifier.go index 7329d385f..5fe2ce4e7 100644 --- a/gameproto/classifier.go +++ b/gameproto/classifier.go @@ -95,7 +95,8 @@ type MinecraftDetail struct { ProtocolVersion int32 // NextState is the requested next protocol state after handshake. - // 1 = Status (server-list ping), 2 = Login (player join attempt). + // 1 = Status (server-list ping), 2 = Login (player join attempt), + // 3 = Transfer (transferred player join, 1.20.5+). NextState int32 // ServerAddr is the server address (host:port) the client sent in the handshake. diff --git a/gameproto/minecraft.go b/gameproto/minecraft.go index 6f1909639..14494758f 100644 --- a/gameproto/minecraft.go +++ b/gameproto/minecraft.go @@ -23,7 +23,7 @@ type minecraftClassifyResult struct { ProtocolVersion int32 // NextState is the requested next protocol state after handshake. - // 1 = Status, 2 = Login. + // 1 = Status, 2 = Login, 3 = Transfer (1.20.5+). NextState int32 // ServerAddr is the server address (host:port) the client sent in the handshake. @@ -95,7 +95,7 @@ func classifyMinecraftHandshake(br *bufio.Reader) (Kind, *minecraftClassifyResul } port := binary.BigEndian.Uint16(portBytes[:]) - // Read next state (VarInt): 1 = Status, 2 = Login. + // Read next state (VarInt): 1 = Status, 2 = Login, 3 = Transfer (1.20.5+). nextState, err := readMinecraftVarInt(frameReader) if err != nil { return Unknown, nil, fmt.Errorf("read next state: %w", err) @@ -111,7 +111,7 @@ func classifyMinecraftHandshake(br *bufio.Reader) (Kind, *minecraftClassifyResul switch nextState { case 1: // Status return Status, result, nil - case 2: // Login + case 2, 3: // Login, Transfer (1.20.5+): both continue into the login state return Join, result, nil default: return Unknown, result, nil diff --git a/gameproto/minecraft_test.go b/gameproto/minecraft_test.go index 833368ba4..dc8fc9dcc 100644 --- a/gameproto/minecraft_test.go +++ b/gameproto/minecraft_test.go @@ -870,3 +870,18 @@ func TestClassifyMinecraftErrorShape(t *testing.T) { t.Errorf("expected nil result alongside error, got %v", result) } } + +// TestClassifyMinecraftTransferIsJoin checks that next state 3 (Transfer, +// 1.20.5+) classifies as a join, like Login. +func TestClassifyMinecraftTransferIsJoin(t *testing.T) { + t.Parallel() + + data := buildMinecraftHandshake(766, "localhost", 25565, 3) + result, err := (&MinecraftClassifier{}).Classify(bufio.NewReader(bytes.NewReader(data))) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if result.Kind != Join { + t.Errorf("expected Join, got %v", result.Kind) + } +} diff --git a/gameproto/specs.md b/gameproto/specs.md index ab59f1c46..eb98da6b6 100644 --- a/gameproto/specs.md +++ b/gameproto/specs.md @@ -10,7 +10,7 @@ Shared wire-protocol parser for game server handshakes (Minecraft Java Edition a ## Responsibilities -1. Parse Minecraft Java Edition handshake frames (VarInt-framed packets) and classify them by next-state (Status vs. Login). +1. Parse Minecraft Java Edition handshake frames (VarInt-framed packets) and classify them by next-state (Status vs. Login or Transfer). 2. Parse Terraria connection frames and identify ConnectRequest messages as join attempts. 3. Preserve consumed bytes for replay to the real game pod, via a `Consumed` field that tracks exactly what was read, enabling lossless hand-off once the upstream connection is established. 4. Distinguish a genuine join from a server-list status ping or other probe without consuming more of the connection than necessary. @@ -172,7 +172,7 @@ type Detail interface { **Concrete Implementations:** -- **`MinecraftDetail`**: Holds ProtocolVersion (int32), NextState (int32: 1=Status, 2=Login), and ServerAddr (string). ProtocolName() returns "minecraft". +- **`MinecraftDetail`**: Holds ProtocolVersion (int32), NextState (int32: 1=Status, 2=Login, 3=Transfer; 2 and 3 classify as Join), and ServerAddr (string). ProtocolName() returns "minecraft". - **`TerrariaDetail`**: Holds Version (string from ConnectRequest). ProtocolName() returns "terraria". ### Stream Replay Contract @@ -294,12 +294,12 @@ To add a new game protocol (e.g., "factorio"): [VarInt] protocol_version [String] server_address (VarInt length + UTF-8 bytes) [UInt16 BE] server_port - [VarInt] next_state (1 = Status, 2 = Login) + [VarInt] next_state (1 = Status, 2 = Login, 3 = Transfer since 1.20.5; 2 and 3 classify as Join) ``` **Parsing:** Read the frame length (VarInt, 5 bytes max), reject if > 512 (minecraftMaxPacketSize), read the frame data, then parse packet fields inside. Strings are bounded at 32KB (Minecraft protocol limit). The packet ID must be 0x00; any other value is a parse error (`Classify` returns `nil, err`, matching the `Classifier` interface contract, not a non-nil Unknown result). -**Classification:** next_state == 2 → Join; next_state == 1 → Status; anything else → Unknown. +**Classification:** next_state == 2 or 3 (Transfer, 1.20.5+) → Join; next_state == 1 → Status; anything else → Unknown. ### Terraria diff --git a/gp-module/internal/packager/archive_allowlist_test.go b/gp-module/internal/packager/archive_allowlist_test.go new file mode 100644 index 000000000..5b657cf73 --- /dev/null +++ b/gp-module/internal/packager/archive_allowlist_test.go @@ -0,0 +1,70 @@ +package packager + +import ( + "os" + "path/filepath" + "slices" + "testing" +) + +// TestCreateArchiveFromDirLeavesOutNonStandardFiles checks that the .tar.gz +// export ships only the standard module files and locales, as the OCI push +// does: a dotfile with a secret, a notes file and an earlier bundle in the +// module directory are not archived. +func TestCreateArchiveFromDirLeavesOutNonStandardFiles(t *testing.T) { + t.Parallel() + dir := t.TempDir() + writeModuleBase(t, dir) + for name, body := range map[string]string{ + "icon.png": "png-bytes", + ".env": "REGISTRY_TOKEN=secret", + ".npmrc": "//registry/:_authToken=secret", + "notes.txt": "scratch", + "demo.tar.gz": "older bundle", + "module.yaml~": "editor backup", + } { + if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o600); err != nil { + t.Fatal(err) + } + } + writeLocale(t, dir, "fr.json", `{"a":1}`) + + data, _, err := CreateArchiveFromDir(dir, PackageLimits{}) + if err != nil { + t.Fatal(err) + } + got := archiveNames(t, data) + want := []string{"module.yaml", "template.yaml", "README.md", "icon.png", "locales/fr.json"} + if len(got) != len(want) { + t.Fatalf("entries = %v, want exactly %v", got, want) + } + for _, name := range want { + if !slices.Contains(got, name) { + t.Fatalf("entries = %v, missing %s", got, name) + } + } +} + +// TestCreateArchiveFromDirOutputInsideModuleDir checks that an --output file +// written inside the module directory is not nested into the next archive. +func TestCreateArchiveFromDirOutputInsideModuleDir(t *testing.T) { + t.Parallel() + dir := t.TempDir() + writeModuleBase(t, dir) + out := filepath.Join(dir, "demo.tar.gz") + if _, err := ExportArchiveToFile(dir, out, PackageLimits{}); err != nil { + t.Fatal(err) + } + if _, err := ExportArchiveToFile(dir, out, PackageLimits{}); err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(out) + if err != nil { + t.Fatal(err) + } + for _, name := range archiveNames(t, data) { + if name == "demo.tar.gz" { + t.Fatal("previous bundle nested into the new archive") + } + } +} diff --git a/gp-module/internal/packager/packager.go b/gp-module/internal/packager/packager.go index a13540f66..d7b2758f4 100644 --- a/gp-module/internal/packager/packager.go +++ b/gp-module/internal/packager/packager.go @@ -170,12 +170,25 @@ func CreateArchiveFromFiles(files map[string][]byte, limits PackageLimits) ([]by return buf.Bytes(), warnings, nil } +// standardModuleFiles is the top-level file set a module bundle carries. It +// matches the layers PushOCI pushes, so the .tar.gz export and the OCI push +// ship the same files. Anything else in the directory (dotfiles, editor +// backups, earlier bundles) is left out. +var standardModuleFiles = []string{"module.yaml", "template.yaml", "README.md", "icon.png"} + // CreateArchiveFromDir reads module files from a directory and compresses them into a .tar.gz archive. +// Only the standard module files and the locales are included, as in an OCI push. func CreateArchiveFromDir(dirPath string, limits PackageLimits) ([]byte, []PackageWarning, error) { - files, err := ReadModuleFiles(dirPath) + dirFiles, err := ReadModuleFiles(dirPath) if err != nil { return nil, nil, err } + files := make(map[string][]byte, len(standardModuleFiles)) + for _, name := range standardModuleFiles { + if data, ok := dirFiles[name]; ok { + files[name] = data + } + } // Translations travel in the archive at the same relative path an OCI // bundle uses as layer title: locales/.json (en.json is not shipped). locales, err := ReadLocaleFiles(dirPath) diff --git a/gp-module/specs.md b/gp-module/specs.md index 590b2a7fe..3f49092ec 100644 --- a/gp-module/specs.md +++ b/gp-module/specs.md @@ -10,7 +10,7 @@ 1. **Scaffolding (`init`)**: Interactive and non-interactive generation of schema-compliant module directories across `steamcmd`, `java`, and `generic` archetypes with DNS-1123 validation. 2. **Offline Validation (`validate`)**: Static offline checking of `module.yaml` metadata, CRD schemas, image digest pinning, canonical categories, port bounds/collisions, and configuration rules with exact source line-number diagnostics via `yaml.v3`. 3. **Dry-Run Preview (`preview`)**: Simulation of runtime server creation from `template.yaml`, evaluating dynamic memory limits (`autoFromMemoryLimit`) and environment variable precedence using native Kubernetes resource types. -4. **OCI Packaging (`package`)**: Asset size sanity checking (icon $\le$ 512 KiB, bundle $\le$ 1 MiB) and automated bundle export via ORAS or local `.tar.gz` archive. A `locales/.json` translation file becomes one extra OCI layer (media type `application/vnd.gameplane.module.locale.v1+json`, title `locales/.json`); the English reference `locales/en.json` is not shipped. The local `.tar.gz` export carries `locales/.json` at the same relative path (`en.json` excluded), so it also works as an HTTP or upload source. +4. **OCI Packaging (`package`)**: Asset size sanity checking (icon $\le$ 512 KiB, bundle $\le$ 1 MiB) and automated bundle export via ORAS or local `.tar.gz` archive. A `locales/.json` translation file becomes one extra OCI layer (media type `application/vnd.gameplane.module.locale.v1+json`, title `locales/.json`); the English reference `locales/en.json` is not shipped. The local `.tar.gz` export carries `locales/.json` at the same relative path (`en.json` excluded), so it also works as an HTTP or upload source. Like the OCI push, it ships only `module.yaml`, `template.yaml`, `README.md`, `icon.png` (when present) and the locales; other files in the module directory (dotfiles, notes, earlier bundles) are left out. 5. **Translations (`i18n extract`, `i18n stamp`, and `validate`)**: `gp-module i18n extract [MODULE_PATH] [--output ]` derives the translatable message ids from `module.yaml` and `template.yaml` (shared `i18n/modlocale` package, also used by the operator) and writes the English reference with translator descriptions to `locales/en.json`. `validate` checks every `locales/.json` against the derived ids and reports rule `locale-invalid` for bad tags, malformed files, unknown ids and placeholder or markup mismatches. Each id derived from `module.yaml` and `template.yaml` that fails `modlocale.ValidID` (for example a config key with a space) is reported as an `ERROR` with rule `locale-id-invalid`, whether or not a `locales/` directory exists. `gp-module i18n stamp [MODULE_PATH]` records a source hash (as in app packs) for translated entries that lack one in `locales/.review.json` (`tag → id → hash`), and moves any inline `sourceHash` out of `locales/.json`; when the English text later changes, `validate` reports a `WARN` with rule `locale-needs-review` (it does not fail validation). 6. **Theme packages (`theme`)**: `gp-module theme init|from-export|validate|preview|package` for spec 043 themes (colors plus a sanitized CSS overlay). Every rule is the shared `themepkg` module's, so the CLI accepts exactly what the panel accepts. See the `Theme packages` section below and [`docs/themes.md`](../docs/themes.md). diff --git a/operator/internal/controller/backup_controller.go b/operator/internal/controller/backup_controller.go index ffc29ae32..b2fc6a177 100644 --- a/operator/internal/controller/backup_controller.go +++ b/operator/internal/controller/backup_controller.go @@ -192,12 +192,18 @@ func (r *BackupReconciler) retrySnapshotScrape( ctx context.Context, b *gameplanev1alpha1.Backup, ) (ctrl.Result, error) { var job batchv1.Job - if err := r.Get(ctx, types.NamespacedName{Namespace: b.Namespace, Name: b.Name}, &job); err != nil { + if err := r.Get(ctx, backupJobKey(b), &job); err != nil { if !apierrors.IsNotFound(err) { return ctrl.Result{}, err } return r.failUnrestorable(ctx, b) } + // A Job at this name that another object controls (a Backup literally + // named like this one's shortened Job name) is not ours: mirroring it + // would record the other Backup's status and snapshot id here. + if owner := metav1.GetControllerOf(&job); owner != nil && owner.UID != b.UID { + return r.failUnrestorable(ctx, b) + } return r.mirrorJobStatus(ctx, b, &job) } @@ -322,7 +328,7 @@ func (r *BackupReconciler) reconcile(ctx context.Context, req ctrl.Request) (ctr // trying to acquire exclusive ownership first would deadlock their cleanup. if legacyBackupOwesUnquiesce(&b) && b.Spec.Strategy != "volume-snapshot" { var existing batchv1.Job - err := r.backupAPIReader().Get(ctx, client.ObjectKeyFromObject(&b), &existing) + err := r.backupAPIReader().Get(ctx, backupJobKey(&b), &existing) if err != nil && !apierrors.IsNotFound(err) { return ctrl.Result{}, err } @@ -986,7 +992,7 @@ func (r *BackupReconciler) readResticSummary(ctx context.Context, b *gameplanev1 } reader = &clientsetLogReader{cs: r.Clientset} } - rc, err := reader.BackupLogs(ctx, b.Namespace, b.Name) + rc, err := reader.BackupLogs(ctx, b.Namespace, backupJobName(b.Name)) if err != nil { return nil, fmt.Errorf("read restic logs: %w", err) } diff --git a/operator/internal/controller/backup_forget.go b/operator/internal/controller/backup_forget.go index bf3dc4b98..c39c204b7 100644 --- a/operator/internal/controller/backup_forget.go +++ b/operator/internal/controller/backup_forget.go @@ -222,12 +222,14 @@ func (r *BackupReconciler) runForgetJob(ctx context.Context, b *gameplanev1alpha deadline := forgetJobDeadlineSeconds job.Spec.BackoffLimit = &backoff job.Spec.ActiveDeadlineSeconds = &deadline - job.Labels = map[string]string{forgetBackupLabel: b.Name} + // Label values stop at 63 characters; backupJobName keeps short + // names as they are and hashes long ones. + job.Labels = map[string]string{forgetBackupLabel: backupJobName(b.Name)} // The pod label is what the chart's allow-backup-restore-egress // NetworkPolicy selects on; without it the pod cannot reach the repo. job.Spec.Template.Labels = map[string]string{ backupRestoreJobLabel: backupRestoreJobValue, - forgetBackupLabel: b.Name, + forgetBackupLabel: backupJobName(b.Name), } job.Spec.Template.Spec = r.buildForgetPodSpec(b) } @@ -285,12 +287,17 @@ func (r *BackupReconciler) clearBackupJob(ctx context.Context, b *gameplanev1alp return false, nil } var job batchv1.Job - if err := r.Get(ctx, types.NamespacedName{Namespace: b.Namespace, Name: b.Name}, &job); err != nil { + if err := r.Get(ctx, backupJobKey(b), &job); err != nil { if apierrors.IsNotFound(err) { return false, nil } return false, fmt.Errorf("get backup job %s: %w", b.Name, err) } + // A Backup literally named like another one's shortened Job name shares + // the key: never wait on or delete a Job another object controls. + if owner := metav1.GetControllerOf(&job); owner != nil && owner.UID != b.UID { + return false, nil + } if !job.DeletionTimestamp.IsZero() { return true, nil } @@ -414,6 +421,27 @@ func jobFailureMessage(job *batchv1.Job) string { return "no failure detail reported" } +// maxBackupJobNameLen is the longest Job name whose job-name pod label stays a +// valid label value. +const maxBackupJobNameLen = 63 + +// backupJobName names the copy Job of a Backup: the Backup name itself when it +// fits in a label value (so Jobs created before this cap are still found), else +// a truncated name plus a hash of the full name so two long names cannot collide. +func backupJobName(backupName string) string { + if len(backupName) <= maxBackupJobNameLen { + return backupName + } + sum := sha256.Sum256([]byte(backupName)) + prefix := strings.TrimRight(backupName[:maxBackupJobNameLen-9], "-.") + return fmt.Sprintf("%s-%x", prefix, sum[:4]) +} + +// backupJobKey is the object key of a Backup's copy Job. +func backupJobKey(b *gameplanev1alpha1.Backup) types.NamespacedName { + return types.NamespacedName{Namespace: b.Namespace, Name: backupJobName(b.Name)} +} + // forgetJobName names the forget Job for a Backup: "-forget", or, when // that would pass maxForgetJobNameLen, a truncated backup name plus a hash of // the full name so two long names cannot collide. diff --git a/operator/internal/controller/backup_forget_foreign_job_test.go b/operator/internal/controller/backup_forget_foreign_job_test.go new file mode 100644 index 000000000..f09ae0875 --- /dev/null +++ b/operator/internal/controller/backup_forget_foreign_job_test.go @@ -0,0 +1,65 @@ +package controller + +import ( + "context" + "strings" + "testing" + + batchv1 "k8s.io/api/batch/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + ctrl "sigs.k8s.io/controller-runtime" + + gameplanev1alpha1 "github.com/GameplanePanel/gameplane/operator/api/v1alpha1" +) + +// A Job at the Backup's copy-Job name that another Backup controls (a short +// name equal to a long name's shortened form) is never deleted or awaited. +func TestFinalizeSnapshot_LeavesForeignControlledBackupJob(t *testing.T) { + b := forgetBackup() + b.UID = "b1-uid" + b.Status.Phase = gameplanev1alpha1.BackupPhaseRunning + b.Status.SnapshotID = "" + foreign := &batchv1.Job{ + ObjectMeta: metav1.ObjectMeta{Name: "b1", Namespace: "ns", OwnerReferences: []metav1.OwnerReference{{ + APIVersion: gameplanev1alpha1.GroupVersion.String(), Kind: "Backup", Name: "other", + UID: "other-uid", Controller: ownerBoolPtr(true), + }}}, + Status: batchv1.JobStatus{Active: 1}, + } + r, _ := newForgetReconciler(t, b, forgetRepoSecret(), foreign) + + if _, err := r.Reconcile(context.Background(), forgetRequest()); err != nil { + t.Fatalf("reconcile: %v", err) + } + if _, ok := getJobNamed(t, r, "b1"); !ok { + t.Fatal("foreign-controlled backup job was deleted") + } +} + +// The forget Job's backup label stays within the 63-character label limit +// for a Backup name longer than that. +func TestRunForgetJob_LongBackupNameLabelFits(t *testing.T) { + b := forgetBackup() + b.Name = strings.Repeat("a", 80) + r, _ := newForgetReconciler(t, b, forgetRepoSecret()) + + req := ctrl.Request{NamespacedName: types.NamespacedName{Namespace: "ns", Name: b.Name}} + if _, err := r.Reconcile(context.Background(), req); err != nil { + t.Fatalf("reconcile: %v", err) + } + job, ok := getJobNamed(t, r, forgetJobName(b.Name)) + if !ok { + t.Fatal("forget job not created") + } + want := backupJobName(b.Name) + if len(want) > 63 { + t.Fatalf("label value %q longer than 63", want) + } + if got := job.Labels[forgetBackupLabel]; got != want { + t.Fatalf("job label = %q, want %q", got, want) + } + if got := job.Spec.Template.Labels[forgetBackupLabel]; got != want { + t.Fatalf("pod label = %q, want %q", got, want) + } +} diff --git a/operator/internal/controller/backup_guard.go b/operator/internal/controller/backup_guard.go index eebbbdf89..1ac963da7 100644 --- a/operator/internal/controller/backup_guard.go +++ b/operator/internal/controller/backup_guard.go @@ -451,7 +451,7 @@ func (r *BackupReconciler) backupWorkersLive(ctx context.Context, namespace stri job := &jobs.Items[i] owner := metav1.GetControllerOf(job) // Only the copy Job, never the repository forget Job. - if job.Name != id.Name || owner == nil || owner.Kind != "Backup" || owner.UID != id.UID { + if job.Name != backupJobName(id.Name) || owner == nil || owner.Kind != "Backup" || owner.UID != id.UID { continue } jobUIDs[job.UID] = true diff --git a/operator/internal/controller/backup_job_name_test.go b/operator/internal/controller/backup_job_name_test.go new file mode 100644 index 000000000..79a6c3f94 --- /dev/null +++ b/operator/internal/controller/backup_job_name_test.go @@ -0,0 +1,28 @@ +package controller + +import ( + "strings" + "testing" +) + +func TestBackupJobName(t *testing.T) { + short := strings.Repeat("a", 63) + if got := backupJobName(short); got != short { + t.Fatalf("63-char name changed: %q", got) + } + long := strings.Repeat("b", 40) + "-auto-20260101-000000-extra-suffix-long" + got := backupJobName(long) + if len(got) > 63 { + t.Fatalf("len = %d, want <= 63", len(got)) + } + if got != backupJobName(long) { + t.Fatal("not deterministic") + } + other := long + "x" + if backupJobName(other) == got { + t.Fatal("distinct long names collided") + } + if strings.HasSuffix(strings.SplitN(got, "-", 2)[0], ".") { + t.Fatalf("bad prefix %q", got) + } +} diff --git a/operator/internal/controller/backup_manifest.go b/operator/internal/controller/backup_manifest.go index 3879a7306..6f46ea430 100644 --- a/operator/internal/controller/backup_manifest.go +++ b/operator/internal/controller/backup_manifest.go @@ -23,7 +23,11 @@ func (r *BackupReconciler) captureWorker(ctx context.Context, b *gameplanev1alph if b.Spec.Strategy == "volume-snapshot" { worker = &snapshotv1.VolumeSnapshot{} } - if err := r.backupAPIReader().Get(ctx, client.ObjectKeyFromObject(b), worker); err != nil { + key := client.ObjectKeyFromObject(b) + if _, isJob := worker.(*batchv1.Job); isJob { + key = backupJobKey(b) + } + if err := r.backupAPIReader().Get(ctx, key, worker); err != nil { return nil, client.IgnoreNotFound(err) } if !metav1.IsControlledBy(worker, b) { diff --git a/operator/internal/controller/backup_preparation.go b/operator/internal/controller/backup_preparation.go index 15a8c257f..9bd0fb36c 100644 --- a/operator/internal/controller/backup_preparation.go +++ b/operator/internal/controller/backup_preparation.go @@ -257,7 +257,7 @@ func (r *BackupReconciler) backupSourceDrained(ctx context.Context, b *gameplane copyJobs := map[types.UID]bool{} for i := range jobs.Items { job := &jobs.Items[i] - if job.Name == b.Name && metav1.IsControlledBy(job, b) { + if job.Name == backupJobName(b.Name) && metav1.IsControlledBy(job, b) { copyJobs[job.UID] = true continue } diff --git a/operator/internal/controller/backup_scrape_foreign_job_test.go b/operator/internal/controller/backup_scrape_foreign_job_test.go new file mode 100644 index 000000000..22e31d241 --- /dev/null +++ b/operator/internal/controller/backup_scrape_foreign_job_test.go @@ -0,0 +1,41 @@ +package controller + +import ( + "context" + "testing" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + gameplanev1alpha1 "github.com/GameplanePanel/gameplane/operator/api/v1alpha1" +) + +// A Job at this Backup's Job name that another Backup controls is never +// mirrored: its snapshot id would be recorded on the wrong Backup. +func TestRetrySnapshotScrape_IgnoresForeignControlledJob(t *testing.T) { + b := quiescedBackup() + b.UID = "b1-uid" + b.Status.Phase = gameplanev1alpha1.BackupPhaseSucceeded + foreign := succeededJob(time.Second) + foreign.OwnerReferences = []metav1.OwnerReference{{ + APIVersion: gameplanev1alpha1.GroupVersion.String(), Kind: "Backup", Name: "other", + UID: "other-uid", Controller: ownerBoolPtr(true), + }} + q := &scrapeQuiescer{} + r := newLiveScrapeReconciler(t, b, + scrapeLogReader{body: `{"message_type":"summary","snapshot_id":"snap-other","total_bytes_processed":1}`}, + time.Hour, q) + if err := r.Create(context.Background(), foreign); err != nil { + t.Fatalf("create foreign job: %v", err) + } + + if _, err := r.retrySnapshotScrape(context.Background(), b); err != nil { + t.Fatalf("retrySnapshotScrape: %v", err) + } + if b.Status.SnapshotID == "snap-other" { + t.Fatal("recorded the foreign Job's snapshot id") + } + if b.Status.Phase != gameplanev1alpha1.BackupPhaseFailed { + t.Errorf("phase = %q, want Failed (own Job gone)", b.Status.Phase) + } +} diff --git a/operator/internal/controller/backup_worker.go b/operator/internal/controller/backup_worker.go index fa95a572a..26fe81363 100644 --- a/operator/internal/controller/backup_worker.go +++ b/operator/internal/controller/backup_worker.go @@ -198,7 +198,7 @@ func (r *BackupReconciler) reconcilePreparedRestic(ctx context.Context, b *gamep // Existing Jobs use their original execution protocol. Never replace a // running pre-upgrade Job with a gated worker or claim it was prepared. var job batchv1.Job - err := r.backupAPIReader().Get(ctx, client.ObjectKeyFromObject(b), &job) + err := r.backupAPIReader().Get(ctx, backupJobKey(b), &job) if err != nil && !apierrors.IsNotFound(err) { return ctrl.Result{}, err } @@ -307,7 +307,7 @@ func (r *BackupReconciler) reconcilePreparedRestic(ctx context.Context, b *gamep return ctrl.Result{}, err } backoff, deadline := resolveJobLimits(r.JobBackoffLimit, r.JobActiveDeadlineSeconds) - job = batchv1.Job{ObjectMeta: metav1.ObjectMeta{Name: b.Name, Namespace: b.Namespace, Annotations: map[string]string{backupWorkerProtocolAnnotation: "v1"}}, Spec: batchv1.JobSpec{BackoffLimit: &backoff, ActiveDeadlineSeconds: &deadline, + job = batchv1.Job{ObjectMeta: metav1.ObjectMeta{Name: backupJobName(b.Name), Namespace: b.Namespace, Annotations: map[string]string{backupWorkerProtocolAnnotation: "v1"}}, Spec: batchv1.JobSpec{BackoffLimit: &backoff, ActiveDeadlineSeconds: &deadline, Template: corev1.PodTemplateSpec{ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{backupRestoreJobLabel: backupRestoreJobValue, backupUIDLabel: string(b.UID)}}, Spec: r.buildPreparedBackupPodSpec(b, tmpl, source, bound.UID, preparation, appliedFSGroup)}}} job.Spec.Template.Spec.RestartPolicy = corev1.RestartPolicyNever if source.NodeName == "" { diff --git a/operator/internal/controller/gameserver_rcon.go b/operator/internal/controller/gameserver_rcon.go index e3d398518..d08d35892 100644 --- a/operator/internal/controller/gameserver_rcon.go +++ b/operator/internal/controller/gameserver_rcon.go @@ -4,6 +4,7 @@ import ( "context" "crypto/rand" "encoding/hex" + "errors" "fmt" corev1 "k8s.io/api/core/v1" @@ -35,6 +36,9 @@ type resolvedRCON struct { // into, "" when the template doesn't declare one or when using passwordFile. passwordEnv string port int32 + // external is true when the template names its own Secret through + // PasswordSecretRef; the operator never adopts, writes or deletes it. + external bool } // resolveRCON computes effective RCON configuration and credentials for a game server. @@ -62,6 +66,7 @@ func resolveRCON(gs *gameplanev1alpha1.GameServer, tmpl *gameplanev1alpha1.GameT if ref := tmpl.Spec.RCON.PasswordSecretRef; ref != nil { r.secretName = ref.Name r.secretKey = ref.Key + r.external = true } else if tmpl.Spec.RCON.PasswordFile != "" { r.passwordFile = tmpl.Spec.RCON.PasswordFile r.passwordEnv = "" @@ -76,10 +81,54 @@ func resolveRCON(gs *gameplanev1alpha1.GameServer, tmpl *gameplanev1alpha1.GameT return r } +// rconPasswordSourceAnnotation marks a -rcon Secret whose password came +// from the GameServer's config rather than being generated, so clearing the +// config field later rotates it to a fresh generated password. +const ( + rconPasswordSourceAnnotation = "gameplane.local/rcon-password-source" + rconPasswordSourceConfig = "config" +) + +// rconConfigPassword returns the password the user set in spec.config for the +// env-target configSchema field that exports the template's rcon.passwordEnv +// (for example FS25 ADMIN_PASSWORD), or "" when no such field exists or the +// user left it empty. Template defaults are ignored on purpose: a default is +// public in the template, so it never replaces a generated password. +func rconConfigPassword(gs *gameplanev1alpha1.GameServer, tmpl *gameplanev1alpha1.GameTemplate) string { + if tmpl.Spec.RCON == nil || tmpl.Spec.RCON.PasswordEnv == "" { + return "" + } + env := tmpl.Spec.RCON.PasswordEnv + for _, f := range tmpl.Spec.ConfigSchema { + if f.Target == "file" || configEnvName(f) != env { + continue + } + return gs.Spec.Config[f.Name] + } + return "" +} + +// errRCONSecretNotOwned reports that -rcon exists but is not controlled by +// the GameServer, so the operator refuses to use it as the RCON password. +var errRCONSecretNotOwned = errors.New("secret exists and is not controlled by this GameServer") + +// recordRCONSecretForeign emits a Warning event on gs (no Secret contents). It +// is a no-op without an EventRecorder. +func (r *GameServerReconciler) recordRCONSecretForeign(gs *gameplanev1alpha1.GameServer, secretName string) { + if r.EventRecorder == nil { + return + } + reason := "RCONSecretNotOwned" + message := fmt.Sprintf("Secret %q already exists and was not created by this GameServer; the operator will not use it as the RCON password. Delete or rename it so the operator can generate one", secretName) + r.EventRecorder.Eventf(gs, nil, corev1.EventTypeWarning, reason, reason, "%s", message) +} + // reconcileRCONSecret ensures an RCON password exists for the GameServer. // When the template declares RCON, doesn't reference an external Secret, and // doesn't use a game-managed password file, the operator generates a random -// password into -rcon and preserves it across reconciles. Templates that +// password into -rcon and preserves it across reconciles, unless the +// user set the config field that exports rcon.passwordEnv: then that value is +// stored instead (see rconConfigPassword). Templates that // reference their own Secret, use a password file, or expose no RCON, get // nothing (the -rcon Secret is removed when RCON is disabled, same // lifecycle as the config Secret). @@ -90,25 +139,57 @@ func (r *GameServerReconciler) reconcileRCONSecret( sec := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{Name: rconSecretName(gs), Namespace: gs.Namespace}, } + // A template-referenced Secret belongs to whoever created it, even when + // it happens to be named -rcon: leave it alone. + if rc.external && rc.secretName == rconSecretName(gs) { + return nil + } // Only manage -rcon ourselves when RCON is enabled, no external // PasswordSecretRef is set, and no game-managed password file is used. if !rc.enabled || rc.secretName != rconSecretName(gs) { return r.deleteIfControlledBy(ctx, gs, sec) } _, err := controllerutil.CreateOrUpdate(ctx, r.Client, sec, func() error { + // Never adopt a Secret this GameServer does not control: any user able + // to create Secrets (e.g. a backup destination named "-rcon") could + // otherwise choose the server's RCON password. Operator-created Secrets + // always carry the controller reference, so they stay reusable. + if sec.ResourceVersion != "" && !metav1.IsControlledBy(sec, gs) { + return errRCONSecretNotOwned + } sec.Type = corev1.SecretTypeOpaque + if sec.Data == nil { + sec.Data = map[string][]byte{} + } + if sec.Annotations == nil { + sec.Annotations = map[string]string{} + } + if pw := rconConfigPassword(gs, tmpl); pw != "" { + // The user typed the password into the template's config field + // for passwordEnv: store it here so the game (which reads this + // Secret through rconGameEnv) and the agent agree on it. + sec.Data["password"] = []byte(pw) + sec.Annotations[rconPasswordSourceAnnotation] = rconPasswordSourceConfig + return controllerutil.SetControllerReference(gs, sec, r.Scheme) + } + if sec.Annotations[rconPasswordSourceAnnotation] == rconPasswordSourceConfig { + // The user cleared the field: stop using their old password + // and generate a fresh one below. + delete(sec.Data, "password") + delete(sec.Annotations, rconPasswordSourceAnnotation) + } if len(sec.Data["password"]) == 0 { pw, gerr := generatePassword() if gerr != nil { return gerr } - if sec.Data == nil { - sec.Data = map[string][]byte{} - } sec.Data["password"] = []byte(pw) } return controllerutil.SetControllerReference(gs, sec, r.Scheme) }) + if errors.Is(err, errRCONSecretNotOwned) { + r.recordRCONSecretForeign(gs, sec.Name) + } if err != nil { return fmt.Errorf("reconcile rcon Secret %s/%s: %w", gs.Namespace, sec.Name, err) } @@ -150,8 +231,10 @@ func agentVolumeMounts(gs *gameplanev1alpha1.GameServer, tmpl *gameplanev1alpha1 // rconGameEnv returns the env var that injects the resolved RCON password // into the game container, or nil when the template declares no PasswordEnv -// or uses a game-managed password file. Appended last so it overrides any -// user-set value, keeping the game and agent in agreement on the password. +// or uses a game-managed password file. Appended last so it overrides the +// config field's own env entry; a password the user typed into that field +// still reaches the game, because reconcileRCONSecret copies it into this +// Secret. The game and agent therefore always agree on the password. func rconGameEnv(gs *gameplanev1alpha1.GameServer, tmpl *gameplanev1alpha1.GameTemplate) *corev1.EnvVar { rc := resolveRCON(gs, tmpl) if !rc.enabled || rc.passwordEnv == "" || rc.passwordFile != "" { diff --git a/operator/internal/controller/gameserver_rcon_config_password_test.go b/operator/internal/controller/gameserver_rcon_config_password_test.go new file mode 100644 index 000000000..7fbde923c --- /dev/null +++ b/operator/internal/controller/gameserver_rcon_config_password_test.go @@ -0,0 +1,107 @@ +package controller + +import ( + "context" + "testing" + + corev1 "k8s.io/api/core/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + gameplanev1alpha1 "github.com/GameplanePanel/gameplane/operator/api/v1alpha1" +) + +// rconConfigFixture is a template whose configSchema exports the same env var +// as rcon.passwordEnv (FS25 ADMIN_PASSWORD, L4D2/Squad/The Isle RCON_PASSWORD). +func rconConfigFixture() (*gameplanev1alpha1.GameServer, *gameplanev1alpha1.GameTemplate) { + gs, tmpl := rconForeignFixture() + tmpl.Spec.ConfigSchema = []gameplanev1alpha1.ConfigField{ + {Name: "ADMIN", EnvName: "PW", Type: "password", Default: "template-default"}, + } + return gs, tmpl +} + +func rconSecretPassword(t *testing.T, cl client.Client) corev1.Secret { + t.Helper() + var got corev1.Secret + if err := cl.Get(context.Background(), client.ObjectKey{Namespace: "ns", Name: "srv-rcon"}, &got); err != nil { + t.Fatal(err) + } + return got +} + +func TestReconcileRCONSecret_UsesUserConfigPassword(t *testing.T) { + gs, tmpl := rconConfigFixture() + gs.Spec.Config = map[string]string{"ADMIN": "typed-by-user"} + s := scrapeScheme(t) + cl := fake.NewClientBuilder().WithScheme(s).Build() + r := &GameServerReconciler{Client: cl, Scheme: s} + if err := r.reconcileRCONSecret(context.Background(), gs, tmpl); err != nil { + t.Fatalf("reconcile: %v", err) + } + got := rconSecretPassword(t, cl) + if string(got.Data["password"]) != "typed-by-user" { + t.Fatalf("password = %q, want the user's config value", got.Data["password"]) + } + if got.Annotations[rconPasswordSourceAnnotation] != rconPasswordSourceConfig { + t.Fatal("config-sourced password not marked") + } + + // Changing the field updates the stored password. + gs.Spec.Config["ADMIN"] = "changed" + if err := r.reconcileRCONSecret(context.Background(), gs, tmpl); err != nil { + t.Fatalf("reconcile: %v", err) + } + if got := rconSecretPassword(t, cl); string(got.Data["password"]) != "changed" { + t.Fatalf("password = %q after change, want %q", got.Data["password"], "changed") + } + + // Clearing the field rotates to a fresh generated password. + gs.Spec.Config["ADMIN"] = "" + if err := r.reconcileRCONSecret(context.Background(), gs, tmpl); err != nil { + t.Fatalf("reconcile: %v", err) + } + got = rconSecretPassword(t, cl) + pw := string(got.Data["password"]) + if pw == "" || pw == "changed" || pw == "template-default" { + t.Fatalf("password = %q after clearing, want a fresh generated one", pw) + } + if _, ok := got.Annotations[rconPasswordSourceAnnotation]; ok { + t.Fatal("source annotation kept after clearing the field") + } +} + +func TestReconcileRCONSecret_IgnoresTemplateDefaultPassword(t *testing.T) { + gs, tmpl := rconConfigFixture() + s := scrapeScheme(t) + cl := fake.NewClientBuilder().WithScheme(s).Build() + r := &GameServerReconciler{Client: cl, Scheme: s} + if err := r.reconcileRCONSecret(context.Background(), gs, tmpl); err != nil { + t.Fatalf("reconcile: %v", err) + } + got := rconSecretPassword(t, cl) + if pw := string(got.Data["password"]); pw == "" || pw == "template-default" { + t.Fatalf("password = %q, want a generated one", pw) + } +} + +func TestRCONConfigPassword(t *testing.T) { + gs, tmpl := rconConfigFixture() + gs.Spec.Config = map[string]string{"ADMIN": "x"} + if got := rconConfigPassword(gs, tmpl); got != "x" { + t.Fatalf("envName match = %q, want x", got) + } + tmpl.Spec.ConfigSchema[0].Target = "file" + if got := rconConfigPassword(gs, tmpl); got != "" { + t.Fatalf("file-target field = %q, want empty", got) + } + tmpl.Spec.ConfigSchema[0] = gameplanev1alpha1.ConfigField{Name: "PW", Type: "password"} + gs.Spec.Config = map[string]string{"PW": "y"} + if got := rconConfigPassword(gs, tmpl); got != "y" { + t.Fatalf("name match = %q, want y", got) + } + tmpl.Spec.RCON = nil + if got := rconConfigPassword(gs, tmpl); got != "" { + t.Fatalf("no rcon = %q, want empty", got) + } +} diff --git a/operator/internal/controller/gameserver_rcon_foreign_test.go b/operator/internal/controller/gameserver_rcon_foreign_test.go new file mode 100644 index 000000000..0b7a72582 --- /dev/null +++ b/operator/internal/controller/gameserver_rcon_foreign_test.go @@ -0,0 +1,94 @@ +package controller + +import ( + "context" + "errors" + "testing" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + + gameplanev1alpha1 "github.com/GameplanePanel/gameplane/operator/api/v1alpha1" +) + +func rconForeignFixture() (*gameplanev1alpha1.GameServer, *gameplanev1alpha1.GameTemplate) { + gs := &gameplanev1alpha1.GameServer{ObjectMeta: metav1.ObjectMeta{Name: "srv", Namespace: "ns", UID: "gs-uid"}} + tmpl := &gameplanev1alpha1.GameTemplate{Spec: gameplanev1alpha1.GameTemplateSpec{ + RCON: &gameplanev1alpha1.RCONSpec{Protocol: "source", PasswordEnv: "PW"}, + }} + return gs, tmpl +} + +func TestReconcileRCONSecret_RefusesUnownedSecret(t *testing.T) { + gs, tmpl := rconForeignFixture() + planted := &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Name: "srv-rcon", Namespace: "ns"}, + Data: map[string][]byte{"password": []byte("attacker")}, + } + s := scrapeScheme(t) + cl := fake.NewClientBuilder().WithScheme(s).WithObjects(planted).Build() + r := &GameServerReconciler{Client: cl, Scheme: s} + err := r.reconcileRCONSecret(context.Background(), gs, tmpl) + if !errors.Is(err, errRCONSecretNotOwned) { + t.Fatalf("err = %v, want errRCONSecretNotOwned", err) + } + var got corev1.Secret + if err := cl.Get(context.Background(), types.NamespacedName{Namespace: "ns", Name: "srv-rcon"}, &got); err != nil { + t.Fatal(err) + } + if len(got.OwnerReferences) != 0 || string(got.Data["password"]) != "attacker" { + t.Fatal("foreign Secret was modified") + } +} + +func TestReconcileRCONSecret_ReusesOwnedSecret(t *testing.T) { + gs, tmpl := rconForeignFixture() + s := scrapeScheme(t) + owned := &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Name: "srv-rcon", Namespace: "ns"}, + Data: map[string][]byte{"password": []byte("kept")}, + } + if err := controllerutil.SetControllerReference(gs, owned, s); err != nil { + t.Fatal(err) + } + cl := fake.NewClientBuilder().WithScheme(s).WithObjects(owned).Build() + r := &GameServerReconciler{Client: cl, Scheme: s} + if err := r.reconcileRCONSecret(context.Background(), gs, tmpl); err != nil { + t.Fatalf("reconcile: %v", err) + } + var got corev1.Secret + if err := cl.Get(context.Background(), client.ObjectKey{Namespace: "ns", Name: "srv-rcon"}, &got); err != nil { + t.Fatal(err) + } + if string(got.Data["password"]) != "kept" { + t.Fatal("owned password was rotated") + } +} + +// A template that references its own Secret named -rcon keeps using it: +// the operator neither refuses, adopts nor rewrites it. +func TestReconcileRCONSecret_LeavesReferencedSecretWithGeneratedName(t *testing.T) { + gs, tmpl := rconForeignFixture() + tmpl.Spec.RCON.PasswordSecretRef = &gameplanev1alpha1.SecretKeySelector{Name: "srv-rcon", Key: "pw"} + mine := &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Name: "srv-rcon", Namespace: "ns"}, + Data: map[string][]byte{"pw": []byte("chosen")}, + } + s := scrapeScheme(t) + cl := fake.NewClientBuilder().WithScheme(s).WithObjects(mine).Build() + r := &GameServerReconciler{Client: cl, Scheme: s} + if err := r.reconcileRCONSecret(context.Background(), gs, tmpl); err != nil { + t.Fatalf("reconcile: %v", err) + } + var got corev1.Secret + if err := cl.Get(context.Background(), client.ObjectKey{Namespace: "ns", Name: "srv-rcon"}, &got); err != nil { + t.Fatal(err) + } + if len(got.OwnerReferences) != 0 || string(got.Data["pw"]) != "chosen" || len(got.Data["password"]) != 0 { + t.Fatal("referenced Secret was modified") + } +} diff --git a/operator/specs.md b/operator/specs.md index 2d2732106..17eb08f3b 100644 --- a/operator/specs.md +++ b/operator/specs.md @@ -467,7 +467,7 @@ Primary reconcilers register with the manager in `cmd/main.go` and handle CRD li - Probe NetworkPolicy (`probe_policy.go`): with `--probe-ingress-policy`, reconcile an owned `-probes` policy admitting `--probe-ingress-from-cidr` to exactly the ports the game container's tcpSocket, httpGet (no `host`) and grpc liveness, readiness and startup probes use; named ports stay named. Exec probes need no network. With the flag off, no network probe, or no CIDRs, delete the policy if the GameServer controls it (a rule with no ports would admit every port). Replaces the chart's catch-all `allow-kubelet-probes` rule. - Template env ownership: Secret and ConfigMap references in the GameTemplate's and GameVersion's `env` must pass the same ownership rule as `spec.env` (`validateTemplateEnvSources` reuses `validateServerEnvSources`), so a template cannot mount another server's Secret into this server's pod. - Sentinel NetworkPolicies: a server is isolated (`sentinelIsolated`) when its template advertises any port or sets `GameTemplate.spec.sentinelIsolation: true`. The sentinel Deployment takes the label at once; a running game StatefulSet keeps its current label until it starts from zero replicas unless the template opts in explicitly, so the default restarts no game. When isolated, reconcile owned `-sentinel-ingress` and `-sentinel-egress` policies joining only the same namespace/server instance on advertised protocol/port tuples. An opted-in template with zero advertised ports revokes its owned game-ingress and sentinel policies plus public/game-direct Services through uncached, UID/resourceVersion-guarded cleanup before reporting actionable `Ready=False`; it creates no workloads or unrestricted grants, preserves foreign resources and the agent Service, and reports the failure even when cleanup needs a retry. Set `gameplane.local/sentinel-isolation=true` on both pod templates, without changing immutable workload selectors. On opt-out, roll the labels off both workloads and retain the per-server grants until uncached reads confirm both controllers observed the unlabeled templates and completed their rollouts, and neither game nor sentinel pods still carry the label. Settled opt-outs first probe cached sentinel policies and skip live rollout reads when no owned grants exist. The owned NetworkPolicy watch must remain enabled: delayed cache visibility enqueues another cleanup pass. The matching chart excludes opted-in sources and destinations from legacy grants; other policies remain additive. - - Fixed-name child cleanup: Delete fixed-name objects (`-config` Secret, `-files` Secret, `-rcon` Secret, `-auto` BackupSchedule, `-wipe` Job) only when the GameServer controls them via OwnerReference; unowned objects with these names stay in place (same rule as game-ingress NetworkPolicy). Wipe cleanup carries the verified Job UID as a delete precondition; a foreign Job cannot acknowledge a pending wipe or resume its server. + - Fixed-name child cleanup: Delete fixed-name objects (`-config` Secret, `-files` Secret, `-rcon` Secret, `-auto` BackupSchedule, `-wipe` Job) only when the GameServer controls them via OwnerReference; unowned objects with these names stay in place (same rule as game-ingress NetworkPolicy). The `-rcon` Secret is likewise never adopted: when it exists without this GameServer as controller (for example one planted before the server was created) the reconcile fails, a Warning event `RCONSecretNotOwned` is emitted (no Secret contents), and the Secret is left untouched until it is deleted or renamed. A template whose `rcon.passwordSecretRef` names `-rcon` itself uses that Secret as is: the operator neither adopts, writes nor deletes it. Operator-created Secrets carry the controller reference and keep working, including after an API-triggered rotation deletes and recreates them. When the template's `configSchema` has an env field exporting `rcon.passwordEnv` and the user set it, `-rcon` stores that value (annotation `gameplane.local/rcon-password-source: config`) instead of a generated password; the field's default is ignored, and clearing the field rotates to a fresh generated password. Wipe cleanup carries the verified Job UID as a delete precondition; a foreign Job cannot acknowledge a pending wipe or resume its server. - **Conflict requeue:** When reconcileStatefulSet or reconcileWipe encounters an apierrors.IsConflict error (concurrent update races), requeue without error logging — conflicts are expected and transient. Idle-transition and restart-acknowledgment conflicts, including wrapped errors, also return before logging and retry after one second with fresh state. Other errors retain their identity, error logging and controller-runtime backoff. The Module, NetworkCapture and Backup reconcilers apply the conflict rule to every error they return, via `requeueOnConflict` (`conflict.go`). - **Load-balancer class (`spec.networking.loadBalancerClass`):** honored only when `expose` is `LoadBalancer`. Kubernetes accepts a Service's `spec.loadBalancerClass` only as the Service becomes a LoadBalancer and rejects any later change, including adding one to a LoadBalancer Service that has none, so `reconcileService` sets the class only on that transition (a new Service, or one changing type to LoadBalancer). Before that, `replaceServiceForClassChange` deletes a GameServer-controlled LoadBalancer Service whose class differs from the requested one, or which has none, with the checked UID as a delete precondition, and returns `errServiceReplaced`; while the old Service is terminating (its load-balancer finalizer can hold it) it returns the same without deleting again. `Reconcile` treats `errServiceReplaced` as a pending networking change, not a failure: the rest of the pass (replicas and the StatefulSet, so Stop works; status) still runs, and the pass requeues after `serviceReplaceRetry` until the next reconcile creates the Service with the new class. The replacement gets a new cluster IP and usually a new external address. An unset class never replaces a Service, so a class set by something else (an admission policy, an older operator) is kept, and a Service the GameServer doesn't control is never deleted. Validation matches Kubernetes' qualified-name rule (a prefix of at most 253 characters and a name part of at most 63, so at most 317 in all), so a rejected class can't delete a working Service and then fail to create its replacement. The dashboard's Networking settings don't edit the class but keep it through a save. Tests: `TestReplaceServiceForClassChange*` (`gameserver_lbclass_test.go`), `TestGameServer_LoadBalancerClass*` and `TestGameServer_StopWhileTheServiceIsReplaced` (envtest), `TestGameServer_LoadBalancerClassReplacesTheService` and `TestCRD_Validation_LoadBalancerClassNameLength` (E2E). - **Port pools (`gameserver_portpool.go`, spec 036):** `--port-pool==-` defines a range of Service ports on one shared endpoint and `--port-pool-template=