diff --git a/.gitea/workflows/image.yaml b/.gitea/workflows/image.yaml index 5494f3d..4ac7a22 100644 --- a/.gitea/workflows/image.yaml +++ b/.gitea/workflows/image.yaml @@ -11,6 +11,8 @@ concurrency: jobs: image: runs-on: ubuntu-latest + env: + CI_IMAGE: coredns-web-ui:ci-${{ github.run_id }}-${{ github.run_attempt }} steps: - uses: actions/checkout@v4 with: @@ -26,17 +28,23 @@ jobs: - name: Test run: | set -eu - docker build --pull --target test -f dockerfile . + docker build --pull --target test --output type=cacheonly -f dockerfile . IT_ID="${GITHUB_RUN_ID}" scripts/integration.sh - name: Build and test image + id: build env: VERSION: ${{ steps.version.outputs.version }} run: | set -eu + if docker image inspect "$CI_IMAGE" >/dev/null 2>&1; then + echo "::error::local image tag already exists: $CI_IMAGE" >&2 + exit 1 + fi commit=${GITHUB_SHA:0:12} - docker build --build-arg APP_VERSION="$VERSION" --build-arg COMMIT_ID="$commit" -f dockerfile -t coredns-web-ui:ci . - scripts/test-image.sh coredns-web-ui:ci "$VERSION" "$commit" - scripts/test-e2e.sh coredns-web-ui:ci + 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: Publish image env: GIT_HOST: ${{ vars.GIT_HOST }} @@ -50,16 +58,25 @@ jobs: image="${GIT_HOST}/${GITHUB_REPOSITORY}" printf '%s' "$GIT_TOKEN" | docker login "$GIT_HOST" --username "$REGISTRY_USER" --password-stdin trap 'docker logout "$GIT_HOST" >/dev/null 2>&1 || true' EXIT - docker tag coredns-web-ui:ci "${image}:${VERSION}" - docker push "${image}:${VERSION}" + push_tag() ( + destination="${image}:$1" + previous=$(docker image inspect --format '{{.Id}}' "$destination" 2>/dev/null || true) + current=$(docker image inspect --format '{{.Id}}' "$CI_IMAGE") + if [ "$previous" != "$current" ]; then + docker tag "$CI_IMAGE" "$destination" + trap 'if [ -n "$previous" ]; then docker tag "$previous" "$destination"; else docker image rm "$destination" >/dev/null; fi' EXIT + fi + docker push "$destination" + ) + push_tag "$VERSION" if [ "$LATEST" = true ]; then - docker tag coredns-web-ui:ci "${image}:latest" - docker push "${image}:latest" + push_tag latest fi - name: Remove local images - if: always() + if: always() && steps.build.outputs.image_id != '' env: - GIT_HOST: ${{ vars.GIT_HOST }} - VERSION: ${{ steps.version.outputs.version }} + IMAGE_ID: ${{ steps.build.outputs.image_id }} run: | - docker image rm -f coredns-web-ui:ci "${GIT_HOST}/${GITHUB_REPOSITORY}:${VERSION}" "${GIT_HOST}/${GITHUB_REPOSITORY}:latest" >/dev/null 2>&1 || true + if [ "$(docker image inspect --format '{{.Id}}' "$CI_IMAGE" 2>/dev/null)" = "$IMAGE_ID" ]; then + docker image rm "$CI_IMAGE" >/dev/null + fi diff --git a/.gitea/workflows/test.yaml b/.gitea/workflows/test.yaml index 0246741..dd6b641 100644 --- a/.gitea/workflows/test.yaml +++ b/.gitea/workflows/test.yaml @@ -21,7 +21,7 @@ jobs: - name: Format, vet, staticcheck and race tests run: | set -eu - docker build --pull --target test -f dockerfile . + docker build --pull --target test --output type=cacheonly -f dockerfile . - name: Integration tests against MySQL run: | set -eu @@ -31,8 +31,12 @@ jobs: set -eu commit=${GITHUB_SHA:0:12} version="0.0.0-main.${commit}" - image="coredns-web-ui:test-${GITHUB_RUN_ID}" - trap 'docker image rm -f "$image" >/dev/null 2>&1 || true' EXIT + image="coredns-web-ui:test-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT:-1}" + if docker image inspect "$image" >/dev/null 2>&1; then + echo "::error::local image tag already exists: $image" >&2 + exit 1 + fi docker build --build-arg APP_VERSION="$version" --build-arg COMMIT_ID="$commit" -f dockerfile -t "$image" . + trap 'docker image rm "$image" >/dev/null' EXIT scripts/test-image.sh "$image" "$version" "$commit" scripts/test-e2e.sh "$image" diff --git a/PLAN.md b/PLAN.md index af92ce6..06e2c68 100644 --- a/PLAN.md +++ b/PLAN.md @@ -270,7 +270,7 @@ CREATE TABLE `coredns_webui_audit` ( `status` SMALLINT NULL, `error` VARCHAR(255) NULL, `zone` VARCHAR(255) NULL, - `record_id` INT NULL, + `record_id` BIGINT NULL, `target_user_id` INT NULL, `before_value` JSON NULL, `after_value` JSON NULL, @@ -284,7 +284,7 @@ CREATE TABLE `coredns_webui_audit` ( ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci; ``` -All times are UTC. Rows of `webui_users` are never deleted (section 8), so, as with the tokens referenced by the audit table of `dpsapi`, the foreign keys from sessions, delegations and audit rows always resolve. Audit rows have no foreign key to the records table, so deleted records keep their history. +All times are UTC. Rows of `webui_users` are never deleted (section 8), so, as with the tokens referenced by the audit table of `dpsapi`, the foreign keys from sessions, delegations and audit rows always resolve. Audit rows have no foreign key to the records table, so deleted records keep their history. The audit `record_id` column holds the full ID range of an `INT UNSIGNED` records table. ### Grants @@ -527,7 +527,7 @@ All under `/api/v1`, session required (`401` JSON otherwise), request bodies `ap | `DELETE` | `/users/{username}` | admin | `user_delete` | body `{"confirm": ""}`, sets `deleted_at`, ends the user's sessions | | `GET` | `/audit` | session | `audit_read` | visible rows; `zone`, `actor`, `operation`, `kind` (`read` or `change`), `outcome` (`success` for statuses below `400`, `error` otherwise), `before_id`, `limit` (1 to 200, default 50) | -`{zone}` is the zone name with or without the trailing dot. A record id that does not belong to the zone in the path is `404`. Changes to a deleted user are `404`. `DELETE /zones/{zone}/users/{username}` also revokes delegations of zones that no longer exist. +`{zone}` is the zone name with or without the trailing dot. Record IDs range from 1 to 4294967295. A record id that does not belong to the zone in the path is `404`. Changes to a deleted user are `404`. `DELETE /zones/{zone}/users/{username}` also revokes delegations of zones that no longer exist. Record representation: diff --git a/README.md b/README.md index 9241a7b..9bc25df 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,8 @@ After field validation every record is converted to the `miekg/dns` RR the plugi Errors refuse a write with HTTP `422`: a zone has exactly one SOA, at the apex, which cannot be created twice or deleted on its own; the last apex NS cannot be deleted; a name with a CNAME has no other record and only one CNAME; no two records share name, type and canonical content. Warnings let the write through and are returned with the response: records of one name and type with different TTLs, `NS`, `MX` or `SRV` targets that are CNAME owners or have no address record in the zone, names below a zone cut, `TXT` text longer than 255 bytes (served as several strings). +The zone page can repair an existing broken SOA set by editing a misplaced SOA or deleting an extra SOA. If a conflicting CNAME blocks the repair, delete that CNAME first. To restore a missing SOA, use a merge import containing an apex SOA. + The zone check (API, UI and `check` command) reports every row the plugin cannot serve correctly. | Severity | Codes | @@ -133,7 +135,7 @@ Migrations are embedded SQL files (`migrations/001_initial.sql`, ...) applied in | `webui_zone_delegations` | `zone`, `user_id`, `created_at`, `created_by` | | `webui_audit` | the audit rows (see [Audit](#audit)) | -All times are UTC. Rows of the users table are never deleted, so the foreign keys from sessions, delegations and audit rows always resolve. Audit rows have no foreign key to the records table, so deleted records keep their history. +All times are UTC. Rows of the users table are never deleted, so the foreign keys from sessions, delegations and audit rows always resolve. Audit rows have no foreign key to the records table, so deleted records keep their history. The audit `record_id` column is `BIGINT` to preserve IDs across the full range of an `INT UNSIGNED` records table. ## Configuration diff --git a/apimatrix_cases_test.go b/apimatrix_cases_test.go index ad261c9..1f7eb79 100644 --- a/apimatrix_cases_test.go +++ b/apimatrix_cases_test.go @@ -307,7 +307,7 @@ func matrixRecordCases() []matrixCase { body: `{"name":"www","type":"A","ttl":300,"data":{"ip":"192.0.2.1"}}`, ifMatch: 3, status: 200, zone: mxZone, record: 3, check: mxUnchanged}, {name: "invalid id", op: opRecordUpdate, method: "PUT", path: "/zones/example.org./records/x", persona: "admin", body: mxUpdateBody, ifMatch: 3, status: 400, msg: "invalid record id", zone: mxZone, check: mxUnchanged}, - {name: "id out of range", op: opRecordUpdate, method: "PUT", path: "/zones/example.org./records/2147483648", persona: "admin", body: mxUpdateBody, ifMatch: 3, + {name: "id out of range", op: opRecordUpdate, method: "PUT", path: "/zones/example.org./records/4294967296", persona: "admin", body: mxUpdateBody, ifMatch: 3, status: 400, msg: "invalid record id", zone: mxZone, check: mxUnchanged}, {name: "malformed", op: opRecordUpdate, method: "PUT", path: "/zones/example.org./records/3", persona: "admin", body: `{"name"`, ifMatch: 3, status: 400, msg: "malformed JSON", zone: mxZone, record: 3, check: mxUnchanged}, diff --git a/delegation_store.go b/delegation_store.go index d2402f1..924ed2a 100644 --- a/delegation_store.go +++ b/delegation_store.go @@ -75,7 +75,7 @@ func (s delegationStore) ZoneUsers(ctx context.Context, zone string) ([]userRow, func (s delegationStore) UserZones(ctx context.Context, userID int64) ([]userZone, error) { defer traceStore(ctx, "delegationStore.UserZones")() rows, err := s.q.QueryContext(ctx, - s.t.sql("SELECT d.`zone`, d.`created_at`, EXISTS (SELECT 1 FROM {records} r WHERE r.`zone` = d.`zone`) "+ + s.t.sql("SELECT d.`zone`, d.`created_at`, EXISTS (SELECT 1 FROM {records} r WHERE "+recordZoneKey("r.`zone`")+" = CAST(d.`zone` AS BINARY)) "+ "FROM {delegations} d WHERE d.`user_id` = ? ORDER BY d.`zone`"), userID) if err != nil { return nil, fmt.Errorf("user zones: %w", err) diff --git a/e2e/harness/decisions.ts b/e2e/harness/decisions.ts index d61f98e..99eb354 100644 --- a/e2e/harness/decisions.ts +++ b/e2e/harness/decisions.ts @@ -13,11 +13,11 @@ export function expectRecordDeleteBody(json: unknown, what: string): void { } export function bulkDeleteBody(deleted: number): Record { - return expect.objectContaining({ deleted }); + return { deleted, warnings: expect.any(Array) }; } export function importApplyBody(added: number, updated: number, deleted: number): Record { - return expect.objectContaining({ added, updated, deleted }); + return { added, updated, deleted, warnings: expect.any(Array) }; } export function expectZoneCreateWarnings(json: unknown): void { diff --git a/e2e/harness/docker.ts b/e2e/harness/docker.ts index 59c2538..26fbf4f 100644 --- a/e2e/harness/docker.ts +++ b/e2e/harness/docker.ts @@ -1,7 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-or-later // Copyright (C) 2026 Bryan Joshua Pedini -import { COMPOSE_FILE, containerName, project, RESOURCE_PREFIX, RUN_LABEL } from './env'; +import { COMPOSE_FILE, containerName, project, RUN_LABEL } from './env'; import { run, runOk, type ProcOptions, type ProcResult } from './proc'; export function docker(args: readonly string[], opts: ProcOptions = {}): Promise { @@ -34,27 +34,11 @@ export interface ProjectResources { } export async function projectResources(): Promise { - const p = project(); - const byLabel = await dockerOk(['ps', '-a', '--filter', `label=${RUN_LABEL}=${p}`, '--format', '{{.Names}}']); - const byName = await dockerOk(['ps', '-a', '--filter', `name=^${p}`, '--format', '{{.Names}}']); - const byCompose = await dockerOk(['ps', '-a', '--filter', `label=com.docker.compose.project=${p}`, '--format', '{{.Names}}']); - const self = new Set([runnerContainer()]); - const containers = [...new Set([...lines(byLabel.stdout), ...lines(byName.stdout), ...lines(byCompose.stdout)])].filter( - (n) => !self.has(n) && !/^.+-runner-run-[0-9a-f]+$/.test(n), - ); - const volumes = new Set(); - for (const filter of [`label=${RUN_LABEL}=${p}`, `label=com.docker.compose.project=${p}`, `name=${p}`]) { - const r = await dockerOk(['volume', 'ls', '-q', '--filter', filter]); - for (const v of lines(r.stdout)) volumes.add(v); - } - const networks = new Set(); - for (const filter of [`label=${RUN_LABEL}=${p}`, `name=${p}`]) { - const r = await dockerOk(['network', 'ls', '--format', '{{.Name}}', '--filter', filter]); - for (const n of lines(r.stdout)) networks.add(n); - } - return { containers, volumes: [...volumes], networks: [...networks] }; -} - -export function isOwnedName(name: string): boolean { - return name.startsWith(RESOURCE_PREFIX); + const filter = `label=${RUN_LABEL}=${project()}`; + const [containers, volumes, networks] = await Promise.all([ + dockerOk(['ps', '-a', '--filter', filter, '--format', '{{.Names}}']), + dockerOk(['volume', 'ls', '-q', '--filter', filter]), + dockerOk(['network', 'ls', '--filter', filter, '--format', '{{.Name}}']), + ]); + return { containers: lines(containers.stdout), volumes: lines(volumes.stdout), networks: lines(networks.stdout) }; } diff --git a/e2e/harness/ledger.ts b/e2e/harness/ledger.ts index c837910..9cb03c3 100644 --- a/e2e/harness/ledger.ts +++ b/e2e/harness/ledger.ts @@ -108,7 +108,10 @@ export function matchRoute(method: string, apiPath: string): RouteMatch | null { const v = groups[i]; if (v === null || v === undefined) return; if (t === 'zone') out.zone = normalizeZoneParam(v); - if (t === 'record') out.recordId = /^[0-9]{1,9}$/.test(v) ? Number(v) : null; + if (t === 'record' && /^\+?[0-9]+$/.test(v)) { + const id = Number(v); + if (id > 0 && id <= 0xffffffff) out.recordId = id; + } if (t === 'user' || t === 'delegation') out.targetUser = v; }); return out; diff --git a/e2e/tests/core.spec.ts b/e2e/tests/core.spec.ts index 1a85b2c..e96c13e 100644 --- a/e2e/tests/core.spec.ts +++ b/e2e/tests/core.spec.ts @@ -9,7 +9,7 @@ import { waitForZone, waitForZoneGone } from '../harness/dig'; import { runnerAddress, SESSION_COOKIE } from '../harness/env'; import { bulkDeleteBody, expectCheckErrorRowsCarryRaw, expectZoneCreateWarnings, importApplyBody, UNKNOWN_API_OPERATION, ZONE_CREATE_DELEGATIONS_IN } from '../harness/decisions'; import { READ_OPERATIONS } from '../harness/ledger'; -import type { AuditRow, RecordRow } from '../harness/mysql'; +import type { AuditRow } from '../harness/mysql'; import { newZoneSerial, uiValue, utcDay } from '../harness/records'; import type { RecordInput, Ui } from '../harness/ui'; import { expectServed } from '../harness/served'; @@ -297,26 +297,31 @@ test.describe('core flow', () => { test('5a. bulk deletion removes the selected records in one transaction', async ({ world }) => { await adminUi.openZone(zone); const recs: Rec[] = [1, 2, 3].map((i) => ({ name: `bulk${i}`, type: 'TXT', ttl: 300, data: { text: `bulk ${i}` } })); + const remaining: Rec = { name: 'bulk4', type: 'TXT', ttl: 300, data: { text: 'x'.repeat(256) } }; for (const r of recs) { const res = await adminApi.post(`${zp(zone)}/records`, { name: r.name, type: r.type, ttl: r.ttl, data: r.data }); expect(res.status, res.text).toBe(201); } + const added = await adminApi.post(`${zp(zone)}/records`, remaining); + expect(added.status, added.text).toBe(201); + const survivor = added.json.record; await adminUi.openZone(zone); const rows = await Promise.all(recs.map((r) => storedRow(world, zone, r))); const change = await begin(world, zone); const mark = await world.db.auditMaxId(); const res = await adminUi.bulkDelete(recs.map((r) => ({ name: r.name, type: r.type })), { expectStatus: 200 }); expect(res.json).toEqual(bulkDeleteBody(3)); + expect(res.json.warnings).toContainEqual(expect.objectContaining({ code: 'txt_split' })); + await adminUi.expectToast('TXT is served in strings of at most 255 bytes'); await expectBumped(world, zone, change, 'bulk delete'); for (const r of recs) await threeWayGone(world, adminUi, zone, r, null, `bulk deleted ${r.name}`); const audit = findAudit(await auditSince(world, mark), 'record_bulk_delete', 200); expect(audit.zone).toBe(zone); await expectAuditChange(world, zone, audit, change, 'bulk delete'); - const survivor = await adminApi.post(`${zp(zone)}/records`, { name: 'bulk4', type: 'TXT', ttl: 300, data: { text: 'bulk 4' } }); - const stale = await adminApi.post(`${zp(zone)}/records/delete`, { records: [{ id: survivor.json.record.id, etag: survivor.json.record.etag }, { id: rows[0].id, etag: '"0000"' }] }); + const stale = await adminApi.post(`${zp(zone)}/records/delete`, { records: [{ id: survivor.id, etag: survivor.etag }, { id: rows[0].id, etag: '"0000"' }] }); expect(stale.status, 'a stale or missing ETag fails the whole bulk delete').toBe(412); - await storedRow(world, zone, { name: 'bulk4', type: 'TXT', ttl: 300, data: { text: 'bulk 4' } }); - const done = await adminApi.post(`${zp(zone)}/records/delete`, { records: [{ id: survivor.json.record.id, etag: survivor.json.record.etag }] }); + await storedRow(world, zone, remaining); + const done = await adminApi.post(`${zp(zone)}/records/delete`, { records: [{ id: survivor.id, etag: survivor.etag }] }); expect(done.status).toBe(200); }); @@ -373,7 +378,9 @@ test.describe('core flow', () => { const applied = await adminUi.importApply(); expect(applied.status).toBe(200); expect(applied.json).toEqual(importApplyBody(3, 1, 0)); + expect(applied.json.warnings).toContainEqual(expect.objectContaining({ message: 'TXT strings were joined and the plugin will re-split them at 255 bytes' })); await expect(adminUi.page).toHaveURL(new RegExp(`/zones/${zone.replace(/\./g, '\\.')}$`)); + await adminUi.expectToast('TXT strings were joined and the plugin will re-split them at 255 bytes'); await expectBumped(world, zone, change, 'merge import'); const imported: Rec[] = [ { name: 'imp1', type: 'A', ttl: 600, data: { ip: '192.0.2.40' } }, @@ -426,7 +433,9 @@ test.describe('core flow', () => { expect(created.status, created.text).toBe(201); await adminApi.post(`${zp(zoneC)}/records`, { name: 'ns1', type: 'A', ttl: 3600, data: { ip: '192.0.2.1' } }); await waitForZone(world.g, zoneC, { recorder: world.recorder }); - const soa = (await world.db.records(zoneC)).find((r) => r.record_type === 'SOA') as RecordRow; + const original = await begin(world, zoneC); + const soa = original.rows.find((r) => r.record_type === 'SOA')!; + const duplicateSOA = JSON.stringify({ ...JSON.parse(soa.content!), ns: 'duplicate.example.net.' }); const id = async (name: string, type: string, ttl: number | null, content: string | null, z = zoneC) => world.db.insertRaw({ zone: z, name, ttl, content, record_type: type }); const broken: Record = { ttl_null: await id('tnull', 'A', null, '{"ip":"192.0.2.60"}'), @@ -438,12 +447,12 @@ test.describe('core flow', () => { name_not_fqdn: await id('nfq', 'CNAME', 3600, '{"host":"target.example.net"}'), mx_priority_key: await id('mxp', 'MX', 3600, '{"host":"mail.example.net.","priority":10}'), soa_not_apex: await id('soasub', 'SOA', 3600, soa.content), - soa_multiple: await id('', 'SOA', 3600, soa.content), + soa_multiple: await id('', 'SOA', 3600, duplicateSOA), cname_apex: await id('', 'CNAME', 3600, '{"host":"target.example.net."}'), cname_conflict: await id('both', 'CNAME', 3600, '{"host":"target.example.net."}'), pack_failed: await id('cut', 'NS', 3600, '{"host":"ns.example.net"}'), }; - await id('both', 'A', 3600, '{"ip":"192.0.2.63"}'); + const conflictAddress = await id('both', 'A', 3600, '{"ip":"192.0.2.63"}'); const codes = Object.keys(broken); const brokenRows = await world.db.records(zoneC); for (const [name, type, rcode] of [ @@ -464,6 +473,8 @@ test.describe('core flow', () => { zone_case: await id('upper', 'A', 3600, '{"ip":"192.0.2.65"}', upper), }; await id('', 'NS', 3600, `{"host":"ns1.${nosoa}"}`, nosoa); + await id('ns1', 'A', 3600, '{"ip":"192.0.2.67"}', nosoa); + const noSOARows = await world.db.records(nosoa); const check = await adminApi.get(`${zp(zoneC)}/check`); expect(check.status).toBe(200); @@ -508,15 +519,31 @@ test.describe('core flow', () => { expect(zonesTable.find((z) => z.zone === zoneC)?.problems).toMatch(/\d+ errors?/); expect(zonesTable.find((z) => z.zone === zone)?.problems).not.toMatch(/error/); - await world.db.exec(`DELETE FROM ${world.db.t.records} WHERE id IN (?, ?)`, [broken.soa_not_apex, broken.soa_multiple]); - await world.db.deleteZoneRaw(nodot); - await world.db.deleteZoneRaw(upper); - await world.db.deleteZoneRaw(nosoa); await adminUi.openZone(zoneC); + await adminUi.deleteRecord({ name: 'soasub', type: 'SOA' }, { expectStatus: 200 }); + expect(await world.db.recordById(broken.soa_not_apex)).toBeUndefined(); + await adminUi.openZone(zoneC); + expect((await adminUi.problems()).map((p) => p.code)).toEqual(expect.arrayContaining(['soa_multiple', 'cname_apex', 'cname_conflict'])); + await adminUi.deleteRecord({ name: '@', type: 'SOA', value: duplicateSOA }, { expectStatus: 200 }); + expect(await world.db.recordById(broken.soa_multiple)).toBeUndefined(); + const soaSerial = await expectBumped(world, zoneC, original, 'repair leaves one managed SOA'); + expect((await world.db.records(zoneC)).filter((row) => row.record_type === 'SOA')).toEqual([ + { ...soa, content: JSON.stringify({ ...JSON.parse(soa.content!), serial: soaSerial }) }, + ]); + await adminUi.openZone(zoneC); + await adminUi.expectRow({ name: '@', type: 'SOA' }); + const beforeCNAMERepair = await begin(world, zoneC); await adminUi.bulkDelete([{ name: 'both', type: 'CNAME' }, { name: '@', type: 'CNAME' }], { expectStatus: 200 }); + expect(await world.db.recordById(broken.cname_apex)).toBeUndefined(); + expect(await world.db.recordById(broken.cname_conflict)).toBeUndefined(); + await adminUi.expectNoRow({ name: 'both', type: 'CNAME' }); + await adminUi.expectNoRow({ name: '@', type: 'CNAME' }); + const preservedAddress = await threeWay(world, adminUi, zoneC, { name: 'both', type: 'A', ttl: 3600, data: { ip: '192.0.2.63' } }, beforeCNAMERepair, 'repair conflicting CNAMEs'); + expect(preservedAddress.id).toBe(conflictAddress); + const listed = (await adminApi.get(`${zp(zoneC)}/records`)).json.records as Array<{ id: number; name: string; type: string; data: unknown; raw: string | null; problems: Array<{ severity: string }> }>; for (const r of listed.filter((x) => x.problems.length > 0 && x.data === null)) expect(r.raw === null || typeof r.raw === 'string').toBe(true); - const storedContent = new Map((await world.db.records(zoneC)).map((r) => [r.id, r.content])); + const storedContent = new Map((await world.db.records()).map((r) => [r.id, r.content])); expectCheckErrorRowsCarryRaw(listed, (i) => storedContent.get(listed[i].id) ?? null); const repair = async (what: string, match: { name: string; type: string }, inp: RecordInput & { selectType?: string }, rec: Rec) => { const apiRow = listed.find((x) => x.name === match.name && x.type === match.type); @@ -550,12 +577,37 @@ test.describe('core flow', () => { await repair('name_not_fqdn', { name: 'nfq', type: 'CNAME' }, { name: 'nfq', type: 'CNAME', ttl: '3600', fields: { host: 'target.example.net' } }, { name: 'nfq', type: 'CNAME', ttl: 3600, data: { host: 'target.example.net.' } }); await repair('mx_priority_key', { name: 'mxp', type: 'MX' }, { name: 'mxp', type: 'MX', ttl: '3600', fields: { preference: '10', host: 'mail.example.net' } }, { name: 'mxp', type: 'MX', ttl: 3600, data: { host: 'mail.example.net.', preference: 10 } }); await repair('pack_failed', { name: 'cut', type: 'NS' }, { name: 'cut', type: 'NS', ttl: '3600', fields: { host: 'ns.example.net' } }, { name: 'cut', type: 'NS', ttl: 3600, data: { host: 'ns.example.net.' } }); + for (const [name, code, ip] of [['nodot', 'zone_not_fqdn', '192.0.2.64'], ['upper', 'zone_case', '192.0.2.65']]) { + await repair(code, { name, type: 'A' }, { name, type: 'A', ttl: '3600', fields: { ip } }, { name, type: 'A', ttl: 3600, data: { ip } }); + expect((await world.db.recordById(other[code]))?.zone).toBe(zoneC); + } const after = await adminApi.get(`${zp(zoneC)}/check`); expect((after.json.problems as Array<{ severity: string; code: string }>).filter((p) => p.severity === 'error')).toEqual([]); + expect((await adminUi.problems()).filter((p) => p.severity === 'error')).toEqual([]); const cliAfter = await world.cli.check(zoneC); expect(cliAfter.code).toBe(after.json.problems.length === 0 ? 0 : 3); expect(cliAfter.stdout).not.toMatch(/\berror\b/); + for (const row of original.rows.filter((r) => r.id !== soa.id)) expect(await world.db.recordById(row.id)).toEqual(row); await servedZone(world, zoneC); + + await adminUi.openZone(nosoa); + expect((await adminUi.problems()).some((p) => p.code === 'soa_missing')).toBe(true); + const started = new Date(); + const preview = await adminUi.importPreview(nosoa, `@ 3600 IN SOA ns1.${nosoa} hostmaster.${nosoa} 1980010100 3600 600 604800 300`, 'merge'); + expect(preview.status, JSON.stringify(preview.json)).toBe(200); + expect(preview.json).toMatchObject({ added: [expect.objectContaining({ name: '', type: 'SOA', ttl: 3600 })], updated: [], deleted: [] }); + const applied = await adminUi.importApply(); + expect(applied.status).toBe(200); + expect(applied.json).toEqual(importApplyBody(1, 0, 0)); + await adminUi.openZone(nosoa); + await waitForZone(world.g, nosoa, { recorder: world.recorder }); + const restoredSerial = (await world.db.soaSerial(nosoa))!; + expect([utcDay(started), utcDay(new Date())]).toContain(restoredSerial); + await threeWay(world, adminUi, nosoa, { name: '', type: 'SOA', ttl: 3600, data: { ns: `ns1.${nosoa}`, MBox: `hostmaster.${nosoa}`, serial: restoredSerial, refresh: 3600, retry: 600, expire: 604800, minttl: 300 } }, null, 'merge-import restores missing SOA'); + expect((await world.db.records(nosoa)).filter((row) => row.record_type !== 'SOA')).toEqual(noSOARows); + expect((await adminApi.get(`${zp(nosoa)}/check`)).json.problems).toEqual([]); + expect(await adminUi.problems()).toEqual([]); + await servedZone(world, nosoa); }); test('noncanonical zones and selected SOA rows can be repaired through the UI', async ({ world }) => { diff --git a/e2e/tests/harness.spec.ts b/e2e/tests/harness.spec.ts index 32a5fb3..43eb09b 100644 --- a/e2e/tests/harness.spec.ts +++ b/e2e/tests/harness.spec.ts @@ -211,15 +211,25 @@ test.describe('harness self-checks', () => { test('the leak detection finds and removes resources of the run', async () => { const name = `${project()}-leakprobe`; + const sentinel = `${project()}-unlabeled`; const image = process.env.E2E_RUNNER_IMAGE as string; - const started = await docker(['run', '--detach', '--name', name, '--label', `${RUN_LABEL}=${project()}`, '--network', 'none', '--entrypoint', 'node', image, '-e', 'setTimeout(() => {}, 120000)']); - expect(started.code, started.stderr).toBe(0); - const allowed = new Set(STACK_SERVICES.map((s) => containerName(s))); - const leaks = await detectLeaks(allowed); - expect(leaks.join('\n')).toContain(name); - const gone = await docker(['inspect', name]); - expect(gone.code).not.toBe(0); - expect(await detectLeaks(allowed)).toEqual([]); + const volume = await docker(['volume', 'create', sentinel]); + expect(volume.code, volume.stderr).toBe(0); + try { + const started = await docker(['run', '--detach', '--name', name, '--label', `${RUN_LABEL}=${project()}`, '--network', 'none', '--entrypoint', 'node', image, '-e', 'setTimeout(() => {}, 120000)']); + expect(started.code, started.stderr).toBe(0); + const allowed = new Set(STACK_SERVICES.map((s) => containerName(s))); + const leaks = await detectLeaks(allowed); + expect(leaks.join('\n')).toContain(name); + const gone = await docker(['inspect', name]); + expect(gone.code).not.toBe(0); + expect(await detectLeaks(allowed)).toEqual([]); + const preserved = await docker(['volume', 'inspect', sentinel]); + expect(preserved.code, preserved.stderr).toBe(0); + } finally { + const removed = await docker(['volume', 'rm', sentinel]); + expect(removed.code, removed.stderr).toBe(0); + } const ps = await run('docker', ['ps', '--format', '{{.Names}}', '--filter', `label=com.docker.compose.project=${project()}`]); for (const service of STACK_SERVICES) expect(ps.stdout).toContain(containerName(service)); expect(Object.keys(GROUPS)).toHaveLength(9); diff --git a/e2e/tests/power.spec.ts b/e2e/tests/power.spec.ts index 38d01ab..7a8331f 100644 --- a/e2e/tests/power.spec.ts +++ b/e2e/tests/power.spec.ts @@ -7,8 +7,8 @@ import { importApplyBody } from '../harness/decisions'; import { parseRR, waitForZone } from '../harness/dig'; import { COREDNS_HOST } from '../harness/env'; import { run } from '../harness/proc'; -import { address, addAddress, createZone, restartWithSessions, zoneInput } from '../harness/personas'; -import { begin, servedZone, threeWay } from '../harness/verify'; +import { address, createZone, restartWithSessions, zoneInput } from '../harness/personas'; +import { begin, expectBumped, servedZone, storedRow, threeWay, type Rec } from '../harness/verify'; test.use({ group: 'power' }); @@ -69,7 +69,8 @@ test('a power user operates a large installation, with restart and edit conflict expect(await world.db.delegations()).toHaveLength(48); const ip = '198.51.100.40'; - const file = Array.from({ length: 1200 }, (_, i) => `load-${i} 300 IN A ${ip}`).join('\n') + '\n'; + const names = Array.from({ length: 1200 }, (_, i) => `load-${i}`); + const file = names.map((name) => `${name} 300 IN A ${ip}`).join('\n') + '\n'; expect((await first.importPreview(imports, file, 'merge')).json.added).toHaveLength(1200); const importChange = await begin(world, imports); expect((await first.importApply()).json).toEqual(importApplyBody(1200, 0, 0)); @@ -78,13 +79,15 @@ test('a power user operates a large installation, with restart and edit conflict await threeWay(world, first, imports, { ...address('load-0', ip), type: 'A' }, importChange, 'large import'); expect(await world.db.records(imports)).toHaveLength(1202); const imported = (await world.db.records(imports)).filter((row) => row.name.startsWith('load-')); - expect(imported).toHaveLength(1200); - const queries = imported.map((row) => `${row.name}.${imports} A`).join('\n') + '\n'; - const batch = await run('dig', [`@${COREDNS_HOST}`, '-p', String(world.g.dnsPort), '+norecurse', '+nocookie', '+time=3', '+tries=2', '+noall', '+answer', '-f', '-'], { input: queries, timeoutMs: 120_000 }); + expect(imported.map((row) => row.name).sort()).toEqual([...names].sort()); + const queries = names.map((name) => `${name}.${imports} A`).join('\n') + '\n'; + const batch = await run('dig', [`@${COREDNS_HOST}`, '-p', String(world.g.dnsPort), '+norecurse', '+nocookie', '+time=3', '+tries=2', '+noall', '+comments', '+answer', '-f', '-'], { input: queries, timeoutMs: 120_000 }); expect(batch.code, batch.stderr).toBe(0); + const rcodes = Array.from(batch.stdout.matchAll(/->>HEADER<<-\s+opcode:\s*\S+,\s*status:\s*([A-Z]+),/g), (match) => match[1]); + expect(rcodes).toEqual(names.map(() => 'NOERROR')); const answers = batch.stdout.split('\n').filter((line) => line.trim() && !line.startsWith(';')).map(parseRR); - expect(answers.map((rr) => `${rr.name} ${rr.ttl} ${rr.type} ${rr.data}`).sort()).toEqual( - imported.map((row) => `${row.name}.${imports} 300 A ${ip}`).sort(), + expect(answers.map((rr) => `${rr.name} ${rr.ttl} ${rr.class} ${rr.type} ${rr.data}`).sort()).toEqual( + names.map((name) => `${name}.${imports} 300 IN A ${ip}`).sort(), ); for (const row of imported) expect(row).toMatchObject({ zone: imports, ttl: 300, record_type: 'A', content: JSON.stringify({ ip }) }); expect((await api.get(`${zp(imports)}/check`)).json.problems).toEqual([]); @@ -94,22 +97,39 @@ test('a power user imports the supported types in one transaction', async ({ wor const admin = await world.bootstrapAdmin(); const api = await world.apiAs(admin); const zone = world.zoneName(); - const zonePath = await createZone(api, zone); - await addAddress(api, zonePath, 'www', '192.0.2.5'); + await createZone(api, zone); const ui = await world.uiAs(admin); const soa = zoneInput(zone); + const replacementNS = 'ns3.example.net.'; const entries = [ - ['@', 'SOA', `${soa.ns} ${soa.mbox} 0 3600 600 604800 300`], + ['@', 'SOA', `${replacementNS} ${soa.mbox} 0 3600 600 604800 300`], ['@', 'NS', 'ns2.example.net.'], + ['www', 'A', '192.0.2.5'], ['www', 'AAAA', '2001:db8::50'], ['*.alias', 'CNAME', `www.${zone}`], - ['@', 'MX', '0 .'], + ['@', 'MX', '17 mail.example.net.'], ['@', 'TXT', '"test"'], - ['_tcp._svc', 'SRV', '0 0 0 .'], - ['@', 'CAA', '0 issue "ca.example.net"'], + ['_tcp._svc', 'SRV', '5 9 8443 svc.example.net.'], + ['@', 'CAA', '128 issue "ca.example.net"'], ]; + const before = await begin(world, zone); expect((await ui.importPreview(zone, entries.map(([n, t, v]) => `${n} 300 IN ${t} ${v}\n`).join(''), 'merge')).status).toBe(200); expect((await ui.importApply()).status).toBe(200); expect((await world.db.records(zone)).map((row) => row.record_type).sort()).toEqual(['A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'NS', 'SOA', 'SRV', 'TXT']); + const serial = await expectBumped(world, zone, before, 'all-types import'); + await storedRow(world, zone, { name: '', type: 'SOA', ttl: 300, data: { ns: replacementNS, MBox: soa.mbox, refresh: 3600, retry: 600, expire: 604800, minttl: 300, serial } }); + const imported: Rec[] = [ + { name: '', type: 'NS', ttl: 300, data: { host: 'ns2.example.net.' } }, + { name: 'www', type: 'A', ttl: 300, data: { ip: '192.0.2.5' } }, + { name: 'www', type: 'AAAA', ttl: 300, data: { ip: '2001:db8::50' } }, + { name: '*.alias', type: 'CNAME', ttl: 300, data: { host: `www.${zone}` } }, + { name: '', type: 'MX', ttl: 300, data: { host: 'mail.example.net.', preference: 17 } }, + { name: '', type: 'TXT', ttl: 300, data: { text: 'test' } }, + { name: '_tcp._svc', type: 'SRV', ttl: 300, data: { priority: 5, weight: 9, port: 8443, target: 'svc.example.net.' } }, + { name: '', type: 'CAA', ttl: 300, data: { flag: 128, tag: 'issue', value: 'ca.example.net' } }, + ]; + await ui.openZone(zone); + await waitForZone(world.g, zone, { recorder: world.recorder }); + for (const record of imported) await threeWay(world, ui, zone, record, null, 'all-types import'); await servedZone(world, zone); }); diff --git a/handlers_api.go b/handlers_api.go index ecbdff6..0777eea 100644 --- a/handlers_api.go +++ b/handlers_api.go @@ -10,6 +10,7 @@ import ( "encoding/json" "errors" "maps" + "math" "net/http" "net/url" "slices" @@ -1473,8 +1474,8 @@ func (h zoneHandlers) createRecord(ctx context.Context, c *apiContext) (apiRespo } func zoneAPIRequestedID(c *apiContext) (int64, error) { - id, err := strconv.ParseInt(c.Vars["id"], 10, 32) - if err != nil || id <= 0 { + id, err := strconv.ParseInt(c.Vars["id"], 10, 64) + if err != nil || id <= 0 || id > math.MaxUint32 { return 0, &apiError{Status: http.StatusBadRequest, Message: "invalid record id"} } c.Entry.RecordID = sql.NullInt64{Int64: id, Valid: true} @@ -1631,8 +1632,8 @@ func (h zoneHandlers) bulkDelete(ctx context.Context, c *apiContext) (apiRespons changes := zoneChanges{Deletes: make([]int64, 0, len(in.Records))} for _, item := range in.Records { var id int64 - if json.Unmarshal(item.ID, &id) != nil || id <= 0 || seen[id] { - return apiResponse{}, zoneAPIFields(map[string]string{"records": "record ids must be distinct positive integers"}) + if json.Unmarshal(item.ID, &id) != nil || id <= 0 || id > math.MaxUint32 || seen[id] { + return apiResponse{}, zoneAPIFields(map[string]string{"records": "record ids must be distinct integers from 1 to 4294967295"}) } row, err := w.findRecord(id, byID) if err != nil { diff --git a/handlers_api_test.go b/handlers_api_test.go index 9a4be3e..44bdcac 100644 --- a/handlers_api_test.go +++ b/handlers_api_test.go @@ -1377,7 +1377,7 @@ func TestZoneAPIWriteRefusals(t *testing.T) { {operation: "record_update", id: "3", status: 412, etag: `"old"`, body: zoneAPITestRecord}, {operation: "record_update", id: "99", status: 412, etag: `"old"`, body: zoneAPITestRecord}, {operation: "record_update", id: "wrong", status: 400, etag: `"old"`, body: zoneAPITestRecord}, - {operation: "record_update", id: "2147483648", status: 400, etag: `"old"`, body: zoneAPITestRecord}, + {operation: "record_update", id: "4294967296", status: 400, etag: `"old"`, body: zoneAPITestRecord}, {operation: "record_update", id: "90", status: 404, etag: `"old"`, body: zoneAPITestRecord}, {operation: "record_delete", id: "3", status: 428}, {operation: "record_delete", id: "3", status: 412, etag: "*"}, @@ -1387,6 +1387,7 @@ func TestZoneAPIWriteRefusals(t *testing.T) { {operation: "record_bulk_delete", status: 412, body: `{"records":[{"id":3,"etag":` + zoneAPITestJSON(t, recordETag(rows[2])) + `},{"id":4,"etag":"old"}]}`}, {operation: "record_bulk_delete", status: 422, field: "records", body: `{"records":[]}`}, {operation: "record_bulk_delete", status: 422, field: "records", body: `{"records":[{"id":"3","etag":"old"}]}`}, + {operation: "record_bulk_delete", status: 422, field: "records", body: `{"records":[{"id":4294967296,"etag":"old"}]}`}, {operation: "record_bulk_delete", status: 404, body: `{"records":[{"id":90,"etag":"old"}]}`}, {operation: "soa_update", status: 428, body: zoneAPITestSOA}, {operation: "soa_update", status: 412, etag: `"old"`, body: zoneAPITestSOA}, diff --git a/handlers_zone_api_test.go b/handlers_zone_api_test.go index 484257e..2ccd9d4 100644 --- a/handlers_zone_api_test.go +++ b/handlers_zone_api_test.go @@ -370,3 +370,48 @@ func TestZoneAPIRepairBlockedByBrokenSOA(t *testing.T) { t.Fatalf("created id %s", id) } } + +func TestZoneAPIRepairApexCNAMEBeforeSOA(t *testing.T) { + for _, missing := range []bool{false, true} { + name := "non-apex SOA" + if missing { + name = "missing SOA" + } + t.Run(name, func(t *testing.T) { + rows := zoneAPITestRows(t) + rows[0].Name = "below" + if missing { + rows = rows[1:] + } + cname := modelRawRow(5, "", "CNAME", 60, `{"host":"target.example.net."}`) + f := zoneAPITestDBFor(t, append(slices.Clone(rows), cname)) + server, state := f.server() + c := zoneAPITestRequest(server, f.actor, opRecordCreate, zoneAPITestName, "", "", zoneAPITestRecord) + zoneAPITestStatus(t, t.Context(), c, 422) + c = zoneAPITestRequest(server, f.actor, opRecordDelete, zoneAPITestName, "5", recordETag(cname), "") + zoneAPITestStatus(t, t.Context(), c, 200) + if state.commits != 1 || !c.auditDone || len(f.rows) != len(rows) { + t.Fatalf("CNAME repair did not commit exactly once: rows %+v, audit %+v", f.rows, c.Entry) + } + if missing { + zoneAPITestAuditIDs(t, c.Entry.Before, []int64{5}) + zoneAPITestAuditIDs(t, c.Entry.After, nil) + c = zoneAPITestRequest(server, f.actor, opRecordCreate, zoneAPITestName, "", "", zoneAPITestSOARecord("@")) + zoneAPITestStatus(t, t.Context(), c, 201) + zoneAPITestSerialOf(t, zoneAPIFindSOA(f.rows), newSOASerial(modelNow)) + } else { + zoneAPITestAuditIDs(t, c.Entry.Before, []int64{1, 5}) + zoneAPITestAuditIDs(t, c.Entry.After, []int64{1}) + zoneAPITestSerialOf(t, f.rows[0], newSOASerial(modelNow)+1) + c = zoneAPITestRequest(server, f.actor, opSOAUpdate, zoneAPITestName, "", recordETag(f.rows[0]), zoneAPITestSOA) + zoneAPITestStatus(t, t.Context(), c, 200) + zoneAPITestSerialOf(t, f.rows[0], newSOASerial(modelNow)+2) + } + zoneAPITestPreserved(t, f, rows, 2, 3, 4) + c = zoneAPITestRequest(server, f.actor, opZoneCheck, zoneAPITestName, "", "", "") + if got := zoneAPITestJSON(t, zoneAPITestStatus(t, t.Context(), c, 200).Body); got != `{"problems":[]}` { + t.Fatalf("zone after repair: %s", got) + } + }) + } +} diff --git a/integration_cli_test.go b/integration_cli_test.go index 11924ae..30174c9 100644 --- a/integration_cli_test.go +++ b/integration_cli_test.go @@ -179,7 +179,7 @@ func TestIntegrationCheckAndAuditCommands(t *testing.T) { if code := c.run("check"); code != 0 || c.stdout.String() != "ZONE NAME TYPE ID SEVERITY PROBLEM\n" { t.Fatalf("%d %q %q", code, c.stdout.String(), c.stderr.String()) } - if d.count(t, "SELECT `version` FROM `dns_webui_schema`") != 1 { + if d.count(t, "SELECT `version` FROM `dns_webui_schema`") != 2 { t.Fatal("check did not migrate") } d.rootExec(t, "INSERT INTO `dns_records` (`zone`, `name`, `ttl`, `content`, `record_type`) VALUES ('example.org.', 'www', NULL, '{\"ip\": \"192.0.2.1\"}', 'A')") @@ -240,7 +240,7 @@ func TestIntegrationServer(t *testing.T) { if results["/health"] != `200 OK {"status":"ok"}` || !strings.Contains(results["/version"], "CoreDNS Web UI") { t.Fatalf("%v", results) } - if d.count(t, "SELECT `version` FROM `coredns_webui_schema`") != 1 { + if d.count(t, "SELECT `version` FROM `coredns_webui_schema`") != 2 { t.Fatal("server did not migrate") } } diff --git a/integration_db_test.go b/integration_db_test.go index 37babef..e87b341 100644 --- a/integration_db_test.go +++ b/integration_db_test.go @@ -97,7 +97,7 @@ func TestIntegrationMigrationRestartsAfterEveryDDL(t *testing.T) { t.Fatal(err) } db, tn = d.migrated(t) - if v, err := schemaVersion(ctx, db, tn); err != nil || v != 1 { + if v, err := schemaVersion(ctx, db, tn); err != nil || v != 2 { t.Fatalf("restarted schema version = %d, %v", v, err) } if n := d.count(t, "SELECT COUNT(*) FROM information_schema.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = DATABASE()"); n != 5 { @@ -140,7 +140,7 @@ func TestIntegrationMigrations(t *testing.T) { d := newITDatabase(t, itOptions{prefix: "coredns_"}) db, tn := d.migrated(t) version, err := schemaVersion(ctx, db, tn) - if err != nil || version != 1 { + if err != nil || version != 2 { t.Fatal(version, err) } for _, table := range []string{"coredns_webui_schema", "coredns_webui_users", "coredns_webui_sessions", "coredns_webui_zone_delegations", "coredns_webui_audit"} { @@ -160,18 +160,64 @@ func TestIntegrationMigrations(t *testing.T) { if n := d.count(t, "SELECT COUNT(*) FROM `coredns_webui_schema`"); n != 1 { t.Fatalf("schema rows %d", n) } - if n := d.count(t, "SELECT `version` FROM `coredns_webui_schema` WHERE `id` = 1"); n != 1 { + if n := d.count(t, "SELECT `version` FROM `coredns_webui_schema` WHERE `id` = 1"); n != 2 { t.Fatalf("version %d", n) } if _, err := d.root.Exec("INSERT INTO `coredns_webui_schema` (`id`, `version`) VALUES (2, 1)"); err == nil { t.Fatal("second schema row accepted") } - d.rootExec(t, "UPDATE `coredns_webui_schema` SET `version` = 2") + d.rootExec(t, "UPDATE `coredns_webui_schema` SET `version` = 3") if err := migrateDatabase(ctx, db, tn, discardLogger()); err == nil || !strings.Contains(err.Error(), "newer") { t.Fatalf("newer schema: %v", err) } } +func TestIntegrationAuditRecordIDMigration(t *testing.T) { + const prefix = "audit_id_" + migrations, err := loadMigrations(migrationFiles, prefix) + if err != nil { + t.Fatal(err) + } + for _, name := range []string{"upgrade", "restart_after_ddl"} { + t.Run(name, func(t *testing.T) { + d := newITDatabase(t, itOptions{prefix: prefix}) + db, tables := d.openApp(t), d.tables(t) + ctx := t.Context() + if err := applyMigrations(ctx, db, tables, migrations[:1], discardLogger()); err != nil { + t.Fatal(err) + } + audit := newAuditStore(db, tables) + oldRecordID := sql.NullInt64{Int64: 2147483647, Valid: true} + old := auditEntry{Time: webNow, Actor: "alice", Origin: "local", Operation: opRecordDelete, RecordID: oldRecordID} + oldID, err := audit.InsertAudit(ctx, old) + if err != nil { + t.Fatal(err) + } + if name == "restart_after_ddl" { + if _, err := db.ExecContext(ctx, migrations[1].statements[0]); err != nil { + t.Fatal(err) + } + } + if version, err := schemaVersion(ctx, db, tables); err != nil || version != 1 { + t.Fatalf("before migration: version %d, error %v", version, err) + } + for range 2 { + if err := migrateDatabase(ctx, db, tables, discardLogger()); err != nil { + t.Fatal(err) + } + } + if version, err := schemaVersion(ctx, db, tables); err != nil || version != 2 { + t.Fatalf("after migration: version %d, error %v", version, err) + } + rows, err := audit.LatestAudit(ctx, 2) + if err != nil || len(rows) != 1 || rows[0].ID != oldID || rows[0].RecordID != oldRecordID || rows[0].Actor != old.Actor || + rows[0].Origin != old.Origin || rows[0].Operation != old.Operation || !rows[0].Time.Equal(old.Time) { + t.Fatalf("the pre-existing audit row changed: %+v, error %v", rows, err) + } + }) + } +} + func TestIntegrationConcurrentMigrations(t *testing.T) { t.Parallel() for round := 0; round < 3; round++ { @@ -202,7 +248,7 @@ func TestIntegrationConcurrentMigrations(t *testing.T) { t.Fatalf("round %d: %v", round, err) } } - if n := d.count(t, "SELECT `version` FROM `coredns_webui_schema` WHERE `id` = 1"); n != 1 { + if n := d.count(t, "SELECT `version` FROM `coredns_webui_schema` WHERE `id` = 1"); n != 2 { t.Fatalf("version %d", n) } } diff --git a/integration_http_race_test.go b/integration_http_race_test.go index a3d6dbf..4e7c428 100644 --- a/integration_http_race_test.go +++ b/integration_http_race_test.go @@ -8,6 +8,7 @@ package main import ( "context" "database/sql" + "encoding/json" "fmt" "log/slog" "net/http" @@ -64,6 +65,9 @@ func (it itHTTP) do(ctx context.Context, req webRequest) *httptest.ResponseRecor } else if req.body != "" { r.Header.Set("Content-Type", "application/json") } + for name, value := range req.header { + r.Header.Set(name, value) + } if req.token != "" { r.AddCookie(sessionCookie(req.token, false)) } @@ -79,14 +83,19 @@ func (it itHTTP) audit(t *testing.T, operation string, status int, actor userRow t.Fatalf("%s audit: got %d rows, want 1, error %v", operation, len(rows), err) } e := rows[0] - if !e.Status.Valid || e.Status.Int64 != int64(status) || !e.UserID.Valid || e.UserID.Int64 != actor.ID || + assertITHTTPAudit(t, e, operation, status, actor) + return e +} + +func assertITHTTPAudit(t *testing.T, e auditRow, operation string, status int, actor userRow) { + t.Helper() + if e.Operation != operation || !e.Status.Valid || e.Status.Int64 != int64(status) || !e.UserID.Valid || e.UserID.Int64 != actor.ID || e.Actor != actor.Username || !e.Time.Equal(webNow) || e.Origin != "192.0.2.1" || e.Error.Valid != (status >= 400) { t.Fatalf("%s audit: %+v", operation, e) } if status >= 400 && (e.Before != nil || e.After != nil) { t.Fatalf("%s failure has snapshots: %+v", operation, e) } - return e } type itCommitGateKey struct{} @@ -141,42 +150,53 @@ func (it itHTTP) race(t *testing.T, first, second webRequest, firstStatus, secon t.Fatal("first request did not reach its commit") } go func() { b <- it.do(ctx, second) }() + it.waitForUserLock(t, ctx, b) + close(gate.release) + return itHTTPResponse(t, ctx, a, firstStatus), itHTTPResponse(t, ctx, b, secondStatus) +} + +func (it itHTTP) waitForUserLock(t *testing.T, ctx context.Context, result <-chan *httptest.ResponseRecorder) { + t.Helper() + it.waitForLock(t, ctx, result, "user row lock", "SELECT EXISTS (SELECT 1 FROM performance_schema.data_lock_waits w "+ + "JOIN performance_schema.data_locks l ON l.ENGINE = w.ENGINE AND l.ENGINE_LOCK_ID = w.REQUESTING_ENGINE_LOCK_ID "+ + "WHERE l.OBJECT_SCHEMA = ? AND l.OBJECT_NAME = ?)", it.database.name, it.database.prefix+"webui_users") +} + +func (it itHTTP) waitForLock(t *testing.T, ctx context.Context, result <-chan *httptest.ResponseRecorder, lock, query string, args ...any) { + t.Helper() tick := time.NewTicker(20 * time.Millisecond) defer tick.Stop() for { var waiting bool - err := it.database.root.QueryRowContext(ctx, "SELECT EXISTS (SELECT 1 FROM performance_schema.data_lock_waits w "+ - "JOIN performance_schema.data_locks l ON l.ENGINE = w.ENGINE AND l.ENGINE_LOCK_ID = w.REQUESTING_ENGINE_LOCK_ID "+ - "WHERE l.OBJECT_SCHEMA = ? AND l.OBJECT_NAME = ?)", - it.database.name, it.database.prefix+"webui_users").Scan(&waiting) + err := it.database.root.QueryRowContext(ctx, query, args...).Scan(&waiting) if err != nil { - t.Fatalf("observe user lock: %v", err) + t.Fatalf("observe %s: %v", lock, err) } if waiting { - break + return } select { - case w := <-b: - t.Fatalf("second request did not wait on the users table: %d %s", w.Code, w.Body) + case w := <-result: + t.Fatalf("request did not wait on %s: %d %s", lock, w.Code, w.Body) case <-ctx.Done(): - t.Fatal("second request did not reach a user row lock") + t.Fatalf("request did not reach %s", lock) case <-tick.C: } } - close(gate.release) - receive := func(ch <-chan *httptest.ResponseRecorder, status int) *httptest.ResponseRecorder { - select { - case w := <-ch: - if w.Code != status { - t.Fatalf("request status = %d, want %d, body %s", w.Code, status, w.Body) - } - return w - case <-ctx.Done(): - t.Fatal("request did not finish") - return nil +} + +func itHTTPResponse(t *testing.T, ctx context.Context, result <-chan *httptest.ResponseRecorder, status int) *httptest.ResponseRecorder { + t.Helper() + select { + case w := <-result: + if w.Code != status { + t.Fatalf("request status = %d, want %d, body %s", w.Code, status, w.Body) } + return w + case <-ctx.Done(): + t.Fatal("request did not finish") + return nil } - return receive(a, firstStatus), receive(b, secondStatus) } func TestIntegrationPasswordRaces(t *testing.T) { @@ -326,6 +346,127 @@ func TestIntegrationAdminMutationAuthorizationRaces(t *testing.T) { } } +func TestIntegrationZoneCreationDelegationRace(t *testing.T) { + for _, createFirst := range []bool{true, false} { + t.Run(fmt.Sprintf("create_first_%t", createFirst), func(t *testing.T) { + it := newITHTTP(t) + creator := it.createUser(t, "creator", roleAdmin) + grantor := it.createUser(t, "grantor", roleAdmin) + grantee := it.createUser(t, "grantee", roleUser) + zone := strings.ReplaceAll(it.database.name, "_", "-") + ".example.org." + create := webRequest{method: "POST", path: apiPrefix + "/zones", token: it.token(t, creator), + body: strings.Replace(zoneAPITestCreate, "Example.ORG", zone, 1)} + grant := webRequest{method: "PUT", path: apiPrefix + "/zones/" + zone + "/users/grantee", token: it.token(t, grantor)} + first, second, firstActor := create, grant, creator + if !createFirst { + first, second, firstActor = grant, create, grantor + } + + ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second) + defer cancel() + tables := it.server.tables + gate, err := it.database.root.BeginTx(ctx, nil) + if err != nil { + t.Fatal(err) + } + defer gate.Rollback() + if _, err := newUserStore(gate, tables).UserByIDForUpdate(ctx, firstActor.ID); err != nil { + t.Fatal(err) + } + // Both handlers acquire the zone lock before checking the actor's row. + a := make(chan *httptest.ResponseRecorder, 1) + b := make(chan *httptest.ResponseRecorder, 1) + go func() { a <- it.do(ctx, first) }() + it.waitForUserLock(t, ctx, a) + go func() { b <- it.do(ctx, second) }() + it.waitForLock(t, ctx, b, "zone named lock", "SELECT EXISTS (SELECT 1 FROM performance_schema.metadata_locks "+ + "WHERE OBJECT_TYPE = 'USER LEVEL LOCK' AND OBJECT_NAME = ? AND LOCK_STATUS = 'PENDING')", tables.zoneLockName(zone)) + if err := gate.Commit(); err != nil { + t.Fatal(err) + } + grantStatus := http.StatusNoContent + if createFirst { + itHTTPResponse(t, ctx, a, http.StatusCreated) + itHTTPResponse(t, ctx, b, grantStatus) + } else { + grantStatus = http.StatusNotFound + response := itHTTPResponse(t, ctx, a, grantStatus) + if response.Body.String() != `{"error":"zone not found"}` { + t.Fatalf("grant before creation: %s", response.Body) + } + itHTTPResponse(t, ctx, b, http.StatusCreated) + } + if exists, err := newDelegationStore(it.server.db, tables).HasDelegation(ctx, zone, grantee.ID); err != nil || exists != createFirst { + t.Fatalf("delegation exists = %t, want %t, error %v", exists, createFirst, err) + } + if rows, err := newRecordStore(it.server.db, tables).ZoneRows(ctx, zone); err != nil || len(rows) != 3 { + t.Fatalf("created zone has %d records, want 3, error %v", len(rows), err) + } + if n := it.database.count(t, tables.sql("SELECT COUNT(*) FROM {audit}")); n != 2 { + t.Fatalf("audit row count = %d, want 2", n) + } + created := it.audit(t, opZoneCreate, http.StatusCreated, creator) + granted := it.audit(t, opDelegationGrant, grantStatus, grantor) + auditZone := sql.NullString{String: zone, Valid: true} + if created.Zone != auditZone || created.RecordID.Valid || created.TargetUserID.Valid || + created.Before != nil || len(created.After) == 0 || granted.Zone != auditZone || granted.RecordID.Valid || granted.Before != nil { + t.Fatalf("unexpected zone race audit: %+v %+v", created, granted) + } + if createFirst { + var snapshot auditDelegationValue + if err := json.Unmarshal(granted.After, &snapshot); err != nil || snapshot != (auditDelegationValue{Zone: zone, Username: grantee.Username}) || + granted.TargetUserID != (sql.NullInt64{Int64: grantee.ID, Valid: true}) || granted.ID <= created.ID { + t.Fatalf("unexpected successful grant audit: %+v, snapshot %+v, error %v", granted, snapshot, err) + } + } else if granted.TargetUserID.Valid || granted.Error.String != msgZoneNotFound { + t.Fatalf("unexpected rejected grant audit: %+v", granted) + } + }) + } +} + +func TestIntegrationAdminsDemotingEachOther(t *testing.T) { + it := newITHTTP(t) + alice := it.createUser(t, "alice", roleAdmin) + bob := it.createUser(t, "bob", roleAdmin) + demote := func(actor, target userRow) webRequest { + return webRequest{method: "PUT", path: apiPrefix + "/users/" + target.Username + "/role", token: it.token(t, actor), body: `{"role":"user"}`} + } + _, refused := it.race(t, demote(alice, bob), demote(bob, alice), http.StatusNoContent, http.StatusForbidden) + if refused.Body.String() != `{"error":"admin role required"}` { + t.Fatalf("refused demotion: %s", refused.Body) + } + ctx, tables := t.Context(), it.server.tables + if n := it.database.count(t, tables.sql("SELECT COUNT(*) FROM {users} WHERE role = 'admin' AND deleted_at IS NULL AND id = ?"), alice.ID); n != 1 { + t.Fatal("the first actor did not remain an active admin") + } + stored, err := newUserStore(it.server.db, tables).UserByID(ctx, bob.ID) + if err != nil || stored.Role != roleUser || stored.DeletedAt.Valid { + t.Fatalf("the second actor was not demoted to user: role %s, deleted %t, error %v", stored.Role, stored.DeletedAt.Valid, err) + } + audit := newAuditStore(it.server.db, tables) + rows, err := audit.LatestAudit(ctx, 3) + if err != nil || len(rows) != 2 { + t.Fatalf("mutual demotion audit: got %d rows, want 2, error %v", len(rows), err) + } + won, lost := rows[0], rows[1] + assertITHTTPAudit(t, won, opUserRole, http.StatusNoContent, alice) + assertITHTTPAudit(t, lost, opUserRole, http.StatusForbidden, bob) + if won.TargetUserID != (sql.NullInt64{Int64: bob.ID, Valid: true}) || lost.TargetUserID != (sql.NullInt64{Int64: alice.ID, Valid: true}) || + won.Zone.Valid || lost.Zone.Valid || won.RecordID.Valid || lost.RecordID.Valid || lost.Error.String != msgAdminRequired { + t.Fatalf("unexpected mutual demotion audit: %+v %+v", won, lost) + } + for _, snapshot := range []struct { + data []byte + want auditUserValue + }{{won.Before, auditUserValueOf(bob)}, {won.After, auditUserValueOf(stored)}} { + var got auditUserValue + if err := json.Unmarshal(snapshot.data, &got); err != nil || got != snapshot.want { + t.Fatalf("demotion snapshot = %+v, want %+v, error %v", got, snapshot.want, err) + } + } +} + func TestIntegrationUserCreateAuditRollback(t *testing.T) { it := newITHTTP(t) admin := it.createUser(t, "admin", roleAdmin) diff --git a/integration_zone_api_test.go b/integration_zone_api_test.go index 8898a2b..f40cbc4 100644 --- a/integration_zone_api_test.go +++ b/integration_zone_api_test.go @@ -12,6 +12,7 @@ import ( "errors" "fmt" "net/http" + "net/http/httptest" "strconv" "strings" "testing" @@ -92,6 +93,94 @@ func (it itZoneAPI) audit(t *testing.T, operation string, want int) []auditRow { return rows } +func TestIntegrationUnsignedRecordIDs(t *testing.T) { + const firstID, lastID = int64(2147483648), int64(4294967295) + d := newITDatabase(t, itOptions{prefix: "uint_ids_", recordDDL: strings.Replace(itRecordsDDL, "`id` INT", "`id` INT UNSIGNED", 1)}) + db, tables := d.migrated(t) + server := newWebServer(d.config(t), discardLogger(), db, tables, func() time.Time { return webNow }) + it := itHTTP{database: d, server: server, handler: server.Handler()} + admin := it.createUser(t, "alice", roleAdmin) + token := it.token(t, admin) + do := func(method, path, etag, body string, status int) *httptest.ResponseRecorder { + t.Helper() + res := it.do(t.Context(), webRequest{method: method, path: apiPrefix + path, token: token, body: body, + header: map[string]string{"If-Match": etag}}) + if res.Code != status { + t.Fatalf("%s %s: got %d, want %d, body %s", method, path, res.Code, status, res.Body) + } + return res + } + assertRecord := func(res *httptest.ResponseRecorder, id int64) string { + t.Helper() + var body struct { + Record zoneAPIRecord `json:"record"` + } + if err := json.Unmarshal(res.Body.Bytes(), &body); err != nil || body.Record.ID != id || body.Record.ETag == "" || body.Record.ETag != res.Header().Get("ETag") { + t.Fatalf("record ID or ETag mismatch, want ID %d, got %s, error %v", id, res.Body, err) + } + return body.Record.ETag + } + do(http.MethodPost, "/zones", "", zoneAPITestCreate, http.StatusCreated) + store := newRecordStore(db, tables) + rows, err := store.ZoneRows(t.Context(), zoneAPITestName) + if err != nil || len(rows) != 3 { + t.Fatalf("zone creation: %d rows, error %v", len(rows), err) + } + soaID := zoneAPIFindSOA(rows).ID + path := "/zones/" + zoneAPITestName + "/records" + firstPath := path + "/" + strconv.FormatInt(firstID, 10) + d.rootExec(t, tables.sql("ALTER TABLE {records} AUTO_INCREMENT = 2147483648")) + etag := assertRecord(do(http.MethodPost, path, "", zoneAPITestRecord, http.StatusCreated), firstID) + newRecord := strings.Replace(zoneAPITestRecord, `"ttl":60`, `"ttl":120`, 1) + newETag := assertRecord(do(http.MethodPut, firstPath, etag, newRecord, http.StatusOK), firstID) + if newETag == etag { + t.Fatal("record update kept the original ETag") + } + do(http.MethodDelete, firstPath, newETag, "", http.StatusOK) + d.rootExec(t, tables.sql("ALTER TABLE {records} AUTO_INCREMENT = 4294967295")) + etag = assertRecord(do(http.MethodPost, path, "", zoneAPITestRecord, http.StatusCreated), lastID) + bulk := fmt.Sprintf(`{"records":[{"id":%d,"etag":%q}]}`, lastID, etag) + do(http.MethodPost, path+"/delete", "", bulk, http.StatusOK) + do(http.MethodPut, path+"/4294967296", etag, zoneAPITestRecord, http.StatusBadRequest) + do(http.MethodPost, path+"/delete", "", strings.Replace(bulk, "4294967295", "4294967296", 1), http.StatusUnprocessableEntity) + for _, id := range []int64{firstID, lastID} { + if _, err := store.RecordByID(t.Context(), id); !errors.Is(err, errRowNotFound) { + t.Errorf("deleted record %d: %v", id, err) + } + } + audit, err := newAuditStore(db, tables).LatestAudit(t.Context(), 9) + want := []struct { + op string + status int + id int64 + }{ + {opZoneCreate, 201, 0}, {opRecordCreate, 201, firstID}, {opRecordUpdate, 200, firstID}, {opRecordDelete, 200, firstID}, + {opRecordCreate, 201, lastID}, {opRecordBulkDelete, 200, 0}, {opRecordUpdate, 400, 0}, {opRecordBulkDelete, 422, 0}, + } + if err != nil || len(audit) != len(want) { + t.Fatalf("audit: got %d rows, want %d, error %v", len(audit), len(want), err) + } + for i, entry := range want { + row := audit[i] + assertITHTTPAudit(t, row, entry.op, entry.status, admin) + if row.RecordID != (sql.NullInt64{Int64: entry.id, Valid: entry.id != 0}) { + t.Fatalf("%s audit: got ID %+v, want %d", entry.op, row.RecordID, entry.id) + } + } + zoneAPITestAuditIDs(t, audit[5].Before, []int64{soaID, lastID}) + zoneAPITestAuditIDs(t, audit[5].After, []int64{soaID}) + var apiAudit auditResponse + res := do(http.MethodGet, "/audit?operation=record_create", "", "", http.StatusOK) + if err := json.Unmarshal(res.Body.Bytes(), &apiAudit); err != nil || len(apiAudit.Entries) != 2 { + t.Fatalf("API audit: %s, error %v", res.Body, err) + } + for i, id := range []int64{lastID, firstID} { + if got := apiAudit.Entries[i].RecordID; got == nil || *got != id { + t.Fatalf("API audit record ID at %d: %v, want %d", i, got, id) + } + } +} + func TestIntegrationZoneAPIHandlers(t *testing.T) { it := newITZoneAPI(t) admin, user := it.admin, it.user @@ -396,6 +485,65 @@ func TestIntegrationZoneAPIRepairs(t *testing.T) { } } +func TestIntegrationUndottedZoneDelegation(t *testing.T) { + it := newITHTTP(t) + admin := it.createUser(t, "admin", roleAdmin) + user := it.createUser(t, "member", roleUser) + adminToken, userToken := it.token(t, admin), it.token(t, user) + zonePath := "/zones/" + zoneAPITestName + request := func(token, method, path, body, etag string, status int) []byte { + t.Helper() + r := it.do(t.Context(), webRequest{token: token, method: method, path: apiPrefix + path, body: body, + header: map[string]string{"If-Match": etag}}) + if r.Code != status { + t.Fatalf("%s %s: status %d, want %d, body %s", method, path, r.Code, status, r.Body) + } + return r.Body.Bytes() + } + request(adminToken, http.MethodPost, "/zones", zoneAPITestCreate, "", http.StatusCreated) + request(adminToken, http.MethodPost, zonePath+"/records", zoneAPITestRecord, "", http.StatusCreated) + request(adminToken, http.MethodPut, zonePath+"/users/member", "", "", http.StatusNoContent) + ctx, tables := t.Context(), it.server.tables + const missing = "missing.example.net." + if _, err := newDelegationStore(it.server.db, tables).GrantDelegation(ctx, missing, user.ID, admin.ID, webNow); err != nil { + t.Fatal(err) + } + undotted := strings.TrimSuffix(zoneAPITestName, ".") + it.database.rootExec(t, tables.sql("UPDATE {records} SET `zone` = ? WHERE `zone` = ?"), undotted, zoneAPITestName) + if n := it.database.count(t, tables.sql("SELECT COUNT(*) FROM {records} WHERE `zone` = ?"), zoneAPITestName); n != 0 { + t.Fatalf("fixture still has %d canonical rows", n) + } + var list struct { + Zones []zoneAPIListItem `json:"zones"` + } + if err := json.Unmarshal(request(userToken, http.MethodGet, "/zones", "", "", http.StatusOK), &list); err != nil || + len(list.Zones) != 1 || list.Zones[0].Name != zoneAPITestName { + t.Fatalf("delegated zone list = %+v, error %v", list.Zones, err) + } + var account accountResponse + if err := json.Unmarshal(request(userToken, http.MethodGet, "/account", "", "", http.StatusOK), &account); err != nil || + len(account.Zones) != 1 || account.Zones[0] != zoneAPITestName { + t.Fatalf("delegated account zones = %v, error %v", account.Zones, err) + } + var detail userDetail + if err := json.Unmarshal(request(adminToken, http.MethodGet, "/users/member", "", "", http.StatusOK), &detail); err != nil || + len(detail.Zones) != 2 || detail.Zones[0] != (userZoneItem{Zone: zoneAPITestName, Exists: true}) || + detail.Zones[1] != (userZoneItem{Zone: missing}) { + t.Fatalf("admin's view of delegated zones = %+v, error %v", detail.Zones, err) + } + records := newRecordStore(it.server.db, tables) + rows, err := records.ZoneRows(ctx, zoneAPITestName) + if err != nil || len(rows) != 4 { + t.Fatalf("zone rows = %+v, error %v", rows, err) + } + record := rows[len(rows)-1] + request(userToken, http.MethodPut, zonePath+"/records/"+strconv.FormatInt(record.ID, 10), zoneAPITestRecord, recordETag(record), http.StatusOK) + repaired, err := records.RecordByID(ctx, record.ID) + if err != nil || repaired.Zone != zoneAPITestName { + t.Fatalf("record not repaired: %+v, error %v", repaired, err) + } +} + func TestIntegrationZoneAPIAuditRollback(t *testing.T) { it := newITZoneAPI(t) it.call(t, it.admin, "zone_create", "", "", zoneAPITestCreate, 201) diff --git a/migrations.go b/migrations.go index 7277553..68d91cb 100644 --- a/migrations.go +++ b/migrations.go @@ -154,7 +154,7 @@ var appSchema = []schemaColumn{ {"webui_audit", "status", "smallint"}, {"webui_audit", "error", "varchar(255)"}, {"webui_audit", "zone", "varchar(255)"}, - {"webui_audit", "record_id", "int"}, + {"webui_audit", "record_id", "bigint"}, {"webui_audit", "target_user_id", "int"}, {"webui_audit", "before_value", "json"}, {"webui_audit", "after_value", "json"}, diff --git a/migrations/002_wide_audit_record_id.sql b/migrations/002_wide_audit_record_id.sql new file mode 100644 index 0000000..e21b91f --- /dev/null +++ b/migrations/002_wide_audit_record_id.sql @@ -0,0 +1,4 @@ +-- SPDX-License-Identifier: GPL-2.0-or-later +-- Copyright (C) 2026 Bryan Joshua Pedini + +ALTER TABLE `{prefix}webui_audit` MODIFY COLUMN `record_id` BIGINT NULL; diff --git a/migrations_test.go b/migrations_test.go index 1546213..af103dc 100644 --- a/migrations_test.go +++ b/migrations_test.go @@ -18,9 +18,13 @@ func TestLoadEmbeddedMigrations(t *testing.T) { if err != nil { t.Fatal(err) } - if len(ms) != 1 || ms[0].version != 1 || ms[0].name != "001_initial.sql" || len(ms[0].statements) != 5 { + if len(ms) != 2 || ms[0].version != 1 || ms[0].name != "001_initial.sql" || len(ms[0].statements) != 5 { t.Fatalf("got %+v", ms) } + if ms[1].version != 2 || ms[1].name != "002_wide_audit_record_id.sql" || !reflect.DeepEqual(ms[1].statements, + []string{"ALTER TABLE `dns_webui_audit` MODIFY COLUMN `record_id` BIGINT NULL"}) { + t.Fatalf("got %+v", ms[1]) + } wantTables := []string{"`dns_webui_schema`", "`dns_webui_users`", "`dns_webui_sessions`", "`dns_webui_zone_delegations`", "`dns_webui_audit`"} for i, stmt := range ms[0].statements { if strings.Contains(stmt, "{prefix}") || strings.Contains(stmt, "coredns_") || strings.Contains(stmt, "--") { @@ -133,8 +137,9 @@ func (m *migrationDB) handler(q string, args []any) fdbResponse { return fdbResponse{rows: fdbRow(m.existsCount)} case strings.HasPrefix(q, "INSERT INTO `coredns_webui_schema`"): m.versionWrite = append(m.versionWrite, "insert", args[0]) + m.updateRows = 1 return fdbResponse{} - case strings.HasPrefix(q, "CREATE TABLE"): + case strings.HasPrefix(q, "CREATE TABLE"), strings.HasPrefix(q, "ALTER TABLE"): m.executedDDL = append(m.executedDDL, q) return fdbResponse{} case strings.Contains(q, "information_schema.COLUMNS"): @@ -207,17 +212,24 @@ func TestApplyMigrations(t *testing.T) { if err := applyMigrations(ctx, db, tn, ms, discardLogger()); err != nil { t.Fatal(err) } - if len(m.executedDDL) != 5 || !reflect.DeepEqual(m.versionWrite, []any{"update", int64(1), "insert", int64(1)}) { + if len(m.executedDDL) != 6 || !reflect.DeepEqual(m.versionWrite, []any{"update", int64(1), "insert", int64(1), "update", int64(2)}) { t.Fatalf("ddl %d writes %v", len(m.executedDDL), m.versionWrite) } - m = &migrationDB{tableCount: 1, version: int64(1)} + m = &migrationDB{tableCount: 1, version: int64(1), updateRows: 1} + db, _ = newFakeDB(t, m.handler) + if err := applyMigrations(ctx, db, tn, ms, discardLogger()); err != nil || !reflect.DeepEqual(m.executedDDL, ms[1].statements) || + !reflect.DeepEqual(m.versionWrite, []any{"update", int64(2)}) { + t.Fatalf("upgrade: %v %v %v", err, m.executedDDL, m.versionWrite) + } + + m = &migrationDB{tableCount: 1, version: int64(2)} db, _ = newFakeDB(t, m.handler) if err := applyMigrations(ctx, db, tn, ms, discardLogger()); err != nil || len(m.executedDDL) != 0 || len(m.versionWrite) != 0 { t.Fatalf("rerun: %v %d %v", err, len(m.executedDDL), m.versionWrite) } - m = &migrationDB{tableCount: 1, version: int64(2)} + m = &migrationDB{tableCount: 1, version: int64(3)} db, _ = newFakeDB(t, m.handler) if err := applyMigrations(ctx, db, tn, ms, discardLogger()); err == nil || !strings.Contains(err.Error(), "newer") { t.Fatalf("got %v", err) @@ -285,11 +297,9 @@ func TestVerifyAppSchema(t *testing.T) { if err != nil { t.Fatal(err) } - for _, migration := range all { - for _, stmt := range migration.statements { - if !strings.HasPrefix(stmt, "CREATE TABLE IF NOT EXISTS ") { - t.Fatalf("%s: not idempotent: %.60s", migration.name, stmt) - } + for _, stmt := range all[0].statements { + if !strings.HasPrefix(stmt, "CREATE TABLE IF NOT EXISTS ") { + t.Fatalf("%s: not idempotent: %.60s", all[0].name, stmt) } } cases := map[string]func(rows [][]driver.Value) [][]driver.Value{ @@ -302,10 +312,18 @@ func TestVerifyAppSchema(t *testing.T) { } return rows }, + "column record_id of table coredns_webui_audit has type int, expected bigint": func(rows [][]driver.Value) [][]driver.Value { + for _, r := range rows { + if r[0] == "coredns_webui_audit" && r[1] == "record_id" { + r[2] = "int" + } + } + return rows + }, "table coredns_webui_schema has no column id": func([][]driver.Value) [][]driver.Value { return nil }, } for want, change := range cases { - m := &migrationDB{tableCount: 1, version: int64(1), schemaChange: change} + m := &migrationDB{tableCount: 1, version: int64(2), schemaChange: change} db, _ := newFakeDB(t, m.handler) if err := migrateDatabase(ctx, db, fdbTables(t), discardLogger()); err == nil || !strings.Contains(err.Error(), want) { t.Fatalf("%s: %v", want, err) diff --git a/rules.go b/rules.go index 37b1881..5372021 100644 --- a/rules.go +++ b/rules.go @@ -162,6 +162,10 @@ func (changes zoneChanges) empty() bool { return len(changes.Creates)+len(changes.Updates)+len(changes.Deletes) == 0 && changes.SOAUpdate == nil && !changes.ManageSerial } +func (changes zoneChanges) deletesOnly() bool { + return len(changes.Deletes) > 0 && len(changes.Creates)+len(changes.Updates) == 0 && changes.SOAUpdate == nil && !changes.ManageSerial +} + func (changes zoneChanges) finalRows(rows []recordRow) []recordRow { updates := make(map[int64]recordRow) deletes := make(map[int64]bool) @@ -192,8 +196,22 @@ func validateZoneChanges(zone string, current []recordRow, changes zoneChanges) before := summarizeZone(current) after := summarizeZone(result) problems, warnings = zoneRuleProblems(zone, result, after, true) - repair := len(after.soa) != 0 && soaDefects(after.soa) < soaDefects(before.soa) - if repair { + soaRepair := len(after.soa) != 0 && soaDefects(after.soa) < soaDefects(before.soa) + soaOnlyRepair := soaRepair && slices.Equal(nonSOARows(current), nonSOARows(result)) + // An existing CNAME can block an SOA repair at the apex. Permit an + // independent repair without permitting normal writes on the broken zone. + cnameRepair := soaDefects(after.soa) != 0 && changes.deletesOnly() + if len(problems) != 0 && (soaOnlyRepair || cnameRepair) { + beforeProblems, _ := zoneRuleProblems(zone, current, before, true) + if soaOnlyRepair || (len(problems) < len(beforeProblems) && deletesOnlyConflictingCNAMEs(changes.Deletes, beforeProblems)) { + existing := make(map[zoneProblem]bool, len(beforeProblems)) + for _, p := range beforeProblems { + existing[p] = true + } + problems = slices.DeleteFunc(problems, func(p zoneProblem) bool { return existing[p] }) + } + } + if soaRepair { problems = slices.DeleteFunc(problems, func(p zoneProblem) bool { return p.Code == "soa_multiple" || p.Code == "soa_not_apex" }) } if len(before.soa) != 0 { @@ -202,7 +220,7 @@ func validateZoneChanges(zone string, current []recordRow, changes zoneChanges) afterSOAs[row.ID] = true } for _, row := range before.soa { - if !afterSOAs[row.ID] && !repair { + if !afterSOAs[row.ID] && !soaRepair { problems = append(problems, recordProblem(row, "error", "soa_delete", "SOA may only be deleted with the zone")) } } @@ -219,6 +237,31 @@ func validateZoneChanges(zone string, current []recordRow, changes zoneChanges) return problems, warnings } +func nonSOARows(rows []recordRow) []recordRow { + var records []recordRow + for _, row := range rows { + if row.RecordType != "SOA" { + records = append(records, row) + } + } + return records +} + +func deletesOnlyConflictingCNAMEs(ids []int64, problems []zoneProblem) bool { + conflicting := make(map[int64]bool) + for _, problem := range problems { + if problem.Type == "CNAME" && (problem.Code == "cname_apex" || problem.Code == "cname_conflict") { + conflicting[problem.RecordID] = true + } + } + for _, id := range ids { + if !conflicting[id] { + return false + } + } + return true +} + func soaDefects(soa []recordRow) int { defects := len(soa) - 1 for _, row := range soa { diff --git a/rules_test.go b/rules_test.go index 48f67c5..bc2acf4 100644 --- a/rules_test.go +++ b/rules_test.go @@ -4,6 +4,7 @@ package main import ( + "cmp" "database/sql" "slices" "strings" @@ -47,6 +48,90 @@ func TestValidateZoneChanges(t *testing.T) { } } +func TestMixedZoneSOARepair(t *testing.T) { + const zone = "example.org." + extraSOA := modelRawRow(3, "", "SOA", 3600, modelSOAContent) + subSOA := modelRawRow(4, "sub", "SOA", 3600, modelSOAContent) + apexCNAME := modelRawRow(5, "", "CNAME", 3600, `{"host":"target.example."}`) + alias := modelRawRow(6, "www", "CNAME", 3600, `{"host":"target.example."}`) + address := modelRawRow(7, "www", "A", 3600, `{"ip":"192.0.2.4"}`) + current := append(modelBaseZone(), extraSOA, subSOA, apexCNAME, alias, address) + for _, changes := range []zoneChanges{ + {Deletes: []int64{address.ID}}, + {Deletes: []int64{alias.ID, address.ID}}, + {Deletes: []int64{extraSOA.ID, address.ID}}, + } { + problems, _ := validateZoneChanges(zone, current, changes) + if len(problems) == 0 { + t.Fatalf("allowed unrelated deletions during SOA repair: %v", changes.Deletes) + } + } + + moved := subSOA + moved.Name = "" + problems, _ := validateZoneChanges(zone, current, zoneChanges{SOAUpdate: &moved}) + if !slices.Contains(modelFindings(problems), modelFinding{subSOA.ID, "error", "cname_conflict"}) { + t.Fatalf("missed new conflict caused by the SOA move: %+v", problems) + } + + for _, changes := range []zoneChanges{ + {Deletes: []int64{subSOA.ID}}, + {Deletes: []int64{extraSOA.ID}}, + {Deletes: []int64{apexCNAME.ID, alias.ID}}, + } { + problems, _ := validateZoneChanges(zone, current, changes) + if len(problems) != 0 { + t.Fatalf("rejected repair %v: %+v", changes.Deletes, problems) + } + current = changes.finalRows(current) + } + if want := append(modelBaseZone(), address); !slices.Equal(current, want) { + t.Fatalf("repair changed other records: got %+v, want %+v", current, want) + } +} + +func TestDeleteApexCNAMEBeforeSOARepair(t *testing.T) { + const zone = "example.org." + base := modelBaseZone() + apexCNAME := modelRawRow(3, "", "CNAME", 3600, `{"host":"target.example."}`) + healthy := modelRawRow(4, "host", "A", 3600, `{"ip":"192.0.2.4"}`) + misplacedSOA := base[0] + misplacedSOA.Name = "sub" + for _, tc := range []struct { + name string + current []recordRow + restore zoneChanges + }{ + {"missing SOA", []recordRow{base[1], apexCNAME, healthy}, zoneChanges{Creates: base[:1]}}, + {"non-apex SOA", []recordRow{misplacedSOA, base[1], apexCNAME, healthy}, zoneChanges{SOAUpdate: &base[0]}}, + } { + t.Run(tc.name, func(t *testing.T) { + for _, changes := range []zoneChanges{ + {Deletes: []int64{apexCNAME.ID, healthy.ID}}, + {Creates: []recordRow{modelRawRow(5, "other", "A", 3600, `{"ip":"192.0.2.5"}`)}}, + } { + if problems, _ := validateZoneChanges(zone, tc.current, changes); len(problems) == 0 { + t.Fatalf("allowed unrelated change during SOA repair: %+v", changes) + } + } + deleteCNAME := zoneChanges{Deletes: []int64{apexCNAME.ID}} + if problems, _ := validateZoneChanges(zone, tc.current, deleteCNAME); len(problems) != 0 { + t.Fatalf("failed to clear the apex conflict: %+v", problems) + } + current := deleteCNAME.finalRows(tc.current) + if problems, _ := validateZoneChanges(zone, current, tc.restore); len(problems) != 0 { + t.Fatalf("failed to restore SOA: %+v", problems) + } + want := append(slices.Clone(base), healthy) + got := tc.restore.finalRows(current) + slices.SortFunc(got, func(a, b recordRow) int { return cmp.Compare(a.ID, b.ID) }) + if !slices.Equal(got, want) { + t.Fatalf("repair changed healthy records: got %+v, want %+v", got, want) + } + }) + } +} + func TestZoneRuleWarnings(t *testing.T) { creates := []recordRow{ modelRawRow(3, "alias", "CNAME", 3600, `{"host":"www.example.net."}`), diff --git a/scripts/test-e2e.sh b/scripts/test-e2e.sh index c7c1821..1e12584 100755 --- a/scripts/test-e2e.sh +++ b/scripts/test-e2e.sh @@ -30,6 +30,7 @@ runner_image="cdwu-e2e-runner:${run_id}" runner="${project}-runner" reports="e2e/reports/${project}" pulled_images= +compose_started=0 E2E_PROJECT=$project E2E_APP_IMAGE=$image @@ -44,39 +45,47 @@ compose() { docker compose --project-name "$project" --file e2e/compose.yaml --profile runner "$@" } -leftovers() { - { - docker ps -a --quiet --filter "label=com.docker.compose.project=${project}" - docker ps -a --quiet --filter "label=cdwu.e2e.run=${project}" - docker ps -a --quiet --filter "name=^${project}-" - } | sort -u +project_in_use() { + [ -e "$reports" ] || docker image inspect "$runner_image" >/dev/null 2>&1 || + [ -n "$(docker ps -aq --filter "name=^${project}-")" ] || + [ -n "$(docker volume ls -q --filter "name=^${project}-")" ] || + [ -n "$(docker network ls -q --filter "name=^${project}-")" ] || + [ -n "$(docker ps -aq --filter "label=com.docker.compose.project=${project}")" ] || + [ -n "$(docker ps -aq --filter "label=cdwu.e2e.run=${project}")" ] || + [ -n "$(docker volume ls -q --filter "label=cdwu.e2e.run=${project}")" ] || + [ -n "$(docker network ls -q --filter "label=cdwu.e2e.run=${project}")" ] } cleanup() { status=$1 trap - 0 INT TERM - docker rm --force --volumes "$runner" >/dev/null 2>&1 || true - compose down --volumes --remove-orphans --timeout 30 >/dev/null 2>&1 || true + if [ "$compose_started" -eq 1 ]; then + runner_id=$(docker ps -aq --filter "label=cdwu.e2e.run=${project}" --filter "name=^${runner}$") + if [ -n "$runner_id" ]; then + docker rm --force --volumes "$runner_id" >/dev/null 2>&1 || true + fi + compose down --volumes --remove-orphans --timeout 30 >/dev/null 2>&1 || true + fi leak=0 - containers=$(leftovers) + containers=$(docker ps -aq --filter "label=cdwu.e2e.run=${project}") if [ -n "$containers" ]; then echo "test-e2e: removing leftover containers: $(echo "$containers" | tr '\n' ' ')" >&2 echo "$containers" | xargs docker rm --force --volumes >/dev/null 2>&1 || true leak=1 fi - volumes=$({ docker volume ls --quiet --filter "label=com.docker.compose.project=${project}"; docker volume ls --quiet --filter "label=cdwu.e2e.run=${project}"; docker volume ls --quiet --filter "name=^${project}-"; } | sort -u) + volumes=$(docker volume ls -q --filter "label=cdwu.e2e.run=${project}") if [ -n "$volumes" ]; then echo "test-e2e: removing leftover volumes: $(echo "$volumes" | tr '\n' ' ')" >&2 echo "$volumes" | xargs docker volume rm --force >/dev/null 2>&1 || true leak=1 fi - networks=$({ docker network ls --quiet --filter "label=com.docker.compose.project=${project}"; docker network ls --quiet --filter "label=cdwu.e2e.run=${project}"; docker network ls --quiet --filter "name=^${project}-"; } | sort -u) + networks=$(docker network ls -q --filter "label=cdwu.e2e.run=${project}") if [ -n "$networks" ]; then echo "test-e2e: removing leftover networks: $(echo "$networks" | tr '\n' ' ')" >&2 echo "$networks" | xargs docker network rm >/dev/null 2>&1 || true leak=1 fi - if docker image inspect "$runner_image" >/dev/null 2>&1; then + if [ "$(docker image inspect --format '{{ index .Config.Labels "cdwu.e2e.run" }}' "$runner_image" 2>/dev/null)" = "$project" ]; then docker image rm "$runner_image" >/dev/null || leak=1 fi printf '%s' "$pulled_images" | while IFS= read -r pulled; do @@ -88,17 +97,19 @@ cleanup() { fi exit "$status" } -if [ -e "$reports" ] || docker image inspect "$runner_image" >/dev/null 2>&1 || [ -n "$(leftovers)" ]; then +if project_in_use; then echo "test-e2e: project name already in use: ${project}" >&2 exit 2 fi -trap 'cleanup "$?"' 0 -trap 'exit 130' INT TERM - if ! docker image inspect "$image" >/dev/null 2>&1; then echo "test-e2e: image $image not found; build it first (make docker)" >&2 exit 2 fi +mkdir -p e2e/reports +mkdir "$reports" +trap 'cleanup "$?"' 0 +trap 'exit 130' INT TERM + for pulled in "$playwright_image" "$mysql_image" "$coredns_image"; do if ! docker image inspect "$pulled" >/dev/null 2>&1; then docker pull --quiet "$pulled" >/dev/null @@ -115,9 +126,8 @@ docker build --quiet \ --tag "$runner_image" \ e2e >/dev/null -mkdir -p e2e/reports -mkdir "$reports" rc=0 +compose_started=1 compose run --no-TTY --name "$runner" runner || rc=$? if ! docker cp "${runner}:/e2e/reports/." "$reports/" >/dev/null 2>&1; then echo "test-e2e: no reports to copy" >&2 diff --git a/stores_test.go b/stores_test.go index 0445f94..3892137 100644 --- a/stores_test.go +++ b/stores_test.go @@ -492,7 +492,7 @@ func TestDelegationStore(t *testing.T) { if err != nil || len(zones) != 2 || !zones[0].ZoneExists || zones[1].ZoneExists || zones[1].Zone != "gone.org." { t.Fatal(zones, err) } - expectQuery(t, st.Calls()[3], "EXISTS (SELECT 1 FROM `coredns_records` r WHERE r.`zone` = d.`zone`)") + expectQuery(t, st.Calls()[3], "EXISTS (SELECT 1 FROM `coredns_records` r WHERE "+recordZoneKey("r.`zone`")+" = CAST(d.`zone` AS BINARY))") deleted, err := s.DeleteZoneDelegations(ctx, "a.org.") if err != nil || len(deleted) != 1 || deleted[0].Username != "carol" || deleted[0].CreatedBy != 1 { t.Fatal(deleted, err) diff --git a/type_webserver_test.go b/type_webserver_test.go index 2950a7f..20053c7 100644 --- a/type_webserver_test.go +++ b/type_webserver_test.go @@ -305,7 +305,7 @@ func TestLogConfigOmitsSecrets(t *testing.T) { } func serverDBHandler(columns [][]driver.Value) fdbHandler { - m := &migrationDB{tableCount: 1, version: int64(1)} + m := &migrationDB{tableCount: 1, version: int64(2)} return func(q string, args []any) fdbResponse { if strings.Contains(q, "information_schema.COLUMNS") && args[0] == "coredns_records" { return fdbResponse{rows: columns}