3 Commits
Author SHA1 Message Date
bryanpedini 440f78ce9e feat(ui): improve the records table, view state and record dialog
Test / test (push) Successful in 26m44s
Build and publish image / image (push) Successful in 27m27s
Sortable record columns, filters and sort kept in the URL on the zones,
zone and audit pages, a Show action that filters the records table to a
problem's owner, Save and add another, a highlight of the saved row, an
Audit history link on the zone page, and dialogs that keep typed input
on a backdrop click.
2026-11-22 17:36:46 +01:00
bryanpedini a67183b646 feat: manage TLSA records
Test / test (push) Successful in 28m4s
Build and publish image / image (push) Successful in 28m43s
2026-11-22 11:31:59 +01:00
bryanpedini 9c2fb9d15b feat(ui): rename the zone list problems column to status 2026-11-22 11:31:59 +01:00
22 changed files with 555 additions and 46 deletions

No files matched your search

+7 -5
View File
@@ -47,7 +47,7 @@ In scope:
- User management from the web UI for admins: create, change role, set password, delete. Deletion only sets `deleted_at`; the row stays in the database for the audit. - User management from the web UI for admins: create, change role, set password, delete. Deletion only sets `deleted_at`; the row stays in the database for the audit.
- Zone list with record counts, SOA serial and problem counts. - Zone list with record counts, SOA serial and problem counts.
- Zone creation (SOA and NS records in one transaction) and zone deletion, by admins. - Zone creation (SOA and NS records in one transaction) and zone deletion, by admins.
- Creation, editing and deletion of records of every type the plugin serves: `A`, `AAAA`, `CNAME`, `NS`, `MX`, `TXT`, `SRV`, `CAA`, `SOA`. Wildcard names are supported. - Creation, editing and deletion of records of every type the plugin serves: `A`, `AAAA`, `CNAME`, `NS`, `MX`, `TXT`, `SRV`, `CAA`, `TLSA`, `SOA`. Wildcard names are supported.
- Bulk deletion of records. - Bulk deletion of records.
- Automatic SOA serial management. - Automatic SOA serial management.
- Zone checks that report every row the plugin cannot serve correctly. - Zone checks that report every row the plugin cannot serve correctly.
@@ -94,7 +94,7 @@ The table belongs to the operator and is shared with CoreDNS and possibly with o
- `name`: the owner name relative to the zone, without trailing dot; the empty string is the apex. `*` as the complete leftmost label is a wildcard (`*`, `*.dev`). Names are matched through the column collation, so case does not affect lookups, but the application stores them lowercase. - `name`: the owner name relative to the zone, without trailing dot; the empty string is the apex. `*` as the complete leftmost label is a wildcard (`*`, `*.dev`). Names are matched through the column collation, so case does not affect lookups, but the application stores them lowercase.
- `ttl`: seconds. `0` is served as 360 seconds (the plugin's built-in default). The plugin scans the column into an unsigned integer, so a `NULL` or a negative value makes every query that reads the row fail with SERVFAIL. The application never writes `NULL` or negative values. - `ttl`: seconds. `0` is served as 360 seconds (the plugin's built-in default). The plugin scans the column into an unsigned integer, so a `NULL` or a negative value makes every query that reads the row fail with SERVFAIL. The application never writes `NULL` or negative values.
- `content`: a JSON object whose shape depends on the type (below). A `NULL` or a value that is not valid JSON makes every query that reads the row fail with SERVFAIL. - `content`: a JSON object whose shape depends on the type (below). A `NULL` or a value that is not valid JSON makes every query that reads the row fail with SERVFAIL.
- `record_type`: one of the nine uppercase type names. The plugin selects rows with a case-insensitive `IN (...)` and then dispatches on the exact string, so a lowercase `a` or an unknown type makes queries of that type answer NOTIMP. The application only writes the nine uppercase names. - `record_type`: one of the ten uppercase type names. The plugin selects rows with a case-insensitive `IN (...)` and then dispatches on the exact string, so a lowercase `a` or an unknown type makes queries of that type answer NOTIMP. The application only writes the ten uppercase names.
### Content JSON per type ### Content JSON per type
@@ -110,6 +110,7 @@ The keys are those of the plugin source (`types.go`). In particular the MX key i
| `TXT` | `{"text": "v=spf1 -all"}` | the plugin splits the text into 255-byte strings | | `TXT` | `{"text": "v=spf1 -all"}` | the plugin splits the text into 255-byte strings |
| `SRV` | `{"priority": 10, "weight": 5, "port": 443, "target": "host.example.org."}` | 0 to 65535 each, FQDN | | `SRV` | `{"priority": 10, "weight": 5, "port": 443, "target": "host.example.org."}` | 0 to 65535 each, FQDN |
| `CAA` | `{"flag": 0, "tag": "issue", "value": "ca.example.net"}` | | | `CAA` | `{"flag": 0, "tag": "issue", "value": "ca.example.net"}` | |
| `TLSA` | `{"usage": 3, "selector": 1, "matching_type": 1, "certificate": "0123...cdef"}` | 0 to 255 each, lowercase hex |
| `SOA` | `{"ns": "ns1.example.org.", "MBox": "hostmaster.example.org.", "refresh": 3600, "retry": 600, "expire": 604800, "minttl": 300, "serial": 2026111700}` | only at the apex | | `SOA` | `{"ns": "ns1.example.org.", "MBox": "hostmaster.example.org.", "refresh": 3600, "retry": 600, "expire": 604800, "minttl": 300, "serial": 2026111700}` | only at the apex |
The application writes content in a canonical form: the keys above in the order above, numbers as JSON numbers, no other keys. Rows written by other writers are read tolerantly (any key order, extra keys ignored) and rewritten in canonical form only when edited. The application writes content in a canonical form: the keys above in the order above, numbers as JSON numbers, no other keys. Rows written by other writers are read tolerantly (any key order, extra keys ignored) and rewritten in canonical form only when edited.
@@ -329,6 +330,7 @@ The CoreDNS user keeps `SELECT` on `coredns_records` only, so it cannot read pas
| `TXT` | 1 to 4096 bytes of printable ASCII without backslash | | `TXT` | 1 to 4096 bytes of printable ASCII without backslash |
| `SRV` | owner name starts with `_service._proto`; priority, weight, port 0 to 65535; target host or `.` | | `SRV` | owner name starts with `_service._proto`; priority, weight, port 0 to 65535; target host or `.` |
| `CAA` | flag `0` or `128`; tag 1 to 15 lowercase letters or digits (`issue`, `issuewild`, `iodef` suggested); value 1 to 1024 bytes of printable ASCII without backslash | | `CAA` | flag `0` or `128`; tag 1 to 15 lowercase letters or digits (`issue`, `issuewild`, `iodef` suggested); value 1 to 1024 bytes of printable ASCII without backslash |
| `TLSA` | usage, selector, matching type 0 to 255; certificate association data 1 to 65532 bytes as even-length hex, stored lowercase; matching type `1` needs 32 bytes, `2` needs 64 bytes |
| `SOA` | apex only; `ns` and `MBox` FQDN; refresh, retry, expire, minttl 0 to 2147483647 | | `SOA` | apex only; `ns` and `MBox` FQDN; refresh, retry, expire, minttl 0 to 2147483647 |
After field validation every record is converted to the `miekg/dns` RR the plugin would build from it and packed into a message; a record that does not pack is refused. This catches anything the field rules miss. After field validation every record is converted to the `miekg/dns` RR the plugin would build from it and packed into a message; a record that does not pack is refused. This catches anything the field rules miss.
@@ -586,7 +588,7 @@ Errors (the plugin fails or serves something different):
| `ttl_negative` | `ttl` below 0 | | `ttl_negative` | `ttl` below 0 |
| `content_null` | `content` is `NULL` | | `content_null` | `content` is `NULL` |
| `content_json` | `content` is not a JSON object | | `content_json` | `content` is not a JSON object |
| `type_unknown` | `record_type` not one of the nine uppercase names | | `type_unknown` | `record_type` not one of the ten uppercase names |
| `field_invalid` | a field missing or outside the per-type rules (the plugin skips or misserves the record) | | `field_invalid` | a field missing or outside the per-type rules (the plugin skips or misserves the record) |
| `name_not_fqdn` | host, target, `ns` or `MBox` without trailing dot | | `name_not_fqdn` | host, target, `ns` or `MBox` without trailing dot |
| `mx_priority_key` | MX content with `priority` and no `preference` | | `mx_priority_key` | MX content with `priority` and no `preference` |
@@ -783,7 +785,7 @@ Core flow:
1. Start the stack and wait for `/health`. 1. Start the stack and wait for `/health`.
2. The login page shows the bootstrap command; create the first admin through `docker exec ... /app user add <username> admin`, log in. 2. The login page shows the bootstrap command; create the first admin through `docker exec ... /app user add <username> admin`, log in.
3. Create a zone, wait for the plugin's zone reload, verify SOA and NS answers. 3. Create a zone, wait for the plugin's zone reload, verify SOA and NS answers.
4. Create, edit and delete records of all nine types, including wildcards, CNAME chains, null MX and SRV `.` targets, verifying each change with `dig` and the SOA serial bump. 4. Create, edit and delete records of all ten types, including wildcards, CNAME chains, null MX and SRV `.` targets, verifying each change with `dig` and the SOA serial bump.
5. Bulk delete; export; replace-import of the export produces no changes; merge and replace imports with diffs verified. 5. Bulk delete; export; replace-import of the export produces no changes; merge and replace imports with diffs verified.
6. Check panel and `check` CLI against rows broken on purpose through direct SQL (each error code), and the UI's repair of those rows. 6. Check panel and `check` CLI against rows broken on purpose through direct SQL (each error code), and the UI's repair of those rows.
7. Users and delegation: the admin creates two users with role `user` and a second admin from the Users page and delegates two zones to the first user. The first user sees and edits only those zones, verified with `dig`; the second sees no zone; both get `404` on every other zone and `403` on admin routes. Revoking a delegation takes effect on the next request of an open session; promotion and demotion likewise. Deleting a user ends their sessions and refuses their login; the row is still in MySQL with `deleted_at` set and its delegations and audit rows intact; creating a user with the same username is refused. The last active admin cannot be demoted or deleted. 7. Users and delegation: the admin creates two users with role `user` and a second admin from the Users page and delegates two zones to the first user. The first user sees and edits only those zones, verified with `dig`; the second sees no zone; both get `404` on every other zone and `403` on admin routes. Revoking a delegation takes effect on the next request of an open session; promotion and demotion likewise. Deleting a user ends their sessions and refuses their login; the row is still in MySQL with `deleted_at` set and its delegations and audit rows intact; creating a user with the same username is refused. The last active admin cannot be demoted or deleted.
@@ -831,7 +833,7 @@ Each phase ends with all tests green and its commits.
- The binary starts the HTTP server with no arguments and provides `help`, `version`, `healthcheck`, `user list|add|passwd|role|delete`, `check [zone]` and `audit [n]` with the documented output and exit codes. - The binary starts the HTTP server with no arguments and provides `help`, `version`, `healthcheck`, `user list|add|passwd|role|delete`, `check [zone]` and `audit [n]` with the documented output and exit codes.
- The application never creates or alters the records table, verifies its contract at startup and works with the least-privilege grants of section 6. - The application never creates or alters the records table, verifies its contract at startup and works with the least-privilege grants of section 6.
- Zones and records of all nine types can be created, edited and deleted from the UI; every write is validated, serialized per zone, protected by ETags, bumps a managed SOA serial once and is audited in the same transaction. - Zones and records of all ten types can be created, edited and deleted from the UI; every write is validated, serialized per zone, protected by ETags, bumps a managed SOA serial once and is audited in the same transaction.
- Admins see and do everything; users see and operate only on the zones delegated to them, on every page and API route. Admins create users, change roles, set passwords, delete users and delegate zones from the web UI. Usernames are unique across all users, deleted ones included; deleting a user only sets `deleted_at`; at least one active admin always remains. - Admins see and do everything; users see and operate only on the zones delegated to them, on every page and API route. Admins create users, change roles, set passwords, delete users and delegate zones from the web UI. Usernames are unique across all users, deleted ones included; deleting a user only sets `deleted_at`; at least one active admin always remains.
- Every operation of section 9 has exactly one audit row with the specified columns, reads and refused requests included, and the audit table is append-only. - Every operation of section 9 has exactly one audit row with the specified columns, reads and refused requests included, and the audit table is append-only.
- Every row written by the application is served by CoreDNS with exactly the entered data, verified end to end with `dig`. - Every row written by the application is served by CoreDNS with exactly the entered data, verified end to end with `dig`.
+3 -2
View File
@@ -9,7 +9,7 @@ The same binary starts the HTTP server when run without arguments and provides s
- Login with local users, sessions and password change. - Login with local users, sessions and password change.
- Two roles: `admin` sees and does everything, `user` sees and operates only on the zones delegated to them. - Two roles: `admin` sees and does everything, `user` sees and operates only on the zones delegated to them.
- Zone creation (SOA and NS records in one transaction) and deletion, by admins. - Zone creation (SOA and NS records in one transaction) and deletion, by admins.
- Creation, editing and deletion of records of every type the plugin serves: `A`, `AAAA`, `CNAME`, `NS`, `MX`, `TXT`, `SRV`, `CAA` and `SOA`. Wildcard names are supported. Bulk deletion of records. - Creation, editing and deletion of records of every type the plugin serves: `A`, `AAAA`, `CNAME`, `NS`, `MX`, `TXT`, `SRV`, `CAA`, `TLSA` and `SOA`. Wildcard names are supported. Bulk deletion of records.
- Automatic SOA serial management. - Automatic SOA serial management.
- A zone check that reports every row the plugin cannot serve correctly, with a repair path in the UI. - A zone check that reports every row the plugin cannot serve correctly, with a repair path in the UI.
- Zone file export and import (RFC 1035 master file format). - Zone file export and import (RFC 1035 master file format).
@@ -53,7 +53,7 @@ The application's own tables live in the same database, prefixed with `<prefix>w
- `zone`: the zone apex, lowercase, with the trailing dot (`example.org.`). The plugin lists zones with `SELECT DISTINCT zone`, so a zone exists as soon as one row carries it. - `zone`: the zone apex, lowercase, with the trailing dot (`example.org.`). The plugin lists zones with `SELECT DISTINCT zone`, so a zone exists as soon as one row carries it.
- `name`: the owner name relative to the zone, lowercase, without trailing dot. The empty string is the apex. `*` as the complete leftmost label is a wildcard. - `name`: the owner name relative to the zone, lowercase, without trailing dot. The empty string is the apex. `*` as the complete leftmost label is a wildcard.
- `ttl`: an integer from 0 to 2147483647. Never `NULL`, never negative. - `ttl`: an integer from 0 to 2147483647. Never `NULL`, never negative.
- `record_type`: one of the nine uppercase type names. - `record_type`: one of the ten uppercase type names.
- `content`: a JSON object in canonical form (keys in the order below, no other keys). Rows written by other writers are read tolerantly (any key order, extra keys ignored) and rewritten in canonical form only when edited. - `content`: a JSON object in canonical form (keys in the order below, no other keys). Rows written by other writers are read tolerantly (any key order, extra keys ignored) and rewritten in canonical form only when edited.
- Every host, target, `ns` and `MBox` is stored as a lowercase FQDN with the trailing dot, because the plugin does not make `NS`, `MX`, `SRV` and `SOA` names fully qualified and packing fails on names without it. - Every host, target, `ns` and `MBox` is stored as a lowercase FQDN with the trailing dot, because the plugin does not make `NS`, `MX`, `SRV` and `SOA` names fully qualified and packing fails on names without it.
@@ -67,6 +67,7 @@ The application's own tables live in the same database, prefixed with `<prefix>w
| `TXT` | `{"text": "v=spf1 -all"}`, 1 to 4096 bytes of printable ASCII without backslash | | `TXT` | `{"text": "v=spf1 -all"}`, 1 to 4096 bytes of printable ASCII without backslash |
| `SRV` | `{"priority": 10, "weight": 5, "port": 443, "target": "host.example.org."}`, the owner name starts with `_service._proto` | | `SRV` | `{"priority": 10, "weight": 5, "port": 443, "target": "host.example.org."}`, the owner name starts with `_service._proto` |
| `CAA` | `{"flag": 0, "tag": "issue", "value": "ca.example.net"}`, flag `0` or `128` | | `CAA` | `{"flag": 0, "tag": "issue", "value": "ca.example.net"}`, flag `0` or `128` |
| `TLSA` | `{"usage": 3, "selector": 1, "matching_type": 1, "certificate": "0123...cdef"}`, usage, selector and matching type 0 to 255, certificate association data as lowercase even-length hex (32 bytes for matching type `1`, 64 bytes for `2`); served only by a plugin build with TLSA support |
| `SOA` | `{"ns": "ns1.example.org.", "MBox": "hostmaster.example.org.", "refresh": 3600, "retry": 600, "expire": 604800, "minttl": 300, "serial": 2026111700}`, only at the apex | | `SOA` | `{"ns": "ns1.example.org.", "MBox": "hostmaster.example.org.", "refresh": 3600, "retry": 600, "expire": 604800, "minttl": 300, "serial": 2026111700}`, only at the apex |
After field validation every record is converted to the `miekg/dns` RR the plugin builds from it and packed into a message; a record that does not pack is refused. After field validation every record is converted to the `miekg/dns` RR the plugin builds from it and packed into a message; a record that does not pack is refused.
+8
View File
@@ -44,6 +44,7 @@ const IPV4: Field = { valid: ['192.0.2.55', '198.51.100.7', '203.0.113.200'], ho
const IPV6: Field = { valid: ['2001:db8::55', '2001:db8:0:0:0:0:0:56', '2001:DB8::57'], hostile: ['192.0.2.55', '::ffff:192.0.2.1', '2001:db8::g', SQL_INJECTION, SCRIPT, '', 1] }; const IPV6: Field = { valid: ['2001:db8::55', '2001:db8:0:0:0:0:0:56', '2001:DB8::57'], hostile: ['192.0.2.55', '::ffff:192.0.2.1', '2001:db8::g', SQL_INJECTION, SCRIPT, '', 1] };
const CAA_TAG: Field = { valid: ['issue', 'issuewild', 'iodef'], hostile: ['bad tag', SCRIPT, SQL_INJECTION, '', 'x'.repeat(256), 1] }; const CAA_TAG: Field = { valid: ['issue', 'issuewild', 'iodef'], hostile: ['bad tag', SCRIPT, SQL_INJECTION, '', 'x'.repeat(256), 1] };
const CAA_FLAG: Field = { valid: [0, 128], hostile: [256, -1, '0', SQL_INJECTION, null] }; const CAA_FLAG: Field = { valid: [0, 128], hostile: [256, -1, '0', SQL_INJECTION, null] };
const OCTET: Field = { valid: [0, 1, 2, 3, 255], hostile: [256, -1, '3', 1.5, null, SQL_INJECTION] };
const SOA_TIMER: Field = { valid: [60, 3600, 604800, 2147483647], hostile: [0, -1, 2147483648, 4294967296, '3600', null, SQL_INJECTION] }; const SOA_TIMER: Field = { valid: [60, 3600, 604800, 2147483647], hostile: [0, -1, 2147483648, 4294967296, '3600', null, SQL_INJECTION] };
function hosts(zone: string): Field { function hosts(zone: string): Field {
@@ -71,6 +72,13 @@ function fields(zone: string, type: RecordType): Record<string, Field> {
return { priority: U16, weight: U16, port: U16, target: { valid: ['sip.example.net.', '.'], hostile: host.hostile } }; return { priority: U16, weight: U16, port: U16, target: { valid: ['sip.example.net.', '.'], hostile: host.hostile } };
case 'CAA': case 'CAA':
return { flag: CAA_FLAG, tag: CAA_TAG, value: { valid: TEXT.valid.filter((t) => t !== '' && String(t).length < 256), hostile: TEXT.hostile } }; return { flag: CAA_FLAG, tag: CAA_TAG, value: { valid: TEXT.valid.filter((t) => t !== '' && String(t).length < 256), hostile: TEXT.hostile } };
case 'TLSA':
return {
usage: OCTET,
selector: OCTET,
matching_type: { valid: [0], hostile: OCTET.hostile },
certificate: { valid: ['0123456789abcdef', '30' + 'AB'.repeat(40), 'ff'], hostile: ['', 'abc', 'xyz0', '0x1234', 'ab cd', SCRIPT, SQL_INJECTION, 7, null] },
};
case 'SOA': case 'SOA':
return { return {
ns: { valid: ['ns1.example.net.', `ns1.${zone}`], hostile: host.hostile }, ns: { valid: ['ns1.example.net.', `ns1.${zone}`], hostile: host.hostile },
+6 -1
View File
@@ -3,7 +3,7 @@
import { expect } from '@playwright/test'; import { expect } from '@playwright/test';
export const TYPES = ['A', 'AAAA', 'CNAME', 'NS', 'MX', 'TXT', 'SRV', 'CAA', 'SOA'] as const; export const TYPES = ['A', 'AAAA', 'CNAME', 'NS', 'MX', 'TXT', 'SRV', 'CAA', 'TLSA', 'SOA'] as const;
export type RecordType = (typeof TYPES)[number]; export type RecordType = (typeof TYPES)[number];
export const EDITABLE_TYPES = TYPES.filter((t) => t !== 'SOA'); export const EDITABLE_TYPES = TYPES.filter((t) => t !== 'SOA');
@@ -16,6 +16,7 @@ export const CANONICAL_KEYS: Readonly<Record<RecordType, readonly string[]>> = {
TXT: ['text'], TXT: ['text'],
SRV: ['priority', 'weight', 'port', 'target'], SRV: ['priority', 'weight', 'port', 'target'],
CAA: ['flag', 'tag', 'value'], CAA: ['flag', 'tag', 'value'],
TLSA: ['usage', 'selector', 'matching_type', 'certificate'],
SOA: ['ns', 'MBox', 'refresh', 'retry', 'expire', 'minttl', 'serial'], SOA: ['ns', 'MBox', 'refresh', 'retry', 'expire', 'minttl', 'serial'],
}; };
@@ -92,6 +93,8 @@ export function digData(type: RecordType, d: RecordData): string {
return `${d.priority} ${d.weight} ${d.port} ${d.target}`; return `${d.priority} ${d.weight} ${d.port} ${d.target}`;
case 'CAA': case 'CAA':
return `${d.flag} ${d.tag} ${dnsQuote(String(d.value))}`; return `${d.flag} ${d.tag} ${dnsQuote(String(d.value))}`;
case 'TLSA':
return `${d.usage} ${d.selector} ${d.matching_type} ${d.certificate}`;
case 'SOA': case 'SOA':
return `${d.ns} ${d.MBox} ${d.serial} ${d.refresh} ${d.retry} ${d.expire} ${d.minttl}`; return `${d.ns} ${d.MBox} ${d.serial} ${d.refresh} ${d.retry} ${d.expire} ${d.minttl}`;
} }
@@ -113,6 +116,8 @@ export function uiValue(type: RecordType, d: RecordData): string {
return `${d.priority} ${d.weight} ${d.port} ${d.target}`; return `${d.priority} ${d.weight} ${d.port} ${d.target}`;
case 'CAA': case 'CAA':
return `${d.flag} ${d.tag} "${d.value}"`; return `${d.flag} ${d.tag} "${d.value}"`;
case 'TLSA':
return `${d.usage} ${d.selector} ${d.matching_type} ${d.certificate}`;
case 'SOA': case 'SOA':
return [d.ns, d.MBox, d.serial ?? 'dynamic', d.refresh, d.retry, d.expire, d.minttl].join(' '); return [d.ns, d.MBox, d.serial ?? 'dynamic', d.refresh, d.retry, d.expire, d.minttl].join(' ');
} }
+15 -2
View File
@@ -7,7 +7,7 @@ import type { GroupConfig } from './env';
import type { RecordRow } from './mysql'; import type { RecordRow } from './mysql';
import type { Recorder } from './recorder'; import type { Recorder } from './recorder';
export const PLUGIN_TYPES = ['A', 'AAAA', 'CNAME', 'NS', 'MX', 'TXT', 'SRV', 'CAA', 'SOA']; export const PLUGIN_TYPES = ['A', 'AAAA', 'CNAME', 'NS', 'MX', 'TXT', 'SRV', 'CAA', 'TLSA', 'SOA'];
const MAX_CNAME_CHAIN = 10; const MAX_CNAME_CHAIN = 10;
const DEFAULT_TTL = 360; const DEFAULT_TTL = 360;
@@ -123,6 +123,14 @@ function rrFor(row: RecordRow, now: () => number): ModelRR | null {
if (str(c.value) === '' || str(c.tag) === '') return null; if (str(c.value) === '' || str(c.tag) === '') return null;
return { name: owner, ttl, type: 'CAA', data: `${u32(c.flag) & 0xff} ${str(c.tag)} ${quote(str(c.value))}` }; return { name: owner, ttl, type: 'CAA', data: `${u32(c.flag) & 0xff} ${str(c.tag)} ${quote(str(c.value))}` };
} }
case 'TLSA': {
const octet = (v: unknown) => typeof v === 'number' && Number.isInteger(v) && v >= 0 && v <= 255;
if (!octet(c.usage) || !octet(c.selector) || !octet(c.matching_type)) throw new ModelFailure('SERVFAIL');
const cert = str(c.certificate);
if (cert === '' || cert.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(cert)) throw new ModelFailure('SERVFAIL');
if ((c.matching_type === 1 && cert.length !== 64) || (c.matching_type === 2 && cert.length !== 128)) throw new ModelFailure('SERVFAIL');
return { name: owner, ttl, type: 'TLSA', data: `${c.usage} ${c.selector} ${c.matching_type} ${cert.toLowerCase()}` };
}
case 'SOA': { case 'SOA': {
const serial = u32(c.serial) === 0 ? now() : u32(c.serial); const serial = u32(c.serial) === 0 ? now() : u32(c.serial);
return { return {
@@ -242,12 +250,17 @@ export class PluginModel {
} }
} }
function tlsaData(data: string): string {
const [usage, selector, matching, ...certificate] = data.trim().split(/\s+/);
return `${usage} ${selector} ${matching} ${certificate.join('').toLowerCase()}`;
}
function canon(rrs: Array<ModelRR | DigRR>, wildcardOk: string): string[] { function canon(rrs: Array<ModelRR | DigRR>, wildcardOk: string): string[] {
return rrs return rrs
.map((r) => { .map((r) => {
const name = r.name.toLowerCase(); const name = r.name.toLowerCase();
const n = name.startsWith('*.') ? wildcardOk : name; const n = name.startsWith('*.') ? wildcardOk : name;
const data = r.type === 'SOA' ? r.data.toLowerCase().replace(/^(\S+ \S+) \d+/, '$1 SERIAL') : r.data; const data = r.type === 'SOA' ? r.data.toLowerCase().replace(/^(\S+ \S+) \d+/, '$1 SERIAL') : r.type === 'TLSA' ? tlsaData(r.data) : r.data;
return `${n} ${r.ttl} ${r.type} ${data}`; return `${n} ${r.ttl} ${r.type} ${data}`;
}) })
.sort(); .sort();
+8
View File
@@ -168,6 +168,8 @@ test.describe('core flow', () => {
nosrv: { name: '_none._tcp', type: 'SRV', ttl: 3600, data: { priority: 0, weight: 0, port: 0, target: '.' } }, nosrv: { name: '_none._tcp', type: 'SRV', ttl: 3600, data: { priority: 0, weight: 0, port: 0, target: '.' } },
caa: { name: '', type: 'CAA', ttl: 3600, data: { flag: 0, tag: 'issue', value: 'ca.example.net' } }, caa: { name: '', type: 'CAA', ttl: 3600, data: { flag: 0, tag: 'issue', value: 'ca.example.net' } },
iodef: { name: '', type: 'CAA', ttl: 3600, data: { flag: 128, tag: 'iodef', value: 'mailto:security@example.net' } }, iodef: { name: '', type: 'CAA', ttl: 3600, data: { flag: 128, tag: 'iodef', value: 'mailto:security@example.net' } },
tlsa: { name: '_25._tcp.mail', type: 'TLSA', ttl: 3600, data: { usage: 3, selector: 1, matching_type: 1, certificate: '0123456789abcdef'.repeat(4) } },
tlsafull: { name: '_443._tcp.www', type: 'TLSA', ttl: 300, data: { usage: 0, selector: 1, matching_type: 0, certificate: '302a300506032b6570032100d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a' } },
sub: { name: 'sub', type: 'NS', ttl: 3600, data: { host: 'ns.example.net.' } }, sub: { name: 'sub', type: 'NS', ttl: 3600, data: { host: 'ns.example.net.' } },
wild: { name: '*', type: 'A', ttl: 0, data: { ip: '192.0.2.99' } }, wild: { name: '*', type: 'A', ttl: 0, data: { ip: '192.0.2.99' } },
wilddev: { name: '*.dev', type: 'TXT', ttl: 600, data: { text: 'wildcard dev' } }, wilddev: { name: '*.dev', type: 'TXT', ttl: 600, data: { text: 'wildcard dev' } },
@@ -235,6 +237,8 @@ test.describe('core flow', () => {
await add('SRV with the . target', R.nosrv, input(R.nosrv, { priority: '0', weight: '0', port: '0', target: '.' })); await add('SRV with the . target', R.nosrv, input(R.nosrv, { priority: '0', weight: '0', port: '0', target: '.' }));
await add('CAA issue', R.caa, input(R.caa, { flag: '0', tag: 'issue', value: 'ca.example.net' })); await add('CAA issue', R.caa, input(R.caa, { flag: '0', tag: 'issue', value: 'ca.example.net' }));
await add('CAA iodef critical', R.iodef, input(R.iodef, { flag: '128', tag: 'iodef', value: 'mailto:security@example.net' })); await add('CAA iodef critical', R.iodef, input(R.iodef, { flag: '128', tag: 'iodef', value: 'mailto:security@example.net' }));
await add('TLSA DANE-EE SHA-256 pasted with colons and uppercase', R.tlsa, input(R.tlsa, { usage: '3', selector: '1', matching_type: '1', certificate: '01:23:45:67:89:AB:CD:EF:'.repeat(4).slice(0, -1) }));
await add('TLSA with zero usage and exact match', R.tlsafull, input(R.tlsafull, { usage: '0', selector: '1', matching_type: '0', certificate: String(R.tlsafull.data.certificate) }));
await add('NS of a delegated subdomain', R.sub, input(R.sub, { host: 'ns.example.net' })); await add('NS of a delegated subdomain', R.sub, input(R.sub, { host: 'ns.example.net' }));
await add('wildcard A with TTL 0', R.wild, input(R.wild, { ip: '192.0.2.99' })); await add('wildcard A with TTL 0', R.wild, input(R.wild, { ip: '192.0.2.99' }));
await adminUi.expectRow({ name: '*', type: 'A', value: '192.0.2.99', ttl: 'default (360 s)' }); await adminUi.expectRow({ name: '*', type: 'A', value: '192.0.2.99', ttl: 'default (360 s)' });
@@ -271,6 +275,9 @@ test.describe('core flow', () => {
R.srv = { ...R.srv, data: { ...R.srv.data, port: 5061 } }; R.srv = { ...R.srv, data: { ...R.srv.data, port: 5061 } };
await edit('edit CAA value', R.iodef, { ...R.iodef, data: { flag: 128, tag: 'iodef', value: 'mailto:dns@example.net' } }, input(R.iodef, { flag: '128', tag: 'iodef', value: 'mailto:dns@example.net' })); await edit('edit CAA value', R.iodef, { ...R.iodef, data: { flag: 128, tag: 'iodef', value: 'mailto:dns@example.net' } }, input(R.iodef, { flag: '128', tag: 'iodef', value: 'mailto:dns@example.net' }));
R.iodef = { ...R.iodef, data: { flag: 128, tag: 'iodef', value: 'mailto:dns@example.net' } }; R.iodef = { ...R.iodef, data: { flag: 128, tag: 'iodef', value: 'mailto:dns@example.net' } };
const sha512 = 'fedcba9876543210'.repeat(8);
await edit('edit TLSA to SHA-512', R.tlsa, { ...R.tlsa, data: { usage: 2, selector: 0, matching_type: 2, certificate: sha512 } }, input(R.tlsa, { usage: '2', selector: '0', matching_type: '2', certificate: sha512 }));
R.tlsa = { ...R.tlsa, data: { usage: 2, selector: 0, matching_type: 2, certificate: sha512 } };
await edit('edit NS host', R.sub, { ...R.sub, data: { host: 'ns2.example.net.' } }, input(R.sub, { host: 'ns2.example.net.' })); await edit('edit NS host', R.sub, { ...R.sub, data: { host: 'ns2.example.net.' } }, input(R.sub, { host: 'ns2.example.net.' }));
R.sub = { ...R.sub, data: { host: 'ns2.example.net.' } }; R.sub = { ...R.sub, data: { host: 'ns2.example.net.' } };
await edit('edit wildcard address', R.wild, { ...R.wild, data: { ip: '192.0.2.98' } }, input(R.wild, { ip: '192.0.2.98' })); await edit('edit wildcard address', R.wild, { ...R.wild, data: { ip: '192.0.2.98' } }, input(R.wild, { ip: '192.0.2.98' }));
@@ -287,6 +294,7 @@ test.describe('core flow', () => {
await del('delete long TXT', R.longtxt); await del('delete long TXT', R.longtxt);
await del('delete SRV with the . target', R.nosrv); await del('delete SRV with the . target', R.nosrv);
await del('delete CAA', R.iodef); await del('delete CAA', R.iodef);
await del('delete TLSA', R.tlsafull);
await del('delete NS of the subdomain', R.sub); await del('delete NS of the subdomain', R.sub);
await del('delete wildcard TXT', R.wilddev); await del('delete wildcard TXT', R.wilddev);
await del('delete one A of an RRset', R.www2); await del('delete one A of an RRset', R.www2);
+1
View File
@@ -132,6 +132,7 @@ test('seeded requests cover every API operation, path parameter, filter and DNS
TXT: { text: 'random fixture' }, TXT: { text: 'random fixture' },
SRV: { priority: 0, weight: 0, port: 0, target: '.' }, SRV: { priority: 0, weight: 0, port: 0, target: '.' },
CAA: { flag: 0, tag: 'issue', value: 'ca.example.net' }, CAA: { flag: 0, tag: 'issue', value: 'ca.example.net' },
TLSA: { usage: 3, selector: 1, matching_type: 1, certificate: '0123456789abcdef'.repeat(4) },
SOA: { ns: 'ns.example.net.', MBox: 'hostmaster.example.net.', refresh: 3600, retry: 600, expire: 604800, minttl: 300 }, SOA: { ns: 'ns.example.net.', MBox: 'hostmaster.example.net.', refresh: 3600, retry: 600, expire: 604800, minttl: 300 },
}; };
for (const [type, data] of Object.entries(types)) { for (const [type, data] of Object.entries(types)) {
+81 -1
View File
@@ -4,7 +4,7 @@
import { test, expect } from '../harness/fixtures'; import { test, expect } from '../harness/fixtures';
import type { RecordInput } from '../harness/ui'; import type { RecordInput } from '../harness/ui';
import { up } from '../harness/api'; import { up } from '../harness/api';
import { addAddress, checkZone, createZone } from '../harness/personas'; import { addAddress, address, checkZone, createZone } from '../harness/personas';
test.use({ group: 'stupid' }); test.use({ group: 'stupid' });
@@ -70,3 +70,83 @@ test('operator mistakes preserve DNS, user records and delegations', async ({ wo
expect((await api.get(zonePath)).status).toBe(404); expect((await api.get(zonePath)).status).toBe(404);
expect(await world.db.records(zone)).toEqual([]); expect(await world.db.records(zone)).toEqual([]);
}); });
test('records page keeps its view in the URL and protects typed input', async ({ world }) => {
const admin = await world.bootstrapAdmin();
const api = await world.apiAs(admin);
const ui = await world.uiAs(admin);
const zone = world.zoneName();
const zonePath = await createZone(api, zone);
await addAddress(api, zonePath, 'zeta', '192.0.2.40');
await addAddress(api, zonePath, 'alpha', '192.0.2.41');
await addAddress(api, zonePath, 'www', '192.0.2.42');
await addAddress(api, zonePath, 'www2', '192.0.2.44');
const mixed = await api.post(`${zonePath}/records`, address('www', '192.0.2.43', 600));
expect(mixed.status, mixed.text).toBe(201);
await ui.openZone(zone);
const page = ui.page;
const names = async () => (await ui.rows()).map((row) => row.name);
const nameHeader = page.locator('#records-table th[data-sort=name]');
await nameHeader.getByRole('button').click();
await expect(nameHeader).toHaveAttribute('aria-sort', 'ascending');
expect(await names()).toEqual(['@', '@', 'alpha', 'www', 'www', 'www2', 'zeta']);
await nameHeader.getByRole('button').click();
await expect(nameHeader).toHaveAttribute('aria-sort', 'descending');
expect(await names()).toEqual(['zeta', 'www2', 'www', 'www', 'alpha', '@', '@']);
await page.locator('#filter-text').fill('alpha');
await expect(page).toHaveURL(/[?&]q=alpha(&|$)/);
await expect(page).toHaveURL(/[?&]sort=-name(&|$)/);
await page.reload();
await ui.settle();
await expect(page.locator('#filter-text')).toHaveValue('alpha');
await expect(nameHeader).toHaveAttribute('aria-sort', 'descending');
expect(await names()).toEqual(['alpha']);
await page.getByRole('button', { name: 'Show www A in the records table' }).first().click();
await expect(page.locator('#filter-text')).toHaveValue(`www.${zone}`);
await expect(page.locator('#filter-type')).toHaveValue('A');
await expect(page.locator('#filter-text')).toBeFocused();
expect(await names()).toEqual(['www', 'www']);
await expect(page).toHaveURL(/[?&]name=www\./);
await page.locator('#filter-text').fill('');
await page.locator('#filter-type').selectOption('');
const dialog = page.locator('#record-dialog');
await page.click('#record-add');
await page.fill('#rec-name', 'unsaved');
await page.mouse.click(4, 4);
await expect(dialog, 'a backdrop click keeps an edited form open').toBeVisible();
await page.keyboard.press('Escape');
await expect(dialog).toBeHidden();
await page.click('#record-add');
await page.mouse.click(4, 4);
await expect(dialog, 'a backdrop click closes an untouched form').toBeHidden();
await page.click('#record-add');
await page.fill('#rec-name', 'multi');
await page.fill('#rec-f-ip', '192.0.2.50');
const first = page.waitForResponse((res) => res.url().endsWith(`/api/v1${zonePath}/records`) && res.request().method() === 'POST');
await page.click('#rec-submit-another');
expect((await first).status()).toBe(201);
await expect(dialog).toBeVisible();
await expect(page.locator('#rec-name')).toHaveValue('multi');
await expect(page.locator('#rec-f-ip')).toHaveValue('');
await expect(page.locator('#rec-f-ip')).toBeFocused();
await expect(page.locator('#rec-status')).toContainText('Record added.');
await page.fill('#rec-f-ip', '192.0.2.51');
const second = page.waitForResponse((res) => res.url().endsWith(`/api/v1${zonePath}/records`) && res.request().method() === 'POST');
await page.click('#rec-submit');
expect((await second).status()).toBe(201);
await expect(dialog).toBeHidden();
await expect(page.locator('#records-body tr.row-flash')).toHaveCount(1);
await expect(page.locator('#records-body tr.row-flash th')).toHaveText('multi');
await ui.settle();
expect((await world.db.records(zone)).filter((row) => row.name === 'multi').length).toBe(2);
await page.click('#audit-link');
await ui.settle();
await expect(page.locator('#af-zone')).toHaveValue(zone);
await expect(page.locator('#af-kind')).toHaveValue('change');
await expect(page.locator('#audit-body tr:not(.detail-row)').first()).toContainText(zone);
});
+12 -1
View File
@@ -68,6 +68,13 @@ type caaData struct {
Value string `json:"value"` Value string `json:"value"`
} }
type tlsaData struct {
Usage uint8 `json:"usage"`
Selector uint8 `json:"selector"`
MatchingType uint8 `json:"matching_type"`
Certificate string `json:"certificate"`
}
type soaData struct { type soaData struct {
NS string `json:"ns"` NS string `json:"ns"`
MBox string `json:"MBox"` MBox string `json:"MBox"`
@@ -182,7 +189,7 @@ func fieldDescription(kind reflect.Kind) string {
func encodeRecord(data any) (string, error) { func encodeRecord(data any) (string, error) {
switch data.(type) { switch data.(type) {
case aData, aaaaData, cnameData, nsData, mxData, txtData, srvData, caaData, soaData: case aData, aaaaData, cnameData, nsData, mxData, txtData, srvData, caaData, tlsaData, soaData:
encoded, err := json.Marshal(data) encoded, err := json.Marshal(data)
return string(encoded), err return string(encoded), err
default: default:
@@ -307,6 +314,10 @@ func buildRecordRR(row recordRow, data any, now time.Time) (dns.RR, error) {
if v.Tag != "" && v.Value != "" { if v.Tag != "" && v.Value != "" {
return &dns.CAA{Hdr: header, Flag: v.Flag, Tag: v.Tag, Value: v.Value}, nil return &dns.CAA{Hdr: header, Flag: v.Flag, Tag: v.Tag, Value: v.Value}, nil
} }
case tlsaData:
if v.Certificate != "" {
return &dns.TLSA{Hdr: header, Usage: v.Usage, Selector: v.Selector, MatchingType: v.MatchingType, Certificate: v.Certificate}, nil
}
case soaData: case soaData:
if v.Serial == 0 { if v.Serial == 0 {
v.Serial = uint32(now.Unix()) v.Serial = uint32(now.Unix())
+18 -1
View File
@@ -47,6 +47,8 @@ func TestRecordCanonicalEncodingAndPluginRR(t *testing.T) {
{"SRV", "_https._tcp.dev", `{"port":443,"weight":0,"priority":65535,"target":"@"}`, `{"priority":65535,"weight":0,"port":443,"target":"example.org."}`, "65535 0 443 example.org."}, {"SRV", "_https._tcp.dev", `{"port":443,"weight":0,"priority":65535,"target":"@"}`, `{"priority":65535,"weight":0,"port":443,"target":"example.org."}`, "65535 0 443 example.org."},
{"SRV", "_https._tcp", `{"port":0,"weight":65535,"priority":0,"target":"."}`, `{"priority":0,"weight":65535,"port":0,"target":"."}`, "0 65535 0 ."}, {"SRV", "_https._tcp", `{"port":0,"weight":65535,"priority":0,"target":"."}`, `{"priority":0,"weight":65535,"port":0,"target":"."}`, "0 65535 0 ."},
{"CAA", "", `{"value":"ca.example.net","tag":"issue","flag":0}`, `{"flag":0,"tag":"issue","value":"ca.example.net"}`, `0 issue "ca.example.net"`}, {"CAA", "", `{"value":"ca.example.net","tag":"issue","flag":0}`, `{"flag":0,"tag":"issue","value":"ca.example.net"}`, `0 issue "ca.example.net"`},
{"TLSA", "_25._tcp.mail", `{"certificate":"0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF","matching_type":1,"selector":1,"usage":3}`, `{"usage":3,"selector":1,"matching_type":1,"certificate":"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"}`, "3 1 1 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"},
{"TLSA", "_443._tcp", `{"usage":255,"selector":255,"matching_type":255,"certificate":"00"}`, `{"usage":255,"selector":255,"matching_type":255,"certificate":"00"}`, "255 255 255 00"},
{"SOA", "@", `{"MBox":"First.Last@EXAMPLE.ORG","ns":"Ns.Example.Net","serial":4294967295,"minttl":0,"expire":2147483647,"retry":600,"refresh":3600}`, {"SOA", "@", `{"MBox":"First.Last@EXAMPLE.ORG","ns":"Ns.Example.Net","serial":4294967295,"minttl":0,"expire":2147483647,"retry":600,"refresh":3600}`,
`{"ns":"ns.example.net.","MBox":"first\\.last.example.org.","refresh":3600,"retry":600,"expire":2147483647,"minttl":0,"serial":4294967295}`, `{"ns":"ns.example.net.","MBox":"first\\.last.example.org.","refresh":3600,"retry":600,"expire":2147483647,"minttl":0,"serial":4294967295}`,
`ns.example.net. first\.last.example.org. 4294967295 3600 600 2147483647 0`}, `ns.example.net. first\.last.example.org. 4294967295 3600 600 2147483647 0`},
@@ -132,6 +134,21 @@ func TestRecordFieldValidation(t *testing.T) {
{"CAA", "x", `{"flag":0,"tag":"Issue","value":"ca.example"}`, "tag", 0}, {"CAA", "x", `{"flag":0,"tag":"Issue","value":"ca.example"}`, "tag", 0},
{"CAA", "x", `{"flag":0,"tag":"a1234567890abcde","value":"ca.example"}`, "tag", 0}, {"CAA", "x", `{"flag":0,"tag":"a1234567890abcde","value":"ca.example"}`, "tag", 0},
{"CAA", "x", `{"flag":0,"tag":"issue","value":""}`, "value", 0}, {"CAA", "x", `{"flag":0,"tag":"issue","value":""}`, "value", 0},
{"TLSA", "_25._tcp", `{"usage":0,"selector":0,"matching_type":0,"certificate":"ab"}`, "", 0},
{"TLSA", "_25._tcp", `{"usage":3,"selector":1,"matching_type":1,"certificate":"` + strings.Repeat("ab", 32) + `"}`, "", 0},
{"TLSA", "_25._tcp", `{"usage":3,"selector":1,"matching_type":1,"certificate":"` + strings.Repeat("ab", 31) + `"}`, "certificate", 0},
{"TLSA", "_25._tcp", `{"usage":3,"selector":1,"matching_type":2,"certificate":"` + strings.Repeat("ab", 64) + `"}`, "", 0},
{"TLSA", "_25._tcp", `{"usage":3,"selector":1,"matching_type":2,"certificate":"` + strings.Repeat("ab", 32) + `"}`, "certificate", 0},
{"TLSA", "_25._tcp", `{"usage":3,"selector":1,"matching_type":0,"certificate":""}`, "certificate", 0},
{"TLSA", "_25._tcp", `{"usage":3,"selector":1,"matching_type":0,"certificate":"abc"}`, "certificate", 0},
{"TLSA", "_25._tcp", `{"usage":3,"selector":1,"matching_type":0,"certificate":"not-hex"}`, "certificate", 0},
{"TLSA", "_25._tcp", `{"usage":3,"selector":1,"matching_type":0,"certificate":"0x12"}`, "certificate", 0},
{"TLSA", "_25._tcp", `{"usage":3,"selector":1,"matching_type":0,"certificate":"` + strings.Repeat("ab", 65533) + `"}`, "certificate", 0},
{"TLSA", "_25._tcp", `{"usage":256,"selector":1,"matching_type":0,"certificate":"ab"}`, "usage", 0},
{"TLSA", "_25._tcp", `{"usage":3,"selector":-1,"matching_type":0,"certificate":"ab"}`, "selector", 0},
{"TLSA", "_25._tcp", `{"usage":3,"selector":1,"matching_type":"1","certificate":"ab"}`, "matching_type", 0},
{"TLSA", "_25._tcp", `{"selector":1,"matching_type":0,"certificate":"ab"}`, "usage", 0},
{"TLSA", "_25._tcp", `{"usage":3,"selector":1,"matching_type":0}`, "certificate", 0},
{"SOA", "child", `{"ns":"ns.example.","MBox":"hostmaster.example.","refresh":0,"retry":0,"expire":0,"minttl":0}`, "name", 0}, {"SOA", "child", `{"ns":"ns.example.","MBox":"hostmaster.example.","refresh":0,"retry":0,"expire":0,"minttl":0}`, "name", 0},
{"SOA", "@", `{"ns":"ns.example.","MBox":"hostmaster.example.","refresh":2147483648,"retry":0,"expire":0,"minttl":0}`, "refresh", 0}, {"SOA", "@", `{"ns":"ns.example.","MBox":"hostmaster.example.","refresh":2147483648,"retry":0,"expire":0,"minttl":0}`, "refresh", 0},
{"SOA", "@", `{"ns":"ns.example.","MBox":"hostmaster.example.","refresh":0,"retry":0,"expire":0,"minttl":0,"serial":4294967296}`, "serial", 0}, {"SOA", "@", `{"ns":"ns.example.","MBox":"hostmaster.example.","refresh":0,"retry":0,"expire":0,"minttl":0,"serial":4294967296}`, "serial", 0},
@@ -190,7 +207,7 @@ func TestPluginRRLegacyRows(t *testing.T) {
if rr, err := recordRR(soa, modelNow); err != nil || rr.Header().Name != soa.Zone || rr.(*dns.SOA).Serial != uint32(modelNow.Unix()) { if rr, err := recordRR(soa, modelNow); err != nil || rr.Header().Name != soa.Zone || rr.(*dns.SOA).Serial != uint32(modelNow.Unix()) {
t.Fatalf("raw populated SOA = %v, %v", rr, err) t.Fatalf("raw populated SOA = %v, %v", rr, err)
} }
for _, typ := range []string{"A", "AAAA", "CNAME", "NS", "MX", "TXT", "SRV", "CAA"} { for _, typ := range []string{"A", "AAAA", "CNAME", "NS", "MX", "TXT", "SRV", "CAA", "TLSA"} {
row := modelRawRow(1, "child", typ, 0, `{}`) row := modelRawRow(1, "child", typ, 0, `{}`)
if rr, err := recordRR(row, modelNow); rr != nil || err != nil || recordValue(row, modelNow) != "{}" { if rr, err := recordRR(row, modelNow); rr != nil || err != nil || recordValue(row, modelNow) != "{}" {
t.Errorf("raw empty %s = %v, %v", typ, rr, err) t.Errorf("raw empty %s = %v, %v", typ, rr, err)
+16
View File
@@ -5,6 +5,7 @@ package main
import ( import (
"cmp" "cmp"
"encoding/hex"
"errors" "errors"
"net/netip" "net/netip"
"reflect" "reflect"
@@ -31,6 +32,7 @@ var recordRules = map[string]recordTypeRule{
"TXT": {dns.TypeTXT, reflect.TypeFor[txtData]()}, "TXT": {dns.TypeTXT, reflect.TypeFor[txtData]()},
"SRV": {dns.TypeSRV, reflect.TypeFor[srvData]()}, "SRV": {dns.TypeSRV, reflect.TypeFor[srvData]()},
"CAA": {dns.TypeCAA, reflect.TypeFor[caaData]()}, "CAA": {dns.TypeCAA, reflect.TypeFor[caaData]()},
"TLSA": {dns.TypeTLSA, reflect.TypeFor[tlsaData]()},
"SOA": {dns.TypeSOA, reflect.TypeFor[soaData]()}, "SOA": {dns.TypeSOA, reflect.TypeFor[soaData]()},
} }
@@ -120,6 +122,20 @@ func normalizeRecordData(zone string, data any) (any, map[string]string) {
fields["tag"] = "must contain 1 to 15 lowercase ASCII letters or digits" fields["tag"] = "must contain 1 to 15 lowercase ASCII letters or digits"
} }
text("value", v.Value, 1024) text("value", v.Value, 1024)
case tlsaData:
v.Certificate = strings.ToLower(v.Certificate)
certificate, err := hex.DecodeString(v.Certificate)
switch {
case err != nil || len(certificate) == 0:
fields["certificate"] = "must be a non-empty even-length hexadecimal string"
case len(certificate) > 65535-3:
fields["certificate"] = "must be at most 65532 bytes"
case v.MatchingType == 1 && len(certificate) != 32:
fields["certificate"] = "must be a 32-byte SHA-256 digest for matching type 1"
case v.MatchingType == 2 && len(certificate) != 64:
fields["certificate"] = "must be a 64-byte SHA-512 digest for matching type 2"
}
data = v
case soaData: case soaData:
v.NS = host("ns", v.NS, false) v.NS = host("ns", v.NS, false)
mailbox, err := normalizeMailbox(v.MBox) mailbox, err := normalizeMailbox(v.MBox)
+73
View File
@@ -283,6 +283,16 @@ pre.code {
opacity: 0.5; opacity: 0.5;
} }
.btn[aria-busy="true"] {
cursor: progress;
}
.btn-link {
border-color: transparent;
color: var(--accent);
text-decoration: underline;
}
.btn-primary { .btn-primary {
background: var(--accent); background: var(--accent);
border-color: var(--accent); border-color: var(--accent);
@@ -488,6 +498,41 @@ input[type="radio"] {
width: 2rem; width: 2rem;
} }
.th-sort {
background: none;
border: 0;
color: inherit;
cursor: pointer;
font: inherit;
font-weight: 600;
padding: 0;
}
.th-sort::after {
color: var(--muted);
content: "\2195";
content: "\2195" / "";
display: inline-block;
margin-left: 0.25rem;
width: 1ch;
}
[aria-sort="ascending"] .th-sort::after {
color: var(--text);
content: "\2191";
content: "\2191" / "";
}
[aria-sort="descending"] .th-sort::after {
color: var(--text);
content: "\2193";
content: "\2193" / "";
}
.th-sort:hover {
color: var(--accent);
}
.table .value code { .table .value code {
overflow-wrap: anywhere; overflow-wrap: anywhere;
} }
@@ -508,6 +553,16 @@ input[type="radio"] {
color: var(--muted); color: var(--muted);
} }
.table tbody tr.row-flash {
animation: row-flash 2s ease-out;
}
@keyframes row-flash {
from {
background: var(--info-bg);
}
}
.detail-row > td { .detail-row > td {
background: var(--stripe); background: var(--stripe);
} }
@@ -660,6 +715,24 @@ input[type="radio"] {
padding: 1rem; padding: 1rem;
} }
.dialog-status {
align-self: center;
flex: 1 1 100%;
margin: 0;
}
.dialog-status:empty {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
white-space: nowrap;
width: 1px;
}
.dialog-actions { .dialog-actions {
border-top: 1px solid var(--border); border-top: 1px solid var(--border);
display: flex; display: flex;
+29 -3
View File
@@ -1,10 +1,10 @@
// SPDX-License-Identifier: GPL-2.0-or-later // SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini // Copyright (C) 2026 Bryan Joshua Pedini
import { $, api, busy, formatTime, h, handleError, icon } from "./common.js"; import { $, api, busy, formatTime, h, handleError, icon, readQuery, writeQuery } from "./common.js";
import { FIELD_SPECS } from "./records.js"; import { FIELD_SPECS } from "./records.js";
const state = { nextBeforeId: null, count: 0, filters: {}, counter: 0 }; const state = { nextBeforeId: null, count: 0, filters: {}, counter: 0, generation: 0 };
const SOA_FIELDS = [ const SOA_FIELDS = [
{ key: "ns", label: "Primary name server" }, { key: "ns", label: "Primary name server" },
{ key: "MBox", label: "Hostmaster" }, { key: "MBox", label: "Hostmaster" },
@@ -211,6 +211,12 @@ async function load(append) {
const status = $("#audit-status"); const status = $("#audit-status");
const query = { ...state.filters }; const query = { ...state.filters };
if (append && state.nextBeforeId !== null) query.before_id = state.nextBeforeId; if (append && state.nextBeforeId !== null) query.before_id = state.nextBeforeId;
if (append && state.nextBeforeId === null) return;
if (!append) {
state.generation += 1;
$("#audit-more").hidden = true;
}
const generation = state.generation;
if (!append) { if (!append) {
body.replaceChildren(); body.replaceChildren();
state.count = 0; state.count = 0;
@@ -218,6 +224,7 @@ async function load(append) {
} }
try { try {
const { data } = await api("GET", "/audit", { query }); const { data } = await api("GET", "/audit", { query });
if (generation !== state.generation) return;
const entries = data.entries || []; const entries = data.entries || [];
for (const entry of entries) body.append(...entryRows(entry)); for (const entry of entries) body.append(...entryRows(entry));
state.count += entries.length; state.count += entries.length;
@@ -225,15 +232,30 @@ async function load(append) {
status.textContent = state.count === 0 ? "No audit rows match." : state.count + " rows shown."; status.textContent = state.count === 0 ? "No audit rows match." : state.count + " rows shown.";
$("#audit-more").hidden = state.nextBeforeId === null; $("#audit-more").hidden = state.nextBeforeId === null;
} catch (err) { } catch (err) {
if (generation !== state.generation) return;
status.textContent = "The audit could not be loaded."; status.textContent = "The audit could not be loaded.";
handleError(err); handleError(err);
} }
} }
const FILTERS = ["zone", "actor", "operation", "kind", "outcome"];
function prefill() {
const form = $("#audit-filters");
const query = readQuery();
for (const name of FILTERS) {
const value = query.get(name);
if (!value) continue;
const control = form.elements[name];
if (control.tagName === "SELECT" && ![...control.options].some((item) => item.value === value)) continue;
control.value = value;
}
}
function readFilters() { function readFilters() {
const form = $("#audit-filters"); const form = $("#audit-filters");
const filters = {}; const filters = {};
for (const name of ["zone", "actor", "operation", "kind", "outcome"]) { for (const name of FILTERS) {
const value = form.elements[name].value.trim(); const value = form.elements[name].value.trim();
if (value) filters[name] = value; if (value) filters[name] = value;
} }
@@ -244,14 +266,18 @@ $("#audit-filters").addEventListener("submit", (event) => {
event.preventDefault(); event.preventDefault();
state.filters = readFilters(); state.filters = readFilters();
state.nextBeforeId = null; state.nextBeforeId = null;
writeQuery(state.filters);
load(false); load(false);
}); });
$("#audit-filters").addEventListener("reset", () => { $("#audit-filters").addEventListener("reset", () => {
setTimeout(() => { setTimeout(() => {
state.filters = {}; state.filters = {};
state.nextBeforeId = null; state.nextBeforeId = null;
writeQuery({});
load(false); load(false);
}, 0); }, 0);
}); });
$("#audit-more").addEventListener("click", (event) => busy(event.target, () => load(true))); $("#audit-more").addEventListener("click", (event) => busy(event.target, () => load(true)));
prefill();
state.filters = readFilters();
load(false); load(false);
+37 -4
View File
@@ -266,11 +266,17 @@ export function handleError(err, options = {}) {
} }
export async function busy(button, task) { export async function busy(button, task) {
if (button) button.disabled = true; if (button) {
button.disabled = true;
button.setAttribute("aria-busy", "true");
}
try { try {
return await task(); return await task();
} finally { } finally {
if (button) button.disabled = false; if (button) {
button.disabled = false;
button.removeAttribute("aria-busy");
}
} }
} }
@@ -278,7 +284,7 @@ const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]):not([t
function trapFocus(dialog, event) { function trapFocus(dialog, event) {
if (event.key !== "Tab") return; if (event.key !== "Tab") return;
const items = [...dialog.querySelectorAll(FOCUSABLE)].filter((el) => !el.hidden && el.offsetParent !== null); const items = [...dialog.querySelectorAll(FOCUSABLE)].filter((el) => !el.hidden && el.offsetParent !== null && !el.closest("[inert]"));
if (items.length === 0) { if (items.length === 0) {
event.preventDefault(); event.preventDefault();
return; return;
@@ -298,8 +304,11 @@ export function setupDialog(dialog) {
if (dialog.dataset.ready) return; if (dialog.dataset.ready) return;
dialog.dataset.ready = "1"; dialog.dataset.ready = "1";
dialog.addEventListener("keydown", (event) => trapFocus(dialog, event)); dialog.addEventListener("keydown", (event) => trapFocus(dialog, event));
dialog.addEventListener("input", () => {
dialog.dataset.dirty = "1";
});
dialog.addEventListener("click", (event) => { dialog.addEventListener("click", (event) => {
if (event.target === dialog) dialog.close(); if (event.target === dialog && !dialog.dataset.dirty) dialog.close();
}); });
for (const button of dialog.querySelectorAll("[data-close]")) { for (const button of dialog.querySelectorAll("[data-close]")) {
button.addEventListener("click", () => dialog.close()); button.addEventListener("click", () => dialog.close());
@@ -314,6 +323,7 @@ export function openDialog(dialog) {
setupDialog(dialog); setupDialog(dialog);
const form = dialog.querySelector("form"); const form = dialog.querySelector("form");
if (form) clearErrors(form); if (form) clearErrors(form);
delete dialog.dataset.dirty;
dialog.showModal(); dialog.showModal();
const first = dialog.querySelector("input:not([type=hidden]):not([disabled]), select:not([disabled]), textarea"); const first = dialog.querySelector("input:not([type=hidden]):not([disabled]), select:not([disabled]), textarea");
if (first) first.focus(); if (first) first.focus();
@@ -389,6 +399,29 @@ export function zoneLink(name) {
return h("a", { href: "/zones/" + encodeURIComponent(name), text: name }); return h("a", { href: "/zones/" + encodeURIComponent(name), text: name });
} }
export function readQuery() {
return new URLSearchParams(location.search);
}
let queryRetry = null;
export function writeQuery(values) {
clearTimeout(queryRetry);
queryRetry = null;
const params = new URLSearchParams();
for (const [key, value] of Object.entries(values)) {
if (value !== undefined && value !== null && value !== "") params.set(key, String(value));
}
const text = params.toString();
const url = location.pathname + (text ? "?" + text : "") + location.hash;
if (url === location.pathname + location.search + location.hash) return;
try {
history.replaceState(history.state, "", url);
} catch (err) {
queryRetry = setTimeout(() => writeQuery(values), 1000);
}
}
export function bindPasswordForm(form, submit) { export function bindPasswordForm(form, submit) {
form.addEventListener("submit", async (event) => { form.addEventListener("submit", async (event) => {
event.preventDefault(); event.preventDefault();
+11 -3
View File
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: GPL-2.0-or-later // SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini // Copyright (C) 2026 Bryan Joshua Pedini
export const EDITABLE_TYPES = ["A", "AAAA", "CNAME", "NS", "MX", "TXT", "SRV", "CAA"]; export const EDITABLE_TYPES = ["A", "AAAA", "CNAME", "NS", "MX", "TXT", "SRV", "CAA", "TLSA"];
export const KNOWN_TYPES = [...EDITABLE_TYPES, "SOA"]; export const KNOWN_TYPES = [...EDITABLE_TYPES, "SOA"];
export const FIELD_SPECS = { export const FIELD_SPECS = {
@@ -35,6 +35,12 @@ export const FIELD_SPECS = {
{ key: "tag", label: "Tag", placeholder: "issue" }, { key: "tag", label: "Tag", placeholder: "issue" },
{ key: "value", label: "Value", placeholder: "ca.example.net" }, { key: "value", label: "Value", placeholder: "ca.example.net" },
], ],
TLSA: [
{ key: "usage", label: "Certificate usage", options: [["0", "0 (PKIX-TA)"], ["1", "1 (PKIX-EE)"], ["2", "2 (DANE-TA)"], ["3", "3 (DANE-EE)"]] },
{ key: "selector", label: "Selector", options: [["0", "0 (full certificate)"], ["1", "1 (SubjectPublicKeyInfo)"]] },
{ key: "matching_type", label: "Matching type", options: [["0", "0 (exact match)"], ["1", "1 (SHA-256)"], ["2", "2 (SHA-512)"]] },
{ key: "certificate", label: "Certificate association data (hex)", multiline: true, hex: true, placeholder: "0123456789abcdef..." },
],
}; };
export function presentValue(record) { export function presentValue(record) {
@@ -55,6 +61,8 @@ export function presentValue(record) {
return data.priority + " " + data.weight + " " + data.port + " " + data.target; return data.priority + " " + data.weight + " " + data.port + " " + data.target;
case "CAA": case "CAA":
return data.flag + " " + data.tag + ' "' + data.value + '"'; return data.flag + " " + data.tag + ' "' + data.value + '"';
case "TLSA":
return data.usage + " " + data.selector + " " + data.matching_type + " " + data.certificate;
case "SOA": case "SOA":
return [data.ns, data.MBox !== undefined ? data.MBox : data.mbox, data.serial == null || data.serial === 0 ? "dynamic (Unix time)" : data.serial, data.refresh, data.retry, data.expire, data.minttl].join(" "); return [data.ns, data.MBox !== undefined ? data.MBox : data.mbox, data.serial == null || data.serial === 0 ? "dynamic (Unix time)" : data.serial, data.refresh, data.retry, data.expire, data.minttl].join(" ");
default: default:
@@ -68,8 +76,8 @@ export function displayName(record) {
export function matchesFilter(record, type, text) { export function matchesFilter(record, type, text) {
if (type && record.type !== type) return false; if (type && record.type !== type) return false;
if (!text) return true; const needle = text.trim().toLowerCase();
const needle = text.toLowerCase(); if (!needle) return true;
const haystack = [displayName(record), record.fqdn || "", record.type, presentValue(record)].join(" ").toLowerCase(); const haystack = [displayName(record), record.fqdn || "", record.type, presentValue(record)].join(" ").toLowerCase();
return haystack.includes(needle); return haystack.includes(needle);
} }
+179 -17
View File
@@ -1,23 +1,47 @@
// SPDX-License-Identifier: GPL-2.0-or-later // SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini // Copyright (C) 2026 Bryan Joshua Pedini
import { $, api, appData, busy, clear, clearErrors, confirmDialog, flash, formatTTL, handleError, h, icon, openDialog, option, parseNumber, plural, setupDialogs, showFieldErrors, showFlash, toast, zonePath } from "./common.js"; import { $, api, appData, busy, clear, clearErrors, confirmDialog, flash, formatTTL, handleError, h, icon, openDialog, option, parseNumber, plural, readQuery, setupDialogs, showFieldErrors, showFlash, toast, writeQuery, zonePath } from "./common.js";
import { EDITABLE_TYPES, FIELD_SPECS, displayName, matchesFilter, presentValue, previewName, stripDot } from "./records.js"; import { EDITABLE_TYPES, FIELD_SPECS, displayName, matchesFilter, presentValue, previewName, stripDot } from "./records.js";
const PAGE_SIZE = 100; const PAGE_SIZE = 100;
const { zone: zoneParam, isAdmin } = appData(); const { zone: zoneParam, isAdmin } = appData();
const base = zonePath(zoneParam); const base = zonePath(zoneParam);
const query = readQuery();
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
function parseSort(text) {
const match = /^(-?)(name|type|ttl|value)$/.exec(text || "");
return match ? { key: match[2], dir: match[1] ? -1 : 1 } : null;
}
const owner = (query.get("name") || "").toLowerCase();
const state = { const state = {
summary: null, summary: null,
records: [], records: [],
problems: [], problems: [],
type: "", type: query.get("type") || "",
text: "", text: owner || query.get("q") || "",
owner,
sort: parseSort(query.get("sort")),
page: 0, page: 0,
pageRows: [],
selected: new Set(), selected: new Set(),
}; };
const COMPARE = {
name: (a, b) => collator.compare(a.name, b.name),
type: (a, b) => collator.compare(a.type, b.type),
ttl: (a, b) => (a.ttl || 360) - (b.ttl || 360),
value: (a, b) => collator.compare(displayValue(a), displayValue(b)),
};
function syncUrl() {
writeQuery({ type: state.type, q: state.owner ? "" : state.text.trim(), name: state.owner, sort: state.sort ? (state.sort.dir < 0 ? "-" : "") + state.sort.key : "" });
}
function zoneName() { function zoneName() {
return state.summary ? state.summary.name : zoneParam; return state.summary ? state.summary.name : zoneParam;
} }
@@ -40,6 +64,10 @@ function isBroken(record) {
return record.data === null || record.data === undefined || hasErrors(record); return record.data === null || record.data === undefined || hasErrors(record);
} }
function displayValue(record) {
return isBroken(record) ? String(record.raw ?? "") : presentValue(record);
}
function problemBadge(problem) { function problemBadge(problem) {
return h("li", { class: "problem problem-" + problem.severity }, return h("li", { class: "problem problem-" + problem.severity },
h("span", { class: "badge badge-" + (problem.severity === "error" ? "error" : "warning"), text: problem.severity }), h("span", { class: "badge badge-" + (problem.severity === "error" ? "error" : "warning"), text: problem.severity }),
@@ -81,6 +109,20 @@ function renderSoa() {
managed.hidden = !dynamic; managed.hidden = !dynamic;
} }
function showRecords(name, type) {
const apex = zoneName().endsWith(".") ? zoneName() : zoneName() + ".";
state.type = type || "";
state.owner = ((name === "" ? "" : name + ".") + apex).toLowerCase();
state.text = state.owner;
state.page = 0;
typeOptions();
$("#filter-text").value = state.text;
syncUrl();
renderRecords();
$("#records-title").scrollIntoView({ block: "start" });
$("#filter-text").focus();
}
function renderProblems() { function renderProblems() {
const panel = $("#problems-panel"); const panel = $("#problems-panel");
const list = $("#problems-list"); const list = $("#problems-list");
@@ -88,9 +130,13 @@ function renderProblems() {
panel.hidden = state.problems.length === 0; panel.hidden = state.problems.length === 0;
$("#problems-title").textContent = "Problems (" + state.problems.length + ")"; $("#problems-title").textContent = "Problems (" + state.problems.length + ")";
for (const problem of state.problems) { for (const problem of state.problems) {
const where = problem.name === null || problem.name === undefined ? "zone" : (problem.name === "" ? "@" : problem.name) + (problem.type ? " " + problem.type : ""); const located = problem.name !== null && problem.name !== undefined;
const where = located ? (problem.name === "" ? "@" : problem.name) + (problem.type ? " " + problem.type : "") : "zone";
const item = problemBadge(problem); const item = problemBadge(problem);
item.append(" ", h("span", { class: "muted", text: "(" + where + ")" })); item.append(" ", h("span", { class: "muted", text: "(" + where + ")" }));
if (located) {
item.append(" ", h("button", { type: "button", class: "btn btn-small btn-link", "aria-label": "Show " + where + " in the records table", text: "Show", onclick: () => showRecords(problem.name, problem.type) }));
}
list.append(item); list.append(item);
} }
} }
@@ -105,7 +151,24 @@ function typeOptions() {
} }
function visibleRecords() { function visibleRecords() {
return state.records.filter((record) => matchesFilter(record, state.type, state.text)); const rows = state.owner
? state.records.filter((record) => (!state.type || record.type === state.type) && (record.fqdn || "").toLowerCase() === state.owner)
: state.records.filter((record) => matchesFilter(record, state.type, state.text));
if (!state.sort) return rows;
const { key, dir } = state.sort;
if (key === "ttl") {
const missing = (record) => !Number.isInteger(record.ttl);
return rows.sort((a, b) => missing(a) - missing(b) || (missing(a) ? 0 : dir * COMPARE.ttl(a, b)));
}
return rows.sort((a, b) => dir * COMPARE[key](a, b));
}
function renderSortHeaders() {
for (const th of document.querySelectorAll("#records-table th[data-sort]")) {
const active = state.sort && state.sort.key === th.dataset.sort;
if (active) th.setAttribute("aria-sort", state.sort.dir > 0 ? "ascending" : "descending");
else th.removeAttribute("aria-sort");
}
} }
function problemsCell(record) { function problemsCell(record) {
@@ -120,8 +183,10 @@ function renderRecords() {
const pages = Math.max(1, Math.ceil(all.length / PAGE_SIZE)); const pages = Math.max(1, Math.ceil(all.length / PAGE_SIZE));
if (state.page >= pages) state.page = pages - 1; if (state.page >= pages) state.page = pages - 1;
const rows = all.slice(state.page * PAGE_SIZE, (state.page + 1) * PAGE_SIZE); const rows = all.slice(state.page * PAGE_SIZE, (state.page + 1) * PAGE_SIZE);
state.pageRows = rows;
clear(body); clear(body);
for (const record of rows) body.append(recordRow(record)); for (const record of rows) body.append(recordRow(record));
renderSortHeaders();
const status = $("#records-status"); const status = $("#records-status");
if (state.records.length === 0) status.textContent = "This zone has no records."; if (state.records.length === 0) status.textContent = "This zone has no records.";
else if (all.length === 0) status.textContent = "No record matches the filter."; else if (all.length === 0) status.textContent = "No record matches the filter.";
@@ -152,14 +217,14 @@ function recordRow(record) {
const hasError = hasErrors(record); const hasError = hasErrors(record);
const hasWarning = (record.problems || []).length > 0; const hasWarning = (record.problems || []).length > 0;
const value = h("td", { class: "value" }, const value = h("td", { class: "value" },
h("code", { class: broken ? "mono raw" : "mono", text: broken ? (record.raw ?? "") : presentValue(record) }), h("code", { class: broken ? "mono raw" : "mono", text: displayValue(record) }),
(record.problems || []).length > 0 ? problemsCell(record) : null); (record.problems || []).length > 0 ? problemsCell(record) : null);
const edit = h("button", { type: "button", class: "btn btn-small", "aria-label": "Edit " + label, onclick: () => (isSoa ? openSoa(record) : openRecord(record)) }, icon("edit"), " Edit"); const edit = h("button", { type: "button", class: "btn btn-small", "aria-label": "Edit " + label, onclick: () => (isSoa ? openSoa(record) : openRecord(record)) }, icon("edit"), " Edit");
const actions = h("td", { class: "actions-cell" }, edit); const actions = h("td", { class: "actions-cell" }, edit);
if (!isSoa || soaRows().length > 1) { if (!isSoa || soaRows().length > 1) {
actions.append(" ", h("button", { type: "button", class: "btn btn-small btn-danger", "aria-label": "Delete " + label, onclick: () => deleteRecord(record) }, icon("trash"), " Delete")); actions.append(" ", h("button", { type: "button", class: "btn btn-small btn-danger", "aria-label": "Delete " + label, onclick: () => deleteRecord(record) }, icon("trash"), " Delete"));
} }
return h("tr", { class: hasError ? "row-error" : hasWarning ? "row-warning" : null }, return h("tr", { class: hasError ? "row-error" : hasWarning ? "row-warning" : null, "data-id": record.id },
h("td", { class: "check" }, checkbox), h("td", { class: "check" }, checkbox),
h("th", { scope: "row", title: record.fqdn || "" }, h("span", { class: "mono", text: displayName(record) })), h("th", { scope: "row", title: record.fqdn || "" }, h("span", { class: "mono", text: displayName(record) })),
h("td", { text: record.type }), h("td", { text: record.type }),
@@ -168,8 +233,22 @@ function recordRow(record) {
actions); actions);
} }
function pageRows() { function highlight(id) {
return visibleRecords().slice(state.page * PAGE_SIZE, (state.page + 1) * PAGE_SIZE); if (id === undefined || id === null || !state.records.some((record) => record.id === id)) return;
const index = visibleRecords().findIndex((record) => record.id === id);
if (index < 0) {
toast("The saved record is hidden by the current filter.");
return;
}
const page = Math.floor(index / PAGE_SIZE);
if (page !== state.page) {
state.page = page;
renderRecords();
}
const row = [...$("#records-body").rows].find((tr) => tr.dataset.id === String(id));
if (!row) return;
row.classList.add("row-flash");
row.scrollIntoView({ block: "nearest" });
} }
function updateSelection() { function updateSelection() {
@@ -178,16 +257,21 @@ function updateSelection() {
const button = $("#bulk-delete"); const button = $("#bulk-delete");
button.disabled = state.selected.size === 0; button.disabled = state.selected.size === 0;
button.textContent = state.selected.size === 0 ? "Delete selected" : "Delete selected (" + state.selected.size + ")"; button.textContent = state.selected.size === 0 ? "Delete selected" : "Delete selected (" + state.selected.size + ")";
const selectable = pageRows().filter((record) => record.type !== "SOA"); const selectable = state.pageRows.filter((record) => record.type !== "SOA");
$("#select-all").checked = selectable.length > 0 && selectable.every((record) => state.selected.has(record.id)); $("#select-all").checked = selectable.length > 0 && selectable.every((record) => state.selected.has(record.id));
} }
let loadGeneration = 0;
async function load() { async function load() {
loadGeneration += 1;
const generation = loadGeneration;
const results = await Promise.allSettled([ const results = await Promise.allSettled([
api("GET", base), api("GET", base),
api("GET", base + "/records"), api("GET", base + "/records"),
api("GET", base + "/check"), api("GET", base + "/check"),
]); ]);
if (generation !== loadGeneration) return;
const [summary, records, check] = results; const [summary, records, check] = results;
if (summary.status === "rejected") { if (summary.status === "rejected") {
$("#soa-status").textContent = "The zone could not be loaded."; $("#soa-status").textContent = "The zone could not be loaded.";
@@ -203,6 +287,7 @@ async function load() {
renderSoa(); renderSoa();
renderProblems(); renderProblems();
typeOptions(); typeOptions();
if (records.status === "fulfilled") syncUrl();
renderRecords(); renderRecords();
if (isAdmin) loadUsers(); if (isAdmin) loadUsers();
} }
@@ -288,6 +373,9 @@ function reportWarnings(message, data) {
const recordForm = { const recordForm = {
editing: null, editing: null,
ttlTouched: false, ttlTouched: false,
another: false,
pending: 0,
session: 0,
}; };
function fieldId(key) { function fieldId(key) {
@@ -309,7 +397,8 @@ function buildTypeFields(type, values) {
let control; let control;
const current = values[spec.key] === undefined || values[spec.key] === null ? "" : String(values[spec.key]); const current = values[spec.key] === undefined || values[spec.key] === null ? "" : String(values[spec.key]);
if (spec.options) { if (spec.options) {
control = h("select", { id, name: spec.key }, spec.options.map(([value, label]) => option(value, label, value === current))); const choices = current !== "" && !spec.options.some(([value]) => value === current) ? [...spec.options, [current, current]] : spec.options;
control = h("select", { id, name: spec.key }, choices.map(([value, label]) => option(value, label, value === current)));
} else if (spec.multiline) { } else if (spec.multiline) {
control = h("textarea", { id, name: spec.key, rows: 3, autocomplete: "off", spellcheck: "false", placeholder: spec.placeholder, value: current }); control = h("textarea", { id, name: spec.key, rows: 3, autocomplete: "off", spellcheck: "false", placeholder: spec.placeholder, value: current });
} else { } else {
@@ -350,6 +439,13 @@ function applyRrsetTtl(result) {
function openRecord(record) { function openRecord(record) {
const form = $("#record-form"); const form = $("#record-form");
recordForm.session += 1;
form.querySelector(".dialog-body").inert = false;
$("#rec-status").textContent = "";
for (const button of [$("#rec-submit"), $("#rec-submit-another")]) {
button.disabled = false;
button.removeAttribute("aria-busy");
}
const broken = Boolean(record) && isBroken(record); const broken = Boolean(record) && isBroken(record);
const known = Boolean(record) && EDITABLE_TYPES.includes(record.type); const known = Boolean(record) && EDITABLE_TYPES.includes(record.type);
recordForm.editing = record || null; recordForm.editing = record || null;
@@ -367,6 +463,7 @@ function openRecord(record) {
form.elements.ttl.value = String(ttl); form.elements.ttl.value = String(ttl);
buildTypeFields(select.value, record && !broken ? record.data : {}); buildTypeFields(select.value, record && !broken ? record.data : {});
$("#rec-submit").textContent = record ? "Save changes" : "Add record"; $("#rec-submit").textContent = record ? "Save changes" : "Add record";
$("#rec-submit-another").hidden = Boolean(record);
updatePreview(); updatePreview();
openDialog($("#record-dialog")); openDialog($("#record-dialog"));
} }
@@ -376,7 +473,7 @@ function recordBody(form) {
const data = {}; const data = {};
for (const spec of FIELD_SPECS[type] || []) { for (const spec of FIELD_SPECS[type] || []) {
const value = form.elements[spec.key].value; const value = form.elements[spec.key].value;
data[spec.key] = spec.numeric || spec.options ? parseNumber(value) : spec.multiline || (type === "CAA" && spec.key === "value") ? value : value.trim(); data[spec.key] = spec.numeric || spec.options ? parseNumber(value) : spec.hex ? value.replace(/[\s:]/g, "").toLowerCase() : spec.multiline || (type === "CAA" && spec.key === "value") ? value : value.trim();
} }
return { name: form.elements.name.value.trim(), type, ttl: parseNumber(form.elements.ttl.value), data }; return { name: form.elements.name.value.trim(), type, ttl: parseNumber(form.elements.ttl.value), data };
} }
@@ -393,27 +490,77 @@ function setupRecordForm() {
buildTypeFields(form.elements.type.value, readTypeValues(form)); buildTypeFields(form.elements.type.value, readTypeValues(form));
if (!recordForm.ttlTouched && !recordForm.editing) updatePreview(); if (!recordForm.ttlTouched && !recordForm.editing) updatePreview();
}); });
const anotherButton = $("#rec-submit-another");
anotherButton.addEventListener("click", () => {
recordForm.another = true;
form.requestSubmit();
});
form.addEventListener("submit", async (event) => { form.addEventListener("submit", async (event) => {
event.preventDefault(); event.preventDefault();
const another = recordForm.another && !recordForm.editing;
recordForm.another = false;
if (recordForm.pending === recordForm.session) return;
clearErrors(form); clearErrors(form);
if (!form.elements.type.value) { if (!form.elements.type.value) {
showFieldErrors(form, { type: "Select a type." }); showFieldErrors(form, { type: "Select a type." });
return; return;
} }
const editing = recordForm.editing; const editing = recordForm.editing;
await busy(form.querySelector("button[type=submit]"), async () => { const session = recordForm.session;
const fields = form.querySelector(".dialog-body");
const submitButton = $("#rec-submit");
const clicked = another ? anotherButton : submitButton;
const current = () => session === recordForm.session && dialog.open;
let refocus = false;
recordForm.pending = session;
fields.inert = true;
$("#rec-status").textContent = "";
submitButton.disabled = true;
anotherButton.disabled = true;
clicked.setAttribute("aria-busy", "true");
try { try {
const body = recordBody(form); const body = recordBody(form);
const result = editing const result = editing
? await api("PUT", base + "/records/" + editing.id, { body, ifMatch: editing.etag }) ? await api("PUT", base + "/records/" + editing.id, { body, ifMatch: editing.etag })
: await api("POST", base + "/records", { body }); : await api("POST", base + "/records", { body });
dialog.close(); const keepOpen = another && current();
if (keepOpen) {
const warnings = result.data && Array.isArray(result.data.warnings) ? result.data.warnings : [];
await load();
if (current()) {
fields.inert = false;
$("#rec-status").textContent = ["Record added.", ...warnings.map((warning) => "Warning: " + warning.message)].join(" ");
buildTypeFields(form.elements.type.value, {});
delete dialog.dataset.dirty;
const first = $("#rec-fields").querySelector("input, select, textarea");
if (first) first.focus();
} else {
reportWarnings("Record added.", result.data);
}
} else {
if (current()) dialog.close();
reportWarnings(editing ? "Record saved." : "Record added.", result.data); reportWarnings(editing ? "Record saved." : "Record added.", result.data);
await load(); await load();
if (!dialog.open) highlight(result.data && result.data.record ? result.data.record.id : null);
}
} catch (err) { } catch (err) {
if (!current()) {
handleError(err, { reload: load });
} else {
fields.inert = false;
handleError(err, { form, reload: () => { dialog.close(); return load(); } }); handleError(err, { form, reload: () => { dialog.close(); return load(); } });
refocus = true;
}
} finally {
if (recordForm.pending === session) recordForm.pending = 0;
if (session === recordForm.session) {
submitButton.disabled = false;
anotherButton.disabled = false;
clicked.removeAttribute("aria-busy");
fields.inert = false;
if (refocus && dialog.open) (form.querySelector('[aria-invalid="true"]:not(:disabled)') || clicked).focus();
}
} }
});
}); });
} }
@@ -447,16 +594,30 @@ async function bulkDelete() {
} }
function setupTable() { function setupTable() {
const search = $("#filter-text");
search.value = state.text;
$("#filter-type").addEventListener("change", (event) => { $("#filter-type").addEventListener("change", (event) => {
state.type = event.target.value; state.type = event.target.value;
state.page = 0; state.page = 0;
syncUrl();
renderRecords(); renderRecords();
}); });
$("#filter-text").addEventListener("input", (event) => { search.addEventListener("input", (event) => {
state.text = event.target.value; state.text = event.target.value;
state.owner = "";
state.page = 0; state.page = 0;
renderRecords(); renderRecords();
syncUrl();
}); });
for (const th of document.querySelectorAll("#records-table th[data-sort]")) {
th.querySelector("button").addEventListener("click", () => {
const key = th.dataset.sort;
state.sort = { key, dir: state.sort && state.sort.key === key ? -state.sort.dir : 1 };
state.page = 0;
syncUrl();
renderRecords();
});
}
$("#page-prev").addEventListener("click", () => { $("#page-prev").addEventListener("click", () => {
state.page -= 1; state.page -= 1;
renderRecords(); renderRecords();
@@ -466,7 +627,7 @@ function setupTable() {
renderRecords(); renderRecords();
}); });
$("#select-all").addEventListener("change", (event) => { $("#select-all").addEventListener("change", (event) => {
for (const record of pageRows()) { for (const record of state.pageRows) {
if (record.type === "SOA") continue; if (record.type === "SOA") continue;
if (event.target.checked) state.selected.add(record.id); if (event.target.checked) state.selected.add(record.id);
else state.selected.delete(record.id); else state.selected.delete(record.id);
@@ -557,6 +718,7 @@ const exportLink = $("#export-link");
exportLink.href = "/api/v1" + base + "/export"; exportLink.href = "/api/v1" + base + "/export";
exportLink.setAttribute("download", ""); exportLink.setAttribute("download", "");
$("#import-link").href = "/zones/" + encodeURIComponent(zoneParam) + "/import"; $("#import-link").href = "/zones/" + encodeURIComponent(zoneParam) + "/import";
$("#audit-link").href = "/audit?zone=" + encodeURIComponent(zoneParam) + "&kind=change";
setupSoa(); setupSoa();
setupRecordForm(); setupRecordForm();
setupTable(); setupTable();
+7 -4
View File
@@ -1,10 +1,10 @@
// SPDX-License-Identifier: GPL-2.0-or-later // SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini // Copyright (C) 2026 Bryan Joshua Pedini
import { $, api, appData, busy, clear, clearErrors, handleError, h, openDialog, parseNumber, plural, setupDialogs, showFlash, toast, zoneLink } from "./common.js"; import { $, api, appData, busy, clear, clearErrors, handleError, h, openDialog, parseNumber, plural, readQuery, setupDialogs, showFlash, toast, writeQuery, zoneLink } from "./common.js";
const { isAdmin } = appData(); const { isAdmin } = appData();
const state = { zones: [], counts: null, countsFailed: false, search: "" }; const state = { zones: [], counts: null, countsFailed: false, search: readQuery().get("q") || "" };
function problemCell(zone) { function problemCell(zone) {
const cell = h("td"); const cell = h("td");
@@ -18,7 +18,7 @@ function problemCell(zone) {
} }
const counts = state.counts.get(zone.name) || { error: 0, warning: 0 }; const counts = state.counts.get(zone.name) || { error: 0, warning: 0 };
if (counts.error === 0 && counts.warning === 0) { if (counts.error === 0 && counts.warning === 0) {
cell.append(h("span", { class: "badge badge-ok", text: "none" })); cell.append(h("span", { class: "badge badge-ok", text: "OK" }));
return cell; return cell;
} }
if (counts.error > 0) cell.append(h("span", { class: "badge badge-error", text: plural(counts.error, "error", "errors") }), " "); if (counts.error > 0) cell.append(h("span", { class: "badge badge-error", text: plural(counts.error, "error", "errors") }), " ");
@@ -123,9 +123,12 @@ function setupCreate() {
setupDialogs(); setupDialogs();
showFlash(); showFlash();
$("#zone-search").addEventListener("input", (event) => { const search = $("#zone-search");
search.value = state.search;
search.addEventListener("input", (event) => {
state.search = event.target.value; state.search = event.target.value;
render(); render();
writeQuery({ q: state.search.trim() });
}); });
if (isAdmin) setupCreate(); if (isAdmin) setupCreate();
load(); load();
+6 -1
View File
@@ -8,6 +8,7 @@
<div class="actions"> <div class="actions">
<a class="btn" id="export-link" href="/">Export zone file</a> <a class="btn" id="export-link" href="/">Export zone file</a>
<a class="btn" id="import-link" href="/">Import zone file</a> <a class="btn" id="import-link" href="/">Import zone file</a>
<a class="btn" id="audit-link" href="/audit">Audit history</a>
</div> </div>
</div> </div>
@@ -51,7 +52,11 @@
<thead> <thead>
<tr> <tr>
<th scope="col" class="check"><input type="checkbox" id="select-all" aria-label="Select all records on this page"></th> <th scope="col" class="check"><input type="checkbox" id="select-all" aria-label="Select all records on this page"></th>
<th scope="col">Name</th><th scope="col">Type</th><th scope="col">TTL</th><th scope="col">Value</th><th scope="col">Actions</th> <th scope="col" data-sort="name"><button type="button" class="th-sort">Name</button></th>
<th scope="col" data-sort="type"><button type="button" class="th-sort">Type</button></th>
<th scope="col" data-sort="ttl"><button type="button" class="th-sort">TTL</button></th>
<th scope="col" data-sort="value"><button type="button" class="th-sort">Value</button></th>
<th scope="col">Actions</th>
</tr> </tr>
</thead> </thead>
<tbody id="records-body"></tbody> <tbody id="records-body"></tbody>
+1 -1
View File
@@ -15,7 +15,7 @@
<div class="table-wrap"> <div class="table-wrap">
<table class="table" id="zones-table"> <table class="table" id="zones-table">
<thead> <thead>
<tr><th scope="col">Zone</th><th scope="col" class="num">Records</th><th scope="col">SOA serial</th><th scope="col">Problems</th></tr> <tr><th scope="col">Zone</th><th scope="col" class="num">Records</th><th scope="col">SOA serial</th><th scope="col">Status</th></tr>
</thead> </thead>
<tbody id="zones-body"></tbody> <tbody id="zones-body"></tbody>
</table> </table>
@@ -29,7 +29,9 @@
<div id="rec-fields"></div> <div id="rec-fields"></div>
</div> </div>
<div class="dialog-actions"> <div class="dialog-actions">
<p class="hint dialog-status" id="rec-status" role="status"></p>
<button type="button" class="btn" data-close>Cancel</button> <button type="button" class="btn" data-close>Cancel</button>
<button type="button" class="btn" id="rec-submit-another" hidden>Save and add another</button>
<button type="submit" class="btn btn-primary" id="rec-submit">Save record</button> <button type="submit" class="btn btn-primary" id="rec-submit">Save record</button>
</div> </div>
</form> </form>
+2
View File
@@ -273,6 +273,8 @@ func zoneFileRecordData(rr dns.RR) (any, error) {
case *dns.CAA: case *dns.CAA:
value, err := unescapeZoneText(v.Value) value, err := unescapeZoneText(v.Value)
return caaData{v.Flag, v.Tag, value}, err return caaData{v.Flag, v.Tag, value}, err
case *dns.TLSA:
return tlsaData{v.Usage, v.Selector, v.MatchingType, strings.ToLower(v.Certificate)}, nil
case *dns.SOA: case *dns.SOA:
return soaData{v.Ns, v.Mbox, v.Refresh, v.Retry, v.Expire, v.Minttl, 0}, nil return soaData{v.Ns, v.Mbox, v.Refresh, v.Retry, v.Expire, v.Minttl, 0}, nil
default: default:
+33
View File
@@ -309,3 +309,36 @@ func TestZoneFingerprint(t *testing.T) {
t.Fatal("raw JSON change did not change fingerprint") t.Fatal("raw JSON change did not change fingerprint")
} }
} }
func TestZoneFileTLSA(t *testing.T) {
parsed := modelParseZone(t, `$ORIGIN example.org.
@ IN SOA ns.example.net. hostmaster.example.org. 1 3600 600 604800 300
_25._tcp.mail 300 IN TLSA 3 1 1 0123456789ABCDEF0123456789ABCDEF 0123456789ABCDEF0123456789ABCDEF
_443._tcp IN TLSA ( 0 1 0
302a300506032b6570032100d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a )
`)
if len(parsed.Rows) != 3 || len(parsed.Skipped) != 0 ||
parsed.Rows[1].Name != "_25._tcp.mail" || parsed.Rows[1].RecordType != "TLSA" ||
parsed.Rows[1].Content.String != `{"usage":3,"selector":1,"matching_type":1,"certificate":"`+strings.Repeat("0123456789abcdef", 4)+`"}` ||
parsed.Rows[2].Content.String != `{"usage":0,"selector":1,"matching_type":0,"certificate":"302a300506032b6570032100d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a"}` {
t.Fatalf("unexpected parsed TLSA: %+v", parsed)
}
rows := parsed.Rows
for i := range rows {
rows[i].ID = int64(i + 1)
}
file, err := exportZoneFile("example.org.", rows, modelNow)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(file, "TLSA\t3 1 1 "+strings.Repeat("0123456789abcdef", 4)) && !strings.Contains(file, "TLSA 3 1 1 "+strings.Repeat("0123456789abcdef", 4)) {
t.Fatalf("export lacks the TLSA record:\n%s", file)
}
diff, err := diffZoneImport("example.org.", rows, modelParseZone(t, file), "replace", modelNow)
if err != nil || !diff.Changes.empty() || len(diff.Problems) != 0 || len(diff.Unchanged) != len(rows) {
t.Fatalf("TLSA round trip = %+v, %v\n%s", diff, err, file)
}
if _, err := parseZoneFile("example.org.", strings.NewReader("_25._tcp IN TLSA 3 1 1 abcd\n"), modelNow); err == nil {
t.Fatal("accepted a SHA-256 TLSA with a short digest")
}
}