diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 7731a64d2..9c4409a28 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -1940,8 +1940,8 @@ jobs: # wide; the api buckets stay within the login limiter's budget). # The arm64 job below uses the same steps/settings except for the # wake-hostport, network-isolation, management-placement, - # backup-preparation, backup-archives, monitoring, recovery and standalone drills, which run once on amd64. - bucket: [operator, api-auth, api-roles, api-rbac, api-agent, api-mods, telemetry, optional-components, restricted-workloads, wake-hostport, network-isolation, management-placement, backup-preparation, backup-archives, monitoring, recovery, standalone, sftp] + # backup-preparation, backup-archives, monitoring, recovery and standalone drills and the sftp and themes buckets, which run once on amd64. + bucket: [operator, api-auth, api-roles, api-rbac, api-agent, api-mods, telemetry, optional-components, restricted-workloads, wake-hostport, network-isolation, management-placement, backup-preparation, backup-archives, monitoring, recovery, standalone, sftp, themes] arch: [amd64] include: - bucket: monitoring @@ -2007,8 +2007,8 @@ jobs: job_timeout: 60 # Boots kind, loads images and installs the chart before the bounded recovery drill. - bucket: standalone parallel: 1 - test_timeout: 20m # panel-only Helm release, remote registration, kubeconfig swap, restart and removal - job_timeout: 60 # Boots kind, loads images and installs the chart before the standalone panel drill. + test_timeout: 30m # panel-only Helm release, remote registration, kubeconfig swap, restart and removal; then a second panel-only release for theme sources (spec 043) + job_timeout: 75 # Boots kind, loads images and installs the chart before the standalone panel drills. - bucket: restricted-workloads parallel: 1 test_timeout: 25m # Includes real projected-token rotation and node capture cleanup. @@ -2017,6 +2017,10 @@ jobs: parallel: 1 test_timeout: 20m # chart enable, SFTP login, 32 MiB round trip, stopped-server and revocation checks job_timeout: 60 # Boots a kind cluster, installs the chart, runs the bucket's suite. + - bucket: themes + parallel: 1 + test_timeout: 20m # theme pushes and cosign signing, source verify, install, update, disable and delete (spec 043) + job_timeout: 60 # Boots a kind cluster, installs the chart, runs the bucket's suite. env: CLUSTER: gameplane-e2e CTX: kind-gameplane-e2e @@ -2089,7 +2093,7 @@ jobs: uses: ./.github/actions/dump-cluster-state with: context: ${{ env.CTX }} - namespaces: "${{ matrix.bucket == 'monitoring' && 'gameplane-system,gameplane-games,monitoring' || matrix.bucket == 'standalone' && 'gameplane-system,gameplane-games,e2e-standalone-panel' || 'gameplane-system,gameplane-games' }}" + namespaces: "${{ matrix.bucket == 'monitoring' && 'gameplane-system,gameplane-games,monitoring' || matrix.bucket == 'standalone' && 'gameplane-system,gameplane-games,e2e-standalone-panel,e2e-standalone-themes' || 'gameplane-system,gameplane-games' }}" include-previous-logs: "true" e2e-go-arm64: @@ -2950,7 +2954,7 @@ jobs: 'go-e2e-unit': (n) => n === 'go (test/e2e)', 'api-postgres': (n) => n === 'api (postgres)', 'e2e-buckets': (n) => n === 'e2e bucket coverage', - 'e2e-go': (n) => /^e2e (operator|api-auth|api-roles|api-rbac|api-agent|api-mods|telemetry|optional-components|restricted-workloads|wake-hostport|network-isolation|management-placement|backup-preparation|backup-archives|monitoring|recovery|standalone|sftp) \//.test(n) && n.includes('/ amd64 '), + 'e2e-go': (n) => /^e2e (operator|api-auth|api-roles|api-rbac|api-agent|api-mods|telemetry|optional-components|restricted-workloads|wake-hostport|network-isolation|management-placement|backup-preparation|backup-archives|monitoring|recovery|standalone|sftp|themes) \//.test(n) && n.includes('/ amd64 '), 'e2e-go-arm64': (n) => /^e2e (operator|api-auth|api-roles|api-rbac|api-agent|api-mods|telemetry|optional-components|restricted-workloads) \//.test(n) && n.includes('/ arm64 '), 'e2e-multicluster': (n) => n.startsWith('e2e multicluster /') && n.includes('/ amd64 '), 'e2e-multicluster-arm64': (n) => n.startsWith('e2e multicluster /') && n.includes('/ arm64 '), @@ -3103,8 +3107,8 @@ jobs: const bucketSet = new Set(); for (const j of apiJobs) { const n = j.name || ''; - const m = n.match(/^e2e (operator|api-auth|api-roles|api-rbac|api-agent|api-mods|telemetry|optional-components|restricted-workloads|wake-hostport|network-isolation|management-placement|backup-preparation|backup-archives|monitoring|recovery|standalone|sftp) \//); - const executionGated = m && ['wake-hostport', 'recovery', 'standalone'].includes(m[1]); + const m = n.match(/^e2e (operator|api-auth|api-roles|api-rbac|api-agent|api-mods|telemetry|optional-components|restricted-workloads|wake-hostport|network-isolation|management-placement|backup-preparation|backup-archives|monitoring|recovery|standalone|sftp|themes) \//); + const executionGated = m && ['wake-hostport', 'recovery', 'standalone', 'themes'].includes(m[1]); if (m && !executionGated) bucketSet.add(m[1]); // Partial selection can complete these legs without running // their drills. Count completed execution, including failure. diff --git a/AGENTS.md b/AGENTS.md index 453131449..fa9f1ca1a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -64,7 +64,7 @@ After cloning: `git submodule update --init modules` (required for `make dev-up` - **Build:** `make build` (all Go + web), `make build-go` (13 modules in GO_MODULES, all but test/e2e), `make build-web` (`npm ci && npm run build`), `make images`. - **Codegen:** `make generate` (deepcopy), `make manifests` (CRD/RBAC YAML, synced to `charts/gameplane/charts/gameplane-crds/crds/` and `charts/gameplane/crd-manifests/`), `make modules-push`, `make tidy`. - **Dev containers:** `make devcontainers` (regenerate every profile and the `website/` and `modules/` copies after editing `.devcontainer/versions.toml`, `.devcontainer/profiles.toml`, `.devcontainer/devcontainer-lock.json`, `.devcontainer/setup.sh` or a `system-deps.toml`), `make check-devcontainers` (drift check). Profile table: `docs/contributing.md`. -- **Tests (CI only — never run locally, see Rule 8):** `make test`, `make test-integration` (envtest operator+api), `make test-e2e` (~10–20 min), `make test-e2e-bucket BUCKET=(operator|api-auth|api-roles|api-rbac|api-agent|api-mods|ratelimit|bot-fast|bot-heavy|multicluster|upgrade|postgres-availability|postgres-pitr|postgres-ha|telemetry|capture-overhead|optional-components|restricted-workloads|wake-hostport|network-isolation|management-placement|backup-preparation|backup-archives|monitoring|recovery|standalone|sftp)`. +- **Tests (CI only — never run locally, see Rule 8):** `make test`, `make test-integration` (envtest operator+api), `make test-e2e` (~10–20 min), `make test-e2e-bucket BUCKET=(operator|api-auth|api-roles|api-rbac|api-agent|api-mods|ratelimit|bot-fast|bot-heavy|multicluster|upgrade|postgres-availability|postgres-pitr|postgres-ha|telemetry|capture-overhead|optional-components|restricted-workloads|wake-hostport|network-isolation|management-placement|backup-preparation|backup-archives|monitoring|recovery|standalone|sftp|themes)`. - **E2E conventions:** register new tests in `test/e2e/buckets.sh`; `t.Parallel()` + unique names; guard shared resources (`ociPushMu` for module pushes, `ensureResticRepo(t)` for shared backup repos). Rate limits per cluster: IP burst 10 (5/min), user burst 6 (3/min) — cap an API bucket at ~7 admin logins. - **Lint:** `make lint` runs `check-doc-versions`, `check-links`, `check-features-sync`, `check-specs`, `check-telemetry-catalog`, `check-i18n`, `check-dev-load-images`, `check-coverage-gaps`, `check-devcontainers`, `test-up-registry`, `lint-go` and `lint-web`. diff --git a/api/specs.md b/api/specs.md index a3fb5d129..3095ec703 100644 --- a/api/specs.md +++ b/api/specs.md @@ -64,6 +64,7 @@ api/ │ ├── steam/ # Steam Workshop ID resolver: cache + singleflight-deduped upstream lookups │ ├── scope/ # namespace + cluster resolution from request context │ ├── telemetry/ # optional anonymous usage metrics collection +│ ├── themes/ # theme marketplace (spec 043): theme sources, indexer, install/update/remove │ ├── messages/ # localizable error registry (ids, English ICU, status) │ ├── httperr/ # error -> HTTP status classification (safe message for client, full error logged) │ └── [test files] @@ -83,6 +84,7 @@ api/ - **registry:** provider types (each implements Search, Details, Manifest, Download), Set (versioned provider pool with key fallback) - **scope:** ResolveNamespace (extract from path or default), ResolveCluster (validate `?cluster=` against registry) - **httperr:** classify error type to safe HTTP status + message; preserve full error server-side +- **themes:** `Service` for theme sources (create/update/delete/refresh, official source seed), the catalog indexer and its scheduler, and per-user install/update/remove (spec 043; see "Theme marketplace" below) - **telemetry:** destination resolution (`ResolveDestination`), consent, report collection and preview (`BuildReport`), the scheduled reporter (Ed25519 signing, proof-of-work solving, install-ID rotation on `409 id_claimed`) ## External interface / contracts @@ -194,6 +196,9 @@ Both stats and fleet inventory emit `storageCapacitySource` (`node-ephemeral` or - `/users/me/servers` — GET: own GameServers (owner/collaborator) - `/users/me/preferences` — GET/PUT: own theme/styling preferences (feature 016) - `/users/me/preferences/reset` — POST: reset own theme preferences to defaults (feature 016) +- `/users/me/themes`, `/users/me/themes/{id}`, `/users/me/themes/{id}/update` — own installed themes (spec 043, see "Theme marketplace") +- `/themes/catalog`, `/themes/catalog/{id}`, `/themes/catalog/{id}/preview/{light|dark}` — GET: theme catalog, any signed-in user (spec 043) +- `/themes/sources`, `/themes/sources/{name}`, `/themes/sources/{name}/refresh` — theme source admin, `themes:manage` (spec 043) - `/users/me/language` — PUT: set or clear own language choice (spec 019; see below) - `/users` — GET, POST: list and create users - `/users/{id}` — PATCH, DELETE: manage users (admin only). DELETE runs `db.Store.DeleteUser`: one transaction deletes the user's `oidc_links`, `user_preferences`, `sessions`, `api_tokens` and role bindings, revokes the share links the user created (sets `revoked_at`), then deletes the `users` row. It does not rely on FK cascades (off on SQLite). An SSO subject whose user was deleted is provisioned as a new user on its next login @@ -663,7 +668,7 @@ Verify from `/api/go.mod`. - Runtime SQL is written once with `?` placeholders; the Postgres connector rewrites them to `$n` (`db.Rebind`). Timestamps that used SQLite's `datetime('now')` are generated in Go (`db.NowTimestamp()`, same `YYYY-MM-DD HH:MM:SS` UTC text) and bound as parameters; inserted ids come from `RETURNING id` (pgx has no `LastInsertId`) - Postgres legacy migrations declare the text columns the API sorts or range-compares (`roles.name`, role-binding scope columns, `audit_events.ts`, `sessions.expires_at`, `share_links.created_at`/`expires_at`) `COLLATE "C"` so ordering matches SQLite's byte-wise collation -### Schema (migrations 001-014 detailed here; 015-027 in `migrations/common/`) +### Schema (migrations 001-014 detailed here; 015-028 in `migrations/common/`; 028 is described under "Theme marketplace") **001_init.sql:** - `users` — username (unique), email, display_name, pw_hash (argon2id), role (legacy, now via role_bindings), created_at, updated_at diff --git a/hack/ci_scope.py b/hack/ci_scope.py index 928400f1d..6f352fb72 100644 --- a/hack/ci_scope.py +++ b/hack/ci_scope.py @@ -29,8 +29,8 @@ FORCE_ALL_PREFIXES = (".github/actions/",) # Mirrors the e2e-go matrix buckets in .github/workflows/ci.yaml. E2E_BUCKETS = ["operator", "api-auth", "api-roles", "api-rbac", "api-agent", "api-mods", - "telemetry", "optional-components", "restricted-workloads", "wake-hostport", "network-isolation", "management-placement", "backup-preparation", "backup-archives", "monitoring", "recovery", "standalone", "sftp"] -E2E_AMD64_ONLY = {"wake-hostport", "network-isolation", "management-placement", "backup-preparation", "backup-archives", "monitoring", "recovery", "standalone", "sftp"} + "telemetry", "optional-components", "restricted-workloads", "wake-hostport", "network-isolation", "management-placement", "backup-preparation", "backup-archives", "monitoring", "recovery", "standalone", "sftp", "themes"] +E2E_AMD64_ONLY = {"wake-hostport", "network-isolation", "management-placement", "backup-preparation", "backup-archives", "monitoring", "recovery", "standalone", "sftp", "themes"} SUITES_FILE = "test/e2e/suite-components.json" # Paths no Go e2e test reads. Their own jobs keep their paths-filter gates. NO_E2E_FILES = { diff --git a/hack/test_ci_scope.py b/hack/test_ci_scope.py index dd4398ce8..c35770bcb 100644 --- a/hack/test_ci_scope.py +++ b/hack/test_ci_scope.py @@ -429,6 +429,21 @@ def test_recovery_inputs_select_the_recovery_drill(self): self.assertIn("TestPanel_OfflineRecovery", self.select(path)["e2e-run"].get("recovery", "")) + def test_theme_inputs_select_the_themes_bucket(self): + """Theme service, handler, shared fetch and package code select the spec 043 e2e tests.""" + for path in ("api/internal/themes/indexer.go", + "api/internal/handlers/themes_catalog.go", + "bundlefetch/oci/client.go", + "themepkg/package.go", + "test/e2e/api_themes_e2e_test.go", + "test/e2e/fixtures/theme-oras-push-job.yaml"): + with self.subTest(path=path): + values = self.select(path) + self.assertIn("TestAPI_ThemeMarketplaceLifecycle", + values["e2e-run"].get("themes", "")) + self.assertIn("TestStandalone_ThemeSourceInstall", + values["e2e-run"].get("standalone", "")) + def test_audit_network_isolation_has_a_run_pattern(self): """Affected components and the owning test file select the audit bucket.""" for path in ("operator/internal/controller/gameserver_controller.go", diff --git a/specs/043-theme-marketplace/tasks.md b/specs/043-theme-marketplace/tasks.md index becb52a3f..bfff95b80 100644 --- a/specs/043-theme-marketplace/tasks.md +++ b/specs/043-theme-marketplace/tasks.md @@ -159,8 +159,8 @@ ## Phase 8: E2E, docs and changelog (PR-G) -- [ ] 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). +- [X] 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). Done: `test/e2e/api_themes_e2e_test.go` (`TestAPI_ThemeMarketplaceLifecycle`, 3 logins), fixtures `test/e2e/fixtures/theme-oras-push{,-v2}-job.yaml` and `theme-cosign-sign{,-v2}-job.yaml`, bucket `themes` in `test/e2e/buckets.sh`, wired in `.github/workflows/ci.yaml` (amd64), `hack/ci_scope.py` and `test/e2e/suite-components.json`. +- [X] 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). Done in a new file, `test/e2e/standalone_themes_e2e_test.go` (`TestStandalone_ThemeSourceInstall`, bucket `standalone`), because `standalone_panel_e2e_test.go` exists on master; it installs its own panel-only release and uses an OCI source, since the chart has no local theme root setting. - [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/test/e2e/api_themes_e2e_test.go b/test/e2e/api_themes_e2e_test.go new file mode 100644 index 000000000..0d0e2b5fb --- /dev/null +++ b/test/e2e/api_themes_e2e_test.go @@ -0,0 +1,441 @@ +//go:build e2e + +package e2e + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "strconv" + "strings" + "testing" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// Theme marketplace e2e (spec 043). The theme packages are pushed by +// fixtures/theme-oras-push-job.yaml to the in-cluster test registry +// (fixtures/oci-registry.yaml) under this prefix; the API dials it through +// netguard.IsAllowed, which admits in-cluster addresses. +const ( + e2eThemeRegistry = "gameplane-test-registry.gameplane-system.svc:5000/e2e-themes" + e2eThemeSigned = "e2e-theme-signed" + e2eThemeUnsigned = "e2e-theme-unsigned" + // e2eThemeKeypair is the Secret theme-cosign-sign-job.yaml generates. + e2eThemeKeypair = "e2e-theme-sign-keypair" +) + +// e2eThemeCatalogItem is one entry of GET /themes/catalog +// (contracts/themes-api.md, "Catalog"). +type e2eThemeCatalogItem struct { + ID int64 `json:"id"` + Source string `json:"source"` + Name string `json:"name"` + Version string `json:"version"` + Status string `json:"status"` + Installed *struct { + Version string `json:"version"` + } `json:"installed"` + UpdateAvailable bool `json:"updateAvailable"` +} + +// e2eThemeCatalog is the GET /themes/catalog body. +type e2eThemeCatalog struct { + Themes []e2eThemeCatalogItem `json:"themes"` + Sources []struct { + Name string `json:"name"` + LastError string `json:"lastError"` + } `json:"sources"` +} + +// e2eInstalledTheme is one installed theme, as listed by GET /users/me/themes +// and, with tokens and css, returned by GET /users/me/themes/{id}. +type e2eInstalledTheme struct { + ID int64 `json:"id"` + Source string `json:"source"` + Name string `json:"name"` + Version string `json:"version"` + UpdateAvailable bool `json:"updateAvailable"` + SourceRemoved bool `json:"sourceRemoved"` + Selected bool `json:"selected"` + Tokens json.RawMessage `json:"tokens"` +} + +// e2eThemeSelection is the theme part of GET /users/me/preferences. +type e2eThemeSelection struct { + ThemeType string `json:"themeType"` + PresetID string `json:"presetId"` + InstalledThemeID *int64 `json:"installedThemeId"` + InstalledTheme *struct { + Tokens json.RawMessage `json:"tokens"` + Version string `json:"version"` + } `json:"installedTheme"` +} + +// themeCall sends one request and fails the test unless the status is want. +// It returns the response body. +func themeCall(t *testing.T, cli *APIClient, method, path string, body any, want int) []byte { + t.Helper() + resp, data, err := cli.DoContext(t.Context(), method, path, body) + if err != nil { + t.Fatalf("%s %s: %v", method, path, err) + } + // DoContext has read and closed the body already; this satisfies bodyclose. + _ = resp.Body.Close() + if resp.StatusCode != want { + t.Fatalf("%s %s: status=%d want=%d body=%s", method, path, resp.StatusCode, want, string(data)) + } + return data +} + +// themeDecode unmarshals a response body into out or fails the test. +func themeDecode(t *testing.T, data []byte, out any) { + t.Helper() + if err := json.Unmarshal(data, out); err != nil { + t.Fatalf("decode %T: %v\n%s", out, err, string(data)) + } +} + +// themeCatalogOf lists the catalog entries of one source as cli sees them. +func themeCatalogOf(t *testing.T, cli *APIClient, source string) map[string]e2eThemeCatalogItem { + t.Helper() + var cat e2eThemeCatalog + themeDecode(t, themeCall(t, cli, http.MethodGet, "/themes/catalog?source="+source, nil, http.StatusOK), &cat) + out := map[string]e2eThemeCatalogItem{} + for _, e := range cat.Themes { + if e.Source == source { + out[e.Name] = e + } + } + return out +} + +// themeSourceErrors returns the lastError the catalog reports for a source, for +// failure messages while waiting on an index. +func themeSourceErrors(t *testing.T, cli *APIClient, source string) string { + t.Helper() + var cat e2eThemeCatalog + themeDecode(t, themeCall(t, cli, http.MethodGet, "/themes/catalog", nil, http.StatusOK), &cat) + for _, s := range cat.Sources { + if s.Name == source { + return s.LastError + } + } + return "" +} + +// installedThemes lists the caller's installed themes by id. +func installedThemes(t *testing.T, cli *APIClient) map[int64]e2eInstalledTheme { + t.Helper() + var list []e2eInstalledTheme + themeDecode(t, themeCall(t, cli, http.MethodGet, "/users/me/themes", nil, http.StatusOK), &list) + out := map[int64]e2eInstalledTheme{} + for _, it := range list { + out[it.ID] = it + } + return out +} + +// themeSelection reads the caller's theme preferences. +func themeSelection(t *testing.T, cli *APIClient) e2eThemeSelection { + t.Helper() + var sel e2eThemeSelection + themeDecode(t, themeCall(t, cli, http.MethodGet, "/users/me/preferences", nil, http.StatusOK), &sel) + return sel +} + +// ociThemeSourceBody is the POST/PUT /themes/sources body of an OCI source on +// the plain-HTTP test registry. verifyKey, when set, is the cosign public key +// PEM of a keyed signature policy. +func ociThemeSourceBody(name string, themes []string, verifyKey string, enabled bool) map[string]any { + body := map[string]any{ + "name": name, + "type": "oci", + "spec": map[string]any{"oci": map[string]any{ + "url": e2eThemeRegistry, + "themes": themes, + "insecure": true, + }}, + "refreshInterval": 300, + "enabled": enabled, + } + if verifyKey != "" { + body["verify"] = map[string]any{"key": verifyKey} + } + return body +} + +// ensureThemeRegistry applies the shared in-cluster test registry and waits +// until it serves. +func ensureThemeRegistry(t *testing.T) { + t.Helper() + ctx := t.Context() + envInstance.ApplyYAML(t, "oci-registry.yaml") + envInstance.Eventually(t, 90*time.Second, func() (bool, string) { + dep, err := envInstance.K8s.AppsV1().Deployments("gameplane-system"). + Get(ctx, "gameplane-test-registry", metav1.GetOptions{}) + if err != nil { + return false, "get registry deploy: " + err.Error() + } + if dep.Status.ReadyReplicas >= 1 { + return true, "" + } + return false, "registry not ready yet" + }) +} + +// pushE2EThemes pushes e2e-theme-signed:0.1.0 and e2e-theme-unsigned:0.1.0. +// The caller holds ociPushMu. +func pushE2EThemes(t *testing.T) { + t.Helper() + ensureThemeRegistry(t) + envInstance.OCIPushFromFixture(t, "gameplane-system", "e2e-theme-oras-push", "theme-oras-push-job.yaml") +} + +// runThemeSignJob applies a cosign sign Job fixture and waits for it to +// succeed. The caller holds ociPushMu. +func runThemeSignJob(t *testing.T, fixture, job string) { + t.Helper() + ctx := context.Background() + bg := metav1.DeletePropagationBackground + _ = envInstance.K8s.BatchV1().Jobs("gameplane-system"). + Delete(ctx, job, metav1.DeleteOptions{PropagationPolicy: &bg}) + envInstance.ApplyYAML(t, fixture) + t.Cleanup(func() { + _ = envInstance.K8s.BatchV1().Jobs("gameplane-system"). + Delete(context.Background(), job, metav1.DeleteOptions{PropagationPolicy: &bg}) + }) + envInstance.Eventually(t, 2*time.Minute, func() (bool, string) { + j, err := envInstance.K8s.BatchV1().Jobs("gameplane-system").Get(ctx, job, metav1.GetOptions{}) + if err != nil { + return false, "get sign job: " + err.Error() + } + if j.Status.Succeeded > 0 { + return true, "" + } + if j.Status.Failed > 0 { + out, _ := envInstance.Kubectl(ctx, "logs", "-n", "gameplane-system", + "job/"+job, "--all-containers", "--tail=200") + return false, "sign job failed:\n" + out + } + return false, "sign job not done yet" + }) +} + +// signE2ETheme generates a fresh key pair and signs e2e-theme-signed:0.1.0. +// It returns the public key PEM. The caller holds ociPushMu. +func signE2ETheme(t *testing.T) string { + t.Helper() + ctx := context.Background() + // generate-key-pair refuses an existing Secret, so start clean. + _ = envInstance.K8s.CoreV1().Secrets("gameplane-system").Delete(ctx, e2eThemeKeypair, metav1.DeleteOptions{}) + t.Cleanup(func() { + _ = envInstance.K8s.CoreV1().Secrets("gameplane-system"). + Delete(context.Background(), e2eThemeKeypair, metav1.DeleteOptions{}) + }) + runThemeSignJob(t, "theme-cosign-sign-job.yaml", "e2e-theme-cosign-sign") + sec, err := envInstance.K8s.CoreV1().Secrets("gameplane-system").Get(ctx, e2eThemeKeypair, metav1.GetOptions{}) + if err != nil { + t.Fatalf("get theme signing key pair: %v", err) + } + pub := strings.TrimSpace(string(sec.Data["cosign.pub"])) + if !strings.Contains(pub, "PUBLIC KEY") { + t.Fatalf("Secret %s has no PEM cosign.pub", e2eThemeKeypair) + } + return pub +} + +// TestAPI_ThemeMarketplaceLifecycle drives the theme marketplace API (spec +// 043, contracts/themes-api.md) against a real registry: a signed and an +// unsigned theme are pushed to the in-cluster test registry, an admin adds an +// insecure OCI source, the catalog lists both, and a keyed verify policy turns +// the unsigned one unverified (not installable). User A installs and selects +// the signed theme, user B's preferences and installed list stay untouched, a +// newer signed version is pushed and A updates to it. Disabling the source +// keeps A's installed copy rendering (sourceRemoved), deleting the source keeps +// it too, and removing it falls A back to Modern Pink (FR-011, FR-013). +// +// Budget: three logins (e2e-admin, user A, user B); see the themes bucket in +// buckets.sh. t.Parallel(): the source and users have unique names; the +// registry pushes and the cosign Jobs run under ociPushMu. +func TestAPI_ThemeMarketplaceLifecycle(t *testing.T) { + t.Parallel() + suffix := strconv.FormatInt(time.Now().UnixNano(), 36) + sourceName := "e2e-themes-" + suffix + + var pubKey string + func() { + ociPushMu.Lock() + defer ociPushMu.Unlock() + pushE2EThemes(t) + pubKey = signE2ETheme(t) + }() + + envInstance.BootstrapAdmin(t, adminUsername, adminPassword) + admin := envInstance.APIClient(t, adminUsername, adminPassword) + // Registered first so it runs last, after the cleanups that use admin. + t.Cleanup(admin.Close) + + userA, passA, idA := envInstance.CreateUser(t, admin, "viewer", "e2e-themes-a") + userB, passB, idB := envInstance.CreateUser(t, admin, "viewer", "e2e-themes-b") + for _, id := range []string{idA, idB} { + t.Cleanup(func() { + r, _, _ := admin.Delete("/users/" + id) + if r != nil { + _ = r.Body.Close() + } + }) + } + t.Cleanup(func() { + r, _, _ := admin.Delete("/themes/sources/" + sourceName) + if r != nil { + _ = r.Body.Close() + } + }) + + themes := []string{e2eThemeSigned, e2eThemeUnsigned} + + // Add the source without a signature policy: both themes index as valid. + var created struct { + Name string `json:"name"` + Builtin bool `json:"builtin"` + CredentialSecret *string `json:"credentialSecret"` + } + themeDecode(t, themeCall(t, admin, http.MethodPost, "/themes/sources", + ociThemeSourceBody(sourceName, themes, "", true), http.StatusCreated), &created) + if created.Name != sourceName || created.Builtin || created.CredentialSecret != nil { + t.Fatalf("created source = %+v, want %s, not built in, no credential Secret", created, sourceName) + } + + a := envInstance.APIClient(t, userA, passA) + defer a.Close() + + envInstance.Eventually(t, 2*time.Minute, func() (bool, string) { + cat := themeCatalogOf(t, a, sourceName) + for _, name := range themes { + e, ok := cat[name] + if !ok || e.Status != "valid" || e.Version != "0.1.0" { + return false, fmt.Sprintf("catalog %v (source error %q)", cat, themeSourceErrors(t, admin, sourceName)) + } + } + return true, "" + }) + + // Keyed verify with the signing public key: the unsigned theme is flagged. + themeCall(t, admin, http.MethodPut, "/themes/sources/"+sourceName, + ociThemeSourceBody(sourceName, themes, pubKey, true), http.StatusOK) + var catalog map[string]e2eThemeCatalogItem + envInstance.Eventually(t, 2*time.Minute, func() (bool, string) { + catalog = themeCatalogOf(t, a, sourceName) + if catalog[e2eThemeSigned].Status != "valid" || catalog[e2eThemeUnsigned].Status != "unverified" { + return false, fmt.Sprintf("want signed valid and unsigned unverified, catalog %v (source error %q)", + catalog, themeSourceErrors(t, admin, sourceName)) + } + return true, "" + }) + // Error ids travel in the problem+json body, so ask for it. + if status, id, _ := ssoRulesProblem(t, a, http.MethodPost, "/users/me/themes", + map[string]any{"catalogId": catalog[e2eThemeUnsigned].ID}); status != http.StatusUnprocessableEntity || id != "server.themes.entry_not_valid" { + t.Errorf("install of the unverified theme: got %d %s, want 422 server.themes.entry_not_valid", status, id) + } + + // User A installs and selects the signed theme. + var installed e2eInstalledTheme + themeDecode(t, themeCall(t, a, http.MethodPost, "/users/me/themes", + map[string]any{"catalogId": catalog[e2eThemeSigned].ID, "select": true}, http.StatusCreated), &installed) + if installed.Name != e2eThemeSigned || installed.Version != "0.1.0" || !installed.Selected || installed.SourceRemoved { + t.Fatalf("installed = %+v, want %s 0.1.0, selected", installed, e2eThemeSigned) + } + themeID := strconv.FormatInt(installed.ID, 10) + selA := themeSelection(t, a) + if selA.ThemeType != "installed" || selA.InstalledThemeID == nil || *selA.InstalledThemeID != installed.ID || + selA.InstalledTheme == nil || selA.InstalledTheme.Version != "0.1.0" { + t.Fatalf("user A preferences = %+v, want installed theme %d at 0.1.0", selA, installed.ID) + } + themeCall(t, a, http.MethodPost, "/users/me/themes", + map[string]any{"catalogId": catalog[e2eThemeSigned].ID}, http.StatusConflict) + + // User B is unaffected: no installed copy, preset preferences, and A's id + // is not reachable. + b := envInstance.APIClient(t, userB, passB) + defer b.Close() + if got := installedThemes(t, b); len(got) != 0 { + t.Fatalf("user B installed themes = %v, want none", got) + } + if selB := themeSelection(t, b); selB.ThemeType == "installed" || selB.InstalledThemeID != nil { + t.Fatalf("user B preferences = %+v, want no installed theme", selB) + } + themeCall(t, b, http.MethodGet, "/users/me/themes/"+themeID, nil, http.StatusNotFound) + themeCall(t, a, http.MethodPost, "/users/me/themes/"+themeID+"/update", nil, http.StatusConflict) + + // Update: push and sign 0.2.0, refresh, and move A's copy to it. + func() { + ociPushMu.Lock() + defer ociPushMu.Unlock() + envInstance.OCIPushFromFixture(t, "gameplane-system", "e2e-theme-oras-push-v2", "theme-oras-push-v2-job.yaml") + runThemeSignJob(t, "theme-cosign-sign-v2-job.yaml", "e2e-theme-cosign-sign-v2") + }() + themeCall(t, admin, http.MethodPost, "/themes/sources/"+sourceName+"/refresh", nil, http.StatusAccepted) + envInstance.Eventually(t, 2*time.Minute, func() (bool, string) { + got := installedThemes(t, a)[installed.ID] + if !got.UpdateAvailable { + return false, fmt.Sprintf("installed %+v has no update yet (catalog %v)", got, themeCatalogOf(t, a, sourceName)) + } + return true, "" + }) + var updated e2eInstalledTheme + themeDecode(t, themeCall(t, a, http.MethodPost, "/users/me/themes/"+themeID+"/update", nil, http.StatusOK), &updated) + if updated.ID != installed.ID || updated.Version != "0.2.0" || updated.UpdateAvailable || !updated.Selected { + t.Fatalf("updated = %+v, want the same id at 0.2.0, selected, no further update", updated) + } + if sel := themeSelection(t, a); sel.InstalledTheme == nil || sel.InstalledTheme.Version != "0.2.0" { + t.Fatalf("user A preferences after update = %+v, want installed theme at 0.2.0", sel) + } + if got := installedThemes(t, b); len(got) != 0 { + t.Fatalf("user B installed themes after A's update = %v, want none", got) + } + + // Disable the source: its entries leave the catalog, A's copy still renders. + themeCall(t, admin, http.MethodPut, "/themes/sources/"+sourceName, + ociThemeSourceBody(sourceName, themes, pubKey, false), http.StatusOK) + if cat := themeCatalogOf(t, a, sourceName); len(cat) != 0 { + t.Fatalf("catalog of the disabled source = %v, want empty", cat) + } + requireRendersSourceRemoved(t, a, themeID, "0.2.0") + if status, id, _ := ssoRulesProblem(t, a, http.MethodPost, "/users/me/themes/"+themeID+"/update", nil); status != http.StatusConflict || id != "server.themes.source_disabled" { + t.Errorf("update with the source disabled: got %d %s, want 409 server.themes.source_disabled", status, id) + } + + // Delete the source: the installed copy stays, marked sourceRemoved. + themeCall(t, admin, http.MethodDelete, "/themes/sources/"+sourceName, nil, http.StatusNoContent) + requireRendersSourceRemoved(t, a, themeID, "0.2.0") + if status, id, _ := ssoRulesProblem(t, a, http.MethodPost, "/users/me/themes/"+themeID+"/update", nil); status != http.StatusConflict || id != "server.themes.source_removed" { + t.Errorf("update with the source deleted: got %d %s, want 409 server.themes.source_removed", status, id) + } + if sel := themeSelection(t, a); sel.ThemeType != "installed" { + t.Fatalf("user A preferences after source delete = %+v, want the installed theme still selected", sel) + } + + // Remove the installed copy: A falls back to Modern Pink. + themeCall(t, a, http.MethodDelete, "/users/me/themes/"+themeID, nil, http.StatusNoContent) + if sel := themeSelection(t, a); sel.ThemeType != "preset" || sel.PresetID != "pink" || sel.InstalledThemeID != nil { + t.Fatalf("user A preferences after removal = %+v, want preset pink", sel) + } + if got := installedThemes(t, a); len(got) != 0 { + t.Fatalf("user A installed themes after removal = %v, want none", got) + } +} + +// requireRendersSourceRemoved asserts that GET /users/me/themes/{id} still +// returns the installed copy at version, with its tokens, marked sourceRemoved. +func requireRendersSourceRemoved(t *testing.T, cli *APIClient, id, version string) { + t.Helper() + var got e2eInstalledTheme + themeDecode(t, themeCall(t, cli, http.MethodGet, "/users/me/themes/"+id, nil, http.StatusOK), &got) + if got.Version != version || !got.SourceRemoved || !strings.Contains(string(got.Tokens), "accent") { + t.Fatalf("installed theme %s = %+v (tokens %s), want version %s, sourceRemoved, tokens kept", + id, got, got.Tokens, version) + } +} diff --git a/test/e2e/buckets.sh b/test/e2e/buckets.sh index 928344ff7..f69e5b4ce 100755 --- a/test/e2e/buckets.sh +++ b/test/e2e/buckets.sh @@ -541,9 +541,13 @@ bucket_network_isolation() { # installs the chart's panel-only profile as a second Helm release in the fixed # namespace e2e-standalone-panel and registers this Kind cluster as its remote. # Zero shared panel logins; the standalone panel has its own login limiter -# (3 logins). +# (3 logins). TestStandalone_ThemeSourceInstall (spec 043) installs a second +# panel-only release e2e-standalone-themes in its own namespace, pushes theme +# packages to the in-cluster test registry and signs in once against that +# panel's own limiter. bucket_standalone() { cat <<'EOF' TestStandalone_HelmPanelLifecycle +TestStandalone_ThemeSourceInstall EOF } @@ -556,8 +560,17 @@ TestSFTP_Lifecycle EOF } +# themes (spec 043): theme marketplace against the in-cluster test registry. +# Its own cluster, so the theme pushes and cosign Jobs never wait on module +# tests. Login tally: TestAPI_ThemeMarketplaceLifecycle = 3 (e2e-admin, user A, +# user B), bucket total 3 of the ~7 ceiling. amd64 only, like sftp. +bucket_themes() { cat <<'EOF' +TestAPI_ThemeMarketplaceLifecycle +EOF +} + bucket_names() { - printf '%s\n' operator api-auth api-roles api-rbac api-agent api-mods ratelimit bot-fast bot-heavy multicluster upgrade postgres-availability postgres-pitr postgres-ha telemetry capture-overhead optional-components restricted-workloads wake-hostport network-isolation management-placement backup-preparation backup-archives monitoring recovery standalone sftp + printf '%s\n' operator api-auth api-roles api-rbac api-agent api-mods ratelimit bot-fast bot-heavy multicluster upgrade postgres-availability postgres-pitr postgres-ha telemetry capture-overhead optional-components restricted-workloads wake-hostport network-isolation management-placement backup-preparation backup-archives monitoring recovery standalone sftp themes } list_bucket() { @@ -588,6 +601,7 @@ list_bucket() { recovery) bucket_recovery ;; standalone) bucket_standalone ;; sftp) bucket_sftp ;; + themes) bucket_themes ;; monitoring) bucket_monitoring ;; *) echo "unknown bucket: $1 (known: $(bucket_names | tr '\n' ' '))" >&2 diff --git a/test/e2e/fixtures/theme-cosign-sign-job.yaml b/test/e2e/fixtures/theme-cosign-sign-job.yaml new file mode 100644 index 000000000..aec961c78 --- /dev/null +++ b/test/e2e/fixtures/theme-cosign-sign-job.yaml @@ -0,0 +1,101 @@ +# Signs the e2e theme e2e-theme-signed:0.1.0 in the in-cluster test registry +# for TestAPI_ThemeMarketplaceLifecycle (spec 043). Same pattern as +# cosign-sign-job.yaml, with its own names so it never touches the module +# test's keypair Secret or Job: the init container generates an ECDSA key pair +# into the Secret gameplane-system/e2e-theme-sign-keypair (cosign.key, +# cosign.pub, cosign.password), and the main container signs keyed and offline. +# The test reads cosign.pub from that Secret and sets it as the theme source's +# verify key. e2e-theme-unsigned is never signed. +# +# backoffLimit 0 / restartPolicy Never: one pod attempt, so generate-key-pair +# never races a Secret it already created. The test deletes this Job and the +# keypair Secret before each apply. +apiVersion: v1 +kind: ServiceAccount +metadata: + name: e2e-theme-cosign-signer + namespace: gameplane-system + labels: + app.kubernetes.io/component: e2e-fixture +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: e2e-theme-cosign-signer + namespace: gameplane-system + labels: + app.kubernetes.io/component: e2e-fixture +rules: + # generate-key-pair k8s://... creates the keypair Secret; signing reads it. + - apiGroups: [""] + resources: [secrets] + verbs: [get, list, create, update, patch, delete] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: e2e-theme-cosign-signer + namespace: gameplane-system + labels: + app.kubernetes.io/component: e2e-fixture +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: e2e-theme-cosign-signer +subjects: + - kind: ServiceAccount + name: e2e-theme-cosign-signer + namespace: gameplane-system +--- +apiVersion: batch/v1 +kind: Job +metadata: + name: e2e-theme-cosign-sign + namespace: gameplane-system + labels: + app.kubernetes.io/component: e2e-fixture +spec: + backoffLimit: 0 + template: + metadata: + labels: + app.kubernetes.io/component: e2e-fixture + spec: + restartPolicy: Never + serviceAccountName: e2e-theme-cosign-signer + initContainers: + - name: keygen + image: ghcr.io/sigstore/cosign/cosign:v3.1.2 + args: + - generate-key-pair + - k8s://gameplane-system/e2e-theme-sign-keypair + env: + - { name: COSIGN_PASSWORD, value: "e2e-pass" } + - { name: COSIGN_YES, value: "true" } + - { name: HOME, value: /tmp } + volumeMounts: + - { name: tmp, mountPath: /tmp } + containers: + - name: sign + image: ghcr.io/sigstore/cosign/cosign:v3.1.2 + args: + - sign + - --key=k8s://gameplane-system/e2e-theme-sign-keypair + # Same flags as cosign-sign-job.yaml (classic .sig, no tlog, plain + # HTTP registry); see that file for why each one is needed. + - --new-bundle-format=false + - --use-signing-config=false + - --tlog-upload=false + - --allow-http-registry + - --allow-insecure-registry + - --yes + - gameplane-test-registry.gameplane-system.svc:5000/e2e-themes/e2e-theme-signed:0.1.0 + env: + - { name: COSIGN_PASSWORD, value: "e2e-pass" } + - { name: COSIGN_YES, value: "true" } + - { name: HOME, value: /tmp } + volumeMounts: + - { name: tmp, mountPath: /tmp } + volumes: + - name: tmp + emptyDir: {} diff --git a/test/e2e/fixtures/theme-cosign-sign-v2-job.yaml b/test/e2e/fixtures/theme-cosign-sign-v2-job.yaml new file mode 100644 index 000000000..0b7fcb750 --- /dev/null +++ b/test/e2e/fixtures/theme-cosign-sign-v2-job.yaml @@ -0,0 +1,43 @@ +# Signs e2e-theme-signed:0.2.0 with the key pair theme-cosign-sign-job.yaml +# generated (Secret gameplane-system/e2e-theme-sign-keypair), for the update +# step of TestAPI_ThemeMarketplaceLifecycle. Uses that file's ServiceAccount. +apiVersion: batch/v1 +kind: Job +metadata: + name: e2e-theme-cosign-sign-v2 + namespace: gameplane-system + labels: + app.kubernetes.io/component: e2e-fixture +spec: + backoffLimit: 0 + template: + metadata: + labels: + app.kubernetes.io/component: e2e-fixture + spec: + restartPolicy: Never + serviceAccountName: e2e-theme-cosign-signer + containers: + - name: sign + image: ghcr.io/sigstore/cosign/cosign:v3.1.2 + args: + - sign + - --key=k8s://gameplane-system/e2e-theme-sign-keypair + # Same flags as cosign-sign-job.yaml (classic .sig, no tlog, plain + # HTTP registry); see that file for why each one is needed. + - --new-bundle-format=false + - --use-signing-config=false + - --tlog-upload=false + - --allow-http-registry + - --allow-insecure-registry + - --yes + - gameplane-test-registry.gameplane-system.svc:5000/e2e-themes/e2e-theme-signed:0.2.0 + env: + - { name: COSIGN_PASSWORD, value: "e2e-pass" } + - { name: COSIGN_YES, value: "true" } + - { name: HOME, value: /tmp } + volumeMounts: + - { name: tmp, mountPath: /tmp } + volumes: + - name: tmp + emptyDir: {} diff --git a/test/e2e/fixtures/theme-oras-push-job.yaml b/test/e2e/fixtures/theme-oras-push-job.yaml new file mode 100644 index 000000000..ace4829e1 --- /dev/null +++ b/test/e2e/fixtures/theme-oras-push-job.yaml @@ -0,0 +1,165 @@ +# Theme packages for the spec 043 e2e tests (TestAPI_ThemeMarketplaceLifecycle, +# TestStandalone_ThemeSourceInstall), pushed to the in-cluster test registry +# (oci-registry.yaml) under gameplane-test-registry.gameplane-system.svc:5000/e2e-themes. +# The layout follows contracts/theme-package.md and `gp-module theme package`: +# artifact type application/vnd.gameplane.theme.v1+json, one layer per file, +# titled with its package path (theme.yaml, previews/dark.png). Each theme has +# dark tokens only, so a dark preview is the one required image. The preview is +# themepkg/testdata/good/previews/dark.png (a 2x2 PNG). +# +# A ConfigMap key cannot hold a "/", so each push Job mounts the keys it needs +# with items that place the preview at previews/dark.png. +apiVersion: v1 +kind: ConfigMap +metadata: + name: e2e-theme-bundles + namespace: gameplane-system + labels: + app.kubernetes.io/component: e2e-fixture +data: + signed-0.1.0.yaml: | + apiVersion: gameplane.local/theme/v1 + name: e2e-theme-signed + version: 0.1.0 + displayName: E2E Signed Theme + author: Gameplane E2E + description: Theme package pushed by the spec 043 e2e tests. + tags: [e2e, dark] + license: MIT + changelog: | + 0.1.0: first release + tokens: + dark: + background: "#0b1220" + foreground: "#e6edf7" + surface: "#111a2e" + surface-secondary: "#16213a" + surface-tertiary: "#1c2946" + overlay: "#0f172a" + accent: "#38bdf8" + accent-foreground: "#04121d" + accent-soft: "#0c2a3d" + accent-soft-foreground: "#a5e3ff" + muted: "#8a9bb8" + border: "#24324f" + focus: "#38bdf8" + link: "#7dd3fc" + signed-0.2.0.yaml: | + apiVersion: gameplane.local/theme/v1 + name: e2e-theme-signed + version: 0.2.0 + displayName: E2E Signed Theme + author: Gameplane E2E + description: Theme package pushed by the spec 043 e2e tests. + tags: [e2e, dark] + license: MIT + changelog: | + 0.2.0: brighter accent + tokens: + dark: + background: "#0b1220" + foreground: "#e6edf7" + surface: "#111a2e" + surface-secondary: "#16213a" + surface-tertiary: "#1c2946" + overlay: "#0f172a" + accent: "#22d3ee" + accent-foreground: "#04121d" + accent-soft: "#0c2a3d" + accent-soft-foreground: "#a5e3ff" + muted: "#8a9bb8" + border: "#24324f" + focus: "#22d3ee" + link: "#7dd3fc" + unsigned-0.1.0.yaml: | + apiVersion: gameplane.local/theme/v1 + name: e2e-theme-unsigned + version: 0.1.0 + displayName: E2E Unsigned Theme + author: Gameplane E2E + description: Theme package pushed by the spec 043 e2e tests. + tags: [e2e, dark] + license: MIT + changelog: | + 0.1.0: first release + tokens: + dark: + background: "#0b1220" + foreground: "#e6edf7" + surface: "#111a2e" + surface-secondary: "#16213a" + surface-tertiary: "#1c2946" + overlay: "#0f172a" + accent: "#38bdf8" + accent-foreground: "#04121d" + accent-soft: "#0c2a3d" + accent-soft-foreground: "#a5e3ff" + muted: "#8a9bb8" + border: "#24324f" + focus: "#38bdf8" + link: "#7dd3fc" +binaryData: + dark.png: iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAG0lEQVR4nGLiFlKw2PuDQVBK79nb74AAAAD//xqpBVBH+2I1AAAAAElFTkSuQmCC +--- +# Pushes e2e-theme-signed:0.1.0 (init container) and e2e-theme-unsigned:0.1.0. +# The test signs only the first (theme-cosign-sign-job.yaml). +apiVersion: batch/v1 +kind: Job +metadata: + name: e2e-theme-oras-push + namespace: gameplane-system + labels: + app.kubernetes.io/component: e2e-fixture +spec: + backoffLimit: 4 + template: + metadata: + labels: + app.kubernetes.io/component: e2e-fixture + spec: + restartPolicy: OnFailure + initContainers: + - name: push-signed + image: ghcr.io/oras-project/oras:v1.3.3 + command: ["oras"] + args: + - push + - --plain-http + - --artifact-type=application/vnd.gameplane.theme.v1+json + - gameplane-test-registry.gameplane-system.svc:5000/e2e-themes/e2e-theme-signed:0.1.0 + - theme.yaml:application/vnd.gameplane.theme.metadata.v1+yaml + - previews/dark.png:image/png + workingDir: /workspace + volumeMounts: + - { name: signed-010, mountPath: /workspace } + - { name: tmp, mountPath: /tmp } + containers: + - name: push-unsigned + image: ghcr.io/oras-project/oras:v1.3.3 + command: ["oras"] + args: + - push + - --plain-http + - --artifact-type=application/vnd.gameplane.theme.v1+json + - gameplane-test-registry.gameplane-system.svc:5000/e2e-themes/e2e-theme-unsigned:0.1.0 + - theme.yaml:application/vnd.gameplane.theme.metadata.v1+yaml + - previews/dark.png:image/png + workingDir: /workspace + volumeMounts: + - { name: unsigned-010, mountPath: /workspace } + - { name: tmp, mountPath: /tmp } + volumes: + - name: signed-010 + configMap: + name: e2e-theme-bundles + items: + - { key: signed-0.1.0.yaml, path: theme.yaml } + - { key: dark.png, path: previews/dark.png } + - name: unsigned-010 + configMap: + name: e2e-theme-bundles + items: + - { key: unsigned-0.1.0.yaml, path: theme.yaml } + - { key: dark.png, path: previews/dark.png } + - name: tmp + emptyDir: {} diff --git a/test/e2e/fixtures/theme-oras-push-v2-job.yaml b/test/e2e/fixtures/theme-oras-push-v2-job.yaml new file mode 100644 index 000000000..92c5a3727 --- /dev/null +++ b/test/e2e/fixtures/theme-oras-push-v2-job.yaml @@ -0,0 +1,42 @@ +# Pushes e2e-theme-signed:0.2.0 for the update step of +# TestAPI_ThemeMarketplaceLifecycle. Needs the e2e-theme-bundles ConfigMap +# from theme-oras-push-job.yaml. +apiVersion: batch/v1 +kind: Job +metadata: + name: e2e-theme-oras-push-v2 + namespace: gameplane-system + labels: + app.kubernetes.io/component: e2e-fixture +spec: + backoffLimit: 4 + template: + metadata: + labels: + app.kubernetes.io/component: e2e-fixture + spec: + restartPolicy: OnFailure + containers: + - name: push-signed-v2 + image: ghcr.io/oras-project/oras:v1.3.3 + command: ["oras"] + args: + - push + - --plain-http + - --artifact-type=application/vnd.gameplane.theme.v1+json + - gameplane-test-registry.gameplane-system.svc:5000/e2e-themes/e2e-theme-signed:0.2.0 + - theme.yaml:application/vnd.gameplane.theme.metadata.v1+yaml + - previews/dark.png:image/png + workingDir: /workspace + volumeMounts: + - { name: signed-020, mountPath: /workspace } + - { name: tmp, mountPath: /tmp } + volumes: + - name: signed-020 + configMap: + name: e2e-theme-bundles + items: + - { key: signed-0.2.0.yaml, path: theme.yaml } + - { key: dark.png, path: previews/dark.png } + - name: tmp + emptyDir: {} diff --git a/test/e2e/standalone_themes_e2e_test.go b/test/e2e/standalone_themes_e2e_test.go new file mode 100644 index 000000000..6df06d3a2 --- /dev/null +++ b/test/e2e/standalone_themes_e2e_test.go @@ -0,0 +1,141 @@ +//go:build e2e + +package e2e + +import ( + "context" + "fmt" + "net/http" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// A second panel-only release, so this test never shares names with +// TestStandalone_HelmPanelLifecycle (which owns e2e-standalone / +// e2e-standalone-panel) and both can run in parallel in the standalone bucket. +const ( + standaloneThemesNamespace = "e2e-standalone-themes" + standaloneThemesRelease = "e2e-standalone-themes" +) + +// TestStandalone_ThemeSourceInstall covers spec 043 OD-4 A on a panel with no +// operator: the chart's panel-only profile (api.standalone=true, +// operator.enabled=false) adds an OCI theme source on the in-cluster test +// registry, indexes it, and the admin installs and selects a theme. Themes live +// in the panel database and the API fetches them itself, so nothing here needs +// a cluster registration. The chart has no setting for a local theme root +// (--themes-local-root), so an OCI source is used. +// +// Budget: one login against the standalone panel's own limiter; none on the +// shared panel. The registry push runs under ociPushMu. +func TestStandalone_ThemeSourceInstall(t *testing.T) { + t.Parallel() + func() { + ociPushMu.Lock() + defer ociPushMu.Unlock() + pushE2EThemes(t) + }() + + p := &standalonePanel{t: t, password: recoveryRandom(t)} + installStandaloneThemesPanel(t) + admin := standaloneThemesLogin(t, p) + defer admin.Close() + + var installation struct { + Standalone bool `json:"standalone"` + LocalCluster bool `json:"localCluster"` + } + p.decode(themeCall(t, admin, http.MethodGet, "/admin/installation", nil, http.StatusOK), &installation) + if !installation.Standalone || installation.LocalCluster { + t.Fatalf("installation = %+v, want standalone without a local cluster", installation) + } + + // No signature policy, so the unsigned package indexes as valid. + sourceName := "e2e-sa-themes-" + strconv.FormatInt(time.Now().UnixNano(), 36) + themeCall(t, admin, http.MethodPost, "/themes/sources", + ociThemeSourceBody(sourceName, []string{e2eThemeUnsigned}, "", true), http.StatusCreated) + var entry e2eThemeCatalogItem + envInstance.Eventually(t, 2*time.Minute, func() (bool, string) { + entry = themeCatalogOf(t, admin, sourceName)[e2eThemeUnsigned] + if entry.Status != "valid" || entry.Version != "0.1.0" { + return false, fmt.Sprintf("catalog entry %+v (source error %q)", entry, themeSourceErrors(t, admin, sourceName)) + } + return true, "" + }) + + var installed e2eInstalledTheme + themeDecode(t, themeCall(t, admin, http.MethodPost, "/users/me/themes", + map[string]any{"catalogId": entry.ID, "select": true}, http.StatusCreated), &installed) + if installed.Name != e2eThemeUnsigned || installed.Version != "0.1.0" || !installed.Selected { + t.Fatalf("installed = %+v, want %s 0.1.0, selected", installed, e2eThemeUnsigned) + } + sel := themeSelection(t, admin) + if sel.ThemeType != "installed" || sel.InstalledTheme == nil || !strings.Contains(string(sel.InstalledTheme.Tokens), "accent") { + t.Fatalf("preferences = %+v, want the installed theme selected with its tokens", sel) + } + + themeCall(t, admin, http.MethodDelete, "/users/me/themes/"+strconv.FormatInt(installed.ID, 10), nil, http.StatusNoContent) + if sel := themeSelection(t, admin); sel.ThemeType != "preset" || sel.PresetID != "pink" { + t.Fatalf("preferences after removal = %+v, want preset pink", sel) + } + themeCall(t, admin, http.MethodDelete, "/themes/sources/"+sourceName, nil, http.StatusNoContent) +} + +// installStandaloneThemesPanel installs the panel-only profile as its own Helm +// release, with the same settings as standalonePanel.install except the +// remote CIDR list, which only applies to cluster registrations. +func installStandaloneThemesPanel(t *testing.T) { + t.Helper() + tag := envInstance.Tag + if tag == "" { + tag = "e2e" + } + chart := filepath.Join("..", "..", "charts", "gameplane") + t.Cleanup(func() { + if t.Failed() && os.Getenv("GITHUB_ACTIONS") == "true" { + return + } + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) + defer cancel() + _ = exec.CommandContext(ctx, "helm", "uninstall", standaloneThemesRelease, "--namespace", standaloneThemesNamespace, + "--kube-context", envInstance.Context, "--wait", "--timeout", "2m").Run() + _ = envInstance.K8s.CoreV1().Namespaces().Delete(ctx, standaloneThemesNamespace, metav1.DeleteOptions{}) + }) + cmd := exec.CommandContext(t.Context(), "helm", "install", standaloneThemesRelease, chart, + "--namespace", standaloneThemesNamespace, "--kube-context", envInstance.Context, "--create-namespace", + "--set", "image.registry=gameplane-test,image.tag="+tag+",operator.enabled=false,api.standalone=true,web.enabled=false,ingress.enabled=false,crds.autoApply.enabled=false", + "--wait", "--timeout", "5m") + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("install standalone themes panel: %v: %s", err, out) + } +} + +// standaloneThemesLogin bootstraps the panel's admin with p.password and signs +// in through a fresh port-forward. +func standaloneThemesLogin(t *testing.T, p *standalonePanel) *APIClient { + t.Helper() + out, err := envInstance.KubectlWithStdin(t.Context(), p.password+"\n", + "exec", "-i", "-n", standaloneThemesNamespace, "deploy/gameplane-api", "-c", "api", "--", + "/api", "bootstrap-admin", "--username=admin", "--password-stdin", "--force") + if err != nil { + t.Fatalf("bootstrap standalone themes admin: %v: %s", err, out) + } + port, stop := envInstance.PortForward(t, standaloneThemesNamespace, "svc/gameplane-api", 80) + c := &APIClient{BaseURL: fmt.Sprintf("http://127.0.0.1:%d", port), HTTP: &http.Client{Jar: newInsecureCookieJar(), Timeout: 20 * time.Second}, stop: stop} + var login struct { + CSRF string `json:"csrf"` + } + p.decode(p.expect(c, http.MethodPost, "/auth/login", map[string]string{"username": "admin", "password": p.password}, http.StatusOK), &login) + if login.CSRF == "" { + t.Fatal("standalone themes login response lacked a CSRF token") + } + c.CSRF = login.CSRF + return c +} diff --git a/test/e2e/suite-components.json b/test/e2e/suite-components.json index 907c9e33a..8f6352ce7 100644 --- a/test/e2e/suite-components.json +++ b/test/e2e/suite-components.json @@ -22,6 +22,8 @@ { "tests": "^(TestPanel_OfflineRecovery|TestAPIClient_DoContextResponseBody|TestAPIClient_ExtractIntField)$", "components": ["operator", "api", "agent"], "paths": ["test/e2e/testdata/recovery/"] }, { "tests": "^TestStandalone_HelmPanelLifecycle$", "components": ["operator", "api", "agent"] }, + { "tests": "^TestStandalone_ThemeSourceInstall$", "components": ["api", "bundlefetch", "themepkg", "netguard"], + "paths": ["test/e2e/fixtures/theme-oras-push-job.yaml"] }, { "tests": "^TestNetworkIsolation_", "components": ["operator", "api", "agent", "tunnel"], "paths": ["test/e2e/fixtures/frps.yaml"] }, @@ -51,6 +53,8 @@ "components": ["agent", "gameaction"] }, { "tests": "^TestAPI_I18n_", "components": ["i18n"] }, { "tests": "^TestAPI_ThemePreferences$", "components": ["themepkg"] }, + { "tests": "^TestAPI_ThemeMarketplaceLifecycle$", "components": ["bundlefetch", "themepkg", "netguard"], + "paths": ["test/e2e/fixtures/theme-oras-push-job.yaml", "test/e2e/fixtures/theme-oras-push-v2-job.yaml", "test/e2e/fixtures/theme-cosign-sign-job.yaml", "test/e2e/fixtures/theme-cosign-sign-v2-job.yaml"] }, { "tests": "^TestAPI_I18n_ModuleLocales$", "components": ["modules"] }, { "tests": "^TestAPI_ModuleUpload_ExtractionStaysWithinBudget$", "components": ["gp-module", "modules"] }, { "tests": "^TestGameServer_.*(Bot_|_Persistence$|_RCON$|_Workshop$|_Mods$)",