diff --git a/docs/reference/renderers.md b/docs/reference/renderers.md index e424e427..b8393105 100644 --- a/docs/reference/renderers.md +++ b/docs/reference/renderers.md @@ -98,7 +98,7 @@ Built-in Projections runtime security policy renderer: hooks, the rules that act - Handles: `runtime-policy` - Comparison modes: `diff`, `side-by-side` - Package: `@githubnext/projections-renderer-runtime-policy` -- Example scenarios ([`scenarios.json`](../../packages/renderers/runtime-policy/scenarios.json)): Kill downloaders reading the service account token; The same change, default comparator; Switch a policy to monitor mode; Broaden a policy and turn off the policy filter; A policy library; A deployment at a glance +- Example scenarios ([`scenarios.json`](../../packages/renderers/runtime-policy/scenarios.json)): Kill downloaders reading the service account token; The same change, default comparator; Switch a policy to monitor mode; Broaden a policy and turn off the policy filter; Broaden a policy, its unchanged rows folded; A policy library; A deployment at a glance ## `text-diff` diff --git a/packages/renderers/runtime-policy/README.md b/packages/renderers/runtime-policy/README.md index a264bd1a..ec1f53a7 100644 --- a/packages/renderers/runtime-policy/README.md +++ b/packages/renderers/runtime-policy/README.md @@ -110,6 +110,18 @@ no `animated` or `swipe` mode. highlighting off carry none, and the change column is laid out on every changed row so status appearing never moves anything. - **Identity comes from the comparison.** Nothing is matched by label. +- **Unchanged rows.** A host control, **Unchanged rows** (`unchanged`: `show`, + the default, or `fold`), folds the All scope's unchanged rows in a comparison: + each run of two or more unchanged agents, kernels, policies or workloads + becomes one row ("2 unchanged kernels"), and each run of unchanged hooks one + line ("3 unchanged hooks"), since a lane is far taller than its fold. A row + counts as changed when it or a chip inside it is. The folds are the kit's + `Fold`, as the database renderer's unchanged columns are: a fold opens in + place and stays above what it lists as "Hide 3 unchanged hooks". A definition + presets it where a change is small beside its unchanged surroundings + (`presentation.rendererOptions: {"unchanged": "fold"}`; the + `deployment-review-folded` scenario). The Changes scope already leaves + unchanged rows out, so it never folds. Without the comparator (a definition that uses the default one) every change is still marked, with old and new values; only the interpretation words and finding diff --git a/packages/renderers/runtime-policy/browser/fold.spec.ts b/packages/renderers/runtime-policy/browser/fold.spec.ts new file mode 100644 index 00000000..4ebddc49 --- /dev/null +++ b/packages/renderers/runtime-policy/browser/fold.spec.ts @@ -0,0 +1,81 @@ +import {expect, test} from '@playwright/test' +import {openStage} from '@githubnext/projections-renderer-testing/playwright' +import {harnessInspector} from '@githubnext/projections-renderer-harness/playwright' + +/** + * The Unchanged rows control: Show (the default) lists every row; Fold, as a definition presets it, folds each run of + * unchanged rows into one row and each unchanged hook's lane into one line, which opens in place and closes again, + * while every change stays drawn. + */ +test('the Unchanged rows control folds unchanged rows and hooks, and a fold opens in place', async ({page}) => { + const inspector = harnessInspector() + const shown = await openStage(page, inspector, {scenario: 'runtime-policy/deployment-review', comparisonMode: 'diff', width: 1000}) + await shown.measure('settle') + const listed = await shown.frame.locator('[data-change]').count() + await expect(shown.frame.locator('.rp-fold')).toHaveCount(0) + const tall = await shown.frame.locator('.rp-view').evaluate(view => view.getBoundingClientRect().height) + + const folded = await openStage(page, inspector, { + scenario: 'runtime-policy/deployment-review-folded', + comparisonMode: 'diff', + width: 1000, + }) + await folded.measure('settle') + const frame = folded.frame + await expect(frame.locator('.rp-fold')).toHaveText(['2 unchanged kernels', '1 unchanged hook', '3 unchanged hooks']) + // Every change is still drawn; only unchanged rows fold. + expect(await frame.locator('[data-change]').count()).toBe(listed) + await expect(frame.locator('.rp-fold [data-change]')).toHaveCount(0) + expect(await frame.locator('.rp-view').evaluate(view => view.getBoundingClientRect().height)).toBeLessThan(tall - 400) + // A fold is a row of its table, as wide as the table, its label on one line. + for (const fold of await frame.locator('.rp-fold').all()) { + const [row, table] = await fold.evaluate(element => [ + element.getBoundingClientRect().width, + (element.parentElement ?? element).getBoundingClientRect().width, + ]) + expect(row).toBeCloseTo(table, 0) + expect(await fold.locator('.pk-fold-label').evaluate(label => label.getClientRects().length)).toBe(1) + } + + const hooks = frame.getByRole('button', {name: '3 unchanged hooks'}) + const lanes = await frame.locator('.rp-lane').count() + await hooks.click() + await expect(frame.getByRole('button', {name: 'Hide 3 unchanged hooks'})).toHaveAttribute('aria-expanded', 'true') + await expect(frame.locator('.rp-lane')).toHaveCount(lanes + 3) + await frame.getByRole('button', {name: 'Hide 3 unchanged hooks'}).click() + await expect(frame.locator('.rp-lane')).toHaveCount(lanes) +}) + +test('the Changes scope never folds: it already leaves unchanged rows out', async ({page}) => { + const stage = await openStage(page, harnessInspector(), { + scenario: 'runtime-policy/deployment-review-folded', + comparisonMode: 'diff', + width: 1000, + }) + await stage.measure('settle') + await expect(stage.frame.locator('.rp-fold')).not.toHaveCount(0) + const subject = stage.subject + if (subject.mode !== 'comparison') throw new Error('the scenario is a comparison') + const scope = subject.comparison.changes.flatMap(change => (change.status === 'unchanged' ? [] : [...change.before, ...change.after])) + await stage.filter({query: '', changesOnly: true, ids: null, scope}) + await expect(stage.frame.locator('.rp-fold')).toHaveCount(0) +}) + +test('a side-by-side pane folds what the comparison leaves unchanged, not what its own revision draws alike', async ({page}) => { + const inspector = harnessInspector() + for (const pane of ['before', 'after'] as const) { + const stage = await openStage(page, inspector, { + scenario: 'runtime-policy/deployment-review-folded', + comparisonMode: 'side-by-side', + pane, + width: 1000, + }) + await stage.measure('settle') + // Every workload's coverage changes, which a pane draws with no chip arriving or leaving: none of them folds. + await expect(stage.frame.locator('.rp-fold', {hasText: 'workload'}), pane).toHaveCount(0) + for (const workload of ['checkout-web', 'payments-api', 'settlement']) { + await expect(stage.frame.locator('.rp-name', {hasText: workload}), `${pane}: ${workload}`).toBeVisible() + } + await expect(stage.frame.locator('.rp-fold', {hasText: 'unchanged kernels'}), pane).toHaveCount(1) + } +}) diff --git a/packages/renderers/runtime-policy/scenarios.json b/packages/renderers/runtime-policy/scenarios.json index f72844a0..5e2ac552 100644 --- a/packages/renderers/runtime-policy/scenarios.json +++ b/packages/renderers/runtime-policy/scenarios.json @@ -37,6 +37,20 @@ "after": "../../extractors/tetragon-policies/tests/fixtures/deployment/after.expected.json", "comparator": "../../comparators/runtime-policy/runtime-policy.comparator.yaml" }, + { + "id": "deployment-review-folded", + "title": "Broaden a policy, its unchanged rows folded", + "group": "With deployment facts", + "description": "The deployment review with the Unchanged rows control preset to Fold, as a definition sets it (`presentation.rendererOptions: {\"unchanged\": \"fold\"}`): each run of unchanged policies, workloads and kernels folds into one row, and each unchanged hook's lane into one line, which opens in place.", + "before": "../../extractors/tetragon-policies/tests/fixtures/deployment/before.expected.json", + "after": "../../extractors/tetragon-policies/tests/fixtures/deployment/after.expected.json", + "comparator": "../../comparators/runtime-policy/runtime-policy.comparator.yaml", + "presentation": { + "rendererOptions": { + "unchanged": "fold" + } + } + }, { "id": "policy-library", "title": "A policy library", diff --git a/packages/renderers/runtime-policy/src/fold.ts b/packages/renderers/runtime-policy/src/fold.ts new file mode 100644 index 00000000..a06337a9 --- /dev/null +++ b/packages/renderers/runtime-policy/src/fold.ts @@ -0,0 +1,84 @@ +import {isChanged} from '@githubnext/projections-renderer-kit' +import type {RendererControl} from '@githubnext/projections-renderer-sdk/protocol' +import type {Chip, HookItem, Item, PolicyItem, RuntimePolicyModel, SelectorItem, WorkloadItem} from './model.js' + +/** + * The host draws this in a comparison: whether the All scope lists unchanged rows or folds them. A definition presets + * it (`presentation.rendererOptions: {"unchanged": "fold"}`) where a change is small beside its unchanged surroundings, + * as on a stage too short to list both. The Changes scope already leaves unchanged rows out. + */ +export const unchangedControl: RendererControl = { + id: 'unchanged', + label: 'Unchanged rows', + description: 'List unchanged agents, policies, workloads and hooks, or fold each run of them into one row', + type: 'choice', + group: 'rows', + groupLabel: 'Rows', + default: 'show', + choices: [ + {value: 'show', label: 'Show'}, + {value: 'fold', label: 'Fold'}, + ], +} + +const chipsChanged = (chips: readonly Chip[]) => chips.some(chip => chip.change !== 'unchanged') + +/** Whether a row draws a change: its own, or a chip arriving or leaving inside it. */ +export function rowChanged(item: Item | PolicyItem | WorkloadItem | SelectorItem): boolean { + if (isChanged(item.row)) return true + if ('scope' in item && chipsChanged(item.scope)) return true + if ('coveredBy' in item && chipsChanged(item.coveredBy)) return true + return 'chips' in item && chipsChanged(item.chips) +} + +/** Whether a hook's lane draws a change: the hook's own, or any of its probes' or rules'. */ +export const laneChanged = (hook: HookItem) => + rowChanged(hook) || hook.probes.some(probe => rowChanged(probe) || probe.selectors.some(rowChanged)) + +/** + * The IDs of every row and hook that changes, read from the diff's model (`buildModel` with side `diff`): a + * side-by-side pane draws one revision, with no chip arriving or leaving, so folding by its own model would fold + * a workload whose coverage changed in both panes. + */ +export function changedRows(diff: RuntimePolicyModel): ReadonlySet { + const rows = [...diff.deployment, ...diff.policies, ...diff.workloads].filter(rowChanged) + const hooks = diff.categories.flatMap(category => category.hooks).filter(laneChanged) + return new Set([...rows, ...hooks].map(item => item.row.id)) +} + +export type Entry = {type: 'item'; item: T} | {type: 'fold'; key: string; count: number; open: boolean} + +/** + * A list with each run of unchanged items folded into one entry, keyed by its first item, when `fold` is on; a run + * `expanded` names is listed after its fold, open. A run shorter than `minimum` stays listed: a row's fold takes as + * much room as the row, but a hook lane's takes much less. + */ +export function foldUnchanged( + items: readonly T[], + changed: (item: T) => boolean, + fold: boolean, + expanded: ReadonlySet, + minimum: number, +): Entry[] { + if (!fold) return items.map(item => ({type: 'item', item})) + const entries: Entry[] = [] + let run: T[] = [] + const flush = () => { + const [first] = run + if (first && run.length >= minimum) { + const key = first.row.id + const open = expanded.has(key) + entries.push({type: 'fold', key, count: run.length, open}) + if (open) for (const item of run) entries.push({type: 'item', item}) + } else for (const item of run) entries.push({type: 'item', item}) + run = [] + } + for (const item of items) { + if (changed(item)) { + flush() + entries.push({type: 'item', item}) + } else run.push(item) + } + flush() + return entries +} diff --git a/packages/renderers/runtime-policy/src/styles.css b/packages/renderers/runtime-policy/src/styles.css index 26bb1b55..588a96dd 100644 --- a/packages/renderers/runtime-policy/src/styles.css +++ b/packages/renderers/runtime-policy/src/styles.css @@ -88,10 +88,32 @@ --pk-line: var(--border); border-bottom: var(--projections-border-width) solid var(--border); } -.rp-lanes > .rp-lane:has(+ .rp-lane) { +.rp-lanes > .rp-lane:has(+ :is(.rp-lane, .rp-fold)), +.rp-lanes > .rp-fold:has(+ .rp-lane) { --pk-line: var(--divider); border-bottom-color: var(--divider); } +/* + * A fold of unchanged rows or hooks (the `unchanged` control) is a row of its table's grid, its glyph and label at the + * names' inset, the row past the sign column. Open, it stays above the rows it lists as "Hide 3 unchanged hooks". + */ +.rp-table > .rp-fold { + grid-column: sign / end; + display: block; + padding-left: var(--rp-sign); + list-style: none; + background: var(--raised); +} +/* As the kit's table folds: the table's rules are its borders, and the whole row, sign column too, takes the hover. */ +.rp-fold > .pk-fold-button, +.rp-fold > .pk-fold-button:hover { + padding-inline: var(--rp-pad-x); + border-block: 0; + background: none; +} +.rp-table > .rp-fold:has(> .pk-fold-button:hover) { + background: var(--hover); +} .rp-view :is(.rp-table, .rp-lane, .rp-region, .rp-rules) > .pk-region-run[data-change][data-run-end]:not(:last-child) { --pk-run-out-bottom: 0px; border-bottom-color: var(--pk-region-line); diff --git a/packages/renderers/runtime-policy/src/view.tsx b/packages/renderers/runtime-policy/src/view.tsx index 38882e19..db4e55f3 100644 --- a/packages/renderers/runtime-policy/src/view.tsx +++ b/packages/renderers/runtime-policy/src/view.tsx @@ -1,13 +1,87 @@ -import {useMemo} from 'react' +import {useCallback, useEffect, useMemo, useState, type ElementType, type ReactNode} from 'react' import {presentedEmphasis} from '@githubnext/projections-renderer-kit' -import {EmptyDomain, Group, type RendererProps} from '@githubnext/projections-renderer-kit/react' +import {EmptyDomain, Fold, Group, type RendererProps} from '@githubnext/projections-renderer-kit/react' import {buildModel} from './build.js' import type {Item, Side} from './model.js' import type {accepts} from './accepts.js' -import {markOf, runs, statusStrength, type Frame} from './frame.js' +import {markOf, runs, statusStrength, type Frame, type Run} from './frame.js' import {Head} from './row.js' import {Agent, Kernel, Policy, Workload} from './tables.js' import {Lane} from './lanes.js' +import {changedRows, foldUnchanged, unchangedControl, type Entry} from './fold.js' + +/** Folding: whether runs of unchanged rows fold (the `unchanged` control, in the All scope of a comparison), which folds are open, and how one opens or closes. */ +interface Folding { + on: boolean + /** What changes, from the diff whatever the frame shows (`changedRows`). */ + changed: ReadonlySet + expanded: ReadonlySet + toggle: (key: string) => void +} + +const plural = (count: number, [one, many]: readonly [string, string]) => (count === 1 ? one : many) + +/** A fold of unchanged rows or hooks, in its table: as a row of the table's grid, its glyph and label at the names' inset. */ +function UnchangedFold({ + entry, + noun, + folding, + as, +}: { + entry: Entry & {type: 'fold'} + noun: readonly [string, string] + folding: Folding + as: ElementType +}) { + return ( + folding.toggle(entry.key)} + /> + ) +} + +/** A section's rows, each run of unchanged rows folded when folding is on, with the change runs of what's listed. */ +function Rows({ + items, + frame, + folding, + noun, + render, +}: { + items: readonly T[] + frame: Frame + folding: Folding + noun: (run: readonly T[]) => readonly [string, string] + render: (item: T, run: Run | undefined) => ReactNode +}) { + const entries = foldUnchanged(items, item => folding.changed.has(item.row.id), folding.on, folding.expanded, 2) + const marks = runs(entries.map(entry => (entry.type === 'item' ? markOf(entry.item, frame) : undefined))) + return entries.map((entry, index) => { + if (entry.type === 'item') return render(entry.item, marks[index]) + const start = items.findIndex(item => item.row.id === entry.key) + return ( + + ) + }) +} + +const deploymentNoun = (run: readonly Item[]): readonly [string, string] => + run.every(item => item.entity.kind === 'kernel') + ? ['kernel', 'kernels'] + : run.every(item => item.entity.kind === 'agent') + ? ['agent', 'agents'] + : ['row', 'rows'] /** * Runtime security policies: the agent and kernels, the policies and the @@ -27,10 +101,28 @@ import {Lane} from './lanes.js' * connecting words are prose. */ export function RuntimePolicyView(props: RendererProps) { - const {comparing, diff, model} = props + const {comparing, diff, model, declareControls} = props const side: Side = !comparing ? 'after' : diff ? 'diff' : props.progress < 0.5 ? 'before' : 'after' const metadata = props.init.mode === 'comparison' ? props.init.comparison.metadata : undefined const view = useMemo(() => buildModel(model, side, metadata), [model, side, metadata]) + useEffect(() => declareControls(comparing ? [unchangedControl] : []), [comparing, declareControls]) + const [expanded, setExpanded] = useState>(() => new Set()) + const toggle = useCallback( + (key: string) => + setExpanded(previous => { + const next = new Set(previous) + if (!next.delete(key)) next.add(key) + return next + }), + [], + ) + // The Changes scope already leaves unchanged rows out; the control folds the All scope's. + const on = comparing && props.scope === undefined && props.controls.unchanged === 'fold' + const changed = useMemo( + () => (on ? changedRows(side === 'diff' ? view : buildModel(model, 'diff', metadata)) : new Set()), + [on, side, view, model, metadata], + ) + const folding: Folding = {on, changed, expanded, toggle} if (!view.policies.length) { return This revision declares no policies. } @@ -40,52 +132,67 @@ export function RuntimePolicyView(props: RendererProps) { comparing, strength: item => (!comparing ? 0 : diff ? props.emphasis(item.row, item.row.id) : presentedEmphasis(item.row, props.highlighting)), } - // Neighbouring rows marked the same way in the diff join into one run. - const runsOf = (items: readonly Item[]) => runs(items.map(item => markOf(item, frame))) - const deploymentRuns = runsOf(view.deployment), - policyRuns = runsOf(view.policies), - workloadRuns = runsOf(view.workloads) + // Neighbouring rows marked the same way in the diff join into one run (`Rows`). // The content root starts at the top of the frame: the host's summary bar, not a line here, summarizes the policies. return (
{view.deployment.length > 0 && (
    - {view.deployment.map((item, index) => - item.entity.kind === 'agent' ? ( - - ) : ( - - ), - )} + + item.entity.kind === 'agent' ? ( + + ) : ( + + ) + } + />
)}
    - {view.policies.map((policy, index) => ( - - ))} + ['policy', 'policies']} + render={(policy, run) => } + />
{view.workloads.length > 0 && (
    - {view.workloads.map((workload, index) => ( - - ))} + ['workload', 'workloads']} + render={(workload, run) => } + />
)} - {/* A category is one table of hook lanes, each headed by its hook, then its column headers. */} + {/* A category is one table of hook lanes, each headed by its hook, then its column headers. A lane is taller than + its fold, so even one unchanged hook folds. */} {view.categories.map(category => (
- {category.hooks.map(hook => ( - - ))} + {foldUnchanged(category.hooks, hook => folding.changed.has(hook.row.id), folding.on, folding.expanded, 1).map(entry => + entry.type === 'item' ? ( + + ) : ( + + ), + )}
))}