Compare commits

...

43 Commits

Author SHA1 Message Date
gitea-actions[bot] 4126439e52 ci: update artifact hub metadata for v0.1.0 2026-02-07 16:37:15 +00:00
Chris Farhood 49ed3ea7ff chore: bump version to 0.1.0 and fix release workflow race condition
Fetch latest main before pushing metadata update to prevent
non-fast-forward rejections when main moves during the release run.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 11:36:13 -05:00
Chris Farhood deafe68893 chore: bump version to 0.0.11
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 10:47:43 -05:00
Chris Farhood a6f30bf681 ci: update artifact hub metadata for v0.0.10
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 10:46:42 -05:00
Chris Farhood 9df30c3943 docs: address review feedback on dashboard.enabled wording
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 10:35:51 -05:00
Chris Farhood cc3cc81af9 docs: add service proxy RBAC/security requirements and update outdated docs
The README, CLAUDE.md, and artifacthub-pkg.yml all referenced the old
ConfigMap-based data source. Updated to document the actual Kubernetes
service proxy path, the correct RBAC Role/RoleBinding (services/proxy
get), and added sections for token-auth mode, NetworkPolicy, audit
logging, and troubleshooting. Also updated the project structure and
feature descriptions to match the current codebase.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 10:25:59 -05:00
Chris Farhood d5ab99116c chore: bump version to 0.0.10
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 09:53:22 -05:00
Chris Farhood 5e330798e1 Merge pull request 'feat: restructure sidebar hierarchy and add full audit view' (#15) from feat/sidebar-restructure-dashboard-views into main
Reviewed-on: farhoodliquor/headlamp-polaris-plugin#15
2026-02-07 09:52:49 -05:00
Chris Farhood 1559a9ffcd feat: restructure sidebar hierarchy and add full audit view
Reorganize the sidebar into a proper hierarchy (Overview, Full Audit,
Namespaces) and add a Full Audit dashboard view that includes skipped
checks. Namespace routes move to /polaris/ns/:namespace to avoid
path collisions, and namespace detail pages now link out to the
Polaris dashboard.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 09:50:28 -05:00
gitea-actions[bot] bea7eaa67b ci: update artifact hub metadata for v0.0.9 2026-02-07 13:46:45 +00:00
Chris Farhood 9a1d7f961f chore: bump version to 0.0.9
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 08:45:43 -05:00
Chris Farhood e6e2aa63a5 Merge pull request 'docs: update ArtifactHub URLs in README' (#14) from fix/readme-artifacthub-urls into main
Reviewed-on: farhoodliquor/headlamp-polaris-plugin#14
Reviewed-by: Chris Farhood <cpfarhood@noreply.git.farh.net>
2026-02-07 08:45:14 -05:00
Chris Farhood dab068a963 refactor: rename npm package to headlamp-polaris-plugin
Aligns npm package name with the repo and ArtifactHub package name.
Updates all references: package.json, registerPluginSettings, Dockerfile,
release workflow tarball URLs, artifacthub-pkg.yml archive-url, and README.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 08:43:55 -05:00
Chris Farhood 244714316f docs: update ArtifactHub URLs to match new package name
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 08:43:43 -05:00
gitea-actions[bot] b1fa087011 ci: update artifact hub metadata for v0.0.8 2026-02-07 13:03:11 +00:00
Chris Farhood bfe926546b chore: bump version to 0.0.8
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 08:02:03 -05:00
Chris Farhood dccc393857 Merge pull request 'fix: correct ArtifactHub package name and checksum' (#13) from fix/artifacthub-package-name into main
Reviewed-on: farhoodliquor/headlamp-polaris-plugin#13
2026-02-07 13:01:29 +00:00
Chris Farhood f414dafa28 fix: correct ArtifactHub package name and release checksum
Rename package from polaris-headlamp-plugin to headlamp-polaris-plugin
so the ArtifactHub URL becomes /headlamp/polaris/headlamp-polaris-plugin.
Also fix the archive checksum to match the actual v0.0.7 tarball on GitHub.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 07:59:35 -05:00
gitea-actions[bot] 6e914ad71f ci: update artifact hub metadata for v0.0.7 2026-02-07 05:11:57 +00:00
Chris Farhood d923e655fe fix: correct GitHub API URLs in release workflow
Two GitHub API URLs still had the old repo name (polaris-headlamp-plugin
instead of headlamp-polaris-plugin), causing the GitHub release step to
target the wrong repository.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 00:10:02 -05:00
gitea-actions[bot] a1ef628fb5 ci: update artifact hub metadata for v0.0.7 2026-02-07 04:58:47 +00:00
Chris Farhood b8129a0dbb chore: bump version to 0.0.7
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-06 23:57:44 -05:00
Chris Farhood 7facb9be10 Merge pull request 'feat: add per-namespace detail pages with sidebar sub-items' (#12) from feature/polaris-detail-view into main
Reviewed-on: farhoodliquor/headlamp-polaris-plugin#12
2026-02-07 04:42:22 +00:00
Chris Farhood 1b86407d8b refactor: precompute resource counts and add return type annotation
Avoid recalculating per-resource counts 3x per table row by precomputing
them into a Map. Add explicit ResultCounts return type to resourceCounts.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-06 23:38:10 -05:00
Chris Farhood 40df014b6b style: fix import sorting and prettier formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-06 23:30:22 -05:00
Chris Farhood b217a8119e feat: add per-namespace detail pages with dynamic sidebar sub-items
Add drill-down namespace views under the Polaris sidebar entry. Each
namespace gets a sidebar sub-item registered dynamically from audit data,
linking to /polaris/:namespace with a score summary and per-resource table.

Introduces a shared PolarisDataContext so the sidebar registrar and view
components share a single data fetch. Also updates the Artifact Hub
repository ID.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-06 23:09:40 -05:00
Chris Farhood 818f4bc9cb chore: update repo URLs after rename to headlamp-polaris-plugin
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-06 22:21:05 -05:00
gitea-actions[bot] a6a1280e4f ci: update artifact hub metadata for v0.0.6 2026-02-07 03:03:21 +00:00
Chris Farhood 7351d88997 chore: bump version to 0.0.6
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-06 22:02:05 -05:00
Chris Farhood 071aab4f7e Merge pull request 'fix: use native Headlamp components for consistent styling' (#11) from fix/native-headlamp-styling into main
Reviewed-on: farhoodliquor/polaris-headlamp-plugin#11
2026-02-07 03:01:18 +00:00
Chris Farhood 40544429f4 fix: remove tarball from repo and gitignore *.tar.gz
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-06 22:00:15 -05:00
Chris Farhood 1f110a2846 style: fix prettier formatting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-06 21:59:16 -05:00
Chris Farhood 672caec903 ci: add build step to CI workflow
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-06 21:56:13 -05:00
Chris Farhood b10d09fd41 feat: move refresh interval to plugin settings
Register plugin settings via registerPluginSettings so the refresh
interval is configurable from Headlamp's plugin config page instead
of being embedded in the main view header.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-06 21:55:13 -05:00
Chris Farhood 8b319c0c8a fix: use native Headlamp components for consistent styling
Replace inline-styled divs and native HTML elements with Headlamp's
built-in NameValueTable, StatusLabel, and HeaderLabel components so the
plugin matches the look and feel of native pages.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-06 21:49:17 -05:00
Chris Farhood 57250a995d ci: update artifact hub checksum for v0.0.5
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-06 21:22:42 -05:00
Chris Farhood 702be12fc8 chore: bump version to 0.0.5
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-06 21:14:00 -05:00
Chris Farhood 95aaaa96bd Merge pull request 'feat: query Polaris dashboard API instead of ConfigMap' (#10) from feat/polaris-api-datasource into main
Reviewed-on: farhoodliquor/polaris-headlamp-plugin#10
2026-02-07 02:11:22 +00:00
Chris Farhood b891b3a624 docs: update CLAUDE.md to reflect API proxy data source
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-06 21:10:00 -05:00
Chris Farhood 7997eb29fa feat: query Polaris dashboard API instead of ConfigMap
The plugin now fetches audit data from the Polaris dashboard service
via the Kubernetes service proxy instead of reading from a ConfigMap.
This works with the standard Polaris dashboard deployment without
requiring additional configuration.

- Replace ConfigMap.useGet with ApiProxy.request to /results.json
- Compute score from result counts (pass/total) since the API
  response doesn't include a pre-computed score
- Update error messages for service proxy context
- Update CLAUDE.md to reflect new data source

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-06 20:50:07 -05:00
Chris Farhood 9885dc44c0 Merge pull request 'chore: add AI code review workflow for PRs' (#9) from chore/add-ai-review into main
Reviewed-on: farhoodliquor/polaris-headlamp-plugin#9
2026-02-06 22:21:35 +00:00
Chris Farhood 72998cfbca fix: add container image for ai-review workflow
The default gitea/act_runner image has no Node.js, which actions/checkout@v4
requires. Use catthehacker/ubuntu:act-latest like the kubernetes repo.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-06 17:18:07 -05:00
Chris Farhood 6f7217f400 chore: add AI code review workflow for PRs
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-06 17:15:50 -05:00
19 changed files with 755 additions and 313 deletions
+36
View File
@@ -0,0 +1,36 @@
name: AI Code Review
on:
pull_request:
branches:
- main
jobs:
ai-review:
name: AI Code Review
runs-on: ubuntu-latest
container:
image: catthehacker/ubuntu:act-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: AI Review
uses: Nikita-Filonov/ai-review@v0.56.0
with:
review-command: run
env:
LLM__PROVIDER: "OPENAI"
LLM__META__MODEL: ${{ vars.AI_REVIEW_MODEL }}
LLM__META__MAX_TOKENS: "15000"
LLM__META__TEMPERATURE: "0.3"
LLM__HTTP_CLIENT__API_URL: "https://api.openai.com/v1"
LLM__HTTP_CLIENT__API_TOKEN: ${{ secrets.OPENAI_API_KEY }}
VCS__PROVIDER: "GITEA"
VCS__PIPELINE__OWNER: ${{ github.repository_owner }}
VCS__PIPELINE__REPO: ${{ github.event.repository.name }}
VCS__PIPELINE__PULL_NUMBER: ${{ github.event.pull_request.number }}
VCS__HTTP_CLIENT__API_URL: ${{ github.server_url }}/api/v1
VCS__HTTP_CLIENT__API_TOKEN: ${{ secrets.AI_REVIEW_GITEA_TOKEN }}
+3
View File
@@ -17,6 +17,9 @@ jobs:
- name: Install dependencies
run: npm ci
- name: Build
run: npx @kinvolk/headlamp-plugin build
- name: Lint
run: npx eslint --ext .ts,.tsx src/
+9 -8
View File
@@ -18,7 +18,7 @@ jobs:
- name: Check if release is already finalized
run: |
VERSION=${GITHUB_REF_NAME#v}
TARBALL_URL="https://github.com/cpfarhood/polaris-headlamp-plugin/releases/download/${GITHUB_REF_NAME}/polaris-headlamp-plugin-${VERSION}.tar.gz"
TARBALL_URL="https://github.com/cpfarhood/headlamp-polaris-plugin/releases/download/${GITHUB_REF_NAME}/headlamp-polaris-plugin-${VERSION}.tar.gz"
HTTP_CODE=$(curl -sL -o /tmp/release.tar.gz -w "%{http_code}" "$TARBALL_URL" 2>/dev/null)
if [ "$HTTP_CODE" = "200" ]; then
ACTUAL="sha256:$(sha256sum /tmp/release.tar.gz | awk '{print $1}')"
@@ -115,7 +115,7 @@ jobs:
continue-on-error: true
run: |
[ "$SKIP_BUILD" = "true" ] && exit 0
GH_API="https://api.github.com/repos/cpfarhood/polaris-headlamp-plugin"
GH_API="https://api.github.com/repos/cpfarhood/headlamp-polaris-plugin"
# Create release or fetch existing one
BODY=$(curl -s -X POST \
-H "Authorization: token ${{ secrets.GH_PAT }}" \
@@ -153,7 +153,7 @@ jobs:
curl -sf -X POST \
-H "Authorization: token ${{ secrets.GH_PAT }}" \
-H "Content-Type: application/gzip" \
"https://uploads.github.com/repos/cpfarhood/polaris-headlamp-plugin/releases/${RELEASE_ID}/assets?name=${TARBALL}" \
"https://uploads.github.com/repos/cpfarhood/headlamp-polaris-plugin/releases/${RELEASE_ID}/assets?name=${TARBALL}" \
--data-binary "@${TARBALL}"
echo "GitHub release updated with same tarball"
@@ -161,12 +161,13 @@ jobs:
run: |
[ "$SKIP_BUILD" = "true" ] && exit 0
VERSION=${GITHUB_REF_NAME#v}
git checkout main
sed -i "s|headlamp/plugin/archive-checksum:.*|headlamp/plugin/archive-checksum: sha256:${CHECKSUM}|" artifacthub-pkg.yml
sed -i "s|headlamp/plugin/archive-url:.*|headlamp/plugin/archive-url: \"https://github.com/cpfarhood/polaris-headlamp-plugin/releases/download/${GITHUB_REF_NAME}/polaris-headlamp-plugin-${VERSION}.tar.gz\"|" artifacthub-pkg.yml
sed -i "s|^version:.*|version: ${VERSION}|" artifacthub-pkg.yml
git config user.name "gitea-actions[bot]"
git config user.email "gitea-actions[bot]@git.farh.net"
git fetch origin main
git checkout origin/main -B main
sed -i "s|headlamp/plugin/archive-checksum:.*|headlamp/plugin/archive-checksum: sha256:${CHECKSUM}|" artifacthub-pkg.yml
sed -i "s|headlamp/plugin/archive-url:.*|headlamp/plugin/archive-url: \"https://github.com/cpfarhood/headlamp-polaris-plugin/releases/download/${GITHUB_REF_NAME}/headlamp-polaris-plugin-${VERSION}.tar.gz\"|" artifacthub-pkg.yml
sed -i "s|^version:.*|version: ${VERSION}|" artifacthub-pkg.yml
git add artifacthub-pkg.yml
git diff --cached --quiet || {
git commit -m "ci: update artifact hub metadata for ${GITHUB_REF_NAME}"
@@ -178,7 +179,7 @@ jobs:
git tag -f ${GITHUB_REF_NAME}
git push -f origin ${GITHUB_REF_NAME}
# Also push to GitHub directly to avoid waiting for mirror sync
git remote add github https://x-access-token:${{ secrets.GH_PAT }}@github.com/cpfarhood/polaris-headlamp-plugin.git 2>/dev/null || true
git remote add github https://x-access-token:${{ secrets.GH_PAT }}@github.com/cpfarhood/headlamp-polaris-plugin.git 2>/dev/null || true
git push github main 2>/dev/null || true
git push -f github ${GITHUB_REF_NAME} 2>/dev/null || true
echo "Tag ${GITHUB_REF_NAME} aligned with updated metadata"
+1
View File
@@ -2,3 +2,4 @@ node_modules/
dist/
.headlamp-plugin/
.mcp.json
*.tar.gz
+2 -2
View File
@@ -6,5 +6,5 @@ COPY src/ src/
RUN npx @kinvolk/headlamp-plugin build
FROM alpine:3.20
COPY --from=build /app/dist/ /plugins/polaris-headlamp-plugin/
COPY --from=build /app/package.json /plugins/polaris-headlamp-plugin/
COPY --from=build /app/dist/ /plugins/headlamp-polaris-plugin/
COPY --from=build /app/package.json /plugins/headlamp-polaris-plugin/
+92 -51
View File
@@ -1,53 +1,58 @@
# polaris-headlamp-plugin
# headlamp-polaris-plugin
[![Artifact Hub](https://img.shields.io/endpoint?url=https://artifacthub.io/badge/repository/polaris-headlamp-plugin)](https://artifacthub.io/packages/headlamp/polaris-headlamp-plugin/polaris-headlamp-plugin)
[![Artifact Hub](https://img.shields.io/endpoint?url=https://artifacthub.io/badge/repository/polaris)](https://artifacthub.io/packages/headlamp/polaris/headlamp-polaris-plugin)
A [Headlamp](https://headlamp.dev/) plugin that surfaces [Fairwinds Polaris](https://polaris.docs.fairwinds.com/) audit results directly in the Headlamp UI.
## What It Does
Adds a **Polaris** sidebar entry to Headlamp that displays:
Adds a **Polaris** top-level sidebar section to Headlamp with the following views:
- **Cluster Score** -- overall Polaris score as a percentage (color-coded green/amber/red)
- **Check Summary** -- total, pass, warning, and danger counts across all workloads
- **Cluster Info** -- node, pod, namespace, and controller counts
- **Overview** -- cluster score as a percentage (color-coded green/amber/red), check summary (pass/warning/danger counts), and cluster info (nodes, pods, namespaces, controllers)
- **Full Audit** -- same as overview but includes skipped checks in the totals
- **Namespace drill-down** -- per-namespace score, check counts, and a resource table showing pass/warning/danger per workload. Namespace entries appear dynamically in the sidebar based on live audit data.
- **External link** -- quick jump to the native Polaris dashboard via the Kubernetes service proxy
Data is read from the `ConfigMap/polaris-dashboard` in the `polaris` namespace (key: `dashboard.json`), which is created by the standard Polaris Helm chart. The plugin is read-only -- it never writes to the cluster.
Data is fetched from the Polaris dashboard API through the Kubernetes service proxy (`/api/v1/namespaces/polaris/services/polaris-dashboard:80/proxy/results.json`). The plugin is read-only -- it never writes to the cluster.
Results are cached and refreshed on a user-configurable interval (1 / 5 / 10 / 30 minutes, default 5). The setting persists in the browser's localStorage.
Results are refreshed on a user-configurable interval (1 / 5 / 10 / 30 minutes, default 5). The setting is available in **Settings > Plugins > Polaris** and persists in the browser's localStorage.
Error states are handled explicitly: RBAC denied (403), Polaris not installed (404), malformed JSON, and loading.
Error states are handled explicitly: RBAC denied (403), Polaris not installed (404/503), malformed JSON, and loading.
## Prerequisites
- **Headlamp** >= v0.26 deployed in your cluster
- **Polaris** installed via the [official Helm chart](https://github.com/FairwindsOps/polaris) with the dashboard component enabled
- The Headlamp service account must have RBAC permission to `get` ConfigMaps in the `polaris` namespace
| Requirement | Minimum version |
|-------------|----------------|
| Headlamp | v0.26+ |
| Polaris (with dashboard enabled) | Any recent release |
| Kubernetes | v1.24+ |
Polaris must be deployed in the `polaris` namespace with the dashboard component enabled (`dashboard.enabled: true` in the Helm chart, which is the default). The plugin reads from the `polaris-dashboard` ClusterIP service on port 80.
## Installing
### Option 1: Artifact Hub + Headlamp plugin manager (recommended)
The plugin is published on [Artifact Hub](https://artifacthub.io/packages/headlamp/polaris-headlamp-plugin/polaris-headlamp-plugin). Configure Headlamp's `pluginsManager` in your Helm values to install it automatically:
The plugin is published on [Artifact Hub](https://artifacthub.io/packages/headlamp/polaris/headlamp-polaris-plugin). Configure Headlamp's `pluginsManager` in your Helm values to install it automatically:
```yaml
pluginsManager:
sources:
- url: https://artifacthub.io/packages/headlamp/polaris-headlamp-plugin/polaris-headlamp-plugin
- url: https://artifacthub.io/packages/headlamp/polaris/headlamp-polaris-plugin
```
Headlamp will fetch and install the plugin on startup.
### Option 2: Docker init container
The plugin ships as a container image at `git.farh.net/farhoodliquor/polaris-headlamp-plugin`.
The plugin ships as a container image at `git.farh.net/farhoodliquor/headlamp-polaris-plugin`.
Add it as an init container in your Headlamp Helm values:
```yaml
initContainers:
- name: polaris-plugin
image: git.farh.net/farhoodliquor/polaris-headlamp-plugin:v0.0.1
image: git.farh.net/farhoodliquor/headlamp-polaris-plugin:v0.0.1
command: ["sh", "-c", "cp -r /plugins/* /headlamp/plugins/"]
volumeMounts:
- name: plugins
@@ -64,10 +69,10 @@ volumeMounts:
### Option 3: Manual tarball install
Download the `.tar.gz` from the [GitHub releases page](https://github.com/cpfarhood/polaris-headlamp-plugin/releases) or the [Gitea releases page](https://git.farh.net/farhoodliquor/polaris-headlamp-plugin/releases), then extract into Headlamp's plugin directory:
Download the `.tar.gz` from the [GitHub releases page](https://github.com/cpfarhood/headlamp-polaris-plugin/releases) or the [Gitea releases page](https://git.farh.net/farhoodliquor/headlamp-polaris-plugin/releases), then extract into Headlamp's plugin directory:
```bash
tar xzf polaris-headlamp-plugin-0.0.1.tar.gz -C /headlamp/plugins/
tar xzf headlamp-polaris-plugin-0.0.1.tar.gz -C /headlamp/plugins/
```
### Option 4: Build from source
@@ -78,42 +83,77 @@ npm run build
npx @kinvolk/headlamp-plugin extract . /headlamp/plugins
```
## RBAC
## RBAC / Security Setup
The plugin reads a single ConfigMap. Minimum RBAC required for the Headlamp service account:
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:
| Verb | API Group | Resource | Resource Name | Namespace |
|------|-----------|----------|---------------|-----------|
| `get` | `""` (core) | `services/proxy` | `polaris-dashboard` | `polaris` |
### Minimal RBAC manifests
```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
kind: Role
metadata:
name: headlamp-polaris-reader
name: polaris-proxy-reader
namespace: polaris
rules:
- apiGroups: [""]
resources: ["configmaps"]
resources: ["services/proxy"]
resourceNames: ["polaris-dashboard"]
verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
kind: RoleBinding
metadata:
name: headlamp-polaris-reader
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: headlamp-polaris-reader
name: headlamp-polaris-proxy
namespace: polaris
subjects:
- kind: ServiceAccount
name: headlamp
namespace: headlamp
name: headlamp # adjust to match your Headlamp service account
namespace: kube-system # adjust to match the namespace Headlamp runs in
roleRef:
kind: Role
name: polaris-proxy-reader
apiGroup: rbac.authorization.k8s.io
```
Apply with `kubectl apply -f polaris-rbac.yaml`.
### Token-auth mode
When Headlamp is configured for user-supplied tokens (rather than a fixed service account), **each user** must have the RoleBinding above attached to their own identity. A 403 error in the plugin means the currently logged-in user lacks this binding.
### NetworkPolicy
If the `polaris` namespace enforces network policies, ensure ingress is allowed from the Kubernetes API server (which performs the proxy hop) to `polaris-dashboard` on port 80.
### Read-only access
The plugin only performs `GET` requests through the service proxy. No `create`, `update`, `delete`, or `patch` verbs are required. Do not grant broader access than `get` on `services/proxy`.
### Audit logging
Every proxied request is recorded in Kubernetes API audit logs as a `get` on `services/proxy` in the `polaris` namespace. If the auto-refresh interval generates more audit volume than desired, increase the refresh interval in the plugin settings or adjust your audit policy.
## Troubleshooting
| Symptom | Likely cause | Fix |
|---------|-------------|-----|
| **403 Access Denied** | Missing RBAC binding for `services/proxy` | Apply the Role + RoleBinding from the RBAC section above |
| **404 or 503** | Polaris not installed, or dashboard disabled | Install Polaris with `dashboard.enabled: true` in the `polaris` namespace |
| **No data** | Polaris running but no workloads scanned yet | Wait for the next Polaris audit cycle or restart the Polaris pod |
| **Stale data** | Refresh interval too long | Lower the interval in **Settings > Plugins > Polaris** |
## Development
### Setup
```bash
git clone https://github.com/cpfarhood/polaris-headlamp-plugin.git
cd polaris-headlamp-plugin
git clone https://github.com/cpfarhood/headlamp-polaris-plugin.git
cd headlamp-polaris-plugin
npm install
```
@@ -129,7 +169,7 @@ This starts the Headlamp plugin dev server. Point a running Headlamp instance at
```bash
npm run build # outputs dist/main.js
npm run package # creates polaris-headlamp-plugin-<version>.tar.gz
npm run package # creates headlamp-polaris-plugin-<version>.tar.gz
```
### Type-check
@@ -142,29 +182,30 @@ npm run tsc
```
src/
index.tsx -- Entry point. Registers sidebar entry and route at /polaris.
index.tsx -- Entry point. Registers sidebar entries and routes.
api/
polaris.ts -- TypeScript types matching the Polaris AuditData schema,
usePolarisData() hook with caching, countResults() utility,
and refresh interval settings (localStorage).
polaris.ts -- TypeScript types (AuditData schema), usePolarisData hook,
countResults utilities, refresh interval settings.
PolarisDataContext.tsx -- React context provider; shared data fetch across views.
components/
PolarisView.tsx -- Main page component. Score badge, check summary cards,
cluster info, error states, refresh interval selector.
DashboardView.tsx -- Overview / Full Audit page (score, check summary, cluster info).
NamespaceDetailView.tsx -- Per-namespace drill-down with resource table.
DynamicSidebarRegistrar.tsx -- Registers sidebar entries dynamically from audit namespaces.
PolarisSettings.tsx -- Plugin settings page (refresh interval selector).
```
## Data Source
The plugin reads from:
The plugin fetches live audit results from the Polaris dashboard HTTP API via the Kubernetes service proxy:
- **ConfigMap**: `polaris-dashboard`
- **Namespace**: `polaris`
- **Key**: `dashboard.json`
```
GET /api/v1/namespaces/polaris/services/polaris-dashboard:80/proxy/results.json
```
This ConfigMap is created automatically when Polaris is installed with the dashboard enabled. The JSON structure matches Polaris's `AuditData` schema (`pkg/validator/output.go`):
This endpoint is served by the `polaris-dashboard` ClusterIP service, which is created by the Polaris Helm chart when `dashboard.enabled: true`. The JSON response matches Polaris's `AuditData` schema (`pkg/validator/output.go`):
```
AuditData
Score -- cluster score (0-100)
ClusterInfo -- nodes, pods, namespaces, controllers
Results[] -- per-workload results
Results{} -- top-level check results (ResultSet)
@@ -174,7 +215,7 @@ AuditData
Results{} -- container-level check results
```
Each check in a `ResultSet` has `Success` (bool) and `Severity` (`"warning"` or `"danger"`).
Each check in a `ResultSet` has `Success` (bool) and `Severity` (`"warning"`, `"danger"`, or `"ignore"`). The cluster score is computed client-side as `pass / total * 100`.
## Releasing
@@ -193,7 +234,7 @@ This triggers two CI pipelines:
**Gitea Actions** (`.gitea/workflows/release.yaml`):
1. Build the plugin in a `node:20` container
2. Package a `.tar.gz` tarball
3. Build and push a Docker image to `git.farh.net/farhoodliquor/polaris-headlamp-plugin:{tag}` and `:latest`
3. Build and push a Docker image to `git.farh.net/farhoodliquor/headlamp-polaris-plugin:{tag}` and `:latest`
4. Create a Gitea release with the tarball attached
**GitHub Actions** (`.github/workflows/release.yml`):
@@ -219,9 +260,9 @@ When releasing a new version, update `artifacthub-pkg.yml`:
## Links
- [Artifact Hub](https://artifacthub.io/packages/headlamp/polaris-headlamp-plugin/polaris-headlamp-plugin)
- [GitHub (mirror)](https://github.com/cpfarhood/polaris-headlamp-plugin)
- [Gitea (source of truth)](https://git.farh.net/farhoodliquor/polaris-headlamp-plugin)
- [Artifact Hub](https://artifacthub.io/packages/headlamp/polaris/headlamp-polaris-plugin)
- [GitHub (mirror)](https://github.com/cpfarhood/headlamp-polaris-plugin)
- [Gitea (source of truth)](https://git.farh.net/farhoodliquor/headlamp-polaris-plugin)
- [Headlamp](https://headlamp.dev/)
- [Fairwinds Polaris](https://polaris.docs.fairwinds.com/)
+13 -7
View File
@@ -1,10 +1,16 @@
version: 0.0.4
name: polaris-headlamp-plugin
version: 0.1.0
name: headlamp-polaris-plugin
displayName: Polaris
createdAt: "2026-02-05T19:00:00Z"
description: Surfaces Fairwinds Polaris audit results inside the Headlamp UI.
description: >-
Surfaces Fairwinds Polaris audit results inside the Headlamp UI.
Shows cluster score, check summary, and per-namespace drill-downs
with per-resource pass/warning/danger breakdowns. Data is fetched
read-only via the Kubernetes service proxy to the Polaris dashboard.
Requires a Role granting `get` on `services/proxy` for the
`polaris-dashboard` service in the `polaris` namespace.
license: MIT
homeURL: "https://github.com/cpfarhood/polaris-headlamp-plugin"
homeURL: "https://github.com/cpfarhood/headlamp-polaris-plugin"
category: security
keywords:
- polaris
@@ -15,14 +21,14 @@ keywords:
- kubernetes
links:
- name: Source
url: "https://github.com/cpfarhood/polaris-headlamp-plugin"
url: "https://github.com/cpfarhood/headlamp-polaris-plugin"
- name: Polaris
url: "https://polaris.docs.fairwinds.com/"
maintainers:
- name: cpfarhood
email: "chris@farhood.org"
annotations:
headlamp/plugin/archive-url: "https://github.com/cpfarhood/polaris-headlamp-plugin/releases/download/v0.0.4/polaris-headlamp-plugin-0.0.4.tar.gz"
headlamp/plugin/archive-url: "https://github.com/cpfarhood/headlamp-polaris-plugin/releases/download/v0.1.0/headlamp-polaris-plugin-0.1.0.tar.gz"
headlamp/plugin/version-compat: ">=0.26"
headlamp/plugin/archive-checksum: sha256:4c460681d389c8977d7e7ae57ac6aedd64281de4b58284b0bcc9fb34525432f2
headlamp/plugin/archive-checksum: sha256:c720f4386a8581560412be43a796316812a5850173d4428a7d0f289d7a04c1a3
headlamp/plugin/distro-compat: in-cluster
+1 -1
View File
@@ -1,4 +1,4 @@
repositoryID: fb4c3789-de2b-4667-8fff-34f22e5648da
repositoryID: fc3397f6-a75a-4950-ab50-da75c08a8089
owners:
- name: cpfarhood
email: "chris@farhood.org"
+55 -6
View File
@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Project Overview
Headlamp plugin that surfaces Fairwinds Polaris audit results inside the Headlamp UI. Reads from `ConfigMap/polaris-dashboard` in the `polaris` namespace (key: `dashboard.json`). Target Headlamp ≥ v0.26.
Headlamp plugin that surfaces Fairwinds Polaris audit results inside the Headlamp UI. Queries the Polaris dashboard API via the Kubernetes service proxy (`/api/v1/namespaces/polaris/services/polaris-dashboard:80/proxy/results.json`). Target Headlamp ≥ v0.26.
## Build & Development Commands
@@ -29,18 +29,67 @@ npx eslint src/
```
src/
├── index.tsx # Entry point: registerSidebarEntry + registerRoute for /polaris
├── index.tsx # Entry point: registers sidebar entries + routes
├── api/
── polaris.ts # Types (AuditData schema), usePolarisData hook, countResults utility, refresh settings
── polaris.ts # Types (AuditData schema), usePolarisData hook, countResults utilities, refresh settings
│ └── PolarisDataContext.tsx # React context provider for shared data fetch
└── components/
── PolarisView.tsx # Main page: score badge, check summary, cluster info, error states, refresh interval selector
── DashboardView.tsx # Overview / Full Audit page (score, check summary, cluster info)
├── NamespaceDetailView.tsx # Per-namespace drill-down with resource table
├── DynamicSidebarRegistrar.tsx # Registers namespace sidebar entries from live audit data
└── PolarisSettings.tsx # Plugin settings (refresh interval selector)
```
Single sidebar page at `/polaris`. Data is cached in React state and refreshed on a user-configurable interval (stored in localStorage under `polaris-plugin-refresh-interval`, default 5 minutes). The `usePolarisData` hook wraps `ConfigMap.useGet` with caching so stale data is shown while refreshing.
Top-level sidebar section at `/polaris` with sub-routes for full audit (`/polaris/full-audit`) and per-namespace views (`/polaris/ns/:namespace`). Data is fetched via `ApiProxy.request` to the Polaris dashboard service proxy and refreshed on a user-configurable interval (stored in localStorage under `polaris-plugin-refresh-interval`, default 5 minutes). Score is computed from result counts (pass/total).
## Security / RBAC Requirements
The plugin reaches Polaris through the Kubernetes API server's service proxy sub-resource (`/api/v1/namespaces/polaris/services/polaris-dashboard:80/proxy/...`). The Headlamp service account (or the user's bearer token when Headlamp runs in token-auth mode) must be granted:
| Verb | API Group | Resource | Resource Name | Namespace |
|------|-----------|----------|---------------|-----------|
| `get` | `""` (core) | `services/proxy` | `polaris-dashboard` | `polaris` |
Minimal RBAC example:
```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: polaris-proxy-reader
namespace: polaris
rules:
- apiGroups: [""]
resources: ["services/proxy"]
resourceNames: ["polaris-dashboard"]
verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: headlamp-polaris-proxy
namespace: polaris
subjects:
- kind: ServiceAccount
name: headlamp # adjust to match your Headlamp SA
namespace: kube-system
roleRef:
kind: Role
name: polaris-proxy-reader
apiGroup: rbac.authorization.k8s.io
```
Additional considerations:
- **NetworkPolicy**: If the `polaris` namespace enforces network policies, allow ingress from the Headlamp pod (or the API server, since it performs the proxy hop) to `polaris-dashboard` on port 80.
- **Polaris dashboard listen address**: The Polaris Helm chart exposes the dashboard on a ClusterIP service (`polaris-dashboard:80`). If the chart is installed with `dashboard.enabled: false`, the service will not be created, resulting in a 404 error for proxy requests.
- **No write operations**: The plugin only performs `GET` requests through the proxy. No `create`, `update`, or `delete` verbs are required. Do not grant broader service proxy access than `get`.
- **Token-auth mode**: When Headlamp is configured for user-supplied tokens (rather than a fixed service account), each user's own RBAC bindings must include the role above. A 403 from the plugin means the logged-in user lacks the binding.
- **Audit logging**: Kubernetes API audit logs will record every proxied request as a `get` on `services/proxy` in the `polaris` namespace. Set an appropriate audit policy level if request volume from the auto-refresh interval is a concern.
## Key Constraints
- **Data source**: `ConfigMap/polaris-dashboard` in `polaris` namespace, key `dashboard.json`. No CRDs, no external API calls, no cluster write operations.
- **Data source**: Polaris dashboard API via K8s service proxy. Requires Polaris deployed in the `polaris` namespace with a `polaris-dashboard` service. No CRDs, no cluster write operations.
- **UI components**: Use only Headlamp-provided components (`@kinvolk/headlamp-plugin/lib/CommonComponents`). Do not import raw MUI packages. No custom theming.
- **Error handling**: Must handle 403 (RBAC denied), 404 (Polaris not installed), malformed JSON, and loading states with distinct visual states.
- **TypeScript strictness**: No `any`, no implicit `unknown` casting, no dead code, no unused imports.
+4 -4
View File
@@ -1,12 +1,12 @@
{
"name": "polaris-headlamp-plugin",
"version": "0.0.3",
"name": "headlamp-polaris-plugin",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "polaris-headlamp-plugin",
"version": "0.0.3",
"name": "headlamp-polaris-plugin",
"version": "0.1.0",
"devDependencies": {
"@kinvolk/headlamp-plugin": "^0.13.0"
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "polaris-headlamp-plugin",
"version": "0.0.4",
"name": "headlamp-polaris-plugin",
"version": "0.1.0",
"description": "Headlamp plugin for Fairwinds Polaris audit results",
"scripts": {
"start": "headlamp-plugin start",
+25
View File
@@ -0,0 +1,25 @@
import React from 'react';
import { AuditData, getRefreshInterval, usePolarisData } from './polaris';
interface PolarisDataContextValue {
data: AuditData | null;
loading: boolean;
error: string | null;
}
const PolarisDataContext = React.createContext<PolarisDataContextValue | null>(null);
export function PolarisDataProvider(props: { children: React.ReactNode }) {
const interval = getRefreshInterval();
const state = usePolarisData(interval);
return <PolarisDataContext.Provider value={state}>{props.children}</PolarisDataContext.Provider>;
}
export function usePolarisDataContext(): PolarisDataContextValue {
const ctx = React.useContext(PolarisDataContext);
if (ctx === null) {
throw new Error('usePolarisDataContext must be used within a PolarisDataProvider');
}
return ctx;
}
+89 -78
View File
@@ -1,4 +1,4 @@
import { K8s } from '@kinvolk/headlamp-plugin/lib';
import { ApiProxy } from '@kinvolk/headlamp-plugin/lib';
import React from 'react';
// --- Polaris AuditData schema (matches pkg/validator/output.go) ---
@@ -52,7 +52,6 @@ export interface AuditData {
DisplayName: string;
ClusterInfo: ClusterInfo;
Results: Result[];
Score: number;
}
// --- Result counting ---
@@ -62,6 +61,7 @@ export interface ResultCounts {
pass: number;
warning: number;
danger: number;
skipped: number;
}
function countResultSet(rs: ResultSet, counts: ResultCounts): void {
@@ -70,6 +70,8 @@ function countResultSet(rs: ResultSet, counts: ResultCounts): void {
counts.total++;
if (msg.Success) {
counts.pass++;
} else if (msg.Severity === 'ignore') {
counts.skipped++;
} else if (msg.Severity === 'warning') {
counts.warning++;
} else if (msg.Severity === 'danger') {
@@ -78,9 +80,9 @@ function countResultSet(rs: ResultSet, counts: ResultCounts): void {
}
}
export function countResults(data: AuditData): ResultCounts {
const counts: ResultCounts = { total: 0, pass: 0, warning: 0, danger: 0 };
for (const result of data.Results) {
function countResultItems(results: Result[]): ResultCounts {
const counts: ResultCounts = { total: 0, pass: 0, warning: 0, danger: 0, skipped: 0 };
for (const result of results) {
countResultSet(result.Results, counts);
if (result.PodResult) {
countResultSet(result.PodResult.Results, counts);
@@ -92,8 +94,35 @@ export function countResults(data: AuditData): ResultCounts {
return counts;
}
export function countResults(data: AuditData): ResultCounts {
return countResultItems(data.Results);
}
export function countResultsForItems(results: Result[]): ResultCounts {
return countResultItems(results);
}
export function getNamespaces(data: AuditData): string[] {
const namespaces = new Set<string>();
for (const result of data.Results) {
namespaces.add(result.Namespace);
}
return Array.from(namespaces).sort();
}
export function filterResultsByNamespace(data: AuditData, namespace: string): Result[] {
return data.Results.filter(r => r.Namespace === namespace);
}
// --- Settings ---
export const INTERVAL_OPTIONS = [
{ label: '1 minute', value: 60 },
{ label: '5 minutes', value: 300 },
{ label: '10 minutes', value: 600 },
{ label: '30 minutes', value: 1800 },
];
const STORAGE_KEY = 'polaris-plugin-refresh-interval';
const DEFAULT_INTERVAL_SECONDS = 300; // 5 minutes
@@ -112,8 +141,23 @@ export function setRefreshInterval(seconds: number): void {
localStorage.setItem(STORAGE_KEY, String(seconds));
}
// --- Polaris dashboard proxy URL ---
export const POLARIS_DASHBOARD_PROXY =
'/api/v1/namespaces/polaris/services/polaris-dashboard:80/proxy/';
// --- Score computation ---
export function computeScore(counts: ResultCounts): number {
if (counts.total === 0) return 0;
return Math.round((counts.pass / counts.total) * 100);
}
// --- Data fetching hook ---
const POLARIS_API_PATH =
'/api/v1/namespaces/polaris/services/polaris-dashboard:80/proxy/results.json';
interface PolarisDataState {
data: AuditData | null;
loading: boolean;
@@ -121,87 +165,54 @@ interface PolarisDataState {
}
export function usePolarisData(refreshIntervalSeconds: number): PolarisDataState {
const [configMap, fetchError] = K8s.ResourceClasses.ConfigMap.useGet(
'polaris-dashboard',
'polaris'
);
const [cachedData, setCachedData] = React.useState<AuditData | null>(null);
const [parseError, setParseError] = React.useState<string | null>(null);
const [lastFetchTime, setLastFetchTime] = React.useState<number>(0);
const [, setTick] = React.useState(0);
const [data, setData] = React.useState<AuditData | null>(null);
const [loading, setLoading] = React.useState(true);
const [error, setError] = React.useState<string | null>(null);
const [tick, setTick] = React.useState(0);
// Parse ConfigMap data when it arrives
React.useEffect(() => {
if (!configMap) {
return;
}
const dataMap = configMap.data as Record<string, string> | undefined;
const raw = dataMap?.['dashboard.json'];
if (!raw) {
setParseError('ConfigMap exists but dashboard.json key is missing.');
return;
}
try {
const parsed: AuditData = JSON.parse(raw);
setCachedData(parsed);
setParseError(null);
setLastFetchTime(Date.now());
} catch {
setParseError('Failed to parse dashboard.json: malformed JSON.');
}
}, [configMap]);
let cancelled = false;
// Periodic refresh via re-render trigger
React.useEffect(() => {
if (refreshIntervalSeconds <= 0) {
return;
async function fetchData() {
try {
const result: AuditData = await ApiProxy.request(POLARIS_API_PATH);
if (!cancelled) {
setData(result);
setError(null);
setLoading(false);
}
} catch (err: unknown) {
if (cancelled) return;
const status = (err as { status?: number }).status;
if (status === 403) {
setError(
'Access denied (403). Check that your RBAC permissions allow proxying to the Polaris service.'
);
} else if (status === 404 || status === 503) {
setError(
'Polaris dashboard not reachable. Ensure Polaris is installed in the polaris namespace.'
);
} else {
setError(`Failed to fetch Polaris data: ${String(err)}`);
}
setLoading(false);
}
}
fetchData();
return () => {
cancelled = true;
};
}, [tick]);
// Periodic refresh
React.useEffect(() => {
if (refreshIntervalSeconds <= 0) return;
const intervalId = window.setInterval(() => {
setTick(t => t + 1);
}, refreshIntervalSeconds * 1000);
return () => window.clearInterval(intervalId);
}, [refreshIntervalSeconds]);
// Determine error state
if (fetchError) {
const status = (fetchError as { status?: number }).status;
if (status === 403) {
return {
data: cachedData,
loading: false,
error:
'Access denied (403). Check that your RBAC permissions allow reading ConfigMaps in the polaris namespace.',
};
}
if (status === 404) {
return {
data: cachedData,
loading: false,
error:
'Polaris dashboard ConfigMap not found (404). Ensure Polaris is installed in the polaris namespace.',
};
}
return {
data: cachedData,
loading: false,
error: `Failed to fetch Polaris data: ${String(fetchError)}`,
};
}
if (parseError) {
return { data: cachedData, loading: false, error: parseError };
}
const isLoading = !configMap && !fetchError;
// Return cached data while loading if we have it
if (isLoading && cachedData && lastFetchTime > 0) {
return { data: cachedData, loading: false, error: null };
}
return {
data: cachedData,
loading: isLoading,
error: null,
};
return { data, loading, error };
}
+127
View File
@@ -0,0 +1,127 @@
import {
Loader,
NameValueTable,
SectionBox,
SectionHeader,
StatusLabel,
} from '@kinvolk/headlamp-plugin/lib/CommonComponents';
import React from 'react';
import { AuditData, countResults, 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 OverviewSection(props: {
data: AuditData;
counts: ResultCounts;
includeSkipped: boolean;
}) {
const { counts, includeSkipped } = props;
const displayTotal = includeSkipped ? counts.total : counts.total - counts.skipped;
const displayPass = counts.pass;
const score = displayTotal === 0 ? 0 : Math.round((displayPass / displayTotal) * 100);
const status = scoreStatus(score);
const summaryRows: { name: string; value: React.ReactNode }[] = [
{ name: 'Total Checks', value: String(displayTotal) },
{
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>,
},
];
if (includeSkipped) {
summaryRows.push({
name: 'Skipped',
value: <StatusLabel status="">{counts.skipped}</StatusLabel>,
});
}
return (
<>
<SectionBox title="Score">
<NameValueTable
rows={[
{
name: 'Cluster Score',
value: <StatusLabel status={status}>{score}%</StatusLabel>,
},
]}
/>
</SectionBox>
<SectionBox title="Check Summary">
<NameValueTable rows={summaryRows} />
</SectionBox>
<SectionBox title="Cluster Info">
<NameValueTable
rows={[
{ name: 'Nodes', value: String(props.data.ClusterInfo.Nodes) },
{ name: 'Pods', value: String(props.data.ClusterInfo.Pods) },
{ name: 'Namespaces', value: String(props.data.ClusterInfo.Namespaces) },
{ name: 'Controllers', value: String(props.data.ClusterInfo.Controllers) },
]}
/>
</SectionBox>
</>
);
}
export default function DashboardView(props: { includeSkipped: boolean }) {
const { data, loading, error } = usePolarisDataContext();
const title = props.includeSkipped ? 'Polaris — Full Audit' : 'Polaris — Overview';
if (loading) {
return <Loader title="Loading Polaris audit data..." />;
}
const counts = data ? countResults(data) : null;
return (
<>
<SectionHeader title={title} />
{error && (
<SectionBox title="Error">
<NameValueTable
rows={[
{
name: 'Status',
value: <StatusLabel status="error">{error}</StatusLabel>,
},
]}
/>
</SectionBox>
)}
{data && counts && (
<OverviewSection data={data} counts={counts} includeSkipped={props.includeSkipped} />
)}
{!data && !error && (
<SectionBox title="No Data">
<NameValueTable
rows={[
{
name: 'Status',
value: 'No Polaris audit results found.',
},
]}
/>
</SectionBox>
)}
</>
);
}
@@ -0,0 +1,29 @@
import { registerSidebarEntry } from '@kinvolk/headlamp-plugin/lib';
import React from 'react';
import { getNamespaces } from '../api/polaris';
import { usePolarisDataContext } from '../api/PolarisDataContext';
const registeredNamespaces = new Set<string>();
export default function DynamicSidebarRegistrar() {
const { data } = usePolarisDataContext();
React.useEffect(() => {
if (!data) return;
const namespaces = getNamespaces(data);
for (const ns of namespaces) {
if (registeredNamespaces.has(ns)) continue;
registeredNamespaces.add(ns);
registerSidebarEntry({
parent: 'polaris-namespaces',
name: `polaris-ns-${ns}`,
label: ns,
url: `/polaris/ns/${ns}`,
icon: 'mdi:folder-outline',
});
}
}, [data]);
return null;
}
+155
View File
@@ -0,0 +1,155 @@
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,
POLARIS_DASHBOARD_PROXY,
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={POLARIS_DASHBOARD_PROXY} 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>,
},
]}
/>
</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>
</>
);
}
+40
View File
@@ -0,0 +1,40 @@
import { NameValueTable, SectionBox } from '@kinvolk/headlamp-plugin/lib/CommonComponents';
import React from 'react';
import { getRefreshInterval, INTERVAL_OPTIONS, setRefreshInterval } from '../api/polaris';
interface PluginSettingsProps {
data?: { [key: string]: string | number | boolean };
onDataChange?: (data: { [key: string]: string | number | boolean }) => void;
}
export default function PolarisSettings(props: PluginSettingsProps) {
const { data, onDataChange } = props;
const currentInterval = (data?.refreshInterval as number) ?? getRefreshInterval();
function handleChange(e: React.ChangeEvent<HTMLSelectElement>) {
const seconds = Number(e.target.value);
setRefreshInterval(seconds);
onDataChange?.({ ...data, refreshInterval: seconds });
}
return (
<SectionBox title="Polaris Settings">
<NameValueTable
rows={[
{
name: 'Refresh Interval',
value: (
<select value={currentInterval} onChange={handleChange}>
{INTERVAL_OPTIONS.map(opt => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
),
},
]}
/>
</SectionBox>
);
}
-151
View File
@@ -1,151 +0,0 @@
import { Loader, SectionBox, SectionHeader } from '@kinvolk/headlamp-plugin/lib/CommonComponents';
import React from 'react';
import {
AuditData,
countResults,
getRefreshInterval,
ResultCounts,
setRefreshInterval,
usePolarisData,
} from '../api/polaris';
const INTERVAL_OPTIONS = [
{ label: '1 minute', value: 60 },
{ label: '5 minutes', value: 300 },
{ label: '10 minutes', value: 600 },
{ label: '30 minutes', value: 1800 },
];
function RefreshSettings(props: { interval: number; onChange: (seconds: number) => void }) {
return (
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<label htmlFor="polaris-refresh-interval">Refresh interval:</label>
<select
id="polaris-refresh-interval"
value={props.interval}
onChange={e => props.onChange(Number(e.target.value))}
>
{INTERVAL_OPTIONS.map(opt => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
</div>
);
}
function StatCard(props: { label: string; value: number; color?: string }) {
return (
<div
style={{
padding: '16px 24px',
textAlign: 'center',
minWidth: '120px',
}}
>
<div
style={{
fontSize: '2rem',
fontWeight: 'bold',
color: props.color,
}}
>
{props.value}
</div>
<div style={{ fontSize: '0.875rem', opacity: 0.8 }}>{props.label}</div>
</div>
);
}
function ScoreBadge(props: { score: number }) {
const color = props.score >= 80 ? '#4caf50' : props.score >= 50 ? '#ff9800' : '#f44336';
return (
<div style={{ textAlign: 'center', marginBottom: '16px' }}>
<div style={{ fontSize: '3rem', fontWeight: 'bold', color }}>{props.score}%</div>
<div style={{ fontSize: '0.875rem', opacity: 0.8 }}>Cluster Score</div>
</div>
);
}
function OverviewSection(props: { data: AuditData; counts: ResultCounts }) {
return (
<>
<SectionBox title="Score">
<ScoreBadge score={props.data.Score} />
</SectionBox>
<SectionBox title="Check Summary">
<div
style={{
display: 'flex',
justifyContent: 'center',
flexWrap: 'wrap',
gap: '16px',
}}
>
<StatCard label="Total" value={props.counts.total} />
<StatCard label="Pass" value={props.counts.pass} color="#4caf50" />
<StatCard label="Warning" value={props.counts.warning} color="#ff9800" />
<StatCard label="Danger" value={props.counts.danger} color="#f44336" />
</div>
</SectionBox>
<SectionBox title="Cluster Info">
<div
style={{
display: 'flex',
justifyContent: 'center',
flexWrap: 'wrap',
gap: '16px',
}}
>
<StatCard label="Nodes" value={props.data.ClusterInfo.Nodes} />
<StatCard label="Pods" value={props.data.ClusterInfo.Pods} />
<StatCard label="Namespaces" value={props.data.ClusterInfo.Namespaces} />
<StatCard label="Controllers" value={props.data.ClusterInfo.Controllers} />
</div>
</SectionBox>
</>
);
}
export default function PolarisView() {
const [interval, setInterval] = React.useState(getRefreshInterval);
function handleIntervalChange(seconds: number) {
setInterval(seconds);
setRefreshInterval(seconds);
}
const { data, loading, error } = usePolarisData(interval);
if (loading) {
return <Loader title="Loading Polaris audit data..." />;
}
const counts = data ? countResults(data) : null;
return (
<>
<SectionHeader
title="Polaris"
actions={[
<RefreshSettings key="refresh" interval={interval} onChange={handleIntervalChange} />,
]}
/>
{error && (
<SectionBox title="Error">
<div style={{ padding: '16px', color: '#f44336' }}>{error}</div>
</SectionBox>
)}
{data && counts && <OverviewSection data={data} counts={counts} />}
{!data && !error && (
<SectionBox title="No Data">
<div style={{ padding: '16px' }}>No Polaris audit results found.</div>
</SectionBox>
)}
</>
);
}
+72 -3
View File
@@ -1,6 +1,16 @@
import { registerRoute, registerSidebarEntry } from '@kinvolk/headlamp-plugin/lib';
import {
registerPluginSettings,
registerRoute,
registerSidebarEntry,
} from '@kinvolk/headlamp-plugin/lib';
import React from 'react';
import PolarisView from './components/PolarisView';
import { PolarisDataProvider } from './api/PolarisDataContext';
import DashboardView from './components/DashboardView';
import DynamicSidebarRegistrar from './components/DynamicSidebarRegistrar';
import NamespaceDetailView from './components/NamespaceDetailView';
import PolarisSettings from './components/PolarisSettings';
// --- Sidebar entries ---
registerSidebarEntry({
parent: null,
@@ -10,10 +20,69 @@ registerSidebarEntry({
icon: 'mdi:shield-check',
});
registerSidebarEntry({
parent: 'polaris',
name: 'polaris-overview',
label: 'Overview',
url: '/polaris',
icon: 'mdi:view-dashboard',
});
registerSidebarEntry({
parent: 'polaris',
name: 'polaris-full',
label: 'Full Audit',
url: '/polaris/full-audit',
icon: 'mdi:clipboard-text-search',
});
registerSidebarEntry({
parent: 'polaris',
name: 'polaris-namespaces',
label: 'Namespaces',
url: '/polaris',
icon: 'mdi:dns',
});
// --- Routes ---
registerRoute({
path: '/polaris',
sidebar: 'polaris',
name: 'polaris',
exact: true,
component: () => <PolarisView />,
component: () => (
<PolarisDataProvider>
<DynamicSidebarRegistrar />
<DashboardView includeSkipped={false} />
</PolarisDataProvider>
),
});
registerRoute({
path: '/polaris/full-audit',
sidebar: 'polaris-full',
name: 'polaris-full-audit',
exact: true,
component: () => (
<PolarisDataProvider>
<DynamicSidebarRegistrar />
<DashboardView includeSkipped />
</PolarisDataProvider>
),
});
registerRoute({
path: '/polaris/ns/:namespace',
sidebar: 'polaris',
name: 'polaris-namespace',
exact: true,
component: () => (
<PolarisDataProvider>
<DynamicSidebarRegistrar />
<NamespaceDetailView />
</PolarisDataProvider>
),
});
registerPluginSettings('headlamp-polaris-plugin', PolarisSettings, true);