diff --git a/api/internal/handlers/theme_sources.go b/api/internal/handlers/theme_sources.go index 6262f73b7..e28eacbe9 100644 --- a/api/internal/handlers/theme_sources.go +++ b/api/internal/handlers/theme_sources.go @@ -19,40 +19,43 @@ import ( // themeSourceHandler serves the admin theme source routes (spec 043, // contracts/themes-api.md, "Theme sources"). The RBAC table admits them only with -// themes:manage. Credentials are never returned: the list and write responses -// carry no credential field, and the stored reference is not part of the item. +// themes:manage. A source names an admin-made credential Secret by name +// (credentialSecret, like a ModuleSource secretRef); responses show that name +// and never the Secret's values. type themeSourceHandler struct { store *db.Store svc *themes.Service } // themeSourceBody is the POST and PUT request. Unknown fields are refused. On PUT -// the name comes from the path and the body name is ignored. Credential is kept -// as raw JSON so an absent field (keep, or none on create) and a JSON null (clear, -// on PUT) can be told apart. +// the name comes from the path and the body name is ignored. CredentialSecret is +// kept as raw JSON so an absent field (keep, or none on create) and a JSON null +// (clear, on PUT) can be told apart. type themeSourceBody struct { - Name string `json:"name"` - Type string `json:"type"` - Spec json.RawMessage `json:"spec"` - Credential json.RawMessage `json:"credential"` - Verify json.RawMessage `json:"verify"` - RefreshInterval *int `json:"refreshInterval"` - Enabled *bool `json:"enabled"` + Name string `json:"name"` + Type string `json:"type"` + Spec json.RawMessage `json:"spec"` + CredentialSecret json.RawMessage `json:"credentialSecret"` + Verify json.RawMessage `json:"verify"` + RefreshInterval *int `json:"refreshInterval"` + Enabled *bool `json:"enabled"` } // themeSourceItem is one source as the admin API shows it. Builtin marks the // reserved official source, which can be disabled but not deleted. type themeSourceItem struct { - Name string `json:"name"` - Type string `json:"type"` - Spec json.RawMessage `json:"spec"` - Verify json.RawMessage `json:"verify"` - RefreshInterval int `json:"refreshInterval"` - Enabled bool `json:"enabled"` - Builtin bool `json:"builtin"` - LastSyncAt *string `json:"lastSyncAt"` - LastError *string `json:"lastError"` - ThemeCount int `json:"themeCount"` + Name string `json:"name"` + Type string `json:"type"` + Spec json.RawMessage `json:"spec"` + Verify json.RawMessage `json:"verify"` + // CredentialSecret is the name of the credential Secret, or null for none. + CredentialSecret *string `json:"credentialSecret"` + RefreshInterval int `json:"refreshInterval"` + Enabled bool `json:"enabled"` + Builtin bool `json:"builtin"` + LastSyncAt *string `json:"lastSyncAt"` + LastError *string `json:"lastError"` + ThemeCount int `json:"themeCount"` } // settings converts the request body to the service input. @@ -60,7 +63,7 @@ func (b themeSourceBody) settings() themes.SourceSettings { return themes.SourceSettings{ Type: b.Type, Spec: b.Spec, - Credential: b.Credential, + CredentialSecret: b.CredentialSecret, Verify: b.Verify, RefreshIntervalS: b.RefreshInterval, Enabled: b.Enabled, @@ -68,18 +71,19 @@ func (b themeSourceBody) settings() themes.SourceSettings { } // sourceItemOf renders a stored source. The spec and policy are the canonical -// JSON the service wrote; no credential reference is included. +// JSON the service wrote; the credential Secret is shown by name only. func sourceItemOf(src db.ThemeSource) themeSourceItem { item := themeSourceItem{ - Name: src.Name, - Type: src.Type, - Spec: json.RawMessage(src.Spec), - RefreshInterval: src.RefreshIntervalS, - Enabled: src.Enabled, - Builtin: src.Name == themes.OfficialSourceName, - LastSyncAt: src.LastSyncAt, - LastError: src.LastError, - ThemeCount: src.ThemeCount, + Name: src.Name, + Type: src.Type, + Spec: json.RawMessage(src.Spec), + CredentialSecret: src.CredentialRef, + RefreshInterval: src.RefreshIntervalS, + Enabled: src.Enabled, + Builtin: src.Name == themes.OfficialSourceName, + LastSyncAt: src.LastSyncAt, + LastError: src.LastError, + ThemeCount: src.ThemeCount, } if src.Verify != nil { item.Verify = json.RawMessage(*src.Verify) diff --git a/api/internal/handlers/theme_sources_credential_envtest_test.go b/api/internal/handlers/theme_sources_credential_envtest_test.go index df27bb113..948c55544 100644 --- a/api/internal/handlers/theme_sources_credential_envtest_test.go +++ b/api/internal/handlers/theme_sources_credential_envtest_test.go @@ -5,10 +5,10 @@ import ( "fmt" "net/http" "strings" + "sync" "testing" corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes/fake" @@ -20,11 +20,11 @@ import ( ) // This file covers the credential path of the admin theme source routes (spec -// 043, OD-5): a credential is stored as a labelled Secret named after the source, -// the source row keeps only the Secret name, no response or error carries the -// value, and the Secret follows the source's lifecycle (kept on PUT without a -// credential, replaced, cleared with null, removed when the location moves or -// the source is deleted). +// 043, OD-5, settled "Secret name, like modules"): the admin creates a Secret in +// the credentials namespace and names it on the source (credentialSecret), the +// source row keeps only that name, the indexer reads the Secret for each pull, +// no response or error carries the Secret's values, and the panel never creates, +// changes or deletes the Secret. // themeCredNS is the credentials namespace the fake Kubernetes client uses. const themeCredNS = "gameplane-test" @@ -36,22 +36,43 @@ const themeCredSecretValue = "hunter2-secret" // themeCredDockerConfig is a docker config JSON credential for the test registry. const themeCredDockerConfig = `{"auths":{"registry.test":{"username":"robot","password":"` + themeCredSecretValue + `"}}}` +// themeCredEnv is a theme catalog env with a Kubernetes fake for the credential +// Secrets. It records the last registry credential function the indexer built. +type themeCredEnv struct { + *themeCatEnv + cs *fake.Clientset + + mu sync.Mutex + creds oci.CredentialFunc +} + // newThemeCredEnv is newThemeCatEnv with a Kubernetes fake that holds the -// credential Secrets. It returns the fake so tests can read the Secrets. -func newThemeCredEnv(t *testing.T) (*themeCatEnv, *fake.Clientset) { +// credential Secrets. +func newThemeCredEnv(t *testing.T) *themeCredEnv { t.Helper() - env := newThemeCatEnv(t) - cs := fake.NewClientset() + env := &themeCredEnv{themeCatEnv: newThemeCatEnv(t), cs: fake.NewClientset()} env.svc = themes.New(themes.Deps{ Store: env.store, - Kube: &kube.Client{Typed: cs}, + Kube: &kube.Client{Typed: env.cs}, CredentialsNS: themeCredNS, - OCI: func(oci.CredentialFunc, bool) source.OCIClient { return env.oci }, + OCI: func(creds oci.CredentialFunc, _ bool) source.OCIClient { + env.mu.Lock() + env.creds = creds + env.mu.Unlock() + return env.oci + }, Verifier: func(context.Context, string, bool) (verify.Verifier, error) { return themeCatVerifier{}, nil }, }) - return env, cs + return env +} + +// lastCreds returns the registry credential function of the last index. +func (e *themeCredEnv) lastCreds() oci.CredentialFunc { + e.mu.Lock() + defer e.mu.Unlock() + return e.creds } // themeCredName returns a source name unique to the test. @@ -59,37 +80,58 @@ func themeCredName() string { return fmt.Sprintf("cred%d", themeCatSeq.Add(1)) } -// themeCredSecretName is the Secret name the service derives from a source name. -func themeCredSecretName(src string) string { - return "gameplane-theme-source-" + src +// themeCredMakeSecret creates the admin's credential Secret name with data, as +// an admin would before naming it on a source. +func themeCredMakeSecret(t *testing.T, cs *fake.Clientset, name string, data map[string][]byte) { + t.Helper() + sec := &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: themeCredNS}, + Type: corev1.SecretTypeDockerConfigJson, + Data: data, + } + if _, err := cs.CoreV1().Secrets(themeCredNS).Create(context.Background(), sec, metav1.CreateOptions{}); err != nil { + t.Fatalf("create secret %s: %v", name, err) + } +} + +// themeCredDockerData is the Secret data of a docker config credential. +func themeCredDockerData() map[string][]byte { + return map[string][]byte{corev1.DockerConfigJsonKey: []byte(themeCredDockerConfig)} } -// themeCredSecret returns the credential Secret of a source, and false when there -// is none. -func themeCredSecret(t *testing.T, cs *fake.Clientset, src string) (*corev1.Secret, bool) { +// themeCredAssertNoPanelWrites fails when the service created, changed or +// deleted any Secret. The fake records every call; the tests' own creates are +// made before the service runs and are counted in allowedCreates. +func themeCredAssertNoPanelWrites(t *testing.T, cs *fake.Clientset, allowedCreates int) { t.Helper() - sec, err := cs.CoreV1().Secrets(themeCredNS).Get(context.Background(), themeCredSecretName(src), metav1.GetOptions{}) - if apierrors.IsNotFound(err) { - return nil, false + creates := 0 + for _, a := range cs.Actions() { + if a.GetResource().Resource != "secrets" { + continue + } + switch a.GetVerb() { + case "create": + creates++ + case "update", "patch", "delete": + t.Fatalf("the panel wrote a credential Secret: %s %v", a.GetVerb(), a) + } } - if err != nil { - t.Fatalf("get credential secret of %s: %v", src, err) + if creates != allowedCreates { + t.Fatalf("secret creates = %d, want only the test's own %d", creates, allowedCreates) } - return sec, true } -// themeCredAssertHidden fails when a response body carries the credential field -// name or the stored secret value. +// themeCredAssertHidden fails when a response body carries the stored secret +// value. func themeCredAssertHidden(t *testing.T, body string) { t.Helper() - themeSrcAssertNoCredential(t, body) if strings.Contains(body, themeCredSecretValue) { t.Fatalf("response carries the credential value: %s", body) } } // themeCredStoredRef returns the credential_ref of a source row. -func themeCredStoredRef(t *testing.T, env *themeCatEnv, name string) *string { +func themeCredStoredRef(t *testing.T, env *themeCredEnv, name string) *string { t.Helper() src, err := env.store.GetThemeSource(context.Background(), name) if err != nil { @@ -98,154 +140,235 @@ func themeCredStoredRef(t *testing.T, env *themeCatEnv, name string) *string { return src.CredentialRef } -func TestThemeSourceCredentialStoredAsLabelledSecret(t *testing.T) { - env, cs := newThemeCredEnv(t) - defer env.svc.WaitIdle() +func TestThemeSourceCredentialSecretNamedAndRead(t *testing.T) { + env := newThemeCredEnv(t) h := env.router("admin") name := themeCredName() - body := themeSrcBody(name, "oci", themeSrcSpec(name), `,"credential":`+themeCredDockerConfig) + secret := name + "-pull" + themeCredMakeSecret(t, env.cs, secret, themeCredDockerData()) + themeSrcPublish(t, env.themeCatEnv, name) + body := themeSrcBody(name, "oci", themeSrcSpec(name), `,"credentialSecret":"`+secret+`"`) rr := themeInstDo(t, h, http.MethodPost, "/themes/sources", body) if rr.Code != http.StatusCreated { - t.Fatalf("create with credential: status %d body %s", rr.Code, rr.Body.String()) + t.Fatalf("create with a credential Secret: status %d body %s", rr.Code, rr.Body.String()) } themeCredAssertHidden(t, rr.Body.String()) + env.svc.WaitIdle() - sec, ok := themeCredSecret(t, cs, name) - if !ok { - t.Fatalf("no credential secret for %s", name) + if ref := themeCredStoredRef(t, env, name); ref == nil || *ref != secret { + t.Fatalf("credential_ref = %v, want %s", ref, secret) } - if sec.Labels[themes.ThemeSourceSecretLabel] != "true" { - t.Fatalf("secret labels %v, want %s=true", sec.Labels, themes.ThemeSourceSecretLabel) + listed := themeSrcFind(t, themeSrcItems(t, h), name) + if listed.CredentialSecret == nil || *listed.CredentialSecret != secret { + t.Fatalf("listed credentialSecret = %v, want %s", listed.CredentialSecret, secret) } - if !strings.Contains(string(sec.Data[corev1.DockerConfigJsonKey]), themeCredSecretValue) { - t.Fatalf("secret does not hold the docker config credential") + if listed.LastError != nil { + t.Fatalf("index with a valid credential Secret failed: %s", *listed.LastError) } - ref := themeCredStoredRef(t, env, name) - if ref == nil || *ref != themeCredSecretName(name) { - t.Fatalf("credential_ref = %v, want %s", ref, themeCredSecretName(name)) + creds := env.lastCreds() + if creds == nil { + t.Fatalf("the indexer built no registry credential from the Secret") } - - items := themeSrcItems(t, h) - if listed := themeSrcFind(t, items, name); listed.Type != "oci" { - t.Fatalf("listed source: %+v", listed) + cred, err := creds(context.Background(), "registry.test") + if err != nil || cred.Username != "robot" || cred.Password != themeCredSecretValue { + t.Fatalf("registry credential = %+v, %v; want the Secret's robot login", cred, err) } if rr := themeInstDo(t, h, http.MethodGet, "/themes/sources", ""); strings.Contains(rr.Body.String(), themeCredSecretValue) { t.Fatalf("list carries the credential value") } + themeCredAssertNoPanelWrites(t, env.cs, 1) } -func TestThemeSourceCredentialUpdateKeepReplaceClear(t *testing.T) { - env, cs := newThemeCredEnv(t) +func TestThemeSourceCredentialSecretKeepReplaceClear(t *testing.T) { + env := newThemeCredEnv(t) defer env.svc.WaitIdle() h := env.router("admin") name := themeCredName() - create := themeSrcBody(name, "oci", themeSrcSpec(name), `,"credential":`+themeCredDockerConfig) + first, second := name+"-a", name+"-b" + themeCredMakeSecret(t, env.cs, first, themeCredDockerData()) + themeCredMakeSecret(t, env.cs, second, themeCredDockerData()) + create := themeSrcBody(name, "oci", themeSrcSpec(name), `,"credentialSecret":"`+first+`"`) if rr := themeInstDo(t, h, http.MethodPost, "/themes/sources", create); rr.Code != http.StatusCreated { t.Fatalf("create: status %d body %s", rr.Code, rr.Body.String()) } - put := func(extra string) { + put := func(spec, extra string) { t.Helper() - rr := themeInstDo(t, h, http.MethodPut, "/themes/sources/"+name, themeSrcBody(name, "oci", themeSrcSpec(name), extra)) + rr := themeInstDo(t, h, http.MethodPut, "/themes/sources/"+name, themeSrcBody(name, "oci", spec, extra)) if rr.Code != http.StatusOK { t.Fatalf("put %q: status %d body %s", extra, rr.Code, rr.Body.String()) } themeCredAssertHidden(t, rr.Body.String()) } - - // Omitted credential keeps the stored one. - put("") - if _, ok := themeCredSecret(t, cs, name); !ok || themeCredStoredRef(t, env, name) == nil { - t.Fatalf("PUT without a credential dropped the stored credential") + wantRef := func(step string, want *string) { + t.Helper() + got := themeCredStoredRef(t, env, name) + if (got == nil) != (want == nil) || (got != nil && *got != *want) { + t.Fatalf("%s: credential_ref = %v, want %v", step, got, want) + } } - // A JSON null clears it and removes the Secret. - put(`,"credential":null`) - if _, ok := themeCredSecret(t, cs, name); ok { - t.Fatalf("PUT with null left the credential secret behind") - } - if ref := themeCredStoredRef(t, env, name); ref != nil { - t.Fatalf("credential_ref after clear = %v, want nil", *ref) - } + // An omitted credentialSecret keeps the stored name. + put(themeSrcSpec(name), "") + wantRef("omitted", &first) - // A new credential is stored again. - put(`,"credential":` + themeCredDockerConfig) - if _, ok := themeCredSecret(t, cs, name); !ok { - t.Fatalf("PUT with a credential stored no secret") - } + // Moving the location keeps the name, as on a ModuleSource. + put(themeSrcSpec(name+"-moved"), "") + wantRef("moved location", &first) - // Moving the location drops the credential, so it never follows the source to - // another host. - moved := name + "-moved" - rr := themeInstDo(t, h, http.MethodPut, "/themes/sources/"+name, themeSrcBody(moved, "oci", themeSrcSpec(moved), "")) - if rr.Code != http.StatusOK { - t.Fatalf("move location: status %d body %s", rr.Code, rr.Body.String()) - } - if _, ok := themeCredSecret(t, cs, name); ok { - t.Fatalf("credential secret survived a location change") - } - if ref := themeCredStoredRef(t, env, name); ref != nil { - t.Fatalf("credential_ref after location change = %v, want nil", *ref) - } -} + // Another name replaces it. + put(themeSrcSpec(name), `,"credentialSecret":"`+second+`"`) + wantRef("replaced", &second) -func TestThemeSourceCredentialDeleteRemovesSecret(t *testing.T) { - env, cs := newThemeCredEnv(t) - defer env.svc.WaitIdle() - h := env.router("admin") - name := themeCredName() - create := themeSrcBody(name, "oci", themeSrcSpec(name), `,"credential":`+themeCredDockerConfig) - if rr := themeInstDo(t, h, http.MethodPost, "/themes/sources", create); rr.Code != http.StatusCreated { - t.Fatalf("create: status %d body %s", rr.Code, rr.Body.String()) - } + // A JSON null clears it; so does an empty string. + put(themeSrcSpec(name), `,"credentialSecret":null`) + wantRef("null", nil) + put(themeSrcSpec(name), `,"credentialSecret":"`+first+`"`) + put(themeSrcSpec(name), `,"credentialSecret":""`) + wantRef("empty string", nil) - // A duplicate create is refused and leaves the existing credential alone. - dup := themeSrcBody(name, "oci", themeSrcSpec(name), `,"credential":{"auths":{"registry.test":{"username":"x","password":"other"}}}`) - if rr := themeInstDo(t, h, http.MethodPost, "/themes/sources", dup); rr.Code != http.StatusConflict { - t.Fatalf("duplicate create: status %d body %s", rr.Code, rr.Body.String()) + // Deleting the source leaves the admin's Secrets in place. + if rr := themeInstDo(t, h, http.MethodDelete, "/themes/sources/"+name, ""); rr.Code != http.StatusNoContent { + t.Fatalf("delete: status %d body %s", rr.Code, rr.Body.String()) } - sec, ok := themeCredSecret(t, cs, name) - if !ok || !strings.Contains(string(sec.Data[corev1.DockerConfigJsonKey]), themeCredSecretValue) { - t.Fatalf("duplicate create replaced the existing credential") + for _, s := range []string{first, second} { + if _, err := env.cs.CoreV1().Secrets(themeCredNS).Get(context.Background(), s, metav1.GetOptions{}); err != nil { + t.Fatalf("secret %s after source delete: %v", s, err) + } } + themeCredAssertNoPanelWrites(t, env.cs, 2) +} - if rr := themeInstDo(t, h, http.MethodDelete, "/themes/sources/"+name, ""); rr.Code != http.StatusNoContent { - t.Fatalf("delete: status %d body %s", rr.Code, rr.Body.String()) +func TestThemeSourceCredentialSecretProblemsFailTheSource(t *testing.T) { + env := newThemeCredEnv(t) + h := env.router("admin") + noKey := themeCredName() + "-nokey" + themeCredMakeSecret(t, env.cs, noKey, map[string][]byte{"password": []byte(themeCredSecretValue)}) + cases := []struct { + name string + secret string + want string + }{ + {"missing secret", "no-such-secret", "no-such-secret"}, + {"no docker config key", noKey, corev1.DockerConfigJsonKey}, } - if _, ok := themeCredSecret(t, cs, name); ok { - t.Fatalf("delete left the credential secret behind") + for _, c := range cases { + name := themeCredName() + themeSrcPublish(t, env.themeCatEnv, name) + body := themeSrcBody(name, "oci", themeSrcSpec(name), `,"credentialSecret":"`+c.secret+`"`) + if rr := themeInstDo(t, h, http.MethodPost, "/themes/sources", body); rr.Code != http.StatusCreated { + t.Fatalf("%s: create: status %d body %s", c.name, rr.Code, rr.Body.String()) + } + env.svc.WaitIdle() + listed := themeSrcFind(t, themeSrcItems(t, h), name) + if listed.LastError == nil || !strings.Contains(*listed.LastError, c.want) { + t.Errorf("%s: lastError = %v, want it to name %q", c.name, listed.LastError, c.want) + } + if listed.LastError != nil { + themeCredAssertHidden(t, *listed.LastError) + } } + themeCredAssertNoPanelWrites(t, env.cs, 1) } -func TestThemeSourceCredentialRefusalsStoreNothing(t *testing.T) { - env, cs := newThemeCredEnv(t) +func TestThemeSourceCredentialSecretRefusals(t *testing.T) { + env := newThemeCredEnv(t) defer env.svc.WaitIdle() h := env.router("admin") cases := []struct { - name string - credential string + name string + typ string + spec string + value string }{ - {"no auths object", `{"username":"u","password":"p"}`}, - {"empty auths", `{"auths":{}}`}, - {"empty registry entry", `{"auths":{"registry.test":{}}}`}, - {"unknown field", `{"auths":{"registry.test":{"username":"u","password":"p"}},"extra":"x"}`}, - {"not an object", `"` + themeCredSecretValue + `"`}, + {"not a Kubernetes name", "oci", "", `"Not_A_Name"`}, + {"not a string", "oci", "", `{"name":"x"}`}, + {"local source", "local", `{"local":{"path":"themes"}}`, `"theme-creds"`}, } for _, c := range cases { name := themeCredName() - body := themeSrcBody(name, "oci", themeSrcSpec(name), `,"credential":`+c.credential) + spec := c.spec + if spec == "" { + spec = themeSrcSpec(name) + } + body := themeSrcBody(name, c.typ, spec, `,"credentialSecret":`+c.value) rr := themeInstDo(t, h, http.MethodPost, "/themes/sources", body) if rr.Code != http.StatusUnprocessableEntity { t.Errorf("%s: status %d, want 422; body %s", c.name, rr.Code, rr.Body.String()) } - themeCredAssertHidden(t, rr.Body.String()) - if _, ok := themeCredSecret(t, cs, name); ok { - t.Errorf("%s: refused credential stored a secret", c.name) - } for _, it := range themeSrcItems(t, h) { if it.Name == name { t.Errorf("%s: refused source was stored", c.name) } } } + themeCredAssertNoPanelWrites(t, env.cs, 0) +} + +// TestThemeSourceCredentialSecretNeedsStore checks that a panel without a credential store refuses a +// credential Secret name instead of storing a reference it cannot read. +func TestThemeSourceCredentialSecretNeedsStore(t *testing.T) { + env := newThemeCatEnv(t) + defer env.svc.WaitIdle() + h := env.router("admin") + name := themeCredName() + body := themeSrcBody(name, "oci", themeSrcSpec(name), `,"credentialSecret":"theme-creds"`) + if rr := themeInstDo(t, h, http.MethodPost, "/themes/sources", body); rr.Code != http.StatusUnprocessableEntity { + t.Fatalf("create without a credential store: status %d, want 422; body %s", rr.Code, rr.Body.String()) + } +} + +func TestThemeSourceCredentialSecretLegacyFieldAndDuplicate(t *testing.T) { + env := newThemeCredEnv(t) + defer env.svc.WaitIdle() + h := env.router("admin") + + // The old credential field carried secret values; it is an unknown field now, + // so the body is refused and nothing is stored. + legacy := themeCredName() + body := themeSrcBody(legacy, "oci", themeSrcSpec(legacy), `,"credential":`+themeCredDockerConfig) + rr := themeInstDo(t, h, http.MethodPost, "/themes/sources", body) + if rr.Code != http.StatusBadRequest { + t.Fatalf("legacy credential field: status %d, want 400; body %s", rr.Code, rr.Body.String()) + } + themeCredAssertHidden(t, rr.Body.String()) + for _, it := range themeSrcItems(t, h) { + if it.Name == legacy { + t.Fatalf("source with a legacy credential field was stored") + } + } + + // A duplicate create is refused and keeps the stored Secret name. + name := themeCredName() + first := name + "-a" + create := themeSrcBody(name, "oci", themeSrcSpec(name), `,"credentialSecret":"`+first+`"`) + if rr := themeInstDo(t, h, http.MethodPost, "/themes/sources", create); rr.Code != http.StatusCreated { + t.Fatalf("create: status %d body %s", rr.Code, rr.Body.String()) + } + dup := themeSrcBody(name, "oci", themeSrcSpec(name), `,"credentialSecret":"`+name+`-other"`) + if rr := themeInstDo(t, h, http.MethodPost, "/themes/sources", dup); rr.Code != http.StatusConflict { + t.Fatalf("duplicate create: status %d, want 409; body %s", rr.Code, rr.Body.String()) + } + if ref := themeCredStoredRef(t, env, name); ref == nil || *ref != first { + t.Fatalf("credential_ref after duplicate create = %v, want %s", ref, first) + } + themeCredAssertNoPanelWrites(t, env.cs, 0) +} + +func TestThemeSourceCredentialSecretUpdateNeedsStore(t *testing.T) { + env := newThemeCatEnv(t) + defer env.svc.WaitIdle() + h := env.router("admin") + name := themeCredName() + if rr := themeInstDo(t, h, http.MethodPost, "/themes/sources", themeSrcBody(name, "oci", themeSrcSpec(name), "")); rr.Code != http.StatusCreated { + t.Fatalf("create: status %d body %s", rr.Code, rr.Body.String()) + } + put := themeSrcBody(name, "oci", themeSrcSpec(name), `,"credentialSecret":"theme-creds"`) + if rr := themeInstDo(t, h, http.MethodPut, "/themes/sources/"+name, put); rr.Code != http.StatusUnprocessableEntity { + t.Fatalf("update without a credential store: status %d, want 422; body %s", rr.Code, rr.Body.String()) + } + src, err := env.store.GetThemeSource(context.Background(), name) + if err != nil || src.CredentialRef != nil { + t.Fatalf("credential_ref after refused update = %v, %v; want nil", src.CredentialRef, err) + } } diff --git a/api/internal/handlers/theme_sources_envtest_test.go b/api/internal/handlers/theme_sources_envtest_test.go index 5e393e159..dac0edca9 100644 --- a/api/internal/handlers/theme_sources_envtest_test.go +++ b/api/internal/handlers/theme_sources_envtest_test.go @@ -79,7 +79,8 @@ func themeSrcEntries(t *testing.T, env *themeCatEnv, source string) []db.ThemeCa return entries } -// themeSrcAssertNoCredential fails when a response body names a credential. +// themeSrcAssertNoCredential fails when a response body carries a credential +// value field. The credentialSecret name is allowed. func themeSrcAssertNoCredential(t *testing.T, body string) { t.Helper() // Error texts may name the credential ("credential for an oci source must @@ -127,10 +128,10 @@ func TestThemeSourcesRefuseInvalidSettings(t *testing.T) { `{"http":{"url":"http://example.com/t.tar.gz"}}`, ""), http.StatusUnprocessableEntity}, {"unknown spec key", themeSrcBody("typo-key", "oci", `{"oci":{"url":"registry.test/typo","themez":["deep-ocean"]}}`, ""), http.StatusUnprocessableEntity}, - {"oci credential not docker config", themeSrcBody("cred-shape", "oci", themeSrcSpec("cred-shape"), - `,"credential":{"username":"u","password":"p"}`), http.StatusUnprocessableEntity}, - {"credential on local source", themeSrcBody("cred-local", "local", - `{"local":{"path":"themes"}}`, `,"credential":{"token":"t"}`), http.StatusUnprocessableEntity}, + {"credential secret not a Kubernetes name", themeSrcBody("cred-shape", "oci", themeSrcSpec("cred-shape"), + `,"credentialSecret":"Not_A_Name"`), http.StatusUnprocessableEntity}, + {"credential secret on local source", themeSrcBody("cred-local", "local", + `{"local":{"path":"themes"}}`, `,"credentialSecret":"theme-creds"`), http.StatusUnprocessableEntity}, } for _, c := range cases { rr := themeInstDo(t, h, http.MethodPost, "/themes/sources", c.body) diff --git a/api/internal/themes/credentials.go b/api/internal/themes/credentials.go index 126c755cc..da4637655 100644 --- a/api/internal/themes/credentials.go +++ b/api/internal/themes/credentials.go @@ -14,8 +14,8 @@ import ( "github.com/go-git/go-git/v5/plumbing/transport" githttp "github.com/go-git/go-git/v5/plumbing/transport/http" corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/validation" "oras.land/oras-go/v2/registry/remote/auth" "github.com/GameplanePanel/gameplane/api/internal/db" @@ -23,43 +23,34 @@ import ( "github.com/GameplanePanel/gameplane/bundlefetch/oci" ) -// Theme source credentials (spec 043, OD-5). A credential is stored as a labelled -// Secret in the credentials namespace, through kube.Client.Secrets: a Kubernetes -// Secret in combined mode, a panel-encrypted management object in standalone -// mode. The source row keeps only the Secret name (credential_ref). The value is -// never returned by the API and never written to a log, an error text or the -// audit target. +// Theme source credentials (spec 043, OD-5, settled 2026-11-27: "Secret name, +// like modules"). An admin creates the credential Secret in the credentials +// namespace and names it on the source, the way a ModuleSource names its +// pullSecretRef or secretRef. The panel never writes, changes or deletes that +// Secret: the source row keeps only its name (credential_ref) and the indexer +// reads it through kube.Client.Secrets (a Kubernetes Secret in combined mode, a +// panel-encrypted management object in standalone mode) for each pull. The +// Secret's values are never returned by the API and never written to a log, an +// error text or the audit target. +// +// The Secret holds, as for module sources: +// - oci: a docker config JSON under .dockerconfigjson (the +// kubernetes.io/dockerconfigjson shape); +// - git, http: "token", or "username" and "password". const ( - // ThemeSourceSecretLabel marks the credential Secrets of theme sources. The - // service reads and deletes only Secrets that carry it. - ThemeSourceSecretLabel = "gameplane.local/theme-source" - - // credentialSecretPrefix starts every credential Secret name. A source name - // is at most 40 characters (maxSourceNameLen), so the prefix plus the name - // fits the 63-character limit of a Kubernetes object name. - credentialSecretPrefix = "gameplane-theme-source-" - - // managedByLabel and managedByValue match the labels the API sets on the - // Secrets it creates for admins (handlers.ManagedByLabel). - managedByLabel = "gameplane.local/managed-by" - managedByValue = "gameplane-api" - // gitHTTPUsername is the user name sent with a token for git sources. Forges // accept a token as the password with any user name. gitHTTPUsername = "gameplane" ) -// errCredentialNotManaged reports a Secret with the credential name that the -// theme service did not create. It is never read or deleted. -var errCredentialNotManaged = errors.New("theme source credential Secret is not managed by Gameplane") - // errCredentialEmpty reports a credential Secret that holds no data. var errCredentialEmpty = errors.New("theme source credential Secret has no data") -// errNoCredentialStore is returned when credentials are needed but the panel has -// no credential store (no Kubernetes client and no management store). -var errNoCredentialStore = &SourceError{Msg: "theme source credentials cannot be stored on this panel"} +// errNoCredentialStore is returned when a source names a credential Secret but +// the panel has no credential store (no Kubernetes client and no management +// store). +var errNoCredentialStore = &SourceError{Msg: "theme source credentials cannot be read on this panel"} // dockerConfig is the docker config JSON an oci source credential carries. It is // the same shape as a module source pull secret (kubernetes.io/dockerconfigjson). @@ -75,90 +66,33 @@ type dockerAuth struct { IdentityToken string `json:"identitytoken,omitempty"` } -// tokenCredential is the credential of a git or http source: a token, or a user -// name and password. -type tokenCredential struct { - Username string `json:"username,omitempty"` - Password string `json:"password,omitempty"` - Token string `json:"token,omitempty"` -} - -// hasCredentialInput reports whether a request carried a credential value. An -// absent field and a JSON null are both "no value". -func hasCredentialInput(raw json.RawMessage) bool { +// checkCredentialSecret reads the credentialSecret field of a request. It +// returns set=false when the field is absent (none on create, keep on update), +// and set=true with a nil name for a JSON null or an empty string (clear on +// update). A name must be a Kubernetes object name (DNS-1123 subdomain), and a +// local source takes none. +func checkCredentialSecret(typ string, raw json.RawMessage) (name *string, set bool, err error) { t := bytes.TrimSpace(raw) - return len(t) > 0 && string(t) != "null" -} - -// isCredentialNull reports whether a request sent an explicit JSON null, which -// clears the credential on update. -func isCredentialNull(raw json.RawMessage) bool { - return string(bytes.TrimSpace(raw)) == "null" -} - -// checkCredential validates a credential for a source type and returns the -// Secret data to store. Error texts are generic: they never echo the input, -// because a malformed credential may still contain a secret value. -func checkCredential(typ string, raw json.RawMessage) (map[string][]byte, error) { - switch typ { - case "oci": - var cfg dockerConfig - if err := decodeCredentialStrict(raw, &cfg); err != nil { - return nil, sourceErrf("credential for an oci source must be docker config JSON with an auths object") - } - if len(cfg.Auths) == 0 { - return nil, sourceErrf("credential needs an auths object with at least one registry") - } - for _, a := range cfg.Auths { - if a.Username == "" && a.Password == "" && a.Auth == "" && a.IdentityToken == "" { - return nil, sourceErrf("an auths entry has no username, password, auth or identitytoken") - } - } - canonical, err := json.Marshal(cfg) - if err != nil { - return nil, fmt.Errorf("encode credential: %w", err) - } - return map[string][]byte{corev1.DockerConfigJsonKey: canonical}, nil - case "git", "http": - var tc tokenCredential - if err := decodeCredentialStrict(raw, &tc); err != nil { - return nil, sourceErrf("credential for a %s source must be {\"token\"} or {\"username\",\"password\"}", typ) - } - if tc.Token != "" { - if tc.Username != "" || tc.Password != "" { - return nil, sourceErrf("credential takes a token or a username and password, not both") - } - return map[string][]byte{"token": []byte(tc.Token)}, nil - } - if tc.Username == "" || tc.Password == "" { - return nil, sourceErrf("credential needs a token or a username and password") - } - return map[string][]byte{"username": []byte(tc.Username), "password": []byte(tc.Password)}, nil - case "local": - return nil, sourceErrf("local theme sources take no credential") - default: - return nil, sourceErrf("unknown source type %q", typ) + if len(t) == 0 { + return nil, false, nil } -} - -// decodeCredentialStrict decodes a credential object, refusing unknown fields -// and trailing data. Its error is discarded by callers: it is never shown. -func decodeCredentialStrict(raw json.RawMessage, v any) error { - dec := json.NewDecoder(bytes.NewReader(bytes.TrimSpace(raw))) - dec.DisallowUnknownFields() - if err := dec.Decode(v); err != nil { - return err + if string(t) == "null" { + return nil, true, nil } - if dec.More() { - return errors.New("trailing data after credential") + var v string + if err := json.Unmarshal(t, &v); err != nil { + return nil, false, sourceErrf("credentialSecret must be a Secret name or null") } - return nil -} - -// credentialSecretName returns the name of the Secret that holds the credential -// of the source named source. -func credentialSecretName(source string) string { - return credentialSecretPrefix + source + if v == "" { + return nil, true, nil + } + if typ == "local" { + return nil, false, sourceErrf("local theme sources take no credential Secret") + } + if msgs := validation.IsDNS1123Subdomain(v); len(msgs) > 0 { + return nil, false, sourceErrf("credentialSecret must be a Kubernetes Secret name: %s", strings.Join(msgs, "; ")) + } + return &v, true, nil } // secretStore returns the credential store, or errNoCredentialStore when the @@ -174,79 +108,10 @@ func (s *Service) secretStore() (kube.SecretStore, error) { return st, nil } -// writeCredential creates or replaces the credential Secret of source with data -// (named by credentialSecretName). An existing Secret that is not labelled as a theme source -// credential is refused, so this path cannot overwrite another Secret. -func (s *Service) writeCredential(ctx context.Context, source string, data map[string][]byte) error { - st, err := s.secretStore() - if err != nil { - return err - } - name := credentialSecretName(source) - labels := map[string]string{ThemeSourceSecretLabel: "true", managedByLabel: managedByValue} - desired := &corev1.Secret{ - ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: s.credentialsNS, Labels: labels}, - Type: corev1.SecretTypeOpaque, - Data: data, - } - _, err = st.Create(ctx, desired, metav1.CreateOptions{}) - if err == nil { - return nil - } - if !apierrors.IsAlreadyExists(err) { - return fmt.Errorf("store theme source credential: %w", err) - } - existing, err := st.Get(ctx, name, metav1.GetOptions{}) - if err != nil { - return fmt.Errorf("read theme source credential: %w", err) - } - if existing.Labels[ThemeSourceSecretLabel] != "true" { - // A foreign Secret with the same name is a conflict the admin can fix by - // renaming the source, so it is a 422 refusal, not a server error. - return sourceErrf("a Secret named %s already exists and is not a theme source credential", name) - } - if existing.Labels == nil { - existing.Labels = map[string]string{} - } - for k, v := range labels { - existing.Labels[k] = v - } - existing.Data = data - existing.StringData = nil - if _, err := st.Update(ctx, existing, metav1.UpdateOptions{}); err != nil { - return fmt.Errorf("update theme source credential: %w", err) - } - return nil -} - -// deleteCredential removes the credential Secret of source. A missing Secret, or -// one that is not labelled as a theme source credential, is not an error. -func (s *Service) deleteCredential(ctx context.Context, source string) error { - st, err := s.secretStore() - if err != nil { - return err - } - name := credentialSecretName(source) - existing, err := st.Get(ctx, name, metav1.GetOptions{}) - if apierrors.IsNotFound(err) { - return nil - } - if err != nil { - return fmt.Errorf("read theme source credential: %w", err) - } - if existing.Labels[ThemeSourceSecretLabel] != "true" { - return nil - } - if err := st.Delete(ctx, name, metav1.DeleteOptions{}); err != nil && !apierrors.IsNotFound(err) { - return fmt.Errorf("delete theme source credential: %w", err) - } - return nil -} - // readCredential returns the Secret data of the credential of src. It returns -// nil when the source has no credential. A referenced credential that cannot be -// read, or is not a theme source credential, is an error; the error names the -// Secret but never its value. +// nil when the source names no Secret. A named Secret that cannot be read, holds +// no data, or lacks the keys its source type needs is an error; the error names +// the Secret but never its values. func (s *Service) readCredential(ctx context.Context, src db.ThemeSource) (map[string][]byte, error) { if src.CredentialRef == nil || *src.CredentialRef == "" { return nil, nil @@ -255,15 +120,25 @@ func (s *Service) readCredential(ctx context.Context, src db.ThemeSource) (map[s if err != nil { return nil, err } - existing, err := st.Get(ctx, *src.CredentialRef, metav1.GetOptions{}) + name := *src.CredentialRef + existing, err := st.Get(ctx, name, metav1.GetOptions{}) if err != nil { - return nil, fmt.Errorf("read credential of theme source %q: %w", src.Name, err) - } - if existing.Labels[ThemeSourceSecretLabel] != "true" { - return nil, errCredentialNotManaged + return nil, fmt.Errorf("read credential Secret %s of theme source %q: %w", name, src.Name, err) } if len(existing.Data) == 0 { - return nil, errCredentialEmpty + return nil, fmt.Errorf("credential Secret %s: %w", name, errCredentialEmpty) + } + switch src.Type { + case "oci": + if len(existing.Data[corev1.DockerConfigJsonKey]) == 0 { + return nil, fmt.Errorf("credential Secret %s has no %s key", name, corev1.DockerConfigJsonKey) + } + case "git", "http": + hasToken := len(existing.Data["token"]) > 0 + hasBasic := len(existing.Data["username"]) > 0 && len(existing.Data["password"]) > 0 + if !hasToken && !hasBasic { + return nil, fmt.Errorf("credential Secret %s needs a token key, or username and password keys", name) + } } return existing.Data, nil } diff --git a/api/internal/themes/credentials_test.go b/api/internal/themes/credentials_test.go new file mode 100644 index 000000000..687ee8303 --- /dev/null +++ b/api/internal/themes/credentials_test.go @@ -0,0 +1,113 @@ +package themes + +import ( + "context" + "encoding/base64" + "strings" + "testing" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes/fake" + + "github.com/GameplanePanel/gameplane/api/internal/db" + "github.com/GameplanePanel/gameplane/api/internal/kube" +) + +// credTestNS is the credentials namespace of these tests. +const credTestNS = "gameplane-test" + +// credTestService returns a Service whose credential store holds secrets. +func credTestService(t *testing.T, secrets ...*corev1.Secret) *Service { + t.Helper() + cs := fake.NewClientset() + for _, s := range secrets { + s.Namespace = credTestNS + if _, err := cs.CoreV1().Secrets(credTestNS).Create(context.Background(), s, metav1.CreateOptions{}); err != nil { + t.Fatalf("create secret %s: %v", s.Name, err) + } + } + return &Service{kube: &kube.Client{Typed: cs}, credentialsNS: credTestNS} +} + +// credTestSource is a source of type typ that names the Secret ref. +func credTestSource(typ, ref string) db.ThemeSource { + return db.ThemeSource{Name: "src", Type: typ, CredentialRef: &ref} +} + +func TestReadCredentialKeysPerType(t *testing.T) { + svc := credTestService(t, + &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "token"}, Data: map[string][]byte{"token": []byte("tok")}}, + &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "basic"}, Data: map[string][]byte{"username": []byte("u"), "password": []byte("p")}}, + &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "user-only"}, Data: map[string][]byte{"username": []byte("u")}}, + &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "empty"}}, + ) + ctx := context.Background() + cases := []struct { + typ, ref string + wantErr string + }{ + {"git", "token", ""}, + {"http", "basic", ""}, + {"git", "user-only", "needs a token key"}, + {"http", "empty", "has no data"}, + {"oci", "token", corev1.DockerConfigJsonKey}, + {"git", "missing", "missing"}, + } + for _, c := range cases { + _, err := svc.readCredential(ctx, credTestSource(c.typ, c.ref)) + switch { + case c.wantErr == "" && err != nil: + t.Errorf("%s/%s: unexpected error %v", c.typ, c.ref, err) + case c.wantErr != "" && (err == nil || !strings.Contains(err.Error(), c.wantErr)): + t.Errorf("%s/%s: err = %v, want it to contain %q", c.typ, c.ref, err, c.wantErr) + } + } + if data, err := svc.readCredential(ctx, db.ThemeSource{Name: "src", Type: "git"}); data != nil || err != nil { + t.Errorf("source without a Secret name: %v, %v; want nil, nil", data, err) + } + if _, err := (&Service{}).readCredential(ctx, credTestSource("git", "token")); err == nil { + t.Errorf("panel without a credential store read a credential") + } +} + +func TestGitAndHTTPAuthFromSecretData(t *testing.T) { + if gitAuth(nil) != nil || httpAuthHeader(nil) != "" { + t.Fatalf("no credential must give anonymous access") + } + tok := map[string][]byte{"token": []byte("tok")} + if got := httpAuthHeader(tok); got != "Bearer tok" { + t.Errorf("http token header = %q", got) + } + basic := map[string][]byte{"username": []byte("u"), "password": []byte("p")} + if got := httpAuthHeader(basic); got != "Basic "+base64.StdEncoding.EncodeToString([]byte("u:p")) { + t.Errorf("http basic header = %q", got) + } + if a := gitAuth(tok); a == nil || !strings.Contains(a.String(), gitHTTPUsername) { + t.Errorf("git token auth = %v, want user %s", a, gitHTTPUsername) + } + if a := gitAuth(basic); a == nil || !strings.Contains(a.String(), "u") { + t.Errorf("git basic auth = %v", a) + } +} + +func TestOCICredentialFuncMatchesRegistryHost(t *testing.T) { + cfg := `{"auths":{"https://index.docker.io/v1/":{"auth":"` + base64.StdEncoding.EncodeToString([]byte("robot:pw")) + `"}}}` + creds, err := ociCredentialFunc(map[string][]byte{corev1.DockerConfigJsonKey: []byte(cfg)}, "docker.io") + if err != nil { + t.Fatalf("ociCredentialFunc: %v", err) + } + got, err := creds(context.Background(), "DOCKER.IO") + if err != nil || got.Username != "robot" || got.Password != "pw" { + t.Fatalf("docker.io credential = %+v, %v", got, err) + } + if other, _ := creds(context.Background(), "evil.example"); other.Username != "" || other.Password != "" { + t.Fatalf("credential sent to another registry: %+v", other) + } + if _, err := ociCredentialFunc(map[string][]byte{corev1.DockerConfigJsonKey: []byte(cfg)}, "ghcr.io"); err == nil || !strings.Contains(err.Error(), "no entry for registry ghcr.io") { + t.Fatalf("missing registry entry: err = %v", err) + } + if _, err := ociCredentialFunc(map[string][]byte{}, "docker.io"); err == nil { + t.Fatalf("Secret without a docker config gave a credential") + } +} diff --git a/api/internal/themes/indexer.go b/api/internal/themes/indexer.go index 567580dee..70e38ea83 100644 --- a/api/internal/themes/indexer.go +++ b/api/internal/themes/indexer.go @@ -158,7 +158,8 @@ func (s *Service) RunDue(ctx context.Context) { } // newSourceSettle is how long after its creation the scheduler leaves a source -// alone, so the credential Secret written by CreateSource is in place first. +// alone, so a scheduled pass does not run beside the first index that +// CreateSource starts. const newSourceSettle = 10 * time.Second // isDue reports whether an enabled source should be refreshed at now. A source @@ -167,9 +168,8 @@ func isDue(src db.ThemeSource, now time.Time) bool { if !src.Enabled { return false } - // CreateSource inserts the row before it writes the credential Secret, so a - // scheduled pass in that gap would read a Secret that is not there yet. A - // source is left alone for newSourceSettle after its creation. + // CreateSource starts the first index itself, so a scheduled pass leaves a + // source alone for newSourceSettle after its creation. if created, err := time.Parse(time.RFC3339, src.CreatedAt); err == nil { if age := now.Sub(created); age >= 0 && age < newSourceSettle { return false diff --git a/api/internal/themes/sources.go b/api/internal/themes/sources.go index 276688cf7..805d8c9c9 100644 --- a/api/internal/themes/sources.go +++ b/api/internal/themes/sources.go @@ -63,11 +63,11 @@ func sourceErrf(format string, args ...any) error { type SourceSettings struct { // Type is "oci", "git", "http" or "local". Type string - // Credential is the optional credential JSON, in the shape checkCredential - // reads for Type. Absent (nil) means none on create and keep on update. The - // JSON null clears it on update. The value is stored as a labelled Secret and - // is never echoed back. - Credential json.RawMessage + // CredentialSecret is the optional name of an admin-made Secret in the + // credentials namespace that holds the source's credential, as raw JSON (a + // string or null). Absent (nil) means none on create and keep on update; a + // JSON null or "" clears it on update. The panel only reads the Secret. + CredentialSecret json.RawMessage // Spec is the type-specific JSON in the shape the indexer reads: one of // {"oci": {...}}, {"git": {...}}, {"http": {...}} or {"local": {...}}, plus an // optional "allow" list of glob patterns. @@ -90,32 +90,6 @@ type checkedSettings struct { refreshS int } -// sourceSpecOf decodes a stored spec. A spec that does not decode yields the -// zero value; stored specs were validated on write, so this is only a guard. -func sourceSpecOf(raw string) sourceSpec { - var sp sourceSpec - _ = json.Unmarshal([]byte(raw), &sp) - return sp -} - -// specURL returns the primary location of a spec: the registry prefix, git or -// HTTP URL, or local path. A change of it drops the source's credential -// reference (a credential must not follow a changed location). -func specURL(raw string) string { - sp := sourceSpecOf(raw) - switch { - case sp.OCI != nil: - return sp.OCI.URL - case sp.Git != nil: - return sp.Git.URL - case sp.HTTP != nil: - return sp.HTTP.URL - case sp.Local != nil: - return sp.Local.Path - } - return "" -} - // decodeSpec parses the spec JSON strictly: unknown keys are an error, so a // misspelled setting never silently has no effect. func decodeSpec(raw json.RawMessage) (sourceSpec, error) { @@ -317,24 +291,19 @@ func (s *Service) CreateSource(ctx context.Context, name string, in SourceSettin if err != nil { return db.ThemeSource{}, err } - var data map[string][]byte - var ref *string - if hasCredentialInput(in.Credential) { - if data, err = checkCredential(c.typ, in.Credential); err != nil { - return db.ThemeSource{}, err - } + ref, _, err := checkCredentialSecret(c.typ, in.CredentialSecret) + if err != nil { + return db.ThemeSource{}, err + } + if ref != nil { if _, err := s.secretStore(); err != nil { return db.ThemeSource{}, err } - secret := credentialSecretName(name) - ref = &secret } enabled := true if in.Enabled != nil { enabled = *in.Enabled } - // The row is inserted before the Secret is written, so a duplicate name is - // refused without touching the existing source's credential. created, err := s.store.CreateThemeSource(ctx, db.ThemeSource{ Name: name, Type: c.typ, @@ -347,16 +316,8 @@ func (s *Service) CreateSource(ctx context.Context, name string, in SourceSettin if err != nil { return db.ThemeSource{}, fmt.Errorf("create theme source %q: %w", name, err) } - if data != nil { - if err := s.writeCredential(ctx, name, data); err != nil { - if derr := s.store.DeleteThemeSource(ctx, created.ID); derr != nil { - s.logger.ErrorContext(ctx, "remove theme source after credential failure", "source", name, "error", derr) - } - return db.ThemeSource{}, err - } - } - // The credential Secret is in place now, so the first index can start at once. - // The scheduler's settle delay (newSourceSettle) remains as a guard only. + // The row is complete, so the first index can start at once. The scheduler's + // settle delay (newSourceSettle) remains as a guard only. if enabled { s.startJob(ctx, name, false) } @@ -389,27 +350,11 @@ func builtinSettings(old db.ThemeSource, in SourceSettings) (SourceSettings, err return in, nil } -// locationChanged reports whether an edit moves a source to another location -// (type, primary URL or path, or the insecure flag of an oci source). A moved -// location drops the credential reference, since a credential must not follow -// the source to a new host or be sent over plain HTTP. -func locationChanged(oldSpec, oldType, newSpec, newType string) bool { - return oldType != newType || - specURL(oldSpec) != specURL(newSpec) || - insecureOf(oldSpec) != insecureOf(newSpec) -} - -// insecureOf reports whether a stored spec allows plain HTTP to its registry. -func insecureOf(raw string) bool { - sp := sourceSpecOf(raw) - return sp.OCI != nil && sp.OCI.Insecure -} - // UpdateSource replaces the settings of the source named name. An edit that // changes the verify policy re-checks every entry of the source in the // background (failures become unverified, with no new digests needed). An edit -// that changes the spec re-indexes it. A changed location drops the credential -// reference. It returns db.ErrThemeNotFound for an unknown name. +// that changes the spec or the credential Secret re-indexes it. The credential +// Secret name stays when the location changes, as on a ModuleSource. It returns db.ErrThemeNotFound for an unknown name. func (s *Service) UpdateSource(ctx context.Context, name string, in SourceSettings) (db.ThemeSource, error) { old, err := s.store.GetThemeSource(ctx, name) if err != nil { @@ -428,13 +373,15 @@ func (s *Service) UpdateSource(ctx context.Context, name string, in SourceSettin // The built-in verify policy is chart-owned: keep the stored one. c.verify = old.Verify } - var data map[string][]byte - if hasCredentialInput(in.Credential) { - if data, err = checkCredential(c.typ, in.Credential); err != nil { + ref, refSet, err := checkCredentialSecret(c.typ, in.CredentialSecret) + if err != nil { + return db.ThemeSource{}, err + } + if ref != nil { + if _, err := s.secretStore(); err != nil { return db.ThemeSource{}, err } } - urlChanged := locationChanged(old.Spec, old.Type, c.spec, c.typ) next := old next.Type = c.typ next.Spec = c.spec @@ -443,40 +390,17 @@ func (s *Service) UpdateSource(ctx context.Context, name string, in SourceSettin if in.Enabled != nil { next.Enabled = *in.Enabled } - // The row is written before the Secret. If the row write fails, the stored - // credential is left untouched and the source keeps working; a failed Secret - // write after the row write is logged and returned, and a failed delete only - // leaves an orphaned Secret. - var writeData map[string][]byte - deleteSecret := false switch { - case data != nil: - // A new credential replaces the stored one, even when the location changed. - writeData = data - ref := credentialSecretName(name) - next.CredentialRef = &ref - case (isCredentialNull(in.Credential) || urlChanged) && old.CredentialRef != nil: - // Clearing, or a moved location, drops the credential: it must not follow - // the source to a new host. - deleteSecret = true + case refSet: + next.CredentialRef = ref + case c.typ == "local": + // A local source takes no credential, so a type change to local drops it. next.CredentialRef = nil } if err := s.store.UpdateThemeSource(ctx, next); err != nil { return db.ThemeSource{}, fmt.Errorf("update theme source %q: %w", name, err) } - credChanged := writeData != nil || deleteSecret - if writeData != nil { - if err := s.writeCredential(ctx, name, writeData); err != nil { - s.logger.ErrorContext(ctx, "write theme source credential after row update", "source", name, "error", err) - return db.ThemeSource{}, err - } - } - if deleteSecret { - if err := s.deleteCredential(ctx, name); err != nil { - s.logger.ErrorContext(ctx, "delete theme source credential after row update", "source", name, "error", err) - return db.ThemeSource{}, err - } - } + credChanged := !equalStringPtr(old.CredentialRef, next.CredentialRef) verifyChanged := !equalStringPtr(old.Verify, next.Verify) // A source that stays disabled is not fetched. Re-enabling one indexes it. reenabled := !old.Enabled && next.Enabled @@ -517,13 +441,6 @@ func (s *Service) DeleteSource(ctx context.Context, name string) (db.ThemeSource if err := s.store.DeleteThemeSource(ctx, src.ID); err != nil { return db.ThemeSource{}, fmt.Errorf("delete theme source %q: %w", name, err) } - if src.CredentialRef != nil { - // The row is gone, so a Secret that outlives it is only clutter. Log the - // failure rather than report a delete that did happen as failed. - if err := s.deleteCredential(ctx, name); err != nil { - s.logger.WarnContext(ctx, "remove theme source credential", "source", name, "error", err) - } - } return src, nil } diff --git a/api/specs.md b/api/specs.md index fe746f989..dc021c4a7 100644 --- a/api/specs.md +++ b/api/specs.md @@ -450,6 +450,26 @@ A submitted stylesheet is rejected with 400 and a message naming the offending r **FR-012 retention invariant:** `custom_accent`, `custom_surface`, and `custom_css` survive preset switches and overlay toggles; only the reset endpoint clears them. Client contract: ordinary updates omit optional custom fields rather than sending explicit nulls. +### Theme marketplace (spec 043) + +Per-user themes from admin-managed sources. Contract: `specs/043-theme-marketplace/contracts/themes-api.md`; data model: `specs/043-theme-marketplace/data-model.md`. Package `api/internal/themes` (`Service`), handlers `handlers/themes.go` (`MountThemes`: catalog and sources), `handlers/theme_sources.go`, `handlers/themes_catalog.go`, `handlers/themes_installed.go` (`MountInstalledThemes`), both mounted in `cmd/main.go`. Same code in combined and standalone mode: sources live in the panel database and the API fetches themes itself, with no operator (OD-4 A). + +**Routes:** +- `GET|POST /themes/sources`, `PUT|DELETE /themes/sources/{name}`, `POST /themes/sources/{name}/refresh` (202, indexes in the background) — RBAC rule `/themes/sources` → `themes:manage` (OD-7). Settings errors are 422 (`themes.SourceError`); duplicate name, deleting `official` (`builtin: true`, disable only) and refreshing a disabled source are 409. Source names are DNS labels of at most 40 characters; `refreshInterval` is seconds (default 3600, minimum 300); `verify` (`{key: PEM}` or `{keyless: {issuer, identity}}`) only for `oci`; URLs carrying credentials are refused. +- `GET /themes/catalog?q=&tag=&source=` → `{themes, sources}`: entries of enabled sources only; `sources` lists enabled sources with a `lastError` (the raw text only for `themes:manage`, a generic text otherwise). `GET /themes/catalog/{id}` adds `changelog`, `homepage`, `problems` and, for `valid` entries, `tokens` and `css`. The preview route serves the stored PNG or WebP with `Cache-Control: private, max-age=3600` and `X-Content-Type-Options: nosniff`. +- `GET|POST /users/me/themes`, `GET|DELETE /users/me/themes/{id}`, `POST /users/me/themes/{id}/update` — the caller's own rows only (another user's id is 404). Install takes `{catalogId, select?}`: 201, 409 `already_installed`, 409 `source_disabled`, 422 `entry_not_valid` (status not `valid`), 409 `install_limit` past `themes.MaxInstalledThemes` (50). Update moves to the newer `valid` entry with the same source id and theme name: 409 `no_update`, `source_disabled` or `source_removed`. Delete of the selected theme sets the preferences to preset Pink in the same transaction (FR-011). `updateAvailable` and `sourceRemoved` (source deleted, disabled, or no entry for the theme) are derived per request. +- `PUT /users/me/preferences` accepts `themeType: "installed"` with `installedThemeId` (422 if not the caller's); the preferences object carries `installedThemeId` and, when selected, `installedTheme: {tokens, css, version}`. + +**Credential Secret rule (OD-5, valgul 2026-11-27):** a source names an admin-made Secret in the credentials namespace by name (`credentialSecret`, column `credential_ref`), like a ModuleSource `pullSecretRef`/`secretRef`. The panel only reads it for each pull (`kube.Client.Secrets`: a Kubernetes Secret in combined mode, a panel-encrypted management object in standalone mode) and never creates, changes or deletes it. Keys: `.dockerconfigjson` for `oci`; `token` or `username` + `password` for `git` and `http`; a `local` source takes none (422). On create an absent field, `null` and `""` all mean none; PUT without the field keeps it, `null` or `""` clears it, and it stays when the location changes. Responses show the name only, never values; a missing Secret or key fails the source with a `lastError` naming the Secret. + +**Indexer (`themes/indexer.go`):** source types `oci` (explicit theme list under a registry prefix, `/:`, plain HTTP only with `oci.insecure`), `git`, `http` (archive) and `local` (under `--themes-local-root` / `GAMEPLANE_THEMES_LOCAL_ROOT`; empty, the default and the chart's setting, disables local sources). Fetching uses `bundlefetch` (OCI artifact type `application/vnd.gameplane.theme.v1+json`, layers keyed by their title annotation, total capped at `themepkg.MaxPackageBytes`); dials go through `netguard.IsAllowed`, so in-cluster registries are reachable and link-local and metadata addresses are not. Each package is validated with `themepkg.Validate` (name and version must match the published ones) and, when the source has a verify policy, checked with the `bundlefetch/verify` cosign verifier; a failed check stores status `unverified` with problem rule `signature`. The latest version is the highest semver tag without a pre-release part, else the highest pre-release. An unchanged digest skips re-validation unless the verify policy changed (then every entry is re-checked). A theme that fails keeps its previous row; a source where every theme fails records `last_error` and keeps its catalog. Errors are redacted (no URL userinfo or query). `Service.Run` runs on the leader replica only (`runPanelWorkers`): every 30 s it refreshes due sources one at a time, each bounded by 2 minutes; create, edit and refresh start an index at once. + +**Official source:** `SeedOfficial` creates and, on every start, reconciles the reserved `official` row (`oci`) from `GAMEPLANE_THEMES_OFFICIAL_SOURCE` (anything but `false` enables it), `GAMEPLANE_THEMES_OFFICIAL_URL`, `GAMEPLANE_THEMES_OFFICIAL_THEMES` (comma list) and, when `GAMEPLANE_THEMES_OFFICIAL_VERIFY=true`, the keyed policy `GAMEPLANE_THEMES_OFFICIAL_COSIGN_KEY`, all set by the chart from `themes.officialSource` (OD-6). The URL, theme list, insecure flag and verify policy are chart-owned (a PUT keeps them; its allow globs and the enabled flag and refresh interval apply); a restart keeps the admin's enabled flag and refresh interval. An empty theme list indexes nothing. + +**Tables (migration `common/028_theme_marketplace.sql`):** `theme_sources`, `theme_catalog_entries` (unique `(source_id, name)`, preview bytes as `BYTEA`/BLOB), `user_installed_themes` (a snapshot: tokens, sanitized CSS, version, digest; `source_id` set to NULL when its source is deleted, so the copy stays and reads as source removed), and `user_preferences.installed_theme_id`. Ids are generated in Go; there are no `REFERENCES`, so dependent rows are deleted or nulled in Go transactions (`DeleteThemeSource`, `DeleteInstalledTheme`, `DeleteUser` also deletes the user's installed themes). + +**Audit:** `theme_source.create|update|delete|refresh` and `theme.install|update|remove`. Reads are not audited. + ### Capture operation auditing **Scope — which operations are audited** (per T010, specs/done_003-network-capture-sidecar/research.md): diff --git a/changelog/unreleased/1135-theme-marketplace-api.md b/changelog/unreleased/1135-theme-marketplace-api.md index e4b1e6fdd..d7972bf8c 100644 --- a/changelog/unreleased/1135-theme-marketplace-api.md +++ b/changelog/unreleased/1135-theme-marketplace-api.md @@ -1,3 +1,3 @@ # Theme marketplace API and the themes:manage permission -The API can now index theme sources (OCI registry, git, HTTP archive or local folder), list their themes, and let each user install, update and remove themes for themselves. Theme sources are managed by admins and by roles granted the new `themes:manage` permission. The official theme source is configured under the new Helm value `themes.officialSource` (`enabled`, `url`, `themes`, `verify.enabled`, `verify.cosignPublicKey`), is verified with the same cosign key as modules, and is reconciled from the chart on every start. Set `themes.officialSource.enabled: false` on air-gapped installs that do not mirror it. [PR #1135](https://github.com/GameplanePanel/Gameplane/pull/1135) +The API can now index theme sources (OCI registry, git, HTTP archive or local folder), list their themes, and let each user install, update and remove themes for themselves. Theme sources are managed by admins and by roles granted the new `themes:manage` permission. The official theme source is configured under the new Helm value `themes.officialSource` (`enabled`, `url`, `themes`, `verify.enabled`, `verify.cosignPublicKey`), is verified with the same cosign key as modules, and is reconciled from the chart on every start. A private source names a Secret the admin creates in the credentials namespace (`credentialSecret`), the same way module sources name theirs; the panel only reads it. Theme sources reach private network addresses under the same rule as module sources. Set `themes.officialSource.enabled: false` on air-gapped installs that do not mirror it. [PR #1135](https://github.com/GameplanePanel/Gameplane/pull/1135) diff --git a/changelog/unreleased/1141-theme-marketplace-dashboard.md b/changelog/unreleased/1141-theme-marketplace-dashboard.md new file mode 100644 index 000000000..798ffd4b5 --- /dev/null +++ b/changelog/unreleased/1141-theme-marketplace-dashboard.md @@ -0,0 +1,3 @@ +# Theme marketplace in the dashboard + +Users can browse the theme catalog, preview a theme across the dashboard before installing it, and install, update, select and remove themes from their own settings. Admins and roles with `themes:manage` get a Theme sources page to add, edit, refresh, enable and remove sources. A private source names a pull secret (OCI) or credentials secret (git, HTTP) that the admin creates, the same way as module sources. [PR #1141](https://github.com/GameplanePanel/Gameplane/pull/1141) diff --git a/i18n/locales/en/app.json b/i18n/locales/en/app.json index 2ca91cd09..08fcbc3bb 100644 --- a/i18n/locales/en/app.json +++ b/i18n/locales/en/app.json @@ -4587,6 +4587,182 @@ "defaultMessage": "Your SFTP password", "description": "SFTP shown-once dialog: heading" }, + "web.components.themes.installed_themes_card.badge_installed": { + "defaultMessage": "Installed", + "description": "Settings theme: badge on an installed theme that is up to date" + }, + "web.components.themes.installed_themes_card.badge_source_removed": { + "defaultMessage": "Source removed", + "description": "Settings theme: badge on an installed theme whose source was removed" + }, + "web.components.themes.installed_themes_card.badge_update": { + "defaultMessage": "Update available", + "description": "Settings theme: badge on an installed theme with a newer version" + }, + "web.components.themes.installed_themes_card.browse": { + "defaultMessage": "Browse themes", + "description": "Settings theme: button linking to the theme catalog" + }, + "web.components.themes.installed_themes_card.installed_count": { + "defaultMessage": "{count, plural, one {# theme installed} other {# themes installed}}", + "description": "Settings theme: summary of installed themes" + }, + "web.components.themes.installed_themes_card.mode_dark": { + "defaultMessage": "Dark", + "description": "Settings theme: name of the dark mode in an installed theme's mode list" + }, + "web.components.themes.installed_themes_card.mode_light": { + "defaultMessage": "Light", + "description": "Settings theme: name of the light mode in an installed theme's mode list" + }, + "web.components.themes.installed_themes_card.modes_version": { + "defaultMessage": "{modes} · v{version}", + "description": "Settings theme: caption under an installed theme in the theme picker; modes are the comma-separated mode names, version the installed version" + }, + "web.components.themes.installed_themes_card.remove": { + "defaultMessage": "Remove", + "description": "Settings theme: button that removes an installed theme" + }, + "web.components.themes.installed_themes_card.remove_confirm": { + "defaultMessage": "Remove theme", + "description": "Settings theme: destructive confirm button for removing an installed theme" + }, + "web.components.themes.installed_themes_card.remove_text": { + "defaultMessage": "The theme is removed from your account. You can install it again from the catalog.", + "description": "Settings theme: confirm dialog text for removing an installed theme" + }, + "web.components.themes.installed_themes_card.remove_title": { + "defaultMessage": "Remove “{name}”?", + "description": "Settings theme: confirm dialog title for removing an installed theme" + }, + "web.components.themes.installed_themes_card.removed_count": { + "defaultMessage": "{count, plural, one {# source removed} other {# sources removed}}", + "description": "Settings theme: summary of installed themes whose source was removed" + }, + "web.components.themes.installed_themes_card.retention": { + "defaultMessage": "Installed themes are saved to your account only. Other users keep the theme they chose.", + "description": "Settings theme: note that installed themes are per user" + }, + "web.components.themes.installed_themes_card.selected_removed": { + "defaultMessage": "{name} was removed, you are back on Modern Pink", + "description": "Settings theme: one-time notice after the selected installed theme was removed; name is the theme display name" + }, + "web.components.themes.installed_themes_card.source_removed_caption": { + "defaultMessage": "Source removed · v{version}", + "description": "Settings theme: caption of an installed theme whose source was removed; version is the installed version" + }, + "web.components.themes.installed_themes_card.subtitle": { + "defaultMessage": "Themes installed for your account. Update or remove them here.", + "description": "Settings theme: subtitle under the installed themes heading" + }, + "web.components.themes.installed_themes_card.title": { + "defaultMessage": "Installed themes", + "description": "Settings theme: heading of the installed themes card" + }, + "web.components.themes.installed_themes_card.update": { + "defaultMessage": "Update", + "description": "Settings theme: button that updates an installed theme" + }, + "web.components.themes.installed_themes_card.update_count": { + "defaultMessage": "{count, plural, one {# update available} other {# updates available}}", + "description": "Settings theme: summary of installed themes with an update" + }, + "web.components.themes.installed_themes_card.update_line": { + "defaultMessage": "Update available: v{from} to v{to}", + "description": "Settings theme: line shown under an installed theme with an update" + }, + "web.components.themes.installed_themes_card.version_modes": { + "defaultMessage": "v{version} · {modes}", + "description": "Settings theme: caption of an installed theme; version is the installed version, modes the comma-separated mode names" + }, + "web.components.themes.theme_card.badge_installed": { + "defaultMessage": "Installed", + "description": "Theme badge: the theme is installed and up to date" + }, + "web.components.themes.theme_card.badge_invalid": { + "defaultMessage": "Invalid", + "description": "Theme badge: the theme package failed validation" + }, + "web.components.themes.theme_card.badge_low_contrast": { + "defaultMessage": "Low contrast", + "description": "Theme badge: the theme fails the contrast check" + }, + "web.components.themes.theme_card.badge_source_removed": { + "defaultMessage": "Source removed", + "description": "Theme badge: the theme source was removed; the installed copy is kept" + }, + "web.components.themes.theme_card.badge_unverified": { + "defaultMessage": "Not verified", + "description": "Theme badge: the theme package signature is not verified" + }, + "web.components.themes.theme_card.badge_update": { + "defaultMessage": "Update available", + "description": "Theme badge: a newer version of the installed theme exists" + }, + "web.components.themes.theme_card.by_author": { + "defaultMessage": "by {author} · v{version}", + "description": "Theme card: mono meta line with the author and version" + }, + "web.components.themes.theme_card.by_author_update": { + "defaultMessage": "by {author} · v{from} → v{to}", + "description": "Theme card: mono meta line with the author and the installed and available versions when an update is available" + }, + "web.components.themes.theme_card.dark_only": { + "defaultMessage": "Dark only", + "description": "Theme preview placeholder: the theme has only a dark mode" + }, + "web.components.themes.theme_card.install": { + "defaultMessage": "Install", + "description": "Theme card and detail: button that installs the theme for the user" + }, + "web.components.themes.theme_card.light_only": { + "defaultMessage": "Light only", + "description": "Theme preview placeholder: the theme has only a light mode" + }, + "web.components.themes.theme_card.mode_dark": { + "defaultMessage": "Dark", + "description": "Theme mode label: dark mode" + }, + "web.components.themes.theme_card.mode_light": { + "defaultMessage": "Light", + "description": "Theme mode label: light mode" + }, + "web.components.themes.theme_card.preview": { + "defaultMessage": "Preview", + "description": "Theme card and detail: button that previews the theme in place" + }, + "web.components.themes.theme_card.remove": { + "defaultMessage": "Remove", + "description": "Theme card and detail: button that removes an installed theme" + }, + "web.components.themes.theme_card.removed_placeholder": { + "defaultMessage": "Removed {name}", + "description": "Theme preview placeholder for an installed theme whose source was removed; name is the theme name" + }, + "web.components.themes.theme_card.unverified_source": { + "defaultMessage": "Signature not verified", + "description": "Theme card: source line when the package signature is not verified" + }, + "web.components.themes.theme_card.update": { + "defaultMessage": "Update", + "description": "Theme card and detail: button that updates an installed theme" + }, + "web.components.themes.theme_card.verified_source": { + "defaultMessage": "Signature verified", + "description": "Theme card: source line when the package signature is verified" + }, + "web.components.themes.theme_preview_banner.exit": { + "defaultMessage": "Exit preview", + "description": "Preview banner: button that ends the preview and restores the saved theme" + }, + "web.components.themes.theme_preview_banner.keep": { + "defaultMessage": "Keep", + "description": "Preview banner: button that installs and selects the previewed theme" + }, + "web.components.themes.theme_preview_banner.previewing": { + "defaultMessage": "Previewing {name}", + "description": "Preview banner: text naming the theme being previewed" + }, "web.components.ui.admin.edit_user_dialog.cancel": { "defaultMessage": "Cancel", "description": "Edit user dialog: button that closes the dialog without saving; keep it short" @@ -5323,6 +5499,10 @@ "defaultMessage": "Theme", "description": "Settings nav: label of the Theme settings page" }, + "web.components.ui.settings_nav.theme_sources": { + "defaultMessage": "Theme sources", + "description": "Settings nav: label of the Theme sources settings page (admins with themes:manage)" + }, "web.components.ui.settings_nav.updates": { "defaultMessage": "Updates", "description": "Settings nav: label of the Updates settings section" @@ -5527,6 +5707,14 @@ "defaultMessage": "invalid theme export: preferences.customCss exceeds the maximum length of {max} characters", "description": "Theme import error: the imported custom CSS is longer than the limit; {max} is the maximum number of characters" }, + "web.lib.theme_export.installed_fallback": { + "defaultMessage": "This export used the installed theme {name} {version} from {source}, which is not installed here. Modern Pink is used instead.", + "description": "Theme import notice: the exported installed theme is missing on this instance, so Modern Pink is applied; {name} is the theme name, {version} its version, {source} the theme source name" + }, + "web.lib.theme_export.installed_object": { + "defaultMessage": "invalid theme export: preferences.installed must be an object with source, name and version strings", + "description": "Theme import error: an installed theme export lacks its source, name or version" + }, "web.lib.theme_export.missing_field": { "defaultMessage": "invalid theme export: missing required field \"{field}\"", "description": "Theme import error: a required field is missing; {field} is the field path, such as preferences.presetId" @@ -12295,6 +12483,126 @@ "defaultMessage": "You need permission to change this server's settings.", "description": "Settings tab: footer text shown to users who can view but not change this server's settings" }, + "web.routes.theme_catalog.all_sources": { + "defaultMessage": "All sources", + "description": "Theme catalog: source filter option that shows every source" + }, + "web.routes.theme_catalog.all_tags": { + "defaultMessage": "All tags", + "description": "Theme catalog: tag filter option that clears the tag filter" + }, + "web.routes.theme_catalog.clear_filters": { + "defaultMessage": "Clear filters", + "description": "Theme catalog: button that resets the search, tag and source filters" + }, + "web.routes.theme_catalog.description": { + "defaultMessage": "Browse themes from your sources, preview them, and install them for your account.", + "description": "Theme catalog page: intro text under the heading" + }, + "web.routes.theme_catalog.empty_text": { + "defaultMessage": "Themes come from theme sources. Enable a source to browse themes. Administrators can manage sources in Theme sources.", + "description": "Theme catalog empty state: explanation text" + }, + "web.routes.theme_catalog.empty_title": { + "defaultMessage": "No theme sources enabled", + "description": "Theme catalog empty state: title when no source is enabled" + }, + "web.routes.theme_catalog.go_to_sources": { + "defaultMessage": "Go to Theme sources", + "description": "Theme catalog empty state: button linking to the theme sources page (admins only)" + }, + "web.routes.theme_catalog.no_results_text": { + "defaultMessage": "Try a different search term, another tag, or all sources.", + "description": "Theme catalog: empty state text when filters hide every theme" + }, + "web.routes.theme_catalog.no_results_title": { + "defaultMessage": "No themes match your filters", + "description": "Theme catalog: empty state title when filters hide every theme" + }, + "web.routes.theme_catalog.search_themes": { + "defaultMessage": "Search themes…", + "description": "Theme catalog: placeholder of the search input" + }, + "web.routes.theme_catalog.source_unreachable": { + "defaultMessage": "Source {name} could not be refreshed: {error}. Showing the last synced themes.", + "description": "Theme catalog: warning per source whose last refresh failed; name is the source name, error the last error" + }, + "web.routes.theme_catalog.title": { + "defaultMessage": "Theme catalog", + "description": "Theme catalog page: page heading" + }, + "web.routes.theme_detail.author": { + "defaultMessage": "Author", + "description": "Theme detail page: label of the author field" + }, + "web.routes.theme_detail.back_to_catalog": { + "defaultMessage": "Back to catalog", + "description": "Theme detail page: link back to the theme catalog" + }, + "web.routes.theme_detail.changelog_title": { + "defaultMessage": "Changelog", + "description": "Theme detail page: heading of the changelog card" + }, + "web.routes.theme_detail.description": { + "defaultMessage": "Preview a theme, then install it for your account.", + "description": "Theme detail page: intro text under the heading" + }, + "web.routes.theme_detail.description_title": { + "defaultMessage": "Description", + "description": "Theme detail page: heading of the description card" + }, + "web.routes.theme_detail.homepage": { + "defaultMessage": "Homepage", + "description": "Theme detail page: label of the homepage link" + }, + "web.routes.theme_detail.install_unavailable": { + "defaultMessage": "Install is unavailable: this theme has {count, plural, one {# problem} other {# problems}}. Ask the author to fix them and refresh the source.", + "description": "Theme detail page: helper text under the disabled Install button for an invalid theme" + }, + "web.routes.theme_detail.license": { + "defaultMessage": "License", + "description": "Theme detail page: label of the license field" + }, + "web.routes.theme_detail.preview_dark": { + "defaultMessage": "Dark", + "description": "Theme detail page: label of the dark preview panel" + }, + "web.routes.theme_detail.preview_light": { + "defaultMessage": "Light", + "description": "Theme detail page: label of the light preview panel" + }, + "web.routes.theme_detail.problem_line": { + "defaultMessage": ":{line}", + "description": "Theme detail: line number appended to a validation rule name, e.g. css.url:12" + }, + "web.routes.theme_detail.problems_found": { + "defaultMessage": "{count, plural, one {# problem found} other {# problems found}}", + "description": "Theme detail page: danger notice title for an invalid theme" + }, + "web.routes.theme_detail.problems_notice": { + "defaultMessage": "{name} cannot be installed until its author fixes these.", + "description": "Theme detail page: danger notice text for an invalid theme; name is the theme display name" + }, + "web.routes.theme_detail.problems_title": { + "defaultMessage": "Problems", + "description": "Theme detail page: heading of the problems card" + }, + "web.routes.theme_detail.title": { + "defaultMessage": "Theme details", + "description": "Theme detail page: page heading" + }, + "web.routes.theme_detail.update_from": { + "defaultMessage": "Update from {from} to {to}", + "description": "Theme detail page: helper text shown next to Update" + }, + "web.routes.theme_detail.version": { + "defaultMessage": "Version", + "description": "Theme detail page: label of the version field" + }, + "web.routes.theme_detail.version_installed": { + "defaultMessage": "{version} (installed {installed})", + "description": "Theme detail page: version value when an older version is installed" + }, "web.routes.theme_settings.a_stylesheet_layered_on_top_of_the": { "defaultMessage": "A stylesheet layered on top of the active base theme.", "description": "Theme settings: subtitle under the custom CSS overlay title: a stylesheet layered on top of the active base theme" @@ -12647,6 +12955,346 @@ "defaultMessage": "Your saved accent and surface", "description": "Theme settings: caption under the colour preview, naming the accent and surface colors you saved" }, + "web.routes.theme_sources.add_description": { + "defaultMessage": "Where the API discovers and pulls theme packages from.", + "description": "Theme sources dialog: text under the title when adding a source" + }, + "web.routes.theme_sources.add_source": { + "defaultMessage": "Add source", + "description": "Theme sources page: button that opens the add source dialog" + }, + "web.routes.theme_sources.add_title": { + "defaultMessage": "Add theme source", + "description": "Theme sources dialog: title when adding a source" + }, + "web.routes.theme_sources.admin_description": { + "defaultMessage": "Platform-wide configuration for this Gameplane instance.", + "description": "Theme sources page: intro text under the heading" + }, + "web.routes.theme_sources.admin_title": { + "defaultMessage": "Admin settings", + "description": "Theme sources page: page heading" + }, + "web.routes.theme_sources.builtin": { + "defaultMessage": "Built-in", + "description": "Theme sources table: badge on the built-in official source" + }, + "web.routes.theme_sources.cancel": { + "defaultMessage": "Cancel", + "description": "Theme sources dialog: button that closes the dialog without saving" + }, + "web.routes.theme_sources.card_description": { + "defaultMessage": "OCI registries, git repositories, HTTP indexes, and local folders the API pulls theme packages from. Installed copies stay with each user when a source is removed.", + "description": "Theme sources page: explanation under the sources card heading" + }, + "web.routes.theme_sources.card_title": { + "defaultMessage": "Theme sources", + "description": "Theme sources page: heading of the sources card" + }, + "web.routes.theme_sources.col_actions": { + "defaultMessage": "Actions", + "description": "Theme sources table: column header for the row action buttons" + }, + "web.routes.theme_sources.col_enabled": { + "defaultMessage": "On", + "description": "Theme sources table: column header for the enabled switch" + }, + "web.routes.theme_sources.col_last_sync": { + "defaultMessage": "Last sync", + "description": "Theme sources table: column header for the last sync time" + }, + "web.routes.theme_sources.col_name": { + "defaultMessage": "Name", + "description": "Theme sources table: column header for the source name" + }, + "web.routes.theme_sources.col_status": { + "defaultMessage": "Status", + "description": "Theme sources table: column header for the sync status" + }, + "web.routes.theme_sources.col_themes": { + "defaultMessage": "Themes", + "description": "Theme sources table: column header for the number of themes" + }, + "web.routes.theme_sources.col_type": { + "defaultMessage": "Type", + "description": "Theme sources table: column header for the source type" + }, + "web.routes.theme_sources.delete_confirm": { + "defaultMessage": "Delete source", + "description": "Theme sources: destructive confirm button for deleting a source" + }, + "web.routes.theme_sources.delete_for": { + "defaultMessage": "Delete {name}", + "description": "Theme sources table: screen-reader name of the delete button of a source; name is the source name" + }, + "web.routes.theme_sources.delete_text": { + "defaultMessage": "The source and its catalog entries are removed. Installed copies stay with each user.", + "description": "Theme sources: confirm dialog text for deleting a source" + }, + "web.routes.theme_sources.delete_title": { + "defaultMessage": "Delete source “{name}”?", + "description": "Theme sources: confirm dialog title for deleting a source; name is the source name" + }, + "web.routes.theme_sources.edit_description": { + "defaultMessage": "Change how the API reaches and verifies this source. The type cannot be changed.", + "description": "Theme sources dialog: text under the title when editing a source" + }, + "web.routes.theme_sources.edit_for": { + "defaultMessage": "Edit {name}", + "description": "Theme sources table: screen-reader name of the edit button of a source; name is the source name" + }, + "web.routes.theme_sources.edit_title": { + "defaultMessage": "Edit theme source", + "description": "Theme sources dialog: title when editing a source" + }, + "web.routes.theme_sources.field_allow": { + "defaultMessage": "Allow list", + "description": "Theme sources dialog: label of the theme name filter field" + }, + "web.routes.theme_sources.field_credentials_secret": { + "defaultMessage": "Credentials secret", + "description": "Theme sources dialog: label of the credentials Secret name field for git and HTTP sources" + }, + "web.routes.theme_sources.field_git_url": { + "defaultMessage": "Repository URL", + "description": "Theme sources dialog: label of the git repository URL field" + }, + "web.routes.theme_sources.field_http_url": { + "defaultMessage": "Index URL", + "description": "Theme sources dialog: label of the HTTP index URL field" + }, + "web.routes.theme_sources.field_identity": { + "defaultMessage": "Cosign identity", + "description": "Theme sources dialog: label of the keyless identity field" + }, + "web.routes.theme_sources.field_insecure": { + "defaultMessage": "Allow plain HTTP (local registries only)", + "description": "Theme sources dialog: switch label for plain HTTP registries" + }, + "web.routes.theme_sources.field_interval": { + "defaultMessage": "Refresh interval", + "description": "Theme sources dialog: label of the refresh interval field" + }, + "web.routes.theme_sources.field_issuer": { + "defaultMessage": "Cosign issuer", + "description": "Theme sources dialog: label of the keyless issuer field" + }, + "web.routes.theme_sources.field_local_path": { + "defaultMessage": "Folder path", + "description": "Theme sources dialog: label of the local folder path field" + }, + "web.routes.theme_sources.field_name": { + "defaultMessage": "Name", + "description": "Theme sources dialog: label of the source name field" + }, + "web.routes.theme_sources.field_path": { + "defaultMessage": "Path in repository", + "description": "Theme sources dialog: label of the optional path inside a git repository field" + }, + "web.routes.theme_sources.field_public_key": { + "defaultMessage": "Public key (PEM)", + "description": "Theme sources dialog: label of the cosign public key field" + }, + "web.routes.theme_sources.field_pull_secret": { + "defaultMessage": "Pull secret", + "description": "Theme sources dialog: label of the OCI pull secret name field; the Secret holds registry credentials" + }, + "web.routes.theme_sources.field_ref": { + "defaultMessage": "Git ref", + "description": "Theme sources dialog: label of the optional git branch or tag field" + }, + "web.routes.theme_sources.field_registry_url": { + "defaultMessage": "Registry URL", + "description": "Theme sources dialog: label of the OCI registry URL field" + }, + "web.routes.theme_sources.field_required": { + "defaultMessage": "Fill in the required fields.", + "description": "Theme sources dialog: validation error when a required field is empty" + }, + "web.routes.theme_sources.field_themes": { + "defaultMessage": "Themes", + "description": "Theme sources dialog: label of the OCI theme names field" + }, + "web.routes.theme_sources.field_type": { + "defaultMessage": "Type", + "description": "Theme sources dialog: label of the source type select" + }, + "web.routes.theme_sources.field_verify": { + "defaultMessage": "Signature verification", + "description": "Theme sources dialog: label of the signature verification select" + }, + "web.routes.theme_sources.footer": { + "defaultMessage": "The official source is built in. It can be disabled but not deleted.", + "description": "Theme sources page: info line under the table about the built-in source" + }, + "web.routes.theme_sources.hint_allow": { + "defaultMessage": "Optional theme name filter, exact names or globs, comma-separated.", + "description": "Theme sources dialog: hint under the allow list field" + }, + "web.routes.theme_sources.hint_git_secret": { + "defaultMessage": "Secret with token or username+password. Optional.", + "description": "Theme sources dialog: hint under the git credentials Secret name field" + }, + "web.routes.theme_sources.hint_http_secret": { + "defaultMessage": "Secret with token (Bearer) or username+password. Optional.", + "description": "Theme sources dialog: hint under the HTTP credentials Secret name field" + }, + "web.routes.theme_sources.hint_identity": { + "defaultMessage": "Signer identity to match, exact or regexp.", + "description": "Theme sources dialog: hint under the identity field" + }, + "web.routes.theme_sources.hint_interval": { + "defaultMessage": "How often the catalog re-indexes. Defaults to 1h.", + "description": "Theme sources dialog: hint under the refresh interval field" + }, + "web.routes.theme_sources.hint_issuer": { + "defaultMessage": "OIDC issuer that signed the packages.", + "description": "Theme sources dialog: hint under the issuer field" + }, + "web.routes.theme_sources.hint_name": { + "defaultMessage": "DNS label identifying this source.", + "description": "Theme sources dialog: hint under the name field" + }, + "web.routes.theme_sources.hint_public_key": { + "defaultMessage": "Paste the PEM public key that signed the packages.", + "description": "Theme sources dialog: hint under the public key field" + }, + "web.routes.theme_sources.hint_pull_secret": { + "defaultMessage": "Credentials for private registries (optional).", + "description": "Theme sources dialog: hint under the OCI pull secret name field" + }, + "web.routes.theme_sources.hint_themes": { + "defaultMessage": "Comma-separated theme names (registries can't be enumerated).", + "description": "Theme sources dialog: hint under the OCI theme names field" + }, + "web.routes.theme_sources.hint_verify": { + "defaultMessage": "Require a valid cosign signature on every theme package from this source.", + "description": "Theme sources dialog: hint under the signature verification select" + }, + "web.routes.theme_sources.interval_invalid": { + "defaultMessage": "Use a duration such as 30m or 1h, at least 5m.", + "description": "Theme sources dialog: validation error for the refresh interval" + }, + "web.routes.theme_sources.ph_allow": { + "defaultMessage": "aurora-*", + "description": "Theme sources dialog: example glob in the empty allow list field; not translated" + }, + "web.routes.theme_sources.ph_git_path": { + "defaultMessage": "themes", + "description": "Theme sources dialog: example folder in the empty path field; not translated" + }, + "web.routes.theme_sources.ph_git_ref": { + "defaultMessage": "main", + "description": "Theme sources dialog: example git branch in the empty ref field; not translated" + }, + "web.routes.theme_sources.ph_git_secret": { + "defaultMessage": "gh-creds", + "description": "Theme sources dialog: example Secret name in the empty git credentials field; a sample value, not a default" + }, + "web.routes.theme_sources.ph_git_url": { + "defaultMessage": "github.com/community/gp-themes", + "description": "Theme sources dialog: example git URL in the empty field; not translated" + }, + "web.routes.theme_sources.ph_http_secret": { + "defaultMessage": "archive-creds", + "description": "Theme sources dialog: example Secret name in the empty HTTP credentials field; a sample value, not a default" + }, + "web.routes.theme_sources.ph_http_url": { + "defaultMessage": "themes.example.org/index.json", + "description": "Theme sources dialog: example HTTP index URL in the empty field; not translated" + }, + "web.routes.theme_sources.ph_identity": { + "defaultMessage": "github.com/gameplane/themes", + "description": "Theme sources dialog: example signer identity in the empty field; not translated" + }, + "web.routes.theme_sources.ph_interval": { + "defaultMessage": "1h", + "description": "Theme sources dialog: example refresh interval in the empty field; h means hours" + }, + "web.routes.theme_sources.ph_issuer": { + "defaultMessage": "https://token.actions.githubusercontent.com", + "description": "Theme sources dialog: example OIDC issuer URL in the empty field; not translated" + }, + "web.routes.theme_sources.ph_local_path": { + "defaultMessage": "/srv/gameplane/themes", + "description": "Theme sources dialog: example folder path in the empty local path field; not translated" + }, + "web.routes.theme_sources.ph_name": { + "defaultMessage": "community", + "description": "Theme sources dialog: example source name shown in the empty name field; a sample value, not a default" + }, + "web.routes.theme_sources.ph_pull_secret": { + "defaultMessage": "registry-creds", + "description": "Theme sources dialog: example Secret name in the empty pull secret field; a sample value, not a default" + }, + "web.routes.theme_sources.ph_registry_url": { + "defaultMessage": "ghcr.io/gameplane/themes", + "description": "Theme sources dialog: example registry URL in the empty field; not translated" + }, + "web.routes.theme_sources.ph_themes": { + "defaultMessage": "aurora-night, paper-light", + "description": "Theme sources dialog: example theme names in the empty field; not translated" + }, + "web.routes.theme_sources.refresh_for": { + "defaultMessage": "Refresh {name}", + "description": "Theme sources table: screen-reader name of the refresh button of a source; name is the source name" + }, + "web.routes.theme_sources.status_failed": { + "defaultMessage": "Sync failed: {error}", + "description": "Theme sources table: status of a source whose last sync failed; error is the last error" + }, + "web.routes.theme_sources.status_never": { + "defaultMessage": "Never synced", + "description": "Theme sources table: status of a source that has not synced yet" + }, + "web.routes.theme_sources.status_synced": { + "defaultMessage": "Synced", + "description": "Theme sources table: status of a source that synced successfully" + }, + "web.routes.theme_sources.submit_add": { + "defaultMessage": "Add source", + "description": "Theme sources dialog: submit button when adding a source" + }, + "web.routes.theme_sources.submit_save": { + "defaultMessage": "Save changes", + "description": "Theme sources dialog: submit button when editing a source" + }, + "web.routes.theme_sources.toggle_for": { + "defaultMessage": "{name}: On", + "description": "Theme sources table: screen-reader name of a source's enabled switch; name is the source name" + }, + "web.routes.theme_sources.type_git": { + "defaultMessage": "Git repository", + "description": "Theme sources dialog: source type option for a git repository" + }, + "web.routes.theme_sources.type_http": { + "defaultMessage": "HTTP index", + "description": "Theme sources dialog: source type option for an HTTP index" + }, + "web.routes.theme_sources.type_local": { + "defaultMessage": "Local folder", + "description": "Theme sources dialog: source type option for a local folder" + }, + "web.routes.theme_sources.type_oci": { + "defaultMessage": "OCI registry", + "description": "Theme sources dialog: source type option for an OCI registry" + }, + "web.routes.theme_sources.verify_key": { + "defaultMessage": "Public key", + "description": "Theme sources dialog: signature verification option for a public key" + }, + "web.routes.theme_sources.verify_keyless": { + "defaultMessage": "Keyless (issuer + identity)", + "description": "Theme sources dialog: signature verification option for keyless signing" + }, + "web.routes.theme_sources.verify_none": { + "defaultMessage": "None", + "description": "Theme sources dialog: signature verification option for no verification" + }, + "web.routes.themes.preview_unavailable_safe_mode": { + "defaultMessage": "Previews are unavailable in safe mode.", + "description": "Theme pages: error shown when a preview is requested while safe mode is active, which suspends installed themes" + }, "web.routes.users.account_is_oidc_managed": { "defaultMessage": "Account is OIDC-managed", "description": "Users: tooltip explaining that an OIDC account's password is managed elsewhere" diff --git a/specs/043-theme-marketplace/OPEN-DECISIONS.md b/specs/043-theme-marketplace/OPEN-DECISIONS.md index 0710358f4..8b5115f47 100644 --- a/specs/043-theme-marketplace/OPEN-DECISIONS.md +++ b/specs/043-theme-marketplace/OPEN-DECISIONS.md @@ -90,7 +90,8 @@ Blocks T046 (source credential handling). Settle before T046 is merged; if B is - `DELETE /themes/sources/official` answers 409: the official source can only be disabled, as the T004 design brief says ("marked as built-in and cannot be deleted, only disabled") and FR-002 allows. - Install limit answers 409 `server.themes.install_limit`; a malformed or foreign installed id answers 404; refresh on a disabled source answers 409 `source_disabled`. - `refreshInterval` is in seconds (default 3600, floor 300). Source names are DNS labels of at most 40 characters (room for a derived Secret name, OD-5). -- OD-5 (option A) is implemented: `POST`/`PUT /themes/sources` take an optional `credential`. An oci source takes docker config JSON (`{"auths": {...}}`); a git or http source takes `{"token"}` or `{"username","password"}`; a local source takes none (422). The value is stored as a labelled Secret `gameplane-theme-source-` (label `gameplane.local/theme-source=true`) through `kube.Client.Secrets(credentialsNS)`, and the row keeps only its name in `credential_ref`. PUT without `credential` keeps it, `null` clears it, and a moved location drops it. Delete removes the Secret. Responses and errors never carry the value. The indexer reads the Secret for each pull; the signature check still pulls anonymously. +- OD-5 follow-up (valgul 2026-11-27, card "Should the theme source dialog take a Secret name, like module sources?": "Secret name, like modules"): the bullet below is replaced. `POST`/`PUT /themes/sources` take an optional `credentialSecret`, the name of a Secret the admin creates in the credentials namespace, stored in `credential_ref` and shown in responses. The panel only reads that Secret (`.dockerconfigjson` for oci; `token` or `username` + `password` for git and http) and never writes or deletes it. PUT without it keeps it, `null` or `""` clears it, and it stays when the location changes, as on a ModuleSource. Contract: contracts/themes-api.md. +- Superseded by the follow-up above: OD-5 (option A) was first implemented as: `POST`/`PUT /themes/sources` take an optional `credential`. An oci source takes docker config JSON (`{"auths": {...}}`); a git or http source takes `{"token"}` or `{"username","password"}`; a local source takes none (422). The value is stored as a labelled Secret `gameplane-theme-source-` (label `gameplane.local/theme-source=true`) through `kube.Client.Secrets(credentialsNS)`, and the row keeps only its name in `credential_ref`. PUT without `credential` keeps it, `null` clears it, and a moved location drops it. Delete removes the Secret. Responses and errors never carry the value. The indexer reads the Secret for each pull; the signature check still pulls anonymously. - Source list items carry an extra `builtin` boolean (additive to `contracts/themes-api.md`). ## OD-7: Permission for theme sources (SETTLED: A, valgul 2026-11-27) diff --git a/specs/043-theme-marketplace/contracts/themes-api.md b/specs/043-theme-marketplace/contracts/themes-api.md index 8e16db8bb..8098cd9b7 100644 --- a/specs/043-theme-marketplace/contracts/themes-api.md +++ b/specs/043-theme-marketplace/contracts/themes-api.md @@ -6,13 +6,15 @@ All routes under the API base path, JSON, session or bearer auth as today. Error | Method | Path | Body / result | |---|---|---| -| GET | `/themes/sources` | list: `{name, type, spec, verify, refreshInterval, enabled, lastSyncAt, lastError, themeCount}`; no credentials | -| POST | `/themes/sources` | create: `{name, type, spec, credential?, verify?, refreshInterval?, enabled?}` → 201 + source; 409 on duplicate name | -| PUT | `/themes/sources/{name}` | replace (credential omitted = keep, `null` = clear) | +| GET | `/themes/sources` | list: `{name, type, spec, verify, credentialSecret, refreshInterval, enabled, builtin, lastSyncAt, lastError, themeCount}`; `credentialSecret` is a Secret name or null, never a Secret value | +| POST | `/themes/sources` | create: `{name, type, spec, credentialSecret?, verify?, refreshInterval?, enabled?}` → 201 + source; 409 on duplicate name | +| PUT | `/themes/sources/{name}` | replace (`credentialSecret` omitted = keep, `null` or `""` = clear; it stays when the location changes, as on a ModuleSource) | | DELETE | `/themes/sources/{name}` | 204; catalog entries go, users' installed copies stay (FR-013) | | POST | `/themes/sources/{name}/refresh` | 202; indexes now | -Validation mirrors `ModuleSource` CEL rules: type-specific spec required, `verify` only for `oci`, interval ≥ 5m. Source URLs pass `netguard.IsPublic` at dial time unless the admin marks `oci.insecure` for a private registry (same rule as module sources). +Validation mirrors `ModuleSource` CEL rules: type-specific spec required, `verify` only for `oci`, interval ≥ 5m. Source URLs pass `netguard.IsAllowed` at dial time, the same rule as module sources: private and in-cluster addresses are allowed, link-local and cloud metadata addresses are refused (valgul 2026-11-27). `oci.insecure` only allows plain HTTP to the registry. + +`credentialSecret` names a Secret the admin creates in the credentials namespace, like a ModuleSource `pullSecretRef` or `secretRef` (OD-5, valgul 2026-11-27: "Secret name, like modules"). The panel only reads it, for each pull, and never creates, changes or deletes it. It must be a Kubernetes object name; a `local` source takes none (422). It holds `.dockerconfigjson` for an `oci` source, and `token` or `username` + `password` for a `git` or `http` source. A missing Secret or missing keys fail the source with a `lastError` that names the Secret, never its values. A restricted install (`nativeRBAC.remoteClusters: false`) lists the name in `nativeRBAC.runtimeSecretNames` so the API may read it. ## Catalog (any signed-in user) diff --git a/specs/043-theme-marketplace/data-model.md b/specs/043-theme-marketplace/data-model.md index 5474ef030..f78c9fe67 100644 --- a/specs/043-theme-marketplace/data-model.md +++ b/specs/043-theme-marketplace/data-model.md @@ -12,7 +12,7 @@ One admin-managed source (FR-001, FR-002). Mirrors `ModuleSourceSpec`. | `name` | text, unique | DNS-1123 label, max 63; `official` reserved for the seeded source | | `type` | text | `oci` \| `git` \| `http` \| `local` | | `spec` | text (JSON) | type-specific settings: `oci {url, themes[], insecure}`, `git {url, ref, path}`, `http {url}`, `local {path}`; plus `allow[]` globs | -| `credential_ref` | text, nullable | name of a labelled credential Secret (Kubernetes Secret in combined mode, panel-encrypted `management_objects` row in standalone mode, covered by key rotation); the credential itself is never stored in the row or returned by the API (OD-5) | +| `credential_ref` | text, nullable | name of an admin-made credential Secret in the credentials namespace (Kubernetes Secret in combined mode, panel-encrypted `management_objects` row in standalone mode, covered by key rotation), shown as `credentialSecret`; the panel only reads it, and its values are never stored in the row or returned by the API (OD-5) | | `verify` | text (JSON), nullable | `{key: PEM}` or `{keyless: {issuer, identity}}`, `requireTransparencyLog`; only for `oci` | | `refresh_interval_s` | integer | default 3600, min 300 | | `enabled` | integer (0/1) | default 1 | diff --git a/specs/043-theme-marketplace/tasks.md b/specs/043-theme-marketplace/tasks.md index 1291afbed..becb52a3f 100644 --- a/specs/043-theme-marketplace/tasks.md +++ b/specs/043-theme-marketplace/tasks.md @@ -81,7 +81,7 @@ - [X] T023 [P] [US1] Envtest `api/internal/handlers/themes_catalog_envtest_test.go`: fake OCI registry with one valid, one invalid and one unsigned theme; filters; unreachable second source still lists the first (SC-006); preview headers; signed-in non-admin can read. - [X] T024 [P] [US1] Unit tests `api/internal/themes/indexer_test.go`: unchanged digest skipped, changed digest re-pulled, per-source failure isolation, refresh interval floor. - [ ] T025 [US1] i18n strings for catalog, detail and preview in `i18n/locales/` (English source pack; other packs follow the spec 019 flow). -- [ ] T026 [US1] Preview state in `web/src/lib/useThemePreview.ts`: apply catalog tokens and css in memory through the same injection path as `useThemePreferences.ts`, restore saved preferences on Exit, route change away from theme pages, or reload; nothing written server-side. +- [ ] T026 [US1] Preview state in `web/src/lib/useThemePreview.ts`: apply catalog tokens and css in memory through the same injection path as `useThemePreferences.ts`, restore saved preferences on Exit or reload; nothing written server-side. The preview stays on across pages, as in the design (valgul 2026-11-27, card "Should a theme preview stay on while browsing other pages?": "Keep it across pages (design)"); the earlier "route change away from theme pages" restore is dropped. - [ ] T027 [P] [US1] Vitest `web/src/lib/useThemePreview.test.ts`: apply, exit restores exactly, reload restores, safe mode blocks preview CSS. - [ ] T028 [US1] Routes `/settings/theme/catalog` and `/settings/theme/catalog/$id` registered in `web/src/router/tree.tsx`. - [ ] T029 [US1] `web/src/routes/ThemeCatalog.tsx` from the T004 export: grid, search, tag and source filters, badges, unreachable-source banner, empty and loading states. @@ -161,7 +161,7 @@ - [ ] T055 New bucket `themes` in `test/e2e/buckets.sh` and `test/e2e/api_themes_e2e_test.go` (`t.Parallel()`, unique names, `ociPushMu` around pushes, ≤ 7 logins): push a signed and an unsigned theme to the Kind registry, add a source, catalog lists both with the unsigned one flagged after enabling verify, user A installs and selects, user B unaffected, update, disable source (installed copy keeps working), remove (fallback to Pink). - [ ] T056 [P] Standalone case in `test/e2e/standalone_panel_e2e_test.go` (new test function): add a local or OCI theme source and install a theme with no operator (OD-4). -- [ ] T057 [P] Update `api/specs.md` (themes service, routes, indexer, tables) and `web/specs.md` (catalog, preview, installed render order, safe mode). +- [X] T057 [P] Update `api/specs.md` (themes service, routes, indexer, tables) and `web/specs.md` (catalog, preview, installed render order, safe mode). Done: `api/specs.md` "Theme marketplace (spec 043)", `web/specs.md` "Theme marketplace (spec 043)". - [ ] T058 [P] `changelog/unreleased/-theme-marketplace.md` per `changelog/unreleased/README.md` (feature, new Helm value `themes.officialSource.enabled`, new permission `themes:manage`). - [ ] T059 Run `quickstart.md` sections 1–6 on a dev cluster and a standalone panel (valgul's manual walk); record results in `specs/043-theme-marketplace/quickstart-results.md`. diff --git a/web/specs.md b/web/specs.md index d38544a87..cb16ac107 100644 --- a/web/specs.md +++ b/web/specs.md @@ -212,6 +212,22 @@ Spec: `specs/done_016-user-theme-customization/`. Both the non-UI plumbing and t **Client endpoints:** `Users.updatePreferences` / `Users.resetPreferences` (Layer 2 above); `Users.me()` returns `preferences` embedded (types.ts `User.preferences`) +### Theme marketplace (spec 043) + +Spec: `specs/043-theme-marketplace/`; API contract `contracts/themes-api.md`. Client: `Themes` in `web/src/lib/endpoints.ts`; types in `src/types.ts` (`ThemeCatalogItem`, installed themes, `themeType: "installed"` with `installedThemeId` / `installedTheme` on `UserThemePreferences`). + +**Screens (`router/tree.tsx`, under the app layout):** +- `/settings/theme/catalog` (`routes/ThemeCatalog.tsx`) — any signed-in user. One `Themes.catalog()` fetch; search, source and tag filters run client-side so the filter options stay complete. Cards (`components/themes/ThemeCard.tsx`) offer Preview, Install, Update and Remove for the user's own copy; sources the API reports as failing are listed with their error. +- `/settings/theme/catalog/$id` (`routes/ThemeDetail.tsx`) — both previews, metadata, description and changelog (text only, never HTML; the homepage link only for http(s)), the problems list of an invalid or unverified entry, and the same actions. +- `/settings/theme` (`routes/ThemeSettings.tsx`) — lists the installed themes (select, update, remove; "Source removed" when the API says so) next to the spec 016 presets and custom colors. +- `/settings/theme-sources` (`routes/ThemeSources.tsx`) — admin page behind `RequirePermission` with `themes:manage`: list, add, edit, enable/disable, refresh and delete sources. The built-in `official` source can be disabled and edited but not deleted. The source dialog takes a credential Secret by name (`credentialSecret`), like module sources; it never asks for or shows a credential value. An empty field sends `null` (clears a stored name), a `local` source sends no `credentialSecret`, and an unchanged edit keeps a stored signature policy, including `requireTransparencyLog`. Refresh answers 202 before indexing ends, so the list is polled every 2 seconds until that row shows a new sync result, for a minute at most. The catalog, detail and sources pages show a loading card, and an error card with Retry when the catalog or the installed-themes list fails. + +**Preview (`lib/useThemePreview.ts`, `components/ThemePreviewBanner.tsx`):** a preview applies a catalog or installed theme in memory through `applyThemePreferences` and never writes localStorage or calls the API. It stays on while the user moves between pages (valgul 2026-11-27, as in the design), with the banner mounted in `AppLayout`. It ends on Exit (re-applies the saved preferences from the cache), Keep (installs and selects the theme, or selects the installed copy, then the refetched preferences apply), a reload, or the banner unmounting. In safe mode a preview is refused with a message. Only the latest Preview click starts a preview. A Keep retry after a failed save skips an update that already succeeded. While a preview is active, paths that refresh the saved theme (profile refetch, appearance changes and their rollback, OS appearance changes, leaving Theme settings) re-apply the preview instead (`applySavedThemeOrPreview`); Theme settings keeps it on screen until the draft is edited or reset, which ends it. In Theme settings every base change (another pick, reset, import, removal) bumps a revision, so a slow fetch or update for an earlier pick is dropped. + +**Installed theme render order (`lib/useThemePreferences.ts`):** with `themeType: "installed"`, the theme's tokens for the resolved mode go into `#gameplane-custom-theme-vars` under `html[data-theme-type="installed"][data-theme]` (beats every preset block), then the theme's own sanitized CSS in `#gameplane-installed-theme-css`, then the user's custom CSS overlay `#gameplane-custom-css` last, so the user's overlay still wins. A theme with tokens for one mode only pins the page to that mode. Server tokens pass `normalizeInstalledRender` before they reach the DOM. The pre-paint boot script in `index.html` does not render installed themes; they apply once the app loads the cached or fetched preferences. + +**Safe mode and unauthenticated views:** safe mode (`?safe-mode=1`, or the `gameplane-safe-mode` session flag) suspends the installed theme as well as the overlay and renders Modern Pink, so Settings → Theme stays reachable. Entering safe mode ends any active preview, re-applies the saved preferences and unmounts the overlay; stored preferences, the stored stylesheet and localStorage are kept. When the keyboard shortcut cannot write the session flag, safe mode is kept in memory for the page load (`markSafeModeActiveInMemory`). `enforceUnauthenticatedTheme()` also strips `#gameplane-installed-theme-css` on `/login` and `/share/*`. The spec 016 export records an installed theme as `{source, name, version}` only; importing it where that theme is not installed falls back to Modern Pink with a notice (`lib/theme-export.ts`). + ### Test Count Rule (FR-010) Each rewritten test file must maintain or exceed the original test count: diff --git a/web/src/components/AppLayout.tsx b/web/src/components/AppLayout.tsx index 8b3c0d769..5c86c38f8 100644 --- a/web/src/components/AppLayout.tsx +++ b/web/src/components/AppLayout.tsx @@ -30,11 +30,15 @@ import { applyThemePreferences, DEFAULT_THEME_PREFERENCES, isSafeModeActive, + markSafeModeActiveInMemory, + readThemePreferences, SAFE_MODE_SESSION_KEY, unmountCustomCssOverlay, useThemePreferences, } from "@/lib/useThemePreferences"; +import { exitThemePreview } from "@/lib/useThemePreview"; import { SafeModeBanner } from "@/components/ui/SafeModeBanner"; +import { ThemePreviewBanner } from "@/components/ThemePreviewBanner"; import { TelemetryNotice } from "@/components/ui/TelemetryNotice"; import { useOptionalIntl } from "@/lib/i18n/format"; @@ -129,7 +133,9 @@ export function AppLayout() { try { window.sessionStorage.setItem(SAFE_MODE_SESSION_KEY, "1"); } catch { - // sessionStorage blocked — safe mode still applies for this view. + // sessionStorage blocked: keep safe mode in memory for this page load, + // so the theme renderer and the preview guard see it too. + markSafeModeActiveInMemory(); } setSafeMode(true); }; @@ -137,11 +143,16 @@ export function AppLayout() { return () => window.removeEventListener("keydown", onKeyDown); }, []); - // Suspension is overlay-only: unmountCustomCssOverlay flips - // data-custom-css="off" and removes the mounted