diff --git a/README.md b/README.md index d22a9b915..b1d1cf000 100644 --- a/README.md +++ b/README.md @@ -104,28 +104,32 @@ Gameplane integrates with **10 mod registries**: Modrinth, CurseForge, Thunderst ## Architecture -```text -Dashboard UI (React + TypeScript + Vite + HeroUI v3) - │ HTTPS / WSS -Central API (Go): authentication, RBAC, REST, WebSocket, aggregation - │ - ├── Direct Kubernetes API access ───────────────────────────────┐ - │ Resource management, Pod logs, PTY attach │ - │ ▼ - │ ┌── Each registered cluster (local or remote) ──────────────────┐ - │ │ Kubernetes API ◄── Operator (Go, controller-runtime) │ - │ │ │ reconciles CRDs into local resources │ - │ │ ├── GameServer Pods + Services + PVCs │ - │ │ ├── Backup / restore Jobs │ - │ │ ├── Sentinel wake-on-connect Pods │ - │ │ └── Tunnel relay Pods │ - │ │ │ - └───┼── Private mTLS ──► Optional per-cluster agent gateway │ - │ ├── mTLS ──► Agent sidecars (:8090) │ - │ │ RCON, logs, files, mods │ - │ └── mTLS ──► Capture sidecars (:9091) │ - │ Capture downloads/cleanup │ - └──────────────────────────────────────────────────────────────┘ +```mermaid +flowchart TB + ui["Dashboard UI
React + TypeScript + Vite + HeroUI v3"] + api["Central API (Go)
auth, RBAC, REST, WebSocket, aggregation"] + ui -- "HTTPS / WSS" --> api + subgraph cluster["Each registered cluster (local or remote)"] + kube["Kubernetes API"] + op["Operator (Go, controller-runtime)"] + gs["GameServer Pods + Services + PVCs"] + jobs["Backup / restore Jobs"] + sen["Sentinel wake-on-connect Pods"] + tun["Tunnel relay Pods"] + gw["Optional agent gateway"] + agent["Agent sidecars :8090
RCON, logs, files, mods"] + cap["Capture sidecars :9091
capture downloads, cleanup"] + op -- "reconciles CRDs" --> kube + op --> gs + op --> jobs + op --> sen + op --> tun + gs --- agent + gw -- mTLS --> agent + gw -- mTLS --> cap + end + api -- "resources, pod logs, PTY attach" --> kube + api -- "private mTLS (remote clusters)" --> gw ``` In a combined installation, the central API connects directly to agents in its local cluster. Remote agent @@ -159,6 +163,8 @@ legacy default for custom deployments. See [storage and recovery](docs/standalon | `charts/` | Helm | Official Helm deployment chart for operator, API gateway, ingress, and helper services. | | `gameproto/` | Go | Shared protocol library for parsing game handshakes (Minecraft, Terraria) in `sentinel`. | | `gameaction/` | Go | Security guard and command renderer for custom module admin actions. | +| `i18n/` | Go | Shared language packs, ICU message formatter and pack checker used by the API, dashboard, operator and `gp-module`. | +| `gp-module/` | Go | Module authoring CLI: scaffold, offline validate, dry-run preview and OCI package. | | `netguard/` | Go | SSRF protection layer for outgoing mod downloads and OCI module fetches. | | `svcutil/` | Go | Shared HTTP server lifecycle and environment configuration utilities. | | `telemetryschema/` | Go | Shared telemetry report contract (types, strict decoder, official module catalog, report signing) used by the API and `telemetry-receiver`. | @@ -178,6 +184,7 @@ Gameplane extends Kubernetes using custom resources under `gameplane.local/v1alp - **`Module`**: An installed game bundle managed by the operator to materialize a `GameTemplate`. - **`ModuleSource`**: A registered game template repository (OCI registry, Git repository, HTTP server, or local upload). - **`Cluster`**: A registered remote Kubernetes cluster target for multi-cluster control plane management. +- **`NetworkCapture`**: An admin-only packet capture on one game server, run by the capture sidecar. ## Repository Layout @@ -196,6 +203,9 @@ Gameplane extends Kubernetes using custom resources under `gameplane.local/v1alp ├── website/ # Submodule: Public documentation site ├── gameproto/ # Wire-protocol parsing library (Minecraft, Terraria) ├── gameaction/ # Console injection guard & action command renderer +├── i18n/ # Shared language packs, ICU formatter, pack checker +├── gp-module/ # Module authoring CLI (init, validate, preview, package) +├── capture-sidecar/ # Optional packet capture sidecar ├── netguard/ # SSRF dial-guard library ├── svcutil/ # Shared HTTP server & env utilities ├── telemetryschema/ # Shared telemetry report contract (types, decoder, signing) @@ -207,6 +217,8 @@ Gameplane extends Kubernetes using custom resources under `gameplane.local/v1alp ├── deploy/standalone/ # API + dashboard Docker Compose deployment ├── docs/ # Technical documentation & guides ├── specs/ # Feature specifications and proposals +├── changelog/unreleased/ # One changelog entry per pull request +├── signing/ # cosign public keys for images and modules └── test/ # Integration & end-to-end kind test suites ``` diff --git a/docs/agent-architecture.md b/docs/agent-architecture.md index cda899821..fbf9bc087 100644 --- a/docs/agent-architecture.md +++ b/docs/agent-architecture.md @@ -29,7 +29,14 @@ This document is the **first stop** for AI agents modifying or extending Gamepla | **Telemetry-Receiver** | `telemetry-receiver/specs.md` | Ingests and processes anonymous usage telemetry from the API. | | **Telemetryschema** | `telemetryschema/specs.md` | Shared telemetry report contract (types, enumerations, strict decode, official module catalog, report signing) used by the API and the telemetry-receiver. | | **MCP-Server** | `mcp-server/specs.md` (submodule `GameplanePanel/mcp`) | Read-only Model Context Protocol server exposing cluster state to AI tools. | -| **Svcutil** | `svcutil/specs.md` | Shared stdlib-only env and graceful-shutdown helpers used by backend components. | +| **Svcutil** | `svcutil/specs.md` | Shared stdlib-only env and graceful-shutdown helpers. No module imports it yet; new backend binaries may adopt it. | + +## Shared Libraries & Tooling + +| Component | `specs.md` location | Primary Responsibilities | +| --- | --- | --- | +| **i18n** | `i18n/specs.md` | Shared language packs (`go:embed`), the ICU MessageFormat subset, the pack validator and the `i18n-check` CI tool. Imported by the API, the operator and `gp-module`. | +| **gp-module** | `gp-module/specs.md` | Module authoring CLI: scaffold, offline validate, dry-run preview and OCI package. Its `pkg/` packages are imported by the API and `test/e2e`. | ## Frontend & Other diff --git a/docs/architecture.md b/docs/architecture.md index 4bdefc0e7..8fa70ec78 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,8 +1,9 @@ # Architecture Gameplane is split across long-lived components — dashboard, API, operator, -and [optional] audit-syslog-bridge / telemetry-receiver satellites — plus a -short-lived per-pod agent sidecar. +and [optional] audit-syslog-bridge / telemetry-receiver / mcp-server / gateway +satellites — plus per-server workloads: the agent sidecar in every game pod and +the optional sentinel, tunnel and capture-sidecar. The default Helm installation runs the panel and operator together. A [standalone panel](standalone-panel.md) runs the dashboard and API without local @@ -11,44 +12,54 @@ The diagram and direct-agent examples below describe the combined installation. > **For AI Agents & Developers:** This document provides a high-level human-readable overview. For deep technical details, specifications, and boundaries of individual components, read the respective `specs.md` files located in each component directory (e.g., `api/specs.md`, `operator/specs.md`). AI Agents should consult [`agent-architecture.md`](agent-architecture.md) as their primary index. +```mermaid +flowchart TB + browser["Browser
web/ (React, TanStack Router/Query,
xterm.js, Monaco, Tailwind)"] + subgraph panel["gameplane namespace"] + web["gameplane-web
nginx: SPA + reverse proxy"] + api["API (api/)
REST + WebSocket + SSE gateway
local + OIDC auth, RBAC, audit log
SQLite or PostgreSQL [experimental]"] + operator["Operator (operator/)
controller-runtime reconcilers"] + sats["audit-syslog-bridge,
telemetry-receiver [optional]"] + mcp["mcp-server [optional]
read-only, stdio via kubectl exec"] + end + kube[("Kubernetes API
Gameplane CRDs")] + subgraph games["gameplane-games namespace"] + sts["StatefulSet + Service + PVC"] + pod["Game pod
game container + agent sidecar
(RCON, files, logs, console, heartbeat)"] + extras["Per-server extras [optional]
sentinel Deployment, tunnel Deployment,
capture-sidecar ephemeral container"] + jobs["restic Jobs
backup, restore, forget"] + end + browser -- "HTTPS / WSS (same origin)" --> web + web -- "proxied API, WS, SSE" --> api + api -- "CRD reads and writes" --> kube + api -- "mTLS :8090" --> pod + operator -- "watch and reconcile" --> kube + operator --> sts + operator --> extras + operator --> jobs + sts --> pod + pod -- "status.agent heartbeat" --> kube + api -. "audit webhook, daily report" .-> sats + mcp -. "get / list / watch" .-> kube ``` -┌───────────────────────────────────────────────────────┐ -│ Browser (web/) │ -│ React + TanStack Router/Query │ -│ xterm.js · Monaco · Tailwind │ -└───────────────────────────────────────────────────────┘ - │ HTTPS / WSS (same-origin) -┌───────────────────────────────────────────────────────┐ -│ API (api/) │ -│ REST + WebSocket gateway │ -│ Local + OIDC auth · RBAC · audit log │ -│ SQLite (production) or Postgres [experimental] for user store │ -│ mTLS to agent │ -└───────────────────────────────────────────────────────┘ - │ - ┌────────────┴────────────┐ - ▼ ▼ -┌──────────────┐ ┌─────────────────────┐ -│ K8s API │ │ In-pod agent │ -│ │ │ (sidecar in every │ -│ CRD reads │ │ GameServer pod) │ -│ CRD writes │ │ RCON · files │ -└──────────────┘ │ logs · console │ - │ │ heartbeat │ - ▼ └─────────────────────┘ -┌────────────────────────────────────────────┐ -│ Operator (operator/) │ -│ controller-runtime reconcilers │ -│ GameServer → StatefulSet+Service+PVC │ -│ Backup → Job (restic) │ -│ BackupSchedule → Backups + retention │ -│ Restore → Job (restic restore) │ -│ GameTemplate → inUseCount bookkeeping │ -│ Module → materializes GameTemplate│ -│ ModuleSource → indexes bundle registry │ -│ Cluster → remote cluster registry │ -└────────────────────────────────────────────┘ -``` + +Remote clusters add a private gateway in front of their agents; see +[Multi-cluster (federation)](#multi-cluster-federation). + +The operator runs one reconciler per CRD: + +| CRD | Reconciler output | +| --- | --- | +| `GameServer` | StatefulSet, Service, PVC, agent certificates, and the optional sentinel and tunnel Deployments | +| `Backup` | restic Job (or a CSI `VolumeSnapshot`), snapshot clean-up on delete | +| `BackupSchedule` | `Backup` objects on a cron, plus retention | +| `Restore` | restic restore Job, or a new GameServer seeded from a volume snapshot | +| `GameTemplate` | `inUseCount` bookkeeping | +| `Module` | an owned `GameTemplate` materialized from a bundle | +| `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 | + ## Dashboard component layer @@ -87,6 +98,55 @@ manage Gameplane with `kubectl apply` — the operator is authoritative. 6. Operator observes heartbeat → sets `status.phase=Running` 7. Dashboard receives the status update through local SSE or resource polling and re-renders +```mermaid +sequenceDiagram + autonumber + actor U as User + participant D as Dashboard + participant A as API + participant K as Kubernetes API + participant O as Operator + participant P as Game pod (game + agent) + U->>D: Start + D->>A: POST /servers/foo:start + A->>K: patch GameServer spec.suspend=false + K-->>O: GameServer changed + O->>K: scale StatefulSet to 1 + K->>P: schedule pod + P->>K: agent patches status.agent.lastHeartbeat + K-->>O: GameServer status changed + O->>K: status.phase=Running (pod Ready, heartbeat fresh) + K-->>A: watch event + A-->>D: SSE event or poll result +``` + +#### GameServer phases + +The operator derives `status.phase` again on every reconcile from the object +and its StatefulSet (`derivePhase` in +`operator/internal/controller/gameserver_status.go`), so a phase is a +reading, not a stored state: a recovered server returns from `Failed` to +`Running` without intervention. + +```mermaid +stateDiagram-v2 + [*] --> Pending: GameServer created + Pending --> Starting: StatefulSet exists + Starting --> Running: pod Ready and heartbeat fresh + Running --> Starting: pod not Ready or heartbeat stale + Starting --> Failed: terminal startup failure + Failed --> Running: recovers + Running --> Stopping: spec.suspend or idle sleep, pod still Ready + Stopping --> Suspended: no ready replica left + Suspended --> Starting: resumed or woken + Pending --> Failed: invalid spec or workload policy rejection +``` + +`Failed` also covers spec errors the reconciler refuses before building a +workload (for example a restricted workload asking for `Hostport`). The +`Stopped` value exists in the API type but the current operator never sets +it; a stopped server reads `Suspended`. + > **What `Running` means.** The phase flips to `Running` once the pod is > Ready *and* the agent heartbeat is fresh. That signals the pod and > sidecar are healthy — **not** that the game protocol (RCON / server @@ -119,6 +179,23 @@ the object alone, whether idle time is accruing: 6. A `wakeWindows` cron tick, or `POST /servers/foo:wake`, clears the marker and the pod comes back +```mermaid +flowchart TD + hb["Agent heartbeat"] --> fresh{"Heartbeat fresh and
phase Running?"} + fresh -- no --> freeze["Idle clock frozen
(reason on status.idle)"] + fresh -- yes --> zero{"playersOnline == 0?"} + zero -- "unknown" --> freeze + zero -- "more than 0" --> reset["Clear status.idle.emptySince"] + zero -- "exactly 0" --> stamp["Stamp status.idle.emptySince"] + stamp --> long{"Older than
spec.idle.afterMinutes?"} + long -- no --> wait["Keep waiting"] + long -- yes --> mark["Write idle-asleep-since annotation"] + mark --> soft["softStop: module stop sequence,
wait for not-ready, scale to 0"] + soft --> asleep["Phase Suspended,
reason IdleAsleep, PVC kept"] + asleep --> wake{"wakeWindows tick,
POST :wake, or sentinel
connection?"} + wake -- yes --> clear["Clear marker, pod returns"] +``` + > **Why not `spec.suspend`.** That field is the user's own power switch — the > `:start`/`:stop` verbs patch it directly. If the operator wrote it too, an > automatic sleep would be indistinguishable from a deliberate stop, and a wake @@ -145,6 +222,22 @@ the object alone, whether idle time is accruing: 3. Agent tails the game container's log file and streams each line as a text WS frame 4. API proxies frames back to the browser; xterm.js renders them +```mermaid +sequenceDiagram + participant B as Browser (xterm.js) + participant A as API + participant G as Agent sidecar :8090 + participant F as Game log file + B->>A: WS /ws/servers/foo/logs + A->>A: verify session and RBAC + A->>G: wss /logs/tail (mTLS) + loop each new line + F-->>G: tail + G-->>A: text frame + A-->>B: text frame + end +``` + The Logs tab can also stream the game container's stdout directly via the Kubernetes pod-log API (`/ws/servers/foo/logs/pod`, no agent mTLS needed). This is the default source and surfaces download/config output during @@ -156,7 +249,32 @@ startup, before the game's own log file exists. 2. API creates the Backup CRD 3. Operator creates a Job running `restic backup /data` against the PVC 4. Job completes; operator mirrors Job status into Backup.status -5. (Agent, during the Job, optionally issues an RCON `save-all` to quiesce) +5. With `spec.quiesce`, the operator first calls the agent's `/quiesce` + endpoint, which runs the module's save and auto-save-off commands, and + calls it again to unquiesce once the Backup is terminal + +```mermaid +sequenceDiagram + participant D as Dashboard + participant A as API + participant O as Operator + participant G as Agent + participant J as restic Job + participant R as restic repository + D->>A: POST /backups (inline spec) + A->>O: create Backup CR + opt spec.quiesce + O->>G: quiesce (save, auto-save off) + end + O->>J: create Job, mount PVC + J->>R: restic backup /data + J-->>O: Job complete + O->>O: read snapshot id from Job pod logs + O->>O: Backup.status.snapshotID, phase Succeeded + opt quiesced + O->>G: unquiesce (retried until it lands) + end +``` A `Backup` is only usable once its `status.snapshotID` has been read out of the restic Job's pod logs — a backup with no snapshot id cannot be restored, @@ -184,6 +302,24 @@ snapshot per deleted Backup. The same path serves every way a Backup can go: `concurrencyPolicy: Replace` schedule dropping an in-flight Backup, and garbage collection of a deleted GameServer's auto-schedule. +```mermaid +flowchart TD + del["Backup deleted"] --> uq{"Quiesced and not
yet released?"} + uq -- yes --> unq["Send unquiesce first"] --> vs + uq -- no --> vs{"volume-snapshot Backup
or no repoRef?"} + vs -- yes --> gc["No finalizer: VolumeSnapshot is
garbage-collected by owner ref"] + vs -- no --> idq{"Failed, or no
status.snapshotID?"} + idq -- yes --> rel["Release finalizer at once"] + idq -- no --> run{"Own backup Job
still running?"} + run -- yes --> kill["Delete Job, await pods"] --> idq + run -- no --> rs{"Non-terminal Restore
uses this Backup?"} + rs -- yes --> waitr["Wait"] --> rs + rs -- no --> forget["Job <backup>-forget:
restic forget id --prune"] + forget --> ok{"Succeeded within
45 minute cap?"} + ok -- yes --> done["SnapshotForgotten=True,
release finalizer"] + ok -- "no, or Secret or
namespace gone" --> ab["SnapshotForgetAbandoned warning,
release finalizer"] +``` + - **Finalizer.** Every Backup that has a `repoRef` and is not a `volume-snapshot` Backup carries `gameplane.local/backup-snapshot-finalizer` (added by the operator on its first reconcile, including for Backups created @@ -245,6 +381,25 @@ garbage collection of a deleted GameServer's auto-schedule. requeue the restore instead of failing it. The restored server must reach Running phase within 10 minutes; if it is still starting after that, the restore fails with a deadline message. +```mermaid +flowchart TD + req["POST /restores"] --> cr["Restore CR"] + cr --> src{"Source Backup present
and not Failed?"} + src -- no --> fail["Restore Failed"] + src -- "yes, no snapshotID yet" --> pend["Pending, requeue 15s"] --> src + src -- "yes, snapshotID set" --> pin["Pin snapshotID into Restore.status"] + pin --> strat{"Backup strategy"} + strat -- "restic snapshot" --> susp["Suspend target GameServer"] + susp --> job["restic restore --target / --delete Job"] + job --> resume["Resume GameServer"] + strat -- "volume snapshot" --> own{"Original server owns every
referenced Secret and ConfigMap?"} + own -- no --> fail + own -- yes --> newgs["Create new GameServer from CSI snapshot,
copy owned Secrets and ConfigMaps"] + newgs --> ready{"Running within
10 minutes?"} + ready -- yes --> ok["Restore Succeeded"] + ready -- no --> fail +``` + A Restore to an existing server (restic-snapshot strategy) requires the target suspended for the Job's duration — the PVC cannot be overwritten while the game is live. Volume-snapshot Restores skip the existing server and provision a fresh @@ -292,6 +447,27 @@ can be loaded from anywhere: commands at runtime — new games get full feature support without agent code changes. +```mermaid +flowchart LR + author["Module author
gp-module init / validate / package"] --> store + subgraph store["Module stores"] + oci["OCI registry"] + git["git repository"] + http["HTTP archive"] + local["local directory"] + upload["upload ConfigMaps"] + end + store --> ms["ModuleSource controller
modsrc.Fetcher indexes,
status.modules + digests"] + ms --> catalog["Dashboard catalog
(API /modules)"] + catalog -- install --> mod["Module CR"] + mod --> mc["Module controller
pulls bundle"] + mc --> gt["GameTemplate
(managed-by=Module)"] + mc --> loc["<template>-locales ConfigMap"] + kubectl["kubectl apply"] --> gt + gt --> gs["GameServer"] + gs --> agent["Agent sidecar
GAMEPLANE_CAPABILITIES"] +``` + The API's `/modules` surface (catalog merge, install, source CRUD, bundle upload) only reads and writes these CRs/ConfigMaps; the operator owns all reconciliation, so the dashboard and kubectl always @@ -320,6 +496,31 @@ Kubernetes clients keyed by cluster ID and dispatches requests via a cluster targeting the same cluster as the API. Standalone panels have no local workload client and start with an empty registry. +```mermaid +flowchart LR + browser["Browser"] --> api + subgraph central["Central panel (combined or standalone)"] + api["API
client pool keyed by cluster,
?cluster= selector, /fleet/* fan-out"] + reg[("Registry
Cluster CRs + kubeconfig Secrets,
or SQL in standalone")] + api --- reg + end + subgraph local["local cluster (combined mode only)"] + lop["Operator"] + lagent["Agents"] + end + subgraph remote["Registered remote cluster"] + rkube["Kubernetes API"] + rop["Operator"] + gw["Gateway [optional]"] + ragent["Agents"] + rop --> rkube + gw -- "agent mTLS,
UID-bound routes" --> ragent + end + api -- "direct mTLS" --> lagent + api -- "kubeconfig: CRDs, pod logs, attach" --> rkube + api -- "central mTLS peer:
RCON, files, logs, players" --> gw +``` + **Cluster registration and health:** - In combined mode, a `Cluster` CRD (group `gameplane.local/v1alpha1`) is the source of @@ -398,6 +599,22 @@ the target. See [registration and permissions](install.md#rbac-and-permissions). ## Security boundaries +```mermaid +flowchart LR + B["Browser"] -- "HTTPS, session cookie + CSRF,
local or OIDC login" --> API + API -- "mTLS, operator-managed CA" --> AG["Local agent"] + API -- "dedicated mTLS, enrolled URI SAN" --> GW["Remote gateway"] + GW -- "agent mTLS, UID-bound routes" --> RAG["Remote agent"] + AG -- "ServiceAccount: own GameServer status" --> K["Kubernetes API"] + OP["Operator"] -- "ClusterRole reads,
namespaced Role writes" --> K + OP -- "netguard IsAllowed" --> SRC["Module sources"] + AG -- "netguard IsPublic" --> DL["Mod downloads"] + AG -- "gameaction checks" --> GAME["Game console (RCON)"] + API -- "gameaction checks, pod attach" --> GAME + API -- "HTTP JSON webhook" --> SB["audit-syslog-bridge"] --> SYS["Syslog collector"] + API -- "daily report" --> TR["telemetry-receiver"] +``` + - **Browser → API**: HTTPS, session cookie + CSRF header, OIDC or local login. - **API → local Agent**: mTLS; client cert signed by operator-managed CA mounted into API pod. - **API → remote Gateway**: dedicated mTLS trust and an exact enrolled central diff --git a/docs/argocd.md b/docs/argocd.md index f3931a5cb..9a739c08d 100644 --- a/docs/argocd.md +++ b/docs/argocd.md @@ -11,6 +11,19 @@ Pin both Applications to the same Gameplane Git commit. Sync the CRD Application | CRDs | Plain directory `charts/gameplane/charts/gameplane-crds/crds` | Use `ServerSideApply=true` for the large schemas. Keep automated pruning off and sync this Application without prune. For Application deletion, preserve its resources by using non-cascading deletion. | | Workload | Helm chart `charts/gameplane` | Set `spec.source.helm.skipCrds: true` and include `examples/argocd-values.yaml` in `spec.source.helm.valueFiles`. The profile disables the CRD apply hook. Set the release name to `gameplane` and the destination namespace to `gameplane-system`. | +The two Applications share one commit, and the CRD Application must finish first: + +```mermaid +flowchart TD + commit["One pinned Gameplane commit"] --> crdapp["CRD Application: crds/ directory, ServerSideApply, no prune"] + commit --> wlapp["Workload Application: charts/gameplane with skipCrds and argocd-values.yaml"] + crdapp --> est["Wait until the CRDs are Established"] + est --> wlapp + sec["External CA and client Secrets, pre-created and versioned"] --> wlapp + caps["Destination serves ValidatingAdmissionPolicy and Binding v1"] --> wlapp + wlapp --> live["Release gameplane in gameplane-system"] +``` + Provision the release namespace, CA and client Secret before syncing. Keep ownership of the release namespace and external Secrets outside the workload Application. The example expects `gameplane-external-ca-v1` with `ca.crt` and `ca.key`, and a different Secret named `gameplane-external-client-v1` with `tls.crt` and `tls.key`. Use immutable, versioned Secret names. The operator signs per-game serving certificates with this CA, and the API and operator present the client certificate to the agents. Carry the installation's `nativeRBAC` settings, additional game namespaces, and credentials namespace into the workload Application. For a single-cluster panel where GitOps owns catalogs, configure the reduced Kubernetes permissions described in the [native RBAC guide](native-rbac.md). diff --git a/docs/contributing.md b/docs/contributing.md index d2c4ba98a..0faee5916 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -257,8 +257,8 @@ port-forward` bypasses NetworkPolicy entirely (it tunnels kubelet→pod), so "it works via port-forward" is not evidence that in-cluster pod→game traffic works. -The bot is `test/e2e/cmd/gameprobe`, built into `gameplane-test/gameprobe:e2e` -by the `e2e-gameprobe` bake target. That target sits outside the `e2e` bake +The bot is built from `test/e2e/Dockerfile` into `gameplane-test/gameprobe:e2e` +by the `e2e-gameprobe` bake target (`containers/docker-bake.hcl`). That target sits outside the `e2e` bake group so only the game-bot job pays to build it, and `deploy/kind/e2e.sh` side-loads it into the cluster when present. The `e2e game bot (kind)` CI job is now blocking rather than advisory. @@ -324,6 +324,22 @@ and test gates below. a file to `changelog/unreleased/` in the same PR (see [Changelog entries](#changelog-entries)). +Each PR moves through these stages, from push to merge: + +```mermaid +flowchart TD + A["Push branch and open PR"] --> B["auto-label: adds missing type: and area: labels (every 15 min)"] + A --> C["ci workflow: detect changes job (hack/ci_scope.py)"] + C --> D{"Selection error, unmapped path or ci: full-run label?"} + D -- yes --> E["Every CI job runs"] + D -- no --> F["Only the jobs the change affects run"] + E --> G["ci report job (needs the CI jobs)"] + F --> G + G --> H["CodeRabbit advisory review"] + H --> I["Human approval (master ruleset)"] + I --> J["Merge; a push to master runs the full suite"] +``` + Game-module changes (`modules/`) belong in the separate **`GameplanePanel/module`** repo, which this repo vendors as a submodule. Open the module PR there; once it merges, bump the submodule pointer here (`git add modules`) in a follow-up PR. @@ -379,7 +395,20 @@ Tags matching `v*` trigger the `release.yaml` workflow, which builds the component images, pushes the Helm chart to the `gameplane` OCI registry, and keyed-cosign-signs all images (component and chart) and official `modules/*` bundles by digest, recording all signatures in the public Sigstore Rekor -transparency log. +transparency log. The jobs run in this order: + +```mermaid +flowchart TD + T["Tag v* pushed"] --> IM["images: one leg per component (12)"] + T --> MO["modules: push and sign official bundles"] + IM --> P["Push image by digest"] + P --> S["Trivy scan, then cosign sign (keyed)"] + S --> V["Verify signature; check signing/cosign.pub matches the key"] + V --> TG["oras tag: attach release tags"] + TG --> CH["chart: helm push, cosign sign, verify"] + CH --> Q["consumer: qualify-release.yaml as anonymous pull"] + Q --> GR["github-release: CHANGELOG section as notes"] +``` Before tagging, fold the files in `changelog/unreleased/` into a `## [x.y.z]` section of `CHANGELOG.md` and delete them (keep the folder's diff --git a/docs/dependencies.md b/docs/dependencies.md index 9a87626cf..bbcfa4a5f 100644 --- a/docs/dependencies.md +++ b/docs/dependencies.md @@ -42,14 +42,14 @@ were added and verified on **2026-09-26**. | `gameproto/` | Go | 0 (stdlib only) | Shared Minecraft/Terraria handshake classifier used by sentinel | | `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 | | `svcutil/` | Go | 0 (stdlib only) | Shared env-parsing + graceful-shutdown helpers (no active importers yet) | -| `operator/` | Go | 19 | controller-runtime reconciler for the 8 CRDs; module OCI pull/verify, git/OCI fetch, restic-backup scheduling | +| `operator/` | Go | 19 | controller-runtime reconciler for the 9 CRDs (`operator/api/v1alpha1/*_types.go`); module OCI pull/verify, git/OCI fetch, restic-backup scheduling | | `api/` | Go | 17 | 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/` | Go | 0 (stdlib only) | Standalone HTTP-JSON → syslog relay for the audit webhook sink | -| `telemetry-receiver/` | Go | 1 | 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) | +| `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) | | `sentinel/` | Go | 2 | Wake-on-connect listener holding ports for sleeping pods | | `capture-sidecar/` | Go | 3 | Ephemeral AF_PACKET packet capture sidecar with BPF filtering | -| `tunnel/` | Go | 0 (stdlib only) | Relay client supervisor for frp/Tailscale/playit | +| `tunnel/` | Go | 1 (`tailscale.com`) | Relay client supervisor for frp/Tailscale/playit | | `gp-module/` | Go | 2 | Module authoring CLI: scaffold, offline validate, dry-run preview, OCI package | | `mcp-server/` (submodule) | Go | 5 | Standalone, strictly read-only MCP server for AI-assisted cluster diagnostics | | `test/e2e/` | Go | 4 | kind + Helm + real-component end-to-end suite | @@ -57,6 +57,29 @@ were added and verified on **2026-09-26**. ## Shared Go modules +Each arrow is a direct Go `require` between `go.work` modules, which resolve to +sibling directories through a local `replace`. Modules with no arrow import no +sibling module. Nothing requires `svcutil` yet. + +```mermaid +flowchart LR + API["api"] --> GA["gameaction"] + API --> GPM["gp-module"] + API --> I18N["i18n"] + API --> NG["netguard"] + API --> TS["telemetryschema"] + AG["agent"] --> GA + AG --> NG + OP["operator"] --> I18N + OP --> NG + GPM --> I18N + SE["sentinel"] --> GP["gameproto"] + TR["telemetry-receiver"] --> TS + E2E["test/e2e"] --> GP + E2E --> GPM + E2E --> TS +``` + ### netguard `netguard/go.mod` has **no `require` block at all** — it imports only the @@ -241,18 +264,21 @@ because the entire job is HTTP-in, hand-formatted-string-out. ### telemetry-receiver -`telemetry-receiver/go.mod` has exactly one direct dependency: +`telemetry-receiver/go.mod` has three external direct dependencies, and the +table lists the first one. The other two are `modernc.org/sqlite` (the store +in `store.go`) and `golang.org/x/mod` (version ordering in `versionorder.go`). +The in-repo `telemetryschema` module is the shared report contract (see above). | Dependency | Version | Why | |---|---|---| | `github.com/prometheus/client_golang` | v1.24.1 | `main.go` — `prometheus.NewRegistry()` + `CounterVec`/`Histogram` for `gameplane_telemetry_reports_total`/`_servers`/`_templates`, exposed via `promhttp.HandlerFor` at `/metrics` | -Deliberately kept to "stdlib + client_golang only" (per the package doc -comment) so it can be deployed standalone on a public host collecting -reports from many installs, independent of Gameplane's release cadence. -It validates the API's daily `{version, servers, templates}` telemetry -POST, logs it structurally, and aggregates it into the metrics above — -never storing raw per-install reports. +Kept to a small dependency set so it can be deployed standalone on a public +host collecting reports from many installs, independent of Gameplane's release +cadence. It decodes and verifies each report with `telemetryschema` +(`ingest.go`, `ingest_ext.go`), counts it into daily aggregates in SQLite +(`store.go`), and serves the metrics above and the public summary. Extended +reports also keep per-install activity records under a transformed install ID. ### mcp-server @@ -302,8 +328,8 @@ trade-off). Direct deps from `capture-sidecar/go.mod`: ### tunnel -`tunnel/go.mod` has **no `require` block at all** — stdlib only -(`os/exec`, `encoding/json`, `net/http`, `context`, etc.). It's the relay +`tunnel/go.mod` has one direct dependency, `tailscale.com` (used by `tunnel/tailscale.go` +and `tunnel/tailscale_forward.go`); the rest is stdlib (`os/exec`, `encoding/json`, `net/http`, `context`, etc.). It's the relay client supervisor: it launches and monitors the `frp`, `tailscaled`, or `playitd` client binary as a subprocess, configured by env vars (`GAMESERVER_NAME`, `TUNNEL_TYPE`, etc.) that the operator renders from diff --git a/docs/gateway-install.md b/docs/gateway-install.md index 0763dbfbe..0693e5e47 100644 --- a/docs/gateway-install.md +++ b/docs/gateway-install.md @@ -207,6 +207,18 @@ and API endpoint allowlists. It permits only: - TCP 8090 to game agents in the explicitly allowed namespaces. - TCP 9091 to capture sidecars in those same namespaces. +The gateway's allowed flows are summarized below; the chart's policy lists the +exact selectors. + +```mermaid +flowchart LR + central["Central API
peerCIDRs or peerSelectors"] -- "TCP 8443 mTLS" --> gw["Gateway Service"] + gw -- "TCP 443 and 6443" --> kapi["Local Kubernetes API
apiServerCIDRs"] + gw -- "TCP and UDP 53" --> dns["DNS pods"] + gw -- "TCP 8090" --> agents["Game agents in allowed namespaces"] + gw -- "TCP 9091" --> sidecars["Capture sidecars in allowed namespaces"] +``` + Use the source IPs the target cluster actually observes, accounting for private relay/SNAT behavior. `peerSelectors` identify pods **inside this cluster**, such as a relay; they cannot select pods by labels across clusters. Supply both a diff --git a/docs/install.md b/docs/install.md index eaa95f8bc..9cf5947ca 100644 --- a/docs/install.md +++ b/docs/install.md @@ -38,6 +38,26 @@ belong to is enabled (and, for `sentinel` and `capture-sidecar`, only for GameServers that opt in). See each component's values block for its enable flag. +The chart's default install renders the following objects, and each optional +branch depends on the values shown: + +```mermaid +flowchart TD + release["helm install or upgrade gameplane"] --> opq{"operator.enabled"} + release --> apiq{"api.enabled"} + release --> monq{"serviceMonitors, prometheusRules or grafanaDashboards"} + opq -- "true (default)" --> crds["gameplane-crds subchart (Helm crds/ phase)"] + opq -- "true (default)" --> op["Operator Deployment, RBAC and NetworkPolicies"] + opq -- "true (default)" --> vap["Admission policies and default ModuleSource"] + apiq -- "true (default)" --> api["API Deployment, Service and data PVC"] + apiq -- "web.enabled (default)" --> web["Web dashboard"] + apiq -- "ingress.enabled" --> ing["Ingress"] + release -- "not api.standalone and crds.autoApply.enabled" --> hook["CRD apply hook Job"] + apiq -- "api.telemetry.receiver.enabled and empty endpoint" --> tr["Telemetry receiver"] + apiq -- "syslogBridge.enabled and empty webhook URL" --> asb["Audit syslog bridge"] + monq -- "opt-in" --> mon["ServiceMonitor, PodMonitor, PrometheusRule and dashboard ConfigMap"] +``` + ### Edge channel (latest edge build) Every push to `master` publishes rolling `:edge` images. To track them, install @@ -970,6 +990,17 @@ not run. A fresh install therefore never depends on pulling the hook's never owned or deleted by Helm here, so `helm uninstall` leaves your GameServers intact. +With Helm 3, the hook's events on `helm install` depend on the live CRD stamp: + +```mermaid +flowchart TD + start["helm install or helm upgrade"] --> up{"Release.IsUpgrade?"} + up -- yes --> pre["pre-upgrade hook: kubectl apply --server-side"] + up -- no --> live{"gameservers CRD present with a different stamp?"} + live -- "no: fresh cluster, stamps match" --> none["No hook Job; crds/ created the CRDs"] + live -- "yes: leftover CRDs" --> pi["pre-install and pre-upgrade hook applies crd-manifests/"] +``` + **Helm 4** installs `crds/` with a server-side apply under the field manager `helm` instead of skipping existing CRDs, so a `helm install` over leftover CRDs updates them itself (stamp included) and the hook stays pre-upgrade diff --git a/docs/key-rotation.md b/docs/key-rotation.md index 53ae64fe5..d635da533 100644 --- a/docs/key-rotation.md +++ b/docs/key-rotation.md @@ -21,6 +21,17 @@ the key type cosign generates by default, so it works cleanly with Rekor. | [`signing/2026-07-24-cosign-legacy.pub`](../signing/2026-07-24-cosign-legacy.pub) | Ed25519 | Retired key. Verifies releases published **before** the rotation, and the cross-signature below. | | [`signing/cosign.pub.legacy-sig`](../signing/cosign.pub.legacy-sig) | — | The old key's signature over the new `signing/cosign.pub` (trust continuity). | +The retired key vouches for the current one, and each key verifies a different release range: + +```mermaid +flowchart LR + Legacy["Retired Ed25519 key
signing/2026-07-24-cosign-legacy.pub"] + Current["Current ECDSA P-256 key
signing/cosign.pub"] + Legacy -->|"cross-signature over cosign.pub
cosign.pub.legacy-sig"| Current + Legacy -->|"verifies releases before rotation"| Old["Pre-rotation artifacts (keyed, unlogged)"] + Current -->|"verifies releases from rotation onward"| New["Post-rotation artifacts (recorded in Rekor)"] +``` + ## Verify the cross-signature Confirm the retired key endorsed the current key. With openssl (portable): diff --git a/docs/layout.md b/docs/layout.md index 0cdd67e84..c5498c3ae 100644 --- a/docs/layout.md +++ b/docs/layout.md @@ -85,20 +85,21 @@ web/src/ ## 2. Layout map -Measured on `master` at `54d5819` (2026-10-22). "Gap today" is `matches` or the -move spec 028 makes. +Measured on `master` at `54d5819` (2026-10-22) and re-counted on 2026-11-17 for +the file and line numbers below. "Gap today" is `matches` or the move spec 028 +makes. | Module | Kind | Target | Gap today | | --- | --- | --- | --- | | `agent` | Service | `cmd/main.go` + `internal//` | matches | -| `api` | Service | `cmd/main.go` + `internal//` | `cmd/` holds 7 non-test files (bootstrap, gateway, management, memlimit, metrics, panel key) → keep wiring in `cmd/`, move behavior to `internal//`; second binary `cmd/messages-export/` matches; `internal/handlers/` is one flat package of 146 files (spec 028 splits it) | +| `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 159 `.go` files, 51 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//` | | `capture-sidecar` | Service | `cmd/main.go` + `internal//` | matches | | `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 150 files (spec 028 splits it); `api/v1alpha1/` see §3 | -| `sentinel` | Service | `cmd/main.go` + `internal//` | `main.go` 1,017 lines at root → `cmd/main.go` + `internal//` | +| `operator` | Service | `cmd/main.go` + `internal//` | matches; `internal/controller/` is one flat package of 221 `.go` files, 65 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//` | 12 source files in root `package main` → `cmd/main.go` + `internal//`; `web/` and `design-export/` assets stay | -| `tunnel` | Service | `cmd/main.go` + `internal//` | `main.go` 1,052 and `playit_reporter.go` 525 lines at root → `cmd/main.go` + `internal//`; `frpc/` (separate build module, not in `go.work`) stays | +| `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 | | `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 | @@ -107,7 +108,7 @@ move spec 028 makes. | `svcutil` | Library | flat root package | matches | | `telemetryschema` | Library | flat root package | matches | | `test/e2e` | Test suite | root package + `internal//` | matches (see §3) | -| `web` | Web app | `src/pages/` + route definitions in `src/routes/` | no `src/pages/` yet: screens live in `src/routes/` → move each to `src/pages/.tsx`; screens over 500 lines to split: `AdminSettings.tsx` 2,478, `CreateServer.tsx` 1,352, `tabs/Mods.tsx` 1,291, `tabs/settings/Networking.tsx` 1,045, `ThemeSettings.tsx` 886, `Users.tsx` 825, `Servers.tsx` 680, `tabs/Files.tsx` 670, `tabs/settings/ShareLinks.tsx` 658, `Backups.tsx` 642, `Dashboard.tsx` 596 | +| `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,306, `CreateServer.tsx` 1,448, `tabs/Mods.tsx` 1,291, `tabs/settings/Networking.tsx` 1,045, `ThemeSettings.tsx` 886, `Users.tsx` 825, `Servers.tsx` 680, `tabs/settings/ShareLinks.tsx` 658, `tabs/Files.tsx` 657, `Backups.tsx` 642, `Dashboard.tsx` 599 | ## 3. Exceptions diff --git a/docs/module-authoring.md b/docs/module-authoring.md index 3f10dcc6c..0f4d2df0b 100644 --- a/docs/module-authoring.md +++ b/docs/module-authoring.md @@ -10,6 +10,20 @@ registry by creating a `ModuleSource` resource; users install a module by creating (or clicking Install on) a `Module` resource, which the operator materializes into an in-cluster `GameTemplate`. +A module travels from authoring to a running server through these stages: + +```mermaid +flowchart LR + A["Author module.yaml, template.yaml, README.md"] --> B["gp-module validate and preview"] + B --> C["gp-module package or modules/build.sh (oras push)"] + C --> D["OCI registry"] + D --> E["ModuleSource catalog (status.modules)"] + E --> F["Module CR (spec.source, spec.name, spec.version)"] + F --> G["Operator pulls, verifies signature, checks digest pin and operator version"] + G --> H["GameTemplate owned by the Module"] + H --> I["GameServer (spec.templateRef)"] +``` + ## Quickstart: Authoring with `gp-module` CLI & Web Builder For a validated wake proxy, add `sentinelIsolation: true` under the template's @@ -75,7 +89,7 @@ bin/gp-module preview modules/minecraft-java \ ### 4. Packaging and Distribution (`package`) -Enforce asset size limits (icon $\le$ 512 KiB, bundle $\le$ 1 MiB) and export to `.tar.gz` or push directly to an OCI registry: +Check asset sizes (icon $\le$ 512 KiB, uncompressed bundle $\le$ 1 MiB; larger files produce a warning, not an error) and export to `.tar.gz` or push directly to an OCI registry: ```sh # Package into a local tar.gz bundle @@ -402,7 +416,19 @@ this as a clear "still in use by N servers" message. If a `Module` fails to upgrade (pull error, bad signature, incompatible operator), the previously-installed `GameTemplate` keeps running unchanged; `status.previousVersion` records the last-known-good to roll back to by -re-pinning `spec.version`. +re-pinning `spec.version`. A `Module` moves between these phases: + +```mermaid +stateDiagram-v2 + [*] --> Pending: WaitingForCatalog or NoVersionAvailable + Pending --> Pulling: catalog entry and version found + Pulling --> Ready: bundle verified and GameTemplate applied + Pending --> Failed: SourceNotFound, SourceConfig, VerifyConfig, VersionUnavailable + Ready --> Failed: SourceNotFound, SourceConfig, VerifyConfig, VersionUnavailable + Pulling --> Failed: PullFailed, SignatureInvalid, DigestMismatch, IncompatibleOperator, ApplyTemplate + Failed --> Pulling: spec change (retries at the same generation stay Failed) + Ready --> Pulling: spec.version or spec.digest changed +``` ### Verifying and pinning bundles diff --git a/docs/monitoring.md b/docs/monitoring.md index e11e2896c..83605371d 100644 --- a/docs/monitoring.md +++ b/docs/monitoring.md @@ -4,6 +4,25 @@ Gameplane exports the existing agent CPU, process memory, disk and player gauges optional game performance measurements, and relay health. Prometheus and Grafana are optional. A monitor resource alone does not prove discovery or network access. +The chart's optional monitoring objects form this pipeline. Agent and tunnel +metrics are scraped by PodMonitors in the games namespace; the operator, API and +telemetry receiver are scraped by ServiceMonitors. + +```mermaid +flowchart LR + agent["Agent sidecar :9090 metrics"] --> pma["PodMonitor gameplane-agent"] + tunnel["Tunnel relay :8091 health and metrics"] --> pmt["PodMonitor gameplane-tunnel"] + op["Operator :8080 metrics"] --> smo["ServiceMonitor gameplane-operator"] + api["API metrics listener"] --> sma["ServiceMonitor gameplane-api"] + pma --> prom["Prometheus"] + pmt --> prom + smo --> prom + sma --> prom + prom --> rules["PrometheusRule alerts (operator, scrape, relay, workload)"] + cm["Dashboard ConfigMap (label grafana_dashboard=1)"] --> graf["Grafana sidecar"] + graf -- "queries" --> prom +``` + ## Complete setup Install the Prometheus Operator and its CRDs first. Apply diff --git a/docs/multicluster-agent-gateway.md b/docs/multicluster-agent-gateway.md index 01f6289b8..db8ad0668 100644 --- a/docs/multicluster-agent-gateway.md +++ b/docs/multicluster-agent-gateway.md @@ -8,6 +8,24 @@ central API still connects directly to each Kubernetes API for resource changes, pod logs, PTY attach, and stdin module actions. The gateway does not provide a Kubernetes tunnel, replicate storage, or run a second user database. +The central API reaches each registered cluster on two separate paths: its +Kubernetes API for resource management, and the gateway for agent operations. + +```mermaid +flowchart LR + subgraph central["Central panel (combined or standalone)"] + api["Central API
user authorization"] + end + subgraph remote["Registered game cluster"] + k8s["Kubernetes API"] + gw["Gateway
gateway subcommand, TCP 8443"] + agent["Agent Service
TCP 8090 agent, TCP 9091 capture"] + end + api -- "Kubernetes API: resources, logs, PTY, stdin" --> k8s + api -- "mTLS: agent operations and capture files" --> gw + gw -- "mTLS, /v1/targets/{uid}" --> agent +``` + ## Register the gateway with the central API In either installation mode, register the workload cluster through @@ -83,7 +101,29 @@ The gateway authenticates the central API, verifies its own cluster ID and the live GameServer/agent Service ownership, and connects to the local agent's UID route. The agent rejects a different UID. Older agents do not implement that versioned route and fail closed; they must be upgraded before gateway access is -available. User cookies, bearer tokens and CSRF headers are never forwarded. +available. User cookies, bearer tokens and CSRF headers are never forwarded. The sequence +below shows each check in order. + +```mermaid +sequenceDiagram + participant B as Browser + participant A as Central API + participant K as Remote Kubernetes API + participant G as Gateway + participant P as Agent in game pod + B->>A: Operation with session cookie and CSRF header + A->>A: Authorize user for cluster, namespace and server + A->>K: Read GameServer and its UID + A->>G: mTLS request to /v1/clusters/.../uids/UID/operation + G->>G: Check central client URI SAN, cluster ID, namespace allowlist + G->>K: Confirm live UID and agent Service owner + G->>P: HTTPS /v1/targets/UID/operation + P->>P: Return 404 if UID differs + P-->>G: Response or stream + G-->>A: Response, with redirects refused and cookies removed + Note over G,P: Transport failure returns 502, and the write outcome may be unknown + A-->>B: Response +``` The central API is the user-authorization authority. A trusted gateway client certificate therefore grants delegated access to the gateway's allowlisted agent diff --git a/docs/networking.md b/docs/networking.md index 65fda8d33..39354fe86 100644 --- a/docs/networking.md +++ b/docs/networking.md @@ -17,6 +17,18 @@ and destinations. Templates without the field retain the existing broad sentinel-to-game allowance; module maintainers can adopt it after validating their proxy traffic. +For an opted-in template, the operator applies the isolation in this order: + +```mermaid +flowchart TD + T["GameTemplate sentinelIsolation: true"] --> P{"Advertised ports declared?"} + P -- no --> N["Reconcile stops with a Failed phase;
existing sentinel exposure is revoked"] + P -- yes --> L["Game and sentinel pod templates labeled gameplane.local/sentinel-isolation: true"] + L --> R["Pods roll out; StatefulSet selectors unchanged"] + R --> Y["Per-server policies: <server>-sentinel-ingress and <server>-sentinel-egress"] + Y --> Z["Sentinel reaches only its server's advertised ports"] +``` + Upgrade the CRDs, operator and chart together before opting in a template. Existing game pods roll out to acquire the isolation label; StatefulSet selectors stay unchanged. Do not claim isolation until both game and sentinel @@ -144,6 +156,20 @@ The dashboard translates these to the CRD fields; the operator then applies them ## Address Preference Behavior +The operator checks a requested pool or address in this order, and the first matching branch sets the `AddressAssignment` reason: + +```mermaid +flowchart TD + A["Pool or address requested"] --> B{"Expose is LoadBalancer?"} + B -- no --> C["IgnoredForExposureMode"] + B -- yes --> D{"Explicit address is an IP?"} + D -- no --> E["InvalidAddress"] + D -- yes --> F{"operator.addressManager"} + F -- "metallb or cilium" --> G["Operator writes annotation or label on the Service"] + F -- none --> H["NoAddressManagerConfigured"] + G --> I["Assigned, AssignmentPending or a failure reason"] +``` + ### When Expose Mode is LoadBalancer - `addressPool` and `address` are honored by the address manager (MetalLB or Cilium). diff --git a/docs/notifications.md b/docs/notifications.md index c729b3bfb..3635de2d6 100644 --- a/docs/notifications.md +++ b/docs/notifications.md @@ -32,6 +32,25 @@ is missed by the sinks (it is still visible in the dashboard, `kubectl`, and the `GameplaneBackupFailed` Prometheus alert). There is deliberately no cross-restart watermark. +An observed transition reaches each matching sink along this path: + +```mermaid +flowchart TD + A["Watchers on GameServer, Backup and Restore status"] --> B{"Transition maps to an event type?"} + B -->|No| Z["Ignored"] + B -->|Yes| C["Enqueue without blocking (queue of 256)"] + C -->|Queue full| D["Dropped, counted in metrics"] + C --> E["Worker matches each sink's event filter"] + E --> F{"Sink has a configRef?"} + F -->|No| G["Counted as skipped_no_secret"] + F -->|Yes| H["Read the sink Secret"] + H --> I{"PostgreSQL: dispatch claim won?"} + I -->|No| Z2["Skipped, another replica owns it"] + I -->|Yes| J["Deliver with retries at 0, 2 s and 8 s"] + J --> K["sent"] + J --> L["failed, 4xx responses not retried"] +``` + ## Sink credentials (Secrets) The **Add sink** form takes the credential material directly — the webhook diff --git a/docs/oidc.md b/docs/oidc.md index 7d5224306..a50e9477a 100644 --- a/docs/oidc.md +++ b/docs/oidc.md @@ -18,6 +18,28 @@ Fill in: The callback URL is automatically set to `{External URL}/auth/oidc/{provider-name}/callback`. +Each login runs this authorization-code sequence: + +```mermaid +sequenceDiagram + autonumber + participant B as Browser + participant A as API (/auth/oidc/NAME) + participant I as Identity provider + B->>A: GET /start + A-->>B: 302 to IdP, sets state and nonce cookies (HttpOnly, Secure) + B->>I: Authorize with state and nonce + I-->>B: 302 to /callback with code and state + B->>A: GET /callback, with state and nonce cookies + A->>A: Compare state with state cookie, 400 on mismatch + A->>I: Exchange code for tokens + I-->>A: id_token + A->>A: Verify id_token signature, check nonce cookie + A->>A: Read groups claim and compute role + A->>A: Create or update user by issuer and subject, audit role + A-->>B: Set session and CSRF cookies, 302 to / +``` + **Note**: The Helm-flag single OIDC provider supports group→role mapping via Helm values `api.oidc.groupsClaim` and `api.oidc.roleMappings.{admin,operator,viewer}` (or CLI flags `--oidc-groups-claim` and `--oidc-role-mapping-{admin,operator,viewer}`) (since v0.3.0). See "Role Mapping at Install Time (No Bootstrap-Admin Required)" below for setup details and worked examples. ## Provider guides @@ -326,6 +348,24 @@ If a user logs in and their IdP groups do not match any configured mapping (or t - If `defaultRole` is set to `"deny"`, the login is rejected and the user is not created - Once logged in, an admin can manually promote the user via the Users page (sidebar: Users & RBAC) if needed +The role is chosen in this order: + +```mermaid +flowchart TD + A["Groups from groupsClaim"] --> B{"Role mappings configured?"} + B -- no --> V["viewer"] + B -- yes --> C{"A group in the admin list?"} + C -- yes --> AD["admin"] + C -- no --> D{"A group in the operator list?"} + D -- yes --> OP["operator"] + D -- no --> E{"A group in the viewer list?"} + E -- yes --> VW["viewer"] + E -- no --> F{"defaultRole"} + F -- "deny" --> R["Login refused"] + F -- "viewer or empty" --> V2["viewer"] + F -- "admin or operator" --> G["defaultRole value"] +``` + **Note**: `groupsClaim` and `defaultRole` are **Helm-only settings in v1** — they are set at install time via Helm values and cannot be changed from the dashboard. Only `roleMappings` can be overridden by admins through the dashboard (see below). ## Managing Role Mappings from the Dashboard @@ -379,8 +419,8 @@ A user in both `gameplane-admins` (admin, Helm-seeded) and `dev-team` (viewer, D |-------|-------| | "issuer discovery failed" (login page won't load) | **Wrong issuer URL or TLS failure.** Verify the exact issuer URL in your IdP's OIDC endpoints, including trailing slash if present. Test locally: `curl https://issuer/.well-known/openid-configuration`. If the IdP uses a private CA, the API container must trust it — there is no chart value for this today, so either use a publicly-trusted certificate on the IdP or mount your CA into the API pod's system trust store. | | "redirect_uri mismatch" at login | **External URL changed after registering the app.** If you set a new `External URL` in Admin Settings, update the redirect URI in your IdP's client config to match `{new-url}/auth/oidc/{provider-name}/callback`. | -| "state mismatch" (blank login error) | **Cookies blocked or clock skew.** Ensure your browser accepts session cookies (`gameplane_oidc_state`, `gameplane_oidc_nonce`) and that server and IdP clocks are synchronized (within 5 minutes). Check browser DevTools → Network/Cookies for blocked third-party cookies if in an iframe. | -| Login succeeds but user is stuck at viewer role | **New OIDC users start as viewer.** An admin must promote them on the Users page (sidebar: Users & RBAC). From v0.2.0-beta.6+, group claims can map to roles automatically; check Authentication settings for group-based role mapping. | +| "state mismatch" or "nonce mismatch" (login error) | **Cookies blocked or clock skew.** Ensure your browser accepts session cookies (`gameplane_oidc_state`, `gameplane_oidc_nonce`) and that server and IdP clocks are synchronized (within 5 minutes). Check browser DevTools → Network/Cookies for blocked third-party cookies if in an iframe. | +| Login succeeds but user is stuck at viewer role | **Without role mappings, new OIDC users start as viewer.** An admin must promote them on the Users page (sidebar: Users & RBAC). From v0.2.0-beta.6+, group claims can map to roles automatically; check Authentication settings for group-based role mapping. | | Login succeeds but role did not update when groups changed at IdP | **Last-admin demotion guard.** When group→role mapping is enabled, users' roles are re-synced from their IdP groups on each login. To prevent lockout, the system blocks any role change that would remove the *last* user capable of managing other users (i.e., the last admin or user-manager). If your group assignment change would demote the sole user-manager, the demotion is silently skipped: the login succeeds, but the user's stored role remains unchanged. To confirm the demotion guard was triggered, check the API pod logs for a warn-level entry containing `oidc role resync skipped`. Verify you have at least one other admin or user-manager in a different group, then have the affected user log in again. | | User created in one IdP logs in as a different account after linking IdP accounts | **Account linking is by OIDC identity, not email.** OIDC identities are permanently linked to Gameplane accounts by (issuer, subject) — the combination of your identity provider and the user's subject claim (a unique per-provider identifier, not email). If a user's email address or display name changes at the IdP, they will still log in as the same Gameplane account. However, if you add a different IdP or reconfigure an existing one to use a different subject attribute, that user will be treated as a new person on first login with the new issuer/subject pair. To prevent duplicate accounts, ensure your IdP subject claim is stable and won't change if you reconfigure the provider. | | Provider button missing from login page | **Provider disabled or secret missing.** Verify in Admin Settings → Authentication that the provider is enabled and has a client secret stored. If the secret was deleted from the API credentials namespace (label `gameplane.local/auth-provider=true`), recreate it with the exact name shown in the provider's config. | diff --git a/docs/operator-operations.md b/docs/operator-operations.md index cd81f5b9d..3f3e6e190 100644 --- a/docs/operator-operations.md +++ b/docs/operator-operations.md @@ -17,6 +17,24 @@ spec: quiesce: true ``` +Each Backup resolves to one of these outcomes, with the two policies applied +independently: + +```mermaid +flowchart TD + req["Backup request"] --> strat{"strategy"} + strat -- "volume-snapshot (CSI)" --> csi["Primary PVC only; stopped and all-data are rejected"] + strat -- "restic-snapshot" --> pp{"powerPolicy"} + pp -- "preserve (default)" --> vp{"volumePolicy"} + pp -- "stop-copy-restart" --> stop["Drain workers, copy, then resume only current intent"] + vp -- "primary-only (default)" --> prim["Primary data, quiesced if quiesce is true"] + vp -- "all-data" --> multi["One snapshot of all data roots"] + multi --> cons{"Source stopped and fully drained?"} + cons -- yes --> ok["Consistency across included roots"] + cons -- no --> live["Consistency=False, LiveMultiVolumeCopy"] + stop --> ok +``` + The two policies are independent. CSI (`volume-snapshot`) rejects stopped or all-data policies; it remains primary-only and offers no cross-volume atomicity. A preserve/all-data Restic copy captures one snapshot but reports @@ -169,6 +187,24 @@ requesting zero replicas. A successful Restore leaves its initial workload runni Stopped-source proof, bounded copy preparation and CSI invalidation build on this ownership boundary. Staged template adoption is tracked separately in #731. +A live Restic backup with `quiesce: true` runs in this order. The worker is +prepared before saving is disabled, and save-on is sent only after the worker drains: + +```mermaid +sequenceDiagram + participant Op as Operator + participant Wk as Restic worker Job + participant Ag as Agent in game pod + participant Repo as Restic repository + Op->>Wk: Create Job, schedule, pull image, mount source, validate repository + Wk-->>Op: Ready + Op->>Ag: Pod-bound quiesce (save-off, save-all flush) + Ag-->>Op: Quiesced + Wk->>Repo: Copy included /volumes roots (expiring, pod-bound authorization) + Wk-->>Op: Copy finished, worker drained + Op->>Ag: Unquiesce (save-on) +``` + ## Backup preparation and capture budgets Restic workers now schedule, pull their image, mount the source and validate the diff --git a/docs/panel-recovery.md b/docs/panel-recovery.md index 9261b292b..484d512cd 100644 --- a/docs/panel-recovery.md +++ b/docs/panel-recovery.md @@ -60,6 +60,27 @@ state and saves through the operational access available during the outage. ## Database loss and recovery order +Choose the branch that matches the failed domain. Each branch restores only +that domain, and none requires recreating live games. + +```mermaid +flowchart TD + incident["Panel incident"] --> what{"Failed domain"} + what -- "SQL unreachable, full or locked, data intact" --> conn["Restore connectivity or capacity; do not bootstrap a new database"] + what -- "SQL lost or corrupt" --> fence["Stop all API writers and fence the old database"] + what -- "Management key missing or wrong" --> keep["Keep the panel stopped"] + conn --> verify["Verify readiness, login and cluster operations"] + fence --> restore["Restore a verified backup to a working copy"] + restore --> reconcile["Reconcile users, grants and UIDs with the external inventory"] + reconcile --> invalidate["Delete sessions, clear api_tokens and revoke share links"] + invalidate --> start["Start one API with --panel-key-provisioned and the original key"] + keep --> recover{"Original paired key recoverable?"} + recover -- yes --> start + recover -- no --> rebuild["Treat encrypted credentials as lost; rebuild under a reviewed plan"] + start --> verify + verify --> reopen["Reopen access"] +``` + 1. Restrict external panel access and stop **all** API writers. Fence the old database instance so it cannot resume writing. Record incident/recovery start time and live GameServer/PVC/Pod UIDs, container IDs and restart counts. Keep diff --git a/docs/production-placement.md b/docs/production-placement.md index ff8dc7f24..a14e86867 100644 --- a/docs/production-placement.md +++ b/docs/production-placement.md @@ -83,6 +83,16 @@ cause API downtime. A PDB is not an availability guarantee and does not prevent node failures. The persistent telemetry receiver is also a singleton; avoid a zero-unavailable budget unless intentionally accepting a blocked drain. +The operator's replica count selects its election and update strategy: + +```mermaid +flowchart TD + rep{"operator.replicas > 1 or operator.leaderElect"} -- yes --> le["Leader election on (--leader-elect) and RollingUpdate"] + rep -- no --> rc["Single reconciler: Recreate strategy"] + rc --> mig{"Upgrade over a RollingUpdate Deployment?"} + mig -- yes --> hook["Pre-upgrade hook clears RollingUpdate fields"] +``` + Redundant operator replicas use leader election and rolling updates. The chart automatically enables election when replicas exceed one, even when an older release retained `leaderElect: false`; upgrades continue rendering and install @@ -121,6 +131,22 @@ With the NodeRestriction admission plugin, a label key such as `gameplane.node-restriction.kubernetes.io/pool` also prevents a kubelet from labeling itself as a game worker. Set the configured key and worker taint to match. +With the policy enabled, a game Pod passes through these checks before it can run: + +```mermaid +flowchart TD + op["Operator sets pool nodeSelector and exact toleration"] --> sts["Game StatefulSet Pod"] + sts --> vap["game-worker-admission ValidatingAdmissionPolicy"] + vap --> p1{"Selects the configured pool and has no nodeName on create?"} + p1 -- no --> deny["Rejected"] + p1 -- yes --> p2{"Resource requests and memory limit within bounds?"} + p2 -- no --> deny + p2 -- yes --> sched["kube-scheduler"] + sched --> ok{"Matching schedulable worker?"} + ok -- yes --> run["Pod runs on the game worker pool"] + ok -- no --> pending["Pod stays Pending"] +``` + The policy validates effective game resources before workload creation and template adoption. The CPU request must fall between the configured bounds. The memory request must meet its floor, and the memory limit must cover the diff --git a/docs/relay-health.md b/docs/relay-health.md index 53545418d..5f010dd2b 100644 --- a/docs/relay-health.md +++ b/docs/relay-health.md @@ -14,7 +14,16 @@ observations expire after ten seconds, and child exit immediately clears them. The operator also requires the current Deployment generation, updated replicas and the expected readiness probe; an old Pod without the probe cannot satisfy the new readiness contract. Configured addresses remain visible while the -connection is unconfirmed, but `TunnelReady` is not true. +connection is unconfirmed, but `TunnelReady` is not true. The flow below shows how the probes depend on the provider's evidence: + +```mermaid +flowchart TD + C["Provider check every 2 s, 2 s deadline (frp: frpc status API on 127.0.0.1:7400)"] --> O["Local observation, expires after 10 s"] + O --> Q{"Connection and every forward confirmed?"} + Q -- yes --> OK["/readyz 200: Pod Ready, TunnelReady can be True"] + Q -- no --> NR["/readyz 503: Pod NotReady, TunnelReady not True"] + O -. "Playit only" .-> PH["Pod readiness via /healthz; TunnelReady is AwaitingAddress until an address
is assigned, then RelayConnectionUnknown"] +``` ## frp @@ -88,6 +97,20 @@ and [the daemon's cached lifecycle publisher](https://github.com/playit-cloud/pl ## Retry and resource policy +The restart delay grows after each unexpected exit and resets only after a healthy minute: + +```mermaid +stateDiagram-v2 + [*] --> Running + Running --> Backoff: child exits, clean or not + Backoff --> Running: wait 1, 2, 4, 8 s ... capped at 300 s + Running --> Healthy: readiness confirmed + Healthy --> Running: failed or stale observation + Healthy --> Backoff: child exits + Healthy --> Reset: one uninterrupted minute + Reset --> Running: delay reset +``` + Unexpected child exits, including clean exits, wait 1, 2, 4, 8 seconds and so on, up to 300 seconds, before another attempt. Cancellation interrupts the wait. There is no jitter, as requested by the maintainer. Retry escalation resets only diff --git a/docs/remote-parity.md b/docs/remote-parity.md index 03f9368d0..20989d118 100644 --- a/docs/remote-parity.md +++ b/docs/remote-parity.md @@ -39,6 +39,21 @@ first: a Pending record can already have an active sidecar if its status update failed. Failed phase, missing CompletionTime, a 404, and gateway errors do not establish file absence. +The delete handler applies these rules in order. Remote cleanup happens before the +CR is deleted with its UID precondition. + +```mermaid +flowchart TD + start["DELETE capture on a remote cluster"] --> phase{"Phase Completed, Failed or Expired?"} + phase -- "No: empty, Pending or Running" --> stop["409: stop the capture first"] + phase -- "Yes" --> never{"Completed, never_started, no pod UID annotation?"} + never -- "Yes" --> delete["Delete CR with UID precondition"] + never -- "No" --> cleanup["Gateway DELETE of capture file"] + cleanup -- "204 or 410" --> delete + cleanup -- "Other status, transport error or unavailable sidecar" --> retain["503: CR retained for retry"] + delete --> done["Success"] +``` + See [capture cleanup recovery](gateway-install.md#capture-cleanup-recovery) for unreachable sites and historical captures without identity metadata. diff --git a/docs/security.md b/docs/security.md index e8d84a526..06bb01aeb 100644 --- a/docs/security.md +++ b/docs/security.md @@ -12,6 +12,41 @@ point. Assume: - a dashboard user with only `servers:read` must not be able to read game passwords (RCON, admin or server passwords) out of a GameServer, - a usage-telemetry receiver is reachable by anyone on the internet, so it must stay safe when fed hostile or invented reports, and must never reveal figures to an unauthenticated viewer (see [Telemetry](#telemetry)). +The main trust boundaries, and the outbound dials that pass a dial-time address guard, are: + +```mermaid +flowchart LR + subgraph Internet["Untrusted"] + Browser["Dashboard user browser"] + Players["Scanners and game players"] + Hosts["Mod download hosts"] + Steam["api.steampowered.com"] + Sinks["Notification sinks (HTTP, SMTP)"] + Sources["Module sources (git, http, OCI)"] + end + subgraph Cluster["Gameplane cluster"] + Ingress["Ingress and web (nginx)"] + API["API (chi gateway)"] + Operator["Operator (controller-runtime)"] + K8s["Kubernetes API server"] + subgraph Game["Game pod (low-trust)"] + Agent["Agent sidecar :8090"] + Server["Game process"] + end + end + Browser -->|"HTTPS, session cookie and CSRF header"| Ingress + Ingress --> API + Players -->|"advertised ports only (NetworkPolicy)"| Server + API -->|"ServiceAccount, Kubernetes RBAC"| K8s + Operator -->|"reconciles CRDs"| K8s + API -->|"mTLS client cert"| Agent + Operator -->|"mTLS, agent CA"| Agent + Agent -->|"IsPublic guard"| Hosts + API -->|"IsPublic guard"| Steam + API -->|"IsAllowed guard"| Sinks + Operator -->|"IsAllowed guard"| Sources +``` + ## Authentication ### Snapshot data and namespace storage trust @@ -55,8 +90,10 @@ Two modes, configurable independently: State validated through a short-lived cookie; `id_token` signature verified against the provider's JWKS. -On first OIDC login for a subject, Gameplane creates a user row with -role `viewer`. Admins must promote new OIDC users manually. +On first OIDC login for a subject, Gameplane creates a user row. Without +role mappings the role is `viewer` and admins must promote new OIDC users +manually; with role mappings the role comes from the user's IdP groups (see +[Install-Time OIDC Role Mappings](#install-time-oidc-role-mappings)). ### Dashboard-managed providers @@ -109,6 +146,20 @@ loopback and private ranges `127.0.0.0/8`, `10.0.0.0/8`, `172.16.0.0/12`, The API applies these rules in order (`api/internal/auth/clientip.go`): +```mermaid +flowchart TD + A["TCP peer address"] --> B{"Peer in api.trustedProxies?"} + B -- no --> C["Client = peer, X-Forwarded-For ignored"] + B -- yes --> D{"Any X-Forwarded-For entry left?"} + D -- no --> E["Client = leftmost address reached"] + D -- yes --> F["Take the rightmost unread entry"] + F --> G{"Entry is an IP address?"} + G -- no --> H["Client = last address reached"] + G -- yes --> I{"Entry in api.trustedProxies?"} + I -- no --> J["Client = this entry"] + I -- yes --> D +``` + 1. A TCP peer outside `api.trustedProxies` is the client. Any `X-Forwarded-For` header on its request is ignored. 2. When the peer is a trusted proxy, the API reads `X-Forwarded-For` from @@ -214,6 +265,24 @@ named set of permissions, and a user is bound to roles **per namespace**. which the shipped SQLite DSN leaves off. An SSO user who is deleted and signs in again is provisioned as a new user. +The middleware decides each request as follows: + +```mermaid +flowchart TD + A["Authenticated request"] --> B{"Route in the permission table?"} + B -- no --> X["Refused (fail closed)"] + B -- yes --> C{"Route needs no permission?"} + C -- yes --> OK["Allowed"] + C -- no --> D["Resolve cluster (cluster selector) and namespace"] + D --> E{"Permission namespaced?"} + E -- no --> F{"Cluster-wide binding on any cluster?"} + E -- yes --> G{"Cluster-wide or same-namespace binding grants it?"} + F -- yes --> OK + F -- no --> X + G -- yes --> OK + G -- no --> X +``` + ### Per-GameServer access (owner + collaborators) In addition to namespace-based RBAC, GameServers support ownership and diff --git a/docs/standalone-panel.md b/docs/standalone-panel.md index b72e60a88..bb6432bff 100644 --- a/docs/standalone-panel.md +++ b/docs/standalone-panel.md @@ -9,6 +9,19 @@ Standalone mode is an explicit choice for a fresh central panel; this guide does not migrate an existing installation's Kubernetes Secrets or Cluster CRs into SQL storage. +In standalone mode the API is the only process that talks to remote clusters. +The Compose profile stores its database and encryption key in separate volumes. + +```mermaid +flowchart LR + browser["Browser over HTTPS reverse proxy"] --> web["web (nginx, 127.0.0.1:8080)"] + web -- "API_UPSTREAM :8000" --> api["gameplane-api (one replica)"] + api --> db[("panel-data: /data/gameplane.db")] + api --> key[("panel-keys: /keys/panel.key")] + api -- "Direct Kubernetes API" --> k8s["Registered cluster Kubernetes API"] + api -- "mTLS gateway" --> gw["Registered cluster gateway"] +``` + ## Docker Compose Install Git and Docker with the Compose plugin. Use a release or commit that @@ -425,8 +438,9 @@ restart; a remote operator upgrade may roll game pods. For a panel-only Helm release, repeat the installation command with the updated chart, matching images, and your standalone values file. Keep `api.replicas=1` and the existing key storage, including when using PostgreSQL. -All Helm API deployments use Recreate and accept a brief panel outage during -rollout. This does not fence a process on a partitioned node after force +Helm API deployments use Recreate by default, which accepts a brief panel outage +during rollout. With `api.postgresHA.enabled` the Deployment instead uses +RollingUpdate with `maxUnavailable: 1` and `maxSurge: 0`. Neither mode fences a process on a partitioned node after force deletion. See [API upgrades and readiness](install.md#api-upgrades-brief-downtime) for the singleton boundary and the separate database readiness probe. diff --git a/docs/tailscale-forwarding-integration.md b/docs/tailscale-forwarding-integration.md index 2874177b5..3f44a61ef 100644 --- a/docs/tailscale-forwarding-integration.md +++ b/docs/tailscale-forwarding-integration.md @@ -95,6 +95,16 @@ devices if the hostname has acquired a suffix; that state must remain not ready. ## Exercise the datapath +The fixture's datapath admits only the approved client, and only to advertised ports: + +```mermaid +flowchart LR + A["Approved client: grant to tag:gameplane-test"] -->|"tcp:25565, udp:19132"| N["Tunnel node gameplane-forward-test"] + D["Denied client: no grant"] -. "must fail" .-> N + N -->|"advertised ports only"| S["Backing Service tailnet-echo"] + S --> E["Echo backend"] +``` + On the approved tailnet client, run this with the fixture's MagicDNS name: ```python diff --git a/docs/telemetry-provider.md b/docs/telemetry-provider.md index a186eb1ab..832b98afe 100644 --- a/docs/telemetry-provider.md +++ b/docs/telemetry-provider.md @@ -23,6 +23,35 @@ project's data-handling statement is at The dashboard listener starts only when `DASHBOARD_TOKEN` is set. The public listener answers `404` for `/metrics`. +A report travels from an install's reporter, through the checks on the public +listener, into the daily aggregates that the two listeners read: + +```mermaid +flowchart TD + subgraph Install["Install (API telemetry reporter)"] + TK["Tick: basic consent on and send slot due"] --> BD["Build report: basic, plus extended when enabled"] + BD --> SG["Extended report: sign body"] + SG --> PW["Solve proof-of-work when the endpoint asks"] + end + PW --> IN["POST /ingest on public listener"] + IN --> AU{"AUTH_TOKEN set and matched?"} + AU -- no --> E1["401"] + AU -- yes --> POW{"INGEST_POW off, or challenge solved?"} + POW -- no --> E2["428"] + POW -- busy --> E2b["503, Retry-After 60"] + POW -- yes --> DC["Decode and validate report"] + DC --> EX{"Extended part?"} + EX -- yes --> VS["Verify signature and install ID claim"] + EX -- no --> RL + VS -- refused --> E4["403 replay, 409 install ID claimed"] + VS -- ok --> RL{"Within INGEST_SOURCE_DAILY_LIMIT?"} + RL -- no --> E3["429"] + RL -- yes --> AG["Daily aggregates in SQLite"] + AG --> DB["Dashboard listener: /api/v1/views, /metrics"] + AG --> SM["GET /v1/summary: snapshot, refreshed at most every 5 min"] + LC["Hourly lifecycle sweep"] --> AG +``` + ## Deploy the image The receiver is a single static binary in a distroless, non-root image: diff --git a/docs/template-rollouts.md b/docs/template-rollouts.md index 2abf84f4f..a0ac25be5 100644 --- a/docs/template-rollouts.md +++ b/docs/template-rollouts.md @@ -29,6 +29,25 @@ Pin `Module.spec.version` before upgrading and enable staging before a later catalog change. A pre-upgrade backup, restore or wipe already in progress finishes before baseline initialization. A new server gets its pin before first startup. +An installed update reaches a running server only through this admission path: + +```mermaid +flowchart TD + A["Module install changes the shared GameTemplate"] --> B["Desired digest in status.templateRevision"] + B --> C{"Rollout policy"} + C -->|Automatic| E["Admit"] + C -->|OnRequest| D{"requestedRevision equals desired digest?"} + D -->|No| H["Held: effective pin unchanged"] + D -->|Yes| F{"cancel-template-rollout annotation set to this digest?"} + F -->|Yes| H + F -->|No| E + E --> G["Wait for any backup, restore or wipe owner"] + G --> I["Graceful stop through the previous effective template"] + I --> J["Old Pod gone, switch effective pin"] + J --> K["Create replacement Pod"] + K --> L["Owner released, running revision observed"] +``` + Inspect the three digests: ```sh diff --git a/docs/translating.md b/docs/translating.md index 3e50b68cf..f4687e8bd 100644 --- a/docs/translating.md +++ b/docs/translating.md @@ -9,6 +9,21 @@ your work, and when a language shows in the picker. Translations are welcome as a partial pack. A pack merges even when it is not finished. It stays hidden from users until enough of it is translated. +A message moves from the dashboard source to a language picker along this path: + +```mermaid +flowchart LR + A["Dashboard source: intl.formatMessage calls"] --> B["npm run i18n:extract writes locales/en/app.json"] + B --> C["Translators: Weblate or a pull request"] + C --> D["locales/tag/app.json and meta.json"] + D --> E["i18n-check: findings and exit codes"] + E -->|accepted entries| F["npm run i18n:compile writes src/generated/i18n/tag.json"] + E -->|listed languages| G["npm run i18n:manifest writes languages.json"] + F --> H["Dashboard shows English for anything not accepted"] + G --> I["Picker lists languages at 80% or more, ltr"] + D --> J["i18n/embed.go embeds the packs into the Go catalog used by the API and operator"] +``` + ## Folder layout ``` diff --git a/docs/tunnels.md b/docs/tunnels.md index 1ba4c9a57..719cf4ac7 100644 --- a/docs/tunnels.md +++ b/docs/tunnels.md @@ -29,6 +29,18 @@ add an extra pod and outbound dependency. ## Choosing a provider +Each provider runs a relay client in a separate tunnel pod. That pod dials out to the relay, and forwards player traffic to the game's backing Service: + +```mermaid +flowchart LR + P["Players"] -->|"public address or tailnet name"| R["Relay: frps, Tailscale tailnet or playit.gg"] + T["Tunnel pod: gameplane-tunnel"] -->|"outbound session"| R + T -->|"dials server.namespace.svc"| S["Backing Service"] + S -->|"running"| G["Game pod"] + S -->|"asleep: routed to sentinel"| W["Wake sentinel"] + W -->|"wakes, then dials game-direct Service"| G +``` + | Feature | frp | Tailscale | playit.gg | |---|---|---|---| | **Public/Private** | Public | Private (tailnet only) | Public | @@ -372,15 +384,39 @@ Service, not to traffic arriving through the tunnel: ## Interaction with idle auto-sleep and wake-on-connect -Idle auto-sleep and tunnels compose; a few things to know: +Idle auto-sleep and tunnels compose; a few things to know. The sequence below shows a join while the game is asleep: + +```mermaid +sequenceDiagram + participant Player + participant Relay + participant Tunnel as Tunnel pod + participant GS as Backing Service + participant Sentinel as Wake sentinel + participant API as Kubernetes API + participant Op as Operator + participant Game as Game pod + + Player->>Relay: connect to public address + Relay->>Tunnel: forward over outbound session + Tunnel->>GS: dial backing Service + GS->>Sentinel: route (server asleep) + Sentinel->>API: patch wake-requested token + API->>Op: GameServer change + Op->>API: clear sleep marker, ack token + Op->>Game: scale game StatefulSet up + Sentinel->>Game: poll game-direct Service until it accepts + Sentinel-->>Player: hold connection, then proxy after handoff +``` - **The tunnel pod stays awake.** Only the game pod sleeps. When the game enters idle sleep, the tunnel pod continues to hold the relay connection and the public address remains advertised. - **Wake-on-connect still works.** If a player connects to the public address - while the game is asleep, the relay wakes the game pod (assuming - `spec.idle.wakeOnConnect` is enabled). The player's connection is handed off - to the newly-started game pod. + while the game is asleep, the relay forwards the connection to the backing + Service, which routes to the wake sentinel (assuming `spec.idle.wakeOnConnect` + is enabled). The tunnel pod does not request the wake; the sentinel does. The + sentinel holds the connection and hands it off once the game pod accepts it. - **Potential reconnect.** Depending on the relay provider and your expose mode, a player may need to reconnect once after the game wakes — the relay may drop the dormant connection and require a new dial to the newly-running pod. diff --git a/docs/unified-dashboard.md b/docs/unified-dashboard.md index 5c85291fd..60d1d34e6 100644 --- a/docs/unified-dashboard.md +++ b/docs/unified-dashboard.md @@ -36,6 +36,25 @@ Collection reads use bounded concurrency, timeouts and response limits. They ret Filters issue a narrower backend read rather than only hiding rows from a capped combined response. Scope metadata exposes explicitly permitted scopes and scopes containing returned owned/collaborating servers, allowing stable Cluster / namespace choices without revealing unrelated registrations. +Authenticated fleet reads such as `GET /fleet/servers` follow the flow below. Each +scope is read independently, so one unavailable site yields partial data rather +than an error for the whole list. + +```mermaid +flowchart TD + req["GET /fleet/servers with optional cluster and namespace filters"] --> cand["Discover local, default and registered clusters"] + cand --> scopes["Build cluster and namespace scopes the user can read"] + scopes --> cap{"More than 128 scopes?"} + cap -- "Yes" --> trim["Keep granted scopes first and mark partial"] + cap -- "No" --> fan + trim --> fan["Read scopes with 4 workers, 5 s timeout each"] + fan --> merge["Merge and sort by cluster, namespace and name"] + merge --> lim{"More than the limit of 2000 items?"} + lim -- "Yes" --> cut["Truncate and mark partial"] + lim -- "No" --> out + cut --> out["Return items, scopes, issues and partial flag"] +``` + Existing per-target mutation and stream APIs remain in use. Every client operation captures its target before asynchronous work, including chained calls and raw file/socket paths. Query keys and invalidation include the resource's cluster and namespace; instance-specific data additionally includes UID. Route changes discard old forms, results and reconnect attempts. UID is also a cache/row identity; it does not claim a new universal server-side mutation precondition beyond existing endpoint and gateway safeguards. ## Acceptance diff --git a/docs/wake-qualification.md b/docs/wake-qualification.md index 36fc90e67..5a0bdc597 100644 --- a/docs/wake-qualification.md +++ b/docs/wake-qualification.md @@ -133,6 +133,21 @@ The GameServer UID and sleep episode let a replacement operator resume the same reservation. A queued game retains its unacknowledged wake token and waker. Its `status.idle.reason` reports the capacity wait. When the game StatefulSet first has a Ready replica the next waiter can use the slot. + +The reservation moves through these states; the diagram omits the wait and retry loops: + +```mermaid +stateDiagram-v2 + [*] --> Asleep: sleep marker set + Asleep --> Requested: sentinel sets wake token + Requested --> Queued: fleet limit reached, token kept + Queued --> Admitted: a slot is freed + Requested --> Admitted: slot available + Admitted --> Starting: sleep marker cleared, token acked + Starting --> Released: first Ready replica + Released --> [*] +``` + Readiness ends startup accounting. Only the game client's completed join measures the player objective. diff --git a/website b/website index 262105c3d..0a65468f7 160000 --- a/website +++ b/website @@ -1 +1 @@ -Subproject commit 262105c3d4ec2a97dd611e5534090d20b1367a0f +Subproject commit 0a65468f7579935c4e021710b56ed8e70d909e99