Skip to content
Open
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
97 changes: 81 additions & 16 deletions api/internal/handlers/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"

"github.com/GameplanePanel/gameplane/api/internal/audit"
"github.com/GameplanePanel/gameplane/api/internal/auth"
"github.com/GameplanePanel/gameplane/api/internal/httperr"
"github.com/GameplanePanel/gameplane/api/internal/kube"
"github.com/GameplanePanel/gameplane/api/internal/messages"
Expand Down Expand Up @@ -154,11 +155,17 @@ func (h *registryHandler) search(w http.ResponseWriter, req *http.Request) {
// slips past) — clamp here once rather than in every engine.
offset = 0
}
typ := req.URL.Query().Get("type")
if typ == "modpack" && allLoadersRequested(req) {
// FR-014: "All loaders" lists packs for every loader and Minecraft
// version, so the server's facets do not narrow the search.
loader, gameVersion = "", ""
}
res, err := p.Search(req.Context(), registry.SearchQuery{
Term: req.URL.Query().Get("q"),
Loader: loader,
GameVersion: gameVersion,
ProjectType: req.URL.Query().Get("type"),
ProjectType: typ,
Category: req.URL.Query().Get("category"),
Sort: req.URL.Query().Get("sort"),
Limit: limit,
Expand Down Expand Up @@ -186,15 +193,35 @@ func (h *registryHandler) versions(w http.ResponseWriter, req *http.Request) {
httperr.WriteCode(w, req, http.StatusBadRequest, errors.New("invalid project id"))
return
}
res, err := p.Versions(req.Context(), project, registry.Filter{
Loader: loader,
GameVersion: gameVersion,
ProjectType: req.URL.Query().Get("type"),
})
typ := req.URL.Query().Get("type")
allLoaders := typ == "modpack" && allLoadersRequested(req)
filter := registry.Filter{Loader: loader, GameVersion: gameVersion, ProjectType: typ}
if allLoaders {
filter.Loader, filter.GameVersion = "", ""
}
res, err := p.Versions(req.Context(), project, filter)
if err != nil {
httperr.WriteCode(w, req, http.StatusBadGateway, fmt.Errorf("mod registry versions failed: %w", err))
return
}
if allLoaders {
// FR-014: keep only the pack versions this server's template can run,
// each naming the template version it runs on. An entry the key check
// blocks is never offered; its verdict is computed once per entry.
selected, _, _ := unstructured.NestedString(target.server.Object, "spec", "version")
prov, _ := pickProvider(target.template, req.URL.Query().Get("provider"))
ctx := req.Context()
unblocked := map[string]bool{}
for _, e := range templateVersionEntries(target.template) {
if id := entryID(e); id != "" {
if _, seen := unblocked[id]; !seen {
unblocked[id] = h.blockedReasonFor(ctx, target, prov, e) == ""
}
}
}
allowed := func(entry map[string]any) bool { return unblocked[entryID(entry)] }
res = matchServerVersionsAllowed(target.template, selected, res, allowed)
}
writeJSON(w, res)
}

Expand Down Expand Up @@ -269,7 +296,35 @@ func (h *registryHandler) installModpack(w http.ResponseWriter, req *http.Reques
httperr.WriteMessage(w, req, messages.New("server.modpack.backup_unavailable", nil))
return
}
if h.modpacksBlockedReason(req.Context(), target, prov) != "" {
// The server runs the entry it has now, unless serverVersion switches it
// (FR-014, OD-13 B); the key check and the audit row follow that entry.
currentID := currentServerVersionID(target)
runEntry := activeVersionEntry(target.template, currentID)
var serverSwitch string
if body.ServerVersion != "" && body.ServerVersion != currentID {
// Changing a server's version needs servers:write in its namespace,
// as in Settings; an owner or collaborator grant is not enough.
if !auth.UserFromContext(req.Context()).Can("servers:write", true, target.cluster, target.namespace) {
httperr.WriteMessage(w, req, messages.New("server.modpack.server_version_forbidden", nil))
return
}
entry, err := h.serverVersionTarget(req.Context(), target, prov, body)
if errors.Is(err, errServerVersionMismatch) {
httperr.WriteMessage(w, req, messages.New("server.modpack.server_version_mismatch", nil))
return
}
if errors.Is(err, errNoRegistry) {
h.writeResolveErr(w, req, err)
return
}
if err != nil {
httperr.WriteCode(w, req, http.StatusBadGateway, err)
return
}
runEntry = entry
serverSwitch = currentID + "->" + body.ServerVersion
}
if h.blockedReasonFor(req.Context(), target, prov, runEntry) != "" {
httperr.WriteMessage(w, req, messages.New("server.modpack.key_required", nil))
return
}
Expand All @@ -294,6 +349,10 @@ func (h *registryHandler) installModpack(w http.ResponseWriter, req *http.Reques
updated, err := updateModTarget(req.Context(), target, func(current *unstructured.Unstructured) {
// SetNestedMap only fails on a non-map parent; spec is always a map here.
_ = unstructured.SetNestedMap(current.Object, spec, "spec", "modpack")
if serverSwitch != "" {
// The server switches to the matching version in the same write as the pack.
_ = unstructured.SetNestedField(current.Object, body.ServerVersion, "spec", "version")
}
// A removal whose backup failed leaves its request behind, and an
// adopted legacy pin would hold back the new pack; installing a pack
// supersedes both.
Expand All @@ -307,25 +366,31 @@ func (h *registryHandler) installModpack(w http.ResponseWriter, req *http.Reques
httperr.Write(w, req, err)
return
}
h.auditModpack(req, target.server.GetName(), action, prov.provider, body.Project, body.Version)
h.auditModpack(req, target.server.GetName(), action, prov.provider, body.Project, body.Version, serverSwitch)
writeJSONStatus(w, http.StatusAccepted, h.modpackViewFor(req, target, updated, false))
}

// resolve picks the requested provider from the selected server's template,
// returning its central engine and the selected server's version filters.
func (h *registryHandler) resolve(ctx context.Context, target *modTarget, providerName string) (registry.Provider, string, string, error) {
prov, ok := pickProvider(target.template, providerName)
if !ok {
return nil, "", "", errNoRegistry
}
p, ok := h.reg.For(ctx, registry.Config{
// providerFor returns the central engine for a template's declared provider,
// or false when the engine is not configured.
func (h *registryHandler) providerFor(ctx context.Context, prov providerCfg) (registry.Provider, bool) {
return h.reg.For(ctx, registry.Config{
Provider: prov.provider,
Community: prov.community,
SteamAppID: prov.steamAppID,
CurseForgeGameID: prov.curseforgeGameID,
GitHubOwner: prov.githubOwner,
GitHubRepo: prov.githubRepo,
})
}

// resolve picks the requested provider from the selected server's template,
// returning its central engine and the selected server's version filters.
func (h *registryHandler) resolve(ctx context.Context, target *modTarget, providerName string) (registry.Provider, string, string, error) {
prov, ok := pickProvider(target.template, providerName)
if !ok {
return nil, "", "", errNoRegistry
}
p, ok := h.providerFor(ctx, prov)
if !ok {
return nil, "", "", errNoRegistry
}
Expand Down
22 changes: 18 additions & 4 deletions api/internal/handlers/registry_modpack.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ type modpackInstallBody struct {
VersionName string `json:"versionName"`
BackupFirst bool `json:"backupFirst"`
Ref string `json:"ref"`
// ServerVersion is an optional template version id (spec 035 FR-014). When
// it differs from the server's current version, the install switches the
// server to it in the same write as the pack.
ServerVersion string `json:"serverVersion"`
}

// modpackRemoveRequest is the JSON stored in the modpack-remove annotation.
Expand Down Expand Up @@ -262,11 +266,16 @@ func (h *registryHandler) backupDestinationName(req *http.Request, target *modTa
// carries one of those tags, and the administrator has not enabled key
// sharing. The Secret is read only when the first two hold.
func (h *registryHandler) modpacksBlockedReason(ctx context.Context, target *modTarget, p providerCfg) string {
selected, _, _ := unstructured.NestedString(target.server.Object, "spec", "version")
return h.blockedReasonFor(ctx, target, p, activeVersionEntry(target.template, selected))
}

// blockedReasonFor is modpacksBlockedReason for the server version entry the
// pack would run on (the image decides whether the CurseForge key is needed).
func (h *registryHandler) blockedReasonFor(ctx context.Context, target *modTarget, p providerCfg, entry map[string]any) string {
if p.modpacks == nil || len(p.modpacks.needsKeyImageTags) == 0 {
return ""
}
selected, _, _ := unstructured.NestedString(target.server.Object, "spec", "version")
entry := activeVersionEntry(target.template, selected)
if entry == nil {
return ""
}
Expand Down Expand Up @@ -370,7 +379,7 @@ func (h *registryHandler) removeModpack(w http.ResponseWriter, req *http.Request
httperr.Write(w, req, err)
return
}
h.auditModpack(req, gs.GetName(), "remove", removed.Provider, removed.Project, removed.Version)
h.auditModpack(req, gs.GetName(), "remove", removed.Provider, removed.Project, removed.Version, "")
writeJSONStatus(w, http.StatusAccepted, h.modpackViewFor(req, target, updated, false))
}

Expand All @@ -387,11 +396,16 @@ func newModpackRequestID() (string, error) {
// install, change or remove). Provider, project and version are validated
// slugs; the CurseForge key never reaches this code. A failed audit write is
// logged and the generic audit middleware row stays as the fallback.
func (h *registryHandler) auditModpack(req *http.Request, serverName, action, provider, project, version string) {
// serverSwitch is "<old>-><new>" when the install also switched the server
// version (FR-014), else "".
func (h *registryHandler) auditModpack(req *http.Request, serverName, action, provider, project, version, serverSwitch string) {
if h.audit == nil {
return
}
reason := fmt.Sprintf("server.modpack.%s provider=%s project=%s version=%s", action, provider, project, version)
if serverSwitch != "" {
reason += " server_version=" + serverSwitch
}
if err := h.audit.WriteSync(req.Context(), req.Method, req.URL.Path, serverName, reason, http.StatusAccepted); err != nil {
slog.Warn("modpack audit write failed", "server", serverName, "action", action, "err", err)
return
Expand Down
162 changes: 162 additions & 0 deletions api/internal/handlers/registry_server_version.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
package handlers

import (
"context"
"errors"
"fmt"
"net/http"
"slices"
"strings"

"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"

"github.com/GameplanePanel/gameplane/api/internal/registry"
)

// Spec 035 FR-014 ("All loaders"): a modpack browse can list every pack
// version and name the template version each one runs on, and an install can
// switch the server to that template version in the same write as the pack.

// errServerVersionMismatch means the POST serverVersion cannot run the chosen
// pack version (unknown or moving entry, or the pack has no such version for
// that entry). Mapped to server.modpack.server_version_mismatch (400).
var errServerVersionMismatch = errors.New("the chosen pack version does not run on that server version")

// allLoadersRequested reports whether the request asked for the "All loaders"
// modpack browse (?allLoaders=true). It only has an effect with type=modpack.
func allLoadersRequested(req *http.Request) bool {
return req.URL.Query().Get("allLoaders") == "true"
}

// currentServerVersionID is the server's selected template version id; when the
// server selects none, the default entry the operator would run.
func currentServerVersionID(target *modTarget) string {
if selected, _, _ := unstructured.NestedString(target.server.Object, "spec", "version"); selected != "" {
return selected
}
return entryID(activeVersionEntry(target.template, ""))
}

// serverVersionTarget validates a POST serverVersion that switches the server
// away from its current version. It returns the template entry the server
// switches to when the pack version body.Version exists for that entry's
// loader and Minecraft version. errServerVersionMismatch means the request
// cannot be honoured; any other error is a provider failure.
func (h *registryHandler) serverVersionTarget(ctx context.Context, target *modTarget, prov providerCfg, body modpackInstallBody) (map[string]any, error) {
entry := templateEntryByID(target.template, body.ServerVersion)
loader, gameVersion := loaderGameVersion(entry)
if entry == nil || gameVersion == "" || body.Version == "" {
return nil, errServerVersionMismatch
}
p, ok := h.providerFor(ctx, prov)
if !ok {
return nil, errNoRegistry
}
versions, err := p.Versions(ctx, body.Project, registry.Filter{
Loader: loader,
GameVersion: gameVersion,
ProjectType: "modpack",
})
if err != nil {
return nil, fmt.Errorf("mod registry versions failed: %w", err)
}
// The provider filter can let through files with no loader tag, or entries
// tagged with a loader the entry does not run, so the match must also check
// that the entry fits the version.
if !slices.ContainsFunc(versions, func(v registry.Version) bool {
return v.ID == body.Version && entryFits(entry, v)
}) {
return nil, errServerVersionMismatch
}
return entry, nil
}

// matchServerVersions keeps the pack versions that some template version entry
// can run, and names that entry on each kept version. An entry fits a version
// when its loader is one of the version's loaders (case-insensitive) and its
// gameVersion is one of the version's game versions; moving entries without a
// gameVersion never fit. The server's current entry wins when it fits, else the
// first fitting entry in template order. Versions with no fitting entry are
// dropped.
func matchServerVersions(tmpl *unstructured.Unstructured, selected string, versions []registry.Version) []registry.Version {
return matchServerVersionsAllowed(tmpl, selected, versions, nil)
}

// matchServerVersionsAllowed is matchServerVersions limited to the entries
// allowed accepts (nil allows all). A disallowed entry is never named, and the
// server's current entry is preferred only when it is allowed.
func matchServerVersionsAllowed(tmpl *unstructured.Unstructured, selected string, versions []registry.Version, allowed func(map[string]any) bool) []registry.Version {
permitted := func(e map[string]any) bool { return allowed == nil || allowed(e) }
entries := templateVersionEntries(tmpl)
current := activeVersionEntry(tmpl, selected)
if current != nil && !permitted(current) {
current = nil
}
out := make([]registry.Version, 0, len(versions))
for _, v := range versions {
entry := current
if entry == nil || !entryFits(entry, v) {
entry = nil
for _, e := range entries {
if permitted(e) && entryFits(e, v) {
entry = e
break
}
}
}
if entry == nil {
continue
}
v.ServerVersion, _ = entry["id"].(string)
v.ServerVersionName, _ = entry["displayName"].(string)
out = append(out, v)
}
return out
}

// entryFits reports whether a template version entry can run a pack version.
func entryFits(entry map[string]any, v registry.Version) bool {
loader, gameVersion := loaderGameVersion(entry)
if loader == "" || gameVersion == "" {
return false
}
loaderOK := slices.ContainsFunc(v.Loaders, func(l string) bool { return strings.EqualFold(l, loader) })
return loaderOK && slices.Contains(v.GameVersions, gameVersion)
}

// templateVersionEntries returns the template's spec.versions maps in order.
func templateVersionEntries(tmpl *unstructured.Unstructured) []map[string]any {
if tmpl == nil {
return nil
}
raw, found, err := unstructured.NestedSlice(tmpl.Object, "spec", "versions")
if !found || err != nil {
return nil
}
out := make([]map[string]any, 0, len(raw))
for _, r := range raw {
if m, ok := r.(map[string]any); ok {
out = append(out, m)
}
}
return out
}

// templateEntryByID returns the template version entry with the given id, or nil.
func templateEntryByID(tmpl *unstructured.Unstructured, id string) map[string]any {
if id == "" {
return nil
}
for _, e := range templateVersionEntries(tmpl) {
if entryID(e) == id {
return e
}
}
return nil
}

// entryID returns a template version entry's id, "" for nil.
func entryID(entry map[string]any) string {
id, _ := entry["id"].(string)
return id
}
Loading
Loading