Compare commits

..

3 Commits

Author SHA1 Message Date
gitea-actions[bot] 6c9df7d40f ci: update artifact hub metadata for v0.2.0-dev.4 2026-02-09 17:27:39 +00:00
Chris Farhood c7a1f15fcf refactor: move to single-repo pattern for releases 2026-02-09 11:59:22 -05:00
Chris Farhood 261d636d71 fix: use dynamic repo URLs in metadata update step
The metadata update step was hardcoded to push to the stable repo,
causing dev releases to pollute the stable repo's main branch.

Changes:
- Use ${GITHUB_REPO} in archive-url instead of hardcoded stable repo
- Use ${GITHUB_REPO} in git remote instead of hardcoded stable repo
- Determine GITEA_BRANCH dynamically (dev/namespace-drawer for dev, main for stable)
- Push the correct Gitea branch to GitHub main branch
- Use temp branch to avoid conflicts

Now dev releases only touch the dev repo, and stable releases only
touch the stable repo.
2026-02-09 11:55:47 -05:00
14 changed files with 127 additions and 637 deletions
+48 -25
View File
@@ -112,35 +112,53 @@ jobs:
echo "Gitea release updated"
- name: Create GitHub release
continue-on-error: true
run: |
[ "$SKIP_BUILD" = "true" ] && exit 0
# GitHub API to create/update release
GITHUB_API="https://api.github.com/repos/cpfarhood/headlamp-polaris-plugin"
# Check if release exists
RELEASE_DATA=$(curl -sf \
-H "Authorization: token ${{ secrets.GH_TOKEN }}" \
"${GITHUB_API}/releases/tags/${GITHUB_REF_NAME}" || echo "{}")
RELEASE_ID=$(echo "$RELEASE_DATA" | node -e "process.stdin.resume();let d='';process.stdin.on('data',c=>d+=c);process.stdin.on('end',()=>console.log(JSON.parse(d).id||''))")
if [ -z "$RELEASE_ID" ]; then
# Create new release
RELEASE_DATA=$(curl -sf -X POST \
-H "Authorization: token ${{ secrets.GH_TOKEN }}" \
-H "Content-Type: application/json" \
"${GITHUB_API}/releases" \
-d "{\"tag_name\":\"${GITHUB_REF_NAME}\",\"name\":\"${GITHUB_REF_NAME}\",\"draft\":false,\"prerelease\":false}")
RELEASE_ID=$(echo "$RELEASE_DATA" | node -e "process.stdin.resume();let d='';process.stdin.on('data',c=>d+=c);process.stdin.on('end',()=>console.log(JSON.parse(d).id))")
# Push tag to GitHub first so it exists before creating the release
git remote add github-release https://x-access-token:${{ secrets.GH_PAT }}@github.com/cpfarhood/headlamp-polaris-plugin.git 2>/dev/null || true
git push -f github-release ${GITHUB_REF_NAME} 2>/dev/null || true
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 }}" \
-H "Accept: application/vnd.github+json" \
"${GH_API}/releases" \
-d "{\"tag_name\":\"${GITHUB_REF_NAME}\",\"name\":\"${GITHUB_REF_NAME}\",\"generate_release_notes\":true}")
RELEASE_ID=$(echo "$BODY" | node -e "process.stdin.resume();let d='';process.stdin.on('data',c=>d+=c);process.stdin.on('end',()=>console.log(JSON.parse(d).id))")
if [ "$RELEASE_ID" = "undefined" ]; then
echo "Release already exists, fetching it..."
BODY=$(curl -sf \
-H "Authorization: token ${{ secrets.GH_PAT }}" \
-H "Accept: application/vnd.github+json" \
"${GH_API}/releases/tags/${GITHUB_REF_NAME}")
RELEASE_ID=$(echo "$BODY" | node -e "process.stdin.resume();let d='';process.stdin.on('data',c=>d+=c);process.stdin.on('end',()=>console.log(JSON.parse(d).id))")
fi
echo "GitHub Release ID: $RELEASE_ID"
# Upload tarball to GitHub
UPLOAD_URL=$(echo "$RELEASE_DATA" | node -e "process.stdin.resume();let d='';process.stdin.on('data',c=>d+=c);process.stdin.on('end',()=>{const r=JSON.parse(d);console.log(r.upload_url||'https://uploads.github.com/repos/cpfarhood/headlamp-polaris-plugin/releases/${RELEASE_ID}/assets')})" | sed 's/{.*}//')
# Delete existing assets with the same name
ASSETS=$(curl -sf \
-H "Authorization: token ${{ secrets.GH_PAT }}" \
-H "Accept: application/vnd.github+json" \
"${GH_API}/releases/${RELEASE_ID}/assets")
echo "$ASSETS" | node -e "
process.stdin.resume();let d='';
process.stdin.on('data',c=>d+=c);
process.stdin.on('end',()=>{
const assets=JSON.parse(d);
assets.filter(a=>a.name==='${TARBALL}').forEach(a=>console.log(a.id));
})" | while read -r ASSET_ID; do
echo "Deleting existing asset $ASSET_ID..."
curl -sf -X DELETE \
-H "Authorization: token ${{ secrets.GH_PAT }}" \
"${GH_API}/releases/assets/${ASSET_ID}"
done
# Upload tarball
curl -sf -X POST \
-H "Authorization: token ${{ secrets.GH_TOKEN }}" \
-H "Authorization: token ${{ secrets.GH_PAT }}" \
-H "Content-Type: application/gzip" \
--data-binary "@${TARBALL}" \
"${UPLOAD_URL}?name=${TARBALL}"
echo "GitHub release updated"
"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"
- name: Update metadata and align tag
run: |
@@ -150,7 +168,7 @@ jobs:
git config user.email "gitea-actions[bot]@git.farh.net"
# Determine which Gitea branch to update based on version suffix
if [[ "$VERSION" == *"-dev."* ]]; then
GITEA_BRANCH="dev"
GITEA_BRANCH="dev/namespace-drawer"
else
GITEA_BRANCH="main"
fi
@@ -169,5 +187,10 @@ jobs:
# that the release checksum already matches and skip the build.
git tag -f ${GITHUB_REF_NAME}
git push -f origin ${GITHUB_REF_NAME}
# Also push to GitHub directly to avoid waiting for mirror sync
# Single repo pattern: both stable and dev releases go to same GitHub repo
# ArtifactHub will differentiate based on prerelease flag in metadata
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 temp-update: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"
echo "Note: GitHub sync handled by Gitea mirror configuration"
-102
View File
@@ -1,102 +0,0 @@
name: Release
on:
push:
tags:
- 'v*'
jobs:
release:
runs-on: ubuntu-latest
permissions:
contents: write
packages: write
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
token: ${{ secrets.GITHUB_TOKEN }}
- name: Check if release is already finalized
run: |
VERSION=${GITHUB_REF_NAME#v}
TARBALL_URL="https://github.com/${{ github.repository }}/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}')"
EXPECTED=$(grep 'archive-checksum' artifacthub-pkg.yml | awk '{print $2}')
echo "Release tarball checksum: $ACTUAL"
echo "Metadata checksum: $EXPECTED"
if [ "$ACTUAL" = "$EXPECTED" ]; then
echo "SKIP_BUILD=true" >> $GITHUB_ENV
echo "Checksums match - release is finalized, nothing to do"
fi
else
echo "No existing release (HTTP $HTTP_CODE) - will build"
fi
rm -f /tmp/release.tar.gz
- name: Setup Node.js
if: env.SKIP_BUILD != 'true'
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install dependencies
if: env.SKIP_BUILD != 'true'
run: npm ci
- name: Build plugin
if: env.SKIP_BUILD != 'true'
run: npx @kinvolk/headlamp-plugin build
- name: Package tarball
if: env.SKIP_BUILD != 'true'
run: npx @kinvolk/headlamp-plugin package
- name: Compute tarball checksum
if: env.SKIP_BUILD != 'true'
run: |
TARBALL=$(ls *.tar.gz)
CHECKSUM=$(sha256sum "$TARBALL" | awk '{print $1}')
echo "TARBALL=$TARBALL" >> $GITHUB_ENV
echo "CHECKSUM=$CHECKSUM" >> $GITHUB_ENV
echo "Tarball: $TARBALL"
echo "Checksum: sha256:$CHECKSUM"
- name: Create GitHub release and upload tarball
if: env.SKIP_BUILD != 'true'
uses: softprops/action-gh-release@v1
with:
files: ${{ env.TARBALL }}
fail_on_unmatched_files: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Update metadata and align tag
if: env.SKIP_BUILD != 'true'
run: |
VERSION=${GITHUB_REF_NAME#v}
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
# Update metadata
git fetch origin main
git checkout origin/main -B temp-update
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/${{ github.repository }}/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
if ! git diff --cached --quiet; then
git commit -m "ci: update artifact hub metadata for ${GITHUB_REF_NAME}"
git push origin temp-update:main
fi
# Force-move tag to the commit with correct checksum.
# This triggers a new CI run, but the guard step will detect
# that the release checksum already matches and skip the build.
git tag -f ${GITHUB_REF_NAME}
git push -f origin ${GITHUB_REF_NAME}
echo "Tag ${GITHUB_REF_NAME} aligned with updated metadata"
-4
View File
@@ -83,10 +83,6 @@ npm run build
npx @kinvolk/headlamp-plugin extract . /headlamp/plugins
```
## Installing Dev/Preview Versions
Dev preview versions are **not currently available** through the Headlamp plugin manager. Stable versions can be installed from ArtifactHub via the plugin manager UI.
## 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:
+3 -3
View File
@@ -1,4 +1,4 @@
version: 0.2.4
version: 0.2.0-dev.4
name: headlamp-polaris-plugin
displayName: Polaris
createdAt: "2026-02-05T19:00:00Z"
@@ -28,7 +28,7 @@ maintainers:
- name: cpfarhood
email: "chris@farhood.org"
annotations:
headlamp/plugin/archive-url: "https://github.com/cpfarhood/headlamp-polaris-plugin/releases/download/v0.2.4/headlamp-polaris-plugin-0.2.4.tar.gz"
headlamp/plugin/archive-url: "https://github.com/cpfarhood/headlamp-polaris-plugin/releases/download/v0.2.0-dev.4/headlamp-polaris-plugin-0.2.0-dev.4.tar.gz"
headlamp/plugin/version-compat: ">=0.26"
headlamp/plugin/archive-checksum: sha256:f619640371dc2d18e0a8eca03ed046ed4adc3a3c11468fc192e536b324f82914
headlamp/plugin/archive-checksum: sha256:70d46b8b478326794646bd90f9b4178c3010310509feecbe40305622954436a4
headlamp/plugin/distro-compat: in-cluster
+15 -64
View File
@@ -20,91 +20,42 @@ test.describe('Polaris plugin smoke tests', () => {
await expect(page.getByText(/%/)).toBeVisible();
});
test('namespaces page renders table with namespace buttons', async ({ page }) => {
test('namespaces page renders table with links', async ({ page }) => {
await page.goto('/c/main/polaris/namespaces');
await expect(page.getByRole('heading', { name: 'Polaris \u2014 Namespaces' })).toBeVisible();
// Table should have at least one row with a namespace button
// Table should have at least one row with a namespace link
const table = page.locator('table');
await expect(table).toBeVisible();
const rows = table.locator('tbody tr');
await expect(rows.first()).toBeVisible();
// Each namespace row should contain a button (now buttons instead of links for drawer)
const firstButton = rows.first().locator('button');
await expect(firstButton).toBeVisible();
// Each namespace row should contain a link
const firstLink = rows.first().locator('a');
await expect(firstLink).toBeVisible();
});
test('namespace detail drawer opens from table button', async ({ page }) => {
test('namespace detail page renders from table link', async ({ page }) => {
await page.goto('/c/main/polaris/namespaces');
// Click the first namespace button in the table
// Click the first namespace link in the table
const table = page.locator('table');
await expect(table).toBeVisible();
const firstButton = table.locator('tbody tr').first().locator('button');
const namespaceName = await firstButton.textContent();
await firstButton.click();
const firstLink = table.locator('tbody tr').first().locator('a');
const namespaceName = await firstLink.textContent();
await firstLink.click();
// Drawer should open and show the namespace name in the heading
await expect(
page.getByRole('heading', { name: `Polaris \u2014 ${namespaceName}` })
).toBeVisible();
// "Namespace Score" section should be present in drawer
await expect(page.getByText('Namespace Score')).toBeVisible();
// Resources table should exist in drawer
await expect(page.getByText('Resources')).toBeVisible();
// URL hash should be updated with namespace name
await expect(page).toHaveURL(/\/polaris\/namespaces#/);
});
test('namespace detail drawer closes with Escape key', async ({ page }) => {
await page.goto('/c/main/polaris/namespaces');
// Open the drawer by clicking a namespace button
const table = page.locator('table');
await expect(table).toBeVisible();
const firstButton = table.locator('tbody tr').first().locator('button');
const namespaceName = await firstButton.textContent();
await firstButton.click();
// Verify drawer is open
await expect(
page.getByRole('heading', { name: `Polaris \u2014 ${namespaceName}` })
).toBeVisible();
// Press Escape key
await page.keyboard.press('Escape');
// Drawer should close (heading should not be visible anymore)
await expect(
page.getByRole('heading', { name: `Polaris \u2014 ${namespaceName}` })
).not.toBeVisible();
// URL hash should be cleared
await expect(page).toHaveURL(/\/polaris\/namespaces$/);
});
test('namespace detail drawer opens from URL hash', async ({ page }) => {
// Get a namespace name first
await page.goto('/c/main/polaris/namespaces');
const table = page.locator('table');
await expect(table).toBeVisible();
const firstButton = table.locator('tbody tr').first().locator('button');
const namespaceName = await firstButton.textContent();
// Navigate directly to URL with hash
await page.goto(`/c/main/polaris/namespaces#${namespaceName}`);
// Drawer should automatically open with the namespace details
// Detail page should show the namespace name in the heading
await expect(
page.getByRole('heading', { name: `Polaris \u2014 ${namespaceName}` })
).toBeVisible();
// "Namespace Score" section should be present
await expect(page.getByText('Namespace Score')).toBeVisible();
// Resources table should exist
await expect(page.getByText('Resources')).toBeVisible();
await expect(page.locator('table')).toBeVisible();
});
});
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "headlamp-polaris-plugin",
"version": "0.2.0",
"version": "0.1.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "headlamp-polaris-plugin",
"version": "0.2.0",
"version": "0.1.3",
"devDependencies": {
"@kinvolk/headlamp-plugin": "^0.13.0",
"@playwright/test": "^1.58.2"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "headlamp-polaris-plugin",
"version": "0.2.4",
"version": "0.1.6",
"description": "Headlamp plugin for Fairwinds Polaris audit results",
"scripts": {
"start": "headlamp-plugin start",
+17 -67
View File
@@ -125,14 +125,11 @@ export const INTERVAL_OPTIONS = [
{ label: '30 minutes', value: 1800 },
];
const REFRESH_STORAGE_KEY = 'polaris-plugin-refresh-interval';
const 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/';
export function getRefreshInterval(): number {
const stored = localStorage.getItem(REFRESH_STORAGE_KEY);
const stored = localStorage.getItem(STORAGE_KEY);
if (stored !== null) {
const parsed = parseInt(stored, 10);
if (!isNaN(parsed) && parsed > 0) {
@@ -143,26 +140,13 @@ export function getRefreshInterval(): number {
}
export function setRefreshInterval(seconds: number): void {
localStorage.setItem(REFRESH_STORAGE_KEY, String(seconds));
}
export function getDashboardUrl(): string {
const stored = localStorage.getItem(URL_STORAGE_KEY);
if (stored !== null && stored.trim() !== '') {
return stored.trim();
}
return DEFAULT_DASHBOARD_URL;
}
export function setDashboardUrl(url: string): void {
localStorage.setItem(URL_STORAGE_KEY, url.trim());
localStorage.setItem(STORAGE_KEY, String(seconds));
}
// --- Polaris dashboard proxy URL ---
export function getPolarisProxyUrl(): string {
return getDashboardUrl();
}
export const POLARIS_DASHBOARD_PROXY =
'/api/v1/namespaces/polaris/services/polaris-dashboard:80/proxy/';
// --- Score computation ---
@@ -173,14 +157,8 @@ export function computeScore(counts: ResultCounts): number {
// --- Data fetching hook ---
function getPolarisApiPath(): string {
const baseUrl = getDashboardUrl();
return baseUrl.endsWith('/') ? `${baseUrl}results.json` : `${baseUrl}/results.json`;
}
function isFullUrl(url: string): boolean {
return url.startsWith('http://') || url.startsWith('https://');
}
const POLARIS_API_PATH =
'/api/v1/namespaces/polaris/services/polaris-dashboard:80/proxy/results.json';
interface PolarisDataState {
data: AuditData | null;
@@ -199,21 +177,7 @@ export function usePolarisData(refreshIntervalSeconds: number): PolarisDataState
async function fetchData() {
try {
const apiPath = getPolarisApiPath();
let result: AuditData;
if (isFullUrl(apiPath)) {
// Direct fetch for full URLs
const response = await fetch(apiPath);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
result = await response.json();
} else {
// Kubernetes proxy for relative URLs
result = await ApiProxy.request(apiPath);
}
const result: AuditData = await ApiProxy.request(POLARIS_API_PATH);
if (!cancelled) {
setData(result);
setError(null);
@@ -221,31 +185,17 @@ export function usePolarisData(refreshIntervalSeconds: number): PolarisDataState
}
} catch (err: unknown) {
if (cancelled) return;
const apiPath = getPolarisApiPath();
const status = (err as { status?: number }).status;
if (isFullUrl(apiPath)) {
// Full URL errors
if (status === 403) {
setError('Access denied (403). Check authentication and CORS configuration.');
} else if (status === 404) {
setError('Polaris dashboard not found (404). Verify the URL is correct.');
} else {
setError(`Failed to fetch from ${apiPath}: ${String(err)}`);
}
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 {
// Kubernetes proxy errors
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 configured namespace.'
);
} else {
setError(`Failed to fetch Polaris data: ${String(err)}`);
}
setError(`Failed to fetch Polaris data: ${String(err)}`);
}
setLoading(false);
}
+9
View File
@@ -26,6 +26,7 @@ function OverviewSection(props: { data: AuditData; counts: ResultCounts }) {
{ name: 'Pass', value: counts.pass, fill: COLORS.pass },
{ name: 'Warning', value: counts.warning, fill: COLORS.warning },
{ name: 'Danger', value: counts.danger, fill: COLORS.danger },
{ name: 'Skipped', value: counts.skipped, fill: COLORS.skipped },
];
return (
@@ -50,6 +51,14 @@ function OverviewSection(props: { data: AuditData; counts: ResultCounts }) {
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>
+2 -2
View File
@@ -12,7 +12,7 @@ import {
computeScore,
countResultsForItems,
filterResultsByNamespace,
getPolarisProxyUrl,
POLARIS_DASHBOARD_PROXY,
Result,
ResultCounts,
} from '../api/polaris';
@@ -89,7 +89,7 @@ export default function NamespaceDetailView() {
{
name: 'Polaris Dashboard',
value: (
<a href={getPolarisProxyUrl()} target="_blank" rel="noopener noreferrer">
<a href={POLARIS_DASHBOARD_PROXY} target="_blank" rel="noopener noreferrer">
View in Polaris Dashboard
</a>
),
+6 -79
View File
@@ -1,5 +1,4 @@
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React from 'react';
import { MemoryRouter } from 'react-router-dom';
import { describe, expect, it, vi } from 'vitest';
@@ -118,7 +117,7 @@ describe('NamespacesListView', () => {
expect(screen.getByText('No Polaris audit results found.')).toBeInTheDocument();
});
it('renders namespace rows with correct scores and buttons', () => {
it('renders namespace rows with correct scores and links', () => {
const data = makeAuditData([
makeResult({
Name: 'deploy-a',
@@ -158,14 +157,12 @@ describe('NamespacesListView', () => {
renderWithRouter(<NamespacesListView />);
// Namespace buttons (now buttons instead of links for drawer)
const alphaButton = screen.getByText('alpha');
expect(alphaButton).toBeInTheDocument();
expect(alphaButton.tagName).toBe('BUTTON');
// Namespace links
const alphaLink = screen.getByText('alpha');
expect(alphaLink.closest('a')).toHaveAttribute('href', '/polaris/ns/alpha');
const betaButton = screen.getByText('beta');
expect(betaButton).toBeInTheDocument();
expect(betaButton.tagName).toBe('BUTTON');
const betaLink = screen.getByText('beta');
expect(betaLink.closest('a')).toHaveAttribute('href', '/polaris/ns/beta');
});
it('uses correct scoreStatus: >=80 success, >=50 warning, <50 error', () => {
@@ -219,74 +216,4 @@ describe('NamespacesListView', () => {
const errorScore = scoreLabels.find(el => el.textContent === '0%');
expect(errorScore).toHaveAttribute('data-status', 'error');
});
it('opens drawer when namespace button is clicked and URL hash is updated', async () => {
const user = userEvent.setup();
const data = makeAuditData([
makeResult({
Name: 'deploy-a',
Namespace: 'alpha',
Results: {
c1: {
ID: 'c1',
Message: '',
Details: [],
Success: true,
Severity: 'warning',
Category: 'X',
},
},
}),
]);
mockUsePolarisDataContext.mockReturnValue({
data,
loading: false,
error: null,
});
renderWithRouter(<NamespacesListView />);
// Click the namespace button
const alphaButton = screen.getByText('alpha');
await user.click(alphaButton);
// Drawer should open (check for the panel title)
expect(screen.getByText(/Polaris — alpha/)).toBeInTheDocument();
});
it('initializes drawer from URL hash', () => {
const data = makeAuditData([
makeResult({
Name: 'deploy-a',
Namespace: 'test-ns',
Results: {
c1: {
ID: 'c1',
Message: '',
Details: [],
Success: true,
Severity: 'warning',
Category: 'X',
},
},
}),
]);
mockUsePolarisDataContext.mockReturnValue({
data,
loading: false,
error: null,
});
// Render with initial hash in URL
render(
<MemoryRouter initialEntries={['/polaris/namespaces#test-ns']}>
<NamespacesListView />
</MemoryRouter>
);
// Drawer should be open with the namespace from hash
expect(screen.getByText(/Polaris — test-ns/)).toBeInTheDocument();
});
});
+8 -253
View File
@@ -1,3 +1,4 @@
import { Router } from '@kinvolk/headlamp-plugin/lib';
import {
Loader,
NameValueTable,
@@ -6,16 +7,13 @@ import {
SimpleTable,
StatusLabel,
} from '@kinvolk/headlamp-plugin/lib/CommonComponents';
import React, { useEffect, useState } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import React from 'react';
import { Link } from 'react-router-dom';
import {
computeScore,
countResultsForItems,
filterResultsByNamespace,
getNamespaces,
getPolarisProxyUrl,
Result,
ResultCounts,
} from '../api/polaris';
import { usePolarisDataContext } from '../api/PolarisDataContext';
@@ -34,226 +32,9 @@ interface NamespaceRow {
skipped: number;
}
function resourceCounts(result: Result): ResultCounts {
return countResultsForItems([result]);
}
interface NamespaceDetailPanelProps {
namespace: string;
onClose: () => void;
}
function NamespaceDetailPanel({ namespace, onClose }: NamespaceDetailPanelProps) {
const { data, loading, error } = usePolarisDataContext();
if (loading) {
return (
<div style={{ padding: '20px' }}>
<Loader title={`Loading Polaris data for ${namespace}...`} />
</div>
);
}
if (error) {
return (
<div style={{ padding: '20px' }}>
<SectionBox title="Error">
<NameValueTable
rows={[
{
name: 'Status',
value: <StatusLabel status="error">{error}</StatusLabel>,
},
]}
/>
</SectionBox>
</div>
);
}
if (!data) {
return (
<div style={{ padding: '20px' }}>
<SectionBox title="No Data">
<NameValueTable rows={[{ name: 'Status', value: 'No Polaris audit results found.' }]} />
</SectionBox>
</div>
);
}
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 (
<div
style={{
position: 'fixed',
right: 0,
top: 0,
bottom: 0,
width: '1000px',
backgroundColor: 'var(--background-paper, #fff)',
boxShadow: '-2px 0 8px rgba(0,0,0,0.15)',
overflowY: 'auto',
zIndex: 1200,
padding: '20px',
}}
>
<div
style={{
marginBottom: '20px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<h2 style={{ margin: 0 }}>Polaris {namespace}</h2>
<button
onClick={onClose}
style={{
border: 'none',
background: 'transparent',
fontSize: '24px',
cursor: 'pointer',
padding: '0 8px',
}}
aria-label="Close panel"
>
×
</button>
</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 location = useLocation();
const history = useHistory();
const { data, loading, error } = usePolarisDataContext();
// Initialize from URL hash
const [selectedNamespace, setSelectedNamespace] = useState<string | null>(
location.hash.slice(1) || null
);
// Sync drawer state when URL hash changes (browser back/forward)
useEffect(() => {
const hashNs = location.hash.slice(1);
setSelectedNamespace(hashNs || null);
}, [location.hash]);
const openNamespace = (ns: string) => {
setSelectedNamespace(ns);
history.push(`${location.pathname}#${ns}`);
};
const closeNamespace = () => {
setSelectedNamespace(null);
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..." />;
}
@@ -311,20 +92,13 @@ export default function NamespacesListView() {
{
label: 'Namespace',
getter: (row: NamespaceRow) => (
<button
onClick={() => openNamespace(row.namespace)}
style={{
border: 'none',
background: 'transparent',
color: 'var(--link-color, #1976d2)',
cursor: 'pointer',
textDecoration: 'underline',
padding: 0,
font: 'inherit',
}}
<Link
to={Router.createRouteURL('polaris-namespace', {
namespace: row.namespace,
})}
>
{row.namespace}
</button>
</Link>
),
},
{
@@ -356,25 +130,6 @@ export default function NamespacesListView() {
emptyMessage="No namespaces found in Polaris audit data."
/>
</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"
/>
<NamespaceDetailPanel namespace={selectedNamespace} onClose={closeNamespace} />
</>
)}
</>
);
}
+3 -35
View File
@@ -1,6 +1,6 @@
import { NameValueTable, SectionBox } from '@kinvolk/headlamp-plugin/lib/CommonComponents';
import React from 'react';
import { getDashboardUrl, getRefreshInterval, INTERVAL_OPTIONS, setDashboardUrl, setRefreshInterval } from '../api/polaris';
import { getRefreshInterval, INTERVAL_OPTIONS, setRefreshInterval } from '../api/polaris';
interface PluginSettingsProps {
data?: { [key: string]: string | number | boolean };
@@ -10,20 +10,13 @@ interface PluginSettingsProps {
export default function PolarisSettings(props: PluginSettingsProps) {
const { data, onDataChange } = props;
const currentInterval = (data?.refreshInterval as number) ?? getRefreshInterval();
const currentUrl = (data?.dashboardUrl as string) ?? getDashboardUrl();
function handleIntervalChange(e: React.ChangeEvent<HTMLSelectElement>) {
function handleChange(e: React.ChangeEvent<HTMLSelectElement>) {
const seconds = Number(e.target.value);
setRefreshInterval(seconds);
onDataChange?.({ ...data, refreshInterval: seconds });
}
function handleUrlChange(e: React.ChangeEvent<HTMLInputElement>) {
const url = e.target.value;
setDashboardUrl(url);
onDataChange?.({ ...data, dashboardUrl: url });
}
return (
<SectionBox title="Polaris Settings">
<NameValueTable
@@ -31,7 +24,7 @@ export default function PolarisSettings(props: PluginSettingsProps) {
{
name: 'Refresh Interval',
value: (
<select value={currentInterval} onChange={handleIntervalChange}>
<select value={currentInterval} onChange={handleChange}>
{INTERVAL_OPTIONS.map(opt => (
<option key={opt.value} value={opt.value}>
{opt.label}
@@ -40,31 +33,6 @@ export default function PolarisSettings(props: PluginSettingsProps) {
</select>
),
},
{
name: 'Dashboard URL',
value: (
<div>
<input
type="text"
value={currentUrl}
onChange={handleUrlChange}
placeholder="/api/v1/namespaces/polaris/services/polaris-dashboard:80/proxy/"
style={{
width: '100%',
padding: '4px 8px',
border: '1px solid #ccc',
borderRadius: '4px',
fontSize: '14px',
}}
/>
<div style={{ fontSize: '12px', color: '#666', marginTop: '4px' }}>
Examples:<br />
K8s proxy: <code>/api/v1/namespaces/polaris/services/polaris-dashboard:80/proxy/</code><br />
Full URL: <code>https://my-polaris.example.com</code>
</div>
</div>
),
},
]}
/>
</SectionBox>
+13
View File
@@ -6,6 +6,7 @@ import {
import React from 'react';
import { PolarisDataProvider } from './api/PolarisDataContext';
import DashboardView from './components/DashboardView';
import NamespaceDetailView from './components/NamespaceDetailView';
import NamespacesListView from './components/NamespacesListView';
import PolarisSettings from './components/PolarisSettings';
@@ -61,4 +62,16 @@ registerRoute({
),
});
registerRoute({
path: '/polaris/ns/:namespace',
sidebar: 'polaris-namespaces',
name: 'polaris-namespace',
exact: true,
component: () => (
<PolarisDataProvider>
<NamespaceDetailView />
</PolarisDataProvider>
),
});
registerPluginSettings('polaris', PolarisSettings, true);