diff --git a/api/internal/handlers/resources.go b/api/internal/handlers/resources.go index 6f571ccdf..7dae9b4ef 100644 --- a/api/internal/handlers/resources.go +++ b/api/internal/handlers/resources.go @@ -74,9 +74,15 @@ func mountOne(r chi.Router, reg *kube.Registry, store *db.Store, auditor *audit. // Effective templates can differ from the catalog while a server's rollout // is pending. Resolve the snapshot through its authorized server identity. +// +// The caller needs templates:read on the cluster, or must own or collaborate +// on this server: owners and collaborators manage the server's mods, modpacks +// and console, and the dashboard needs its template to show those tabs +// (#1063). The grant covers only the template of a server they hold. func effectiveTemplateHandler(reg *kube.Registry) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { - if !auth.UserFromContext(req.Context()).Can("templates:read", false, scope.RequestedCluster(req), "") { + u := auth.UserFromContext(req.Context()) + if u == nil { httperr.WriteMessage(w, req, messages.New("server.forbidden", nil)) return } @@ -92,6 +98,12 @@ func effectiveTemplateHandler(reg *kube.Registry) http.HandlerFunc { if !ok { return } + if cl := scope.RequestedCluster(req); !u.Can("templates:read", false, cl, "") { + if access := serverFleetAccess(u, cl, ns, server); !access.IsOwner && !access.IsCollaborator { + httperr.WriteMessage(w, req, messages.New("server.forbidden", nil)) + return + } + } tmpl, err := k.EffectiveGameTemplate(req.Context(), server) if err != nil { httperr.Write(w, req, err) diff --git a/api/internal/handlers/server_template_access_test.go b/api/internal/handlers/server_template_access_test.go new file mode 100644 index 000000000..709a902ce --- /dev/null +++ b/api/internal/handlers/server_template_access_test.go @@ -0,0 +1,60 @@ +package handlers + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + "github.com/GameplanePanel/gameplane/api/internal/auth" + "github.com/GameplanePanel/gameplane/api/internal/kube" +) + +// Owners and collaborators of a server read its template without +// templates:read, so the dashboard can show the Mods, Modpacks and Console +// tabs they manage (#1063). Anyone else still needs templates:read. +func TestServerTemplate_OwnerAndCollaboratorWithoutTemplatesRead(t *testing.T) { + k := fakeKubeClient(catalogWithoutPasswords()) + gs := serverWithConfig("alpha", plainConfig()) + gs.SetAnnotations(map[string]string{ + "gameplane.local/owner-id": "7", + collaboratorsAnnotation: "9, 42", + }) + if _, err := k.Dynamic.Resource(kube.GVRs["servers"]).Namespace(redactNS).Create(t.Context(), gs, metav1.CreateOptions{}); err != nil { + t.Fatal(err) + } + router := mountResourcesRouter(k) + get := func(u *auth.User) *httptest.ResponseRecorder { + req := httptest.NewRequestWithContext(auth.WithUser(t.Context(), u), http.MethodGet, "/servers/alpha/template", nil) + rr := httptest.NewRecorder() + router.ServeHTTP(rr, req) + return rr + } + + for name, u := range map[string]*auth.User{ + "collaborator": {ID: 42}, + "owner": {ID: 7}, + } { + t.Run(name, func(t *testing.T) { + rr := get(u) + var got map[string]any + if rr.Code != http.StatusOK || json.Unmarshal(rr.Body.Bytes(), &got) != nil { + t.Fatalf("unexpected answer: %d %s", rr.Code, rr.Body) + } + md, _ := got["metadata"].(map[string]any) + if md["name"] != catalogWithoutPasswords().GetName() { + t.Fatalf("unexpected template: %v", got["metadata"]) + } + }) + } + + t.Run("server reader without a server grant", func(t *testing.T) { + u := inventoryUser("local", "*", "servers:read") + u.ID = 100 + if rr := get(u); rr.Code != http.StatusForbidden { + t.Fatalf("template read without templates:read or a server grant: %d %s", rr.Code, rr.Body) + } + }) +} diff --git a/api/specs.md b/api/specs.md index dd78a1bae..18148f3c7 100644 --- a/api/specs.md +++ b/api/specs.md @@ -739,7 +739,7 @@ Foreign keys are enforced only on Postgres (modernc-sqlite runs with FK OFF); th ### GameServer config password redaction - Every covered response omits `metadata.annotations["kubectl.kubernetes.io/last-applied-configuration"]`: this historical manifest can contain passwords absent from the current config or template. Omission applies even when current config is absent, empty, or malformed; stored Kubernetes metadata and other annotations remain unchanged. `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 and cluster-wide `templates:read` on the target cluster. +- **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. - **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. diff --git a/changelog/unreleased/1103-collaborator-mods-tabs.md b/changelog/unreleased/1103-collaborator-mods-tabs.md new file mode 100644 index 000000000..1f440d46d --- /dev/null +++ b/changelog/unreleased/1103-collaborator-mods-tabs.md @@ -0,0 +1,8 @@ +# Server collaborators see the Mods and Modpacks tabs + +A server's collaborators (and owner) no longer need the cluster-wide +`templates:read` permission to see the Mods, Modpacks and Console tabs on the +servers they work on. As before, each tab still appears only when the server's +template and active version support it. The server's template is read through +the server itself for them, so nothing changes for other users. +[PR #1103](https://github.com/GameplanePanel/Gameplane/pull/1103) diff --git a/web/specs.md b/web/specs.md index d377525b5..a20275f39 100644 --- a/web/specs.md +++ b/web/specs.md @@ -1181,6 +1181,7 @@ Each namespace is an object of typed functions building and fetching URLs: `Players.operators(server, namespace?)` reads configured operator identities through the resource client's captured cluster and namespace. Its optional `capabilities.operators` flag is provided by the agent; the dashboard does not infer support from game names or read arbitrary game files. The method accepts the resource client's cancellation signal. - **capabilities.ts** — `resolveConsoleMode(template)`, `serverHasMods(template, server)`, `serverHasModpacks(template, server)` — drive tab visibility +- **serverTemplate.ts** — `getServerTemplate(client, name, ns, templateName)` reads a server's template for ServerDetail, the Console tab and the Settings tab: the catalog `GET /templates/{name}` first, and only after a 403 the server-scoped `GET /servers/{name}/template`, which the API allows for the server's owner and collaborators without `templates:read` (#1063). The Settings tab keeps reading `Servers.effectiveTemplate` directly when a rollout revision is pinned. - **useThemePreferences.ts** — theme preferences plumbing (feature 016; full behavior documented under "User Theme Customization" above): `useThemePreferences(me?, opts?)` reconciles the backend `preferences` from `/users/me` over the `gameplane-theme-prefs` localStorage cache (backend wins on drift), exposes `preferences` + an optimistic `updatePreferences(patch)` mutation (DOM + cache first, PUT via `Users.updatePreferences`, revert-and-report on failure, replay-on-`online` after connectivity loss), and keeps the DOM attributes (`class`/`data-theme`, `data-theme-preset`, `data-theme-type`, `data-custom-css`) and the `#gameplane-custom-css` overlay (always last in ``; unmounted on logout and on `/login`/`/share/:token`) in sync. Plain helpers exported for routes and the boot script's post-boot path: `isSafeModeActive()` (`?safe-mode=1` or the `gameplane-safe-mode` sessionStorage flag — suspends only the overlay), `readThemePreferences` / `writeThemePreferences`, `normalizeThemePreferences`, `themePreferencesEqual`, `applyThemePreferences`, `unmountCustomCssOverlay`, plus the storage keys/element ids and the `gameplane-theme-error` window event. The inline `theme-boot` script in `index.html` applies the same cache synchronously pre-paint and is the authoritative boot path (never applies cached prefs on `/login` or `/share/:token`). - **servers.ts** — `countByState(items)` (running/stopped/pending/failed counts), `phaseGroups(items)` (items grouped by phase) - **games.ts** — category helpers: `gameCategory(game)`, `resolveCategories(explicit, game)`, `matchesCategory`, `matchesAllCategories`, `categoryFilters(categories)` diff --git a/web/src/lib/serverTemplate.test.ts b/web/src/lib/serverTemplate.test.ts new file mode 100644 index 000000000..0dad6897a --- /dev/null +++ b/web/src/lib/serverTemplate.test.ts @@ -0,0 +1,40 @@ +import { describe, it, expect } from "vitest"; +import { http, HttpResponse } from "msw"; +import { server } from "@/test/server"; +import { makeTemplate } from "@/test/factories"; +import { createResourceClient } from "./endpoints"; +import { getServerTemplate } from "./serverTemplate"; + +const client = () => createResourceClient({ cluster: "local", namespace: "gameplane-games" }); + +describe("getServerTemplate", () => { + it("reads the catalog template when the caller may", async () => { + let scoped = 0; + server.use( + http.get("/templates/:name", ({ params }) => HttpResponse.json(makeTemplate({ metadata: { name: String(params.name) } }))), + http.get("/servers/alpha/template", () => { scoped += 1; return HttpResponse.json(makeTemplate()); }), + ); + const tmpl = await getServerTemplate(client(), "alpha", "gameplane-games", "valheim"); + expect(tmpl.metadata.name).toBe("valheim"); + expect(scoped).toBe(0); + }); + + it("falls back to the server-scoped template when the catalog refuses", async () => { + let namespace: string | null = null; + server.use( + http.get("/templates/:name", () => HttpResponse.json({ detail: "forbidden" }, { status: 403 })), + http.get("/servers/alpha/template", ({ request }) => { + namespace = new URL(request.url).searchParams.get("namespace"); + return HttpResponse.json(makeTemplate({ metadata: { name: "scoped" } })); + }), + ); + const tmpl = await getServerTemplate(client(), "alpha", "gameplane-games", "valheim"); + expect(tmpl.metadata.name).toBe("scoped"); + expect(namespace).toBe("gameplane-games"); + }); + + it("passes other errors through", async () => { + server.use(http.get("/templates/:name", () => HttpResponse.json({ detail: "boom" }, { status: 500 }))); + await expect(getServerTemplate(client(), "alpha", "gameplane-games", "valheim")).rejects.toMatchObject({ status: 500 }); + }); +}); diff --git a/web/src/lib/serverTemplate.ts b/web/src/lib/serverTemplate.ts new file mode 100644 index 000000000..edac6cad7 --- /dev/null +++ b/web/src/lib/serverTemplate.ts @@ -0,0 +1,26 @@ +import { APIError } from "@/lib/api"; +import type { ResourceClient } from "@/lib/endpoints"; +import type { GameTemplate } from "@/types"; + +// getServerTemplate reads the template a server was created from. The +// catalog read (GET /templates/{name}) needs templates:read on the cluster, +// which a server's owners and collaborators may not hold. They still manage +// the server's mods, modpacks and console, and those tabs need the template +// to render (#1063), so a refused catalog read falls back to the +// server-scoped GET /servers/{name}/template, which the API allows for the +// server's owners and collaborators. +export async function getServerTemplate( + client: ResourceClient, + name: string, + ns: string | undefined, + templateName: string, +): Promise { + try { + return await client.Templates.get(templateName); + } catch (err) { + if (err instanceof APIError && err.status === 403) { + return client.Servers.effectiveTemplate(name, ns); + } + throw err; + } +} diff --git a/web/src/routes/ServerDetail.test.tsx b/web/src/routes/ServerDetail.test.tsx index c18885085..68627d273 100644 --- a/web/src/routes/ServerDetail.test.tsx +++ b/web/src/routes/ServerDetail.test.tsx @@ -415,6 +415,29 @@ describe("ServerDetailPage dynamic tabs", () => { await waitFor(() => expect(screen.getByText("mods-tab")).toBeInTheDocument()); }); + it("shows the Mods tab to a collaborator who cannot read the template catalog", async () => { + // A collaborator without templates:read gets 403 from the catalog; the + // server-scoped template read still gives the tabs their template (#1063). + server.use( + http.get("/servers/alpha", () => HttpResponse.json(makeServer())), + http.get("/servers/alpha/access", () => HttpResponse.json({ + target: { cluster: "local", namespace: "gameplane-games", name: "alpha" }, + canWrite: false, canControl: true, canConsole: true, canDelete: false, isOwner: false, isCollaborator: true, + permissions: [], + })), + http.get("/templates/:name", () => HttpResponse.json({ detail: "forbidden" }, { status: 403 })), + http.get("/servers/alpha/template", () => + HttpResponse.json( + makeTemplate({ spec: { capabilities: { mods: { path: "mods" } } } }), + ), + ), + ); + renderWithQuery(); + const modsTab = await screen.findByRole("tab", { name: "Mods" }); + await userEvent.click(modsTab); + await waitFor(() => expect(screen.getByText("mods-tab")).toBeInTheDocument()); + }); + it("keeps the Logs tab available even when the template logs only to stdout", async () => { server.use( http.get("/servers/alpha", () => HttpResponse.json(makeServer())), diff --git a/web/src/routes/ServerDetail.tsx b/web/src/routes/ServerDetail.tsx index 6a972cfd3..76d7bc0ce 100644 --- a/web/src/routes/ServerDetail.tsx +++ b/web/src/routes/ServerDetail.tsx @@ -14,6 +14,7 @@ import { import { createResourceClient, type LifecycleVerb } from "@/lib/endpoints"; import { useGameCodes } from "@/lib/useGameCodes"; import { resolveConsoleMode, serverHasMods, serverHasModpacks } from "@/lib/capabilities"; +import { getServerTemplate } from "@/lib/serverTemplate"; import { useMe } from "@/lib/auth"; import { PhaseChip } from "@/components/ui/PhaseChip"; import { GameIcon } from "@/components/ui/GameIcon"; @@ -154,7 +155,7 @@ function ServerDetailView({ lookupTarget, file }: { lookupTarget: ResourceTarget const templateName = gs?.spec.templateRef.name; const { data: tmpl } = useQuery({ queryKey: resourceKey(target, "template", templateName), - queryFn: ({ signal }) => client.withSignal(signal).Templates.get(templateName as string), + queryFn: ({ signal }) => getServerTemplate(client.withSignal(signal), name, ns, templateName as string), enabled: !!templateName, }); diff --git a/web/src/routes/tabs/Console.tsx b/web/src/routes/tabs/Console.tsx index 06787f80b..0d0c493eb 100644 --- a/web/src/routes/tabs/Console.tsx +++ b/web/src/routes/tabs/Console.tsx @@ -6,6 +6,7 @@ import { ErrorCard } from "@/components/ui/ErrorCard"; import { useResourceTarget, useResourceClient, resourceKey } from "@/lib/resourceTarget"; import { createRequestClient } from "@/lib/api"; import { resolveConsoleMode } from "@/lib/capabilities"; +import { getServerTemplate } from "@/lib/serverTemplate"; import { ConsoleShell } from "./ConsoleShell"; import { LogHistory } from "./LogHistory"; @@ -23,7 +24,7 @@ export function ConsoleTab({ name, ns }: { name: string; ns?: string }) { const templateName = gs?.spec.templateRef.name; const { data: tmpl } = useQuery({ queryKey: resourceKey(target, "template", templateName), - queryFn: ({ signal }) => client.withSignal(signal).Templates.get(templateName!), + queryFn: ({ signal }) => getServerTemplate(client.withSignal(signal), name, ns, templateName!), enabled: !!templateName, }); const mode = resolveConsoleMode(tmpl); diff --git a/web/src/routes/tabs/Settings.tsx b/web/src/routes/tabs/Settings.tsx index ea32b6969..0301521d6 100644 --- a/web/src/routes/tabs/Settings.tsx +++ b/web/src/routes/tabs/Settings.tsx @@ -1,4 +1,5 @@ import { useResourceClient, useResourceAccess, useResourcePermissions, useResourceTarget, resourceCan, resourceKey } from "@/lib/resourceTarget"; +import { getServerTemplate } from "@/lib/serverTemplate"; import { useEffect, useMemo, useRef, useState, Suspense, lazy } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { Button, Tabs } from "@heroui/react"; @@ -177,7 +178,7 @@ export function SettingsTab({ gs, name, ns, initialSection = "general", onDirtyC queryKey: resourceKey(resourceTarget, "template", draft?.spec.templateRef.name, revision), queryFn: ({ signal }) => revision ? resourceClient.withSignal(signal).Servers.effectiveTemplate(name, ns) - : resourceClient.withSignal(signal).Templates.get(draft!.spec.templateRef.name), + : getServerTemplate(resourceClient.withSignal(signal), name, ns, draft!.spec.templateRef.name), enabled: !!draft?.spec.templateRef.name, }); const moduleText = useModuleText(draft?.spec.templateRef.name, resourceTarget.cluster);