Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 19 additions & 15 deletions api/internal/handlers/installation.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package handlers

import (
"context"
"encoding/json"
"log/slog"
"net/http"
Expand All @@ -14,25 +15,28 @@ import (
// MountInstallation exposes capabilities only through the authenticated router.
func MountInstallation(r chi.Router, store *db.Store, standalone bool, version string) {
r.Get("/admin/installation", func(w http.ResponseWriter, req *http.Request) {
// The display name is optional: a config failure must not hide the
// static capabilities that the rest of the dashboard depends on.
name := "gameplane"
raw, found, err := store.ConfigValue(req.Context(), "general")
if err != nil {
slog.Warn("installation name: read general config", "err", err)
} else if found {
var general generalCfg
if err := json.Unmarshal([]byte(raw), &general); err != nil {
slog.Warn("installation name: decode general config", "err", err)
} else if configuredName := strings.TrimSpace(general.InstanceName); configuredName != "" {
name = configuredName
}
}
writeJSON(w, struct {
Standalone bool `json:"standalone"`
LocalCluster bool `json:"localCluster"`
Version string `json:"version"`
InstanceName string `json:"instanceName"`
}{Standalone: standalone, LocalCluster: !standalone, Version: version, InstanceName: name})
}{Standalone: standalone, LocalCluster: !standalone, Version: version, InstanceName: installationDisplayName(req.Context(), store)})
})
}

// The optional display name is shared by the dashboard and valid public links.
// A configuration failure must leave both available with the default brand.
func installationDisplayName(ctx context.Context, store *db.Store) string {
raw, found, err := store.ConfigValue(ctx, "general")
if err != nil {
slog.Warn("installation name: read general config", "err", err)
} else if found {
var general generalCfg
if err := json.Unmarshal([]byte(raw), &general); err != nil {
slog.Warn("installation name: decode general config", "err", err)
} else if name := strings.TrimSpace(general.InstanceName); name != "" {
return name
}
}
return "gameplane"
}
75 changes: 59 additions & 16 deletions api/internal/handlers/shares.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,17 @@ import (
"errors"
"io"
"net/http"
"net/netip"
"strconv"
"strings"
"time"

"github.com/go-chi/chi/v5"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/validation"

"github.com/GameplanePanel/gameplane/api/internal/auth"
"github.com/GameplanePanel/gameplane/api/internal/db"
Expand Down Expand Up @@ -312,6 +315,8 @@ func mutateShareHandler(reg *kube.Registry, store *db.Store) http.HandlerFunc {

type sharePublicResp struct {
ServerName string `json:"serverName"`
InstanceName string `json:"instanceName"`
Description string `json:"description,omitempty"`
Status string `json:"status"`
ManuallyStopped bool `json:"manuallyStopped"`
CanStart bool `json:"canStart"`
Expand Down Expand Up @@ -384,6 +389,8 @@ func resolveShareHandler(reg *kube.Registry, store *db.Store) http.HandlerFunc {

resp := sharePublicResp{
ServerName: link.ServerName,
InstanceName: installationDisplayName(req.Context(), store),
Description: strings.TrimSpace(obj.GetAnnotations()["gameplane.local/description"]),
Status: status,
Address: address,
PlayersOnline: players,
Expand Down Expand Up @@ -547,17 +554,18 @@ func getPlayersOnline(obj *unstructured.Unstructured) *int32 {
return nil
}

// getPublicAddress returns the first publicly reachable (non-private) endpoint
// that is served by a tunnel provider. If no tunnel endpoint, falls back to the
// first non-private regular endpoint. Returns nil if no suitable endpoint exists.
// getPublicAddress picks a published host and its matching port. The operator
// resolves per-server and template hostnames after the backing Service is ready.
func getPublicAddress(obj *unstructured.Unstructured) *shareAddr {
endpoints, ok, err := unstructured.NestedSlice(obj.Object, "status", "endpoints")
if err != nil || !ok || len(endpoints) == 0 {
return nil
}

expose, _, _ := unstructured.NestedString(obj.Object, "spec", "networking", "expose")
var fallback *shareAddr
configuredHost, _, _ := unstructured.NestedString(obj.Object, "spec", "networking", "hostname")
var best *shareAddr
bestRank := 0
for _, ep := range endpoints {
epMap, ok := ep.(map[string]interface{})
if !ok {
Expand All @@ -569,26 +577,61 @@ func getPublicAddress(obj *unstructured.Unstructured) *shareAddr {
}
host, _, _ := unstructured.NestedString(epMap, "host")
port := nestedPort(epMap)
if host == "" || port == 0 {
if host == "" || host == "None" || port == 0 {
continue
}
provider, _, _ := unstructured.NestedString(epMap, "tunnelProvider")
if provider != "" {
return &shareAddr{Host: host, Port: port}
}
serviceAddress, _, _ := unstructured.NestedString(epMap, "serviceAddress")
// Older operators published the Service ClusterIP as the NodePort
// host. A refreshed endpoint records the ClusterIP separately.
if expose == "NodePort" {
serviceAddress, _, _ := unstructured.NestedString(epMap, "serviceAddress")
if serviceAddress == "" || serviceAddress == host {
continue
}
if provider == "" && expose == "NodePort" && (serviceAddress == "" || serviceAddress == host) {
continue
}
if fallback == nil {
fallback = &shareAddr{Host: host, Port: port}

rank := shareAddressRank(host, configuredHost, serviceAddress, provider)
if rank > bestRank {
best = &shareAddr{Host: host, Port: port}
bestRank = rank
}
}
return fallback
return best
}

func shareAddressRank(host, configuredHost, serviceAddress, provider string) int {
const (
invalid = iota
nativeIP
tunnelIP
nativeDNS
tunnelDNS
advertisedDNS
)
// Some providers wrap IPv6 literals in brackets for use with a port.
if strings.HasPrefix(host, "[") {
addr, err := netip.ParseAddrPort(host + ":0")
if err != nil {
return invalid
}
host = addr.Addr().String()
}
if _, err := netip.ParseAddr(host); err == nil {
if provider != "" {
return tunnelIP
}
return nativeIP
}
if len(validation.IsDNS1123Subdomain(strings.ToLower(strings.TrimSuffix(host, ".")))) != 0 {
return invalid
}
if provider != "" {
return tunnelDNS
}
// The operator may advertise a template default identical to the load
// balancer's ingress hostname. Its source is indistinguishable in status.
if strings.EqualFold(host, configuredHost) || (configuredHost == "" && serviceAddress != "") {
return advertisedDNS
}
return nativeDNS
}

// nestedPort extracts the "port" field from an endpoint map as an int32.
Expand Down
71 changes: 70 additions & 1 deletion api/internal/handlers/shares_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -241,8 +241,16 @@ func TestChangeShareWakePermission(t *testing.T) {
func TestShareResolveValidToken(t *testing.T) {
store := newTestStore(t)
ownerID := insertShareTestUser(t, store, "owner-resolve")
if _, err := store.DB.ExecContext(t.Context(), `INSERT INTO config(key, value) VALUES ('general', '{"instanceName":" Northstar Games ","externalURL":"https://internal.example","defaultNamespace":"internal-games"}')`); err != nil {
t.Fatal(err)
}
server := newShareTestServer("srv-resolve", ownerID)
annotations := server.GetAnnotations()
annotations["gameplane.local/description"] = " A survival world for our community. "
annotations["internal.example/note"] = "internal-only note"
server.SetAnnotations(annotations)
reg := kube.NewRegistry("local")
reg.Set("local", fakeKubeClient(newShareTestServer("srv-resolve", ownerID)))
reg.Set("local", fakeKubeClient(server))
h := mountSharesRouter(reg, store)
owner := &auth.User{ID: ownerID, Username: "owner-resolve", Role: "admin"}

Expand Down Expand Up @@ -270,6 +278,9 @@ func TestShareResolveValidToken(t *testing.T) {
if resp["serverName"] != "srv-resolve" {
t.Fatalf("serverName = %v, want srv-resolve; body=%s", resp["serverName"], body)
}
if resp["instanceName"] != "Northstar Games" || resp["description"] != "A survival world for our community." || bytes.Contains(body, []byte("internal")) {
t.Fatalf("unexpected public share identity: %s", body)
}
if resp["status"] != "Running" {
t.Fatalf("status = %v, want Running; body=%s", resp["status"], body)
}
Expand Down Expand Up @@ -320,6 +331,9 @@ func TestShareResolvePrivateEndpointOmitted(t *testing.T) {
if _, ok := resp["address"]; ok {
t.Fatalf("address must be omitted for a private-only endpoint, got %v; body=%s", resp["address"], body)
}
if _, described := resp["description"]; described || resp["instanceName"] != "gameplane" {
t.Fatalf("unexpected public share defaults: %s", body)
}
}

// TestShareResolveInvalidToken verifies that unknown, expired, and revoked
Expand Down Expand Up @@ -516,6 +530,8 @@ func TestSharePublicPayloadSafe(t *testing.T) {
// The response should only have the safe fields.
expectedKeys := map[string]bool{
"serverName": true,
"instanceName": true,
"description": true,
"status": true,
"manuallyStopped": true,
"canStart": true,
Expand Down Expand Up @@ -563,6 +579,59 @@ func TestShareNodePortPlayerAddress(t *testing.T) {
}
}

func TestSharePrefersPublishedHostnameAndItsPort(t *testing.T) {
t.Parallel()
const gameHost = "play.example.com"
nativeDNS := map[string]any{"host": gameHost, "port": int64(31042), "serviceAddress": "10.43.0.5"}
relayDNS := map[string]any{"host": "relay.example.com", "port": int64(31999), "tunnelProvider": "frp"}
relayIP := map[string]any{"host": "2001:db8::2", "port": int64(31999), "tunnelProvider": "frp"}
directIP := map[string]any{"host": "192.0.2.10", "port": int64(31042), "serviceAddress": "10.43.0.5"}
for _, tc := range []struct {
name, configured string
endpoints []any
want shareAddr
}{
{"configured native name after relay", gameHost, []any{relayDNS, nativeDNS}, shareAddr{gameHost, 31042}},
{"inherited native name before relay", "", []any{nativeDNS, relayDNS}, shareAddr{gameHost, 31042}},
{"DNS relay over native IP", "", []any{directIP, relayDNS}, shareAddr{"relay.example.com", 31999}},
{"configured name awaiting reconciliation", gameHost, []any{relayIP, directIP}, shareAddr{"2001:db8::2", 31999}},
{"other published DNS over a relay IP", "pending.example.com", []any{relayIP, nativeDNS}, shareAddr{gameHost, 31042}},
{"malformed hosts before a bracketed IPv6 relay", "", []any{
map[string]any{"host": "[2001:db8::1", "port": int64(25565), "tunnelProvider": "frp"},
map[string]any{"host": "invalid/host", "port": int64(25566), "tunnelProvider": "frp"},
map[string]any{"host": "[2001:db8::2]", "port": int64(31999), "tunnelProvider": "frp"},
}, shareAddr{"[2001:db8::2]", 31999}},
{"configured name on private endpoint", gameHost, []any{
map[string]any{"host": gameHost, "port": int64(30123), "private": true},
relayIP,
}, shareAddr{"2001:db8::2", 31999}},
} {
t.Run(tc.name, func(t *testing.T) {
obj := newShareTestServer("world", 1)
obj.Object["spec"] = map[string]any{"networking": map[string]any{"expose": "NodePort", "hostname": tc.configured}}
obj.Object["status"].(map[string]any)["endpoints"] = tc.endpoints
if got := getPublicAddress(obj); got == nil || *got != tc.want {
t.Fatalf("got %+v, want %+v", got, tc.want)
}
})
}
}

func TestSharePrefersLoadBalancerDNSMatchingTemplateHostname(t *testing.T) {
t.Parallel()
const gameHost = "games.example.com"
obj := newShareTestServer("world", 1)
obj.Object["spec"] = map[string]any{"networking": map[string]any{"expose": "LoadBalancer"}}
obj.Object["status"].(map[string]any)["endpoints"] = []any{
map[string]any{"host": "relay.example.com", "port": int64(31999), "tunnelProvider": "frp"},
map[string]any{"host": gameHost, "serviceAddress": gameHost, "port": int64(25565)},
}
want := shareAddr{gameHost, 25565}
if got := getPublicAddress(obj); got == nil || *got != want {
t.Fatalf("got %+v, want %+v", got, want)
}
}

// TestSharePrivateEndpointNotReturned verifies that private/tailnet-only endpoints
// are never returned to anonymous callers.
func TestSharePrivateEndpointNotReturned(t *testing.T) {
Expand Down
4 changes: 3 additions & 1 deletion api/specs.md
Original file line number Diff line number Diff line change
Expand Up @@ -666,6 +666,8 @@ Verify from `/api/go.mod`.
**005_audit_chain.sql:** (hash-chain integrity)
- Adds `prev_hash` and `hash` columns to `audit_events` for tamper detection

Valid public share responses include `instanceName` from the panel’s general settings (default `gameplane`) and the optional `description` from the server’s `gameplane.local/description` annotation. The connection address uses the operator’s published, non-private endpoints. An advertised server hostname takes priority. Without a server override, a native DNS endpoint with a recorded Service address takes priority, including when a template hostname matches the load balancer’s ingress hostname. Other DNS names follow, then IP addresses. Tunnels take precedence among otherwise equivalent addresses. Each host keeps its endpoint’s port.

**Public share power policy:** `GET /shares/{token}` includes `manuallyStopped` (the server's explicit stop setting) and `canStart` (the link permits waking and the server is not manually stopped). The existing `status` remains the observed phase. `POST /shares/{token}/start` is wake-only: an authorized link to a manually stopped server returns 409 with the stable generic JSON body `{"error":"server stopped"}` without stamping a wake or changing `spec.suspend`. Idle-asleep servers still receive a conditional wake annotation and 202; the operator owns reconciliation. Invalid and view-only start requests retain the identical neutral 404 response.

**006_share_links.sql:** (unauthenticated server access tokens)
Expand Down Expand Up @@ -749,7 +751,7 @@ Foreign keys are enforced only on Postgres (modernc-sqlite runs with FK OFF); th
`GameServer.spec.config` stores wizard values in clear, including those of `type: password` fields in the template's `configSchema`. Anyone holding `servers:read` (or the owner/collaborator fallback) could therefore read every password. The API now redacts them; implementation and tests are in `api/internal/handlers/config_redact.go` and `config_redact_test.go`.
- **Effective template.** `GET /servers/{name}/template` reads the server's verified, admitted snapshot or the installed template before its first pin. It requires read access to the exact server. A caller without cluster-wide `templates:read` on the target cluster must be the server's owner or a collaborator on it (#1063), so the dashboard can show that server's template-driven tabs; anyone else still needs `templates:read`.
- **Marker:** `__gameplane_redacted__`. On reads, each non-empty password-type value is replaced by the marker (an empty value stays empty so clients can show "not set"). The password-field set comes from the server's effective `GameTemplate.spec.configSchema`. When `gameplane.local/effective-template-revision` is set, the API reads the server's immutable snapshot from the selected cluster and namespace, verifies its controller owner, identity, digest and template name, and rejects deleting snapshots. The exact stored JSON must match the pinned SHA-256 digest. An OnRequest server keeps its admitted password rules even when the catalog removes or retypes those fields. Servers without a pin use the current catalog. Rules are memoised only within one request or SSE event, keyed by template, namespace, server name, UID and revision.
- **Covered paths (one helper):** GET/POST/PUT `/servers` and `/servers/{name}` (including the create and update replies), `POST /servers/{name}:clone` reply (the clone itself stores the source's values verbatim), `GET /users/me/servers`, `GET /fleet/servers`, and the `/events` SSE stream (each watch event is redacted on a copy). Share links expose only name/status/address/player count; capture, mod, tunnel-credential, notification and WebSocket paths never carry `spec.config`; the audit log and its sinks record actor/method/path/target/status/ip/reason only and never request bodies.
- **Covered paths (one helper):** GET/POST/PUT `/servers` and `/servers/{name}` (including the create and update replies), `POST /servers/{name}:clone` reply (the clone itself stores the source's values verbatim), `GET /users/me/servers`, `GET /fleet/servers`, and the `/events` SSE stream (each watch event is redacted on a copy). Share links expose the instance name, server name, optional description, power and wake status, address and player count. Share, capture, mod, tunnel-credential, notification and WebSocket paths never carry `spec.config`. The audit log and its sinks record actor/method/path/target/status/ip/reason only and never request bodies.
- **Fail closed:** when the template cannot be read (no `templateRef`, not found, API error, malformed `configSchema`), or a pinned snapshot is missing, unreadable or invalid, every non-empty config value is redacted. A failed pin lookup never falls back to the latest catalog. The API needs `get` on ConfigMaps in each allowed game namespace; the chart grants it through the games Role, and remote kubeconfigs need the same permission. Failed lookups are not cached. PUT secret preservation uses this same effective schema.
- **Update rule (PUT `/servers/{name}`)**, applied before the write (markers: every key; the other rules: per password-type key, every key when failing closed): a value equal to the marker keeps the stored value for ANY key, whether or not the current template marks it a password and whatever the stored value's type (the marker is API-emitted, and a fail-closed read marks every key); if the key is absent from the stored object the marker is dropped, never stored; a different non-empty value replaces it; an explicit empty string clears it only when the field is optional, for a `required` field (or when failing closed, where optionality is unknown) the stored value is kept; a key omitted from the body is removed as in any PUT, except a `required` password field, which is restored. This is what makes the dashboard's whole-`spec` PUT (`mergeDraftOntoLatest`) safe. On POST, marker values are dropped.
- **Not covered:** Kubernetes API readers (kubectl, GitOps, the optional read-only `mcp-server`) see the stored object; protect it with cluster RBAC.
Expand Down
Binary file modified assets/design-export/fig/1-46396.fig
Binary file not shown.
Binary file modified assets/design-export/fig/1-46397.fig
Binary file not shown.
Binary file modified assets/design-export/fig/1-46398.fig
Binary file not shown.
Binary file modified assets/design-export/fig/B57dG.fig
Binary file not shown.
Binary file modified assets/design-export/fig/C2LQE4.fig
Binary file not shown.
Binary file modified assets/design-export/fig/EWrn0.fig
Binary file not shown.
Binary file modified assets/design-export/fig/EcoGD.fig
Binary file not shown.
Binary file modified assets/design-export/fig/FBiMN.fig
Binary file not shown.
Binary file modified assets/design-export/fig/LYPXU.fig
Binary file not shown.
Binary file modified assets/design-export/fig/WrmU5.fig
Binary file not shown.
Binary file modified assets/design-export/fig/Z0oyh.fig
Binary file not shown.
Binary file modified assets/design-export/fig/ZlLf0.fig
Binary file not shown.
Binary file modified assets/design-export/fig/iYUWc.fig
Binary file not shown.
Binary file modified assets/design-export/fig/kK8Ji.fig
Binary file not shown.
Binary file modified assets/design-export/fig/p8QSPq.fig
Binary file not shown.
Binary file modified assets/design-export/fig/q31B6w.fig
Binary file not shown.
Binary file modified assets/design-export/fig/qFLfB.fig
Binary file not shown.
Loading
Loading