From 32a0cf68018e8c5646e808e7f6edd5e671e13aed Mon Sep 17 00:00:00 2001 From: Bryan Joshua Pedini Date: Fri, 20 Nov 2026 18:43:07 +0100 Subject: [PATCH] Improve audit diffs and gate image releases on main CI --- .gitea/workflows/image.yaml | 57 ++++++++++------ README.md | 3 +- e2e/tests/core.spec.ts | 17 +++++ e2e/tests/fuzzer.spec.ts | 4 +- static/css/app.css | 40 ++++++++++-- static/js/audit.js | 125 ++++++++++++++++++++++++++++++++---- 6 files changed, 207 insertions(+), 39 deletions(-) diff --git a/.gitea/workflows/image.yaml b/.gitea/workflows/image.yaml index f106db9..d2571d8 100644 --- a/.gitea/workflows/image.yaml +++ b/.gitea/workflows/image.yaml @@ -11,6 +11,9 @@ concurrency: jobs: image: runs-on: ubuntu-latest + permissions: + contents: read + actions: read env: CI_IMAGE: coredns-web-ui:ci-${{ github.run_id }}-${{ github.run_attempt }} steps: @@ -25,17 +28,43 @@ jobs: printf '%s\n' "$version" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$' || { echo "::error::tag $GITHUB_REF_NAME is not a semantic version" >&2; exit 1; } echo "version=$version" >> "$GITHUB_OUTPUT" case $version in *-*) echo latest=false ;; *) echo latest=true ;; esac >> "$GITHUB_OUTPUT" - - name: Test + - name: Wait for CI on main + env: + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} run: | set -eu - docker build --pull --target test --output type=cacheonly -f dockerfile . - for database in mysql:5.7 mysql:8.4 mariadb:10.11; do - echo "Running integration tests against $database" - MYSQL_IMAGE="$database" IT_ID="${GITHUB_RUN_ID}" scripts/integration.sh + commit=$(git rev-parse HEAD) + url="${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/actions/workflows/test.yaml/runs" + deadline=$((SECONDS + 1800)) + registration_deadline=$((SECONDS + 120)) + while (( SECONDS < deadline )); do + response=$(curl --fail --silent --show-error --max-time 20 --retry 2 \ + --header "Authorization: Bearer ${GITEA_TOKEN:?missing Gitea job token}" \ + "$url?branch=main&event=push&head_sha=$commit&limit=1") + run=$(jq -c --arg sha "$commit" ' + .workflow_runs | map(select(.head_branch == "main" and .event == "push" and .head_sha == $sha)) | first // empty + ' <<< "$response") + if [ -z "$run" ]; then + if (( SECONDS >= registration_deadline )); then + echo "No push CI run on main for $commit" >&2 + exit 1 + fi + else + status=$(jq -r '.status' <<< "$run") + conclusion=$(jq -r '.conclusion // ""' <<< "$run") + run_url=$(jq -r '.html_url' <<< "$run") + echo "Main CI for $commit: $status ${conclusion} ($run_url)" + case "$status:$conclusion" in + completed:success) exit 0 ;; + requested:|pending:|queued:|waiting:|in_progress:) ;; + *) exit 1 ;; + esac + fi + sleep 15 done - echo "Running integration tests against MariaDB Galera" - IT_GALERA=1 MYSQL_IMAGE=mariadb:10.11.3 IT_ID="${GITHUB_RUN_ID}" scripts/integration.sh - - name: Build and test image + echo "Timed out waiting for main CI for $commit" >&2 + exit 1 + - name: Build image id: build env: VERSION: ${{ steps.version.outputs.version }} @@ -45,18 +74,10 @@ jobs: echo "::error::local image tag already exists: $CI_IMAGE" >&2 exit 1 fi - commit=${GITHUB_SHA:0:12} + commit=$(git rev-parse HEAD) + commit=${commit:0:12} docker build --build-arg APP_VERSION="$VERSION" --build-arg COMMIT_ID="$commit" -f dockerfile -t "$CI_IMAGE" . printf 'image_id=%s\n' "$(docker image inspect --format '{{.Id}}' "$CI_IMAGE")" >> "$GITHUB_OUTPUT" - scripts/test-image.sh "$CI_IMAGE" "$VERSION" "$commit" - scripts/test-e2e.sh "$CI_IMAGE" - - name: Save accessibility screenshots - if: always() - uses: actions/upload-artifact@v3 - with: - name: accessibility-screenshots - path: e2e/reports/**/screenshots/*.png - if-no-files-found: warn - name: Publish image env: GIT_HOST: ${{ vars.GIT_HOST }} diff --git a/README.md b/README.md index 8f0479e..8e2f210 100644 --- a/README.md +++ b/README.md @@ -440,7 +440,8 @@ Optional environment variables: `E2E_RUN_ID` (lowercase letters, digits and hyph Gitea Actions: - `.gitea/workflows/test.yaml` runs on pushes to `main`, every Monday and manually: the `test` stage, the integration tests, the image tests and the E2E suite. -- `.gitea/workflows/image.yaml` runs on semantic version tags (`1.2.3`, `v1.2.3`, with an optional prerelease suffix): the same tests, then it builds the image with the tag as version and the commit as revision, publishes `git.bjphoster.com/source/coredns-web-ui:` and, for tags without a prerelease suffix, `latest`, and removes the local images. The repository needs the Actions variables `GIT_HOST` and `REGISTRY_USER` and the secret `GIT_TOKEN` with package write access. +- Run the tests locally, push to `main`, wait for its CI to pass, then create and push the release tag. `.gitea/workflows/image.yaml` accepts semantic version tags (`1.2.3`, `v1.2.3`, with an optional prerelease suffix). It requires a successful push run of `test.yaml` on `main` for the exact tagged commit. It waits up to 30 minutes for CI and allows two minutes for Gitea to register the run. A failed, cancelled or missing run blocks the build and publish. +- Once CI passes, the tag workflow builds the image with the tag as version and the commit as revision, publishes `git.bjphoster.com/source/coredns-web-ui:` and, for tags without a prerelease suffix, `latest`, and removes the local images. The built-in job token needs Actions read access. Publishing uses the Actions variables `GIT_HOST` and `REGISTRY_USER` and the secret `GIT_TOKEN` with package write access. ## Deployment diff --git a/e2e/tests/core.spec.ts b/e2e/tests/core.spec.ts index 17cd0b1..4de0f82 100644 --- a/e2e/tests/core.spec.ts +++ b/e2e/tests/core.spec.ts @@ -1076,6 +1076,23 @@ test.describe('core flow', () => { const diff = adminUi.page.locator('#audit-body tr.detail-row:not([hidden]) table.diff'); await expect(diff).toBeVisible(); await expect(diff.locator('tr.diff-changed').first()).toBeVisible(); + + const soaEntries = await adminApi.get('/audit', { query: { zone, operation: 'soa_update', limit: 1 } }); + const soaEntry = soaEntries.json.entries[0]; + expect(soaEntry.before).toMatchObject({ record_type: 'SOA', ttl: 3600, content: expect.any(String) }); + expect(soaEntry.after).toMatchObject({ record_type: 'SOA', ttl: 1800, content: expect.any(String) }); + expect(JSON.parse(soaEntry.after.content)).toMatchObject({ refresh: 7200, retry: 900, minttl: 600 }); + await adminUi.filterAudit({ zone, operation: 'soa_update' }); + await toggle.click(); + const type = diff.getByRole('rowheader', { name: 'type', exact: true }); + await expect(type).toBeVisible(); + await expect(diff.getByRole('rowheader', { name: 'record_type', exact: true })).toHaveCount(0); + const content = diff.locator('tr.diff-content-row'); + await expect(content.getByRole('rowheader', { name: 'content', exact: true })).toHaveCSS('white-space', 'nowrap'); + await expect(content.getByRole('group', { name: 'Before content' })).toHaveCSS('white-space', 'pre'); + await expect(content.locator('.diff-before').filter({ hasText: 'Refresh: 3600' })).toHaveText('− Refresh: 3600'); + await expect(content.locator('.diff-after').filter({ hasText: 'Refresh: 7200' })).toHaveText('+ Refresh: 7200'); + await expect(content.locator('.diff-after').filter({ hasText: 'Primary name server' })).toHaveCount(0); await adminUi.filterAudit({ zone: '', operation: '', outcome: 'error' }); for (const r of await adminUi.auditRows()) expect(Number(r.status.slice(0, 3))).toBeGreaterThanOrEqual(400); diff --git a/e2e/tests/fuzzer.spec.ts b/e2e/tests/fuzzer.spec.ts index 3c1a9bb..5c322e8 100644 --- a/e2e/tests/fuzzer.spec.ts +++ b/e2e/tests/fuzzer.spec.ts @@ -207,7 +207,9 @@ test('script payloads render as plain text in the audit diff and the import prev await expect(diff).toBeVisible(); const row = diff.locator('tbody tr').filter({ has: ui.page.locator('th', { hasText: new RegExp(`^(record ${id}\\.)?content$`) }) }); await expect(row).toHaveCount(1); - await expect(row.locator('td').nth(side === 'Before' ? 0 : 1)).toHaveText(JSON.stringify(content).replace(/\s+/g, ' ')); + const marker = side === 'Before' ? '−' : '+'; + const cell = row.getByRole('group', { name: side + ' content' }); + await expect(cell).toHaveText(`${marker} Text: ${JSON.parse(content).text}`); await expect(ui.page.locator('#app script, #app img')).toHaveCount(0); }; const pwned = () => ui.page.evaluate(() => (window as unknown as { __pwned?: number }).__pwned); diff --git a/static/css/app.css b/static/css/app.css index 0e0b082..caac845 100644 --- a/static/css/app.css +++ b/static/css/app.css @@ -508,20 +508,48 @@ input[type="radio"] { color: var(--muted); } -.detail-row td { +.detail-row > td { background: var(--stripe); } -.diff-changed { - background: var(--warn-bg); +.diff { + min-width: 36rem; + table-layout: fixed; } -.diff-added { - background: var(--ok-bg); +.diff th:first-child { + width: 13rem; } -.diff-removed { +.diff-content-row th { + white-space: nowrap; +} + +.diff-content { + display: flex; + gap: 0.75rem; + overflow-x: auto; + white-space: pre; +} + +.diff-value { + display: inline-block; + overflow-wrap: anywhere; + padding: 0 0.25rem; +} + +.diff-content .diff-value { + flex: none; +} + +.diff-before { background: var(--danger-bg); + color: var(--danger); +} + +.diff-after { + background: var(--ok-bg); + color: var(--ok); } .diff-same { diff --git a/static/js/audit.js b/static/js/audit.js index 4e9b6fb..164c016 100644 --- a/static/js/audit.js +++ b/static/js/audit.js @@ -2,8 +2,26 @@ // Copyright (C) 2026 Bryan Joshua Pedini import { $, api, busy, formatTime, h, handleError, icon } from "./common.js"; +import { FIELD_SPECS } from "./records.js"; const state = { nextBeforeId: null, count: 0, filters: {}, counter: 0 }; +const SOA_FIELDS = [ + { key: "ns", label: "Primary name server" }, + { key: "MBox", label: "Hostmaster" }, + { key: "serial", label: "Serial" }, + { key: "refresh", label: "Refresh" }, + { key: "retry", label: "Retry" }, + { key: "expire", label: "Expire" }, + { key: "minttl", label: "Minimum TTL" }, +]; + +function isObject(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function isRecord(value) { + return isObject(value) && Object.hasOwn(value, "id") && typeof value.record_type === "string"; +} function flatten(value, prefix, out) { if (Array.isArray(value)) { @@ -17,12 +35,16 @@ function flatten(value, prefix, out) { } function show(value) { - return value === undefined ? "(none)" : JSON.stringify(value); + if (value === undefined) return "—"; + if (typeof value === "string" && value !== "") { + return value.replaceAll("\r", "\\r").replaceAll("\n", "\\n").replaceAll("\t", "\\t"); + } + return JSON.stringify(value); } function itemLabel(item, index) { - if (item !== null && typeof item === "object" && !Array.isArray(item)) { - if ("record_type" in item && "id" in item) return "record " + item.id; + if (isRecord(item)) return "record " + item.id; + if (isObject(item)) { if ("zone" in item && "username" in item && !("id" in item)) return "delegation " + item.zone + " " + item.username; if ("username" in item && "id" in item) return "user " + item.id; } @@ -36,10 +58,8 @@ function keyed(value) { return out; } -function diffValues(before, after, prefix) { - const left = before === undefined ? new Map() : flatten(before, prefix, new Map()); - const right = after === undefined ? new Map() : flatten(after, prefix, new Map()); - const paths = [...new Set([...left.keys(), ...right.keys()])].filter((path) => path !== ""); +function compareFields(left, right) { + const paths = [...new Set([...left.keys(), ...right.keys()])]; return paths.map((path) => { const old = left.get(path); const now = right.get(path); @@ -47,13 +67,74 @@ function diffValues(before, after, prefix) { if (!left.has(path)) kind = "added"; else if (!right.has(path)) kind = "removed"; else if (JSON.stringify(old) !== JSON.stringify(now)) kind = "changed"; - return { path, kind, before: left.has(path) ? old : undefined, after: right.has(path) ? now : undefined }; + return { path, kind, before: old, after: now }; }); } +function recordFields(value) { + if (!isRecord(value)) return value; + const { record_type, content, ...fields } = value; + return { ...fields, type: record_type }; +} + +function contentFields(record) { + const fields = new Map(); + const labels = new Map(); + if (!isRecord(record) || !Object.hasOwn(record, "content")) return { fields, labels }; + let content = record.content; + if (typeof content === "string") { + try { + content = JSON.parse(content); + } catch { + // Unparseable records keep their original text in the audit. + } + } + if (!isObject(content) || Object.keys(content).length === 0) { + fields.set("", content); + return { fields, labels }; + } + const type = record.record_type.toUpperCase(); + if (type === "SOA" && !Object.hasOwn(content, "MBox") && Object.hasOwn(content, "mbox")) { + const { mbox, ...rest } = content; + content = { ...rest, MBox: mbox }; + } + const specs = type === "SOA" ? SOA_FIELDS : Object.hasOwn(FIELD_SPECS, type) ? FIELD_SPECS[type] : []; + for (const { key, label } of specs) { + labels.set(key, label); + if (Object.hasOwn(content, key)) fields.set(key, content[key]); + } + for (const key of Object.keys(content).sort()) { + if (!fields.has(key)) fields.set(key, content[key]); + } + return { fields, labels }; +} + +function diffValues(before, after, prefix) { + const left = before == null ? new Map() : flatten(recordFields(before), prefix, new Map()); + const right = after == null ? new Map() : flatten(recordFields(after), prefix, new Map()); + const rows = compareFields(left, right).filter(({ path }) => path !== ""); + if (isRecord(before) || isRecord(after)) { + const oldContent = contentFields(before); + const newContent = contentFields(after); + const fields = compareFields(oldContent.fields, newContent.fields); + if (fields.length !== 0) { + // Put changed fields first so they are visible before horizontal scrolling. + fields.sort((a, b) => Number(a.kind === "same") - Number(b.kind === "same")); + rows.push({ + path: prefix ? prefix + ".content" : "content", + kind: fields[0].kind === "same" ? "same" : "changed", + fields, + beforeLabels: oldContent.labels, + afterLabels: newContent.labels, + }); + } + } + return rows; +} + export function diffRows(before, after) { if (!Array.isArray(before) && !Array.isArray(after)) { - return diffValues(before === undefined ? null : before, after === undefined ? null : after, ""); + return diffValues(before, after, ""); } const left = keyed(before); const right = keyed(after); @@ -61,15 +142,33 @@ export function diffRows(before, after) { return labels.flatMap((label) => diffValues(left.has(label) ? left.get(label) : undefined, right.has(label) ? right.get(label) : undefined, label)); } +function diffValue(value, kind, side, label = "") { + const changed = value !== undefined && kind !== "same"; + const color = changed ? " diff-" + side : ""; + return h("code", { class: "diff-value" + color }, + changed ? h("span", { "aria-hidden": "true", text: side === "before" ? "− " : "+ " }) : null, + label ? h("strong", { text: label + ": " }) : null, + show(value)); +} + +function diffCell(row, side) { + if (!row.fields) return h("td", null, diffValue(row[side], row.kind, side)); + const labels = side === "before" ? row.beforeLabels : row.afterLabels; + const parts = row.fields.filter((field) => field[side] !== undefined); + return h("td", null, + h("div", { class: "diff-content", tabindex: "0", role: "group", "aria-label": side === "before" ? "Before content" : "After content" }, + parts.length ? parts.map((field) => diffValue(field[side], field.kind, side, labels.get(field.path) ?? field.path)) : "—")); +} + function diffTable(entry) { const rows = diffRows(entry.before, entry.after); if (rows.length === 0) return h("p", { class: "muted", text: "No field-level data." }); - return h("table", { class: "table diff" }, + return h("div", { class: "table-wrap" }, h("table", { class: "table diff" }, h("thead", null, h("tr", null, h("th", { scope: "col", text: "Field" }), h("th", { scope: "col", text: "Before" }), h("th", { scope: "col", text: "After" }))), - h("tbody", null, rows.map((row) => h("tr", { class: "diff-" + row.kind }, + h("tbody", null, rows.map((row) => h("tr", { class: "diff-" + row.kind + (row.fields ? " diff-content-row" : "") }, h("th", { scope: "row", class: "mono", text: row.path }), - h("td", { class: "mono", text: show(row.before) }), - h("td", { class: "mono", text: show(row.after) }))))); + diffCell(row, "before"), + diffCell(row, "after")))))); } function entryRows(entry) {