diff --git a/AGENTS.md b/AGENTS.md index 453131449..8c627fc45 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,7 +34,7 @@ operator/ controller-runtime operator cmd/main.go entrypoint; config/{crd,rbac}/ GENERATED api/ REST + WebSocket gateway (chi); cmd/main.go: `serve`, `gateway`, `bootstrap-admin`, `rotate-panel-key` internal/{audit,auth,controlplane,db,gateway,gatewayprotocol,handlers,httperr,kube,kubeconfig,messages,notify,rbac,registry,scope,steam,telemetry,workerconn,ws}/ -agent/ in-pod sidecar; internal/{a2s,actions,auth,caps,console,files,heartbeat,httpjson,lifecycle,logs,metrics,mods,players,quiesce,rcon,status,target,usage}/ +agent/ in-pod sidecar; internal/{a2s,actions,archive,auth,caps,console,files,heartbeat,httpjson,lifecycle,logs,metrics,mods,players,quiesce,rcon,status,target,usage}/ audit-syslog-bridge/ SUBMODULE GameplanePanel/audit-syslog-bridge (RFC 5424 HTTP→syslog forwarder; own go.mod, not in go.work; image still built here) telemetry-receiver/ usage telemetry ingest sentinel/ wake-on-connect proxy for sleeping pods @@ -45,7 +45,7 @@ tunnel/ SUBMODULE GameplanePanel/tunnel (relay client supervisor: f web/ React 19 + strict TS + Vite dashboard; src/{__tests__,api,components,lib,pages,router,routes,styles,test}/ (plus main.tsx and types.ts) modules/ SUBMODULE GameplanePanel/module (OCI game templates) website/ SUBMODULE GameplanePanel/website (Astro docs/marketing; has its own CLAUDE.md and AGENTS.md) -charts/gameplane/ Helm chart (crd-manifests/, hooks) +charts/gameplane/ Helm chart (crd-manifests/, templates/ including the crd-apply pre-upgrade hook) deploy/kind/ local Kind scripts test/e2e/ Kind E2E suite (//go:build e2e) docs/ architecture, security, modules; layout.md (target folder shape per module); archive/ (read-only old designs) diff --git a/FEATURES.md b/FEATURES.md index ce8beb134..3f6e61863 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -37,7 +37,7 @@ See [docs/roadmap.md](docs/roadmap.md) for what is planned and in progress. | Validate action input and run actions on PTY-only games | beta | on | Validates action parameters against the template schema and escapes them before they reach the game console, and runs actions on PTY-console games by writing lines to the container stdin. | [dependencies](docs/dependencies.md#gameaction) | | Live game log tail | stable | on | Streams the game log file over a WebSocket from the agent sidecar. | [architecture](docs/architecture.md#tail-logs) | | Replay and download the full game log | beta | on | Replays up to the last 500 game-log lines when a tab opens, capped by the agent at 20,000 lines and 4 MiB, and downloads the whole log file without interrupting the live stream. | [architecture](docs/architecture.md#tail-logs) | -| Send commands over RCON and ten console protocols | beta | on | Sends line-based commands over RCON or any of the ten console protocols a template selects, including REST and CLI; running without a password (rcon.authentication false) is opt-in. | [module-authoring](docs/module-authoring.md#rcon) | +| Send commands over RCON and ten console protocols | beta | on | Sends line-based commands over RCON or any of the eight other console protocols a template selects (telnet, WebSocket, BattlEye, Satisfactory, Palworld, Nuclear Option, REST and CLI); running without a password (rcon.authentication false) is opt-in. | [module-authoring](docs/module-authoring.md#rcon) | | Console toolbar with history, clear, download and fullscreen | beta | on | Recalls the last 100 sent commands with the arrow keys, kept only while the Console tab stays open, and toolbar buttons clear the terminal, download its buffer and toggle fullscreen without stopping the stream. | [README](README.md#features) | | Kubernetes events timeline for a server | beta | on | Shows the 50 most recent Kubernetes events for the server pod and its parent objects. | [architecture](docs/architecture.md#start-a-server) | @@ -93,7 +93,7 @@ See [docs/roadmap.md](docs/roadmap.md) for what is planned and in progress. | Install modules and block deleting ones a server uses | stable | on | Applying a Module CR makes the operator create the cluster-scoped GameTemplate for that module, and a finalizer keeps a Module or GameTemplate in place while a GameServer still uses its template. | [module-authoring](docs/module-authoring.md#installing-a-module) | | Reject unsafe or unreachable module sources | stable | on | Module source fetches go through the SSRF dial guard, which refuses unsafe destinations, and a Module reports a failure when its source registry cannot be reached. | [module-authoring](docs/module-authoring.md#module-sources) | | Switch a running server to another module version | stable | on | Changes a GameServer to another catalog version and loader, keeping each version and loader on its own data volume. | [module-authoring](docs/module-authoring.md#version-catalog-specversions) | -| Browse the official catalog and merged module states | beta | on | The official OCI catalog holds 29 game modules and the chart enables 16 by default, and the Modules page shows available, installed, verified, failed and update states across all configured sources. | [module-authoring](docs/module-authoring.md#installing-a-module) | +| Browse the official catalog and merged module states | beta | on | The official OCI catalog holds 29 game modules and the chart's default ModuleSource lists 30 module names (the 29 games plus Minecraft Proxy), and the Modules page shows available, installed, verified, failed and update states across all configured sources. | [module-authoring](docs/module-authoring.md#installing-a-module) | | Pin or verify module bundles with digests and signatures | beta | off | Sets a Module digest so only that exact bundle installs, and checks bundle signatures against a cosign public key or a keyless Sigstore identity before installing. | [module-authoring](docs/module-authoring.md#verifying-and-pinning-bundles) | | Use a Git repository, HTTP archive or local directory as a module source | beta | off | Reads module directories from a Git repository at a pinned ref, from a tar.gz or zip archive served over HTTP or HTTPS, or from a path mounted into the operator pod. | [module-authoring](docs/module-authoring.md#module-sources) | | Complete specs.md for all 29 game modules | planned | n/a | Each game module carries a specs.md documenting its template configuration; 27 of 29 have one today. | [roadmap](docs/roadmap.md#game-module-template-specifications-planned) | diff --git a/README.md b/README.md index 9c090e9ad..433db9855 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,7 @@ Gameplane extends Kubernetes using custom resources under `gameplane.local/v1alp - **`GameTemplate`**: Reusable blueprint for a game (container image, default ports, environment variables, volume layouts, shutdown hooks, and custom admin actions). - **`GameServer`**: An active game server instance created from a `GameTemplate` with customized resources, storage, idle auto-sleep settings, networking, relay tunnels, and backup policies. - **`Backup`**: A one-shot restic snapshot job targeting S3-compatible storage. +- **`BackupExport`**: A download of one restic Backup as a `.tar.gz` or `.zip` archive, created by the API and run by the operator's export worker. - **`BackupSchedule`**: A recurring cron backup policy attached to a game server. - **`Restore`**: A task that restores a backup snapshot into a server data volume. - **`Module`**: An installed game bundle managed by the operator to materialize a `GameTemplate`. diff --git a/api/specs.md b/api/specs.md index 5b54833e2..90978b0e6 100644 --- a/api/specs.md +++ b/api/specs.md @@ -31,7 +31,7 @@ The api module is the REST + WebSocket gateway for Gameplane, serving the web da - **Authorization:** three built-in roles (admin/operator/viewer) plus custom roles; granular per-GameServer owner/collaborator fallback; cluster and namespace dimensions on permissions - **Audit:** structured audit log (database + external sinks: webhook, S3, syslog bridge, stdout) with hash-chain integrity; per-user and per-IP tracking - **Notifications:** watch CRD status transitions (server health, backup outcomes) and dispatch to admin-configured sinks (Discord, Slack, SMTP, webhook) -- **Module registries:** pluggable providers (CurseForge, Modrinth, Spigot, Hangar, Nexus, Steam, Thunderstore, Factorio, GitHub, UMod); live lookup + caching +- **Module registries:** pluggable providers (CurseForge, Modrinth, Spigot, Hangar, Nexus, Steam, Thunderstore, Factorio, GitHub, UMod, FTB); live lookup + caching - **Multi-cluster dispatch:** `?cluster=` selector routes requests to remote clusters via registered kubeconfigs; home cluster is `local` - **Unified reads:** `/fleet/*` aggregates only the caller's authorized resources across registered clusters, with explicit target identities, target permissions, partial failures and bounded work; it does not schedule or mutate resources. - **Telemetry:** daily usage reports POSTed to the resolved destination (operator hard-off, bundled receiver, custom endpoint, or the project's default receiver). Two admin-consented tiers: basic (`version`, `servers`, `templates`) and extended (random install ID, environment categories, game and feature counts, signing key, send time; reports are signed). Counts cover every managed cluster: each cluster in the registry except a standalone panel's own client, each read with a 10 s timeout; a cluster whose GameServer, GameTemplate or (extended only) backup schedule list fails is left out of that report. Servers, templates and game counts are summed; extended `env.k8s` and `env.distro` are sets over the reachable clusters, `env.arch` their union, `env.nodes` one band over their total node count, and `env.deployment` is `standalone` or `cluster` (extended schema 2). New installs share both tiers by default once the first-login notice has been shown to an admin; nothing is sent before then. The schedule and consent source live in `telemetry_state` (migration 015), so restarts never send early and replicas share one schedule. When the destination offers proof-of-work challenges (`GET /v1/challenge`), the reporter solves one per request (a challenge above 26 bits is refused) @@ -60,7 +60,7 @@ api/ │ ├── audit/ # audit logger (database, webhook sink, S3 sink) │ ├── notify/ # notification delivery (Discord/Slack/SMTP/webhook watch -> dispatch) │ ├── ws/ # WebSocket (console RCON/PTY, pod logs, agent client) -│ ├── registry/ # mod registry providers (CurseForge, Modrinth, Spigot, Hangar, Nexus, Steam, Thunderstore, Factorio, GitHub, UMod) +│ ├── registry/ # mod registry providers (CurseForge, Modrinth, Spigot, Hangar, Nexus, Steam, Thunderstore, Factorio, GitHub, UMod, FTB) │ ├── steam/ # Steam Workshop ID resolver: cache + singleflight-deduped upstream lookups │ ├── scope/ # namespace + cluster resolution from request context │ ├── telemetry/ # optional anonymous usage metrics collection @@ -477,7 +477,7 @@ A submitted stylesheet is rejected with 400 and a message naming the offending r **Audit implementation pattern** (api/internal/audit/audit.go and api/internal/handlers/capture.go): - **Synchronous writes:** All capture handlers call `Auditor.WriteSync(ctx, method, path, target, reason, status)` directly before writing the HTTP response body to the client -- **Signature:** `WriteSync(ctx context.Context, method, path, target, reason string, status int) error` (api/internal/audit/audit.go:755) +- **Signature:** `WriteSync(ctx context.Context, method, path, target, reason string, status int) error` (api/internal/audit/audit.go:829) - **Timing:** The audit row is inserted into the database **before WriteHeader is called**, so if the audit write fails, the handler returns HTTP 500 (internal error) without sending the response body — **a failed audit write fails the entire capture operation (FR-006)** - **Error handling:** WriteSync returns an error if the database write fails; the handler must check the return value and bail if it's non-nil. This is enforced by a helper method `auditWriteOrFail` in capture.go, which returns false on write failure (the handler then returns 500 without proceeding) - **One row per request:** after a successful WriteSync, `auditWriteOrFail` calls `audit.MarkRecorded(ctx)`, which makes the global `audit.Middleware` skip its generic row for that request, so each capture mutation is audited once (the explicit row also carries `reason` and the composite `target`). If WriteSync fails the flag stays unset and the middleware row is written as a fallback @@ -486,29 +486,29 @@ A submitted stylesheet is rejected with 400 and a message naming the offending r - **Column:** `audit_events.reason` (nullable TEXT, added by migration 007_audit_reason.sql, api/internal/db/migrations/) - **Purpose:** Structured, machine-readable reason codes for operations that need fault reporting beyond HTTP status — e.g., capture start may fail with reasons "server_not_found", "capture_not_enabled", "invalid_filter", "invalid_duration", "invalid_size", "capture_in_progress", "ttl_exceeded", "create_failed", or "" on success -- **Hash chain compatibility** (api/internal/audit/audit.go:309-331): - - The `reason` field **participates in the hash chain ONLY when non-empty** (api/internal/audit/audit.go computeHash function, starting at line 365) +- **Hash chain compatibility** (api/internal/audit/audit.go:330-356): + - The `reason` field **participates in the hash chain ONLY when non-empty** (api/internal/audit/audit.go computeHash function, starting at line 367) - Pre-migration rows (written before 007_audit_reason.sql shipped) have NULL/empty reason and were hashed without a reason field; their stored hash remains valid and is verified bit-for-bit - Post-migration rows with non-empty reason include it in their content hash; two rows differing only in reason hash differently - - The Verify function (api/internal/audit/audit.go:455+) correctly reconstructs this at each row: pre-migration rows are hashed without reason (as originally computed), post-migration rows with non-empty reason include it + - The Verify function (api/internal/audit/audit.go:496) correctly reconstructs this at each row: pre-migration rows are hashed without reason (as originally computed), post-migration rows with non-empty reason include it - This preserves backward compatibility: the hash chain is never invalidated by the migration, and pre-existing audit rows remain verifiable **Fan-out to external sinks:** -- WriteSync passes the reason field to all configured external sinks (webhook, S3, stdout) via the Event struct (api/internal/audit/audit.go:722-731), enabling external audit systems to capture structured failure reasons alongside the HTTP status code +- WriteSync passes the reason field to all configured external sinks (webhook, S3, stdout) via the Event struct (the Event type, api/internal/audit/audit.go:240, and the webhook payload at line 186), enabling external audit systems to capture structured failure reasons alongside the HTTP status code **Captures:manage permission model** (api/internal/rbac/ and api/internal/db/migrations/): -- **Permission key:** `captures:manage` (defined in api/internal/rbac/catalog.go:72, namespaced) +- **Permission key:** `captures:manage` (defined in api/internal/rbac/catalog.go:75, namespaced) - **Label:** "Enable, start, stop, download, and delete packet captures" -- **Seeding:** Only the **admin role** has this permission, via the wildcard admin permission `*` (admin holds `perm: "*"` in 003_roles.sql:48, which covers all permissions including captures:manage) +- **Seeding:** Only the **admin role** has this permission, via the wildcard admin permission `*` (admin holds `perm: "*"` in 003_roles.sql:44, which covers all permissions including captures:manage) - **Migration 008 (008_captures_rbac.sql):** This migration deliberately does NOT explicitly INSERT captures:manage into role_permissions for the admin role, because admin's permission set must remain exactly `['*']` as verified by the test TestRoles_ListIncludesBuiltins - **Grantability:** captures:manage is a normal catalog permission that *could technically* be granted to custom roles via the roles API (it has no structural restriction like the `*` wildcard does). However, the default seeding keeps it admin-only; future phases may decide to allow operator or custom-role grantability (T012 in research.md left that as an open decision) - **Ownership fallback limitation:** The owner/collaborator fallback in rbac.go (around lines 147-170) is explicitly restricted to `servers:read`, `servers:write`, and `servers:console` permissions. Even a GameServer owner without the `captures:manage` permission will get HTTP 403 Forbidden on all capture endpoints **RBAC rule-table ordering (critical security constraint)**: -- **Constraint:** All ten capture permission rows in `api/internal/rbac/rbac.go` (lines 329-338, including `:capture-node-enable` and `:capture-node-disable`) MUST precede the `servers:read` rule (line 342) and the `servers:write` catch-all rule (line 343) +- **Constraint:** All ten capture permission rows in `api/internal/rbac/rbac.go` (lines 337-346, including `:capture-node-enable` and `:capture-node-disable`) MUST precede the `servers:read` rule (line 350) and the `servers:write` catch-all rule (line 351) - **Why it matters:** Path matching is done on the first segment, stripped of any verb suffix ("servers"). So `/servers/{name}:capture-start` matches segment "servers" just like `/servers/{name}` (ordinary CRUD). An unordered insertion of capture rules after the `servers:write` catch-all (which the operator role holds via 003_roles.sql:48) would silently grant all 10 capture endpoints to the operator role, **breaking the security requirement that only admin has capture permissions (FR-005/SC-005) with no test failure, no log line, no observable error — just silent escalation** - **What breaks if reordered:** - Any HTTP verb on any path matching `/servers/{name}:capture-*` would resolve to `servers:write` permission instead of `captures:manage` @@ -523,7 +523,7 @@ A submitted stylesheet is rejected with 400 and a message naming the offending r **Security & invariants:** - **Asymmetry clarity:** Enable is live and restart-free. Disable is similarly live but not truly "off" — the container remains in the pod until recreation. Spec.md documents this precisely; dashboa will surface it to users (e.g., "Capture disabled but sidecar remains until pod restart"). -- **RBAC ordering (critical):** All 10 capture permission rows in `api/internal/rbac/rbac.go` (lines 329-338) MUST precede the `servers:read` rule and the `servers:write` catch-all. Path matching is done on segment "servers" (via chi's `{name}` segment stripping), so a /servers/{name}:verb verb routes as "servers" segment. An unordered insertion after servers:write would silently grant capture access to the operator role (which holds servers:write), breaking the security requirement that only admin has capture permissions (FR-005/SC-005). CI does not currently detect this regression; future edits must preserve order or add a structural test. +- **RBAC ordering (critical):** All 10 capture permission rows in `api/internal/rbac/rbac.go` (lines 337-346) MUST precede the `servers:read` rule and the `servers:write` catch-all. Path matching is done on segment "servers" (via chi's `{name}` segment stripping), so a /servers/{name}:verb verb routes as "servers" segment. An unordered insertion after servers:write would silently grant capture access to the operator role (which holds servers:write), breaking the security requirement that only admin has capture permissions (FR-005/SC-005). CI does not currently detect this regression; future edits must preserve order or add a structural test. - **Concurrent capture limit (API + operator):** API enforces at creation time (rejects 409); operator enforces again at reconciliation time. Two independent gates prevent race conditions and eventual-consistency lag. - **Sidecar authentication:** mTLS only; both client cert+key and server CA are passed from cmd/main.go to MountCapture and built into an http.Client. No sidecar auth tokens in URLs (SSRF risk), no secrets echoed in logs. @@ -596,13 +596,13 @@ audit:read, config:read, config:manage (cluster-scoped) 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. 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. +8. **Audit pagination is bounded:** The `Auditor.Page(req, limit, before)` 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 26) and the store layer (api/internal/audit/audit.go line 984) 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`. 10. **Cluster-watch logging is privacy-preserving:** The `kube.Watch` goroutine logs cluster synchronization events using only the cluster name and error details, never secret material. While cluster credentials are held in memory and used to construct clients, logging never includes kubeconfig bytes, API tokens, or other sensitive data. The taint-source variable naming (`kubeconfigField` for field names like "kubeconfig") is distinct from the actual credential bytes flowing through the client, preserving clarity for future readers and static analysis. 11. **Secure error handling:** internal errors (DB failures, K8s API errors) logged in full; safe generic messages sent to clients 12. **Cluster dispatch validation:** `?cluster=` matched against registered Cluster CRDs via registry; unknown cluster is a 400 13. **WebSocket/HTTP proxy path validation:** `api/internal/ws/dialer.go` takes the namespace and pod name from the request path before building the agent's upstream URL. Both are validated as DNS-1123 labels (`isDNS1123Label`) and rejected with a 400 before any URL is constructed — gosec's taint analysis doesn't model a custom validator as a sanitizer, hence the scoped G704 exclusion on that file. -14. **Capture rule-table ordering:** All 10 capture permission rows (POST `:capture-enable`, `:capture-node-enable`, `:capture-node-disable`, `:capture-disable`, `:capture-start`, `:capture-stop`; GET `:captures`, `:capture`, `:capture-file`; DELETE `:capture`) **MUST precede** the `servers:read` rule and the `servers:write` catch-all rule in `api/internal/rbac/rbac.go` (lines 329-338; `servers:read` at line 342, catch-all at line 343). Because all `/servers/{name}:verb` paths match the segment "servers" (chi's `{name}` segment strips the verb suffix), an unordered insertion after `servers:write` (which the operator role holds) would **silently grant all 10 capture endpoints to the operator role**, breaking the security requirement that only admin has capture permissions (FR-005/SC-005). This regression is a structural bug CI does not currently catch — moving the capture rules after servers:write is a one-line security break. Any future RBAC edits must preserve this order; consider a structural test to prevent silent reordering. +14. **Capture rule-table ordering:** All 10 capture permission rows (POST `:capture-enable`, `:capture-node-enable`, `:capture-node-disable`, `:capture-disable`, `:capture-start`, `:capture-stop`; GET `:captures`, `:capture`, `:capture-file`; DELETE `:capture`) **MUST precede** the `servers:read` rule and the `servers:write` catch-all rule in `api/internal/rbac/rbac.go` (lines 337-346; `servers:read` at line 350, catch-all at line 351). Because all `/servers/{name}:verb` paths match the segment "servers" (chi's `{name}` segment strips the verb suffix), an unordered insertion after `servers:write` (which the operator role holds) would **silently grant all 10 capture endpoints to the operator role**, breaking the security requirement that only admin has capture permissions (FR-005/SC-005). This regression is a structural bug CI does not currently catch — moving the capture rules after servers:write is a one-line security break. Any future RBAC edits must preserve this order; consider a structural test to prevent silent reordering. 15. **Helm-seeded OIDC role mappings:** The "helm" provider is synthesized from CLI flags and the optional helmOverride overlay. No database migration carries the Helm seed; it lives only in flags. The helmOverride.roleMappings lives on the existing "auth" config row, per-role independently optional (key presence = overridden, absence = use Helm seed). Re-evaluated at login time so changes take effect without restart. Demotion guard prevents removing the last user able to manage users. 16. **Home-cluster-only routes:** Handlers built on the API's home-cluster client, and routes that reach agent or sidecar Services, serve the home cluster only and answer 501 not implemented (no cross-cluster agent yet) for a `?cluster=` naming any other registered cluster, so a permission granted on one cluster is never applied to another. The route list and its tests are under Authorization → Home-cluster-only routes. 17. **GameServer config passwords never leave the API in clear:** password-type `spec.config` values are replaced by a fixed marker in every response that carries a GameServer, through the single helper in `api/internal/handlers/config_redact.go`; a PUT that echoes the marker keeps the stored value. See Security considerations → GameServer config password redaction. @@ -783,7 +783,7 @@ Foreign keys are enforced only on Postgres (modernc-sqlite runs with FK OFF); th ### Outbound safety - **netguard dial guard:** mod-registry browse/search (`api/internal/registry`) shares one client built with `netguard.HTTPClient(…, netguard.IsPublic)`, so every registry fetch, redirects included, connects only to a globally routable address and never through a proxy from the pod environment. Notification sinks use the permissive `netguard.IsAllowed` policy, so self-hosted endpoints on private addresses stay reachable. - **mTLS to agent:** client cert + key validate console operations -- **Agent proxy URL construction:** `api/internal/ws/dialer.go`'s ws and http proxy handlers build the upstream agent URL from the namespace and pod name taken off the request path. In both handlers the namespace and pod name are validated as DNS-1123 labels via `isDNS1123Label` first, and a request with an invalid namespace or pod name is rejected with `400 Bad Request` before any URL is built. Only after that validation do the two paths diverge in how they construct the URL: the HTTP proxy path assembles it with `url.URL`, while the WebSocket proxy path concatenates the already-validated host onto a fixed `wss://` scheme and the fixed agent path (`upstream := "wss://" + host + agentPath`). The load-bearing safety property — validation strictly precedes URL construction — holds for both paths regardless of which one then uses string concatenation. +- **Agent proxy URL construction:** `api/internal/ws/dialer.go`'s ws and http proxy handlers validate the namespace and pod name taken off the request path, then pass the target to the shared agent transport. In both handlers the namespace and pod name are validated as DNS-1123 labels via `isDNS1123Label` first, and a request with an invalid namespace or pod name is rejected with `400 Bad Request` before any URL is built. Both proxy paths then hand the validated target to the shared agent transport in `api/internal/ws/transport.go`, which assembles the URL with `url.URL` from a fixed scheme and the registered agent path; no string concatenation builds the upstream URL. The load-bearing safety property, validation before URL construction, holds for both paths. ### Backup archives (spec 041) The API is a gateway for these routes (core rule 10): it creates a `BackupExport` or upload `Restore` and streams bytes to or from the operator-managed worker. Every route is mounted by `MountBackupArchives` (`api/internal/handlers/backup_archives.go`, upload and confirm in `backup_archives_upload.go`). @@ -857,7 +857,7 @@ The API is a gateway for these routes (core rule 10): it creates a `BackupExport - Real kind cluster (1.31) - Real Helm chart installation - Real agents + console/file operations - - Bucket sharding (api-auth, api-rbac, api-agent, ratelimit, bot, multicluster) + - Bucket sharding (api-auth, api-rbac, api-agent, ratelimit, bot-fast, bot-heavy, multicluster) - ~10-20 min total (parallel buckets on CI) ### Coverage gate diff --git a/containers/README.md b/containers/README.md index 99a32e053..e0fe35620 100644 --- a/containers/README.md +++ b/containers/README.md @@ -40,12 +40,12 @@ containers/ ├── farming-simulator-25/ # standalone base (debian + Wine) │ ├── Dockerfile │ └── entrypoint.sh - └── euro-truck-simulator-2/ # standalone base (debian) + └── euro-truck-simulator-2/ # game image built FROM the common-steamcmd base ├── Dockerfile └── entrypoint.sh ``` -`fivem`, `beammp`, `farming-simulator-25` and `euro-truck-simulator-2` moved here from the `GameplanePanel/module` repo unchanged. They do not build on the SteamCMD base and run as UID/GID 1000 with `HOME=/home/gameplane`; the `STEAMCMD_BASE_IMAGE` build arg CI passes is unused by them. +`fivem`, `beammp` and `farming-simulator-25` moved here from the `GameplanePanel/module` repo unchanged. They do not build on the SteamCMD base and run as UID/GID 1000 with `HOME=/home/gameplane`; the `STEAMCMD_BASE_IMAGE` build arg CI passes is unused by them. ### `common/` — reusable base images @@ -193,7 +193,7 @@ When using `runAsUser`, the `$HOME` environment variable must also be set — ei ### Data Persistence -Game server data (worlds, configurations, logs) must persist across pod restarts. Set up a PersistentVolumeClaim and mount it at the install directory (e.g., `/data`). The Gameplane chart's `storage.mountPath` field handles this. +Game server data (worlds, configurations, logs) must persist across pod restarts. Set up a PersistentVolumeClaim and mount it at the install directory (e.g., `/data`). The GameTemplate's `spec.storage.mountPath` field handles this. ### RCON & Console diff --git a/docs/architecture.md b/docs/architecture.md index 42ff7f396..63d66419b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -59,6 +59,7 @@ The operator runs one reconciler per CRD: | `ModuleSource` | an index of the bundles in one store | | `Cluster` | health of a registered remote cluster | | `NetworkCapture` | a capture-sidecar ephemeral container and its PCAPNG output | +| `BackupExport` | export worker Pod and ClusterIP Service that stream a restic `Backup` out as a `.tar.gz` or `.zip` archive (spec 041) | ## Dashboard component layer diff --git a/docs/comparison-sources.md b/docs/comparison-sources.md index 9cdf7a173..6eeb57b86 100644 --- a/docs/comparison-sources.md +++ b/docs/comparison-sources.md @@ -49,7 +49,7 @@ verified. ### Row (d): Backup and restore **Source ID**: G-d -**Evidence**: operator/api/v1alpha1/backup_types.go:262; CLAUDE.md architecture section +**Evidence**: operator/api/v1alpha1/backup_types.go:269; CLAUDE.md architecture section **Checked on**: 2026-09-02 **What was verified**: Backup CRD type defined with support for Restic snapshots to S3-compatible storage; BackupSchedule CRD supports cron-scheduled backups; one-click restore via Restore CRD. **Last-known URL**: https://github.com/GameplanePanel/Gameplane/tree/master/operator/api/v1alpha1 @@ -67,9 +67,9 @@ verified. ### Row (f): Game template distribution **Source ID**: G-f -**Evidence**: docs/module-authoring.md § Verifying and pinning bundles (lines 433–515); CLAUDE.md § Repository Map (`modules/`) +**Evidence**: docs/module-authoring.md § Verifying and pinning bundles (lines 442–524); CLAUDE.md § Repository Map (`modules/`) **Checked on**: 2026-09-26 (re-verified) -**What was verified**: OCI bundles via ModuleSource CRD supporting git/http/oci/local/upload sources; cosign signature verification documented at lines 433–515; 30 ready-to-use templates in gameplane-module repository. +**What was verified**: OCI bundles via ModuleSource CRD supporting git/http/oci/local/upload sources; cosign signature verification documented at lines 442–524; 30 ready-to-use templates in gameplane-module repository. **Last-known URL**: https://github.com/GameplanePanel/Gameplane/tree/master/modules diff --git a/docs/contributing.md b/docs/contributing.md index 6c599d593..a38778d46 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -104,7 +104,7 @@ Reopen the container with one of the named profiles (or `full`) and run the targ relevant screen, regenerate the export with `hack/design/fig-export.ts` (see `assets/design-export/MANIFEST.md`; it renders only the screens that changed, and the `design export` workflow commits it on pull requests from branches of this repository), review with the maintainers, *then* -translate to React. This keeps the 251 designed screens (`assets/design-export/screens.json`) the source of truth and +translate to React. This keeps the 314 designed screens (`assets/design-export/screens.json`) the source of truth and prevents the dashboard from drifting into code-led redesigns. Backend/operator/API changes do not need a design pass. @@ -400,7 +400,7 @@ transparency log. The jobs run in this order: ```mermaid flowchart TD - T["Tag v* pushed"] --> IM["images: one leg per component (12)"] + T["Tag v* pushed"] --> IM["images: one leg per component (13)"] T --> MO["modules: push and sign official bundles"] IM --> P["Push image by digest"] P --> S["Trivy scan, then cosign sign (keyed)"] diff --git a/docs/dependencies.md b/docs/dependencies.md index 55ddefa05..2de9bfcf3 100644 --- a/docs/dependencies.md +++ b/docs/dependencies.md @@ -42,8 +42,8 @@ were added and verified on **2026-09-26**. | `telemetryschema/` | Go | 0 (stdlib only) | Shared telemetry report contract (types, strict decoder, official module catalog, report signing) used by the API reporter and the telemetry receiver | | `themepkg/` | Go | 1 (`gopkg.in/yaml.v3`) | Shared theme package validator (theme.yaml, tokens and contrast, custom CSS sanitizer, previews, size limits) used by the API and `gp-module` (spec 043) | | `bundlefetch/` | Go | 11 (oras-go, image-spec, go-digest, x/mod, go-containerregistry, cosign, sigstore-go, go-git, go-billy, x/crypto, go-logr) | Shared OCI client, cosign verifier core and git/HTTP/local/OCI fetch code (no Kubernetes imports) used by the operator's module sources and the API's theme sources (spec 043) | -| `operator/` | Go | 16 | controller-runtime reconciler for the 9 CRDs (`operator/api/v1alpha1/*_types.go`); module OCI pull/verify, git/OCI fetch, restic-backup scheduling | -| `api/` | Go | 21 | chi REST + WebSocket gateway: auth (local + OIDC), RBAC, K8s client, SQLite/Postgres persistence, notifications | +| `operator/` | Go | 16 | controller-runtime reconciler for the 10 CRDs (`operator/api/v1alpha1/*_types.go`); module OCI pull/verify, git/OCI fetch, restic-backup scheduling | +| `api/` | Go | 24 | chi REST + WebSocket gateway: auth (local + OIDC), RBAC, K8s client, SQLite/Postgres persistence, notifications | | `agent/` | Go | 6 | In-pod sidecar: RCON/WebRcon console, chi HTTP surface, heartbeat status patch, disk usage stats | | `audit-syslog-bridge/` (submodule) | Go | 0 (stdlib only) | Standalone HTTP-JSON → syslog relay for the audit webhook sink | | `telemetry-receiver/` | Go | 3 | Standalone collector for the API's usage telemetry (daily counts; extended reports add a random install ID and its public key; on by default for new installs; `api.telemetry.enabled=false` turns it off) | @@ -181,7 +181,7 @@ Importers use a local `replace` module (`replace github.com/GameplanePanel/gamep ### operator controller-runtime operator reconciling GameServer, GameTemplate, Backup, -BackupSchedule, Restore, Module, and ModuleSource. Direct deps from +BackupSchedule, BackupExport, Restore, Module, ModuleSource, Cluster and NetworkCapture. Direct deps from `operator/go.mod` (excluding the local `netguard` replace, covered above): | Dependency | Version | Why | Status | @@ -345,9 +345,9 @@ trade-off). Direct deps from `capture-sidecar/go.mod`: | Dependency | Version | Why | |---|---|---| -| `github.com/gopacket/gopacket` | v1.7.7 | `internal/capture/writer.go`/`afpacket.go` — `AF_PACKET` socket capture via `gopacket/afpacket`, plus pcap-format frame writing via `pcapgo`/`layers` | +| `github.com/gopacket/gopacket` | v1.8.0 | `internal/capture/writer.go`/`afpacket.go` — `AF_PACKET` socket capture via `gopacket/afpacket`, plus pcap-format frame writing via `pcapgo`/`layers` | | `github.com/packetcap/go-pcap` | v0.0.0-20260731105150-c86974bbfbcd | `internal/capture/filter.go` — compiles the tcpdump-style filter expression to BPF without requiring libpcap at runtime | -| `golang.org/x/net` | v0.62.0 | `internal/capture/filter.go`/`afpacket.go` — `x/net/bpf`: assembling the classic-BPF program attached to the AF_PACKET socket | +| `golang.org/x/net` | v0.63.0 | `internal/capture/filter.go`/`afpacket.go` — `x/net/bpf`: assembling the classic-BPF program attached to the AF_PACKET socket | ### tunnel @@ -393,15 +393,15 @@ React 19 + TypeScript strict + Vite dashboard (`web/package.json` version **Routing / data fetching** - `@tanstack/react-router` `^1.170.46` — file-based route tree; `createRouter`/`RouterProvider` in `src/main.tsx`, tree built in `src/router/tree.tsx`, `Link`/`useNavigate` used across `src/routes/*.tsx`. -- `@tanstack/react-query` `^5.108.1` — server-state cache; `QueryClient`/`QueryClientProvider` in `src/main.tsx`, `useQuery`/`useMutation` used pervasively across routes and `src/lib/` — the dominant data-fetching layer. -- `@tanstack/react-virtual` `^3.14.26` — `useVirtualizer` in `src/routes/tabs/Logs.tsx`, virtualizes the log-line list. +- `@tanstack/react-query` `^5.108.4` — server-state cache; `QueryClient`/`QueryClientProvider` in `src/main.tsx`, `useQuery`/`useMutation` used pervasively across routes and `src/lib/` — the dominant data-fetching layer. +- `@tanstack/react-virtual` `^3.14.28` — `useVirtualizer` in `src/routes/tabs/Logs.tsx`, virtualizes the log-line list. - `@tanstack/router-devtools` (dev) — **no import found anywhere in `src/`**. Installed but apparently unused; flag as a candidate for removal or an intentionally-deferred addition. **UI primitives (HeroUI v3)** -- `@heroui/react` `3.2.7` — foundational component library (Button, Input, Select, Modal, Table, etc.); composed and themed in `src/components/ui/` (Gameplane's composition layer over HeroUI). -- `@heroui/styles` `3.2.7` — companion style package with semantic token infrastructure for light/dark modes and brand customization; `@heroui/styles` is imported in `src/styles/globals.css` for global theme setup. +- `@heroui/react` `3.2.8` — foundational component library (Button, Input, Select, Modal, Table, etc.); composed and themed in `src/components/ui/` (Gameplane's composition layer over HeroUI). +- `@heroui/styles` `3.2.8` — companion style package with semantic token infrastructure for light/dark modes and brand customization; `@heroui/styles` is imported in `src/styles/globals.css` for global theme setup. - `clsx` `^2.1.1` + `tailwind-merge` `^3.7.1` — combined into the `cn()` helper in `src/lib/utils.ts`, used app-wide for conditional/merged Tailwind classes and with HeroUI's theme tokens. -- `lucide-react` `^1.76.0` — icon set, imported in roughly 83 files (`AppLayout`, `Dashboard`, `Login`, dialogs, etc.). +- `lucide-react` `^1.79.0` — icon set, imported in roughly 96 files (`AppLayout`, `Dashboard`, `Login`, dialogs, etc.). - `react-aria` — peer dependency of HeroUI, providing accessibility primitives (via `react-aria-components`) used by HeroUI atoms. **Editors / terminals** @@ -464,7 +464,7 @@ These aren't code dependencies of any component; they're invoked by - **`sigs.k8s.io/controller-runtime/tools/setup-envtest@release-0.24`** — installed by `make envtest-bin`; downloads the K8s 1.36.2 envtest binaries (`kube-apiserver`, `etcd`) that back `operator`'s and `api`'s `-tags=envtest` integration tests. - **`golangci-lint` v2.14.0** — pinned in `.github/workflows/ci.yaml`, `.devcontainer/versions.toml` (`golangci_lint`, installed by `.devcontainer/setup.sh`), and the exact-version guard in `test/e2e/lint-gate-verify.sh`. Its `golang.org/x/tools v0.50.0` importer supports the export-data version 5 emitted by Go 1.27.3; v2.13.2's importer does not. CI uses the published binary and the devcontainer builds the same release from source. The CI `lint` matrix gates every selected workspace module with `.golangci.yml`, using `envtest` tags for operator/API and `e2e` tags for test/e2e. Update the verifier's valid fixtures with the pin; unsupported or unpinned versions must still fail. Tests and general lint run only in CI under repository policy. - **`oras` CLI ≥ 1.2.0** (pinned `1.2.0` in `.devcontainer/versions.toml`; `oras-project/setup-oras@v2.0.4` action in `release.yaml`) — `modules/build.sh` pushes each `modules//` directory as an OCI module bundle (`make modules-push`); this is a *different* thing from `operator`'s `oras.land/oras-go/v2` **library** dependency, which is the operator's own pull-side client, not the CLI. -- **`cosign` CLI v3.1.2** (`sigstore/cosign-installer@v4.1.3`) — used in `publish-edge.yaml`/`release.yaml` to sign published container images, the Helm chart, and module bundles against `COSIGN_PRIVATE_KEY`, recording each signature in the public Rekor transparency log, and to round-trip-verify against the derived public key before publishing. Signatures use the classic format (`--new-bundle-format=false --use-signing-config=false`), which is what keeps them readable by the operator's `sigstore/cosign/v3` library; cosign's newer Rekor v2 flow additionally requires an RFC3161 timestamp authority that keyed signing cannot satisfy. `modules/build.sh` gates the same behaviour behind its own `--tlog-upload` flag so local and air-gapped authoring stays offline. Distinct from `operator`'s `sigstore/cosign/v3` **library** dependency, which only ever *verifies* (never signs) at reconcile time. +- **`cosign` CLI v3.1.2** (`sigstore/cosign-installer@v4.1.4`) — used in `publish-edge.yaml`/`release.yaml` to sign published container images, the Helm chart, and module bundles against `COSIGN_PRIVATE_KEY`, recording each signature in the public Rekor transparency log, and to round-trip-verify against the derived public key before publishing. Signatures use the classic format (`--new-bundle-format=false --use-signing-config=false`), which is what keeps them readable by the operator's `sigstore/cosign/v3` library; cosign's newer Rekor v2 flow additionally requires an RFC3161 timestamp authority that keyed signing cannot satisfy. `modules/build.sh` gates the same behaviour behind its own `--tlog-upload` flag so local and air-gapped authoring stays offline. Distinct from `operator`'s `sigstore/cosign/v3` **library** dependency, which only ever *verifies* (never signs) at reconcile time. - **`kind`** v0.32.0 (pinned in `.devcontainer/versions.toml`) / `helm/kind-action@v1.15.2` (`install_only: true` in CI) — spins up the ephemeral clusters for `make dev-up`, `make test-e2e`, and every `e2e-*` CI job. - **`helm`** (`azure/setup-helm@v5.1.0` in CI; `helm` 4.3.1 pinned in `.devcontainer/versions.toml` and installed by the full dev container profile) — chart lint (`helm lint`), chart render sanity-check, `helm template`, and `helm upgrade --install` in `deploy/kind/*.sh`/`Makefile`'s `dev-install`. - **`docker buildx bake`** (`containers/docker-bake.hcl`, `docker/bake-action@v7.3.0`) — builds the operator/api/agent e2e images concurrently with a shared GitHub Actions layer cache (`.github/actions/e2e-images`); also builds the `e2e-gameprobe` headless bot image used only by the game-bot CI job. @@ -505,7 +505,7 @@ The Helm chart itself (`charts/gameplane/Chart.yaml`) declares no chart dependen - **Signing has two independent code paths that must be kept in sync.** Verification (`operator`'s `sigstore/cosign/v3` **library**, checked at Module-reconcile time against `cosign.pub`) and signing (the `cosign` **CLI** - v3.1.2, `sigstore/cosign-installer@v4.1.3` in CI) both use classic cosign + v3.1.2, `sigstore/cosign-installer@v4.1.4` in CI) both use classic cosign signature format (`--new-bundle-format=false --use-signing-config=false`) for mutual compatibility. A bump to either side needs to preserve that format compatibility and the ability to sign with `--tlog-upload` (Rekor logging). diff --git a/docs/gateway-install.md b/docs/gateway-install.md index 23f600ec4..8309975f4 100644 --- a/docs/gateway-install.md +++ b/docs/gateway-install.md @@ -15,7 +15,7 @@ cluster. The remote operator/gateway installation below is the same in both case Use matching API, operator and agent versions. The gateway uses the API image's `gateway` subcommand, a dedicated ServiceAccount, and read-only `get` access to -GameServers, NetworkCaptures and Services in its configured namespaces. It has no database and no +GameServers, NetworkCaptures, Backups, BackupExports and Services in its configured namespaces. It has no database and no user login. Users authenticate to the central API, which retains authorization. Create these Secrets in the chart release namespace before enabling the gateway: diff --git a/docs/layout.md b/docs/layout.md index 06b8c1558..b9c17e139 100644 --- a/docs/layout.md +++ b/docs/layout.md @@ -92,14 +92,14 @@ makes. | Module | Kind | Target | Gap today | | --- | --- | --- | --- | | `agent` | Service | `cmd/main.go` + `internal//` | matches | -| `api` | Service | `cmd/main.go` + `internal//` | `cmd/` holds 9 non-test files (bootstrap, gateway, health, main, management, memlimit, metrics, panel_key, workers) → keep wiring in `cmd/`, move behavior to `internal//`; second binary `cmd/messages-export/` matches; `internal/handlers/` is one flat package of 216 `.go` files, 64 of them non-test (spec 028 splits it) | -| `audit-syslog-bridge` | Service | `cmd/main.go` + `internal//` | 3 files in root `package main` (`main.go` 460 lines) → `cmd/main.go` + `internal//`. Lives in the `GameplanePanel/audit-syslog-bridge` submodule. | +| `api` | Service | `cmd/main.go` + `internal//` | `cmd/` holds 9 non-test files (bootstrap, gateway, health, main, management, memlimit, metrics, panel_key, workers) → keep wiring in `cmd/`, move behavior to `internal//`; second binary `cmd/messages-export/` matches; `internal/handlers/` is one flat package of 240 `.go` files, 71 of them non-test (spec 028 splits it) | +| `audit-syslog-bridge` | Service | `cmd/main.go` + `internal//` | 3 files in root `package main` (`main.go` 507 lines) → `cmd/main.go` + `internal//`. Lives in the `GameplanePanel/audit-syslog-bridge` submodule. | | `capture-sidecar` | Service | `cmd/main.go` + `internal//` | matches. Lives in the `GameplanePanel/capture-sidecar` submodule. | | `mcp-server` | Service | `cmd/main.go` + `internal//` | root `package main` (`main.go`, `tools.go`, `fixadvice.go`) → `cmd/main.go` + `internal//`; `internal/kube/` matches. Lives in the `GameplanePanel/mcp` submodule; the layout is tracked there. | -| `operator` | Service | `cmd/main.go` + `internal//` | matches; `internal/controller/` is one flat package of 258 `.go` files, 73 of them non-test (spec 028 splits it); `api/v1alpha1/` see §3 | +| `operator` | Service | `cmd/main.go` + `internal//` | matches; `internal/controller/` is one flat package of 275 `.go` files, 77 of them non-test (spec 028 splits it); `api/v1alpha1/` see §3 | | `sentinel` | Service | `cmd/main.go` + `internal//` | `main.go` 1,068 lines at root → `cmd/main.go` + `internal//` | | `telemetry-receiver` | Service | `cmd/main.go` + `internal//` | 14 source files in root `package main` → `cmd/main.go` + `internal//`; `web/` and `design-export/` assets stay | -| `tunnel` | Service | `cmd/main.go` + `internal//` | `main.go` 619 and `playit_reporter.go` 525 lines at root → `cmd/main.go` + `internal//`; `frpc/` (separate build module, not in `go.work`) stays. Lives in the `GameplanePanel/tunnel` submodule. | +| `tunnel` | Service | `cmd/main.go` + `internal//` | `main.go` 681 and `playit_reporter.go` 525 lines at root → `cmd/main.go` + `internal//`; `frpc/` (separate build module, not in `go.work`) stays. Lives in the `GameplanePanel/tunnel` submodule. | | `gp-module` | CLI tool | `cmd/gp-module/` + `internal//` | matches; `pkg/` holds the 5 packages `api` and `test/e2e` import | | `i18n` | Library + CLI | flat root package + `cmd/i18n-check/` | matches (see §3) | | `gameaction` | Library | flat root package | matches | @@ -109,7 +109,7 @@ makes. | `themepkg` | Library | flat root package | matches | | `bundlefetch` | Library | `oci/`, `verify/`, `source/` packages | matches | | `test/e2e` | Test suite | root package + `internal//` | matches (see §3) | -| `web` | Web app | `src/pages/` + route definitions in `src/routes/` | `src/pages/` has started (`ClusterDetail.tsx`, `Nodes.tsx`); most screens still live in `src/routes/` → move each to `src/pages/.tsx`; screens over 500 lines to split: `AdminSettings.tsx` 2,290, `CreateServer.tsx` 1,448, `tabs/Mods.tsx` 1,291, `tabs/settings/Networking.tsx` 1,055, `ThemeSettings.tsx` 886, `Users.tsx` 825, `Servers.tsx` 674, `tabs/settings/ShareLinks.tsx` 658, `tabs/Files.tsx` 657, `Backups.tsx` 642, `Dashboard.tsx` 599 | +| `web` | Web app | `src/pages/` + route definitions in `src/routes/` | `src/pages/` has started (`ClusterDetail.tsx`, `Nodes.tsx`); most screens still live in `src/routes/` → move each to `src/pages/.tsx`; screens over 500 lines to split: `AdminSettings.tsx` 2,098, `CreateServer.tsx` 1,488, `tabs/Mods.tsx` 1,291, `tabs/settings/Networking.tsx` 1,059, `ThemeSettings.tsx` 886, `Users.tsx` 1,045, `Servers.tsx` 695, `tabs/settings/ShareLinks.tsx` 705, `tabs/Files.tsx` 767, `Backups.tsx` 670, `Dashboard.tsx` 599 | ## 3. Exceptions diff --git a/docs/module-authoring.md b/docs/module-authoring.md index b35420cab..1c42902e0 100644 --- a/docs/module-authoring.md +++ b/docs/module-authoring.md @@ -1094,7 +1094,7 @@ The agent automatically selects the appropriate adapter based on game identifier #### CLI (Container Stdin / Local Execution) Console access over the container's stdin/PTY or local process execution. -Per the resolution recorded in `OPEN-DECISIONS.md` (Option A): +Per the resolution recorded in `specs/done_015-top-steam-game-modules/OPEN-DECISIONS.md` (Option A): - The web dashboard console continues to attach directly via Kubernetes pod-attach / PTY (`consoleMode: pty`). - The agent executes lifecycle stop sequences, health checks, and scheduled commands locally via standard input (Unix FIFO pipe or local process execution) without requiring remote TCP networking or an external password secret: diff --git a/docs/oidc.md b/docs/oidc.md index d26cb13b3..3e0d22f4d 100644 --- a/docs/oidc.md +++ b/docs/oidc.md @@ -349,7 +349,7 @@ Setting a role by hand and returning a user to SSO control are both written to t The Authentication page edits the rule list as an ordered list: add, remove, reorder, and pick the role from the existing roles. Saving a rule list in the dashboard replaces the old per-role form for that provider. For the Helm provider, the dashboard override replaces the whole Helm rule list and fallback; **Reset to Helm default** removes the override. -The rule editor, the role-source badge and the Return to SSO control action are part of the dashboard build for this feature. Until that build ships, the API (`PUT /admin/config/auth`, `PATCH /users/{id}` with `roleSource`) and Helm behavior above applies, and the per-role override steps later in this page describe the dashboard as it works today. +The rule editor, the role-source badge and the Return to SSO control action are in the dashboard. For the Helm provider, the dashboard override replaces the whole Helm rule list and fallback, as the steps below describe. ### Audit Log Reasons @@ -500,29 +500,25 @@ Once a Gameplane instance is running with Helm-seeded role mappings, admins can 2. Locate the Helm-configured provider section (displayed as read-only) -3. For each role (`admin`, `operator`, `viewer`), you'll see: - - The **Helm-seeded value** (groups configured at install time) - - An option to **override** this list +3. Find the role rule override card under the Helm-seeded provider. Before an override it shows the Helm rules and fallback read-only, with an **Override** button. -4. Click the override button for a role and enter a comma-separated list of group names: - - Example: for the admin role, enter `gameplane-admins, infrastructure-team, devops-leads` - - An empty list (`[]`) is valid and means "nobody gets this role from a group match" +4. Click **Override**. The card fills the ordered rule editor and fallback with the Helm values. Add, remove or reorder rules (each rule is a group and a role) and set the fallback. -5. Click **Save** +5. Click **Save role rules**. The override takes effect immediately on the very next OIDC login for that role — no API restart, no `helm upgrade`, no redeployment. Users who already hold that role keep it on their current session; users on new logins are assigned roles based on the updated mapping. ### Reset a Role Back to Its Helm Default -If you've overridden a role's group list and later want to restore the original Helm-seeded value: +If you've overridden the Helm rules and want to restore the Helm-seeded rules and fallback: 1. Navigate to **Admin Settings → Authentication** -2. For the role you want to reset, click the **reset** button (shown only if the role is currently overridden) +2. On the override card, click **Reset to Helm default**. This changes only the draft. -3. Confirm the action +3. Click **Save role rules**. -The role is immediately restored to the Helm-seeded group list. If users are currently logged in with that role, they keep it on their current session; on next login, the role assignment uses the reset mapping. +The Helm rules and fallback apply from the next sign-in. Users already signed in keep their current role until their next sign-in. ### Precedence: Most-Privileged Match Wins (Per-Role Form Only) diff --git a/docs/roadmap.md b/docs/roadmap.md index c005fc99f..cca772301 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -218,7 +218,7 @@ it on a genuine connection attempt. Opt-in per server via `spec.idle.wakeOnConne - Costs one small pod per sleeping server, which is why it is opt-in. **Honest limitations:** Only Minecraft and Terraria get real parsing; tModLoader -also declares the Terraria parser. The other 26 of the 29 catalog modules use the +also declares the Terraria parser. The other 27 of the 30 catalog modules use the `generic` default (they hold no connection to parse), and hostport is asymmetric as described. #### Read-only MCP server (PR #105) (shipped v0.2.0-beta.6) @@ -333,10 +333,10 @@ the `api.oidc.*` Helm values. The tab's own UI is tracked for v1.1. Constitution IV requires a `specs.md` file per game module documenting the template's authoring and configuration — the game module itself, not its join-protocol wire format. Those specification files belong in the -`gameplane-module` submodule repo (e.g., `modules/minecraft-java/specs.md`), +`GameplanePanel/module` submodule repo (e.g., `modules/minecraft-java/specs.md`), are tracked there in the module repository rather than in this main repo, and -are a known incomplete item for v1. As of 2026-10-14, 26 of the 29 modules have -a `specs.md`; `enshrouded`, `minecraft-java` and `v-rising` do not yet. See the +are a known incomplete item for v1. As of 2026-11-28, 28 of the 30 modules have +a `specs.md`; `enshrouded` and `v-rising` do not yet. See the module submodule's project board for status. --- @@ -359,8 +359,9 @@ canonical per-module status: wire-protocol formats, each with a named unblocking artifact (packet capture, reverse-engineering session, or anti-cheat analysis). They are candidates for future protocol work once documentation becomes available. -- **2 modules** are permanently out-of-scope-by-design due to architectural +- **3 modules** are permanently out-of-scope-by-design due to architectural constraints (`valheim` routes through Steam Datagram Relay; - `dayz` requires BattlEye anti-cheat validation before join completion). + `dayz` requires BattlEye anti-cheat validation before join completion; + `minecraft-proxy` only forwards logins to a backend server, so it has no join test of its own). -Total: 29 modules. +Total: 30 modules. diff --git a/docs/security.md b/docs/security.md index 180c69c13..ef0e1248d 100644 --- a/docs/security.md +++ b/docs/security.md @@ -909,7 +909,7 @@ through the Steam Web API (`ISteamUser/GetPlayerSummaries/v2`, batched up to moderation: kick, ban and unban key on the Steam ID alone, so a name change or a spoofed display name cannot change who is acted on. - **Failure mode.** If the key is unset, Steam is unreachable, or a call times - out (the lookup has a per-request budget of about 1.5 seconds), the player + out (the lookup has a per-request budget of 2 seconds by default, set by `GAMEPLANE_STEAM_TIMEOUT`), the player list falls back to raw Steam IDs. The player list is never blocked or failed by the lookup. @@ -1034,7 +1034,7 @@ termination is not clean. Default timeout budget is ≤30 minutes. Documented exceptions with inline justification comments: -- The e2e jobs in ci.yaml run at 45 to 105 minutes: most buckets at 60 or 75 minutes (the `e2e-go` jobs use a +- The e2e jobs in ci.yaml run at 15 to 105 minutes: most buckets at 60 or 75 minutes (the `e2e-go` jobs use a `job_timeout` matrix value), `e2e-upgrade` at 85 and `e2e-postgres` at 105. E2E test suites on kind clusters are inherently slow; the budgets are measured from prior runs. @@ -1370,7 +1370,7 @@ deployments. Secrets Gameplane reads or creates, by convention: -- `gameplane--rcon` — per-game RCON password, created by operator +- `-rcon` — per-game RCON password, created by operator - `gameplane-agent-ca` — CA bundle the API trusts - `gameplane-agent-client` — API's client cert/key - `gameplane-oidc` — OIDC client secret (user-supplied) diff --git a/gameaction/specs.md b/gameaction/specs.md index aa5f5570a..a6b38f80e 100644 --- a/gameaction/specs.md +++ b/gameaction/specs.md @@ -169,7 +169,7 @@ No external modules. ## References -- **CRD types:** `operator/api/v1alpha1/gametemplate_types.go` — `ActionParamSpec`, `ActionSpec` +- **CRD types:** `operator/api/v1alpha1/gametemplate_types.go` — `ActionParamSpec`, `ServerActionSpec` - **API usage:** `api/internal/ws/actions.go` — WebSocket action execution - **Agent usage:** `agent/internal/actions/actions.go` — RCON action execution - **Module authoring:** `docs/module-authoring.md` — defines the `actions` field in `template.yaml` diff --git a/operator/specs.md b/operator/specs.md index 9e6ec03f5..70195367c 100644 --- a/operator/specs.md +++ b/operator/specs.md @@ -312,18 +312,18 @@ operator/ ├── api/v1alpha1/ │ CRD type definitions (gameserver_types.go, gametemplate_types.go, backup_types.go, │ backupschedule_types.go, restore_types.go, module_types.go, modulesource_types.go, -│ cluster_types.go, networkcapture_types.go) and generated deepcopy helpers (zz_generated.deepcopy.go). +│ cluster_types.go, networkcapture_types.go, backupexport_types.go) and generated deepcopy helpers (zz_generated.deepcopy.go). │ Edited manually; regenerate deepcopy + YAML after any type edit. │ ├── config/ -│ ├── crd/ Generated CRD YAML (9 kinds). Do not hand-edit. +│ ├── crd/ Generated CRD YAML (10 kinds). Do not hand-edit. │ ├── rbac/ Generated ServiceAccount, Role, RoleBinding, ClusterRole, │ │ ClusterRoleBinding. Do not hand-edit. │ ├── manager/ Manager deployment, StatefulSet, and RBAC references. │ └── samples/ Sample GameServer, GameTemplate, Backup, etc. CRs for testing. │ ├── internal/ -│ ├── controller/ Reconciler implementations (9 controllers + co-located envtest). +│ ├── controller/ Reconciler implementations (10 controllers + co-located envtest). │ │ ├── gameserver_controller.go Reconciles GameServer → StatefulSet+Service+PVC │ │ ├── gameserver_*.go Split concerns: config, modcreds, rcon, restart, │ │ │ wipe, version, stop_attach, node, status, extravolumes @@ -771,10 +771,10 @@ until cancellation or replacement because it may have partially cleared data. ### Sidecar client (operator/internal/agent/sidecar_capture.go) - **`SidecarCaptureClient interface`** — injected into NetworkCaptureReconciler; abstracts mTLS communication with capture sidecar's `:9091` HTTP control endpoint (testable; tests inject a stub) - - `StartCapture(ctx, namespace, serverName, captureID string, filter *string, maxDurationSeconds, maxSizeBytes int64) error` — POST `/captures/{id}/start` on sidecar - - `StopCapture(ctx, namespace, serverName, captureID string) error` — POST `/captures/{id}/stop` on sidecar - - `GetCaptureStatus(ctx, namespace, serverName, captureID string) (phase string, packetsWritten, bytesWritten int64, message string, err error)` — GET `/captures/{id}/status` on sidecar; polls current state during Running phase - - `DeleteCaptureFile(ctx, namespace, serverName, captureID string) error` — added for retention (Phase 6 / US4); removes a capture's backing PCAPNG file once its TTL elapses. Implemented end to end: `DELETE /captures/{id}` on the sidecar (`capture-sidecar/internal/httpserver/handlers.go`), calling `CaptureClient.DeleteCaptureFile` (`operator/internal/agent/sidecar_capture.go`) — success on 204, treated as idempotent on 404 (already gone), a distinguishable error on 409 (still running). + - `StartCapture(ctx, namespace, serverName, captureID, serverUID, captureUID string, filter *string, maxDurationSeconds, maxSizeBytes int64) error` — POST `/captures/{id}/start` on sidecar + - `StopCapture(ctx, namespace, serverName, captureID, serverUID, captureUID string) error` — POST `/captures/{id}/stop` on sidecar + - `GetCaptureStatus(ctx, namespace, serverName, captureID, serverUID, captureUID string) (phase string, packetsWritten, bytesWritten int64, message string, err error)` — GET `/captures/{id}/status` on sidecar; polls current state during Running phase + - `DeleteCaptureFile(ctx, namespace, serverName, captureID, serverUID, captureUID string) error` — added for retention (Phase 6 / US4); removes a capture's backing PCAPNG file once its TTL elapses. Implemented end to end: `DELETE /captures/{id}` on the sidecar (`capture-sidecar/internal/httpserver/handlers.go`), calling `CaptureClient.DeleteCaptureFile` (`operator/internal/agent/sidecar_capture.go`) — success on 204, treated as idempotent on 404 (already gone), a distinguishable error on 409 (still running). - **`CaptureClient struct`** — production implementation of SidecarCaptureClient - `NewCaptureClient(agent *Client) *CaptureClient` — factory; reuses agent's existing mTLS http.Client (same CA cert/client cert/private key material) - `Disabled bool` flag — set to true if no mTLS material provided (graceful degradation). `StartCapture`, `StopCapture`, and `DeleteCaptureFile` return `nil` on Disabled=true; `GetCaptureStatus` instead returns `ErrCaptureClientDisabled` so a Pending-phase reconcile can tell "no mTLS configured" apart from a real sidecar answer. @@ -785,8 +785,8 @@ until cancellation or replacement because it may have partially cleared data. - **agent_certs.go:** Generate per-GameServer CA-signed mTLS server cert for agent sidecar (operator CA cert/key injected via flags). - **agent_rbac.go:** Create per-GameServer ServiceAccount + Role for the agent sidecar (used to verify token). -- **internal/kube/capture.go:** Kubernetes client helper functions for NetworkCapture CRD operations (API-tier use): - - `CreateNetworkCapture(ctx, ns, captureID, serverName string, filter *string, maxDuration *metav1.Duration, maxSize *resource.Quantity, ttlSecondsAfterFinished *int32) (*NetworkCapture, error)` — creates NetworkCapture CR with Pending phase; sets ownerRef for cascade delete +- **api/internal/kube/capture.go:** Kubernetes client helper methods on `*Client` for NetworkCapture CRD operations (API-tier use): + - `(*Client) CreateNetworkCapture(ctx, ns, captureID, serverName string, serverUID types.UID, filter *string, maxDuration *metav1.Duration, maxSize *resource.Quantity, ttlSecondsAfterFinished *int32) (*NetworkCapture, error)` — creates NetworkCapture CR with Pending phase; sets ownerRef for cascade delete - `GetNetworkCapture(ctx, ns, name string) (*NetworkCapture, error)` — fetches by namespace/name; returns nil if not found - `ListNetworkCaptures(ctx, ns, serverName string) ([]NetworkCapture, error)` — lists all captures in namespace; filters by spec.serverRef.name on client side - `DeleteNetworkCapture(ctx, ns, name string) error` — deletes NetworkCapture by namespace/name diff --git a/telemetryschema/specs.md b/telemetryschema/specs.md index ddc65d2b0..beb7a71af 100644 --- a/telemetryschema/specs.md +++ b/telemetryschema/specs.md @@ -146,4 +146,4 @@ A module added to the chart catalog after a receiver was built counts as `custom ## Testing & coverage -Unit tests only (`decode_test.go`, `enums_test.go`, `catalog_test.go`, `sign_test.go`, `pow_test.go`). They cover every reject case of the receiver's original decoder, every `ext` rule, the band boundaries, catalog membership, a fixed key-derivation vector, the sign and verify round trip, single-byte tampering, malformed headers and keys, and different IDs deriving different keys. `pow_test.go` pins fixed hash vectors (the hash input, the bit count and the smallest-nonce search order), the solver's difficulty and context errors, and every malformed-header case of `ParsePoW`. Coverage gate: 90% total, set in `.testcoverage.yml` and enforced by `make cover-go-check`. +Unit tests only (`decode_test.go`, `decode_schema2_test.go`, `decode_k8s_cap_test.go`, `enums_test.go`, `catalog_test.go`, `sign_test.go`, `pow_test.go`). They cover every reject case of the receiver's original decoder, every `ext` rule, the band boundaries, catalog membership, a fixed key-derivation vector, the sign and verify round trip, single-byte tampering, malformed headers and keys, and different IDs deriving different keys. `pow_test.go` pins fixed hash vectors (the hash input, the bit count and the smallest-nonce search order), the solver's difficulty and context errors, and every malformed-header case of `ParsePoW`. Coverage gate: 90% total, set in `.testcoverage.yml` and enforced by `make cover-go-check`. diff --git a/test/e2e/specs.md b/test/e2e/specs.md index 4d2c2a80e..69dce10e5 100644 --- a/test/e2e/specs.md +++ b/test/e2e/specs.md @@ -44,7 +44,7 @@ after the Restricted upgrade and after capture completion and revocation. The `test/e2e` module is Gameplane's end-to-end test suite: it stands up a real (kind-based) Kubernetes cluster, installs the Helm chart, and drives the operator/api/agent/sentinel stack as real components rather than mocks — CRDs applied through the typed/dynamic client, HTTP calls through a real port-forward, RCON/wire-protocol joins against real game server containers. Where the other modules' test tiers (unit, envtest) prove a component's own logic in isolation, this module proves the whole product works together on a cluster shaped like the ones users actually run. -It was one of three `go.work` modules without CI lint coverage until this feature (`api`, `agent`, and `test/e2e` — see FR-001); all 13 `go.work` members (`netguard`, `gameaction`, `gameproto`, `operator`, `agent`, `api`, `sentinel`, `audit-syslog-bridge`, `telemetry-receiver`, `mcp-server`, `svcutil`, `tunnel`, and `test/e2e`) are golangci-lint gated in CI now — see the `lint` job's matrix in `.github/workflows/ci.yaml`. `test/e2e` lints with `--build-tags=e2e`, same tier as `operator`/`api`'s `--build-tags=envtest`, run as their own step so the catch-all lint step excludes all three and nothing is linted twice. +It was one of three `go.work` modules without CI lint coverage until this feature (`api`, `agent`, and `test/e2e` — see FR-001); all 14 `go.work` members (`netguard`, `gameaction`, `gameproto`, `telemetryschema`, `themepkg`, `bundlefetch`, `i18n`, `gp-module`, `operator`, `agent`, `api`, `sentinel`, `telemetry-receiver`, and `test/e2e`) are golangci-lint gated in CI now — see the `lint` job's matrix in `.github/workflows/ci.yaml`. `test/e2e` lints with `--build-tags=e2e`, same tier as `operator`/`api`'s `--build-tags=envtest`, run as their own step so the catch-all lint step excludes all three and nothing is linted twice. ### Modpack drills (spec 035) @@ -75,7 +75,7 @@ complete pinned render inputs and source-template preservation for CSI restore. - The optional-components lifecycle's `frp-identity-health` subtest runs two same-template TCP/UDP echo GameServers through one real frps. It asserts backend identity, registration rejection, replacement isolation, invalid credentials, relay outage/recovery and secret-free logs. It shares the lifecycle's controlled fixture and serial bucket; no extra top-level test or login budget is introduced. - Boot and tear down (or reuse) a kind cluster, install the working-tree Helm chart, and wait for every component to come up healthy. -- Exercise the full CRD lifecycle for all 8 kinds (GameServer, GameTemplate, Backup, BackupSchedule, Restore, Module, ModuleSource, Cluster) against a real API server and operator. +- Exercise the full CRD lifecycle for all 10 CRD kinds (GameServer, GameTemplate, Backup, BackupExport, BackupSchedule, Restore, Module, ModuleSource, Cluster, NetworkCapture) against a real API server and operator. - Drive the REST + WebSocket API as a real HTTP client would: login, session/CSRF handling, RBAC matrix checks, console/PTY/log streaming, file upload/download. - Launch real game server containers and either speak their wire protocol directly (the CI `bot-fast` bucket: Minecraft, Terraria, Garry's Mod — narrower than `fastGameSet`'s manual/local default scope; see `test/e2e/internal/specs.md`) or query them, proving a Gameplane-managed server is genuinely playable, not merely "Running" in Kubernetes. The per-game protocol clients and the shared probe harness that does this live one level down, in `test/e2e/internal/` — see `test/e2e/internal/specs.md` for that layer's Path A / Path B contract, protocol clients, and JoinDepth model. This file does not duplicate that; it covers the outer suite that hosts and buckets those probes. - Validate multi-cluster dispatch, upgrade-from-previous-release, wake-on-connect, module signing/SSRF rejection, and backup/restore round trips end to end. @@ -237,9 +237,9 @@ value after each flip, and the audit rows for the flip and the refusal. ## The `//go:build e2e` boundary — why this module is invisible to ordinary tooling -53 of this directory's 82 `.go` files carry `//go:build e2e` (every `*_test.go` file plus the shared non-test helpers they depend on: `env.go`, `gameprobe_job.go`). Without `-tags=e2e`, the Go toolchain — `go build ./...`, `go vet ./...`, `gofmt`, an editor's language server, a plain `go test ./...` — silently skips every one of those files. This has a direct, previously-burned consequence documented project-wide in `MEMORY.md`: **`go vet ./...` does not compile envtest/e2e-tagged files**, so a bad import or a broken reference introduced here passes local checks and every other CI job cleanly, and only reddens the run once the dedicated e2e job compiles with the tag. There is no cheap local signal for a broken build in this module short of `go vet -tags=e2e ./...` (or, per the project's "nothing runs locally" rule, waiting for CI). Treat any change under `test/e2e/` as unverified until the e2e CI job runs it. +All 146 top-level `.go` files in this directory carry `//go:build e2e` (every `*_test.go` file plus the shared non-test helpers they depend on: `env.go`, `gameprobe_job.go`). Without `-tags=e2e`, the Go toolchain — `go build ./...`, `go vet ./...`, `gofmt`, an editor's language server, a plain `go test ./...` — silently skips every one of those files. This has a direct, previously-burned consequence documented project-wide in `MEMORY.md`: **`go vet ./...` does not compile envtest/e2e-tagged files**, so a bad import or a broken reference introduced here passes local checks and every other CI job cleanly, and only reddens the run once the dedicated e2e job compiles with the tag. There is no cheap local signal for a broken build in this module short of `go vet -tags=e2e ./...` (or, per the project's "nothing runs locally" rule, waiting for CI). Treat any change under `test/e2e/` as unverified until the e2e CI job runs it. -The golangci-lint job mirrors this: it must be invoked with `--build-tags=e2e` or it lints an effectively-empty package (only the 29 untagged files: `Dockerfile`-adjacent Go tooling, `internal/` package code not gated by the tag, fixtures, etc.). +The golangci-lint job mirrors this: it must be invoked with `--build-tags=e2e` or it lints an effectively-empty package (the top-level package has no untagged files; the 45 untagged `.go` files under `internal/` and `cmd/` are separate packages). ## The bucket contract — the module's most important invariant @@ -260,7 +260,7 @@ This is a name-matching contract, not a structural one: - **Anchoring matters.** `^(...)$` is deliberate — an unanchored regex would let `TestGameServer` also match `TestGameServer_Cascading`, silently running one bucket's test inside another's job. - **Renaming a `func Test...` breaks CI silently everywhere except the one place that catches it.** If a test is renamed without updating `buckets.sh`, the old name still matches nothing (dropping the test from every bucket) or the new name matches nothing in any bucket (same result) — either way, the compiler, `go vet`, and lint all stay green. The **only** thing that fails is `buckets.sh verify`, run as the dedicated "e2e bucket coverage" CI job: it greps `^func Test[A-Za-z0-9_]+` out of every `*_test.go` file (a flat directory, so a file grep is an exact inventory — see the comment on `suite_tests` in `buckets.sh`), diffs that set against the union of every bucket's list, and fails on any test that's in the suite but in no bucket, in more than one bucket, or bucketed but no longer present (deleted/renamed). -- **New tests must be added to a bucket in the same change.** There is no "unbucketed but intentional" escape hatch beyond the explicit, reviewed `unbucketed()` list in `buckets.sh` (currently empty) — every addition there needs a stated reason. +- **New tests must be added to a bucket in the same change.** There is no "unbucketed but intentional" escape hatch beyond the explicit, reviewed `unbucketed()` list in `buckets.sh` (currently the two hand-run tests `TestGameServer_Modpack_BlockedModManualDownload` and `TestGameServer_Modpack_FTBInstall`) — every addition there needs a stated reason. - **Buckets are cut by login pressure, not feature area.** The API's login rate limiter is per-IP (burst 10, 5/min) and per-username (burst 6, 3/min), and every test in one job shares a single client IP through the shared `kubectl port-forward` — so a bucket's budget is bounded by admin logins, not CPU. `operator` does zero logins and runs wide; each `api-*` bucket stays within roughly 7 admin logins so retries absorb overflow without exhausting the per-user burst. `ratelimit` deliberately drains the shared limiter and is intentionally its own last, non-parallel `go test` invocation so it doesn't starve every other test's logins. ## The `Env` helpers and context threading (`env.go`) diff --git a/web/specs.md b/web/specs.md index 208a67684..20840e4d6 100644 --- a/web/specs.md +++ b/web/specs.md @@ -240,7 +240,7 @@ The old Radix-based `ui/` components that shipped before this rebuild — `butto ### Screens and Routes -1. **Servers Page** (`web/src/routes/Servers.tsx`, 674 lines) +1. **Servers Page** (`web/src/routes/Servers.tsx`, 695 lines) - List all GameServers in a responsive table (desktop ≥768px) or stacked cards (mobile <768px) - Renders server phase, game icon, player count, resource usage, and uptime via StatCard compositions - Filter by phase (Running/Stopped/Pending/Failed), game template, and namespace via FilterPopover @@ -248,7 +248,7 @@ The old Radix-based `ui/` components that shipped before this rebuild — `butto - Server count summary via StatCard at the top; search box using HeroUI Input - Action menu (clone, transfer, wipe, delete) via ServerActionsMenu composition (uses DropdownMenu) -2. **ServerDetail Page** (`web/src/routes/ServerDetail.tsx`, 407 lines) +2. **ServerDetail Page** (`web/src/routes/ServerDetail.tsx`, 413 lines) - Full server view with header showing phase chip, uptime, player count, and action buttons - Both the header and Overview offer Stop during Pending and Starting to users with control access to that server. - Tabbed interface (HeroUI Tabs) routing to eleven sub-views: Overview, Events, Console, Logs, Files, Mods, Modpacks, Players, Backups, Capture, Settings @@ -294,7 +294,7 @@ Six of the nine ServerDetail tabs are rebuilt in this slice: - Filter state (all/info/warnings) via HeroUI Button - Uses HeroUI Button, Card (line 3) -3. **Console** (`web/src/routes/tabs/Console.tsx`, 175 lines) +3. **Console** (`web/src/routes/tabs/Console.tsx`, 176 lines) - Interactive RCON/PTY terminal (xterm.js, lazy-loaded, NOT rebuilt — uses existing engine) - LoadingCard during template resolution (line 28); ErrorCard if no console available (line 35) - Uses ui/ LoadingCard, ErrorCard only (lines 4–5); console I/O engine unchanged @@ -302,14 +302,14 @@ Six of the nine ServerDetail tabs are rebuilt in this slice: - RCON text replies normalize LF and CRLF to terminal CRLF, preserving indentation and content so each line starts in column zero. PTY output retains its raw terminal line endings and control sequences. - Command bar under the terminal (`ConsoleShell.tsx`): Send or Enter submits; ArrowUp/ArrowDown recall the last 100 commands sent from this tab (consecutive repeats collapsed), and ArrowDown past the newest restores the unsent line. History lives per mount and is not persisted -4. **Logs** (`web/src/routes/tabs/Logs.tsx`, 288 lines) +4. **Logs** (`web/src/routes/tabs/Logs.tsx`, 307 lines) - Pod stdout or configured game log file stream (WebSocket, NOT rebuilt — uses existing engine) - Requests last 500 lines of history via `?tail=500` query parameter before streaming new output - Search/filter input via HeroUI Input; download button - Virtualized log viewer (TanStack Virtual, NOT rebuilt) - Uses HeroUI Button, Input only (line 4); log streaming engine unchanged -5. **Files** (`web/src/routes/tabs/Files.tsx`, 657 lines) +5. **Files** (`web/src/routes/tabs/Files.tsx`, 767 lines) - File browser and editor (Monaco, lazy-loaded, NOT rebuilt) - Create folder/file dialogs via HeroUI Modal/ModalBackdrop/ModalContainer/ModalDialog/ModalHeader/ModalBody/ModalFooter (lines 9–19) - Delete confirmation via ui/ ConfirmDialog (line 35, used at line 408) @@ -401,13 +401,13 @@ CloneServerDialog, TransferServerDialog and WipeServerDialog do not route throug - Rendering strategy differs by game: ARK/Project Zomboid use idList editor; others show file list - Uses HeroUI Button, Input, Chip; ui/ ConfirmDialog (for destructive actions) -2. **Modpacks Tab** (`web/src/routes/tabs/Modpacks.tsx`, 175 lines) +2. **Modpacks Tab** (`web/src/routes/tabs/Modpacks.tsx`, 402 lines) - Modpack-capable games render a selector/browser - Select active pack, view pack contents, toggle mods within a pack - Uses HeroUI Select, Table, Button, Chip - "All loaders" switch (spec 035 FR-014, env-mode registries only, off by default): search drops the server's loader and Minecraft version filters, the install picker lists every version a template version entry runs ("Runs on …"), and the confirmation warns when the install switches the server version (sent as `serverVersion`). Change version stays filtered. -3. **Backups Tab** (`web/src/routes/tabs/Backups.tsx`, 290 lines) +3. **Backups Tab** (`web/src/routes/tabs/Backups.tsx`, 386 lines) - Per-server backup list (snapshots created via the /backups page or on-demand) - Users with schedule write access can edit or delete standalone schedules here. The **Managed by server settings** action opens the selected server’s **Settings → Scheduled backups**, where users with server write access can edit its inline backup policy. - Table columns: backup name, phase (Pending/Succeeded/Failed), size, completion time, actions @@ -415,7 +415,7 @@ CloneServerDialog, TransferServerDialog and WipeServerDialog do not route throug - Open backup detail drawer, trigger restore dialog, delete backup - Uses HeroUI Table, Button, Modal (restore trigger), ui/ PhaseChip -4. **Settings Tab** (`web/src/routes/tabs/Settings.tsx`, 396 lines) +4. **Settings Tab** (`web/src/routes/tabs/Settings.tsx`, 429 lines) - Sub-section navigation tabs (11 sections below) via HeroUI Tabs - Opening Settings from the tab bar starts in **General**. The managed schedule action passes `initialSection="backups"` to start in **Scheduled backups**. - Layout: left sidebar with section buttons, right panel for section content @@ -441,7 +441,7 @@ All 11 sections render form controls from HeroUI (TextField, Select, Slider, Swi 6. **Lifecycle** (`web/src/routes/tabs/settings/Lifecycle.tsx`) — Auto-pause threshold, idle sleep settings, quiesce strategy selector via HeroUI Switch/Select/Slider. Inside the idle settings, a "Wake on connect" switch writes `spec.idle.wakeOnConnect`, which arms the wake sentinel. It is disabled when the template advertises no port whose `wakeProtocol` can wake the server (every advertised port is `none`, mirroring the operator's `wakeOnConnectEligible`), unless the server is already armed, so it can still be turned off. Switching idle auto-sleep off and on keeps `wakeOnConnect`. 7. **Scheduled backups** (`web/src/routes/tabs/settings/Backups.tsx`) — Retention days selector, retention policy dropdown via HeroUI Select/TextField 8. **Network capture** (`web/src/routes/tabs/settings/NetworkCapture.tsx`) — Capture enabled toggle, BPF filter input, retention policy via HeroUI Switch/TextField/Select; warning banner via ui/ component -9. **Placement** (`web/src/routes/tabs/settings/Placement.tsx`) — Node affinity rules, pod-node-selector builder via HeroUI form components +9. **Placement** (`web/src/routes/tabs/settings/Placement.tsx`) — Raw-JSON Monaco editors for `spec.tolerations` and `spec.affinity` (no node-selector builder) 10. **RBAC & access** (`web/src/routes/tabs/settings/Access.tsx`) — Per-role read/exec/admin permissions toggle matrix via HeroUI Switch grid 11. **Danger zone** (`web/src/routes/tabs/settings/Danger.tsx`) — Destructive action buttons (Delete server, Wipe world, Transfer ownership to another user) wired to confirmation dialogs via HeroUI Button (danger variant) + ui/ ConfirmDialog @@ -502,7 +502,7 @@ Every file in slice 2b imports **only** from `@heroui/react` and `@/components/u ### Screens and Routes -1. **Create Server Wizard** (`web/src/routes/CreateServer.tsx`, 99,594 bytes) +1. **Create Server Wizard** (`web/src/routes/CreateServer.tsx`, 101,809 bytes) - Multi-step form guiding server creation through five steps; each step has validation, back/next navigation, and error display - Step 1: Server name and template selection (game type pick) - Step 2: Version selection (pick released/beta/unstable version per template) @@ -519,7 +519,7 @@ Every file in slice 2b imports **only** from `@heroui/react` and `@/components/u - Filter by game type or source; search by name - InstallDialog, UploadModuleDialog, SourceDialog (add/edit module source) for workflow UI -3. **Backups Management Page** (`web/src/routes/Backups.tsx`, 43,135 bytes) +3. **Backups Management Page** (`web/src/routes/Backups.tsx`, 45,430 bytes) - Tabbed interface with three sub-views: Backups (index), Schedules, Restores - All three table empty states use consistent horizontal and vertical padding, centered muted text, and wrapping for longer messages, including filtered and unavailable-data states. Empty messages use the table scroll viewport width and remain visible while wide column headers scroll horizontally. - **Backups tab:** List all Backup CRs (manual + scheduled); filter by server/status; view backup metadata (size, created/expires); select row to open detail drawer, or restore — no inline delete action on the row @@ -663,11 +663,11 @@ Every file in slice 2b imports **only** from `@heroui/react` and `@/components/u ### Backup-Related Components (`web/src/components/backups/`) -- **BackupRow.tsx** (49 lines) — Single table row rendering one Backup CR; ID, server, phase chip, size, timestamps +- **BackupRow.tsx** (55 lines) — Single table row rendering one Backup CR; ID, server, phase chip, size, timestamps - **BackupDetailDrawer.tsx** (169 lines) — Slide-out detail panel for backup metadata - **BackupFilters.tsx** (145 lines) — Filter controls (search box, server picker, phase filter — no date-range filter) - **RestoreDialog.tsx** (221 lines) — Modal form for restore workflow (source backup, destination server, confirm) -- **ScheduleForm.tsx** (184 lines) — Inline (non-modal) form for creating a schedule (cron expression, retention) — no edit mode +- **ScheduleForm.tsx** (222 lines) — Inline (non-modal) form for creating a schedule (cron expression, retention) — no edit mode - **RetentionFields.tsx** (107 lines) — Sub-component with a numeric count input per retention bucket (keep last/hourly/daily/weekly/monthly/yearly) - **ErrorBanner.tsx** (15 lines) — Error display for backup/schedule operations @@ -803,24 +803,24 @@ eslint.config.js # JavaScript, React Hooks and FormatJS rules package.json # @gameplane/web v0.5.0; dev: vite, npm scripts for build/test/lint ``` -## SSO Role Rules and Role Source (spec 034) — pending dashboard build +## SSO Role Rules and Role Source (spec 034) -**Status:** pending the dashboard build. The API and Helm parts are in place. The screens below are not built yet, and the design in `design.fig` is not done. Per core rule 1, the design comes first: the rule editor, the role-source badge and the "Return to SSO control" action are designed through the Pencil MCP (on the maintainer's machine, via a local-agent prompt), then exported to `assets/design-export/`, then built. This section will be revised when those screens land. +**Status:** built. The rule editor is `web/src/components/ui/admin/RoleRulesEditor.tsx` (used by `AdminSettings.tsx`), and `web/src/routes/Users.tsx` shows the role-source badges and the Return to SSO control action. **Already in place:** - `web/src/types.ts`: `UserRoleSource = "sso" | "sso_pending" | "manual"` and `roleSource?: UserRoleSource` on `User` (the API always sends it; optional only for older typed payloads). - `web/src/lib/endpoints.ts`: `roleSource?: "sso"` on the `UserUpdate` body type (the "Return to SSO control" request body; the API refuses it together with `role`). -**Rule editor (Authentication, planned):** -- Replaces the per-role override card (`RoleMappingOverridesCard` in `AdminSettings.tsx`) for dashboard providers and for the Helm provider's override. Rules are one ordered list: each row is a group (exact, case-sensitive text) and a role picked from the existing roles, with add, remove and reorder. +**Rule editor (Authentication):** +- Replaces the earlier per-role override card for dashboard providers and for the Helm provider's override (the Helm override now lives in `RoleRuleOverrideCard` in `AdminSettings.tsx`). Rules are one ordered list: each row is a group (exact, case-sensitive text) and a role picked from the existing roles, with add, remove and reorder. - The first rule whose group matches wins. The list states this in its helper text, and a later row with a group already used above shows a warning that it can never match. - The fallback control offers "viewer" (empty), "deny", and every existing role. - Save is refused for a role that does not exist. Deleting a role that a rule or fallback uses shows the API's `server.roles.in_use_by_sso` message, which names the provider. - The Helm provider: the override replaces the whole Helm rule list and fallback. "Reset to Helm default" removes the override and is shown only when one exists. -- The admin-role confirmation (FR-015, `AdminMappingConfirmDialog`) applies to any rule whose role is `admin` and is added or changed. +- The admin-role confirmation (FR-015, `ConfirmAdminMappingDialog`) applies to any rule whose role is `admin` and is added or changed. - A provider with both old `roleMappings` and `roleRules` cannot be saved; the form saves old-form providers in the rule form. -**Users page (planned):** +**Users page:** - For SSO-linked users (`provider` is `oidc` in `GET /users`), show a role-source badge: "From SSO" for `sso`, "From SSO (applies at next sign-in)" for `sso_pending`, "Set by hand" for `manual`. Local users show no badge and no action. - "Return to SSO control" is offered on hand-set SSO users, gated by the existing `users:manage` check, and sends `PATCH /users/{id}` with `{ roleSource: "sso" }`. The result shows the `sso_pending` badge at once. - Changing a role on this page marks the user "Set by hand" (the API does this on every role change). @@ -948,12 +948,12 @@ A StorageClass is a cluster infrastructure concern, not an authentication concer **Permission gating:** - **Route guard (web/src/router/tree.tsx):** The `/admin` route itself is guarded by `config:manage` permission (admin and operator roles only). -- **AdminSettings.tsx** (OIDC/auth section): The `RoleMappingOverridesCard` component is gated by `config:manage` permission check at render time — since it is an editing surface for role mappings (not read-only display). The route-level and component-level gates are now aligned. +- **AdminSettings.tsx** (OIDC/auth section): The `RoleRuleOverrideCard` component is gated by `config:manage` permission check at render time — since it is an editing surface for role mappings (not read-only display). The route-level and component-level gates are now aligned. - **ClusterConfiguration.tsx** (storage card): Is **not** already admin-only, so it requires an explicit `can(me, "config:read")` permission check on both the query (to avoid 403 errors) and the rendered card (to hide it from viewers lacking permission). Precedent: Dashboard.tsx:51 and Users.tsx:688. **OIDC Role Mapping Overrides (AdminSettings.tsx):** -The `helmOverride` object in the API's `AuthCfg` response (`auth.helmOverride.roleMappings`) allows dashboard users to override the Helm-seeded role mappings **per role**. Each role (admin/operator/viewer) is independently optional: +This describes the legacy per-role override. The current override card (`RoleRuleOverrideCard`) writes `helmOverride.roleRules`, one ordered rule list that replaces the whole Helm rule list and fallback (see the rule editor section above). The API still reads an older `helmOverride.roleMappings` value saved before the rule editor existed (`api/internal/auth/oidc.go`): it overrides the Helm-seeded role mappings **per role**, and each role (admin/operator/viewer) is independently optional: - **Key present** (including empty list `[]`): an override exists, stored in the dashboard database, superseding the Helm value - **Key absent**: no override; the role uses the Helm-seeded value @@ -964,7 +964,7 @@ The `helmOverride` object in the API's `AuthCfg` response (`auth.helmOverride.ro - If absent and Helm-seeded value exists → "From Helm values" - If absent and no Helm-seeded value → "Not configured" -**Per-role UI in RoleMappingOverridesCard (AdminSettings.tsx):** +**Per-role UI (removed; superseded by the rule editor above):** For each role (admin/operator/viewer), the card displays: 1. **Effective mapping:** the list of IdP group names currently mapped (from override if present, else from Helm-seeded) @@ -983,7 +983,7 @@ When no role mappings exist (neither overridden nor Helm-seeded), the card displ Mapping users to the admin role grants full cluster control. The dashboard enforces a two-step confirmation: - **Read-only Helm-seeded path (HelmOIDCProviderCard):** If Helm-seeded role mappings include admin mappings, show a warning banner (no confirm step; the admin already made this decision at deploy time) -- **Editable override path (RoleMappingOverridesCard):** When a user tries to **add** an admin role mapping via the overrides editor, show `ConfirmAdminMappingDialog` +- **Editable override path (RoleRuleOverrideCard):** When a user tries to **add** an admin role mapping via the overrides editor, show `ConfirmAdminMappingDialog` The confirm dialog displays: - A fixed warning banner with exact copy: "Mapping users to the admin role grants full cluster control. Ensure the mapped group contains only authorized personnel. Anyone in these groups gets full admin access from their next login." @@ -1069,7 +1069,7 @@ The API remains authoritative; no role or server-side authorization rule changes ## ServerDetail Settings Sub-sections -Settings tab (`SettingsTab`, `web/src/routes/tabs/Settings.tsx`) displays up to 13 sections in a left sidebar (`SECTIONS` array; Version only when the template has versions, Game configuration only when the template declares a `configSchema` or the server carries config keys; Share links is described after the list): +Settings tab (`SettingsTab`, `web/src/routes/tabs/Settings.tsx`) displays up to 14 sections in a left sidebar (`SECTIONS` array; Version only when the template has versions, Game configuration only when the template declares a `configSchema` or the server carries config keys; Share links is described after the list): Save fetches the latest server and applies only the changes from the original baseline to the draft (`web/src/lib/settingsMerge.ts`). Untouched spec fields, labels, annotations, status and resourceVersion survive concurrent edits. Nested object keys merge independently; arrays are atomic. Divergent changes to the same field, including deleting a concurrently modified field, show the existing reload prompt before any PUT. Clearing config/label/annotation maps removes baseline keys while preserving concurrently added keys. Save waits for the template and validates the entire draft's game configuration regardless of the selected section; section-reported editor validity is retained across navigation. Discard, reload and successful save reset editor state and validity. @@ -1186,7 +1186,7 @@ Each namespace is an object of typed functions building and fetching URLs: - **useThemePreferences.ts** — theme preferences plumbing (feature 016; full behavior documented under "User Theme Customization" above): `useThemePreferences(me?, opts?)` reconciles the backend `preferences` from `/users/me` over the `gameplane-theme-prefs` localStorage cache (backend wins on drift), exposes `preferences` + an optimistic `updatePreferences(patch)` mutation (DOM + cache first, PUT via `Users.updatePreferences`, revert-and-report on failure, replay-on-`online` after connectivity loss), and keeps the DOM attributes (`class`/`data-theme`, `data-theme-preset`, `data-theme-type`, `data-custom-css`) and the `#gameplane-custom-css` overlay (always last in ``; unmounted on logout and on `/login`/`/share/:token`) in sync. Plain helpers exported for routes and the boot script's post-boot path: `isSafeModeActive()` (`?safe-mode=1` or the `gameplane-safe-mode` sessionStorage flag — suspends only the overlay), `readThemePreferences` / `writeThemePreferences`, `normalizeThemePreferences`, `themePreferencesEqual`, `applyThemePreferences`, `unmountCustomCssOverlay`, plus the storage keys/element ids and the `gameplane-theme-error` window event. The inline `theme-boot` script in `index.html` applies the same cache synchronously pre-paint and is the authoritative boot path (never applies cached prefs on `/login` or `/share/:token`). - **servers.ts** — `countByState(items)` (running/stopped/pending/failed counts), `phaseGroups(items)` (items grouped by phase) - **games.ts** — category helpers: `gameCategory(game)`, `resolveCategories(explicit, game)`, `matchesCategory`, `matchesAllCategories`, `categoryFilters(categories)` -- **auth.ts** — `useMe()` (current-user query hook), `hasRole(me, allowed)`, `can(me, perm, ns?, cluster?)` +- **auth.ts** — `useMe()` (current-user query hook), `can(me, perm, ns?, cluster?)` - **config.ts** — admin-config hooks: `useConfig()`, `useUpdateConfigSection(section)`, `useResetRoleMapping()` - **errors.ts** — `errorText(err, fallback?)`, `errorTextWithStatus(err, fallback?)` - **cluster.ts** — `getCurrentCluster()` / `setCurrentCluster()` retain the localStorage-backed infrastructure selection; resource requests use their explicit target instead @@ -1280,14 +1280,14 @@ openEventStream(opts: EventStreamOptions) - `react@19.3.1` — React library - `react-dom@19.3.1` — DOM renderer - `@tanstack/react-router@1.170.46` — file-based routing (via tree.tsx) -- `@tanstack/react-query@5.108.1` — data fetching, caching, invalidation -- `@tanstack/react-virtual@3.14.26` — virtualized lists for large tables -- `@heroui/react@3.2.7` — component library (Button, Card, Modal, Table, Tabs, etc.); underlies every atom in `web/src/components/ui/` +- `@tanstack/react-query@5.108.4` — data fetching, caching, invalidation +- `@tanstack/react-virtual@3.14.28` — virtualized lists for large tables +- `@heroui/react@3.2.8` — component library (Button, Card, Modal, Table, Tabs, etc.); underlies every atom in `web/src/components/ui/` - `@heroui/styles` — HeroUI's semantic token / theme layer, mapped to Gameplane brand tokens (see `specs/done_014-heroui-web-rebuild/contracts/theme-tokens.md`) - `clsx@2.1.1` — conditional classNames - `tailwind-merge@3.7.1` — Tailwind class conflict resolution - `tailwindcss@^4.3.3` — utility-first CSS framework -- `lucide-react@^1.73.0` — SVG icon library +- `lucide-react@^1.79.0` — SVG icon library - `@monaco-editor/react@^4.7.0` — code editor (lazy-loaded, file/config edit tabs) - `@xterm/xterm@^6.0.0` — terminal emulator (Console tab) - `@xterm/addon-fit@^0.11.0` — xterm fit-to-container addon @@ -1301,14 +1301,14 @@ openEventStream(opts: EventStreamOptions) - `@testing-library/react@16.3.3` — component test utilities - `@testing-library/jest-dom@8.0.0` — DOM matchers - `@testing-library/user-event@14.6.13` — user interaction simulation -- `msw@^3.0.5` — Mock Service Worker for request interception (e2e mock mode) +- `msw@^3.0.7` — Mock Service Worker for request interception (e2e mock mode) - `vitest-websocket-mock@0.8.0` — WebSocket mock for unit tests -- `@playwright/test@^1.65.0` — browser e2e testing (mock + live modes) -- `jsdom@^31.0.0` — DOM implementation for unit tests +- `@playwright/test@^1.65.1` — browser e2e testing (mock + live modes) +- `jsdom@^31.0.1` — DOM implementation for unit tests - `eslint@10.15.0` and `@babel/eslint-parser` — lint JavaScript, TypeScript and TSX - `eslint-plugin-react-hooks@7.1.1` — React Hooks and compiler diagnostics - `oxlint` and `oxlint-tsgolint` — React rules and type-aware TypeScript linting -- `tailwindcss@^4.3.3` + `postcss@^8.5.32` + `autoprefixer@^10.6.2` — CSS processing +- `tailwindcss@^4.3.3` + `postcss@^8.5.33` + `autoprefixer@^10.7.0` — CSS processing - `@tanstack/router-devtools@1.167.4` — TanStack Router dev tools (optional, for debugging) ## Security considerations