Compare commits

..

93 Commits

Author SHA1 Message Date
privilegedescalation-engineer[bot] 2a156c4e63 fix(e2e): serialize concurrent E2E runs to prevent environment conflicts
Concurrent E2E runs share the same headlamp-e2e release name in
privilegedescalation-dev. When two runs overlap, one run's teardown
(if: always()) deletes the shared Deployment/Service/ConfigMap while
the other is still using it, causing Playwright auth setup to time out
waiting for the Headlamp UI.

Adds a repo-wide concurrency group so only one E2E run executes at a
time. cancel-in-progress: false queues incoming runs rather than
cancelling in-flight ones to avoid leaving dangling cluster resources
when teardown is interrupted.

Fixes: PRI-815

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-03-24 16:31:14 +00:00
privilegedescalation-ceo[bot] 5f817ec4f6 Merge pull request #108 from privilegedescalation/fix/node24-action-versions
ci: upgrade e2e.yaml actions to Node.js 24-compatible versions
2026-03-24 16:25:26 +00:00
Hugh Hackman 06d7dfb212 ci: upgrade e2e.yaml actions to Node.js 24-compatible versions
Update action versions ahead of GitHub's June 2, 2026 Node.js 20 deprecation:

- actions/setup-node@v4 → @v6
- actions/upload-artifact@v4 → @v7

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-03-24 16:11:05 +00:00
privilegedescalation-engineer[bot] ba508b8fc4 release: v1.0.0 (#107)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-03-24 15:27:35 +00:00
privilegedescalation-ceo[bot] b928fff4a5 release: v1.0.0
release: v1.0.0
2026-03-22 19:19:53 +00:00
Gandalf the Greybeard df6a5967ea fix(changelog): remove false coverage claim and fix compare link
- Remove "Coverage threshold: Vitest coverage threshold enforced in CI
  (#82)" — the shared CI workflow does not run coverage; this line was
  inaccurate.
- Fix [1.0.0] compare link from v0.6.0...v1.0.0 to v0.7.2...v1.0.0
  to accurately reflect the last tagged release.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-22 15:17:11 +00:00
Gandalf the Greybeard 415e32cdc9 release: v1.0.0
- Bump version to 1.0.0 in package.json and package-lock.json
- Update artifacthub-pkg.yml: version, archive-url, and changes section
- Add v1.0.0 CHANGELOG entry covering changes since v0.7.2

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-03-22 11:58:44 +00:00
privilegedescalation-engineer[bot] aa32e7a353 ci: add packageManager field to pin pnpm version (#103)
* ci: add packageManager field to pin pnpm version

Pins pnpm@10.32.1 via the packageManager field. This allows
pnpm/action-setup@v4 to resolve the version from package.json instead
of relying on `version: latest`, preventing silent breakage on major
pnpm version bumps.

Fixes: PRI-674

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* ci: trigger fresh CI run after Corepack fix merges in .github PR #57

The shared plugin-ci.yaml now uses Corepack when packageManager field
is set, avoiding the 'Multiple versions of pnpm specified' error.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* ci: retrigger CI with updated shared workflow (python3 pnpm detection)

---------

Co-authored-by: Hugh Hackman <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: privilegedescalation-ceo[bot] <269721483+privilegedescalation-ceo[bot]@users.noreply.github.com>
Co-authored-by: Hugh Hackman <hugh@privilegedescalation.paperclip.ing>
Co-authored-by: Hugh Hackman <hugh@privilegedescalation.com>
2026-03-22 11:17:41 +00:00
privilegedescalation-ceo[bot] 67bfe5ff5c Merge pull request #105 from privilegedescalation/chore/renovate-pin-digests
chore(renovate): add pinDigests for GitHub Actions SHA pinning
2026-03-22 11:06:32 +00:00
privilegedescalation-engineer[bot] c08f3fbdbe chore(renovate): add pinDigests to ensure SHA pinning for GitHub Actions
The org renovate-config.json (PR #63) adds pinDigests: true at the org level,
but this repo extends config:recommended directly. Adding pinDigests: true here
ensures GitHub Actions are pinned to full commit SHAs regardless of whether the
org config is extended.

Related: privilegedescalation/.github#63, PRI-757
2026-03-22 07:16:04 +00:00
privilegedescalation-ceo[bot] 02dc79b739 Merge pull request #98 from privilegedescalation/feat/dual-approval-status-check
ci: add dual-approval status check (CTO + QA)
2026-03-22 05:58:29 +00:00
Hugh Hackman d1097c2dbf ci: trigger fresh CI run with updated shared workflows 2026-03-22 05:49:14 +00:00
privilegedescalation-ceo[bot] 5fa14ab353 Merge pull request #104 from privilegedescalation/fix/e2e-dns-readiness-check
fix: wait for HTTP reachability after rollout in deploy-e2e-headlamp.sh
2026-03-22 05:24:23 +00:00
Hugh Hackman acd53c297b fix: wait for HTTP reachability after rollout in deploy-e2e-headlamp.sh
kubectl rollout status confirms the pod is ready per readinessProbe, but
Kubernetes Service DNS propagation to the runner pod may lag behind.
This caused intermittent E2E failures with ERR_NAME_NOT_RESOLVED.

Add a poll loop (max 120s) after rollout status that verifies the service
URL is reachable via HTTP before writing .env.e2e. This eliminates the
race condition between DNS propagation and Playwright launch.

Fixes: PRI-687 (intermittent E2E DNS failure)
2026-03-22 04:51:30 +00:00
privilegedescalation-engineer[bot] fd66b119b3 ci: add dual-approval caller workflow
Calls the shared privilegedescalation/.github dual-approval-check
reusable workflow to enforce CTO + QA approval as a GitHub status check.

Once privilegedescalation/.github#47 is merged, this status check can
be added to required_status_checks in branch protection.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-03-22 04:41:32 +00:00
privilegedescalation-ceo[bot] 21026cc992 Merge pull request #102 from privilegedescalation/fix/add-eslint-direct-dep
fix: add eslint as direct devDependency
2026-03-22 04:38:32 +00:00
Gandalf the Greybeard 95096562e4 fix: add @headlamp-k8s/eslint-config as direct devDependency
pnpm strict mode does not hoist transitive deps. @headlamp-k8s/eslint-config
was only available via @kinvolk/headlamp-plugin, causing ESLint to fail with
"Cannot find config @headlamp-k8s/eslint-config to extend from". Adding it
as a direct devDependency makes it accessible at the root node_modules level.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-03-22 04:29:31 +00:00
Hugh Hackman 62baf2bd5e fix: also add prettier as direct devDependency
pnpm strict mode does not expose transitive dependency binaries.
Adding prettier@^2.8.8 alongside eslint@^8.57.0 so that
pnpm run format:check works in CI without 'prettier: not found'.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-22 04:24:45 +00:00
Hugh Hackman d2da09406a fix: add eslint as direct devDependency
pnpm's strict node_modules layout does not expose transitive dependency
binaries. eslint was only a transitive dep via @kinvolk/headlamp-plugin,
causing 'eslint: not found' when running pnpm run lint in CI.

Adding eslint@^8.57.0 as a direct devDependency ensures the binary is
available in node_modules/.bin/ under pnpm.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-22 04:21:28 +00:00
privilegedescalation-ceo[bot] a975192dfb Merge pull request #92 from privilegedescalation/fix/npm-audit-vulnerabilities
fix: patch 8/9 npm audit vulnerabilities via pnpm.overrides
2026-03-21 23:45:32 +00:00
Gandalf the Greybeard 2c80d0451e fix: patch 8 of 9 npm vulnerabilities via pnpm.overrides
Move vulnerability overrides from npm-format top-level `overrides` to
pnpm-format `pnpm.overrides`. Add flatted override to patch the
high-severity prototype pollution CVE. All 5 high + 3 moderate severity
issues are now resolved.

Remaining: elliptic (low, no patch available upstream).

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-03-21 22:41:32 +00:00
privilegedescalation-ceo[bot] d4a4e9a355 Merge pull request #95 from privilegedescalation/fix/add-typescript-devdep
fix: add typescript as explicit devDependency
2026-03-21 22:39:17 +00:00
privilegedescalation-ceo[bot] a08c0fc368 Merge branch 'main' into fix/add-typescript-devdep 2026-03-21 22:35:56 +00:00
privilegedescalation-ceo[bot] d0a6794576 Merge pull request #97 from privilegedescalation/fix/e2e-token-auth
fix: use token auth in E2E — handle direct /token redirect
2026-03-21 22:35:45 +00:00
Hugh Hackman 00c270b0d4 fix: use token auth in E2E workflow, handle direct /token redirect
The E2E Headlamp instance is deployed without OIDC configuration, so
Headlamp redirects / → /token directly instead of / → /login. The
authenticateWithToken function was hardcoded to expect /login first,
causing a 60s timeout on every run.

- e2e.yaml: remove unused Setup Helm step (deploy script uses kubectl)
- e2e.yaml: remove AUTHENTIK_USERNAME/PASSWORD (no OIDC in E2E instance)
- auth.setup.ts: waitForURL accepts both /login and /token; only clicks
  "use a token" if landed on /login (OIDC-configured Headlamp)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 20:55:44 +00:00
privilegedescalation-ceo[bot] 7f115e0d6e Merge pull request #94 from privilegedescalation/fix/e2e-kubectl-deploy
fix: replace Helm-based E2E deploy with kubectl apply
2026-03-21 20:51:01 +00:00
Gandalf the Greybeard 9d02f504fd fix: add typescript as explicit devDependency
pnpm run tsc failed with "tsc not found" because typescript was only
available as a transitive dependency from @kinvolk/headlamp-plugin.
Adding it explicitly as a direct devDependency ensures tsc is always
accessible regardless of pnpm hoisting behavior.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-03-21 20:45:46 +00:00
Gandalf the Greybeard 65c25067ec fix: replace Helm-based E2E deploy with kubectl apply
The Helm chart deployment was consistently failing — the pod enters
CrashLoopBackOff despite identical kubectl manifests working. The Helm
chart also silently ignored extraVolumes/extraVolumeMounts (pnpm-style
keys not supported by the chart), meaning the plugin ConfigMap was
never actually mounted even when deploy appeared to succeed.

Replace with direct kubectl apply using a bash heredoc to render the
manifest with shell variable substitution. This removes the Helm
dependency, fixes the plugin volume mount, and uses the exact
configuration that was proven to work in the cluster.

Also adds explicit initialDelaySeconds/failureThreshold on readiness
and liveness probes to give Headlamp adequate startup time.

Note: .github/workflows/e2e.yaml still has a Setup Helm step that is
now unused — assigned to Hugh Hackman to remove.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-03-21 20:43:25 +00:00
privilegedescalation-ceo[bot] 4c6324c4c2 Merge pull request #89 from privilegedescalation/fix/e2e-namespace-privilegedescalation-dev
fix: move E2E test namespace from default to privilegedescalation-dev
2026-03-21 20:17:41 +00:00
Hugh Hackman ca4832bcc3 fix: add watch verb to services/serviceaccounts/configmaps/secrets in RBAC
Helm --wait requires watch on these resources to track rollout readiness.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 20:10:32 +00:00
Hugh Hackman d6c8a8bbfc fix: disable ClusterRoleBinding creation in E2E Helm values
The Headlamp chart defaults to creating a ClusterRoleBinding, but the
ARC runner service account lacks cluster-scoped RBAC permissions. E2E
tests only need Headlamp to serve the UI — no cluster-admin required.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 20:08:25 +00:00
Hugh Hackman 3d91572b59 fix: update Headlamp Helm repo URL to kubernetes-sigs
The Headlamp project moved from headlamp-k8s to kubernetes-sigs GitHub org.
The old chart URL https://headlamp-k8s.github.io/headlamp/ now returns 404.
Updated to https://kubernetes-sigs.github.io/headlamp/.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 20:05:08 +00:00
Hugh Hackman f0f3bd51a4 ci: change E2E_NAMESPACE from default to privilegedescalation-dev
Align workflow with org RBAC policy — agents have read-write access only
in privilegedescalation-dev, not the default namespace.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 20:01:04 +00:00
Gandalf the Greybeard 6e9c97593c fix: move E2E test namespace from default to privilegedescalation-dev
Per org RBAC policy, development/testing Headlamp instances must run in
`privilegedescalation-dev`, not `default`. Agents only have read-write
access in `privilegedescalation` and `privilegedescalation-dev` — the
`default` namespace is outside our permitted scope.

Updated:
- deployment/e2e-ci-runner-rbac.yaml: Role/RoleBinding now targets privilegedescalation-dev
- deployment/headlamp-e2e-values.yaml: comment updated
- scripts/deploy-e2e-headlamp.sh: default namespace changed
- scripts/teardown-e2e-headlamp.sh: default namespace changed

Note: .github/workflows/e2e.yaml still sets E2E_NAMESPACE: default and
needs a separate update — delegated to Hugh Hackman (workflow owner).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 19:51:18 +00:00
privilegedescalation-engineer[bot] a5398e8409 feat: add ExemptionManager tests, coverage threshold, and ArtifactHub metadata polish (#82)
* ci: rework E2E infrastructure to use default namespace

Board directive: E2E tests must run in the `default` namespace.
Nothing should persist beyond a test run; no dedicated namespace needed.

Changes:
- e2e-ci-runner-rbac.yaml: retarget Role/RoleBinding to `default`,
  remove ClusterRole/ClusterRoleBinding (no longer needed since we
  don't need cluster-scoped namespace read permission)
- e2e.yaml: set E2E_NAMESPACE=default
- deploy-e2e-headlamp.sh: default namespace to `default`, remove
  namespace existence check (default always exists)
- teardown-e2e-headlamp.sh: default namespace to `default`, remove
  namespace existence check guard
- headlamp-e2e-values.yaml: update usage comment
- e2e/README.md: remove namespace creation prerequisite

Closes #78 #79

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* ci: add RBAC preflight check to deploy-e2e-headlamp.sh

Fails fast with a clear error and remediation hint if the runner SA
lacks configmap delete permission, instead of dying mid-deploy.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat: add ExemptionManager tests, coverage threshold, and ArtifactHub metadata

- Add 22 unit tests for ExemptionManager.tsx covering:
  - Failing checks extraction (pod-level, container-level, ignore-severity, dedup)
  - Dialog open/close, check toggle, exempt-all toggle
  - Apply button enabled/disabled state
  - ApiProxy.request called with correct path (apps/batch/core) and annotation structure
  - Success and error feedback states, in-flight "Applying..." label
- Add vitest coverage config with >=80% threshold (lines/functions/branches/statements)
- Update artifacthub-pkg.yml:
  - Add install section (Headlamp-native plugin installer only)
  - Add appVersion: "5.0" (compatible Polaris dashboard version)
  - Expand distro-compat from "in-cluster" to "in-cluster,web,desktop"
  - Add changes block documenting v1.0 features

Closes privilegedescalation/headlamp-polaris-plugin#81 (partial — test and metadata tasks)

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* style: fix Prettier formatting in ExemptionManager.test.tsx

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix: add @vitest/coverage-v8 devDependency for coverage provider

vitest.config.mts specifies coverage.provider: 'v8' but the
@vitest/coverage-v8 package was missing from devDependencies.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Hugh Hackman <hugh@privilegedescalation.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Gandalf the Greybeard <gandalf@privilegedescalation.com>
Co-authored-by: Samuel Stinkpost <samuel@privilegedescalation.dev>
Co-authored-by: Gandalf the Greybeard <gandalf@privilegedescalation.dev>
2026-03-21 12:53:07 +00:00
privilegedescalation-ceo[bot] bb1df5f3f6 Merge pull request #80 from privilegedescalation/ci/e2e-default-namespace
ci: rework E2E infrastructure to use default namespace
2026-03-21 03:26:13 +00:00
Hugh Hackman 1bf5c2431c ci: add RBAC preflight check to deploy-e2e-headlamp.sh
Fails fast with a clear error and remediation hint if the runner SA
lacks configmap delete permission, instead of dying mid-deploy.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 03:15:06 +00:00
Hugh Hackman 08a3009ba8 ci: rework E2E infrastructure to use default namespace
Board directive: E2E tests must run in the `default` namespace.
Nothing should persist beyond a test run; no dedicated namespace needed.

Changes:
- e2e-ci-runner-rbac.yaml: retarget Role/RoleBinding to `default`,
  remove ClusterRole/ClusterRoleBinding (no longer needed since we
  don't need cluster-scoped namespace read permission)
- e2e.yaml: set E2E_NAMESPACE=default
- deploy-e2e-headlamp.sh: default namespace to `default`, remove
  namespace existence check (default always exists)
- teardown-e2e-headlamp.sh: default namespace to `default`, remove
  namespace existence check guard
- headlamp-e2e-values.yaml: update usage comment
- e2e/README.md: remove namespace creation prerequisite

Closes #78 #79

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-03-21 01:40:47 +00:00
privilegedescalation-ceo[bot] b3f1f65b2f Merge pull request #73 from privilegedescalation/gandalf/e2e-redesign-custom-image
refactor: redesign E2E to use ConfigMap volume mount with stock Headlamp image
2026-03-21 00:09:09 +00:00
Gandalf the Greybeard 74a5bb0a01 fix: teardown-e2e-headlamp.sh gracefully skips missing namespace
When the headlamp-e2e namespace does not exist, teardown now exits
early with a clear message instead of failing with a misleading RBAC
error. Addresses PRI-443.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-03-20 22:45:39 +00:00
Gandalf the Greybeard 9249f151a8 fix: add ClusterRole for runner SA to verify headlamp-e2e namespace
kubectl get namespace is cluster-scoped and requires a ClusterRole.
The runner SA only had a namespaced Role, causing E2E to fail with
Forbidden even when the namespace existed. Adds a minimal ClusterRole
restricted to get on headlamp-e2e only.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-03-20 22:29:00 +00:00
privilegedescalation-paperclip[bot] dd782fbea0 ci: pass GitHub App token secrets to release workflow (#76)
The shared release workflow now requires RELEASE_APP_ID and
RELEASE_APP_PRIVATE_KEY secrets for PR creation, since the org
blocks GITHUB_TOKEN from creating PRs.

Depends on privilegedescalation/.github#31

Co-authored-by: privilegedescalation-paperclip[bot] <268365651+privilegedescalation-paperclip[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 13:24:35 +00:00
Hugh Hackman 0a52a8effa fix: remove namespace create/delete from E2E scripts
The CI runner SA only has namespace-scoped RBAC in headlamp-e2e — it
cannot create or delete namespaces at the cluster level. Deploy now
verifies the namespace exists (with a clear error if not), and teardown
cleans up resources without deleting the namespace itself.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-03-20 01:13:02 +00:00
Hugh Hackman 902f206e32 ci: update E2E workflow for ConfigMap approach
Match deploy-e2e-headlamp.sh changes:
- Remove Docker image build/push steps (no custom images)
- Remove packages:write permission (no GHCR push needed)
- Add kubectl and Helm setup steps
- Deploy script creates ConfigMap from dist/ and uses stock Headlamp image
2026-03-20 01:05:39 +00:00
Gandalf the Greybeard 4344d33349 refactor: replace Dockerfile.e2e with ConfigMap volume mount for E2E plugin loading
Delete custom Docker image approach per board directive. Plugin is now
loaded into stock Headlamp via a ConfigMap volume mount:

- Delete Dockerfile.e2e
- deploy-e2e-headlamp.sh creates a ConfigMap from dist/ and mounts it
  into the stock ghcr.io/headlamp-k8s/headlamp image
- Helm values use extraVolumes/extraVolumeMounts for the ConfigMap
- No custom images, no PVCs, no kubectl exec/cp

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-03-20 01:01:39 +00:00
Hugh Hackman 8ac890a1c6 ci: update E2E workflow for Docker image approach
Replace PVC/kubectl-patch E2E workflow with the new Docker image approach:
- Build custom Headlamp image with plugin pre-installed (Dockerfile.e2e)
- Push to ghcr.io/privilegedescalation/headlamp-polaris-e2e
- Deploy dedicated instance in headlamp-e2e namespace via Helm
- Auto-generate auth token via deploy-e2e-headlamp.sh
- Teardown after tests (always runs)

No more PVCs, kubectl exec/cp, or kube-system deployment patching.
2026-03-20 01:01:11 +00:00
Gandalf the Greybeard 6189f2b983 refactor: redesign E2E to use custom Docker image instead of PVC/kubectl
Replace the PVC + kubectl-patch approach for E2E plugin deployment with
a custom Docker image that has the plugin pre-installed. This eliminates
all policy-violating operations:

- No PVCs in kube-system
- No kubectl exec/cp to Headlamp pods
- No deployment patching via kubectl
- No temporary pods or ConfigMap-based file transfers

The new approach builds a Headlamp image with the plugin baked in
(Dockerfile.e2e), deploys it as a dedicated instance in the headlamp-e2e
namespace via Helm, and tears it down after tests complete.

RBAC is scoped to the headlamp-e2e namespace instead of kube-system.

Note: .github/workflows/e2e.yaml still needs updating to use the new
scripts — that change is delegated to Hugh (CI/CD owner).

Closes: privilegedescalation/headlamp-polaris-plugin#72

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-03-20 00:33:09 +00:00
privilegedescalation-paperclip[bot] 4296eb97fb release: v0.7.2 (#70)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-03-19 21:34:59 +00:00
privilegedescalation-paperclip[bot] 87bf1a321f fix: update e2e runner label to runners-privilegedescalation (#71)
ARC runner scale set label changed from local-ubuntu-latest to
runners-privilegedescalation. The shared workflows were updated in
.github PR #28 but this per-repo e2e workflow was missed.

Co-authored-by: Hugh Hackman <hugh@privilegedescalation.com>
2026-03-19 21:34:45 +00:00
hugh-hackman[bot] 37af076456 chore: bump actions/checkout from v4 to v6 in E2E workflow (#69)
Co-authored-by: hugh-hackman[bot] <266376744+hugh-hackman[bot]@users.noreply.github.com>
2026-03-19 00:14:43 +00:00
gandalf-the-greybeard[bot] 0476fd1076 fix: add tar and undici as direct devDependencies for Dependabot resolution (#68)
Dependabot security update runs are failing because it cannot resolve
patched versions of tar (>=7.5.11) and undici (>=7.24.0) through
transitive dependency chains. While npm overrides already mitigate the
vulnerabilities locally, Dependabot's resolver doesn't honor overrides.

Adding these as explicit devDependencies lets Dependabot see and
resolve the patched versions directly.

Co-authored-by: Gandalf the Greybeard <gandalf@privilegedescalation.dev>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-03-18 23:54:21 +00:00
null-pointer-nancy[bot] 6a47358771 Merge pull request #65 from privilegedescalation/fix/dep-security-overrides-tar-undici
fix: add npm overrides for tar and undici security advisories
2026-03-18 02:49:22 +00:00
Gandalf the Greybeard f7d415e013 fix: add npm overrides for tar and undici security advisories
The dependency tree through @kinvolk/headlamp-plugin constrains tar
(via pluginctl) and undici (via cheerio/i18next-parser). While the
lockfile currently resolves to patched versions, Dependabot cannot
auto-update these transitive deps. Adding explicit overrides ensures
tar>=7.5.11 and undici>=7.24.3 are always resolved, preventing
future Dependabot failures.

Fixes #64

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-03-18 02:44:24 +00:00
gandalf-the-greybeard[bot] 2a60029104 e2e: shared volume plugin deployment for CI tests (#59)
* e2e: shared volume plugin deployment replacing init container approach

Replace the init container plugin installation with a shared PVC volume
between the CI runner and Headlamp pod. The runner builds the plugin and
copies it to the shared mount; Headlamp reads from the same volume.

- Add deployment/headlamp-e2e-values.yaml (PVC-backed shared volume)
- Add deployment/headlamp-plugins-pvc.yaml (PVC manifest)
- Add scripts/deploy-plugin-via-volume.sh (build + copy + restart)
- Remove deployment/headlamp-static-plugin-values.yaml (init container)

This is CI-only test infrastructure — ArtifactHub remains the sole
user-facing distribution channel.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* ci: update e2e workflow for shared volume plugin deployment

Replace the old preflight-only approach with a build-and-deploy flow
that uses a shared volume (hostPath) between the CI runner and the
Headlamp pod. The workflow now builds the plugin from source, copies
the artifact to a shared volume path, and optionally calls Gandalf's
deploy script for Headlamp rollout coordination.

Removes kubectl exec/cp references and version-match preflight in
favor of deploying the PR's actual build artifact.

Refs: PRI-216, PRI-195

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* ci: align e2e workflow with Gandalf's deploy script interface

Simplify deploy step to call scripts/deploy-plugin-via-volume.sh
directly instead of duplicating copy logic. Align env var names
(PLUGIN_VOLUME_PATH, HEADLAMP_DEPLOY) with the deploy script's
expected interface from PR #59.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix: deploy plugin via temporary pod instead of assuming local PVC mount

The deploy script assumed the PVC was mounted on the CI runner at
/mnt/headlamp-plugins, but the runner pod doesn't have that mount.
Fix by using a temporary pod (kubectl run) that mounts the PVC,
receives the plugin tarball via stdin, and extracts it.

Also adds missing workflow steps to create the PVC and upgrade
Headlamp with the shared volume helm values before deploying.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix: add kubectl, helm, and helm repo setup steps to e2e workflow

The self-hosted runner doesn't have kubectl or helm pre-installed.
Add setup steps using azure/setup-kubectl and azure/setup-helm
actions, and add the Headlamp helm repo before the upgrade step.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix: update Headlamp Helm repo URL from headlamp-k8s to kubernetes-sigs

The Headlamp project moved to the kubernetes-sigs org. The old Helm chart
repository URL (headlamp-k8s.github.io) returns 404, causing E2E workflow
failure at the `helm repo add` step.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* chore: add RBAC manifest for E2E CI runner

Documents the Role and RoleBinding applied to the cluster for the ARC
runner service account. Grants permissions in kube-system needed for
shared volume plugin deployment (PVCs, pods, Helm resources).

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix: remove .github/workflows/e2e.yaml changes from PR

The workflow changes should be handled separately by Hugh Hackman
per PRI-215. This PR should only contain deployment manifests and
scripts, not CI workflow modifications.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* ci: add shared volume plugin deployment to E2E workflow

Adds the build, Helm, PVC, and plugin deploy steps needed for the
shared volume E2E approach. Uses the correct kubernetes-sigs Helm repo
URL and overrides config.sessionTTL=0 to avoid schema validation error.

This is the workflow counterpart to the deployment manifests and scripts
already in this PR (PVC, values overlay, deploy script).

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(e2e): set sessionTTL=1 to satisfy Helm schema minimum

The Headlamp Helm chart schema enforces a minimum of 1 for
config.sessionTTL. Setting it to 0 caused helm upgrade to fail
with a schema validation error.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(e2e): add cluster-scoped RBAC for CI runner

The Headlamp Helm chart manages ClusterRole and ClusterRoleBinding
resources. The CI runner SA needs cluster-level permissions to
get/update these during helm upgrade. Added ClusterRole and
ClusterRoleBinding alongside the existing namespace-scoped Role.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(e2e): replace helm upgrade with kubectl patch to avoid cluster RBAC

The CI runner SA cannot access cluster-scoped resources (ClusterRole,
ClusterRoleBinding) needed by helm upgrade's 3-way merge. Replace the
helm upgrade step with kubectl patch commands that add the shared volume
mount directly to the Headlamp deployment.

This eliminates the need for cluster-admin intervention:
- kubectl patch adds PVC volume + volumeMount to the deployment
- kubectl set env configures the plugins directory
- kubectl rollout status waits for the update

Also removes the now-unnecessary ClusterRole/ClusterRoleBinding from the
RBAC manifest — only namespace-scoped Role/RoleBinding is needed.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(e2e): improve volume mount idempotency check

Check for existing volume mount by mountPath and PVC claimName, not
just by volume name. A prior helm upgrade may have created mounts
with different names but the same path, causing kubectl patch to fail
with "mountPath must be unique".

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(e2e): schedule deploy pod on same node as Headlamp

The headlamp-plugins PVC is ReadWriteOnce, so the temporary deploy
pod must run on the same node as the Headlamp pod to mount it.
Look up the Headlamp pod's node and set nodeName in the pod spec.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(e2e): use Job with base64 tarball instead of kubectl run stdin

The kubectl run --rm -i stdin pipe times out in the ARC runner
environment. Replace with a Kubernetes Job that receives the plugin
tarball as base64-encoded data in the container command. This avoids
the unreliable attach/stdin mechanism entirely.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(e2e): use ConfigMap for tarball instead of inline base64

Embedding base64 data in the YAML spec broke parsing. Store the plugin
tarball in a ConfigMap via --from-file and mount it in the deploy Job.
This avoids both the stdin pipe issue and the YAML escaping issue.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(e2e): use temp file for Job YAML to avoid heredoc escaping

Variable expansion inside heredocs breaks YAML parsing when values
contain colons and quotes (like nodeName). Write the Job manifest to
a temp file with literal YAML, then sed-substitute the dynamic values.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(e2e): use Pod instead of Job for plugin deploy

The CI runner SA has permission to create Pods but not Jobs in
kube-system. Switch from a Job to a plain Pod with restartPolicy:Never.
Use ConfigMap mount for tarball data (no stdin piping needed).

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix: align registerPluginSettings name with deployed plugin directory

The plugin is deployed to the 'polaris' directory but was registered with
'headlamp-polaris', causing Headlamp to not match the settings component
with the loaded plugin. This fixes all 5 failing E2E settings tests.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix: use package name for registerPluginSettings, not directory name

Headlamp identifies plugins by their package.json name (headlamp-polaris),
not the deploy directory name (polaris). The previous commit incorrectly
changed this to 'polaris', causing the settings component to never render
in the plugin settings page — breaking all 5 E2E settings tests.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix: align registerPluginSettings name with deploy directory 'polaris'

The shared volume deploy script places the plugin at /headlamp/plugins/polaris/,
so Headlamp matches settings by directory name 'polaris', not the package.json
name 'headlamp-polaris'. This reverts commit b9d718b which incorrectly changed
the registration name back to 'headlamp-polaris'.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix: align plugin deploy dir with package.json name, clean stale dirs

The PVC had a stale headlamp-polaris directory from a previous install.
Headlamp loads plugins by scanning the plugins dir and reading package.json
from each subdirectory — it was loading the old build from headlamp-polaris/
while the deploy script was writing to polaris/. The settings registration
name needs to match the plugin name Headlamp identifies.

Changes:
- Deploy script now uses headlamp-polaris as the directory name (matching
  package.json name field)
- Deploy pod cleans up both polaris/ and headlamp-polaris/ before deploying
  to ensure no stale copies remain
- registerPluginSettings uses headlamp-polaris to match Headlamp's plugin
  identifier

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix: align registerPluginSettings and E2E test with package.json name

Headlamp identifies plugins by reading package.json from the plugin
directory. Since package.json name is 'headlamp-polaris', both the
registerPluginSettings call and the E2E settings test must use
'headlamp-polaris', not 'polaris'.

- registerPluginSettings('polaris') → registerPluginSettings('headlamp-polaris')
- E2E test locator: text=polaris → text=headlamp-polaris

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(e2e): load main page before settings to ensure plugin list is populated

Headlamp's PluginSettings component initializes its state from
localStorage on mount and never syncs when props.plugins updates later.
If the settings page loads before fetchAndExecutePlugins completes,
the plugin list stays empty and the test can't find "headlamp-polaris".

Fix: navigate to the main page first, wait for the Polaris sidebar
entry to confirm the plugin is loaded (which populates localStorage),
then navigate to the settings page.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(e2e): use client-side routing for settings navigation

The PluginSettings component reads the plugin registry once on mount
and never re-renders when new plugins register. Using page.goto() for
the settings URL re-initializes the SPA, causing PluginSettings to
mount before async plugin scripts finish calling registerPluginSettings().

Replace page.goto() with pushState + popstate to do client-side routing.
This preserves the already-loaded plugin registrations from the main
page, so PluginSettings sees the plugin immediately on mount.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix(e2e): use correct HOME-context URL for plugin settings page

The settings page is at /settings/plugins (HOME sidebar context), not
/c/main/settings/plugins (in-cluster context). The in-cluster URL
doesn't match any route, so PluginSettings never mounted and the
plugin entry was never visible.

With the correct URL, no preloading or client-side routing hacks are
needed — PluginSettings uses useTypedSelector on the Redux plugin store,
so it re-renders automatically when registerPluginSettings() fires.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

---------

Co-authored-by: Gandalf the Greybeard <gandalf@privilegedescalation.dev>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Hugh Hackman <hugh@privilegedescalation.com>
Co-authored-by: Hugh Hackman <hugh-hackman[bot]@users.noreply.github.com>
2026-03-18 02:42:42 +00:00
gandalf-the-greybeard[bot] 76c7a5bc1f fix: badge navigation uses window.location.pathname for cluster extraction
* fix: badge navigation uses window.location + correct settings plugin name

- AppBarScoreBadge: Read cluster from window.location.pathname instead of
  useCluster() (returns null in AppBar context) or useLocation() (may not
  reflect cluster prefix outside cluster route context)
- registerPluginSettings: Use 'polaris' to match the deployed directory name
  (plugin is at static-plugins/polaris, not headlamp-polaris)
- Add unit test for no-cluster fallback navigation

Supersedes the source-code fixes from PR #55 without the workflow/deploy
script changes that broke CI.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* fix: use Object.defineProperty for window.location in test

Replace `as Location` cast with Object.defineProperty to match the
existing beforeEach pattern and fix TypeScript strict mode error.

Co-Authored-By: Paperclip <noreply@paperclip.ing>

---------

Co-authored-by: Gandalf the Greybeard <gandalf@privilegedescalation.dev>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-03-17 17:06:14 +00:00
gandalf-the-greybeard[bot] d64db24240 docs: remove manual install sections from README
ArtifactHub plugin installer is the only supported installation method.
Remove sidecar, manual tarball, and build-from-source install options
to align documentation with company policy.

Co-authored-by: Gandalf the Greybeard <gandalf@privilegedescalation.dev>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-03-17 17:04:35 +00:00
hugh-hackman[bot] 9bd07e1928 release: v0.7.1 (#62)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-03-17 17:00:48 +00:00
gandalf-the-greybeard[bot] 40b0a2d220 fix: resolve 6 E2E failures — cluster URL prefix + settings registration (#51)
Two root causes for the remaining 6 E2E failures after PR #50:

1. AppBarScoreBadge: Router.createRouteURL('polaris') was called without
   the cluster parameter, producing '/polaris' instead of '/c/main/polaris'.
   Now uses K8s.useCluster() to pass the active cluster. (appbar.spec.ts:18)

2. Plugin settings: registerPluginSettings was called with 'polaris' but
   the package.json name is 'headlamp-polaris'. Headlamp matches settings
   registrations to the package name, so the component never rendered.
   (settings.spec.ts — all 5 tests)

Co-authored-by: gandalf-the-greybeard[bot] <gandalf-the-greybeard[bot]@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-03-15 15:40:27 -04:00
gandalf-the-greybeard[bot] fb3d262eb7 fix: resolve 7 E2E test failures — badge nav + test selectors (#50)
Fix badge navigation to use cluster-scoped path via Router.createRouteURL
instead of hardcoded '/polaris'. Remove hardcoded RGB color assertions in
badge color test. Scope ambiguous /%/ and 'Resources' selectors in polaris
E2E tests. Fix settings tests to click into plugin settings before asserting.

Fixes: PRI-151

Co-authored-by: gandalf-the-greybeard[bot] <gandalf-the-greybeard[bot]@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-03-15 14:04:53 -04:00
hugh-hackman[bot] 0f88a9b19f fix: sync package-lock.json (fresh) (#49)
Co-authored-by: Hugh Hackman <hugh@privilegedescalation.com>
2026-03-15 14:04:20 -04:00
null-pointer-nancy[bot] d3860ff5a2 ci: retrigger after shared workflow fix (#48)
CI retrigger after shared workflow fix (.github PR#14). E2E failures are pre-existing test bugs tracked in PRI-151.
2026-03-15 17:55:09 +00:00
hugh-hackman[bot] 7165bdf79b fix: sync package-lock.json with package.json (#46)
Co-authored-by: Hugh Hackman <hugh@privilegedescalation.com>
2026-03-15 12:40:12 -04:00
null-pointer-nancy[bot] eb218dc7f4 policy: add ArtifactHub-only installation policy (#47)
Per CEO directive, ArtifactHub via the Headlamp plugin installer is the
only approved installation method. No exceptions.

Co-authored-by: null-pointer-nancy[bot] <266300690+null-pointer-nancy[bot]@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-03-15 12:39:29 -04:00
gandalf-the-greybeard[bot] c02efe5430 fix: add @types/react and @types/react-dom to fix TypeScript errors (#45)
Adds missing TypeScript type declarations for React and React-DOM as devDependencies.

QA-approved by Regression Regina.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-03-15 16:06:02 +00:00
hugh-hackman[bot] daf0ebbff5 release: v0.7.1 — fix Artifact Hub checksum mismatch (#41)
Co-authored-by: Hugh Hackman <hugh@privilegedescalation.com>
2026-03-15 13:54:58 +00:00
hugh-hackman[bot] fc8a9eebac ci: add pull-requests write permission to release workflow (#40)
Co-authored-by: Hugh Hackman <hugh@privilegedescalation.com>
2026-03-15 13:54:53 +00:00
null-pointer-nancy[bot] 07bcfa084a ci: remove helm/kubectl Polaris deploy steps from E2E workflow (#38)
Polaris is already installed on the CI cluster. The E2E workflow
was failing because the runner SA lacks RBAC to deploy to the
polaris namespace. Remove Setup Helm, Setup kubectl, Deploy Polaris,
Apply RBAC, and Wait for readiness steps.

Resolves: PRI-28, PRI-109

Co-authored-by: Null Pointer Nancy <nancy@privilegedescalation.dev>
2026-03-12 22:13:11 +00:00
gandalf-the-greybeard[bot] 1755cedd88 fix: remove unused type references from tsconfig.json (#37)
These type references were causing tsc to fail because neither vite nor
vite-plugin-svgr is installed as a dependency. The codebase does not use
any Vite-specific APIs or SVG imports, so the references are unnecessary.

Fixes #36

Co-authored-by: gandalf-the-greybeard[bot] <gandalf-the-greybeard[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 13:53:24 +00:00
hugh-hackman[bot] 07a99a76ce ci: install helm and kubectl in e2e workflow (#35)
Co-authored-by: Hugh Hackman <hugh@privilegedescalation.com>
2026-03-11 02:05:53 +00:00
hugh-hackman[bot] c3d3989cdc ci: deploy polaris dashboard to E2E cluster (#34)
Adds Helm-based Polaris dashboard deployment step to E2E workflow, fixing the long-standing E2E failure where Polaris was not accessible in the CI cluster.
2026-03-10 23:50:37 +00:00
hugh-hackman[bot] 2012a34938 fix: improve E2E auth resilience and diagnostics (#33)
- Wait for Authentik popup to fully load (domcontentloaded + networkidle)
  before interacting with form elements
- Add explicit waitFor on username/password fields with 15s timeout
- Enable screenshot capture on test failure for better diagnostics
- Increase auth setup timeout to 60s to accommodate slow IdP responses

The auth setup was failing because the popup form elements weren't
ready when Playwright tried to fill them — this adds proper load
state waits between each interaction step.

Co-authored-by: gandalf-the-greybeard[bot] <gandalf-the-greybeard[bot]@users.noreply.github.com>
2026-03-10 07:31:27 +00:00
hugh-hackman[bot] 7603dfeb29 ci: improve E2E preflight with version mismatch detection (#32)
Enhances the preflight step to:
- Check the deployed plugin version against the repo version
- Emit a clear warning annotation when there's a mismatch
- Report the plugin name from artifacthub metadata
- Still runs tests (warning, not error) so we catch other issues

This makes plugin version mismatches immediately visible in the
CI summary instead of requiring investigators to dig through
14 timeout failures.

Co-authored-by: hugh-hackman[bot] <hugh-hackman[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 13:16:16 -04:00
null-pointer-nancy[bot] 9ad0b24580 Merge pull request #31 from privilegedescalation/fix/artifacthub-checksum-v070
fix: update artifacthub checksum for v0.7.0
2026-03-09 13:01:02 +00:00
Hugh Hackman acc9d8fac1 fix: update artifacthub checksum for v0.7.0 release 2026-03-09 10:43:25 +00:00
hugh-hackman[bot] 7413f699de release: bump version to v0.7.0 (#30)
Updates package.json and artifacthub-pkg.yml for the v0.7.0 release.
Includes all changes since v0.6.0:
- RBAC fix for Polaris dashboard proxy access (PR #22)
- Settings test selector fix (PR #22)
- Package name correction from solaris to polaris (PR #26)
- E2E preflight check (PR #24)
- Missing test dependencies (PR #28)

Co-authored-by: gandalf-the-greybeard[bot] <gandalf-the-greybeard[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 06:34:14 -04:00
gandalf-the-greybeard[bot] 497c040dbe fix: add missing test dependencies to devDependencies (#28)
vitest, @testing-library/react, @testing-library/user-event,
@testing-library/jest-dom, jsdom, react, react-dom, @mui/material,
and react-router-dom were all used directly but only available as
transitive dependencies through @kinvolk/headlamp-plugin. pnpm's
strict module resolution prevented them from being resolved.

Also adds process.env.NODE_ENV="test" to vitest config so React
loads its development build (required for act() support in tests).

Fixes #27

Co-authored-by: gandalf-the-greybeard[bot] <gandalf-the-greybeard[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 21:08:43 -04:00
hugh-hackman[bot] 29bc953522 ci: add E2E preflight check for Headlamp connectivity and plugin version (#24)
Adds a diagnostic step before E2E tests that:
- Logs the expected plugin version from package.json
- Verifies Headlamp is reachable (fails fast if not)
- Attempts to list installed plugins for debugging

This surfaces version mismatches and connectivity issues immediately
instead of requiring analysis of cryptic test timeout failures.

Co-authored-by: gandalf-the-greybeard[bot] <gandalf-the-greybeard[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 21:07:46 -04:00
gandalf-the-greybeard[bot] 0bd5223587 fix: correct package name from solaris to polaris (#26)
* ci: add E2E preflight check for Headlamp connectivity and plugin version

Adds a diagnostic step before E2E tests that:
- Logs the expected plugin version from package.json
- Verifies Headlamp is reachable (fails fast if not)
- Attempts to list installed plugins for debugging

This surfaces version mismatches and connectivity issues immediately
instead of requiring analysis of cryptic test timeout failures.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: correct package name from headlamp-solaris to headlamp-polaris

The package name was misspelled as "solaris" instead of "polaris" in
artifacthub-pkg.yml, package.json, and package-lock.json.

Fixes PRI-49

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: correct package name from headlamp-solaris to headlamp-polaris

Fixes the ArtifactHub package name typo introduced in 0.6.0.
Only changes the name field in artifacthub-pkg.yml, package.json,
and package-lock.json. No dependency or workflow changes.

Fixes #25

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: gandalf-the-greybeard[bot] <gandalf-the-greybeard[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 21:07:19 -04:00
hugh-hackman[bot] 2c441bf867 chore: rename Artifact Hub package to headlamp-solaris (#23)
Update package name and Artifact Hub repository ID to reflect the
rename from polaris to headlamp-solaris (new ID: 0243bdaf-c926-44dc-b411-a7c291bf1fcd).

Files updated:
- package.json: name polaris -> headlamp-solaris
- package-lock.json: name polaris -> headlamp-solaris
- artifacthub-pkg.yml: name headlamp-polaris-plugin -> headlamp-solaris
- artifacthub-repo.yml: repositoryID updated to new ID

Co-authored-by: gandalf-the-greybeard[bot] <gandalf-the-greybeard[bot]@users.noreply.github.com>
2026-03-08 22:08:53 +00:00
gandalf-the-greybeard[bot] 222346759e fix: E2E tests — RBAC for Polaris service proxy + settings selector (#22)
* fix: correct settings test selector to match plugin name

The settings E2E test looked for 'headlamp-polaris-plugin' but the
plugin is registered as 'polaris' (package.json name and
registerPluginSettings call). Fix the selector to match.

Refs: PRI-28

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* ci: add RBAC manifest for Polaris dashboard service proxy access

E2E tests fail with 403 because users lack RBAC to proxy to the Polaris
dashboard service. The plugin reads audit data via the K8s service proxy
at /api/v1/namespaces/polaris/services/http:polaris-dashboard:80/proxy/.

Add deployment/polaris-rbac.yaml with:
- Role granting `get` on `services/proxy` for polaris-dashboard
- RoleBinding granting this to all authenticated users (read-only)

The E2E workflow also needs a `kubectl apply -f deployment/polaris-rbac.yaml`
step added before running tests. This requires the `workflows` permission
on the GitHub App, which is tracked separately.

Refs: PRI-28

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* ci: add Polaris RBAC apply and readiness check to E2E workflow

The E2E tests fail because the CI runner lacks RBAC permissions to
proxy to the Polaris dashboard service. Apply the RBAC manifest
(added in this PR) and verify Polaris is reachable before running tests.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* ci: remove kubectl steps from E2E workflow

The CI runner (local-ubuntu-latest) has no kubectl or cluster access.
E2E tests are browser-only via Playwright against a remote Headlamp URL.
The Polaris RBAC fix (deployment/polaris-rbac.yaml) must be applied
directly to the cluster by an operator with kubectl access.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: gandalf-the-greybeard[bot] <gandalf-the-greybeard[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 22:08:51 +00:00
hugh-hackman[bot] d543e3bf9d feat: add upstream appVersion tracking to release workflow (#21)
Configures the reusable release workflow to fetch the latest release
tag from FairwindsOps/polaris and set appVersion in artifacthub-pkg.yml.
This keeps our Artifact Hub listing in sync with the upstream project.

Co-authored-by: Hugh Hackman <hugh@privilegedescalation.dev>
2026-03-08 13:10:00 -04:00
hugh-hackman[bot] 4e66a4b7cc Merge PR #20
Enable manual triggering of the CI workflow via GitHub Actions UI.
The release workflow already supports workflow_dispatch.

Co-authored-by: hugh-hackman[bot] <hugh-hackman[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 11:16:32 +00:00
gandalf-the-greybeard[bot] e800adfc19 fix: restore badge emoji, fix aria-label, and correct service proxy URL (#19)
* fix: restore badge emoji, fix aria-label, and correct service proxy URL

Three root causes for E2E test failures since March 4:

1. Service proxy URL missing http: protocol prefix — Kubernetes requires
   the format http:service-name:port, not service-name:port. This caused
   all data fetches to fail, making data-dependent components render
   empty states instead of expected content.

2. AppBarScoreBadge aria-label "Polaris cluster score: X%" doesn't match
   the E2E test regex /Polaris: \d+%/. Simplified to "Polaris: X%".

3. Shield emoji was removed from badge in commit 514de78 but E2E tests
   still assert its presence.

Fixes PRI-20

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* style: format polaris.ts to pass prettier check

The service proxy URL fix in 61bf1fe exceeded the line length limit.
Run prettier to split the long line.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: gandalf-the-greybeard[bot] <gandalf-the-greybeard[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 22:13:28 -05:00
hugh-hackman[bot] b3349b71d5 ci: switch to org-level reusable workflows (#18)
Co-authored-by: hugh-hackman[bot] <hugh-hackman[bot]@users.noreply.github.com>
2026-03-07 22:12:47 -05:00
hugh-hackman[bot] ceb7f31257 ci: align E2E workflow Node version to 22 (#17)
The CI and release workflows use Node 22, but E2E was still on Node 20.
This aligns all workflows to the same Node version for consistency.

Co-authored-by: gandalf-the-greybeard[bot] <gandalf-the-greybeard[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 22:12:30 -05:00
gandalf-the-greybeard[bot] 8f69329764 Enhance Renovate configuration (#16)
- Target main branch explicitly
- Set weekly schedule (weekends)
- Limit concurrent PRs to 10
- Group minor/patch updates for npm and github-actions to reduce PR noise

Ref: PRI-16

Co-authored-by: gandalf-the-greybeard[bot] <gandalf-the-greybeard[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 19:01:20 +00:00
Chris Farhood 0882d663fd chore: add LICENSE and FUNDING.yml (#14)
* chore: add Apache-2.0 LICENSE file

* chore: add FUNDING.yml
2026-03-07 10:37:37 -05:00
DevContainer User 6c7064faf0 docs: add architecture decision records for service proxy, error boundary, settings, and exemptions
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-05 13:49:56 +00:00
DevContainer User fb445954e0 Add artifacthub-headlamp agent skill
Adds Claude Code agent skill for ArtifactHub metadata and publishing,
sourced from headlamp-agent-skills repository.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 17:36:42 +00:00
github-actions[bot] 8bc6575ac3 release: v0.6.0 2026-03-04 17:03:10 +00:00
DevContainer User 514de78ba7 fix: comprehensive code quality, theming, and test coverage improvements
- Fix ExemptionManager apiVersion bug (apps/batch resources used wrong API path)
- Replace resource: any with proper KubeResource interface (strict TypeScript)
- Replace all var(--mui-palette-*) CSS variables with useTheme() + theme.palette.*
- Replace custom drawer with MUI Drawer component (proper a11y and theming)
- Replace alert() calls with StatusLabel-based inline feedback
- Add PolarisErrorBoundary wrapping all registered plugin components
- Export getPolarisApiPath/isFullUrl from polaris.ts, deduplicate in PolarisSettings
- Fix PolarisDataContext test mock missing triggerRefresh
- Fix DashboardView test SimpleTable mock using any
- Remove dead NamespaceDetailView (replaced by drawer), unused MockPolarisProvider,
  unused getSeverityColor export
- Add tests for InlineAuditSection, AppBarScoreBadge, topIssues, checkMapping (32 new)
- Update CLAUDE.md, CHANGELOG.md, README.md for v0.6.0

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 16:59:50 +00:00
DevContainer User 6dd64e87ce Add headlamp-plugin-developer agent skill
Adds Claude Code agent skill for Headlamp plugin development,
sourced from headlamp-agent-skills repository.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 12:26:52 +00:00
github-actions[bot] 9b9052243f release: v0.5.2 2026-03-04 02:44:40 +00:00
60 changed files with 16115 additions and 1646 deletions
+241
View File
@@ -0,0 +1,241 @@
---
name: artifacthub-headlamp
description: Use when working with ArtifactHub metadata, releases, or publishing for Headlamp plugins. Covers artifacthub-repo.yml, artifacthub-pkg.yml, Headlamp-specific annotations, and the release-to-publish workflow.
tools: Read, Write, Edit, Glob, Grep, Bash
model: sonnet
---
You are an expert in publishing Headlamp Kubernetes dashboard plugins to ArtifactHub. You understand exactly how ArtifactHub discovers and indexes Headlamp plugins, what metadata is required, and how the release workflow feeds into ArtifactHub listings.
Before editing any metadata files, read the existing `artifacthub-repo.yml`, `artifacthub-pkg.yml`, and `package.json` to understand the current state.
---
## How ArtifactHub Works (Critical Mental Model)
ArtifactHub is a **pull-based, read-only registry**. It periodically scrapes registered GitHub repositories for metadata. There is:
- **NO push API** — you cannot push packages to ArtifactHub
- **NO reconciliation trigger** — you cannot force ArtifactHub to re-scan
- **NO upload endpoint** — tarballs are hosted on GitHub Releases, not ArtifactHub
- **NO webhook integration** — ArtifactHub polls on its own schedule (~30 min)
**The only interface is two YAML files committed to git.** ArtifactHub reads them, and that's it.
---
## Repository Registration
### artifacthub-repo.yml (root of repo)
This file registers the GitHub repository with ArtifactHub. Created once, rarely changed.
```yaml
# Artifact Hub repository metadata file
# https://github.com/artifacthub/hub/blob/master/docs/metadata/artifacthub-repo.yml
repositoryID: <uuid> # Assigned by ArtifactHub when you add the repo via the web UI
owners:
- name: <github-username-or-org>
email: <email>
```
**How to get the repositoryID:**
1. Log into artifacthub.io
2. Go to Control Panel → Repositories → Add
3. Select repository kind: "Headlamp plugins"
4. Provide the GitHub repo URL
5. ArtifactHub generates the UUID — copy it into this file
You do NOT generate this UUID yourself. It comes from ArtifactHub's web UI.
---
## Package Metadata
### artifacthub-pkg.yml (root of repo)
This is the primary metadata file that defines how the plugin appears on ArtifactHub. Updated with each release.
```yaml
version: "X.Y.Z" # MUST match package.json version
name: <package-name> # npm package name from package.json
displayName: <Human Readable Name> # Shown on ArtifactHub listing
createdAt: "YYYY-MM-DDTHH:MM:SSZ" # ISO 8601 — update each release
description: >-
Multi-line description of what the plugin does.
Be specific about features and requirements.
license: Apache-2.0
homeURL: https://github.com/<owner>/<repo>
appVersion: "X.Y.Z" # Version of upstream project (optional)
category: <category> # See categories below
keywords:
- headlamp
- kubernetes
- <plugin-specific>
maintainers:
- name: <name>
email: <email>
provider:
name: <name>
links:
- name: GitHub
url: https://github.com/<owner>/<repo>
- name: Issues
url: https://github.com/<owner>/<repo>/issues
changes: # Changelog for this version
- kind: added|changed|fixed|removed
description: "What changed"
annotations: # CRITICAL — Headlamp-specific
headlamp/plugin/archive-url: "https://github.com/<owner>/<repo>/releases/download/v<VERSION>/<pkgname>-<VERSION>.tar.gz"
headlamp/plugin/archive-checksum: "sha256:<checksum>"
headlamp/plugin/version-compat: ">=X.Y.Z"
headlamp/plugin/distro-compat: "<targets>"
```
---
## Headlamp-Specific Annotations (Required)
These annotations in `artifacthub-pkg.yml` are what make ArtifactHub treat the package as a Headlamp plugin:
### headlamp/plugin/archive-url
**Required.** Direct download URL to the plugin tarball on GitHub Releases.
Format: `https://github.com/<owner>/<repo>/releases/download/v<VERSION>/<pkgname>-<VERSION>.tar.gz`
- The tarball is built by `npx @kinvolk/headlamp-plugin build` and then `npx @kinvolk/headlamp-plugin package`
- The `<pkgname>` comes from `package.json` `name` field
- The tarball is uploaded as a GitHub Release asset — NOT to ArtifactHub
### headlamp/plugin/archive-checksum
**Recommended.** SHA256 checksum of the tarball.
Format: `sha256:<hex-digest>`
Generated via: `sha256sum <tarball> | awk '{print $1}'`
Can be empty string if not yet computed (release workflow fills it in).
### headlamp/plugin/version-compat
**Required.** Minimum Headlamp version the plugin works with.
Format: `>=X.Y.Z` (e.g., `>=0.20.0`, `>=0.26`)
### headlamp/plugin/distro-compat
**Required.** Comma-separated list of supported Headlamp deployment targets.
Valid values:
- `in-cluster` — Headlamp running inside a Kubernetes cluster
- `web` — Web-based Headlamp deployment
- `app` — Headlamp desktop application (Electron)
- `desktop` — Alias for desktop app
- `docker-desktop` — Docker Desktop Headlamp extension
Example: `"in-cluster,web,app"`
---
## ArtifactHub Categories
Valid `category` values for Headlamp plugins:
- `security` — Secrets, RBAC, policy enforcement
- `storage` — CSI drivers, persistent volumes, Ceph/Rook
- `monitoring-logging` — Metrics, GPU monitoring, observability
- `networking` — Load balancers, virtual IPs, ingress
---
## Optional Fields
### containersImages
For plugins associated with a specific container/operator:
```yaml
containersImages:
- name: <component-name>
image: docker.io/<org>/<image>:<tag>
```
### recommendations
Link to related ArtifactHub packages:
```yaml
recommendations:
- url: https://artifacthub.io/packages/helm/<repo>/<chart>
```
### install
Custom installation instructions (markdown):
```yaml
install: |
## Install via Headlamp Plugin Manager
...
```
### logoPath
Path to a logo image file in the repo (relative to root).
---
## The Release → ArtifactHub Pipeline
This is the actual flow. There is NO other way to publish:
```
1. Developer triggers release workflow (workflow_dispatch with version)
2. CI runs tests
3. Workflow updates:
- package.json (npm version)
- artifacthub-pkg.yml (version, archive-url, checksum, createdAt, changes)
4. Plugin is built: npx @kinvolk/headlamp-plugin build
5. Plugin is packaged: creates <pkgname>-<version>.tar.gz
6. SHA256 checksum is computed and written to artifacthub-pkg.yml
7. Changes committed to main
8. Git tag created: v<version>
9. GitHub Release created with tarball attached
10. ArtifactHub polls the repo (~30 min) and picks up the new metadata
11. Plugin appears/updates on artifacthub.io
```
**Key points:**
- Steps 1-9 happen in your GitHub Actions workflow
- Step 10 is entirely controlled by ArtifactHub — you cannot trigger it
- The tarball lives on GitHub Releases, not ArtifactHub
- ArtifactHub only reads `artifacthub-pkg.yml` to discover the download URL
---
## Common Mistakes to Avoid
1. **Trying to push/trigger ArtifactHub** — There is no API for this. Just commit metadata and wait.
2. **Version mismatch**`version` in `artifacthub-pkg.yml` MUST match `package.json`. The release workflow should update both.
3. **Wrong archive-url** — Must point to the actual GitHub Release asset URL. Verify the tarball filename matches what the build produces.
4. **Missing checksum** — While optional, missing checksums may cause warnings. The release workflow should compute and write it.
5. **Forgetting createdAt** — Must be updated each release. ArtifactHub uses this for sorting.
6. **Stale changes section** — The `changes` list should reflect the current version's changelog only, not cumulative history.
7. **Assuming ArtifactHub hosts anything** — It's an index/catalog. All artifacts are hosted elsewhere (GitHub Releases).
8. **Trying to generate repositoryID** — This UUID comes from ArtifactHub's web UI when you register the repo. Don't make one up.
---
## Tarball Structure
The plugin tarball built by `@kinvolk/headlamp-plugin` contains:
```
<pkgname>/
main.js # Bundled plugin code
package.json # Plugin metadata
```
The `<pkgname>` directory inside the tarball matches the `name` field from `package.json`.
---
## Validating Metadata
Before committing, check:
1. `version` matches across `package.json` and `artifacthub-pkg.yml`
2. `archive-url` version tag matches the `version` field
3. `name` in `artifacthub-pkg.yml` matches `package.json` `name`
4. `createdAt` is a valid ISO 8601 timestamp
5. All required annotations are present
6. `changes` entries use valid `kind` values: `added`, `changed`, `fixed`, `removed`
+320
View File
@@ -0,0 +1,320 @@
---
name: headlamp-plugin-developer
description: Use when building, extending, debugging, or reviewing Headlamp Kubernetes dashboard plugins. Covers registration APIs, CommonComponents, CRD integration, testing mocks, and codebase conventions.
tools: Read, Write, Edit, Glob, Grep, Bash, WebFetch, WebSearch
model: sonnet
---
You are a senior Headlamp plugin engineer. You produce code matching this codebase's exact conventions. Before writing new code, read `CLAUDE.md` and review existing files in `src/` to understand established patterns.
---
## Plugin Registration Functions
All from `@kinvolk/headlamp-plugin/lib`:
```typescript
registerRoute({
path: string; // React Router path (e.g., '/myresource/:namespace?/:name?')
sidebar?: string; // Sidebar entry name to highlight
component: () => JSX.Element; // Arrow function wrapper required
exact?: boolean;
name?: string; // Used by Link's routeName prop
}): void
registerSidebarEntry({
parent: string | null; // null = top-level
name: string;
label: string;
url: string;
icon?: string; // Iconify ID (e.g., 'mdi:lock')
}): void
registerDetailsViewSection(
(props: { resource: KubeObjectInterface }) => JSX.Element | null
): void
// Runs for ALL resource detail views — MUST check resource?.kind
registerDetailsViewHeaderAction(
(props: { resource: KubeObjectInterface }) => JSX.Element | null
): void
registerResourceTableColumnsProcessor(
(args: { id: string; columns: Column[] }) => Column[]
): void
// id examples: 'headlamp-storageclasses', 'headlamp-persistentvolumes'
registerPluginSettings(
pluginName: string,
component: React.ComponentType<{
data?: Record<string, string | number | boolean>;
onDataChange?: (data: Record<string, string | number | boolean>) => void;
}>,
showSaveButton?: boolean
): void
// Also available but less commonly used:
registerAppBarAction(component): void
registerAppLogo(component): void
registerClusterChooser(component): void
registerSidebarEntryFilter(filter): void
registerRouteFilter(filter): void
registerDetailsViewSectionsProcessor(fn): void
registerHeadlampEventCallback(callback): void
registerAppTheme(theme): void
registerUIPanel(panel): void
```
---
## K8s Module
```typescript
import { K8s } from '@kinvolk/headlamp-plugin/lib';
```
### KubeObject Base Class
```typescript
class KubeObject<T extends KubeObjectInterface> {
jsonData: T; // Raw K8s JSON — use this for spec/status access
metadata: KubeMetadata;
kind: string;
getAge(): string;
getName(): string;
getNamespace(): string | undefined;
delete(force?: boolean): Promise<void>;
patch(body: RecursivePartial<T>): Promise<void>;
static useGet(name?, namespace?): [item: T | null, error: ApiError | null];
static useList(opts?: { namespace?: string }): [items: T[], error: ApiError | null, loading: boolean];
static apiEndpoint: ApiClient | ApiWithNamespaceClient;
static className: string;
}
```
**CRITICAL**: Resource hooks return class instances. Raw K8s JSON lives under `.jsonData`. Access fields via `.jsonData.spec`, `.jsonData.status`, or typed getters.
### ResourceClasses
All standard K8s resource types available (Secret, Namespace, Pod, etc.):
```typescript
const [secrets, error, loading] = K8s.ResourceClasses.Secret.useList({ namespace: 'default' });
const [secret, error] = K8s.ResourceClasses.Secret.useGet('my-secret', 'default');
```
---
## ApiProxy
```typescript
import { ApiProxy } from '@kinvolk/headlamp-plugin/lib';
ApiProxy.request(
path: string,
options?: {
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
body?: string; // JSON.stringify'd
isJSON?: boolean; // false for non-JSON (logs, metrics)
headers?: Record<string, string>;
}
): Promise<unknown>
// CRD endpoint factories
ApiProxy.apiFactoryWithNamespace(group, version, resource): ApiWithNamespaceClient
ApiProxy.apiFactory(group, version, resource): ApiClient
```
**Service proxy URL** (accessing in-cluster services):
```
/api/v1/namespaces/${ns}/services/http:${name}:${port}/proxy${path}
```
---
## CommonComponents
From `@kinvolk/headlamp-plugin/lib/CommonComponents`:
`SectionBox` — container with title and optional `headerProps.actions`
`SectionHeader` — standalone header with title and actions array
`SectionFilterHeader` — header with namespace filter; `noNamespaceFilter` to hide it; `actions` array
`StatusLabel` — status chip; `status`: `'success' | 'error' | 'warning' | 'info'`
`Link` — internal nav; `routeName` + `params` object
`Loader` — spinner with `title` prop
`PercentageBar` — bar chart with `data` array of `{ name, value, fill }`
### SimpleTable (non-obvious props)
```typescript
<SimpleTable
data={items}
columns={[
{ label: 'Name', getter: (item) => item.metadata.name },
{ label: 'Status', getter: (item) => <StatusLabel status="success">Ready</StatusLabel> },
]}
emptyMessage="No items found."
/>
```
### NameValueTable (non-obvious props)
```typescript
<NameValueTable
rows={[
{ name: 'Key', value: 'display value' },
{ name: 'Hidden', value: 'x', hide: true },
]}
/>
```
### ConfigStore
```typescript
import { ConfigStore } from '@kinvolk/headlamp-plugin/lib';
const store = new ConfigStore<MyConfig>('plugin-name');
store.get(): MyConfig;
store.update(partial: Partial<MyConfig>): void;
store.useConfig(): () => MyConfig;
```
### Pre-bundled (no package.json entry needed)
react, react-dom, react-router-dom, @iconify/react, react-redux, @material-ui/core, @material-ui/styles, lodash, notistack, recharts, monaco-editor
---
## CRD Class Pattern
```typescript
import { ApiProxy, K8s } from '@kinvolk/headlamp-plugin/lib';
const { apiFactoryWithNamespace } = ApiProxy;
const { KubeObject } = K8s.cluster;
type KubeObjectInterface = K8s.cluster.KubeObjectInterface;
interface MyResourceInterface extends KubeObjectInterface {
spec: MySpec;
status?: MyStatus;
}
export class MyResource extends KubeObject<MyResourceInterface> {
static apiEndpoint = apiFactoryWithNamespace('mygroup.io', 'v1', 'myresources');
static get className(): string { return 'MyResource'; }
get spec(): MySpec { return this.jsonData.spec; }
get status(): MyStatus | undefined { return this.jsonData.status; }
}
```
---
## Plugin Entry Point Pattern
```typescript
// 1. Sidebar (parent → children)
registerSidebarEntry({ parent: null, name: 'my-plugin', label: 'My Plugin', icon: 'mdi:icon', url: '/mypath' });
registerSidebarEntry({ parent: 'my-plugin', name: 'my-list', label: 'Resources', url: '/mypath' });
// 2. Routes wrapped in ApiErrorBoundary
registerRoute({
path: '/mypath/:namespace?/:name?',
sidebar: 'my-list',
component: () => <ApiErrorBoundary><MyListPage /></ApiErrorBoundary>,
exact: true, name: 'my-resource',
});
// 3. Detail injection wrapped in GenericErrorBoundary
registerDetailsViewSection(({ resource }) => {
if (resource?.kind !== 'Secret') return null;
return <GenericErrorBoundary><MySection resource={resource} /></GenericErrorBoundary>;
});
// 4. Settings
registerPluginSettings('my-plugin', SettingsPage, true);
```
---
## Headlamp Test Mocks
```typescript
vi.mock('@kinvolk/headlamp-plugin/lib', () => ({
ApiProxy: { request: vi.fn().mockResolvedValue({}) },
K8s: { ResourceClasses: {}, cluster: { KubeObject: class {} } },
}));
vi.mock('@kinvolk/headlamp-plugin/lib/CommonComponents', () => ({
SectionBox: ({ children, title }: any) => <div data-testid="section-box">{title}{children}</div>,
SimpleTable: ({ data, columns }: any) => (
<table><tbody>{data.map((d: any, i: number) =>
<tr key={i}>{columns.map((c: any, j: number) => <td key={j}>{c.getter(d)}</td>)}</tr>
)}</tbody></table>
),
NameValueTable: ({ rows }: any) => (
<dl>{rows.filter((r: any) => !r.hide).map((r: any) =>
<div key={r.name}><dt>{r.name}</dt><dd>{r.value}</dd></div>
)}</dl>
),
StatusLabel: ({ children, status }: any) => <span data-status={status}>{children}</span>,
Link: ({ children }: any) => <a>{children}</a>,
Loader: ({ title }: any) => <div data-testid="loader">{title}</div>,
}));
```
---
## Theming & Dark Mode
Headlamp supports light and dark themes. **Never hardcode colors.** Use CSS custom properties with light-mode fallbacks:
### Required CSS variables for inline styles
```typescript
// Text
color: 'var(--mui-palette-text-primary)'
color: 'var(--mui-palette-text-secondary, #666)'
// Backgrounds
backgroundColor: 'var(--mui-palette-background-default, #fafafa)'
backgroundColor: 'var(--mui-palette-background-paper, #fff)'
// Borders
border: '1px solid var(--mui-palette-divider, #e0e0e0)'
// Interactive
backgroundColor: 'var(--mui-palette-primary-main, #1976d2)'
color: 'var(--mui-palette-primary-contrastText, #fff)'
// Disabled states
backgroundColor: 'var(--mui-palette-action-disabledBackground, #e0e0e0)'
color: 'var(--mui-palette-action-disabled, #9e9e9e)'
// Links
color: 'var(--link-color, #1976d2)'
```
### Common mistakes to avoid
- **NEVER** use raw `#fff`, `#000`, `#333`, `#666` etc. without wrapping in `var(--mui-palette-*)`
- **NEVER** use `rgba(0,0,0,0.5)` for overlays without a variable — this is the one exception where raw rgba is acceptable (backdrop overlays)
- **NEVER** assume white backgrounds or dark text — always use `background-paper`/`text-primary`
- For `<style>` blocks (drawers, etc.), use the same CSS variables in the stylesheet
- Fallback values after the comma are for environments where the variable isn't set — always use the light-mode default
### Form inputs in custom components
```typescript
const inputStyle = {
border: '1px solid var(--mui-palette-divider, #ccc)',
borderRadius: '4px',
backgroundColor: 'var(--mui-palette-background-paper)',
color: 'var(--mui-palette-text-primary)',
};
```
---
## Code Quality Rules
1. **Functional components only** — no class components (except ErrorBoundary)
2. **TypeScript strict mode** — no `any`; use `unknown` + type guards at API boundaries
3. **Headlamp CommonComponents + MUI**`@mui/material` is available via Headlamp's bundled deps; no other UI libraries (no Ant Design, etc.)
4. **Inline CSS only**`style={{}}` props, CSS variables (`var(--mui-palette-*)`) for theming
5. **Accessibility**`aria-label`, `aria-modal`, `role="dialog"`, `aria-live` for dynamic content
6. **Cancellation safety** — async effects must check a `cancelled` flag
7. **Error handling** — Result types in lib/, ErrorBoundaries wrapping components (ApiErrorBoundary for routes, GenericErrorBoundary for injected sections)
8. **Tests** — vitest + @testing-library/react, mock Headlamp APIs per above pattern
9. Run `npm run tsc` and `npm test` after implementation changes
+1
View File
@@ -0,0 +1 @@
github: [privilegedescalation]
+2 -30
View File
@@ -5,37 +5,9 @@ on:
branches: [main]
pull_request:
branches: [main]
workflow_dispatch:
workflow_call:
jobs:
ci:
runs-on: local-ubuntu-latest
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build plugin
run: npx @kinvolk/headlamp-plugin build
- name: Lint
run: npm run lint
- name: Type-check
run: npm run tsc
- name: Format check
run: npm run format:check
- name: Run tests
run: npm test
uses: privilegedescalation/.github/.github/workflows/plugin-ci.yaml@main
+18
View File
@@ -0,0 +1,18 @@
name: Dual Approval (CTO + QA)
# Calls the shared dual-approval-check workflow.
# Passes when both privilegedescalation-cto and privilegedescalation-qa
# have approved the PR. Add "Dual Approval (CTO + QA)" to required_status_checks
# in branch protection to enforce this gate.
on:
pull_request_review:
types: [submitted, dismissed]
pull_request:
branches: [main]
types: [opened, reopened, synchronize]
jobs:
dual-approval:
uses: privilegedescalation/.github/.github/workflows/dual-approval-check.yaml@main
secrets: inherit
+47 -10
View File
@@ -7,37 +7,74 @@ on:
branches: [main]
workflow_dispatch:
permissions:
contents: read
# Serialize E2E runs repo-wide. All concurrent runs share the same
# E2E_RELEASE name (headlamp-e2e) in a single namespace. Without
# serialization, one run's teardown (if: always()) deletes the
# deployment while a concurrent run is still using it, causing auth
# setup timeouts. cancel-in-progress: false queues rather than kills
# to avoid leaving dangling cluster resources.
concurrency:
group: e2e-${{ github.repository }}
cancel-in-progress: false
env:
E2E_NAMESPACE: privilegedescalation-dev
E2E_RELEASE: headlamp-e2e
jobs:
e2e:
runs-on: local-ubuntu-latest
runs-on: runners-privilegedescalation
timeout-minutes: 15
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
- name: Setup Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version: '20'
node-version: '22'
cache: 'npm'
- name: Setup kubectl
uses: azure/setup-kubectl@v4
- name: Install dependencies
run: npm ci
- name: Build plugin
run: npx @kinvolk/headlamp-plugin build
- name: Deploy E2E Headlamp instance
run: scripts/deploy-e2e-headlamp.sh
- name: Load E2E environment
run: |
if [ -f .env.e2e ]; then
cat .env.e2e >> "$GITHUB_ENV"
else
echo "::error::deploy-e2e-headlamp.sh did not produce .env.e2e"
exit 1
fi
- name: Install Playwright browsers
run: npx playwright install --with-deps chromium
- name: Run E2E tests
run: npm run e2e
env:
HEADLAMP_URL: ${{ secrets.HEADLAMP_URL || 'http://headlamp.kube-system.svc.cluster.local' }}
HEADLAMP_TOKEN: ${{ secrets.HEADLAMP_TOKEN }}
AUTHENTIK_USERNAME: ${{ secrets.AUTHENTIK_USERNAME }}
AUTHENTIK_PASSWORD: ${{ secrets.AUTHENTIK_PASSWORD }}
HEADLAMP_URL: ${{ env.HEADLAMP_URL }}
HEADLAMP_TOKEN: ${{ env.HEADLAMP_TOKEN }}
- name: Teardown E2E instance
if: always()
run: scripts/teardown-e2e-headlamp.sh
- name: Upload Playwright report
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
if: failure()
with:
name: playwright-report
@@ -45,7 +82,7 @@ jobs:
retention-days: 7
- name: Upload test results
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
if: failure()
with:
name: test-results
+8 -91
View File
@@ -10,97 +10,14 @@ on:
permissions:
contents: write
concurrency:
group: release
cancel-in-progress: false
pull-requests: write
jobs:
ci:
uses: ./.github/workflows/ci.yaml
release:
needs: ci
runs-on: local-ubuntu-latest
timeout-minutes: 10
steps:
- name: Validate version format
run: |
if [[ ! "${{ inputs.version }}" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "Error: Version must be in X.Y.Z format"
exit 1
fi
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
cache: 'npm'
- name: Configure Git
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
- name: Update version in package.json
run: npm version ${{ inputs.version }} --no-git-tag-version --allow-same-version
- name: Update artifacthub-pkg.yml
run: |
VERSION="${{ inputs.version }}"
PKG_NAME=$(jq -r .name package.json)
RELEASE_URL="https://github.com/${{ github.repository }}/releases/download/v${VERSION}/${PKG_NAME}-${VERSION}.tar.gz"
sed -i "s/^version:.*/version: \"${VERSION}\"/" artifacthub-pkg.yml
sed -i "s|headlamp/plugin/archive-url:.*|headlamp/plugin/archive-url: \"${RELEASE_URL}\"|" artifacthub-pkg.yml
- name: Install dependencies
run: npm ci
- name: Build plugin
run: npx @kinvolk/headlamp-plugin build
- name: Package plugin
run: npx @kinvolk/headlamp-plugin package
- name: Prepare release tarball
run: |
VERSION="${{ inputs.version }}"
PKG_NAME=$(jq -r .name package.json)
TARBALL="${PKG_NAME}-${VERSION}.tar.gz"
echo "TARBALL=$TARBALL" >> $GITHUB_ENV
echo "PKG_NAME=$PKG_NAME" >> $GITHUB_ENV
- name: Validate tarball
run: |
echo "Tarball: ${{ env.TARBALL }}"
ls -lh "${{ env.TARBALL }}"
tar -tzf "${{ env.TARBALL }}" | head -20
tar -tzf "${{ env.TARBALL }}" | grep -q "main.js" || { echo "Error: main.js not found in tarball"; exit 1; }
- name: Compute checksum
run: |
CHECKSUM=$(sha256sum "${{ env.TARBALL }}" | awk '{print $1}')
echo "CHECKSUM=$CHECKSUM" >> $GITHUB_ENV
sed -i "s|headlamp/plugin/archive-checksum:.*|headlamp/plugin/archive-checksum: sha256:${CHECKSUM}|" artifacthub-pkg.yml
- name: Commit and tag
run: |
VERSION="${{ inputs.version }}"
git add package.json package-lock.json artifacthub-pkg.yml
git commit -m "release: v${VERSION}"
git tag "v${VERSION}"
git push origin main --tags
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: "v${{ inputs.version }}"
files: ${{ env.TARBALL }}
fail_on_unmatched_files: true
generate_release_notes: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
uses: privilegedescalation/.github/.github/workflows/plugin-release.yaml@main
secrets:
RELEASE_APP_ID: ${{ secrets.RELEASE_APP_ID }}
RELEASE_APP_PRIVATE_KEY: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
with:
version: ${{ inputs.version }}
upstream-repo: 'FairwindsOps/polaris'
+1
View File
@@ -6,5 +6,6 @@ e2e/.auth/
test-results/
.playwright-mcp/
.env
.env.e2e
.env.local
.eslintcache
+56 -1
View File
@@ -7,6 +7,59 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [1.0.0] - 2026-03-22
First stable release. The plugin API (routes, sidebar entries, settings schema, and app bar action) is
now frozen — no breaking changes without a new major version.
### Security
- Patched 8 of 9 npm audit vulnerabilities via `pnpm.overrides` (#92)
### Added
- **Dual-approval CI check**: PRs now require approval from both CTO and QA before merging (#98, #76)
- **ExemptionManager test suite**: Full coverage of annotation-based exemption flows, exemption creation, and inline feedback (#82)
- **RBAC preflight check**: `deploy-e2e-headlamp.sh` now verifies runner RBAC before attempting E2E deploy (#80)
### Fixed
- **E2E infrastructure overhaul**: Replaced Dockerfile.e2e with ConfigMap volume mount for plugin loading; tests now run in the `privilegedescalation-dev` namespace (#73, #89, #94)
- **E2E token auth**: Workflow uses GitHub App token auth and handles the `/token` redirect correctly (#97)
- **E2E HTTP readiness**: `deploy-e2e-headlamp.sh` waits for HTTP reachability after rollout before running tests (#104)
- **E2E runner label**: Updated to `runners-privilegedescalation` for self-hosted ARC runners (#71)
- **Direct devDependencies**: Added `typescript`, `eslint`, `prettier`, and `@headlamp-k8s/eslint-config` as explicit direct devDependencies to prevent phantom-dep failures in clean installs (#95, #102)
### Changed
- **pnpm version pinned**: `packageManager` field in `package.json` pins the pnpm version used in CI (#103)
- **GitHub Actions SHA pinning**: Renovate `pinDigests` enabled to SHA-pin all GitHub Actions (#105)
- **ArtifactHub metadata polish**: Improved `install` instructions and `changes` section formatting (#82)
## [0.6.0] - 2026-03-04
### Fixed
- **ExemptionManager apiVersion bug**: `apps` and `batch` resources now correctly use `/apis/{group}/v1/` instead of the broken `/api/v1/` path
- **Strict TypeScript**: Replaced `resource: any` in InlineAuditSection with proper `KubeResource` interface
- **PolarisDataContext test mock**: Added missing `triggerRefresh` to mock, preventing silent `undefined` for `refresh` in context
- **DashboardView test**: Fixed `SimpleTable` mock that used `Array<any>` and didn't exercise column getters
### Changed
- **Dark mode / theming**: Replaced all `var(--mui-palette-*)` CSS variables with `useTheme()` + `theme.palette.*` across all components (DashboardView, NamespacesListView, InlineAuditSection, ExemptionManager, PolarisSettings, AppBarScoreBadge)
- **Namespace drawer**: Replaced custom `<style>` block + positioned `<div>` with MUI `Drawer` component for proper accessibility (`role="dialog"`, `aria-modal`, Escape key handling via MUI)
- **AppBarScoreBadge**: Uses `theme.palette.success/warning/error` with proper `contrastText` instead of hardcoded hex colors
- **ExemptionManager feedback**: Replaced `alert()` calls with `StatusLabel`-based inline feedback; removed dead `getExemptions()` stub and unreachable remove-exemption UI
- **URL construction**: Exported `getPolarisApiPath` and `isFullUrl` from `polaris.ts`; PolarisSettings now reuses them instead of duplicating logic
### Added
- **Error boundaries**: All registered components (routes, detail sections, app bar action) wrapped in `PolarisErrorBoundary` for graceful error rendering
- **Tests for InlineAuditSection** (7 tests): loading, unsupported kind, not found, score/summary, failing checks, link, exemption manager
- **Tests for AppBarScoreBadge** (6 tests): loading, no data, score colors, navigation, aria-label
- **Tests for topIssues.ts** (8 tests): empty, all pass, controller/pod/container results, counting, ignore filter, sorting, max 10
- **Tests for checkMapping.ts** (11 tests): name/description/category/severity lookups, unknown checks, CHECK_MAPPING structure validation
### Removed
- **NamespaceDetailView.tsx**: Dead code with no registered route (replaced by drawer in NamespacesListView)
- **NamespaceDetailView.test.tsx**: Tests for removed component
- **MockPolarisProvider in test-utils.tsx**: Unused mock provider (tests use `vi.mock` instead)
- **`getSeverityColor` export in checkMapping.ts**: Dead export not imported anywhere
## [0.3.5] - 2026-02-12
### Fixed
@@ -242,7 +295,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Automated release workflow
- Basic CI/CD pipeline
[Unreleased]: https://github.com/privilegedescalation/headlamp-polaris-plugin/compare/v0.3.5...HEAD
[Unreleased]: https://github.com/privilegedescalation/headlamp-polaris-plugin/compare/v1.0.0...HEAD
[1.0.0]: https://github.com/privilegedescalation/headlamp-polaris-plugin/compare/v0.7.2...v1.0.0
[0.6.0]: https://github.com/privilegedescalation/headlamp-polaris-plugin/releases/tag/v0.6.0
[0.3.5]: https://github.com/privilegedescalation/headlamp-polaris-plugin/releases/tag/v0.3.5
[0.3.4]: https://github.com/privilegedescalation/headlamp-polaris-plugin/releases/tag/v0.3.4
[0.3.3]: https://github.com/privilegedescalation/headlamp-polaris-plugin/releases/tag/v0.3.3
+11 -9
View File
@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Project
Headlamp plugin surfacing Fairwinds Polaris audit results. Queries the Polaris dashboard API via Kubernetes service proxy (`/api/v1/namespaces/polaris/services/polaris-dashboard/proxy/results.json`). Read-only — no cluster write operations except exemption annotation patches.
Headlamp plugin surfacing Fairwinds Polaris audit results. Queries the Polaris dashboard API via Kubernetes service proxy (`/api/v1/namespaces/polaris/services/http:polaris-dashboard:80/proxy/results.json`). Read-only — no cluster write operations except exemption annotation patches.
- **Plugin name**: `polaris`
- **Target**: Headlamp >= v0.26
@@ -35,17 +35,16 @@ All tests and `tsc` must pass before committing.
```
src/
├── index.tsx # Plugin entry: registerRoute, registerSidebarEntry, registerDetailsViewSection, registerAppBarAction, registerPluginSettings
├── test-utils.tsx # Shared test utilities
├── index.tsx # Plugin entry: registerRoute, registerSidebarEntry, registerDetailsViewSection, registerAppBarAction, registerPluginSettings; PolarisErrorBoundary
├── test-utils.tsx # Shared test fixtures (makeResult, makeAuditData)
├── api/
│ ├── polaris.ts # Types (AuditData schema), countResults utilities, refresh settings
│ ├── polaris.ts # Types (AuditData schema), countResults utilities, refresh settings, getPolarisApiPath, isFullUrl
│ ├── checkMapping.ts # Polaris check ID → human-readable name mapping
│ ├── topIssues.ts # Top failing checks aggregation logic
│ └── PolarisDataContext.tsx # Shared React context provider (ApiProxy.request + configurable refresh)
└── components/
├── DashboardView.tsx # Overview page (score gauge, check distribution, top failing checks)
├── NamespacesListView.tsx # Namespace list with per-namespace scores
├── NamespaceDetailView.tsx # Per-namespace drill-down with resource table
├── NamespacesListView.tsx # Namespace list with per-namespace scores + MUI Drawer detail panel
├── InlineAuditSection.tsx # Injected into Deployment/StatefulSet/DaemonSet/Job/CronJob detail views
├── ExemptionManager.tsx # Polaris exemption annotation management
├── AppBarScoreBadge.tsx # App bar cluster score chip
@@ -60,12 +59,15 @@ Data is fetched via `ApiProxy.request` to the Polaris dashboard service proxy an
## Code conventions
- Functional React components only — no class components
- Functional React components only — class components only for error boundaries (PolarisErrorBoundary in index.tsx)
- All imports from `@kinvolk/headlamp-plugin/lib` and `@kinvolk/headlamp-plugin/lib/CommonComponents`
- No additional UI libraries (no MUI direct imports, no Ant Design, etc.)
- `@mui/material` is available as a shared external via Headlamp — use `useTheme` from `@mui/material/styles` for theming, MUI `Drawer`/`IconButton` etc. as needed. Do NOT add `@mui/material` to package.json dependencies.
- Use `useTheme()` + `theme.palette.*` for all theme-aware colors — never use `var(--mui-palette-*)` CSS variables
- No other UI libraries (no Ant Design, etc.)
- TypeScript strict mode — no `any`, use `unknown` + type guards at API boundaries
- Context provider (`PolarisDataProvider`) wraps each route component in `index.tsx`
- Tests: vitest + @testing-library/react, mock with `vi.mock('@kinvolk/headlamp-plugin/lib', ...)`
- All registered components wrapped in `PolarisErrorBoundary` for graceful error handling
- Tests: vitest + @testing-library/react, mock with `vi.mock('@kinvolk/headlamp-plugin/lib', ...)` and `vi.mock('@mui/material/styles', ...)`
- `vitest.setup.ts` provides a spec-compliant `localStorage` shim for Node 22+ compatibility
## Testing
+24
View File
@@ -0,0 +1,24 @@
# Installation Policy
## Approved Installation Method
**The ONLY approved method for installing this plugin is via [Artifact Hub](https://artifacthub.io/) using the Headlamp plugin installer.**
No other installation method is acceptable. This includes but is not limited to:
- Direct installation from GitHub release assets
- Manual npm pack / tarball extraction
- initContainer workarounds that bypass Artifact Hub
- Direct file copy or sidecar injection
## Enforcement
All deployment configurations, CI/CD pipelines, and documentation MUST reference Artifact Hub as the sole plugin distribution channel. Any pull request that introduces an alternative installation method will be rejected.
## Rationale
Artifact Hub provides verified checksums, consistent versioning, and a standard discovery mechanism for the CNCF ecosystem. Bypassing it introduces security and integrity risks.
---
*This policy is set by the CTO and approved by the CEO of Privileged Escalation.*
+73
View File
@@ -0,0 +1,73 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+18 -59
View File
@@ -26,7 +26,7 @@ Adds a **Polaris** top-level sidebar section to Headlamp with comprehensive secu
- **Exemption Management** -- add or remove Polaris exemptions via annotation patches directly from the UI; supports per-check exemptions or exempt-all
- **Configurable Dashboard URL** -- supports both Kubernetes service proxy URLs and full HTTP/HTTPS URLs for external Polaris deployments
- **Connection Testing** -- test button in settings to verify Polaris dashboard connectivity and show version info
- **Dark Mode Support** -- full theme adaptation using MUI CSS variables; drawer, settings, and all UI elements respect system/Headlamp theme
- **Dark Mode Support** -- full theme adaptation using MUI `useTheme()` API; drawer, settings, and all UI elements respect system/Headlamp theme
### Data & Refresh
@@ -48,9 +48,14 @@ Polaris must be deployed in the `polaris` namespace with the dashboard component
## Installing
### Option 1: Headlamp Plugin Manager (Recommended)
The plugin is published on [Artifact Hub](https://artifacthub.io/packages/headlamp/polaris/headlamp-polaris-plugin). Install via the Headlamp UI:
The plugin is published on [Artifact Hub](https://artifacthub.io/packages/headlamp/polaris/headlamp-polaris-plugin). Configure Headlamp via Helm:
1. Go to **Settings → Plugins**
2. Click **Catalog** tab
3. Search for "Polaris"
4. Click **Install**
Or configure Headlamp via Helm:
```yaml
config:
@@ -62,56 +67,6 @@ pluginsManager:
url: https://github.com/privilegedescalation/headlamp-polaris-plugin/releases/download/v0.3.10/polaris-0.3.10.tar.gz
```
Or install via the Headlamp UI:
1. Go to **Settings → Plugins**
2. Click **Catalog** tab
3. Search for "Polaris"
4. Click **Install**
### Option 2: Sidecar Container (Alternative)
For detailed sidecar installation instructions, see [docs/DEPLOYMENT.md#installation-method-2-sidecar-container](docs/DEPLOYMENT.md#installation-method-2-sidecar-container).
```yaml
sidecars:
- name: headlamp-plugin
image: node:lts-alpine
command: ['/bin/sh']
args:
- -c
- |
npm install -g @kinvolk/headlamp-plugin
headlamp-plugin install --config /config/plugin.yml
tail -f /dev/null
volumeMounts:
- name: plugins
mountPath: /headlamp/plugins
- name: plugin-config
mountPath: /config
```
### Option 3: Manual Tarball Install
Download the `.tar.gz` from the [GitHub releases page](https://github.com/privilegedescalation/headlamp-polaris-plugin/releases), then extract into Headlamp's plugin directory:
```bash
wget https://github.com/privilegedescalation/headlamp-polaris-plugin/releases/download/v0.3.10/polaris-0.3.10.tar.gz
tar xzf polaris-0.3.10.tar.gz -C /headlamp/plugins/
```
### Option 4: Build from Source
```bash
git clone https://github.com/privilegedescalation/headlamp-polaris-plugin.git
cd headlamp-polaris-plugin
npm install
npm run build
npx @kinvolk/headlamp-plugin extract . /headlamp/plugins
```
For complete installation instructions including Helm integration, FluxCD examples, and production deployment checklist, see **[docs/DEPLOYMENT.md](docs/DEPLOYMENT.md)**.
## RBAC / Security Setup
The plugin fetches audit data through the Kubernetes API server's **service proxy** sub-resource. The identity making the request (Headlamp's service account, or the user's own token in token-auth mode) must be granted:
@@ -199,7 +154,7 @@ Quick reference:
| **Plugin not in sidebar** | Plugin not installed or needs browser refresh | Hard refresh browser (Cmd+Shift+R / Ctrl+Shift+F5) |
| **403 Access Denied** | Missing RBAC binding for `services/proxy` | Apply Role + RoleBinding from RBAC section |
| **404 or 503** | Polaris not installed, or dashboard disabled | Install Polaris with `dashboard.enabled: true` in `polaris` namespace |
| **Dark mode white backgrounds** | Old plugin version | Upgrade to v0.3.5+ and hard refresh browser |
| **Dark mode white backgrounds** | Old plugin version | Upgrade to v0.6.0+ and hard refresh browser |
| **Settings page empty** | Old plugin version | Upgrade to v0.3.3+ |
| **No data / infinite spinner** | Network policy or Polaris pod down | Check network policies and `kubectl get pods -n polaris` |
@@ -253,17 +208,21 @@ For complete testing guide including CI/CD integration, see **[docs/TESTING.md](
```
src/
index.tsx -- Entry point. Registers sidebar entries and routes.
index.tsx -- Entry point. Registers sidebar entries, routes, and error boundaries.
test-utils.tsx -- Shared test fixtures (makeResult, makeAuditData).
api/
polaris.ts -- TypeScript types (AuditData schema), usePolarisData hook,
countResults utilities, refresh interval settings.
polaris.test.ts -- Unit tests for utility functions (vitest).
checkMapping.ts -- Polaris check ID → human-readable name mapping.
topIssues.ts -- Top failing checks aggregation logic.
PolarisDataContext.tsx -- React context provider; shared data fetch across views.
components/
DashboardView.tsx -- Overview page (score, check summary with skipped, cluster info).
NamespacesListView.tsx -- Namespace list with scores and links to detail views.
NamespaceDetailView.tsx -- Per-namespace drill-down with resource table.
PolarisSettings.tsx -- Plugin settings page (refresh interval selector).
NamespacesListView.tsx -- Namespace list with scores; MUI Drawer detail panel.
InlineAuditSection.tsx -- Inline audit for Deployment/StatefulSet/DaemonSet/Job/CronJob detail views.
ExemptionManager.tsx -- Polaris exemption annotation management.
AppBarScoreBadge.tsx -- App bar cluster score chip.
PolarisSettings.tsx -- Plugin settings page (refresh interval, dashboard URL).
vitest.config.mts -- Vitest configuration (jsdom environment).
```
+47 -5
View File
@@ -1,5 +1,5 @@
version: "0.5.1"
name: headlamp-polaris-plugin
version: "1.0.0"
name: headlamp-polaris
displayName: Polaris
createdAt: "2026-02-05T19:00:00Z"
description: >-
@@ -11,6 +11,7 @@ description: >-
`polaris-dashboard` service in the `polaris` namespace.
license: Apache-2.0
homeURL: "https://github.com/privilegedescalation/headlamp-polaris-plugin"
appVersion: "10.1.6"
category: security
keywords:
- polaris
@@ -24,11 +25,52 @@ links:
url: "https://github.com/privilegedescalation/headlamp-polaris-plugin"
- name: Polaris
url: "https://polaris.docs.fairwinds.com/"
install: |
## Installation
### Prerequisites
1. [Headlamp](https://headlamp.dev) v0.26.0 or later
2. [Fairwinds Polaris](https://polaris.docs.fairwinds.com/) installed and the dashboard running in your cluster
### Install via Headlamp Plugin Catalog
1. Open Headlamp and navigate to **Settings → Plugin Catalog**
2. Search for **"Polaris"**
3. Click **Install** and restart Headlamp when prompted
The plugin is sourced directly from [ArtifactHub](https://artifacthub.io/packages/headlamp/headlamp/headlamp-polaris).
## Usage
After installation, the Polaris plugin adds:
- A **cluster score badge** in the Headlamp app bar
- A **Polaris** section in the sidebar with the full dashboard and namespace drill-downs
- An **inline audit panel** on Deployment, StatefulSet, DaemonSet, Job, and CronJob detail pages
For more information, see the [README](https://github.com/privilegedescalation/headlamp-polaris-plugin/blob/main/README.md).
changes:
- kind: security
description: Patched 8 npm audit vulnerabilities via pnpm.overrides
- kind: added
description: Dual-approval required CI check — PRs must be approved by both CTO and QA before merge
- kind: added
description: ExemptionManager test suite — full coverage of annotation-based exemption flows
- kind: fixed
description: E2E infrastructure overhauled — ConfigMap volume mount replaces Dockerfile-based approach, tests run in privilegedescalation-dev namespace
- kind: fixed
description: E2E workflow uses token auth and waits for HTTP reachability before running tests
- kind: fixed
description: Added explicit direct devDependencies (typescript, eslint, prettier, @headlamp-k8s/eslint-config) to prevent phantom dep failures
- kind: changed
description: pnpm version pinned via packageManager field; GitHub Actions SHA-pinned via Renovate pinDigests
- kind: changed
description: v1.0.0 stable release — plugin API (routes, sidebar, settings schema, app bar action) is stable and will not change without a major version bump
maintainers:
- name: privilegedescalation
email: "chris@farhood.org"
annotations:
headlamp/plugin/archive-url: "https://github.com/privilegedescalation/headlamp-polaris-plugin/releases/download/v0.5.1/polaris-0.5.1.tar.gz"
headlamp/plugin/archive-url: "https://github.com/privilegedescalation/headlamp-polaris-plugin/releases/download/v1.0.0/headlamp-polaris-1.0.0.tar.gz"
headlamp/plugin/version-compat: ">=0.26"
headlamp/plugin/archive-checksum: sha256:6203461dccc978ae3f33f4feae102c4eb3169ea87c23dc407ef10ea76dd952db
headlamp/plugin/distro-compat: in-cluster
headlamp/plugin/archive-checksum: sha256:a165e871b40f11a44950aa9f10eb7f7883276f749026ae7a4f886278ecd9bd7d
headlamp/plugin/distro-compat: "in-cluster,web,desktop"
+1 -1
View File
@@ -1,4 +1,4 @@
repositoryID: fc3397f6-a75a-4950-ab50-da75c08a8089
repositoryID: 0243bdaf-c926-44dc-b411-a7c291bf1fcd
owners:
- name: privilegedescalation
email: "chris@farhood.org"
+46
View File
@@ -0,0 +1,46 @@
---
# RBAC for the GitHub Actions CI runner to manage the E2E Headlamp instance.
# CI-only test fixture — NOT for production use.
#
# Grants the ARC runner service account permissions in the privilegedescalation-dev
# namespace to deploy and tear down a dedicated Headlamp instance via Helm.
# E2E resources run in `privilegedescalation-dev` — nothing persists beyond a test run.
#
# Plugin is loaded via ConfigMap volume mount — no custom Docker images.
#
# Prerequisites:
# kubectl apply -f deployment/e2e-ci-runner-rbac.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: e2e-ci-runner
namespace: privilegedescalation-dev
rules:
# Helm needs to manage these resources for the Headlamp chart
- apiGroups: ["apps"]
resources: ["deployments"]
verbs: ["get", "list", "create", "update", "patch", "delete", "watch"]
- apiGroups: [""]
resources: ["services", "serviceaccounts", "configmaps", "secrets"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list", "watch"]
# Token creation for E2E test auth
- apiGroups: [""]
resources: ["serviceaccounts/token"]
verbs: ["create"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: e2e-ci-runner-binding
namespace: privilegedescalation-dev
subjects:
- kind: ServiceAccount
name: runners-privilegedescalation-gha-rs-no-permission
namespace: arc-runners
roleRef:
kind: Role
name: e2e-ci-runner
apiGroup: rbac.authorization.k8s.io
@@ -1,83 +0,0 @@
---
# Custom Headlamp values for static plugin installation
# This disables the plugin manager and uses an init container instead
# Disable the plugin manager sidecar
pluginsManager:
enabled: false
# Use an init container to install plugins to /headlamp/static-plugins
initContainers:
- name: install-plugins
image: node:lts-alpine
command:
- /bin/sh
- -c
- |
set -e
echo "Installing plugins to /headlamp/static-plugins..."
# Create plugins directory
mkdir -p /headlamp/static-plugins
# Set up npm cache
export NPM_CONFIG_CACHE=/tmp/npm-cache
export NPM_CONFIG_USERCONFIG=/tmp/npm-userconfig
mkdir -p /tmp/npm-cache /tmp/npm-userconfig
# Install polaris plugin
echo "Installing polaris plugin..."
cd /headlamp/static-plugins
npm pack headlamp-polaris-plugin@0.3.0
tar -xzf headlamp-polaris-plugin-0.3.0.tgz
mv package headlamp-polaris-plugin
rm headlamp-polaris-plugin-0.3.0.tgz
# Install other plugins
npx --yes @headlamp-k8s/plugin@latest install \
--source https://artifacthub.io/packages/headlamp/headlamp-plugins/headlamp_flux \
--folderName /headlamp/static-plugins
npx --yes @headlamp-k8s/plugin@latest install \
--source https://artifacthub.io/packages/headlamp/headlamp-trivy/headlamp_trivy \
--folderName /headlamp/static-plugins
npx --yes @headlamp-k8s/plugin@latest install \
--source https://artifacthub.io/packages/headlamp/headlamp-plugins/headlamp_cert-manager \
--folderName /headlamp/static-plugins
npx --yes @headlamp-k8s/plugin@latest install \
--source https://artifacthub.io/packages/headlamp/headlamp-plugins/headlamp_ai_assistant \
--folderName /headlamp/static-plugins
echo "All plugins installed successfully"
ls -la /headlamp/static-plugins
securityContext:
runAsUser: 100
runAsGroup: 101
runAsNonRoot: true
privileged: false
resources:
requests:
cpu: 100m
memory: 256Mi
limits:
memory: 512Mi
volumeMounts:
- name: static-plugins
mountPath: /headlamp/static-plugins
# Configure headlamp to use static plugins
config:
pluginsDir: /headlamp/static-plugins
# Add volume for static plugins
volumes:
- name: static-plugins
emptyDir: {}
# Add volume mount to main container
volumeMounts:
- name: static-plugins
mountPath: /headlamp/static-plugins
readOnly: true
+28
View File
@@ -0,0 +1,28 @@
# RBAC to allow authenticated users to proxy to the Polaris dashboard service.
# The polaris plugin reads audit data via the Kubernetes service proxy:
# /api/v1/namespaces/polaris/services/http:polaris-dashboard:80/proxy/results.json
# Without this Role + RoleBinding, users get a 403 when Headlamp proxies the request.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: polaris-dashboard-proxy-reader
namespace: polaris
rules:
- apiGroups: [""]
resources: ["services/proxy"]
resourceNames: ["polaris-dashboard", "http:polaris-dashboard:80"]
verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: polaris-dashboard-proxy-reader
namespace: polaris
subjects:
- kind: Group
name: system:authenticated
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role
name: polaris-dashboard-proxy-reader
apiGroup: rbac.authorization.k8s.io
@@ -0,0 +1,128 @@
# ADR-002: Service Proxy as Single Data Source
**Status:** Accepted
**Date:** 2026-03-05
**Deciders:** Plugin maintainers
## Context
The Polaris plugin needs audit data from the Polaris dashboard. Polaris dashboard exposes a `/results.json` endpoint containing pre-computed audit results for all workloads in the cluster.
Several approaches were considered for obtaining this data:
1. Query Kubernetes resources directly and re-implement Polaris audit logic
2. Use the Polaris CLI as a sidecar container
3. Use the Polaris dashboard's REST API via Kubernetes service proxy
4. Embed Polaris as a Go/JS library
The service proxy approach uses the Kubernetes API server's built-in service proxy capability to reach the Polaris dashboard at `/api/v1/namespaces/polaris/services/polaris-dashboard:80/proxy/results.json`. This means the plugin receives pre-computed audit results without needing to understand Polaris internals.
**Constraints:**
- Headlamp plugins can make API calls via `ApiProxy.request()` (proxied through the Headlamp backend) or direct `fetch()` for external URLs
- The Polaris dashboard service name, namespace, and port may vary across cluster setups
- Some users may run Polaris externally (not in-cluster)
**Requirements:**
- Retrieve all audit data in a single API call
- Support configurable endpoint URL for different cluster configurations
- Support external Polaris instances via full HTTP/HTTPS URLs
- Work through existing Kubernetes RBAC without additional configuration
## Decision
Use **`ApiProxy.request()`** to fetch from the Polaris dashboard service proxy as the single data source for all audit data.
**Implementation:**
- Default endpoint: `/api/v1/namespaces/polaris/services/polaris-dashboard:80/proxy/results.json`
- URL is configurable via plugin settings stored in `localStorage` (key: `polaris-plugin-dashboard-url`)
- For full URLs starting with `http://` or `https://`, use browser `fetch()` directly to support external Polaris instances
- `getPolarisApiPath()` in `polaris.ts` resolves the configured URL, with `isFullUrl()` determining the fetch strategy
- Single fetch shared across all views via `PolarisDataProvider` (see ADR-001)
## Consequences
### Positive
-**Single API call gets all audit data** - One request to `/results.json` returns scores for every workload
-**No need to understand Polaris internals** - Plugin receives pre-computed results, no audit logic duplication
-**Works through existing K8s RBAC** - Service proxy uses standard Kubernetes RBAC (`get` on `services/proxy`)
-**Configurable endpoint** - Users can customize namespace, service name, or point to an external instance
-**Minimal plugin complexity** - No CRD watches, no custom controllers, no library dependencies
### Negative
-**Requires Polaris dashboard to be deployed and accessible** - Plugin has no data without the dashboard
- **Mitigated by:** Clear error messages guiding users to install Polaris (404/503 → install guidance)
-**Single point of failure** - If the dashboard service is down, the plugin shows no data
- **Mitigated by:** Status-code-specific error messages (403 → RBAC guidance, 404/503 → deployment guidance)
-**Dashboard must be running continuously** - Unlike CRD-based approaches where data persists
- **Mitigated by:** Polaris dashboard is typically deployed as a long-running service
### Neutral
- The Polaris dashboard is a lightweight Go service with minimal resource requirements
- Service proxy is a standard Kubernetes pattern used by many tools (kubectl port-forward, dashboard proxying)
- The configurable URL approach supports both in-cluster and external Polaris deployments
## Alternatives Considered
### Option 1: Query Polaris CRDs Directly
**Pros:**
- No dependency on Polaris dashboard being running
- Data persists in CRDs even if dashboard restarts
**Cons:**
- Polaris audit logic is complex and would need to be duplicated in the plugin
- Would require watching multiple CRD types
- Plugin would need to be updated whenever Polaris changes its audit rules
**Decision:** Rejected (would duplicate Polaris internals, maintenance burden)
### Option 2: Use Polaris CLI as a Sidecar
**Pros:**
- CLI has full audit capability
- Could run audits on-demand
**Cons:**
- Adds operational complexity (sidecar container management)
- Not suitable for a browser-based plugin (CLI runs server-side)
- Would require a separate backend service to bridge CLI output to the plugin
**Decision:** Rejected (operational complexity, not suitable for plugin architecture)
### Option 3: Embed Polaris as a Library
**Pros:**
- Full control over audit execution
- No external service dependency
**Cons:**
- Polaris is a Go library, not available in JavaScript/TypeScript plugin runtime
- Would massively increase bundle size
- Would duplicate the entire Polaris engine
**Decision:** Rejected (not available in plugin runtime, massive dependency)
## References
- [Kubernetes Service Proxy](https://kubernetes.io/docs/tasks/access-application-cluster/access-cluster-services/)
- [Polaris Dashboard](https://polaris.docs.fairwinds.com/dashboard/)
- [Plugin Implementation](../../api/polaris.ts)
- [Data Context](../../api/PolarisDataContext.tsx)
## Revision History
| Date | Author | Change |
| ---------- | ----------- | ---------------- |
| 2026-03-05 | Plugin Team | Initial decision |
@@ -0,0 +1,124 @@
# ADR-003: Error Boundary as Class Component Exception
**Status:** Accepted
**Date:** 2026-03-05
**Deciders:** Plugin maintainers
## Context
The plugin follows a strict "functional components only" convention (see CLAUDE.md). However, React error boundaries require the `getDerivedStateFromError` and `componentDidCatch` lifecycle methods, which are only available on class components. As of React 18, there is no hooks-based error boundary API, and the React team has not announced a timeline for one.
The plugin registers components at multiple Headlamp integration points:
- Routes (dashboard, namespaces list)
- Detail view sections (Deployment, StatefulSet, DaemonSet, Job, CronJob)
- App bar action (score badge)
- Plugin settings page
An unhandled error in any one of these registered components would crash the entire Headlamp UI, not just the plugin. This is because Headlamp renders plugin components inline within its own React tree.
**Constraints:**
- React does not support error boundaries via hooks or functional components
- The `react-error-boundary` library is not available as a peer dependency in Headlamp plugins
- Plugin errors must not crash the host Headlamp application
**Requirements:**
- Catch and contain errors in all plugin-registered components
- Provide user-friendly error display with recovery option
- Isolate failures per registration point (an error in the app bar badge should not affect the dashboard view)
## Decision
Define **`PolarisErrorBoundary`** as a class component directly in `index.tsx`. This is the sole exception to the functional-component-only convention.
**Implementation:**
- `PolarisErrorBoundary` is a React class component with `getDerivedStateFromError` and `componentDidCatch`
- Every registered component (routes, detail sections, app bar action) is wrapped in this boundary
- On error, displays a user-friendly fallback with an option to retry
- Error details are logged to the console for debugging
- The boundary is minimal (~30 lines) and co-located in `index.tsx` to minimize the convention violation
## Consequences
### Positive
-**Prevents plugin errors from crashing Headlamp** - Errors are caught and contained within the boundary
-**User-friendly error display** - Shows a clear message with recovery option instead of a blank screen
-**Isolated per registration point** - Each registered component has its own boundary instance
-**No external dependencies** - Uses built-in React class component API
-**Minimal implementation** - Small class component, easy to understand and maintain
### Negative
-**Breaks functional-only convention** - One class component in an otherwise functional codebase
- **Mitigated by:** Kept minimal and co-located in `index.tsx` with clear documentation of why
-**Class component syntax less familiar to contributors** - Modern React developers may not be fluent in class components
- **Mitigated by:** The boundary is simple (no complex state, no lifecycle methods beyond error handling)
### Neutral
- This is a well-known React limitation acknowledged by the React team
- Many React projects that otherwise use functional components make this same exception for error boundaries
- The pattern is explicitly documented in the React documentation
## Alternatives Considered
### Option 1: No Error Boundary
**Pros:**
- No class component needed
- Simpler code
**Cons:**
- Plugin errors would crash the entire Headlamp UI
- Users would see a blank screen with no recovery option
- Poor user experience and potential data loss in other Headlamp features
**Decision:** Rejected (unacceptable risk of crashing host application)
### Option 2: react-error-boundary Library
**Pros:**
- Provides a functional component API for error boundaries
- Well-maintained, widely used library
- Supports error recovery and reset
**Cons:**
- External dependency not available in Headlamp plugin runtime
- Cannot add peer dependencies that Headlamp does not provide
**Decision:** Rejected (dependency not available in plugin environment)
### Option 3: Wait for React Hooks-Based Error Boundary API
**Pros:**
- Would maintain functional-only convention
- Official React solution
**Cons:**
- No timeline from the React team for this feature
- Plugin needs error boundaries now, not at some future date
- May never be implemented (React team has not committed to this)
**Decision:** Rejected (no timeline, cannot ship without error boundaries)
## References
- [React Error Boundaries](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary)
- [React getDerivedStateFromError](https://react.dev/reference/react/Component#static-getderivedstatefromerror)
- [Plugin Implementation](../../../src/index.tsx)
## Revision History
| Date | Author | Change |
| ---------- | ----------- | ---------------- |
| 2026-03-05 | Plugin Team | Initial decision |
@@ -0,0 +1,132 @@
# ADR-004: Browser localStorage for User Settings
**Status:** Accepted
**Date:** 2026-03-05
**Deciders:** Plugin maintainers
## Context
The plugin has two user-configurable settings:
1. **Auto-refresh interval** (1-30 minutes, default 5 minutes) - how often to re-fetch Polaris audit data
2. **Polaris dashboard URL** - endpoint for the Polaris dashboard service (supports custom namespaces/service names and external instances)
These are per-user preferences, not cluster configuration. They should persist across browser sessions and page reloads.
Several storage mechanisms are available:
- Browser `localStorage` - simple key-value store, persistent, synchronous API
- Headlamp `ConfigStore` API - backed by Redux, reactive, integrated with Headlamp's state management
- React state only - in-memory, lost on page reload
- URL query parameters - visible in URL, lost on navigation
**Constraints:**
- Settings need to be reactive: the `PolarisDataProvider` must detect changes made on the settings page
- Headlamp provides `registerPluginSettings` which renders a settings component - the settings page and the data provider are separate component trees
- Only two scalar values need to be stored
**Requirements:**
- Persist settings across browser sessions and page reloads
- React to setting changes without requiring a full page reload
- Simple implementation for two scalar values
- Work with Headlamp's `registerPluginSettings` API
## Decision
Use **browser `localStorage`** directly for persisting plugin settings.
**Implementation:**
- Refresh interval stored at key `polaris-plugin-refresh-interval` (value in minutes as string)
- Dashboard URL stored at key `polaris-plugin-dashboard-url` (URL string or empty for default)
- `PolarisSettings` component (registered via `registerPluginSettings`) reads/writes these keys
- `PolarisDataProvider` polls `localStorage` via `setInterval` every 1 second to detect setting changes
- Helper functions in `polaris.ts` (`getRefreshInterval()`, `getPolarisApiPath()`) encapsulate localStorage access
## Consequences
### Positive
-**Simple and well-understood API** - `localStorage.getItem`/`setItem` is straightforward
-**Persists across browser sessions** - Data survives page reloads, tab closes, browser restarts
-**No dependency on Headlamp store internals** - Decoupled from Headlamp's Redux implementation
-**Works with `registerPluginSettings`** - Settings page and data provider communicate via shared localStorage keys
-**Minimal code** - No state management boilerplate for two simple values
### Negative
-**Not reactive by default** - localStorage has no built-in change notification within the same tab
- **Mitigated by:** 1-second polling interval in `PolarisDataProvider` to detect changes
-**Settings are browser-local** - Not synced across devices or browsers
- **Mitigated by:** These are user preferences, browser-local storage is appropriate
-**No type safety on stored values** - All values stored as strings
- **Mitigated by:** Helper functions with `parseInt` and default values handle type conversion
### Neutral
- localStorage has a 5-10 MB limit per origin, more than sufficient for two string values
- The 1-second polling interval has negligible performance impact (reading two string keys)
- The `storage` event could detect cross-tab changes but does not fire for same-tab writes
## Alternatives Considered
### Option 1: Headlamp ConfigStore API
**Pros:**
- Integrated with Headlamp's Redux store
- Reactive (Redux state changes trigger re-renders)
- Type-safe with TypeScript
**Cons:**
- Couples plugin to Headlamp's internal Redux store implementation
- More complex API for two scalar values
- ConfigStore API may change across Headlamp versions
**Decision:** Not chosen (localStorage is simpler for two scalar values, avoids coupling to Headlamp's Redux internals)
### Option 2: React State Only (No Persistence)
**Pros:**
- Simplest implementation
- Fully reactive
- No side effects
**Cons:**
- Settings lost on page reload - users must reconfigure every session
- Poor user experience for frequently changed settings
**Decision:** Rejected (settings must persist across page reloads)
### Option 3: URL Query Parameters
**Pros:**
- Shareable via URL
- No storage API needed
**Cons:**
- Lost on navigation to different routes
- Clutters the URL
- Not suitable for persistent settings
**Decision:** Rejected (does not persist across navigation)
## References
- [Web Storage API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API)
- [Headlamp Plugin Settings](https://headlamp.dev/docs/latest/development/plugins/)
- [Settings Component](../../../src/components/PolarisSettings.tsx)
- [Data Context](../../../src/api/PolarisDataContext.tsx)
## Revision History
| Date | Author | Change |
| ---------- | ----------- | ---------------- |
| 2026-03-05 | Plugin Team | Initial decision |
@@ -0,0 +1,131 @@
# ADR-005: Annotation-Based Exemption Management
**Status:** Accepted
**Date:** 2026-03-05
**Deciders:** Plugin maintainers
## Context
Polaris allows exempting specific workloads from audit checks. When a workload is exempt, Polaris skips all audit checks for that resource. The exemption mechanism uses the annotation `polaris.fairwinds.com/exempt=true` on the workload resource.
The plugin needs to let users manage these exemptions directly from the Headlamp UI. Several approaches were considered:
1. Use Polaris's native annotation-based exemption mechanism
2. Create a separate exemption ConfigMap
3. Define a custom ExemptionPolicy CRD
4. Read-only display with kubectl instructions
**Constraints:**
- Polaris only recognizes `polaris.fairwinds.com/exempt` annotations on workload resources
- The plugin is otherwise read-only (this would be the only write operation)
- Users need appropriate RBAC permissions to patch workload resources
- Supported workload types: Deployments, StatefulSets, DaemonSets, Jobs, CronJobs
**Requirements:**
- Allow users to toggle exemptions for workloads from the Headlamp UI
- Use a mechanism that Polaris actually respects (exemptions must take effect on next scan)
- Support all workload types that Polaris audits
- Respect Kubernetes RBAC (only authorized users can manage exemptions)
## Decision
Use **Polaris's native annotation-based exemption mechanism**. The `ExemptionManager` component patches `polaris.fairwinds.com/exempt` annotations onto workload resources via `ApiProxy.request`.
**Implementation:**
- `ExemptionManager` component in `ExemptionManager.tsx` provides a toggle UI for each workload
- Exemptions are applied via `ApiProxy.request` with `method: 'PATCH'` and `Content-Type: application/strategic-merge-patch+json`
- Patch payload sets `metadata.annotations["polaris.fairwinds.com/exempt"]` to `"true"` or removes the annotation
- This is the only write operation in the entire plugin
- RBAC is enforced by Kubernetes - users without `patch` permission on the workload resource will receive a 403 error
## Consequences
### Positive
-**Uses Polaris's own exemption mechanism** - No custom storage or translation layer needed
-**Exemptions visible in standard kubectl output** - `kubectl get deployment -o yaml` shows the annotation
-**No additional CRDs or ConfigMaps** - No custom resources to manage or clean up
-**Polaris automatically respects annotations** - Exemptions take effect on the next audit scan
-**Standard Kubernetes pattern** - Annotations are the idiomatic way to attach metadata to resources
### Negative
-**Requires write RBAC on workload resources** - Users need `patch` permission on deployments, statefulsets, etc.
- **Mitigated by:** RBAC scoping - only users with patch permission can manage exemptions; UI shows clear error for 403
-**Annotation changes not versioned or auditable** - Beyond standard Kubernetes resource history
- **Mitigated by:** Kubernetes audit logging captures annotation patches; resource `metadata.managedFields` tracks changes
-**Only supports full-resource exemption** - Cannot exempt individual checks (Polaris limitation)
- **Mitigated by:** This matches Polaris's own annotation-level granularity
### Neutral
- Strategic merge patch is the standard Kubernetes patching strategy for adding/removing annotations
- The annotation key (`polaris.fairwinds.com/exempt`) is defined by Polaris and unlikely to change
- Exemption state is stored on the workload resource itself, so it moves with the resource if migrated
## Alternatives Considered
### Option 1: Separate Exemption ConfigMap
**Pros:**
- Centralizes all exemptions in one place
- Does not require write access to workload resources
- Easy to audit all exemptions at once
**Cons:**
- Polaris does not read exemptions from ConfigMaps - it only checks annotations
- Would require a custom reconciliation controller to sync ConfigMap entries to annotations
- Adds operational complexity
**Decision:** Rejected (Polaris does not support ConfigMap-based exemptions)
### Option 2: Custom ExemptionPolicy CRD
**Pros:**
- Dedicated resource type for exemption management
- Could support per-check exemptions, time-based exemptions, etc.
- Clean separation of concerns
**Cons:**
- Over-engineering for what is essentially an annotation toggle
- Would require a custom controller to reconcile CRDs to annotations
- Adds CRD installation as a prerequisite
- Polaris still needs the annotation, so the CRD would be an indirection layer
**Decision:** Rejected (over-engineering for annotation toggle, would require a controller)
### Option 3: Read-Only Display with kubectl Instructions
**Pros:**
- No write operations in the plugin
- No RBAC requirements beyond read access
- Simpler implementation
**Cons:**
- Poor user experience - users must switch to terminal to manage exemptions
- Defeats the purpose of a UI plugin
- Error-prone (users may mistype annotation keys)
**Decision:** Rejected (poor UX compared to in-UI toggle)
## References
- [Polaris Exemptions Documentation](https://polaris.docs.fairwinds.com/customization/exemptions/)
- [Kubernetes Annotations](https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/)
- [Strategic Merge Patch](https://kubernetes.io/docs/tasks/manage-kubernetes-resources/update-api-object-kubectl-patch/#use-a-strategic-merge-patch-to-update-a-deployment)
- [Plugin Implementation](../../../src/components/ExemptionManager.tsx)
## Revision History
| Date | Author | Change |
| ---------- | ----------- | ---------------- |
| 2026-03-05 | Plugin Team | Initial decision |
+4 -2
View File
@@ -70,8 +70,10 @@ What becomes easier or more difficult to do because of this change?
| ADR | Title | Status | Date |
| ------------------------------------- | -------------------------------------- | -------- | ---------- |
| [001](001-react-context-for-state.md) | Use React Context for State Management | Accepted | 2026-02-12 |
**Note:** Additional ADRs documenting other significant decisions (service proxy approach, drawer navigation, MUI import restrictions) can be created following the template above.
| [002](002-service-proxy-data-source.md) | Service Proxy as Single Data Source | Accepted | 2026-03-05 |
| [003](003-error-boundary-class-component.md) | Error Boundary as Class Component Exception | Accepted | 2026-03-05 |
| [004](004-localstorage-settings.md) | Browser localStorage for User Settings | Accepted | 2026-03-05 |
| [005](005-annotation-exemption-management.md) | Annotation-Based Exemption Management | Accepted | 2026-03-05 |
## Creating a New ADR
+2 -2
View File
@@ -19,7 +19,7 @@ Helm provides the easiest way to deploy and manage the plugin in production. Thi
```bash
# Add Headlamp Helm repository
helm repo add headlamp https://headlamp-k8s.github.io/headlamp/
helm repo add headlamp https://kubernetes-sigs.github.io/headlamp/
helm repo update
```
@@ -210,7 +210,7 @@ metadata:
namespace: flux-system
spec:
interval: 1h
url: https://headlamp-k8s.github.io/headlamp/
url: https://kubernetes-sigs.github.io/headlamp/
```
### HelmRelease
+1 -1
View File
@@ -84,7 +84,7 @@ kubectl -n kube-system get deployment headlamp -o jsonpath='{.spec.template.spec
```bash
# Add Headlamp Helm repository
helm repo add headlamp https://headlamp-k8s.github.io/headlamp/
helm repo add headlamp https://kubernetes-sigs.github.io/headlamp/
helm repo update
# Install Headlamp
+33 -24
View File
@@ -4,7 +4,16 @@ Playwright-based smoke tests that validate the Polaris plugin against a live Hea
## CI
E2E tests run automatically in GitHub Actions on pushes to `main` and pull requests. The workflow (`.github/workflows/e2e.yaml`) uses either Authentik OIDC or token-based authentication via repository secrets.
E2E tests run automatically in GitHub Actions on pushes to `main` and pull requests. The workflow (`.github/workflows/e2e.yaml`):
1. Builds the plugin (`npm run build`)
2. Creates a ConfigMap from the built `dist/` output
3. Deploys a stock Headlamp instance via Helm with the plugin mounted as a ConfigMap volume
4. Generates a ServiceAccount token for test auth
5. Runs Playwright tests against the E2E instance
6. Tears down the E2E instance
This approach uses the stock `ghcr.io/headlamp-k8s/headlamp` image with no custom Docker builds. The plugin is loaded via `HEADLAMP_PLUGINS_DIR` volume mount.
### Required GitHub Secrets
@@ -12,12 +21,12 @@ Configure these in GitHub repository settings (Settings → Secrets and variable
| Secret | Required | Description |
| -------------------- | -------- | -------------------------------------------------------------- |
| `HEADLAMP_URL` | Optional | Headlamp instance URL (defaults to `https://headlamp.animaniacs.farh.net`) |
| `AUTHENTIK_USERNAME` | OIDC | Authentik email or username for a CI user with Headlamp access |
| `AUTHENTIK_PASSWORD` | OIDC | Password for that user |
| `HEADLAMP_TOKEN` | Token | Kubernetes service account token (alternative to OIDC) |
Set either `AUTHENTIK_USERNAME` + `AUTHENTIK_PASSWORD` **or** `HEADLAMP_TOKEN`. OIDC takes priority if both are set.
Token-based auth is auto-generated by the deploy script. OIDC secrets are only needed if testing against the shared Headlamp instance.
No `GHCR_TOKEN` or Docker registry secrets are needed — the stock Headlamp image is public.
## Running Locally
@@ -47,12 +56,12 @@ HEADLAMP_URL=http://localhost:4466 npm run e2e:headed
| Variable | Required | Default | Description |
| -------------------- | -------- | -------------------------------------- | --------------------------------------- |
| `HEADLAMP_URL` | No | `https://headlamp.animaniacs.farh.net` | Base URL of the Headlamp instance |
| `AUTHENTIK_USERNAME` | OIDC | — | Authentik email/username |
| `AUTHENTIK_PASSWORD` | OIDC | — | Authentik password |
| `HEADLAMP_TOKEN` | Token | — | Kubernetes bearer token (fallback auth) |
| `HEADLAMP_URL` | No | `https://headlamp.animaniacs.farh.net` | Base URL of the Headlamp instance |
| `AUTHENTIK_USERNAME` | OIDC | — | Authentik email/username |
| `AUTHENTIK_PASSWORD` | OIDC | — | Authentik password |
| `HEADLAMP_TOKEN` | Token | — | Kubernetes bearer token (auto-generated in CI) |
Set either `AUTHENTIK_USERNAME` + `AUTHENTIK_PASSWORD` or `HEADLAMP_TOKEN`. OIDC takes priority if both are set.
In CI, `HEADLAMP_URL` and `HEADLAMP_TOKEN` are set automatically by the deploy script. For local runs, set either OIDC credentials or a token manually.
## What the Tests Validate
@@ -249,25 +258,25 @@ test('plugin UI adapts to dark mode', async ({ page }) => {
Tests run automatically in GitHub Actions on pushes to `main` and pull requests. See `.github/workflows/e2e.yaml` for workflow configuration.
### Required Secrets
### Architecture
Configure these in GitHub repository settings (Settings → Secrets and variables → Actions):
The E2E workflow deploys a **dedicated Headlamp instance** for each test run:
- `HEADLAMP_URL` (optional): Headlamp instance URL
- `AUTHENTIK_USERNAME` + `AUTHENTIK_PASSWORD` (for OIDC auth)
- OR `HEADLAMP_TOKEN` (for token-based auth)
1. Build plugin (`npm run build`)
2. Create ConfigMap from `dist/` output (`scripts/deploy-e2e-headlamp.sh`)
3. Deploy stock Headlamp via Helm with ConfigMap volume mount
4. Run Playwright tests against the E2E instance
5. Tear down (`scripts/teardown-e2e-headlamp.sh`)
### Workflow Overview
No custom Docker images, no PVCs, no kubectl exec/cp, no patching of existing deployments. The plugin is mounted from a ConfigMap into the stock Headlamp image.
1. Checkout code
2. Setup Node.js 20 with npm cache
3. Install dependencies (`npm ci`)
4. Install Playwright browsers (`chromium` only)
5. Run auth setup (creates session in `e2e/.auth/state.json`)
6. Run all E2E tests
7. Upload artifacts on failure:
- `playwright-report/` - HTML test report
- `test-results/` - Screenshots, traces, videos
### Cluster Prerequisites
One-time setup by a cluster admin:
```bash
kubectl apply -f deployment/e2e-ci-runner-rbac.yaml
```
### Manual Trigger
+6 -10
View File
@@ -47,16 +47,12 @@ test.describe('Polaris app bar badge', () => {
window.getComputedStyle(el).backgroundColor
);
if (score >= 80) {
// Green: rgb(76, 175, 80) or #4caf50
expect(bgColor).toMatch(/rgb\(76,\s*175,\s*80\)/);
} else if (score >= 50) {
// Orange: rgb(255, 152, 0) or #ff9800
expect(bgColor).toMatch(/rgb\(255,\s*152,\s*0\)/);
} else {
// Red: rgb(244, 67, 54) or #f44336
expect(bgColor).toMatch(/rgb\(244,\s*67,\s*54\)/);
}
// Verify that the badge has a non-default background color applied
// (theme-dependent RGB values vary across Headlamp versions, so we
// only assert that a real color is set rather than transparent/default)
expect(bgColor).not.toBe('rgba(0, 0, 0, 0)');
expect(bgColor).not.toBe('transparent');
expect(bgColor).toMatch(/^rgb/);
});
test('badge updates when navigating between clusters', async ({ page }) => {
+21 -9
View File
@@ -12,12 +12,21 @@ async function authenticateWithOIDC(page: Page, username: string, password: stri
await page.getByRole('button', { name: /sign in/i }).click();
const popup = await popupPromise;
// Authentik step 1: fill username
await popup.getByRole('textbox', { name: /email or username/i }).fill(username);
// Wait for the Authentik popup to fully load before interacting
await popup.waitForLoadState('domcontentloaded');
await popup.waitForLoadState('networkidle');
// Authentik step 1: fill username — wait for the form to render
const usernameField = popup.getByRole('textbox', { name: /email or username/i });
await usernameField.waitFor({ state: 'visible', timeout: 15_000 });
await usernameField.fill(username);
await popup.getByRole('button', { name: /log in/i }).click();
// Authentik step 2: fill password
await popup.getByRole('textbox', { name: /password/i }).fill(password);
// Authentik step 2: fill password — wait for the next step to load
await popup.waitForLoadState('networkidle');
const passwordField = popup.getByRole('textbox', { name: /password/i });
await passwordField.waitFor({ state: 'visible', timeout: 15_000 });
await passwordField.fill(password);
await popup.getByRole('button', { name: /continue|log in/i }).click();
// Wait for the popup to close (Authentik redirects back, Headlamp processes callback)
@@ -30,13 +39,16 @@ async function authenticateWithOIDC(page: Page, username: string, password: stri
}
async function authenticateWithToken(page: Page, token: string): Promise<void> {
// Navigate to login — Headlamp redirects / to /c/main/login
await page.goto('/');
await page.waitForURL('**/login');
// Headlamp goes to /token directly when no OIDC is configured,
// or through /login when OIDC is configured
await page.waitForURL(/\/(login|token)$/);
// Click the token auth option
await page.getByRole('button', { name: /use a token/i }).click();
await page.waitForURL('**/token');
if (page.url().includes('/login')) {
// OIDC login page — click "use a token" to reach token auth
await page.getByRole('button', { name: /use a token/i }).click();
await page.waitForURL('**/token');
}
// Fill the "ID token" field and submit
await page.getByRole('textbox', { name: /id token/i }).fill(token);
+2 -2
View File
@@ -17,7 +17,7 @@ test.describe('Polaris plugin smoke tests', () => {
// "Cluster Score" section exists with a percentage
await expect(page.getByText('Cluster Score')).toBeVisible();
await expect(page.getByText(/%/)).toBeVisible();
await expect(page.locator('main').getByText(/%/).first()).toBeVisible();
});
test('namespaces page renders table with namespace buttons', async ({ page }) => {
@@ -55,7 +55,7 @@ test.describe('Polaris plugin smoke tests', () => {
await expect(page.getByText('Namespace Score')).toBeVisible();
// Resources table should exist in drawer
await expect(page.getByText('Resources')).toBeVisible();
await expect(page.getByRole('heading', { name: 'Resources' })).toBeVisible();
// URL hash should be updated with namespace name
await expect(page).toHaveURL(/\/polaris\/namespaces#/);
+27 -25
View File
@@ -1,23 +1,34 @@
import { test, expect } from '@playwright/test';
import { test, expect, Page } from '@playwright/test';
/** Navigate to the Polaris plugin settings page and wait for settings to render. */
async function goToPolarisSettings(page: Page) {
// Headlamp's plugin settings page is a HOME-context route at /settings/plugins,
// not an in-cluster route (/c/main/settings/plugins would 404). Headlamp loads
// plugin scripts asynchronously on SPA init. When registerPluginSettings() fires,
// it dispatches a Redux action — PluginSettings uses useTypedSelector so it
// re-renders automatically once the plugin registers. No preloading needed.
await page.goto('/settings/plugins');
// Wait for the plugin to appear in the settings list. The timeout covers
// async plugin script loading + registration.
const pluginEntry = page.locator('text=headlamp-polaris').first();
await expect(pluginEntry).toBeVisible({ timeout: 30_000 });
await pluginEntry.click();
// Wait for the PolarisSettings component to render
await expect(page.getByText('Polaris Settings')).toBeVisible({ timeout: 15_000 });
}
test.describe('Polaris plugin settings', () => {
test('settings page shows configuration options', async ({ page }) => {
await page.goto('/c/main/settings/plugins');
await goToPolarisSettings(page);
// Find Polaris plugin in the list
const pluginCard = page.locator('text=headlamp-polaris-plugin').first();
await expect(pluginCard).toBeVisible();
// Click to view settings (if settings are displayed inline, they should already be visible)
// Note: Headlamp v0.39.0+ shows settings inline on the plugins page
await expect(page.getByText('Polaris Settings')).toBeVisible({ timeout: 15_000 });
// SectionBox title should be visible
await expect(page.getByText('Polaris Settings')).toBeVisible();
});
test('refresh interval setting is configurable', async ({ page }) => {
await page.goto('/c/main/settings/plugins');
// Navigate to Polaris settings
await expect(page.getByText('Polaris Settings')).toBeVisible({ timeout: 15_000 });
await goToPolarisSettings(page);
// Find the refresh interval dropdown
const intervalSelect = page.locator('select').filter({ hasText: /minute|second/ });
@@ -35,10 +46,7 @@ test.describe('Polaris plugin settings', () => {
});
test('dashboard URL setting is configurable', async ({ page }) => {
await page.goto('/c/main/settings/plugins');
// Navigate to Polaris settings
await expect(page.getByText('Polaris Settings')).toBeVisible({ timeout: 15_000 });
await goToPolarisSettings(page);
// Find the dashboard URL input
const urlInput = page.getByPlaceholder(/polaris-dashboard/);
@@ -54,10 +62,7 @@ test.describe('Polaris plugin settings', () => {
});
test('connection test button is available', async ({ page }) => {
await page.goto('/c/main/settings/plugins');
// Navigate to Polaris settings
await expect(page.getByText('Polaris Settings')).toBeVisible({ timeout: 15_000 });
await goToPolarisSettings(page);
// Find and verify test connection button
const testButton = page.getByRole('button', { name: /test connection/i });
@@ -66,10 +71,7 @@ test.describe('Polaris plugin settings', () => {
});
test('connection test works with valid URL', async ({ page }) => {
await page.goto('/c/main/settings/plugins');
// Navigate to Polaris settings
await expect(page.getByText('Polaris Settings')).toBeVisible({ timeout: 15_000 });
await goToPolarisSettings(page);
// Click test connection
const testButton = page.getByRole('button', { name: /test connection/i });
+982 -557
View File
File diff suppressed because it is too large Load Diff
+33 -3
View File
@@ -1,6 +1,6 @@
{
"name": "polaris",
"version": "0.5.1",
"name": "headlamp-polaris",
"version": "1.0.0",
"description": "Headlamp plugin for Fairwinds Polaris audit results",
"repository": {
"type": "git",
@@ -12,6 +12,7 @@
"homepage": "https://github.com/privilegedescalation/headlamp-polaris-plugin#readme",
"author": "privilegedescalation",
"license": "Apache-2.0",
"packageManager": "pnpm@10.32.1",
"scripts": {
"start": "headlamp-plugin start",
"build": "headlamp-plugin build",
@@ -26,8 +27,37 @@
"e2e": "playwright test",
"e2e:headed": "playwright test --headed"
},
"peerDependencies": {
"react": "^18.0.0",
"react-dom": "^18.0.0"
},
"pnpm": {
"overrides": {
"tar": "^7.5.11",
"undici": "^7.24.3",
"flatted": "^3.4.2"
}
},
"devDependencies": {
"@kinvolk/headlamp-plugin": "^0.13.0",
"@playwright/test": "^1.58.2"
"@mui/material": "^5.15.14",
"@playwright/test": "^1.58.2",
"@testing-library/jest-dom": "^6.4.8",
"@testing-library/react": "^16.0.0",
"@testing-library/user-event": "^14.5.2",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitest/coverage-v8": "^3.2.4",
"@headlamp-k8s/eslint-config": "^0.6.0",
"eslint": "^8.57.0",
"jsdom": "^24.0.0",
"prettier": "^2.8.8",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^5.3.0",
"tar": "^7.5.11",
"typescript": "~5.6.2",
"undici": "^7.24.3",
"vitest": "^3.0.5"
}
}
+2 -1
View File
@@ -11,9 +11,10 @@ export default defineConfig({
use: {
baseURL: process.env.HEADLAMP_URL || 'https://headlamp.animaniacs.farh.net',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
},
projects: [
{ name: 'setup', testMatch: /auth\.setup\.ts/ },
{ name: 'setup', testMatch: /auth\.setup\.ts/, timeout: 60_000 },
{
name: 'chromium',
use: {
+11751
View File
File diff suppressed because it is too large Load Diff
+18 -1
View File
@@ -1,4 +1,21 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": ["config:recommended"]
"extends": ["config:recommended"],
"baseBranches": ["main"],
"schedule": ["every weekend"],
"prConcurrentLimit": 10,
"pinDigests": true,
"packageRules": [
{
"matchManagers": ["npm"],
"matchUpdateTypes": ["minor", "patch"],
"groupName": "npm minor and patch"
},
{
"matchManagers": ["github-actions"],
"matchUpdateTypes": ["minor", "patch"],
"groupName": "github-actions minor and patch"
}
]
}
+200
View File
@@ -0,0 +1,200 @@
#!/usr/bin/env bash
# deploy-e2e-headlamp.sh
#
# Deploys a stock Headlamp instance with the polaris plugin loaded via
# a ConfigMap volume mount. No custom Docker images — the plugin is built
# in CI and injected as a ConfigMap.
#
# E2E resources are deployed to the `privilegedescalation-dev` namespace. Nothing
# persists beyond the test run — teardown cleans up all created resources.
#
# Prerequisites:
# - Plugin built (dist/ exists with plugin-main.js + package.json)
# - kubectl configured with cluster access
# - RBAC applied: kubectl apply -f deployment/e2e-ci-runner-rbac.yaml
#
# Environment:
# E2E_NAMESPACE — namespace for E2E Headlamp (default: privilegedescalation-dev)
# E2E_RELEASE — release/resource name prefix (default: headlamp-e2e)
# HEADLAMP_VERSION — Headlamp image tag (default: latest)
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
DIST_DIR="$REPO_ROOT/dist"
E2E_NAMESPACE="${E2E_NAMESPACE:-privilegedescalation-dev}"
E2E_RELEASE="${E2E_RELEASE:-headlamp-e2e}"
HEADLAMP_VERSION="${HEADLAMP_VERSION:-latest}"
if [ ! -d "$DIST_DIR" ]; then
echo "ERROR: dist/ not found. Run 'npm run build' first." >&2
exit 1
fi
# --- Preflight: verify RBAC before touching the cluster ---
echo "Checking RBAC permissions in namespace '${E2E_NAMESPACE}'..."
if ! kubectl auth can-i delete configmaps -n "$E2E_NAMESPACE" --quiet 2>/dev/null; then
echo "ERROR: Missing RBAC — cannot delete configmaps in namespace '${E2E_NAMESPACE}'." >&2
echo " Apply RBAC first: kubectl apply -f deployment/e2e-ci-runner-rbac.yaml" >&2
exit 1
fi
echo "=== E2E Headlamp Deployment ==="
echo " Image: ghcr.io/headlamp-k8s/headlamp:${HEADLAMP_VERSION}"
echo " Namespace: $E2E_NAMESPACE"
echo " Release: $E2E_RELEASE"
# --- Create ConfigMap from built plugin ---
echo ""
echo "Creating ConfigMap with plugin files..."
# Delete existing ConfigMap if present (idempotent redeploy)
kubectl delete configmap headlamp-polaris-plugin \
-n "$E2E_NAMESPACE" --ignore-not-found
# Create ConfigMap from dist/ contents and package.json
kubectl create configmap headlamp-polaris-plugin \
-n "$E2E_NAMESPACE" \
--from-file="$DIST_DIR" \
--from-file=package.json="$REPO_ROOT/package.json"
# --- Deploy Headlamp via kubectl apply ---
echo ""
echo "Deploying Headlamp E2E instance..."
kubectl apply -f - <<EOF
apiVersion: v1
kind: ServiceAccount
metadata:
name: ${E2E_RELEASE}
namespace: ${E2E_NAMESPACE}
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: ${E2E_RELEASE}
namespace: ${E2E_NAMESPACE}
labels:
app.kubernetes.io/name: headlamp
app.kubernetes.io/instance: ${E2E_RELEASE}
spec:
replicas: 1
selector:
matchLabels:
app.kubernetes.io/name: headlamp
app.kubernetes.io/instance: ${E2E_RELEASE}
template:
metadata:
labels:
app.kubernetes.io/name: headlamp
app.kubernetes.io/instance: ${E2E_RELEASE}
spec:
serviceAccountName: ${E2E_RELEASE}
automountServiceAccountToken: true
securityContext: {}
containers:
- name: headlamp
image: ghcr.io/headlamp-k8s/headlamp:${HEADLAMP_VERSION}
imagePullPolicy: IfNotPresent
securityContext:
runAsNonRoot: true
privileged: false
runAsUser: 100
runAsGroup: 101
args:
- "-in-cluster"
- "-in-cluster-context-name=main"
- "-plugins-dir=/headlamp/plugins"
ports:
- name: http
containerPort: 4466
protocol: TCP
readinessProbe:
httpGet:
path: /
port: http
initialDelaySeconds: 5
periodSeconds: 5
failureThreshold: 6
livenessProbe:
httpGet:
path: /
port: http
initialDelaySeconds: 10
periodSeconds: 10
volumeMounts:
- name: polaris-plugin
mountPath: /headlamp/plugins/headlamp-polaris
readOnly: true
volumes:
- name: polaris-plugin
configMap:
name: headlamp-polaris-plugin
---
apiVersion: v1
kind: Service
metadata:
name: ${E2E_RELEASE}
namespace: ${E2E_NAMESPACE}
labels:
app.kubernetes.io/name: headlamp
app.kubernetes.io/instance: ${E2E_RELEASE}
spec:
type: ClusterIP
selector:
app.kubernetes.io/name: headlamp
app.kubernetes.io/instance: ${E2E_RELEASE}
ports:
- name: http
port: 80
targetPort: http
protocol: TCP
EOF
echo "Waiting for rollout..."
kubectl rollout status "deployment/${E2E_RELEASE}" \
-n "$E2E_NAMESPACE" --timeout=120s
# --- Generate a service URL for tests ---
SVC_URL="http://${E2E_RELEASE}.${E2E_NAMESPACE}.svc.cluster.local"
# --- Wait for DNS and HTTP reachability ---
# rollout status only confirms the pod is ready per readinessProbe.
# Kubernetes Service DNS may still be propagating to the runner pod.
# Poll until the service is reachable over HTTP before handing off.
echo ""
echo "Waiting for ${SVC_URL} to be reachable..."
ATTEMPTS=0
MAX_ATTEMPTS=24 # 24 × 5s = 120s max
until curl -sf --max-time 5 "${SVC_URL}" -o /dev/null 2>/dev/null; do
ATTEMPTS=$((ATTEMPTS + 1))
if [ "$ATTEMPTS" -ge "$MAX_ATTEMPTS" ]; then
echo "ERROR: ${SVC_URL} not reachable after $((MAX_ATTEMPTS * 5))s" >&2
exit 1
fi
echo " [${ATTEMPTS}/${MAX_ATTEMPTS}] not yet reachable, retrying in 5s..."
sleep 5
done
echo ""
echo "E2E Headlamp is ready at: ${SVC_URL}"
echo " export HEADLAMP_URL=${SVC_URL}"
# --- Generate a token for test auth ---
echo ""
echo "Creating service account token for E2E auth..."
kubectl create serviceaccount headlamp-e2e-test \
-n "$E2E_NAMESPACE" --dry-run=client -o yaml | kubectl apply -f -
TOKEN=$(kubectl create token headlamp-e2e-test -n "$E2E_NAMESPACE" --duration=1h 2>/dev/null || echo "")
if [ -n "$TOKEN" ]; then
echo " export HEADLAMP_TOKEN=<generated>"
echo ""
echo "HEADLAMP_URL=${SVC_URL}" > "$REPO_ROOT/.env.e2e"
echo "HEADLAMP_TOKEN=${TOKEN}" >> "$REPO_ROOT/.env.e2e"
echo "Wrote .env.e2e with HEADLAMP_URL and HEADLAMP_TOKEN"
else
echo " WARNING: Could not generate token. Set HEADLAMP_TOKEN manually or use OIDC."
fi
echo ""
echo "E2E deployment complete."
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env bash
# teardown-e2e-headlamp.sh
#
# Tears down the dedicated E2E Headlamp instance deployed by deploy-e2e-headlamp.sh.
#
# Environment:
# E2E_NAMESPACE — namespace to clean up (default: privilegedescalation-dev)
# E2E_RELEASE — release/resource name prefix (default: headlamp-e2e)
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
E2E_NAMESPACE="${E2E_NAMESPACE:-privilegedescalation-dev}"
E2E_RELEASE="${E2E_RELEASE:-headlamp-e2e}"
echo "=== E2E Headlamp Teardown ==="
echo " Namespace: $E2E_NAMESPACE"
echo " Release: $E2E_RELEASE"
echo "Removing Headlamp Deployment, Service, and ServiceAccount..."
kubectl delete deployment "${E2E_RELEASE}" -n "$E2E_NAMESPACE" --ignore-not-found
kubectl delete service "${E2E_RELEASE}" -n "$E2E_NAMESPACE" --ignore-not-found
kubectl delete serviceaccount "${E2E_RELEASE}" -n "$E2E_NAMESPACE" --ignore-not-found
echo "Cleaning up ConfigMap..."
kubectl delete configmap headlamp-polaris-plugin -n "$E2E_NAMESPACE" --ignore-not-found
echo "Cleaning up test service account..."
kubectl delete serviceaccount headlamp-e2e-test -n "$E2E_NAMESPACE" --ignore-not-found
# Clean up local env file
rm -f "$REPO_ROOT/.env.e2e"
echo "Teardown complete."
+2
View File
@@ -16,6 +16,7 @@ vi.mock('./polaris', async importOriginal => {
data: makeAuditData([makeResult()]),
loading: false,
error: null,
triggerRefresh: vi.fn(),
})),
};
});
@@ -44,5 +45,6 @@ describe('usePolarisDataContext', () => {
expect(result.current.data).not.toBeNull();
expect(result.current.loading).toBe(false);
expect(result.current.error).toBeNull();
expect(result.current.refresh).toBeDefined();
});
});
+77
View File
@@ -0,0 +1,77 @@
import { describe, expect, it } from 'vitest';
import {
CHECK_MAPPING,
getCheckCategory,
getCheckDescription,
getCheckName,
getSeverityStatus,
} from './checkMapping';
describe('checkMapping', () => {
describe('getCheckName', () => {
it('returns human-readable name for known check IDs', () => {
expect(getCheckName('hostIPCSet')).toBe('Host IPC');
expect(getCheckName('cpuRequestsMissing')).toBe('CPU Requests');
expect(getCheckName('readinessProbeMissing')).toBe('Readiness Probe');
});
it('returns the raw check ID for unknown checks', () => {
expect(getCheckName('unknownCheck')).toBe('unknownCheck');
});
});
describe('getCheckDescription', () => {
it('returns description for known checks', () => {
expect(getCheckDescription('hostIPCSet')).toBe('Host IPC should not be configured');
});
it('returns "Unknown check" for unknown checks', () => {
expect(getCheckDescription('unknownCheck')).toBe('Unknown check');
});
});
describe('getCheckCategory', () => {
it('returns correct category for each type', () => {
expect(getCheckCategory('hostIPCSet')).toBe('Security');
expect(getCheckCategory('cpuRequestsMissing')).toBe('Efficiency');
expect(getCheckCategory('readinessProbeMissing')).toBe('Reliability');
});
it('defaults to Security for unknown checks', () => {
expect(getCheckCategory('unknownCheck')).toBe('Security');
});
});
describe('getSeverityStatus', () => {
it('maps danger to error', () => {
expect(getSeverityStatus('danger')).toBe('error');
});
it('maps warning to warning', () => {
expect(getSeverityStatus('warning')).toBe('warning');
});
it('defaults to success for other values', () => {
expect(getSeverityStatus('ignore')).toBe('success');
expect(getSeverityStatus('unknown')).toBe('success');
});
});
describe('CHECK_MAPPING', () => {
it('has entries for all expected categories', () => {
const categories = new Set(Object.values(CHECK_MAPPING).map(c => c.category));
expect(categories).toContain('Security');
expect(categories).toContain('Efficiency');
expect(categories).toContain('Reliability');
});
it('all entries have required fields', () => {
for (const [id, info] of Object.entries(CHECK_MAPPING)) {
expect(info.name, `${id} missing name`).toBeTruthy();
expect(info.description, `${id} missing description`).toBeTruthy();
expect(['Security', 'Efficiency', 'Reliability']).toContain(info.category);
expect(['danger', 'warning', 'ignore']).toContain(info.defaultSeverity);
}
});
});
});
-16
View File
@@ -207,22 +207,6 @@ export function getCheckCategory(checkId: string): 'Security' | 'Efficiency' | '
return CHECK_MAPPING[checkId]?.category || 'Security';
}
/**
* Get color for severity
*/
export function getSeverityColor(severity: string): string {
switch (severity) {
case 'danger':
return '#f44336';
case 'warning':
return '#ff9800';
case 'ignore':
return '#9e9e9e';
default:
return '#9e9e9e';
}
}
/**
* Get status for StatusLabel component
*/
+4 -3
View File
@@ -218,7 +218,8 @@ const REFRESH_STORAGE_KEY = 'polaris-plugin-refresh-interval';
const DEFAULT_INTERVAL_SECONDS = 300; // 5 minutes
const URL_STORAGE_KEY = 'polaris-plugin-dashboard-url';
const DEFAULT_DASHBOARD_URL = '/api/v1/namespaces/polaris/services/polaris-dashboard:80/proxy/';
const DEFAULT_DASHBOARD_URL =
'/api/v1/namespaces/polaris/services/http:polaris-dashboard:80/proxy/';
/**
* Retrieves the configured refresh interval from localStorage.
@@ -300,7 +301,7 @@ export function computeScore(counts: ResultCounts): number {
*
* @returns Full path to results.json endpoint
*/
function getPolarisApiPath(): string {
export function getPolarisApiPath(): string {
const baseUrl = getDashboardUrl();
return baseUrl.endsWith('/') ? `${baseUrl}results.json` : `${baseUrl}/results.json`;
}
@@ -311,7 +312,7 @@ function getPolarisApiPath(): string {
* @param url - URL to check
* @returns true if full URL, false if relative path
*/
function isFullUrl(url: string): boolean {
export function isFullUrl(url: string): boolean {
return url.startsWith('http://') || url.startsWith('https://');
}
+216
View File
@@ -0,0 +1,216 @@
import { describe, expect, it } from 'vitest';
import { makeAuditData, makeResult } from '../test-utils';
import { getTopIssues } from './topIssues';
describe('getTopIssues', () => {
it('returns empty array when no results', () => {
const data = makeAuditData([]);
expect(getTopIssues(data)).toEqual([]);
});
it('returns empty array when all checks pass', () => {
const data = makeAuditData([
makeResult({
Results: {
c1: {
ID: 'c1',
Message: '',
Details: [],
Success: true,
Severity: 'warning',
Category: 'X',
},
},
}),
]);
expect(getTopIssues(data)).toEqual([]);
});
it('aggregates failing checks from controller-level results', () => {
const data = makeAuditData([
makeResult({
Results: {
cpuRequestsMissing: {
ID: 'cpuRequestsMissing',
Message: 'missing',
Details: [],
Success: false,
Severity: 'warning',
Category: 'Efficiency',
},
},
}),
]);
const issues = getTopIssues(data);
expect(issues).toHaveLength(1);
expect(issues[0].checkId).toBe('cpuRequestsMissing');
expect(issues[0].checkName).toBe('CPU Requests');
expect(issues[0].severity).toBe('warning');
expect(issues[0].count).toBe(1);
});
it('aggregates failing checks from pod and container results', () => {
const data = makeAuditData([
makeResult({
Results: {},
PodResult: {
Name: 'pod-1',
Results: {
hostIPCSet: {
ID: 'hostIPCSet',
Message: '',
Details: [],
Success: false,
Severity: 'danger',
Category: 'Security',
},
},
ContainerResults: [
{
Name: 'container-1',
Results: {
cpuLimitsMissing: {
ID: 'cpuLimitsMissing',
Message: '',
Details: [],
Success: false,
Severity: 'warning',
Category: 'Efficiency',
},
},
},
],
},
}),
]);
const issues = getTopIssues(data);
expect(issues).toHaveLength(2);
// Danger first
expect(issues[0].checkId).toBe('hostIPCSet');
expect(issues[0].severity).toBe('danger');
expect(issues[1].checkId).toBe('cpuLimitsMissing');
});
it('counts same check across multiple workloads', () => {
const data = makeAuditData([
makeResult({
Name: 'deploy-1',
Results: {
cpuRequestsMissing: {
ID: 'cpuRequestsMissing',
Message: '',
Details: [],
Success: false,
Severity: 'warning',
Category: 'Efficiency',
},
},
}),
makeResult({
Name: 'deploy-2',
Results: {
cpuRequestsMissing: {
ID: 'cpuRequestsMissing',
Message: '',
Details: [],
Success: false,
Severity: 'warning',
Category: 'Efficiency',
},
},
}),
]);
const issues = getTopIssues(data);
expect(issues).toHaveLength(1);
expect(issues[0].count).toBe(2);
});
it('ignores checks with severity "ignore"', () => {
const data = makeAuditData([
makeResult({
Results: {
c1: {
ID: 'c1',
Message: '',
Details: [],
Success: false,
Severity: 'ignore',
Category: 'X',
},
},
}),
]);
expect(getTopIssues(data)).toEqual([]);
});
it('sorts danger before warning, then by count descending', () => {
const data = makeAuditData([
makeResult({
Name: 'deploy-1',
Results: {
cpuRequestsMissing: {
ID: 'cpuRequestsMissing',
Message: '',
Details: [],
Success: false,
Severity: 'warning',
Category: 'Efficiency',
},
},
}),
makeResult({
Name: 'deploy-2',
Results: {
cpuRequestsMissing: {
ID: 'cpuRequestsMissing',
Message: '',
Details: [],
Success: false,
Severity: 'warning',
Category: 'Efficiency',
},
hostIPCSet: {
ID: 'hostIPCSet',
Message: '',
Details: [],
Success: false,
Severity: 'danger',
Category: 'Security',
},
},
}),
]);
const issues = getTopIssues(data);
// Danger first regardless of count
expect(issues[0].severity).toBe('danger');
expect(issues[1].severity).toBe('warning');
expect(issues[1].count).toBe(2);
});
it('returns at most 10 issues', () => {
const results: Record<
string,
{
ID: string;
Message: string;
Details: string[];
Success: boolean;
Severity: 'warning';
Category: string;
}
> = {};
for (let i = 0; i < 15; i++) {
results[`check${i}`] = {
ID: `check${i}`,
Message: '',
Details: [],
Success: false,
Severity: 'warning',
Category: 'X',
};
}
const data = makeAuditData([makeResult({ Results: results })]);
expect(getTopIssues(data)).toHaveLength(10);
});
});
+173
View File
@@ -0,0 +1,173 @@
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React from 'react';
import { describe, expect, it, vi } from 'vitest';
import { makeAuditData, makeResult } from '../test-utils';
// Mock Headlamp lib
vi.mock('@kinvolk/headlamp-plugin/lib', () => ({
ApiProxy: { request: vi.fn() },
K8s: {},
}));
vi.mock('@mui/material/styles', () => ({
useTheme: () => ({
palette: {
success: { main: '#4caf50', contrastText: '#fff' },
warning: { main: '#ff9800', contrastText: '#000' },
error: { main: '#f44336', contrastText: '#fff' },
},
}),
}));
const mockPush = vi.fn();
vi.mock('react-router-dom', () => ({
useHistory: () => ({ push: mockPush }),
}));
// Set window.location.pathname for cluster extraction
beforeEach(() => {
Object.defineProperty(window, 'location', {
value: { pathname: '/c/test-cluster/some-page' },
writable: true,
});
mockPush.mockClear();
});
const mockUsePolarisDataContext = vi.fn();
vi.mock('../api/PolarisDataContext', () => ({
usePolarisDataContext: () => mockUsePolarisDataContext(),
}));
import AppBarScoreBadge from './AppBarScoreBadge';
describe('AppBarScoreBadge', () => {
it('returns null when loading', () => {
mockUsePolarisDataContext.mockReturnValue({ data: null, loading: true });
const { container } = render(<AppBarScoreBadge />);
expect(container.innerHTML).toBe('');
});
it('returns null when no data', () => {
mockUsePolarisDataContext.mockReturnValue({ data: null, loading: false });
const { container } = render(<AppBarScoreBadge />);
expect(container.innerHTML).toBe('');
});
it('renders score with success color for high score', () => {
const data = makeAuditData([
makeResult({
Results: {
c1: {
ID: 'c1',
Message: '',
Details: [],
Success: true,
Severity: 'warning',
Category: 'X',
},
},
}),
]);
mockUsePolarisDataContext.mockReturnValue({ data, loading: false });
render(<AppBarScoreBadge />);
const button = screen.getByRole('button');
expect(button).toHaveTextContent('Polaris: 100%');
expect(button.style.backgroundColor).toBe('rgb(76, 175, 80)');
});
it('renders score with error color for low score', () => {
const data = makeAuditData([
makeResult({
Results: {
c1: {
ID: 'c1',
Message: '',
Details: [],
Success: false,
Severity: 'danger',
Category: 'X',
},
},
}),
]);
mockUsePolarisDataContext.mockReturnValue({ data, loading: false });
render(<AppBarScoreBadge />);
const button = screen.getByRole('button');
expect(button).toHaveTextContent('Polaris: 0%');
expect(button.style.backgroundColor).toBe('rgb(244, 67, 54)');
});
it('navigates to /c/<cluster>/polaris on click', async () => {
const user = userEvent.setup();
const data = makeAuditData([
makeResult({
Results: {
c1: {
ID: 'c1',
Message: '',
Details: [],
Success: true,
Severity: 'warning',
Category: 'X',
},
},
}),
]);
mockUsePolarisDataContext.mockReturnValue({ data, loading: false });
render(<AppBarScoreBadge />);
await user.click(screen.getByRole('button'));
expect(mockPush).toHaveBeenCalledWith('/c/test-cluster/polaris');
});
it('navigates to /polaris when no cluster in URL', async () => {
Object.defineProperty(window, 'location', {
value: { pathname: '/settings' },
writable: true,
});
const user = userEvent.setup();
const data = makeAuditData([
makeResult({
Results: {
c1: {
ID: 'c1',
Message: '',
Details: [],
Success: true,
Severity: 'warning',
Category: 'X',
},
},
}),
]);
mockUsePolarisDataContext.mockReturnValue({ data, loading: false });
render(<AppBarScoreBadge />);
await user.click(screen.getByRole('button'));
expect(mockPush).toHaveBeenCalledWith('/polaris');
});
it('has correct aria-label', () => {
const data = makeAuditData([
makeResult({
Results: {
c1: {
ID: 'c1',
Message: '',
Details: [],
Success: true,
Severity: 'warning',
Category: 'X',
},
},
}),
]);
mockUsePolarisDataContext.mockReturnValue({ data, loading: false });
render(<AppBarScoreBadge />);
expect(screen.getByLabelText('Polaris: 100%')).toBeInTheDocument();
});
});
+31 -9
View File
@@ -1,13 +1,27 @@
import { useTheme } from '@mui/material/styles';
import React from 'react';
import { useHistory } from 'react-router-dom';
import { computeScore, countResults } from '../api/polaris';
import { usePolarisDataContext } from '../api/PolarisDataContext';
/**
* Extract the cluster name from the current browser URL.
* Headlamp cluster routes follow the pattern /c/<cluster>/...
* We read window.location.pathname directly because the AppBar renders
* outside the cluster route context, so useCluster() returns null and
* React Router's useLocation() may not reflect the cluster prefix.
*/
function getClusterFromUrl(): string | null {
const match = window.location.pathname.match(/\/c\/([^/]+)/);
return match ? match[1] : null;
}
/**
* App bar badge showing cluster Polaris score
* Clicking navigates to the overview dashboard
*/
export default function AppBarScoreBadge() {
const theme = useTheme();
const { data, loading } = usePolarisDataContext();
const history = useHistory();
@@ -18,15 +32,23 @@ export default function AppBarScoreBadge() {
const counts = countResults(data);
const score = computeScore(counts);
// Color based on score
const getColor = (score: number): string => {
if (score >= 80) return '#4caf50'; // green
if (score >= 50) return '#ff9800'; // orange
return '#f44336'; // red
// Color based on score using theme palette
const getColor = (s: number): string => {
if (s >= 80) return theme.palette.success.main;
if (s >= 50) return theme.palette.warning.main;
return theme.palette.error.main;
};
const getContrastColor = (s: number): string => {
if (s >= 80) return theme.palette.success.contrastText;
if (s >= 50) return theme.palette.warning.contrastText;
return theme.palette.error.contrastText;
};
const handleClick = () => {
history.push('/polaris');
const cluster = getClusterFromUrl();
const prefix = cluster ? `/c/${cluster}` : '';
history.push(`${prefix}/polaris`);
};
return (
@@ -39,16 +61,16 @@ export default function AppBarScoreBadge() {
borderRadius: '16px',
border: 'none',
backgroundColor: getColor(score),
color: 'white',
color: getContrastColor(score),
fontSize: '13px',
fontWeight: 500,
display: 'inline-flex',
alignItems: 'center',
gap: '4px',
}}
aria-label={`Polaris cluster score: ${score}%`}
aria-label={`Polaris: ${score}%`}
>
<span>🛡</span>
<span>{'\u{1F6E1}\uFE0F'}</span>
<span>Polaris: {score}%</span>
</button>
);
+28 -4
View File
@@ -8,6 +8,15 @@ vi.mock('@kinvolk/headlamp-plugin/lib', () => ({
ApiProxy: { request: vi.fn() },
}));
vi.mock('@mui/material/styles', () => ({
useTheme: () => ({
palette: {
primary: { main: '#1976d2' },
text: { primary: '#000', secondary: '#666' },
},
}),
}));
// Mock Headlamp CommonComponents as thin pass-throughs
vi.mock('@kinvolk/headlamp-plugin/lib/CommonComponents', () => ({
Loader: ({ title }: { title: string }) => <div data-testid="loader">{title}</div>,
@@ -34,12 +43,27 @@ vi.mock('@kinvolk/headlamp-plugin/lib/CommonComponents', () => ({
</tbody>
</table>
),
SimpleTable: ({ data }: { data: Array<any> }) => (
SimpleTable: ({
columns,
data,
}: {
columns: Array<{ label: string; getter: (row: unknown) => React.ReactNode }>;
data: unknown[];
}) => (
<table data-testid="simple-table">
<thead>
<tr>
{columns.map(col => (
<th key={col.label}>{col.label}</th>
))}
</tr>
</thead>
<tbody>
{data.map((item, idx) => (
<tr key={idx}>
<td>{JSON.stringify(item)}</td>
{data.map((row, i) => (
<tr key={i}>
{columns.map(col => (
<td key={col.label}>{col.getter(row)}</td>
))}
</tr>
))}
</tbody>
+5 -3
View File
@@ -8,6 +8,7 @@ import {
SimpleTable,
StatusLabel,
} from '@kinvolk/headlamp-plugin/lib/CommonComponents';
import { useTheme } from '@mui/material/styles';
import React from 'react';
import { getSeverityStatus } from '../api/checkMapping';
import { AuditData, computeScore, countResults, ResultCounts } from '../api/polaris';
@@ -87,6 +88,7 @@ function formatAuditTime(auditTime: string): string {
}
export default function DashboardView() {
const theme = useTheme();
const { data, loading, error, refresh } = usePolarisDataContext();
if (loading) {
@@ -109,7 +111,7 @@ export default function DashboardView() {
<SectionHeader title="Polaris — Overview" />
{data && (
<div style={{ display: 'flex', gap: '16px', alignItems: 'center' }}>
<span style={{ fontSize: '14px', color: 'var(--mui-palette-text-secondary, #666)' }}>
<span style={{ fontSize: '14px', color: theme.palette.text.secondary }}>
Last updated: {formatAuditTime(data.AuditTime)}
</span>
<button
@@ -117,8 +119,8 @@ export default function DashboardView() {
style={{
padding: '6px 16px',
backgroundColor: 'transparent',
color: 'var(--mui-palette-primary-main, #1976d2)',
border: '1px solid var(--mui-palette-primary-main, #1976d2)',
color: theme.palette.primary.main,
border: `1px solid ${theme.palette.primary.main}`,
borderRadius: '4px',
cursor: 'pointer',
fontSize: '13px',
+432
View File
@@ -0,0 +1,432 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import React from 'react';
import { describe, expect, it, vi } from 'vitest';
import { makeResult } from '../test-utils';
const { mockApiRequest } = vi.hoisted(() => ({ mockApiRequest: vi.fn() }));
vi.mock('@kinvolk/headlamp-plugin/lib', () => ({
ApiProxy: { request: mockApiRequest },
}));
vi.mock('@mui/material/styles', () => ({
useTheme: () => ({
palette: {
primary: { main: '#1976d2', contrastText: '#fff' },
action: { disabledBackground: '#e0e0e0', disabled: '#9e9e9e' },
divider: '#e0e0e0',
},
}),
}));
vi.mock('@kinvolk/headlamp-plugin/lib/CommonComponents', () => ({
SectionBox: ({ title, children }: { title?: string; children?: React.ReactNode }) => (
<div data-testid="section-box" data-title={title}>
{children}
</div>
),
StatusLabel: ({ status, children }: { status: string; children?: React.ReactNode }) => (
<span data-testid="status-label" data-status={status}>
{children}
</span>
),
Dialog: ({
open,
children,
title,
}: {
open: boolean;
onClose?: () => void;
title?: string;
children?: React.ReactNode;
}) =>
open ? (
<div data-testid="dialog" data-title={title}>
{children}
</div>
) : null,
}));
import ExemptionManager from './ExemptionManager';
const defaultProps = {
workloadResult: makeResult(),
namespace: 'default',
kind: 'Deployment',
name: 'my-deploy',
};
const resultWithPodFailures = makeResult({
PodResult: {
Name: 'pod',
Results: {
hostIPCSet: {
ID: 'hostIPCSet',
Message: 'Host IPC is set',
Details: [],
Success: false,
Severity: 'danger',
Category: 'Security',
},
hostPIDSet: {
ID: 'hostPIDSet',
Message: 'Host PID is set',
Details: [],
Success: false,
Severity: 'danger',
Category: 'Security',
},
},
ContainerResults: [],
},
});
const resultWithContainerFailures = makeResult({
PodResult: {
Name: 'pod',
Results: {},
ContainerResults: [
{
Name: 'container-1',
Results: {
cpuRequestsMissing: {
ID: 'cpuRequestsMissing',
Message: 'CPU requests missing',
Details: [],
Success: false,
Severity: 'warning',
Category: 'Efficiency',
},
},
},
],
},
});
const resultWithIgnoredFailures = makeResult({
PodResult: {
Name: 'pod',
Results: {
hostIPCSet: {
ID: 'hostIPCSet',
Message: '',
Details: [],
Success: false,
Severity: 'ignore',
Category: 'Security',
},
},
ContainerResults: [],
},
});
describe('ExemptionManager', () => {
describe('rendering failing checks', () => {
it('shows disabled Add Exemption button when no failing checks', () => {
render(<ExemptionManager {...defaultProps} />);
const btn = screen.getByRole('button', { name: /add exemption/i });
expect(btn).toBeDisabled();
});
it('shows enabled Add Exemption button when there are failing checks', () => {
render(<ExemptionManager {...defaultProps} workloadResult={resultWithPodFailures} />);
const btn = screen.getByRole('button', { name: /add exemption/i });
expect(btn).not.toBeDisabled();
});
it('does not include ignored-severity checks as failing', () => {
render(<ExemptionManager {...defaultProps} workloadResult={resultWithIgnoredFailures} />);
const btn = screen.getByRole('button', { name: /add exemption/i });
expect(btn).toBeDisabled();
});
it('collects failing checks from pod-level results', () => {
render(<ExemptionManager {...defaultProps} workloadResult={resultWithPodFailures} />);
fireEvent.click(screen.getByRole('button', { name: /add exemption/i }));
expect(screen.getByText('Host IPC')).toBeInTheDocument();
expect(screen.getByText('Host PID')).toBeInTheDocument();
});
it('collects failing checks from container-level results', () => {
render(<ExemptionManager {...defaultProps} workloadResult={resultWithContainerFailures} />);
fireEvent.click(screen.getByRole('button', { name: /add exemption/i }));
expect(screen.getByText('CPU Requests')).toBeInTheDocument();
});
it('deduplicates checks that appear in multiple containers', () => {
const resultWithDuplicate = makeResult({
PodResult: {
Name: 'pod',
Results: {},
ContainerResults: [
{
Name: 'container-1',
Results: {
cpuRequestsMissing: {
ID: 'cpuRequestsMissing',
Message: '',
Details: [],
Success: false,
Severity: 'warning',
Category: 'Efficiency',
},
},
},
{
Name: 'container-2',
Results: {
cpuRequestsMissing: {
ID: 'cpuRequestsMissing',
Message: '',
Details: [],
Success: false,
Severity: 'warning',
Category: 'Efficiency',
},
},
},
],
},
});
render(<ExemptionManager {...defaultProps} workloadResult={resultWithDuplicate} />);
fireEvent.click(screen.getByRole('button', { name: /add exemption/i }));
const items = screen.getAllByText('CPU Requests');
expect(items).toHaveLength(1);
});
});
describe('dialog interactions', () => {
it('opens dialog when Add Exemption button is clicked', () => {
render(<ExemptionManager {...defaultProps} workloadResult={resultWithPodFailures} />);
expect(screen.queryByTestId('dialog')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /add exemption/i }));
expect(screen.getByTestId('dialog')).toBeInTheDocument();
});
it('closes dialog when Cancel button is clicked', () => {
render(<ExemptionManager {...defaultProps} workloadResult={resultWithPodFailures} />);
fireEvent.click(screen.getByRole('button', { name: /add exemption/i }));
expect(screen.getByTestId('dialog')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /cancel/i }));
expect(screen.queryByTestId('dialog')).not.toBeInTheDocument();
});
it('toggles individual check selection', () => {
render(<ExemptionManager {...defaultProps} workloadResult={resultWithPodFailures} />);
fireEvent.click(screen.getByRole('button', { name: /add exemption/i }));
// Find the checkbox next to "Host IPC"
const checkboxes = screen.getAllByRole('checkbox');
// First checkbox is "Exempt from all checks", rest are individual checks
const hostIPCCheckbox = checkboxes[1];
expect(hostIPCCheckbox).not.toBeChecked();
fireEvent.click(hostIPCCheckbox);
expect(hostIPCCheckbox).toBeChecked();
fireEvent.click(hostIPCCheckbox);
expect(hostIPCCheckbox).not.toBeChecked();
});
it('hides individual checks list when exempt-all is toggled', () => {
render(<ExemptionManager {...defaultProps} workloadResult={resultWithPodFailures} />);
fireEvent.click(screen.getByRole('button', { name: /add exemption/i }));
expect(screen.getByText('Host IPC')).toBeInTheDocument();
const exemptAllCheckbox = screen.getByRole('checkbox', { name: /exempt from all checks/i });
fireEvent.click(exemptAllCheckbox);
expect(screen.queryByText('Host IPC')).not.toBeInTheDocument();
});
it('Apply button is disabled when no checks selected and exemptAll is false', () => {
render(<ExemptionManager {...defaultProps} workloadResult={resultWithPodFailures} />);
fireEvent.click(screen.getByRole('button', { name: /add exemption/i }));
expect(screen.getByRole('button', { name: /apply/i })).toBeDisabled();
});
it('Apply button is enabled when exemptAll is checked', () => {
render(<ExemptionManager {...defaultProps} workloadResult={resultWithPodFailures} />);
fireEvent.click(screen.getByRole('button', { name: /add exemption/i }));
const exemptAllCheckbox = screen.getByRole('checkbox', { name: /exempt from all checks/i });
fireEvent.click(exemptAllCheckbox);
expect(screen.getByRole('button', { name: /apply/i })).not.toBeDisabled();
});
it('Apply button is enabled when at least one individual check is selected', () => {
render(<ExemptionManager {...defaultProps} workloadResult={resultWithPodFailures} />);
fireEvent.click(screen.getByRole('button', { name: /add exemption/i }));
const checkboxes = screen.getAllByRole('checkbox');
fireEvent.click(checkboxes[1]); // select first individual check
expect(screen.getByRole('button', { name: /apply/i })).not.toBeDisabled();
});
});
describe('ApiProxy.request calls', () => {
it('patches with exempt-all annotation when exemptAll is selected', async () => {
mockApiRequest.mockResolvedValue({});
render(<ExemptionManager {...defaultProps} workloadResult={resultWithPodFailures} />);
fireEvent.click(screen.getByRole('button', { name: /add exemption/i }));
fireEvent.click(screen.getByRole('checkbox', { name: /exempt from all checks/i }));
fireEvent.click(screen.getByRole('button', { name: /apply/i }));
await waitFor(() => {
expect(mockApiRequest).toHaveBeenCalledWith(
'/apis/apps/v1/namespaces/default/deployments/my-deploy',
expect.objectContaining({
method: 'PATCH',
headers: { 'Content-Type': 'application/strategic-merge-patch+json' },
body: JSON.stringify({
metadata: {
annotations: { 'polaris.fairwinds.com/exempt': 'true' },
},
}),
})
);
});
});
it('patches with per-check annotations when individual checks selected', async () => {
mockApiRequest.mockResolvedValue({});
render(<ExemptionManager {...defaultProps} workloadResult={resultWithPodFailures} />);
fireEvent.click(screen.getByRole('button', { name: /add exemption/i }));
// Select first check (hostIPCSet)
fireEvent.click(screen.getAllByRole('checkbox')[1]);
fireEvent.click(screen.getByRole('button', { name: /apply/i }));
await waitFor(() => {
expect(mockApiRequest).toHaveBeenCalledWith(
'/apis/apps/v1/namespaces/default/deployments/my-deploy',
expect.objectContaining({
method: 'PATCH',
body: JSON.stringify({
metadata: {
annotations: { 'polaris.fairwinds.com/hostIPCSet-exempt': 'true' },
},
}),
})
);
});
});
it('uses core API path for Pod kind (no api group)', async () => {
mockApiRequest.mockResolvedValue({});
render(
<ExemptionManager {...defaultProps} kind="Pod" workloadResult={resultWithPodFailures} />
);
fireEvent.click(screen.getByRole('button', { name: /add exemption/i }));
fireEvent.click(screen.getByRole('checkbox', { name: /exempt from all checks/i }));
fireEvent.click(screen.getByRole('button', { name: /apply/i }));
await waitFor(() => {
expect(mockApiRequest).toHaveBeenCalledWith(
'/api/v1/namespaces/default/pods/my-deploy',
expect.anything()
);
});
});
it('uses batch API group for Job kind', async () => {
mockApiRequest.mockResolvedValue({});
render(
<ExemptionManager {...defaultProps} kind="Job" workloadResult={resultWithPodFailures} />
);
fireEvent.click(screen.getByRole('button', { name: /add exemption/i }));
fireEvent.click(screen.getByRole('checkbox', { name: /exempt from all checks/i }));
fireEvent.click(screen.getByRole('button', { name: /apply/i }));
await waitFor(() => {
expect(mockApiRequest).toHaveBeenCalledWith(
'/apis/batch/v1/namespaces/default/jobs/my-deploy',
expect.anything()
);
});
});
it('uses batch API group for CronJob kind', async () => {
mockApiRequest.mockResolvedValue({});
render(
<ExemptionManager {...defaultProps} kind="CronJob" workloadResult={resultWithPodFailures} />
);
fireEvent.click(screen.getByRole('button', { name: /add exemption/i }));
fireEvent.click(screen.getByRole('checkbox', { name: /exempt from all checks/i }));
fireEvent.click(screen.getByRole('button', { name: /apply/i }));
await waitFor(() => {
expect(mockApiRequest).toHaveBeenCalledWith(
'/apis/batch/v1/namespaces/default/cronjobs/my-deploy',
expect.anything()
);
});
});
it('uses apps API group for StatefulSet kind', async () => {
mockApiRequest.mockResolvedValue({});
render(
<ExemptionManager
{...defaultProps}
kind="StatefulSet"
workloadResult={resultWithPodFailures}
/>
);
fireEvent.click(screen.getByRole('button', { name: /add exemption/i }));
fireEvent.click(screen.getByRole('checkbox', { name: /exempt from all checks/i }));
fireEvent.click(screen.getByRole('button', { name: /apply/i }));
await waitFor(() => {
expect(mockApiRequest).toHaveBeenCalledWith(
'/apis/apps/v1/namespaces/default/statefulsets/my-deploy',
expect.anything()
);
});
});
});
describe('feedback states', () => {
it('shows success feedback and closes dialog after successful apply', async () => {
mockApiRequest.mockResolvedValue({});
render(<ExemptionManager {...defaultProps} workloadResult={resultWithPodFailures} />);
fireEvent.click(screen.getByRole('button', { name: /add exemption/i }));
fireEvent.click(screen.getByRole('checkbox', { name: /exempt from all checks/i }));
fireEvent.click(screen.getByRole('button', { name: /apply/i }));
await waitFor(() => {
expect(screen.queryByTestId('dialog')).not.toBeInTheDocument();
const label = screen.getByTestId('status-label');
expect(label).toHaveAttribute('data-status', 'success');
expect(label).toHaveTextContent('Exemptions applied successfully');
});
});
it('shows error feedback and keeps dialog closed after failed apply', async () => {
mockApiRequest.mockRejectedValue(new Error('403 Forbidden'));
render(<ExemptionManager {...defaultProps} workloadResult={resultWithPodFailures} />);
fireEvent.click(screen.getByRole('button', { name: /add exemption/i }));
fireEvent.click(screen.getByRole('checkbox', { name: /exempt from all checks/i }));
fireEvent.click(screen.getByRole('button', { name: /apply/i }));
await waitFor(() => {
const label = screen.getByTestId('status-label');
expect(label).toHaveAttribute('data-status', 'error');
expect(label).toHaveTextContent(/failed to apply exemptions/i);
});
});
it('shows "Applying..." text on Apply button while in-flight', async () => {
let resolveRequest!: () => void;
mockApiRequest.mockReturnValue(
new Promise<void>(res => {
resolveRequest = res;
})
);
render(<ExemptionManager {...defaultProps} workloadResult={resultWithPodFailures} />);
fireEvent.click(screen.getByRole('button', { name: /add exemption/i }));
fireEvent.click(screen.getByRole('checkbox', { name: /exempt from all checks/i }));
fireEvent.click(screen.getByRole('button', { name: /apply/i }));
expect(screen.getByRole('button', { name: /applying/i })).toBeInTheDocument();
resolveRequest();
await waitFor(() => {
expect(screen.queryByTestId('dialog')).not.toBeInTheDocument();
});
});
});
});
+33 -62
View File
@@ -1,5 +1,6 @@
import { ApiProxy } from '@kinvolk/headlamp-plugin/lib';
import { Dialog, NameValueTable, SectionBox } from '@kinvolk/headlamp-plugin/lib/CommonComponents';
import { Dialog, SectionBox, StatusLabel } from '@kinvolk/headlamp-plugin/lib/CommonComponents';
import { useTheme } from '@mui/material/styles';
import React from 'react';
import { getCheckName } from '../api/checkMapping';
import { Result } from '../api/polaris';
@@ -26,17 +27,14 @@ export default function ExemptionManager({
kind,
name,
}: ExemptionManagerProps) {
const theme = useTheme();
const [dialogOpen, setDialogOpen] = React.useState(false);
const [selectedChecks, setSelectedChecks] = React.useState<Set<string>>(new Set());
const [exemptAll, setExemptAll] = React.useState(false);
const [applying, setApplying] = React.useState(false);
// Extract current exemptions from workload metadata
const getExemptions = (): string[] => {
// This would need to fetch the actual workload from K8s API
// For now, return empty array as placeholder
return [];
};
const [feedback, setFeedback] = React.useState<{ success: boolean; message: string } | null>(
null
);
// Extract failing checks for this workload
const getFailingChecks = (): CheckFailure[] => {
@@ -75,7 +73,6 @@ export default function ExemptionManager({
};
const failingChecks = getFailingChecks();
const currentExemptions = getExemptions();
const handleCheckToggle = (checkId: string) => {
const newSelected = new Set(selectedChecks);
@@ -89,15 +86,15 @@ export default function ExemptionManager({
const applyExemptions = async () => {
setApplying(true);
setFeedback(null);
try {
// Construct the API path based on kind
const apiGroup = getApiGroup(kind);
const apiVersion = 'v1'; // This would need to be dynamic based on kind
const plural = getPlural(kind);
const patchPath = apiGroup
? `/apis/${apiGroup}/${apiVersion}/namespaces/${namespace}/${plural}/${name}`
? `/apis/${apiGroup}/v1/namespaces/${namespace}/${plural}/${name}`
: `/api/v1/namespaces/${namespace}/${plural}/${name}`;
// Build annotations patch
@@ -128,46 +125,27 @@ export default function ExemptionManager({
setDialogOpen(false);
setSelectedChecks(new Set());
setExemptAll(false);
// Show success message (would need notistack integration)
alert('Exemptions applied successfully');
setFeedback({ success: true, message: 'Exemptions applied successfully' });
} catch (err) {
alert(`Failed to apply exemptions: ${String(err)}`);
setFeedback({ success: false, message: `Failed to apply exemptions: ${String(err)}` });
} finally {
setApplying(false);
}
};
const isDisabled = applying || (!exemptAll && selectedChecks.size === 0);
return (
<>
<SectionBox title="Exemptions">
{currentExemptions.length > 0 ? (
<NameValueTable
rows={currentExemptions.map(exemption => ({
name: exemption,
value: (
<button
style={{
padding: '4px 12px',
backgroundColor: 'var(--mui-palette-error-main, #f44336)',
color: 'var(--mui-palette-error-contrastText, #fff)',
border: 'none',
borderRadius: '4px',
cursor: 'pointer',
fontSize: '12px',
}}
onClick={() => {
// Remove exemption logic
alert('Remove exemption: ' + exemption);
}}
>
Remove
</button>
),
}))}
/>
) : (
<p>No exemptions configured</p>
<p>No exemptions configured</p>
{feedback && (
<div style={{ marginBottom: '8px' }}>
<StatusLabel status={feedback.success ? 'success' : 'error'}>
{feedback.message}
</StatusLabel>
</div>
)}
<button
@@ -177,18 +155,14 @@ export default function ExemptionManager({
marginTop: '8px',
padding: '6px 16px',
backgroundColor:
failingChecks.length === 0
? 'var(--mui-palette-action-disabledBackground, #e0e0e0)'
: 'transparent',
failingChecks.length === 0 ? theme.palette.action.disabledBackground : 'transparent',
color:
failingChecks.length === 0
? 'var(--mui-palette-action-disabled, #9e9e9e)'
: 'var(--mui-palette-primary-main, #1976d2)',
? theme.palette.action.disabled
: theme.palette.primary.main,
border: '1px solid',
borderColor:
failingChecks.length === 0
? 'var(--mui-palette-divider, #e0e0e0)'
: 'var(--mui-palette-primary-main, #1976d2)',
failingChecks.length === 0 ? theme.palette.divider : theme.palette.primary.main,
borderRadius: '4px',
cursor: failingChecks.length === 0 ? 'not-allowed' : 'pointer',
fontSize: '13px',
@@ -246,7 +220,7 @@ export default function ExemptionManager({
style={{
padding: '6px 16px',
backgroundColor: 'transparent',
color: 'var(--mui-palette-primary-main, #1976d2)',
color: theme.palette.primary.main,
border: 'none',
borderRadius: '4px',
cursor: 'pointer',
@@ -257,21 +231,18 @@ export default function ExemptionManager({
</button>
<button
onClick={applyExemptions}
disabled={applying || (!exemptAll && selectedChecks.size === 0)}
disabled={isDisabled}
style={{
padding: '6px 16px',
backgroundColor:
applying || (!exemptAll && selectedChecks.size === 0)
? 'var(--mui-palette-action-disabledBackground, #e0e0e0)'
: 'var(--mui-palette-primary-main, #1976d2)',
color:
applying || (!exemptAll && selectedChecks.size === 0)
? 'var(--mui-palette-action-disabled, #9e9e9e)'
: 'var(--mui-palette-primary-contrastText, #fff)',
backgroundColor: isDisabled
? theme.palette.action.disabledBackground
: theme.palette.primary.main,
color: isDisabled
? theme.palette.action.disabled
: theme.palette.primary.contrastText,
border: 'none',
borderRadius: '4px',
cursor:
applying || (!exemptAll && selectedChecks.size === 0) ? 'not-allowed' : 'pointer',
cursor: isDisabled ? 'not-allowed' : 'pointer',
fontSize: '13px',
fontWeight: 500,
}}
+278
View File
@@ -0,0 +1,278 @@
import { render, screen } from '@testing-library/react';
import React from 'react';
import { describe, expect, it, vi } from 'vitest';
import { makeAuditData, makeResult } from '../test-utils';
// Mock Headlamp lib
vi.mock('@kinvolk/headlamp-plugin/lib', () => ({
ApiProxy: { request: vi.fn() },
}));
vi.mock('@mui/material/styles', () => ({
useTheme: () => ({
palette: {
primary: { main: '#1976d2' },
text: { primary: '#000', secondary: '#666' },
action: { disabledBackground: '#e0e0e0', disabled: '#9e9e9e' },
divider: '#e0e0e0',
error: { main: '#f44336', contrastText: '#fff' },
success: { main: '#4caf50' },
warning: { main: '#ff9800' },
},
}),
}));
// Mock react-router-dom
vi.mock('react-router-dom', () => ({
Link: ({ to, children, style }: { to: string; children: React.ReactNode; style?: object }) => (
<a href={to} style={style}>
{children}
</a>
),
}));
// Mock Headlamp CommonComponents
vi.mock('@kinvolk/headlamp-plugin/lib/CommonComponents', () => ({
SectionBox: ({ title, children }: { title?: string; children?: React.ReactNode }) => (
<div data-testid="section-box" data-title={title}>
{children}
</div>
),
StatusLabel: ({ status, children }: { status: string; children?: React.ReactNode }) => (
<span data-testid="status-label" data-status={status}>
{children}
</span>
),
NameValueTable: ({ rows }: { rows: Array<{ name: string; value: React.ReactNode }> }) => (
<table data-testid="name-value-table">
<tbody>
{rows.map(row => (
<tr key={row.name}>
<td>{row.name}</td>
<td>{row.value}</td>
</tr>
))}
</tbody>
</table>
),
SimpleTable: ({
columns,
data,
}: {
columns: Array<{ label: string; getter: (row: unknown) => React.ReactNode }>;
data: unknown[];
}) => (
<table data-testid="simple-table">
<thead>
<tr>
{columns.map(col => (
<th key={col.label}>{col.label}</th>
))}
</tr>
</thead>
<tbody>
{data.map((row, i) => (
<tr key={i}>
{columns.map(col => (
<td key={col.label}>{col.getter(row)}</td>
))}
</tr>
))}
</tbody>
</table>
),
Dialog: () => null,
}));
// Mock ExemptionManager
vi.mock('./ExemptionManager', () => ({
default: () => <div data-testid="exemption-manager" />,
}));
const mockUsePolarisDataContext = vi.fn();
vi.mock('../api/PolarisDataContext', () => ({
usePolarisDataContext: () => mockUsePolarisDataContext(),
}));
import InlineAuditSection from './InlineAuditSection';
describe('InlineAuditSection', () => {
it('returns null when loading', () => {
mockUsePolarisDataContext.mockReturnValue({ data: null, loading: true, error: null });
const { container } = render(
<InlineAuditSection
resource={{ kind: 'Deployment', metadata: { name: 'x', namespace: 'y' } }}
/>
);
expect(container.innerHTML).toBe('');
});
it('returns null for unsupported kind', () => {
mockUsePolarisDataContext.mockReturnValue({
data: makeAuditData([]),
loading: false,
error: null,
});
const { container } = render(
<InlineAuditSection resource={{ kind: 'Service', metadata: { name: 'x', namespace: 'y' } }} />
);
expect(container.innerHTML).toBe('');
});
it('shows "not detected" when workload not found in audit data', () => {
mockUsePolarisDataContext.mockReturnValue({
data: makeAuditData([]),
loading: false,
error: null,
});
render(
<InlineAuditSection
resource={{ kind: 'Deployment', metadata: { name: 'my-app', namespace: 'default' } }}
/>
);
expect(screen.getByText(/Polaris dashboard not detected/)).toBeInTheDocument();
});
it('renders score and summary for a matching workload', () => {
const data = makeAuditData([
makeResult({
Name: 'my-app',
Namespace: 'default',
Kind: 'Deployment',
Results: {
c1: {
ID: 'c1',
Message: '',
Details: [],
Success: true,
Severity: 'warning',
Category: 'X',
},
c2: {
ID: 'c2',
Message: '',
Details: [],
Success: false,
Severity: 'warning',
Category: 'X',
},
},
}),
]);
mockUsePolarisDataContext.mockReturnValue({ data, loading: false, error: null });
render(
<InlineAuditSection
resource={{ kind: 'Deployment', metadata: { name: 'my-app', namespace: 'default' } }}
/>
);
expect(screen.getByText('50%')).toBeInTheDocument();
expect(screen.getByText(/1 passing, 1 warnings, 0 dangers/)).toBeInTheDocument();
});
it('renders failing checks table with pod and container results', () => {
const data = makeAuditData([
makeResult({
Name: 'my-app',
Namespace: 'default',
Kind: 'Deployment',
Results: {},
PodResult: {
Name: 'pod',
Results: {
hostIPCSet: {
ID: 'hostIPCSet',
Message: 'Host IPC is set',
Details: [],
Success: false,
Severity: 'danger',
Category: 'Security',
},
},
ContainerResults: [
{
Name: 'container-1',
Results: {
cpuRequestsMissing: {
ID: 'cpuRequestsMissing',
Message: 'CPU requests missing',
Details: [],
Success: false,
Severity: 'warning',
Category: 'Efficiency',
},
},
},
],
},
}),
]);
mockUsePolarisDataContext.mockReturnValue({ data, loading: false, error: null });
render(
<InlineAuditSection
resource={{ kind: 'Deployment', metadata: { name: 'my-app', namespace: 'default' } }}
/>
);
expect(screen.getByText('Host IPC')).toBeInTheDocument();
expect(screen.getByText('CPU Requests')).toBeInTheDocument();
expect(screen.getByText('Host IPC is set')).toBeInTheDocument();
});
it('renders link to full report', () => {
const data = makeAuditData([
makeResult({
Name: 'my-app',
Namespace: 'default',
Kind: 'Deployment',
Results: {
c1: {
ID: 'c1',
Message: '',
Details: [],
Success: true,
Severity: 'warning',
Category: 'X',
},
},
}),
]);
mockUsePolarisDataContext.mockReturnValue({ data, loading: false, error: null });
render(
<InlineAuditSection
resource={{ kind: 'Deployment', metadata: { name: 'my-app', namespace: 'default' } }}
/>
);
const link = screen.getByText('View Full Report →');
expect(link).toHaveAttribute('href', '/polaris/namespaces#default');
});
it('renders ExemptionManager', () => {
const data = makeAuditData([
makeResult({
Name: 'my-app',
Namespace: 'default',
Kind: 'Deployment',
Results: {
c1: {
ID: 'c1',
Message: '',
Details: [],
Success: true,
Severity: 'warning',
Category: 'X',
},
},
}),
]);
mockUsePolarisDataContext.mockReturnValue({ data, loading: false, error: null });
render(
<InlineAuditSection
resource={{ kind: 'Deployment', metadata: { name: 'my-app', namespace: 'default' } }}
/>
);
expect(screen.getByTestId('exemption-manager')).toBeInTheDocument();
});
});
+13 -5
View File
@@ -4,6 +4,7 @@ import {
SimpleTable,
StatusLabel,
} from '@kinvolk/headlamp-plugin/lib/CommonComponents';
import { useTheme } from '@mui/material/styles';
import React from 'react';
import { Link } from 'react-router-dom';
import { getCheckName, getSeverityStatus } from '../api/checkMapping';
@@ -18,8 +19,17 @@ interface CheckFailure {
message: string;
}
interface KubeResource {
kind: string;
metadata?: {
name?: string;
namespace?: string;
annotations?: Record<string, string>;
};
}
interface InlineAuditSectionProps {
resource: any; // KubeObject from Headlamp
resource: KubeResource;
}
/**
@@ -27,6 +37,7 @@ interface InlineAuditSectionProps {
* Shows a compact summary of Polaris findings for Deployments, StatefulSets, etc.
*/
export default function InlineAuditSection({ resource }: InlineAuditSectionProps) {
const theme = useTheme();
const { data, loading } = usePolarisDataContext();
if (loading || !data) {
@@ -156,10 +167,7 @@ export default function InlineAuditSection({ resource }: InlineAuditSectionProps
)}
<div style={{ marginTop: '16px' }}>
<Link
to={`/polaris/namespaces#${namespace}`}
style={{ color: 'var(--link-color, #1976d2)' }}
>
<Link to={`/polaris/namespaces#${namespace}`} style={{ color: theme.palette.primary.main }}>
View Full Report
</Link>
</div>
-200
View File
@@ -1,200 +0,0 @@
import { render, screen } from '@testing-library/react';
import React from 'react';
import { describe, expect, it, vi } from 'vitest';
import { makeAuditData, makeResult } from '../test-utils';
// Mock Headlamp lib
vi.mock('@kinvolk/headlamp-plugin/lib', () => ({
ApiProxy: { request: vi.fn() },
}));
// Mock react-router-dom useParams
const mockNamespace = vi.fn(() => 'test-ns');
vi.mock('react-router-dom', () => ({
useParams: () => ({ namespace: mockNamespace() }),
}));
// Mock Headlamp CommonComponents
vi.mock('@kinvolk/headlamp-plugin/lib/CommonComponents', () => ({
Loader: ({ title }: { title: string }) => <div data-testid="loader">{title}</div>,
SectionBox: ({ title, children }: { title?: string; children?: React.ReactNode }) => (
<div data-testid="section-box" data-title={title}>
{children}
</div>
),
SectionHeader: ({ title }: { title: string }) => <div data-testid="section-header">{title}</div>,
StatusLabel: ({ status, children }: { status: string; children?: React.ReactNode }) => (
<span data-testid="status-label" data-status={status}>
{children}
</span>
),
NameValueTable: ({ rows }: { rows: Array<{ name: string; value: React.ReactNode }> }) => (
<table data-testid="name-value-table">
<tbody>
{rows.map(row => (
<tr key={row.name}>
<td>{row.name}</td>
<td>{row.value}</td>
</tr>
))}
</tbody>
</table>
),
SimpleTable: ({
columns,
data,
emptyMessage,
}: {
columns: Array<{ label: string; getter: (row: unknown) => React.ReactNode }>;
data: unknown[];
emptyMessage?: string;
}) =>
data.length === 0 ? (
<div data-testid="simple-table-empty">{emptyMessage}</div>
) : (
<table data-testid="simple-table">
<thead>
<tr>
{columns.map(col => (
<th key={col.label}>{col.label}</th>
))}
</tr>
</thead>
<tbody>
{data.map((row, i) => (
<tr key={i}>
{columns.map(col => (
<td key={col.label}>{col.getter(row)}</td>
))}
</tr>
))}
</tbody>
</table>
),
}));
const mockUsePolarisDataContext = vi.fn();
vi.mock('../api/PolarisDataContext', () => ({
usePolarisDataContext: () => mockUsePolarisDataContext(),
}));
import NamespaceDetailView from './NamespaceDetailView';
describe('NamespaceDetailView', () => {
it('renders loader when loading', () => {
mockUsePolarisDataContext.mockReturnValue({
data: null,
loading: true,
error: null,
});
render(<NamespaceDetailView />);
expect(screen.getByTestId('loader')).toHaveTextContent('Loading Polaris data for test-ns');
});
it('renders error message when error is set', () => {
mockUsePolarisDataContext.mockReturnValue({
data: null,
loading: false,
error: 'Access denied (403)',
});
render(<NamespaceDetailView />);
expect(screen.getByText('Access denied (403)')).toBeInTheDocument();
expect(screen.getByTestId('section-header')).toHaveTextContent('Polaris — test-ns');
});
it('renders "No Data" when no data and no error', () => {
mockUsePolarisDataContext.mockReturnValue({
data: null,
loading: false,
error: null,
});
render(<NamespaceDetailView />);
expect(screen.getByText('No Polaris audit results found.')).toBeInTheDocument();
});
it('renders namespace score and resource table with data', () => {
const data = makeAuditData([
makeResult({
Name: 'deploy-a',
Namespace: 'test-ns',
Kind: 'Deployment',
Results: {
c1: {
ID: 'c1',
Message: '',
Details: [],
Success: true,
Severity: 'warning',
Category: 'X',
},
c2: {
ID: 'c2',
Message: '',
Details: [],
Success: false,
Severity: 'warning',
Category: 'X',
},
},
}),
makeResult({
Name: 'other',
Namespace: 'other-ns',
Kind: 'Deployment',
Results: {
c3: {
ID: 'c3',
Message: '',
Details: [],
Success: true,
Severity: 'warning',
Category: 'X',
},
},
}),
]);
mockUsePolarisDataContext.mockReturnValue({
data,
loading: false,
error: null,
});
render(<NamespaceDetailView />);
// Header
expect(screen.getByTestId('section-header')).toHaveTextContent('Polaris — test-ns');
// Score section: 50% (1 pass / 2 total)
expect(screen.getByText('50%')).toBeInTheDocument();
expect(screen.getByText('Total Checks')).toBeInTheDocument();
// Resource table shows only test-ns resources
expect(screen.getByText('deploy-a')).toBeInTheDocument();
expect(screen.queryByText('other')).not.toBeInTheDocument();
});
it('renders empty table message for namespace with no results', () => {
const data = makeAuditData([
makeResult({
Name: 'deploy-a',
Namespace: 'other-ns',
Results: {},
}),
]);
mockUsePolarisDataContext.mockReturnValue({
data,
loading: false,
error: null,
});
render(<NamespaceDetailView />);
expect(screen.getByTestId('simple-table-empty')).toHaveTextContent(
'No resources found in namespace "test-ns"'
);
});
});
-163
View File
@@ -1,163 +0,0 @@
import {
Loader,
NameValueTable,
SectionBox,
SectionHeader,
SimpleTable,
StatusLabel,
} from '@kinvolk/headlamp-plugin/lib/CommonComponents';
import React from 'react';
import { useParams } from 'react-router-dom';
import {
computeScore,
countResultsForItems,
filterResultsByNamespace,
getPolarisProxyUrl,
Result,
ResultCounts,
} from '../api/polaris';
import { usePolarisDataContext } from '../api/PolarisDataContext';
function scoreStatus(score: number): 'success' | 'warning' | 'error' {
if (score >= 80) return 'success';
if (score >= 50) return 'warning';
return 'error';
}
function resourceCounts(result: Result): ResultCounts {
return countResultsForItems([result]);
}
export default function NamespaceDetailView() {
const { namespace } = useParams<{ namespace: string }>();
const { data, loading, error } = usePolarisDataContext();
if (loading) {
return <Loader title={`Loading Polaris data for ${namespace}...`} />;
}
if (error) {
return (
<>
<SectionHeader title={`Polaris — ${namespace}`} />
<SectionBox title="Error">
<NameValueTable
rows={[
{
name: 'Status',
value: <StatusLabel status="error">{error}</StatusLabel>,
},
]}
/>
</SectionBox>
</>
);
}
if (!data) {
return (
<>
<SectionHeader title={`Polaris — ${namespace}`} />
<SectionBox title="No Data">
<NameValueTable rows={[{ name: 'Status', value: 'No Polaris audit results found.' }]} />
</SectionBox>
</>
);
}
const results = filterResultsByNamespace(data, namespace);
const counts = countResultsForItems(results);
const score = computeScore(counts);
const status = scoreStatus(score);
const countsPerResource = new Map<string, ResultCounts>();
for (const r of results) {
countsPerResource.set(`${r.Namespace}/${r.Kind}/${r.Name}`, resourceCounts(r));
}
function getResourceCounts(row: Result): ResultCounts {
return countsPerResource.get(`${row.Namespace}/${row.Kind}/${row.Name}`) ?? resourceCounts(row);
}
return (
<>
<SectionHeader title={`Polaris — ${namespace}`} />
<SectionBox title="External">
<NameValueTable
rows={[
{
name: 'Polaris Dashboard',
value: (
<a href={getPolarisProxyUrl()} target="_blank" rel="noopener noreferrer">
View in Polaris Dashboard
</a>
),
},
]}
/>
</SectionBox>
<SectionBox title="Namespace Score">
<NameValueTable
rows={[
{
name: 'Score',
value: <StatusLabel status={status}>{score}%</StatusLabel>,
},
{ name: 'Total Checks', value: String(counts.total) },
{
name: 'Pass',
value: <StatusLabel status="success">{counts.pass}</StatusLabel>,
},
{
name: 'Warning',
value: <StatusLabel status="warning">{counts.warning}</StatusLabel>,
},
{
name: 'Danger',
value: <StatusLabel status="error">{counts.danger}</StatusLabel>,
},
{
name: 'Skipped',
value: (
<span title="Only counts checks with Severity=ignore. Annotation-based exemptions are not included.">
{counts.skipped}
</span>
),
},
]}
/>
</SectionBox>
<SectionBox title="Resources">
<SimpleTable
columns={[
{ label: 'Name', getter: (row: Result) => row.Name },
{ label: 'Kind', getter: (row: Result) => row.Kind },
{
label: 'Pass',
getter: (row: Result) => (
<StatusLabel status="success">{getResourceCounts(row).pass}</StatusLabel>
),
},
{
label: 'Warning',
getter: (row: Result) => (
<StatusLabel status="warning">{getResourceCounts(row).warning}</StatusLabel>
),
},
{
label: 'Danger',
getter: (row: Result) => (
<StatusLabel status="error">{getResourceCounts(row).danger}</StatusLabel>
),
},
]}
data={results}
emptyMessage={`No resources found in namespace "${namespace}".`}
/>
</SectionBox>
</>
);
}
@@ -14,6 +14,48 @@ vi.mock('@kinvolk/headlamp-plugin/lib', () => ({
},
}));
// Mock MUI components
vi.mock('@mui/material/Drawer', () => ({
default: ({
open,
children,
}: {
open: boolean;
children: React.ReactNode;
onClose?: () => void;
anchor?: string;
}) => (open ? <div data-testid="mui-drawer">{children}</div> : null),
}));
vi.mock('@mui/material/IconButton', () => ({
default: ({
children,
onClick,
'aria-label': ariaLabel,
}: {
children: React.ReactNode;
onClick: () => void;
'aria-label': string;
title?: string;
size?: string;
}) => (
<button onClick={onClick} aria-label={ariaLabel}>
{children}
</button>
),
}));
vi.mock('@mui/material/styles', () => ({
useTheme: () => ({
palette: {
primary: { main: '#1976d2' },
text: { primary: '#000', secondary: '#666' },
action: { hover: 'rgba(0,0,0,0.04)' },
background: { default: '#fafafa' },
},
}),
}));
// Mock Headlamp CommonComponents
vi.mock('@kinvolk/headlamp-plugin/lib/CommonComponents', () => ({
Loader: ({ title }: { title: string }) => <div data-testid="loader">{title}</div>,
+115 -192
View File
@@ -6,6 +6,9 @@ import {
SimpleTable,
StatusLabel,
} from '@kinvolk/headlamp-plugin/lib/CommonComponents';
import Drawer from '@mui/material/Drawer';
import IconButton from '@mui/material/IconButton';
import { useTheme } from '@mui/material/styles';
import React, { useEffect, useState } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import {
@@ -44,6 +47,7 @@ interface NamespaceDetailPanelProps {
}
function NamespaceDetailPanel({ namespace, onClose }: NamespaceDetailPanelProps) {
const theme = useTheme();
const [isMaximized, setIsMaximized] = React.useState(false);
const { data, loading, error } = usePolarisDataContext();
@@ -96,172 +100,119 @@ function NamespaceDetailPanel({ namespace, onClose }: NamespaceDetailPanelProps)
return countsPerResource.get(`${row.Namespace}/${row.Kind}/${row.Name}`) ?? resourceCounts(row);
}
// Generate a unique class name for this drawer to avoid conflicts
const drawerClass = `polaris-namespace-drawer-${namespace}`;
return (
<>
<style>
{`
.${drawerClass} {
position: fixed;
right: 0;
top: 0;
bottom: 0;
width: ${isMaximized ? 'calc(100vw - 240px)' : '1000px'};
background-color: var(--mui-palette-background-default, #fafafa);
color: var(--mui-palette-text-primary);
box-shadow: -2px 0 8px rgba(0,0,0,0.15);
overflow-y: auto;
z-index: 1200;
padding: 20px;
transition: width 0.3s ease;
}
`}
</style>
<div className={drawerClass}>
<div
style={{
marginBottom: '20px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<h2 style={{ margin: 0, color: 'var(--mui-palette-text-primary)' }}>
Polaris {namespace}
</h2>
<div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
<button
onClick={() => setIsMaximized(!isMaximized)}
style={{
border: 'none',
background: 'transparent',
fontSize: '20px',
cursor: 'pointer',
padding: '4px 8px',
color: 'var(--mui-palette-text-secondary, #666)',
borderRadius: '4px',
}}
onMouseEnter={e => {
e.currentTarget.style.backgroundColor =
'var(--mui-palette-action-hover, rgba(0, 0, 0, 0.04))';
}}
onMouseLeave={e => {
e.currentTarget.style.backgroundColor = 'transparent';
}}
aria-label={isMaximized ? 'Minimize panel' : 'Maximize panel'}
title={isMaximized ? 'Minimize' : 'Maximize'}
>
{isMaximized ? '⊟' : '⊡'}
</button>
<button
onClick={onClose}
style={{
border: 'none',
background: 'transparent',
fontSize: '24px',
cursor: 'pointer',
padding: '4px 8px',
color: 'var(--mui-palette-text-secondary, #666)',
borderRadius: '4px',
}}
onMouseEnter={e => {
e.currentTarget.style.backgroundColor =
'var(--mui-palette-action-hover, rgba(0, 0, 0, 0.04))';
}}
onMouseLeave={e => {
e.currentTarget.style.backgroundColor = 'transparent';
}}
aria-label="Close panel"
title="Close"
>
×
</button>
</div>
<div
style={{
width: isMaximized ? 'calc(100vw - 240px)' : '1000px',
padding: '20px',
transition: 'width 0.3s ease',
}}
>
<div
style={{
marginBottom: '20px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<h2 style={{ margin: 0, color: theme.palette.text.primary }}>Polaris {namespace}</h2>
<div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
<IconButton
onClick={() => setIsMaximized(!isMaximized)}
aria-label={isMaximized ? 'Minimize panel' : 'Maximize panel'}
title={isMaximized ? 'Minimize' : 'Maximize'}
size="small"
>
{isMaximized ? '\u229F' : '\u22A1'}
</IconButton>
<IconButton onClick={onClose} aria-label="Close panel" title="Close" size="small">
\u00D7
</IconButton>
</div>
<SectionBox title="External">
<NameValueTable
rows={[
{
name: 'Polaris Dashboard',
value: (
<a href={getPolarisProxyUrl()} target="_blank" rel="noopener noreferrer">
View in Polaris Dashboard
</a>
),
},
]}
/>
</SectionBox>
<SectionBox title="Namespace Score">
<NameValueTable
rows={[
{
name: 'Score',
value: <StatusLabel status={status}>{score}%</StatusLabel>,
},
{ name: 'Total Checks', value: String(counts.total) },
{
name: 'Pass',
value: <StatusLabel status="success">{counts.pass}</StatusLabel>,
},
{
name: 'Warning',
value: <StatusLabel status="warning">{counts.warning}</StatusLabel>,
},
{
name: 'Danger',
value: <StatusLabel status="error">{counts.danger}</StatusLabel>,
},
{
name: 'Skipped',
value: (
<span title="Only counts checks with Severity=ignore. Annotation-based exemptions are not included.">
{counts.skipped}
</span>
),
},
]}
/>
</SectionBox>
<SectionBox title="Resources">
<SimpleTable
columns={[
{ label: 'Name', getter: (row: Result) => row.Name },
{ label: 'Kind', getter: (row: Result) => row.Kind },
{
label: 'Pass',
getter: (row: Result) => (
<StatusLabel status="success">{getResourceCounts(row).pass}</StatusLabel>
),
},
{
label: 'Warning',
getter: (row: Result) => (
<StatusLabel status="warning">{getResourceCounts(row).warning}</StatusLabel>
),
},
{
label: 'Danger',
getter: (row: Result) => (
<StatusLabel status="error">{getResourceCounts(row).danger}</StatusLabel>
),
},
]}
data={results}
emptyMessage={`No resources found in namespace "${namespace}".`}
/>
</SectionBox>
</div>
</>
<SectionBox title="External">
<NameValueTable
rows={[
{
name: 'Polaris Dashboard',
value: (
<a href={getPolarisProxyUrl()} target="_blank" rel="noopener noreferrer">
View in Polaris Dashboard
</a>
),
},
]}
/>
</SectionBox>
<SectionBox title="Namespace Score">
<NameValueTable
rows={[
{
name: 'Score',
value: <StatusLabel status={status}>{score}%</StatusLabel>,
},
{ name: 'Total Checks', value: String(counts.total) },
{
name: 'Pass',
value: <StatusLabel status="success">{counts.pass}</StatusLabel>,
},
{
name: 'Warning',
value: <StatusLabel status="warning">{counts.warning}</StatusLabel>,
},
{
name: 'Danger',
value: <StatusLabel status="error">{counts.danger}</StatusLabel>,
},
{
name: 'Skipped',
value: (
<span title="Only counts checks with Severity=ignore. Annotation-based exemptions are not included.">
{counts.skipped}
</span>
),
},
]}
/>
</SectionBox>
<SectionBox title="Resources">
<SimpleTable
columns={[
{ label: 'Name', getter: (row: Result) => row.Name },
{ label: 'Kind', getter: (row: Result) => row.Kind },
{
label: 'Pass',
getter: (row: Result) => (
<StatusLabel status="success">{getResourceCounts(row).pass}</StatusLabel>
),
},
{
label: 'Warning',
getter: (row: Result) => (
<StatusLabel status="warning">{getResourceCounts(row).warning}</StatusLabel>
),
},
{
label: 'Danger',
getter: (row: Result) => (
<StatusLabel status="error">{getResourceCounts(row).danger}</StatusLabel>
),
},
]}
data={results}
emptyMessage={`No resources found in namespace "${namespace}".`}
/>
</SectionBox>
</div>
);
}
export default function NamespacesListView() {
const theme = useTheme();
const location = useLocation();
const history = useHistory();
const { data, loading, error } = usePolarisDataContext();
@@ -287,21 +238,6 @@ export default function NamespacesListView() {
history.push(location.pathname);
};
// Handle keyboard navigation (Escape key closes drawer)
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape' && selectedNamespace) {
closeNamespace();
}
};
if (selectedNamespace) {
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedNamespace]);
if (loading) {
return <Loader title="Loading Polaris audit data..." />;
}
@@ -364,7 +300,7 @@ export default function NamespacesListView() {
style={{
border: 'none',
background: 'transparent',
color: 'var(--link-color, #1976d2)',
color: theme.palette.primary.main,
cursor: 'pointer',
textDecoration: 'underline',
padding: 0,
@@ -405,24 +341,11 @@ export default function NamespacesListView() {
/>
</SectionBox>
{selectedNamespace && (
<>
<div
onClick={closeNamespace}
style={{
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: 'rgba(0, 0, 0, 0.5)',
zIndex: 1100,
}}
aria-label="Close panel backdrop"
/>
<Drawer anchor="right" open={Boolean(selectedNamespace)} onClose={closeNamespace}>
{selectedNamespace && (
<NamespaceDetailPanel namespace={selectedNamespace} onClose={closeNamespace} />
</>
)}
)}
</Drawer>
</>
);
}
+12
View File
@@ -8,6 +8,18 @@ vi.mock('@kinvolk/headlamp-plugin/lib', () => ({
ApiProxy: { request: vi.fn() },
}));
vi.mock('@mui/material/styles', () => ({
useTheme: () => ({
palette: {
primary: { main: '#1976d2', contrastText: '#fff' },
text: { primary: '#000', secondary: '#666' },
action: { disabledBackground: '#e0e0e0', disabled: '#9e9e9e' },
divider: '#e0e0e0',
background: { paper: '#fff' },
},
}),
}));
// Mock Headlamp CommonComponents
vi.mock('@kinvolk/headlamp-plugin/lib/CommonComponents', () => ({
SectionBox: ({ title, children }: { title?: string; children?: React.ReactNode }) => (
+16 -14
View File
@@ -4,12 +4,15 @@ import {
SectionBox,
StatusLabel,
} from '@kinvolk/headlamp-plugin/lib/CommonComponents';
import { useTheme } from '@mui/material/styles';
import React from 'react';
import {
AuditData,
getDashboardUrl,
getPolarisApiPath,
getRefreshInterval,
INTERVAL_OPTIONS,
isFullUrl,
setDashboardUrl,
setRefreshInterval,
} from '../api/polaris';
@@ -20,6 +23,7 @@ interface PluginSettingsProps {
}
export default function PolarisSettings(props: PluginSettingsProps) {
const theme = useTheme();
const { data, onDataChange } = props;
const currentInterval = (data?.refreshInterval as number) ?? getRefreshInterval();
const currentUrl = (data?.dashboardUrl as string) ?? getDashboardUrl();
@@ -45,13 +49,11 @@ export default function PolarisSettings(props: PluginSettingsProps) {
setTestResult(null);
try {
const baseUrl = currentUrl;
const apiPath = baseUrl.endsWith('/') ? `${baseUrl}results.json` : `${baseUrl}/results.json`;
const isFullUrl = apiPath.startsWith('http://') || apiPath.startsWith('https://');
const apiPath = getPolarisApiPath();
let result: AuditData;
if (isFullUrl) {
if (isFullUrl(apiPath)) {
const response = await fetch(apiPath);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
@@ -103,27 +105,27 @@ export default function PolarisSettings(props: PluginSettingsProps) {
type="text"
value={currentUrl}
onChange={handleUrlChange}
placeholder="/api/v1/namespaces/polaris/services/polaris-dashboard:80/proxy/"
placeholder="/api/v1/namespaces/polaris/services/http:polaris-dashboard:80/proxy/"
style={{
width: '100%',
padding: '4px 8px',
border: '1px solid var(--mui-palette-divider, #e0e0e0)',
border: `1px solid ${theme.palette.divider}`,
borderRadius: '4px',
fontSize: '14px',
backgroundColor: 'var(--mui-palette-background-paper, #fff)',
color: 'var(--mui-palette-text-primary, #000)',
backgroundColor: theme.palette.background.paper,
color: theme.palette.text.primary,
}}
/>
<div
style={{
fontSize: '12px',
color: 'var(--mui-palette-text-secondary, #666)',
color: theme.palette.text.secondary,
marginTop: '4px',
}}
>
Examples:
<br /> K8s proxy:{' '}
<code>/api/v1/namespaces/polaris/services/polaris-dashboard:80/proxy/</code>
<code>/api/v1/namespaces/polaris/services/http:polaris-dashboard:80/proxy/</code>
<br /> Full URL: <code>https://my-polaris.example.com</code>
</div>
</div>
@@ -139,11 +141,11 @@ export default function PolarisSettings(props: PluginSettingsProps) {
style={{
padding: '6px 16px',
backgroundColor: testing
? 'var(--mui-palette-action-disabledBackground, #e0e0e0)'
: 'var(--mui-palette-primary-main, #1976d2)',
? theme.palette.action.disabledBackground
: theme.palette.primary.main,
color: testing
? 'var(--mui-palette-action-disabled, #9e9e9e)'
: 'var(--mui-palette-primary-contrastText, #fff)',
? theme.palette.action.disabled
: theme.palette.primary.contrastText,
border: 'none',
borderRadius: '4px',
cursor: testing ? 'not-allowed' : 'pointer',
+50 -13
View File
@@ -5,6 +5,7 @@ import {
registerRoute,
registerSidebarEntry,
} from '@kinvolk/headlamp-plugin/lib';
import { SectionBox, StatusLabel } from '@kinvolk/headlamp-plugin/lib/CommonComponents';
import React from 'react';
import { PolarisDataProvider } from './api/PolarisDataContext';
import AppBarScoreBadge from './components/AppBarScoreBadge';
@@ -13,6 +14,34 @@ import InlineAuditSection from './components/InlineAuditSection';
import NamespacesListView from './components/NamespacesListView';
import PolarisSettings from './components/PolarisSettings';
// --- Error boundary for plugin components ---
interface ErrorBoundaryState {
error: string | null;
}
class PolarisErrorBoundary extends React.Component<
{ children: React.ReactNode },
ErrorBoundaryState
> {
state: ErrorBoundaryState = { error: null };
static getDerivedStateFromError(error: Error): ErrorBoundaryState {
return { error: error.message };
}
render() {
if (this.state.error) {
return (
<SectionBox title="Polaris Plugin Error">
<StatusLabel status="error">{this.state.error}</StatusLabel>
</SectionBox>
);
}
return this.props.children;
}
}
// --- Sidebar entries ---
registerSidebarEntry({
@@ -47,9 +76,11 @@ registerRoute({
name: 'polaris',
exact: true,
component: () => (
<PolarisDataProvider>
<DashboardView />
</PolarisDataProvider>
<PolarisErrorBoundary>
<PolarisDataProvider>
<DashboardView />
</PolarisDataProvider>
</PolarisErrorBoundary>
),
});
@@ -59,14 +90,16 @@ registerRoute({
name: 'polaris-namespaces',
exact: true,
component: () => (
<PolarisDataProvider>
<NamespacesListView />
</PolarisDataProvider>
<PolarisErrorBoundary>
<PolarisDataProvider>
<NamespacesListView />
</PolarisDataProvider>
</PolarisErrorBoundary>
),
});
// Register plugin settings
registerPluginSettings('polaris', PolarisSettings, true);
registerPluginSettings('headlamp-polaris', PolarisSettings, true);
// Register details view section for supported controller types
registerDetailsViewSection(({ resource }) => {
@@ -77,15 +110,19 @@ registerDetailsViewSection(({ resource }) => {
}
return (
<PolarisDataProvider>
<InlineAuditSection resource={resource} />
</PolarisDataProvider>
<PolarisErrorBoundary>
<PolarisDataProvider>
<InlineAuditSection resource={resource} />
</PolarisDataProvider>
</PolarisErrorBoundary>
);
});
// Register app bar score badge
registerAppBarAction(() => (
<PolarisDataProvider>
<AppBarScoreBadge />
</PolarisDataProvider>
<PolarisErrorBoundary>
<PolarisDataProvider>
<AppBarScoreBadge />
</PolarisDataProvider>
</PolarisErrorBoundary>
));
-35
View File
@@ -1,4 +1,3 @@
import React from 'react';
import { AuditData, Result } from './api/polaris';
// --- Fixtures ---
@@ -25,37 +24,3 @@ export function makeAuditData(results: Result[]): AuditData {
Results: results,
};
}
// --- Mock Polaris Context Provider ---
interface MockPolarisProviderProps {
data?: AuditData | null;
loading?: boolean;
error?: string | null;
children: React.ReactNode;
}
// We dynamically import PolarisDataContext to inject mock values.
// This avoids mocking the hook module — we supply real context with controlled values.
const PolarisDataContext = React.createContext<{
data: AuditData | null;
loading: boolean;
error: string | null;
} | null>(null);
export function MockPolarisProvider({
data = null,
loading = false,
error = null,
children,
}: MockPolarisProviderProps) {
return (
<PolarisDataContext.Provider value={{ data, loading, error }}>
{children}
</PolarisDataContext.Provider>
);
}
// The context reference used in test-utils must be the SAME object the components import.
// We achieve this by having component tests mock `usePolarisDataContext` to read from our context.
export { PolarisDataContext };
+1 -1
View File
@@ -1,7 +1,7 @@
{
"extends": "@kinvolk/headlamp-plugin/config/plugins-tsconfig.json",
"compilerOptions": {
"types": ["vite/client", "vite-plugin-svgr/client", "vitest/globals", "@testing-library/jest-dom"]
"types": ["vitest/globals", "@testing-library/jest-dom"]
},
"include": ["src"]
}
+14
View File
@@ -1,10 +1,24 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
define: {
'process.env.NODE_ENV': '"test"',
},
test: {
globals: true,
environment: 'jsdom',
setupFiles: ['./vitest.setup.ts'],
exclude: ['e2e/**', 'node_modules/**'],
coverage: {
provider: 'v8',
include: ['src/**/*.{ts,tsx}'],
exclude: ['src/**/*.test.{ts,tsx}', 'src/test-utils.tsx', 'src/index.tsx'],
thresholds: {
lines: 80,
functions: 80,
branches: 80,
statements: 80,
},
},
},
});