From d266a863c722385ea305d63238b72ccbed4bfef7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 04:33:56 +0000 Subject: [PATCH 01/20] fix(api): harden readiness, login throttling, audit and resource ownership - Readiness probes answer 404 to proxied requests (X-Forwarded-For or Forwarded), so anonymous traffic cannot hold the shared DB ping slot. - Per-IP login, OIDC, share, MCP and SFTP buckets key on the IPv6 /64. At most 64 callers queue for argon2; beyond that login and SFTP login answer 503 with Retry-After instead of stalling every sign-in. - Generic POST/PUT never take ownerReferences or finalizers from the client, so a servers:write holder cannot make the garbage collector delete a server they may not delete. - Unrouted requests (router 404/405) write no audit row, and stored audit paths and targets are capped at 512 bytes. - Resetting a role mapping with no stored auth row no longer writes providers:null. - Kubeconfig CSR names are DNS-safe for any username. - A pod attach that times out before stdin drained is reported as an error, not as sent. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Claude --- api/cmd/health.go | 7 + api/cmd/health_forwarded_test.go | 36 ++++ api/cmd/main.go | 4 + api/internal/audit/audit.go | 73 ++++++- api/internal/audit/audit_unrouted_test.go | 111 +++++++++++ api/internal/auth/argon_busy_test.go | 144 ++++++++++++++ api/internal/auth/local.go | 16 +- api/internal/auth/mcptokens.go | 6 +- api/internal/auth/password.go | 59 +++++- api/internal/auth/ratelimit.go | 19 +- api/internal/auth/sftp.go | 4 +- api/internal/auth/testparams.go | 28 +++ api/internal/handlers/cluster_actions.go | 10 +- api/internal/handlers/config.go | 16 +- .../handlers/ownership_protect_test.go | 188 ++++++++++++++++++ api/internal/handlers/resources.go | 37 ++++ api/internal/handlers/sftp_login.go | 9 +- api/internal/handlers/sftp_login_busy_test.go | 26 +++ api/internal/kube/stdin.go | 22 +- api/internal/kube/stdin_result_test.go | 33 +++ api/specs.md | 11 +- docs/security.md | 12 +- 22 files changed, 836 insertions(+), 35 deletions(-) create mode 100644 api/cmd/health_forwarded_test.go create mode 100644 api/internal/audit/audit_unrouted_test.go create mode 100644 api/internal/auth/argon_busy_test.go create mode 100644 api/internal/handlers/ownership_protect_test.go create mode 100644 api/internal/handlers/sftp_login_busy_test.go create mode 100644 api/internal/kube/stdin_result_test.go 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 86b74f318..36eac0d6d 100644 --- a/api/cmd/main.go +++ b/api/cmd/main.go @@ -343,6 +343,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..d545ff545 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, max int) string { + if len(s) <= max { + return s + } + for max > 0 && !utf8.RuneStart(s[max]) { + max-- + } + return s[:max] +} + // 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,21 @@ 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 an + // unauthenticated flood cannot fill the audit table. + if unrouted.Load() { + return + } actor := "anonymous" if name := holder.Name(); name != "" { actor = name @@ -699,7 +769,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..1e493b5f5 --- /dev/null +++ b/api/internal/auth/argon_busy_test.go @@ -0,0 +1,144 @@ +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) { + if err := argonSem.Acquire(context.Background(), argonConcurrency); err != nil { + t.Fatalf("acquire: %v", err) + } + defer argonSem.Release(argonConcurrency) + argonWaiters.Add(maxArgonWaiters) + defer argonWaiters.Add(-maxArgonWaiters) + + 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 fillArgon(t *testing.T) func() { + t.Helper() + if err := argonSem.Acquire(context.Background(), argonConcurrency); err != nil { + t.Fatalf("acquire: %v", err) + } + argonWaiters.Add(maxArgonWaiters) + return func() { + argonWaiters.Add(-maxArgonWaiters) + argonSem.Release(argonConcurrency) + } +} + +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() + release := fillArgon(t) + defer release() + + 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 TestDummyHash_ComputedWhileQueueFull(t *testing.T) { + SetFastHashParams(t) + // Hold the slot and fill the waiter queue, as during a flood, then make + // sure the dummy hash still computes once the slot frees and never + // panics (a panic would be cached by sync.OnceValue). + if err := argonSem.Acquire(context.Background(), argonConcurrency); err != nil { + t.Fatal(err) + } + argonWaiters.Add(maxArgonWaiters) + defer argonWaiters.Add(-maxArgonWaiters) + type result struct { + hash string + panic any + } + done := make(chan result, 1) + go func() { + defer func() { + if p := recover(); p != nil { + done <- result{panic: p} + } + }() + done <- result{hash: computeDummyHash()} + }() + argonSem.Release(argonConcurrency) + select { + case r := <-done: + if r.panic != nil { + t.Fatalf("computeDummyHash panicked: %v", r.panic) + } + if r.hash == "" { + t.Fatal("empty dummy hash") + } + case <-time.After(30 * time.Second): + t.Fatal("computeDummyHash did not finish") + } +} + +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..e8b7d0432 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 @@ -251,3 +258,10 @@ func setLoginDeviceCookie(w http.ResponseWriter, req *http.Request, username str SameSite: http.SameSiteStrictMode, }) } + +// writePasswordBusy answers 503 with Retry-After when the argon2 queue is +// full. The response is identical whatever the username, so it leaks nothing. +func writePasswordBusy(w http.ResponseWriter, req *http.Request) { + w.Header().Set("Retry-After", "5") + httperr.WriteMessage(w, req, messages.New("server.generic.503", nil)) +} 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..d16292a85 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,50 @@ 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. +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)) + // Bypass the waiter cap: this runs lazily on the first unknown-user + // login, which may be during a flood, and a cached panic would break the + // deny path for good. Waiting on the slot here is bounded by one hash. + if err := argonSem.Acquire(context.Background(), 1); err != nil { + panic("init dummy hash: " + err.Error()) + } + defer argonSem.Release(1) + 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. +func VerifyDummy(ctx context.Context, pw string) error { + _, err := VerifyPassword(ctx, 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,7 +160,7 @@ 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) 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..b507b601f 100644 --- a/api/internal/handlers/cluster_actions.go +++ b/api/internal/handlers/cluster_actions.go @@ -244,7 +244,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}, 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/ownership_protect_test.go b/api/internal/handlers/ownership_protect_test.go new file mode 100644 index 000000000..1219e5bd0 --- /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.QueryRow(`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/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_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/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..50d39bcee 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 @@ -586,7 +587,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 +713,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 +750,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; 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/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 From ddad5870546ae47d626f23635b811b43abc359b0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 04:33:56 +0000 Subject: [PATCH 02/20] fix(web): block every readiness path, honour the upload limit, flush autosave - nginx refuses every /readyz path, including /readyz/postgres-ha. - File uploads to the files stream route use files.maxUploadSize (nginx include and a path-specific Ingress) instead of the 512m server cap. - Leaving the Files tab writes pending autosaves instead of dropping them. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Claude --- charts/gameplane/templates/ingress.yaml | 33 ++++++++++++++++++++ charts/gameplane/templates/web.yaml | 3 ++ docs/install.md | 6 +++- web/Dockerfile | 6 ++++ web/files-upload-limit.inc.template | 1 + web/nginx.conf.template | 35 ++++++++++++++++++++-- web/specs.md | 4 +-- web/src/lib/fileDrafts.ts | 16 +++++++++- web/src/lib/fileDraftsFlush.test.ts | 40 +++++++++++++++++++++++++ web/src/routes/tabs/Files.tsx | 5 ++++ 10 files changed, 143 insertions(+), 6 deletions(-) create mode 100644 web/files-upload-limit.inc.template create mode 100644 web/src/lib/fileDraftsFlush.test.ts 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/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/web/Dockerfile b/web/Dockerfile index c4aebe678..d29b99a00 100644 --- a/web/Dockerfile +++ b/web/Dockerfile @@ -54,6 +54,9 @@ LABEL org.opencontainers.image.version="${VERSION}" # /etc/nginx/conf.d/). The chart sets it to the in-cluster API service; this # default keeps a bare `docker run` from failing to start. ENV API_UPSTREAM=http://gameplane-api.gameplane-system.svc.cluster.local +# Body-size limit for dashboard file uploads (bytes), rendered into +# conf.d/files-upload-limit.inc. The chart sets it from files.maxUploadSize. +ENV FILES_MAX_UPLOAD_BYTES=21474836480 # The base image (last rebuilt 2026-10-19) ships brotli-libs 1.2.0-r1 # (CVE-2026-111497) and curl/libcurl 8.22.0-r0 (CVE-2026-92392); Trivy fails @@ -73,6 +76,9 @@ USER 101 # Replace the base image's default server block with ours. RUN rm -f /etc/nginx/conf.d/default.conf COPY web/nginx.conf.template /etc/nginx/templates/gameplane.conf.template +# Rendered by the same envsubst step to conf.d/files-upload-limit.inc (the +# base image strips ".template"; only *.conf is auto-included by nginx). +COPY web/files-upload-limit.inc.template /etc/nginx/templates/files-upload-limit.inc.template # Sourced at start (before envsubst) to export NGINX_RESOLVER from the pod's # /etc/resolv.conf — see the file and nginx.conf.template for why. The nginx diff --git a/web/files-upload-limit.inc.template b/web/files-upload-limit.inc.template new file mode 100644 index 000000000..d40cd4db2 --- /dev/null +++ b/web/files-upload-limit.inc.template @@ -0,0 +1 @@ +client_max_body_size ${FILES_MAX_UPLOAD_BYTES}; diff --git a/web/nginx.conf.template b/web/nginx.conf.template index e58b106b3..132af540b 100644 --- a/web/nginx.conf.template +++ b/web/nginx.conf.template @@ -158,11 +158,42 @@ server { } # The database readiness slot belongs to kubelet probes on the API's - # internal port. Public requests must never compete for that slot. - location = /readyz { + # internal port. Public requests must never compete for that slot. The + # whole prefix is blocked, so /readyz/postgres-ha is not proxied either. + location ~ ^/readyz(/|$) { return 404; } + # Dashboard file uploads (Files tab) stream one whole file as the PUT body. + # The limit follows Helm files.maxUploadSize (spec 040 OD-6) instead of the + # server-wide 512m, and the body is not spooled to disk before the API sees + # it. The chart renders conf.d/files-upload-limit.inc from the + # FILES_MAX_UPLOAD_BYTES environment variable; where that file is absent + # (the proxy smoke test) the location keeps the server-wide limit. + # Keep the proxy settings in step with @backend. + location ~ ^/servers/[^/]+/files/stream$ { + add_header Vary Accept always; + add_header X-Content-Type-Options "nosniff" always; + include /etc/nginx/conf.d/files-upload-limit*.inc; + proxy_request_buffering off; + if ($serve_shell) { + rewrite ^ /index.html last; + } + set $upstream ${API_UPSTREAM}; + proxy_pass $upstream$request_uri; + + proxy_http_version 1.1; + proxy_set_header Host $http_host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $connection_upgrade; + proxy_buffering off; + proxy_read_timeout 1h; + proxy_send_timeout 1h; + } + # Share paths carry their token. The access log already skips them # ($gameplane_loggable), but nginx's error log names the request line # and upstream URI when the API is unreachable, so this location logs diff --git a/web/specs.md b/web/specs.md index d38544a87..208a67684 100644 --- a/web/specs.md +++ b/web/specs.md @@ -46,7 +46,7 @@ These are CRD/API contracts; no new rollout controls or visual flow are defined. **API-only:** The dashboard never speaks directly to the operator or agent. All reads/writes flow through the Kubernetes API server and the REST/WebSocket API gateway (`api/`). -**Internal readiness:** Dashboard nginx returns 404 for `/readyz`, including query strings and normalized paths, before SPA routing or API proxying. Kubelet probes reach the API directly; public traffic cannot consume its database readiness slot. The nginx proxy smoke test checks rejection against a live upstream and confirms ordinary proxying still works. +**Internal readiness:** Dashboard nginx returns 404 for `/readyz` and everything under it (`/readyz/postgres-ha`), including query strings and normalized paths, before SPA routing or API proxying. Kubelet probes reach the API directly; public traffic cannot consume its database readiness slot. The nginx proxy smoke test checks rejection against a live upstream and confirms ordinary proxying still works. **Browser hardening:** nginx sends the SPA shell with a build-generated `Content-Security-Policy` (`cspHeader` in `vite.config.ts`: inline boot scripts allowed only by hash, no third-party script, style or font hosts), `X-Frame-Options: DENY`, `nosniff`, `Referrer-Policy: no-referrer` and HSTS. Fonts (Geist, JetBrains Mono) are bundled from `@fontsource/*`, so no page, the login page included, loads a third-party stylesheet or tells a font CDN who visits. nginx runs with `server_tokens off`, so neither its `Server` header nor its own error pages carry a version. Production builds drop `public/mockServiceWorker.js` (`dropMockWorker` in `vite.config.ts`); only the E2E mock mode serves it. @@ -318,7 +318,7 @@ Six of the nine ServerDetail tabs are rebuilt in this slice: - The new file/folder name prompt explains a rejected name inline ("Names can't contain "/" or be "." or "..".") and marks the input `aria-invalid`; Create stays disabled - Monaco editor unchanged - The tree expands folders on demand. A server URL with a `file` query opens the path directly, even if a directory listing is truncated. A trailing slash browses that directory. - - Open files have separate tabs and drafts scoped by cluster, namespace, server name, UID and path. Edits autosave after a pause, with one write at a time per file. A failed write retains the draft for retry within the current session. Closing a dirty tab waits for saving. Deletion waits for outstanding writes and invalidates pending reads of removed paths. If deletion fails, dirty drafts resume autosaving. Browser navigation controls the visible mobile pane. + - Open files have separate tabs and drafts scoped by cluster, namespace, server name, UID and path. Edits autosave after a pause, with one write at a time per file. A failed write retains the draft for retry within the current session. Closing a dirty tab waits for saving. Leaving the Files tab (unmount) writes pending autosaves immediately, including text queued behind an in-flight write, unless control permission was already lost. Deletion waits for outstanding writes and invalidates pending reads of removed paths. If deletion fails, dirty drafts resume autosaving. Browser navigation controls the visible mobile pane. - Check one or more paths to download a ZIP, create a ZIP in the current directory, or confirm deletion. The file manager identifies failed paths and keeps them selected. - New file uses POST `/files/create` with the encoded path, namespace/cluster scope, credentials and CSRF headers. The agent atomically refuses existing entries with 409; a conflict or unsupported older agent/gateway keeps the prompt open, shows the error and does not select a file or invalidate the list. Never fall back to `/files/write`; editor saves and uploads retain overwrite behavior. diff --git a/web/src/lib/fileDrafts.ts b/web/src/lib/fileDrafts.ts index 44c59bc0a..f18238564 100644 --- a/web/src/lib/fileDrafts.ts +++ b/web/src/lib/fileDrafts.ts @@ -4,6 +4,7 @@ interface Draft { error?: string; deleting?: boolean; pending?: Promise; + draining?: boolean; timer?: ReturnType; } @@ -55,6 +56,18 @@ export class FileDrafts { } } + // Unmount flush: write the latest text of every dirty draft, then stop. Runs + // with saving still enabled so an in-flight write's loop also queues newer + // text; call setEnabled(false) afterwards. + flushAll() { + if (!this.enabled) return; + for (const [path, draft] of this.files) { + if (draft.deleting || draft.error || (draft.text === draft.saved && !draft.pending)) continue; + draft.draining = true; + void this.save(path); + } + } + private schedule(path: string, draft: Draft) { clearTimeout(draft.timer); draft.timer = setTimeout(() => { void this.save(path); }, 1200); @@ -76,6 +89,7 @@ export class FileDrafts { if (!draft.pending) { draft.pending = this.flush(path, draft).finally(() => { draft.pending = undefined; + draft.draining = false; this.changed(); }); this.changed(); @@ -86,7 +100,7 @@ export class FileDrafts { private async flush(path: string, draft: Draft) { draft.error = undefined; try { - while (this.enabled && !draft.deleting && draft.saved !== draft.text) { + while ((this.enabled || draft.draining) && !draft.deleting && draft.saved !== draft.text) { const body = draft.text; await this.write(path, body); draft.saved = body; diff --git a/web/src/lib/fileDraftsFlush.test.ts b/web/src/lib/fileDraftsFlush.test.ts new file mode 100644 index 000000000..60a186a8c --- /dev/null +++ b/web/src/lib/fileDraftsFlush.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it, vi } from "vitest"; +import { FileDrafts } from "./fileDrafts"; + +describe("file drafts unmount flush", () => { + it("writes a pending autosave when flushed before disabling", async () => { + const write = vi.fn().mockResolvedValue(undefined); + const drafts = new FileDrafts(write); + drafts.open("/a", "old"); + drafts.edit("/a", "new"); + drafts.flushAll(); + drafts.setEnabled(false); + await Promise.resolve(); + expect(write.mock.calls).toEqual([["/a", "new"]]); + }); + + it("writes newer text queued behind an in-flight write", async () => { + let finish!: () => void; + const write = vi.fn().mockImplementationOnce(() => new Promise((r) => { finish = r; })).mockResolvedValue(undefined); + const drafts = new FileDrafts(write); + drafts.open("/a", "old"); + drafts.edit("/a", "first"); + const pending = drafts.save("/a"); + drafts.edit("/a", "second"); + drafts.flushAll(); + drafts.setEnabled(false); + finish(); + await pending; + expect(write.mock.calls).toEqual([["/a", "first"], ["/a", "second"]]); + }); + + it("does not write when saving is already disabled", () => { + const write = vi.fn().mockResolvedValue(undefined); + const drafts = new FileDrafts(write); + drafts.open("/a", "old"); + drafts.edit("/a", "new"); + drafts.setEnabled(false); + drafts.flushAll(); + expect(write).not.toHaveBeenCalled(); + }); +}); diff --git a/web/src/routes/tabs/Files.tsx b/web/src/routes/tabs/Files.tsx index 6a207312c..83aa6a552 100644 --- a/web/src/routes/tabs/Files.tsx +++ b/web/src/routes/tabs/Files.tsx @@ -95,6 +95,11 @@ function FilesBrowser({ resourceTarget, path, onNavigate }: { resourceTarget: Re }); const drafts = cachedDrafts!; // Synchronous initialData, never fetched or undefined. useSyncExternalStore(drafts.subscribe, drafts.snapshot); + const canControlRef = useRef(canControl); + useEffect(() => { canControlRef.current = canControl; }, [canControl]); + // Declared before the enable effect so its cleanup runs first on unmount: + // pending autosaves are flushed (not dropped) when the tab is left. + useEffect(() => () => { if (canControlRef.current) drafts.flushAll(); }, [drafts]); useEffect(() => { drafts.setEnabled(canControl); return () => drafts.setEnabled(false); From a5c980d6c12570e4dc8fea656baafac968304d6f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 04:33:56 +0000 Subject: [PATCH 03/20] fix(operator): rcon Secret adoption, backup Job names, OCI layer caps, guarded cosign - Never adopt a -rcon Secret the GameServer does not control. - Backup copy Job names longer than 63 characters are truncated with a hash at every lookup, so long server names can back up. - OCI module layers are size-capped before they are read. - Cosign signature fetches go through the netguard dialer. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Claude --- .../internal/controller/backup_controller.go | 6 +- operator/internal/controller/backup_forget.go | 23 +++++- operator/internal/controller/backup_guard.go | 2 +- .../controller/backup_job_name_test.go | 28 ++++++++ .../internal/controller/backup_manifest.go | 6 +- .../internal/controller/backup_preparation.go | 2 +- operator/internal/controller/backup_worker.go | 4 +- .../internal/controller/gameserver_rcon.go | 26 +++++++ .../gameserver_rcon_foreign_test.go | 70 +++++++++++++++++++ operator/internal/oci/bundle.go | 33 +++++++++ operator/internal/oci/client.go | 19 ++++- operator/internal/oci/layer_caps_test.go | 67 ++++++++++++++++++ operator/internal/verify/verify.go | 11 +++ .../internal/verify/verify_transport_test.go | 30 ++++++++ operator/specs.md | 7 +- 15 files changed, 321 insertions(+), 13 deletions(-) create mode 100644 operator/internal/controller/backup_job_name_test.go create mode 100644 operator/internal/controller/gameserver_rcon_foreign_test.go create mode 100644 operator/internal/oci/layer_caps_test.go create mode 100644 operator/internal/verify/verify_transport_test.go diff --git a/operator/internal/controller/backup_controller.go b/operator/internal/controller/backup_controller.go index 824732e30..7d5483e3f 100644 --- a/operator/internal/controller/backup_controller.go +++ b/operator/internal/controller/backup_controller.go @@ -192,7 +192,7 @@ 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 } @@ -322,7 +322,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 } @@ -984,7 +984,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..f04c767bf 100644 --- a/operator/internal/controller/backup_forget.go +++ b/operator/internal/controller/backup_forget.go @@ -285,7 +285,7 @@ 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 } @@ -414,6 +414,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_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_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..38847a8dd 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" @@ -76,6 +77,21 @@ func resolveRCON(gs *gameplanev1alpha1.GameServer, tmpl *gameplanev1alpha1.GameT return r } +// 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 @@ -96,6 +112,13 @@ func (r *GameServerReconciler) reconcileRCONSecret( 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 len(sec.Data["password"]) == 0 { pw, gerr := generatePassword() @@ -109,6 +132,9 @@ func (r *GameServerReconciler) reconcileRCONSecret( } 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) } 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..4064cd8c1 --- /dev/null +++ b/operator/internal/controller/gameserver_rcon_foreign_test.go @@ -0,0 +1,70 @@ +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") + } +} diff --git a/operator/internal/oci/bundle.go b/operator/internal/oci/bundle.go index 828d96947..e3c46bdf3 100644 --- a/operator/internal/oci/bundle.go +++ b/operator/internal/oci/bundle.go @@ -36,6 +36,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/operator/internal/oci/client.go b/operator/internal/oci/client.go index dc4fe4199..4f09f33ee 100644 --- a/operator/internal/oci/client.go +++ b/operator/internal/oci/client.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "io" "net/http" "sort" "time" @@ -139,6 +140,7 @@ 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 + var total int64 for _, layer := range layers { title := layer.Annotations[AnnotationTitle] if title == "" { @@ -156,6 +158,19 @@ func (c *Client) Pull(ctx context.Context, ref, reference string) (string, map[s files[title] = OversizedLocale continue } + } else { + // Only the layers the bundle format defines are read; each is + // size-checked before any byte is fetched. + limit, known := layerSizeLimit(title) + if !known { + continue + } + if layer.Size < 0 || layer.Size > limit { + return "", nil, fmt.Errorf("layer %s is %d bytes, over the %d-byte limit", title, layer.Size, limit) + } + } + if total += layer.Size; total > MaxBundleSize { + return "", nil, fmt.Errorf("bundle layers exceed the %d-byte limit", int64(MaxBundleSize)) } blob, err := readBlob(ctx, r, layer) if err != nil { @@ -174,7 +189,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/operator/internal/oci/layer_caps_test.go b/operator/internal/oci/layer_caps_test.go new file mode 100644 index 000000000..42dc3ff6a --- /dev/null +++ b/operator/internal/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/operator/internal/verify/verify.go b/operator/internal/verify/verify.go index 0bfb20ab1..22a2f1c5f 100644 --- a/operator/internal/verify/verify.go +++ b/operator/internal/verify/verify.go @@ -11,10 +11,13 @@ import ( "encoding/json" "errors" "fmt" + "net/http" "os" "path" "strings" + "time" + "github.com/GameplanePanel/gameplane/netguard" "github.com/google/go-containerregistry/pkg/authn" "github.com/google/go-containerregistry/pkg/name" ggcrremote "github.com/google/go-containerregistry/pkg/v1/remote" @@ -133,6 +136,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, @@ -140,6 +150,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/operator/internal/verify/verify_transport_test.go b/operator/internal/verify/verify_transport_test.go new file mode 100644 index 000000000..59c9c38c2 --- /dev/null +++ b/operator/internal/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/operator/specs.md b/operator/specs.md index 6a3919053..5e2971423 100644 --- a/operator/specs.md +++ b/operator/specs.md @@ -465,7 +465,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. Operator-created Secrets carry the controller reference and keep working, including after an API-triggered rotation deletes and recreates them. 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=