68 KiB
coredns-web-ui: implementation plan
1. Project definition
Repository: git.bjphoster.com/source/coredns-web-ui
Application: coredns-web-ui
Container image: git.bjphoster.com/source/coredns-web-ui
License: GPL-2.0-or-later. Every source file starts with the SPDX header used in the other repositories of the organization:
SPDX-License-Identifier: GPL-2.0-or-later
Copyright (C) 2026 Bryan Joshua Pedini
Purpose: a Go web application, shipped as a container image, to manage the DNS zones and records that CoreDNS serves through the mysql plugin (github.com/cloud66-oss/coredns_mysql, built into git.bjphoster.com/docker/coredns-mysql). The application reads and writes the plugin's records table in MySQL directly. CoreDNS reads the same table. The application never talks to CoreDNS, never edits the Corefile and never starts, stops or reloads CoreDNS.
The same binary starts the HTTP server when run without arguments and provides CLI subcommands for user management, zone checks, audit inspection, health checks, version and help.
The layout uses go-template-container-webserver as a reference only (main.go, type_webserver.go, routes.go, version.go with templates/html/version.html, version.sh, deploy.sh, initialize.sh, vars.example/.vars, makefile, two-stage dockerfile with a scratch final stage, gorilla/mux routing), with the changes already adopted in dpsapi and netbox-mcp-server: environment-only runtime configuration (no YAML), log/slog logging with a TRACE level, a test stage in the dockerfile, OCI image labels, a non-root final image and SPDX headers.
Reference repositories:
- https://git.bjphoster.com/source/go-template-container-webserver
- https://git.bjphoster.com/source/dpsapi
- https://git.bjphoster.com/source/netbox-mcp-server
- https://git.bjphoster.com/source/gestionale-inquilini
- https://git.bjphoster.com/docker/coredns-mysql
Project rules:
- Identifiers, strings, UI text, log messages and documentation are in English.
- No code comments apart from the SPDX header.
- No em dash in any text: code, UI, logs, documentation and commit messages.
- Go builds and tests run in containers. Node tooling (Playwright) runs only inside containers, never on the host.
- Commits follow Conventional Commits (
feat:,fix:,test:,docs:,build:,ci:,refactor:), one or more per implementation phase, without attribution trailers.
2. Scope
In scope:
- Login with local users, sessions, password change.
- Two roles:
adminsees and does everything;usersees and operates only on the zones delegated to them (section 8). - Zone delegation: admins delegate zones to users and revoke them.
- 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 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. - Bulk deletion of records.
- Automatic SOA serial management.
- Zone checks that report every row the plugin cannot serve correctly.
- Zone file export and import (RFC 1035 master file format).
- An audit table, as in
dpsapi, with one row for every operation performed through the web UI and the API, reads and refused requests included, and for every change made through the CLI (section 9). - CLI for users, checks, audit, health and version.
Out of scope:
- Creating, altering or dropping the plugin's records table.
- Corefile management and any interaction with the CoreDNS process.
- Record types the plugin does not serve, DNSSEC, zone transfers.
- API tokens or non-browser API clients.
- Roles other than
adminanduser, and per-record or per-type permissions. - Restoring deleted users and renaming users.
- Updating, deleting or purging audit rows: the audit table is append-only.
- External identity providers.
- Zone renaming and reverting changes from the audit log.
- Internationalized domain names in Unicode form (punycode
xn--labels are accepted as ASCII).
3. Backend contract: the plugin's records table
Table
The plugin documents this table (<prefix>records, default prefix coredns_):
CREATE TABLE `coredns_records` (
`id` INT NOT NULL AUTO_INCREMENT,
`zone` VARCHAR(255) NOT NULL,
`name` VARCHAR(255) NOT NULL,
`ttl` INT DEFAULT NULL,
`content` TEXT,
`record_type` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4;
The table belongs to the operator and is shared with CoreDNS and possibly with other writers. The application only runs SELECT, INSERT, UPDATE and DELETE on it. At startup it verifies, through information_schema.COLUMNS of DATABASE(), that the table exists and has the six columns with compatible types; otherwise it exits with a clear error naming the missing table or column. It never creates or changes the table, its indexes or its collation.
Column semantics, as implemented by the plugin
zone: the zone apex as a fully qualified, lowercase name with the trailing dot (example.org.). The plugin's zone list isSELECT DISTINCT zone, so a zone exists as soon as one row carries it. The plugin compares the zone string case-sensitively when it derives the relative query name, so a zone value with uppercase letters or without the trailing dot breaks every lookup in it.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.0is served as 360 seconds (the plugin's built-in default). The plugin scans the column into an unsigned integer, so aNULLor a negative value makes every query that reads the row fail with SERVFAIL. The application never writesNULLor negative values.content: a JSON object whose shape depends on the type (below). ANULLor 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-insensitiveIN (...)and then dispatches on the exact string, so a lowercaseaor an unknown type makes queries of that type answer NOTIMP. The application only writes the nine uppercase names.
Content JSON per type
The keys are those of the plugin source (types.go). In particular the MX key is preference; a priority key is ignored by the plugin and the record is served with preference 0.
| Type | Content | Notes |
|---|---|---|
A |
{"ip": "192.0.2.10"} |
IPv4 address |
AAAA |
{"ip": "2001:db8::10"} |
IPv6 address, not IPv4-mapped |
CNAME |
{"host": "target.example.org."} |
FQDN |
NS |
{"host": "ns1.example.org."} |
FQDN |
MX |
{"host": "mail.example.org.", "preference": 10} |
FQDN, preference 0 to 65535 |
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 |
CAA |
{"flag": 0, "tag": "issue", "value": "ca.example.net"} |
|
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 plugin passes NS, MX, SRV and SOA names to miekg/dns without making them fully qualified, and packing fails on names without the trailing dot. The application therefore stores every host, target, ns and MBox as a lowercase FQDN with the trailing dot, CNAME included for uniformity.
The plugin hands TXT text and the CAA value to miekg/dns in presentation format, where a backslash starts an escape sequence, and splits TXT text by bytes. To keep the stored text and the served data identical, both accept printable ASCII (0x20 to 0x7E) without backslash.
Plugin behavior the UI makes visible
- The plugin reloads its zone list at most every
zone_update_interval(default 10 minutes). A new zone is served only after the next reload; a deleted zone is still matched until then. The UI states this after creating or deleting a zone. - Record changes in an existing zone are read by the next query, apart from any caching configured in the Corefile.
- Without a
serialkey (or with0) the plugin serves the current Unix time as the SOA serial, so it changes on every query and differs between instances. The application manages explicit serials (section 7). - A name with a CNAME and no record of the requested type is answered with the CNAME chain within the zone; NODATA and NXDOMAIN follow the plugin's rules.
4. Runtime configuration
Configuration comes from environment variables only. No configuration file is read.
| Variable | Required | Default | Meaning |
|---|---|---|---|
DB_HOST |
yes | none | MySQL host |
DB_PORT |
no | 3306 |
MySQL port |
DB_USER |
yes | none | MySQL user |
DB_PASSWORD |
yes | none | MySQL password |
DB_NAME |
yes | none | Database holding the records table |
DB_TLS |
no | false |
false, true, skip-verify or preferred |
DB_TABLE_PREFIX |
no | coredns_ |
Must equal the plugin's table_prefix |
HTTP_ADDR |
no | 0.0.0.0 |
HTTP listen address |
HTTP_PORT |
no | 8080 |
HTTP listen port |
LOG_LEVEL |
no | INFO |
ERROR, WARN, INFO, DEBUG, TRACE, case-insensitive |
APP_NAME |
no | CoreDNS Web UI |
Name shown in page titles and on /version |
COOKIE_SECURE |
no | true |
Sets the Secure attribute of the session cookie |
SESSION_IDLE_TIMEOUT |
no | 1h |
Go duration, at least 1m |
SESSION_MAX_AGE |
no | 12h |
Go duration, at least SESSION_IDLE_TIMEOUT |
TRUSTED_PROXIES |
no | empty | Comma-separated CIDRs whose X-Forwarded-For is trusted |
Validation happens before any other work. A missing required variable, an empty value, an invalid port, address, duration, boolean, CIDR, log level or TLS mode, or a table prefix not matching ^[A-Za-z0-9_]{0,32}$ produces a message naming the variable (never its value for DB_PASSWORD) and exit code 2.
The connection is built with mysql.Config from github.com/go-sql-driver/mysql, never by string concatenation: Net=tcp, ParseTime=true, Loc=UTC, charset utf8mb4 via SET NAMES, connect timeout 5 s, read and write timeouts 30 s, MultiStatements=false, InterpolateParams=false, TLS from DB_TLS. The pool uses the plugin's defaults: at most 10 open and 10 idle connections, connection lifetime 1 minute. The DSN and the password are never logged; logs carry host, port, user and database only.
5. Process and command behavior
Server mode
/app with no arguments:
- Load and validate the configuration.
- Initialize the logger and log version and commit.
- Open the pool and ping MySQL, retrying with backoff for up to 30 seconds.
- Verify the records table contract (section 3).
- Apply the application's migrations (section 6) while holding the MySQL named lock
<prefix>webui_migrate(GET_LOCK, 30 s timeout), so several instances starting together never race. - Start a background task that deletes expired sessions every 10 minutes.
- Register the routes and listen on
${HTTP_ADDR}:${HTTP_PORT}withReadHeaderTimeout10 s,ReadTimeout30 s,WriteTimeout60 s,IdleTimeout120 s andMaxHeaderBytes64 KiB. - On
SIGINTorSIGTERM, stop accepting connections, wait up to 25 seconds for running requests, stop the background task and close the pool.
The application keeps no local state: several instances can run against the same database. Login rate limits are kept per instance.
Exit codes
| Code | Meaning |
|---|---|
0 |
success, clean shutdown, check without problems |
1 |
runtime, database or I/O error |
2 |
usage or configuration error |
3 |
check found at least one problem |
CLI
help and version read no configuration. healthcheck reads only HTTP_ADDR and HTTP_PORT. Every other command loads and validates the full configuration, then validates its arguments before connecting to MySQL, so usage errors never touch the database. CLI commands that need the database run the contract check and the migrations like the server.
The usage text, printed to stdout by help and to stderr after a usage error:
usage:
coredns-web-ui start the HTTP server
coredns-web-ui help print this usage text
coredns-web-ui version print the version and commit
coredns-web-ui healthcheck query the local /health endpoint
coredns-web-ui user list [all] list the active users, or every user with all
coredns-web-ui user add <username> <role> create a user with role admin or user, reading the password from stdin
coredns-web-ui user passwd <username> set the password of a user, reading it from stdin
coredns-web-ui user role <username> <role> set the role of a user to admin or user
coredns-web-ui user delete <username> mark a user as deleted and end their sessions
coredns-web-ui check [zone] report the rows the plugin cannot serve correctly
coredns-web-ui audit [n] print the latest n audit rows (default 20)
versionprintscoredns-web-ui <APP_VERSION> <COMMIT_ID>.healthchecksendsGET /healthto127.0.0.1:${HTTP_PORT}(or toHTTP_ADDRwhen it is a specific address) with a 3 s timeout and exits0on HTTP 200,1otherwise. It is the image'sHEALTHCHECK, since thescratchimage has no shell or HTTP client.user add <username> <role>anduser passwd <username>read the password. When stdin is a terminal they promptPassword:andRepeat password:on stderr with echo disabled (golang.org/x/term) and fail when the two differ; otherwise they read one line from stdin, soprintf '%s\n' "$PASSWORD" | docker exec -i <container> /app user add alice adminworks. Usernames and passwords follow the rules of section 8.<role>isadminoruser, exact and lowercase.user addfails when the username is already used, also by a deleted user;user passwd,user roleanduser deletefail when no active user has that username.user passwdanduser deleteend the user's sessions.user deleteonly setsdeleted_at(section 8).user roleanduser deletefail when they would leave no active admin.user list [all]prints a padded table (text/tabwriter, as indpsapi) withUSERNAME,ROLE,ZONES(number of delegated zones),CREATED_AT,LAST_LOGIN_AT(-when never) andDELETED_AT(-when NULL), ordered by username. Without an argument it lists active users only; withall(exact, case-sensitive) deleted users too; any other argument is a usage error.check [zone]runs the zone check (section 12) on one zone or on all zones and prints a padded table withZONE,NAME,TYPE,ID,SEVERITY,PROBLEM. Exit0without problems,3with at least one error or warning.audit [n]prints the latestnaudit rows (default 20,nfrom 1, digits only) oldest first, withTIME,ACTOR,ORIGIN,OPERATION,STATUS,ZONE,RECORD,TARGET_USER(-for empty values).- Every successful CLI change (
user add,user passwd,user role,user delete) writes one audit row in the same transaction (section 9). As indpsapi, failed commands and read-only commands (user list,check,audit) write nothing.
Usage errors are fixed messages prefixed by coredns-web-ui: usage error: that never echo the arguments, followed by the usage text, exit 2.
6. Application schema
The application keeps its own tables in the same database, prefixed with <prefix>webui_, so the plugin never sees them. Migrations are embedded SQL files (migrations/001_initial.sql, ...) applied in order inside the migration lock; the current version is the single row of <prefix>webui_schema, as in gestionale-inquilini. The table prefix is substituted into the SQL after validation; it is the only value ever interpolated into SQL, and it comes from configuration, not from users.
CREATE TABLE IF NOT EXISTS `coredns_webui_schema` (
`id` TINYINT NOT NULL,
`version` INT NOT NULL,
PRIMARY KEY (`id`),
CHECK (`id` = 1)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
CREATE TABLE `coredns_webui_users` (
`id` INT NOT NULL AUTO_INCREMENT,
`username` VARCHAR(64) COLLATE utf8mb4_bin NOT NULL,
`role` VARCHAR(8) NOT NULL,
`password_hash` VARCHAR(255) NOT NULL,
`created_at` DATETIME(6) NOT NULL,
`updated_at` DATETIME(6) NOT NULL,
`last_login_at` DATETIME(6) NULL,
`deleted_at` DATETIME(6) NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`),
CHECK (`role` IN ('admin', 'user'))
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
CREATE TABLE `coredns_webui_sessions` (
`token_hash` BINARY(32) NOT NULL,
`user_id` INT NOT NULL,
`created_at` DATETIME(6) NOT NULL,
`last_seen_at` DATETIME(6) NOT NULL,
`expires_at` DATETIME(6) NOT NULL,
`origin` VARCHAR(45) NOT NULL,
`user_agent` VARCHAR(255) NOT NULL,
PRIMARY KEY (`token_hash`),
KEY `user_id` (`user_id`),
KEY `expires_at` (`expires_at`),
FOREIGN KEY (`user_id`) REFERENCES `coredns_webui_users` (`id`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
CREATE TABLE `coredns_webui_zone_delegations` (
`zone` VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,
`user_id` INT NOT NULL,
`created_at` DATETIME(6) NOT NULL,
`created_by` INT NOT NULL,
PRIMARY KEY (`zone`, `user_id`),
KEY `user_id` (`user_id`),
FOREIGN KEY (`user_id`) REFERENCES `coredns_webui_users` (`id`),
FOREIGN KEY (`created_by`) REFERENCES `coredns_webui_users` (`id`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
CREATE TABLE `coredns_webui_audit` (
`id` BIGINT NOT NULL AUTO_INCREMENT,
`time` DATETIME(6) NOT NULL,
`user_id` INT NULL,
`actor` VARCHAR(64) NOT NULL,
`origin` VARCHAR(45) NOT NULL,
`operation` VARCHAR(32) NOT NULL,
`status` SMALLINT NULL,
`error` VARCHAR(255) NULL,
`zone` VARCHAR(255) NULL,
`record_id` BIGINT NULL,
`target_user_id` INT NULL,
`before_value` LONGTEXT NULL,
`after_value` LONGTEXT NULL,
PRIMARY KEY (`id`),
KEY `time` (`time`),
KEY `zone_time` (`zone`, `time`),
KEY `user_time` (`user_id`, `time`),
KEY `operation_time` (`operation`, `time`),
FOREIGN KEY (`user_id`) REFERENCES `coredns_webui_users` (`id`),
FOREIGN KEY (`target_user_id`) REFERENCES `coredns_webui_users` (`id`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
All times are UTC. Rows of <prefix>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
MySQL allows table-level grants on tables that do not exist yet when CREATE is included, so the application user gets least privilege:
CREATE USER 'coredns_webui'@'%' IDENTIFIED BY '<password>';
GRANT SELECT, INSERT, UPDATE, DELETE ON `coredns`.`coredns_records` TO 'coredns_webui'@'%';
GRANT SELECT, INSERT, UPDATE, CREATE, ALTER, INDEX, REFERENCES ON `coredns`.`coredns_webui_schema` TO 'coredns_webui'@'%';
GRANT SELECT, INSERT, UPDATE, CREATE, ALTER, INDEX, REFERENCES ON `coredns`.`coredns_webui_users` TO 'coredns_webui'@'%';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, INDEX, REFERENCES ON `coredns`.`coredns_webui_sessions` TO 'coredns_webui'@'%';
GRANT SELECT, INSERT, DELETE, CREATE, ALTER, INDEX, REFERENCES ON `coredns`.`coredns_webui_zone_delegations` TO 'coredns_webui'@'%';
GRANT SELECT, INSERT, CREATE, ALTER, INDEX, REFERENCES ON `coredns`.`coredns_webui_audit` TO 'coredns_webui'@'%';
Without DELETE on the users table and without UPDATE and DELETE on the audit table, MySQL itself guarantees that users are never removed and audit rows are never changed or removed, even through a bug in the application.
The CoreDNS user keeps SELECT on coredns_records only, so it cannot read password hashes, sessions, delegations or the audit.
7. Record model and rules
Input normalization
- Zone: ASCII letters, digits, hyphens and underscores in labels of 1 to 63 characters, at most 253 characters without the final dot, at least one label (the root zone is refused). Lowercased; the trailing dot is added when missing.
- Owner name:
@or empty means the apex. A name ending with the zone followed by a dot is converted to the relative form; a name ending with a dot and outside the zone is refused. Any other name is relative to the zone.*is allowed only as the complete leftmost label. Lowercased. The resulting FQDN must fit 253 characters. The form shows the resulting FQDN under the field while typing. - Host and target fields (
CNAME,NS,MX,SRV, SOAns): absolute names, with or without the trailing dot, which is always stored;@means the zone apex. Lowercased.MXandSRValso accept.(null MX and "service not available"). - SOA
MBox: accepted as a mailbox (hostmaster@example.org, a dot in the local part escaped as\.) or as a domain name; stored as a domain name with the trailing dot. - TTL: integer from 0 to 2147483647;
0is displayed as "default (360 s)". New records are prefilled with the TTL of the RRset they join, or 3600.
Per-type validation
| Type | Rules |
|---|---|
A |
IPv4 dotted quad |
AAAA |
IPv6, not IPv4-mapped; stored in canonical compressed form |
CNAME |
host; not at the apex |
NS |
host; not on a wildcard name |
MX |
host or .; preference 0 to 65535 |
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 . |
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 |
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.
Zone rules
Errors refuse the write with HTTP 422. Warnings let the write through and are returned with the response and listed by the zone check.
Errors:
- A zone has exactly one SOA, at the apex. The SOA cannot be created when one exists and the last SOA can only be deleted with the zone. Repair may move a misplaced SOA, correct its content, or remove an extra SOA.
- The last NS at the apex cannot be deleted.
- A name with a CNAME has no other record, and has only one CNAME.
- No two records with the same name, type and canonical content.
Warnings:
- Records of the same name and type with different TTLs.
NS,MXorSRVtargets inside the zone that are CNAME owners.- In-zone targets with no
AorAAAArecord. - Names below a non-apex NS, that is below a zone cut (DNS delegation of a subdomain, unrelated to the zone delegation of section 8).
TXTtext longer than 255 bytes (served as several strings).
Concurrency
Every write runs on a dedicated connection: take the named lock <prefix>webui:<first 16 hex chars of sha256(zone)> with GET_LOCK (10 s timeout, HTTP 503 "zone busy" on timeout), begin the transaction, check again that the actor may operate on the zone (the user row and, for role user, the delegation row read with LOCK IN SHARE MODE, so a concurrent revocation, demotion or deletion waits for the write or wins before it), read the zone's rows, apply the rules, write records, SOA serial and audit row, commit, release the lock. The lock serializes writers of this application; other writers of the table are detected through ETags.
Every record carries an ETag: the hex SHA-256 of id, zone, name, ttl, record_type and the raw content, with explicit markers for NULL. Updates and deletes require If-Match; inside the transaction the row is read with SELECT ... FOR UPDATE and compared. A missing If-Match is HTTP 428, a mismatch or a missing row is HTTP 412 and the UI offers to reload.
SOA serial
- Format
YYYYMMDDxx: the UTC date and a two-digit counterxxthat starts at00and grows by 1 at every change, so a zone takes 100 changes a day (00to99) before the serial moves into the following day's numbers. - New zones get
YYYYMMDD00of today. - Every committed transaction that changes a zone whose SOA content has a non-zero serial sets it to
max(serial + 1, YYYYMMDD00 of today), in unsigned 32-bit arithmetic, skipping0. The first change of a day therefore gets00; after99the next change gets the following day's00(2026111799becomes2026111800), and later changes keep counting from there until the real date catches up, so the serial always increases. A transaction bumps the serial once, whatever the number of changed records (bulk delete, import). - A zone whose SOA has no serial keeps it that way; the UI shows "dynamic (Unix time)" and offers "Use managed serial", which sets
YYYYMMDD00of today through asoa_update. - Editing the SOA never takes a serial from the user; the serial is bumped like any other change.
8. Users, roles and zone delegation
Users
- Username:
^[a-z0-9][a-z0-9._-]{0,63}$, unique across every row of the users table, deleted users included. A deleted user's username can never be used again, so every audit row keeps pointing at one person.cliis reserved, because it is the actor of CLI audit rows. - Password: 12 to 256 bytes of valid UTF-8 without control characters, hashed as in section 11.
- Role:
adminoruser. - Deletion only sets
deleted_at(andupdated_at) and deletes the user's sessions. The row, its password hash, its delegations and its audit history stay in the database. A deleted user cannot log in, cannot receive delegations and cannot be changed, is listed only when deleted users are asked for, and its username stays taken. Deleted users are never restored. - Sessions are bound to the user row: every request reads the user's role and
deleted_at, and every zone-scoped request reads the delegation, so deletions, role changes and delegation changes take effect on the next request, without a new login. - Once an active admin exists, at least one always remains: demoting or deleting the last active admin is refused (HTTP
409, CLI exit1). The check and the change run in one transaction that locks the active admin rows withSELECT ... FOR UPDATE, so two admins demoting each other at the same time cannot leave none. - From the web UI an admin cannot change their own role or delete their own account, and changes their own password only on the account page, which asks for the current one.
- The first admin is created with the CLI (
user add <username> adminthroughdocker exec). Until an active admin exists, the login page shows that command.
Roles
| Capability | admin |
user |
|---|---|---|
| Zone list, zone page, records, SOA, check, export, import | every zone | delegated zones only |
| Create and delete zones | yes | no |
| Delegate and revoke zones | yes | no |
| Create users, change roles, set passwords, delete users | yes | no |
| Audit | every row | rows of their delegated zones and their own rows |
| Change their own password | yes | yes |
For a user, a zone that is not delegated to them does not exist: zone-scoped pages and API routes answer 404 exactly as for a missing zone, lists and the check of all zones contain only their delegated zones, and record ids of other zones are 404. Admin-only pages and routes answer 403.
Zone delegation
Zone delegation gives a user access to a zone in this application. It never touches the records table or the Corefile and has nothing to do with DNS delegation through NS records.
- A delegation is a row of
<prefix>webui_zone_delegations: a zone name, normalized as in section 7, and an active user with roleuser. A user can have any number of zones and a zone any number of users. Admins need no delegation, and delegating to an admin is refused (422). A user promoted to admin keeps their delegation rows, which apply again if they are demoted. - Only admins grant and revoke delegations, from the zone page or the user page. Granting requires the zone to exist in the records table (at least one row, otherwise
404) and is idempotent; revoking a delegation that does not exist is404. - Deleting a zone deletes its delegation rows in the same transaction, listed in the audit row, so a zone created later with the same name starts with none. When the rows of a zone are removed outside the application, its delegation rows remain: creating a zone with that name deletes them in the creation transaction, listed in its audit row, and until then the user page marks them "zone not found" and lets an admin revoke them.
- Deleting a user keeps their delegation rows, like the rest of the user row. They have no effect, because the user cannot log in, and zone pages do not list them.
9. Audit
As in dpsapi, the audit table records every operation, who performed it and from where; here it also records what changed.
What is an operation, with exactly one audit row each:
- Every request to
/api/v1made with a valid session, reads included, whatever the outcome: success, refused (403,404), invalid (400,413,415,422,428), conflict (409,412), busy or failed (500,503). - Every login attempt (success, wrong credentials, rate limited) and every logout.
- Every successful CLI change.
Requests without a valid session (401), requests refused by the cross-origin protection and requests to /health, /version, /static/ and the HTML pages are not operations and are only logged. Pages carry no zone, record, user or audit data: everything is read through the API, so every read of data has its audit row.
Columns:
time: UTC, with microseconds.user_id: the acting user; NULL for CLI rows and for login attempts with an unknown username.actor: the acting user's username; for login attempts the submitted username, with non-printable runes replaced by spaces and cropped to 64 runes;clifor CLI rows.origin: the client origin (section 11);localfor CLI rows.operation: one of the names below.status: the HTTP status of the response; NULL for CLI rows.error: theerrormessage of the response for statuses from400; NULL otherwise.zone,record_id,target_user_id: the objects the operation addressed, when any.before_value,after_value: for successful changes, the affected objects as JSON before and after the change. Records asid,zone,name,ttl,record_type,content; users asid,username,role,created_at,deleted_at; delegations aszone,username. Changes of several objects store arrays of the changed objects only. NULL for reads and for requests that changed nothing.
Passwords, password hashes, session tokens, cookies, request bodies and import file contents are never stored.
Writing:
- A successful change and its audit row are written in the same transaction. When the audit insert fails, the change is rolled back and the request answers
500. - For every other operation the audit row is inserted before the response is written. When the insert fails, the response is replaced by
500and no data is returned, so no read happens without its audit row, as indpsapi, where the audit insert precedes the operation. When the audit row of a500cannot be written either, the failure is only logged atERROR. - The table is append-only: the application never updates or deletes audit rows, the grants of section 6 do not allow it, and there is no retention.
Reading: admins see every row; users see the rows whose zone is currently delegated to them and the rows they performed themselves. Reading the audit through the API is itself an operation (audit_read); the audit CLI command only reads, as in dpsapi.
Operations:
| Area | Reads | Changes |
|---|---|---|
| Authentication and account | account_read |
login, logout, password_change |
| Zones | zone_list, zone_read |
zone_create, zone_delete |
| Records | record_list |
record_create, record_update, record_delete, record_bulk_delete, soa_update |
| Checks | zone_check, check_all |
|
| Zone files | zone_export, zone_import_preview |
zone_import |
| Delegation | delegation_list |
delegation_grant, delegation_revoke |
| Users | user_list, user_read |
user_create, user_role, user_password, user_delete |
| Audit | audit_read |
|
| Unknown API request | api_unknown |
Each API route maps to exactly one operation (section 11). CLI rows use user_create, user_password, user_role and user_delete.
10. Web UI
Pages are rendered by Go with html/template (a layout, pages and partials, as in gestionale-inquilini); behavior is plain JavaScript modules calling the JSON API; styling is one CSS file. Everything is embedded with go:embed and served from /static/<hash>/..., where the hash is computed from the embedded files at startup, with long-lived immutable caching. No CDN, no web fonts, no front-end build step, no Node at build time. Icons are inline SVG. Light and dark themes follow prefers-color-scheme. The layout works from 360 px wide. Every control has a label, every dialog traps focus and closes with Escape, notifications use an aria-live region. JavaScript builds the DOM with textContent and attributes only, never with HTML strings built from data.
Pages carry no zone, record, user or audit data: the server renders the layout with the current username and role, and every piece of data is read through the JSON API (section 9). The layout shows Zones, Audit and Account to everyone, Users to admins only, the current username and role, and logout. Controls a role cannot use are not rendered; the API enforces the same rules on its own.
Pages:
- Login: username, password. Until an active admin exists, the page says so and shows the
user add <username> admincommand. - Zones (
/): table with zone, record count, SOA serial (or "dynamic"), problem counts (loaded asynchronously from the check endpoint); client-side search. Admins see every zone and a "New zone" dialog with zone name, primary NS, hostmaster mailbox, additional NS hosts, SOA timers prefilled (refresh 3600, retry 600, expire 604800, minttl 300) and TTL 3600; after creation a notice about the plugin's zone reload interval. Users see only their delegated zones, without "New zone", and "No zone is delegated to you" when they have none. - Zone (
/zones/{zone}): SOA summary with an edit dialog; records table with name (@for the apex, FQDN on hover), type, TTL and value in presentation form (10 mail.example.org.,0 issue "ca.example.net"); apex first, then names in DNS canonical order, within a name SOA, NS, then types alphabetically, then values; filter by type, text search, client-side pages of 100 rows; add and edit dialogs whose fields change with the type; delete with confirmation; multi-select bulk delete; problems panel; export; link to import. Admins also get a Users panel listing the active users the zone is delegated to, with add (a picker over active users with roleuser) and remove, and zone deletion in a separate danger section that requires typing the zone name. - Import (
/zones/{zone}/import): text area or file upload, modemergeorreplace, preview table with additions, updates, deletions, unchanged and skipped entries with reasons, then apply. - Audit (
/audit): newest first, paged, filters by zone, actor, operation, kind (reads or changes) and outcome (success or error), each row showing time, actor, origin, operation, status, error and target, expandable to a field-level diff of before and after. Users see only the rows of section 9. - Account (
/account): username, role, the delegated zones for users, change password (current, new, repeat). - Users (
/users, admins): table with username, role, number of delegated zones, creation, last login and state (active, or deleted with its date); a "Show deleted users" toggle; a "New user" dialog with username, role, password and repeat. - User (
/users/{username}, admins): role selector; set password (new, repeat), which ends the user's sessions; delegated zones with add (a picker over existing zones) and remove, zones that no longer exist marked "zone not found"; a danger section to delete the user that requires typing the username and states that the username stays taken and the history stays in the audit. Deleted users are shown read-only. The admin's own row shows no role, password or delete controls and links to/account. - Version (
/version): application version and commit, rendered fromtemplates/html/version.html.
Rows that the zone check marks as errors are shown with their raw content and problems; editing one starts an empty typed form for its type (or a type selector for unknown types) and replaces the row.
11. HTTP interface
Pages
| Method | Path | Access |
|---|---|---|
GET |
/login |
none |
POST |
/login |
none |
POST |
/logout |
session |
GET |
/ |
session |
GET |
/zones/{zone} |
zone |
GET |
/zones/{zone}/import |
zone |
GET |
/audit |
session |
GET |
/account |
session |
GET |
/users |
admin |
GET |
/users/{username} |
admin |
GET |
/version |
none |
GET |
/health |
none |
GET |
/static/{hash}/... |
none |
Access: session is any active user; zone is admins and the users the zone is delegated to, a not found page with 404 for others; admin is admins only, a forbidden page with 403 for users.
Pages without a valid session redirect to /login?next=<path>; next is accepted only as a local path starting with a single /.
/health answers 200 {"status":"ok"} when a MySQL ping succeeds within 2 s, 503 {"status":"unavailable"} otherwise.
JSON API
All under /api/v1, session required (401 JSON otherwise), request bodies application/json (415 otherwise). Access as for pages: session, zone (404 for users without the delegation, as for a missing zone), admin (403 for users). Each route is exactly one audit operation (section 9).
| Method | Path | Access | Operation | Purpose |
|---|---|---|---|---|
GET |
/account |
session | account_read |
own username, role and, for users, delegated zones |
PUT |
/account/password |
session | password_change |
change the own password, body {"current": "...", "password": "..."} |
GET |
/zones |
session | zone_list |
visible zones with record count and serial |
POST |
/zones |
admin | zone_create |
create a zone with SOA and NS records |
GET |
/zones/{zone} |
zone | zone_read |
zone summary, SOA, ETag of the SOA |
DELETE |
/zones/{zone} |
admin | zone_delete |
delete every row and every delegation of the zone; body {"confirm": "<zone>"} |
GET |
/zones/{zone}/records |
zone | record_list |
all records of the zone |
POST |
/zones/{zone}/records |
zone | record_create |
create a record |
PUT |
/zones/{zone}/records/{id} |
zone | record_update |
replace a record, If-Match |
DELETE |
/zones/{zone}/records/{id} |
zone | record_delete |
delete a record, If-Match |
POST |
/zones/{zone}/records/delete |
zone | record_bulk_delete |
bulk delete, body {"records": [{"id": 1, "etag": "..."}]}, all or nothing |
PUT |
/zones/{zone}/soa |
zone | soa_update |
update the SOA, If-Match |
GET |
/zones/{zone}/check |
zone | zone_check |
problems of one zone |
GET |
/check |
session | check_all |
problems of the visible zones |
GET |
/zones/{zone}/export |
zone | zone_export |
zone file, text/plain, attachment |
POST |
/zones/{zone}/import/preview |
zone | zone_import_preview |
parse and diff, returns a fingerprint |
POST |
/zones/{zone}/import/apply |
zone | zone_import |
apply, requires the preview fingerprint |
GET |
/zones/{zone}/users |
admin | delegation_list |
active users the zone is delegated to |
PUT |
/zones/{zone}/users/{username} |
admin | delegation_grant |
delegate the zone to a user, idempotent |
DELETE |
/zones/{zone}/users/{username} |
admin | delegation_revoke |
revoke a delegation |
GET |
/users |
admin | user_list |
users; deleted=true includes deleted users |
POST |
/users |
admin | user_create |
body {"username": "...", "role": "user", "password": "..."} |
GET |
/users/{username} |
admin | user_read |
a user, deleted ones included, with delegated zones |
PUT |
/users/{username}/role |
admin | user_role |
body {"role": "admin"} |
PUT |
/users/{username}/password |
admin | user_password |
body {"password": "..."}, ends the user's sessions |
DELETE |
/users/{username} |
admin | user_delete |
body {"confirm": "<username>"}, 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. 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:
{
"id": 42,
"name": "www",
"fqdn": "www.example.org.",
"type": "A",
"ttl": 3600,
"data": {"ip": "192.0.2.10"},
"raw": null,
"etag": "\"9f2c...\"",
"problems": []
}
data is the parsed content; when the content cannot be parsed data is null and raw holds the stored string. The ETag is also returned in the ETag header of single-record responses.
Status codes: 200, 201, 204, 303 (form redirects), 400 malformed JSON or parameters, 401, 403 cross-origin request refused, admin-only route, or an admin changing their own role or password or deleting their own account through the users routes, 404 also for zones not delegated to the user, 405, 409 zone already exists, username already used (deleted users included), last active admin, or import fingerprint changed, 412, 413 body too large (64 KiB, import 2 MiB), 415, 422 validation with {"error": "...", "fields": {"ttl": "..."}}, 428, 429 login rate limit, 500, 503 database unavailable or zone busy. Error bodies are {"error": "message"} and never contain SQL errors, driver messages or stack traces.
Authentication and sessions
- Passwords are hashed with argon2id (
golang.org/x/crypto/argon2, 64 MiB, 3 iterations, parallelism 2, 16-byte salt, 32-byte key) stored as a PHC string, so parameters can change later. At most 4 hashes run at the same time. - An unknown username is verified against a fixed dummy hash, so timing and message (
invalid username or password) are the same as for a wrong password. - After 5 failures within 15 minutes for the same username or the same origin, login answers
429for 15 minutes. Counters are in memory with bounded size; a success resets the username counter. - A session token is 32 bytes from
crypto/rand, base64url without padding, in cookiecoredns_webui_sessionwithHttpOnly,SameSite=Strict,Path=/andSecureperCOOKIE_SECURE. The database stores only its SHA-256. A new token is issued at every login. Sessions end afterSESSION_IDLE_TIMEOUTwithout requests orSESSION_MAX_AGEafter login;last_seen_atis written at most once per minute. Logout deletes the row. A password change deletes every other session of the user; a password set by an admin and a user deletion delete all of them. A session is valid only while its user row has nodeleted_at; the role is read from the user row on every request. POST /loginanswers303tonexton success, renders the login page again with401on wrong credentials and with429when rate limited; these statuses are the ones stored in the audit row. Deleted users fail like unknown usernames.- Cross-site request forgery is refused for every non-safe method by
net/http'sCrossOriginProtection(Sec-Fetch-Site and Origin checks), together withSameSite=Strictand the JSON content type requirement.
Response headers
Every response: Content-Security-Policy: default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none', X-Content-Type-Options: nosniff, Referrer-Policy: no-referrer. Pages and API responses: Cache-Control: no-store. HSTS is left to the reverse proxy.
Client origin
The origin stored in sessions and audit rows is the TCP peer address. When the peer is in TRUSTED_PROXIES, it is the rightmost X-Forwarded-For entry that is not in TRUSTED_PROXIES. Forwarding headers from other peers are ignored.
12. Zone check
The check is a pure Go function over the rows of a zone, used by the API, the UI and the check command.
Errors (the plugin fails or serves something different):
| Code | Condition |
|---|---|
zone_not_fqdn |
zone value without trailing dot |
zone_case |
zone value with uppercase letters |
ttl_null |
ttl is NULL |
ttl_negative |
ttl below 0 |
content_null |
content is NULL |
content_json |
content is not a JSON object |
type_unknown |
record_type not one of the nine uppercase names |
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 |
mx_priority_key |
MX content with priority and no preference |
soa_missing |
zone without SOA |
soa_multiple |
more than one SOA |
soa_not_apex |
SOA on a non-apex name |
cname_apex |
CNAME at the apex |
cname_conflict |
CNAME next to other records or several CNAMEs on a name |
pack_failed |
the RR the plugin builds does not pack |
Warnings: ns_apex_missing, duplicate, rrset_ttl_mismatch, target_is_cname, target_no_address, below_zone_cut, txt_split, name_case, ttl_zero, soa_dynamic_serial, content_not_canonical.
13. Zone file export and import
Export writes $ORIGIN <zone>, the SOA first and the other records in the UI order, each with an explicit TTL (0 exported as 360, as served), rendered by miekg/dns. Rows with check errors are not exported; each produces a ; skipped id=<id>: <code> line at the end.
Import:
- Parsed with
miekg/dns'sZoneParser, origin set to the zone, default TTL 3600 when the file has no$TTL,$INCLUDEdisabled, classINonly. Parsing stops with an error after 10000 records,$GENERATEincluded, and the body is limited to 2 MiB. - Records of other types are listed as skipped. Records outside the zone are errors.
TXTrecords with several strings are joined into one text, with a warning that the plugin re-splits it at 255 bytes. - Every record goes through the same normalization and validation as the forms, and the resulting zone must satisfy the zone rules.
- Identity of a record is name, type and canonical content.
mergeadds missing records and updates the TTL of matching records with a different TTL;replacealso deletes records that are not in the file. When the file has an SOA, itsns,MBox, timers and TTL replace the current ones in both modes; its serial is ignored and the managed serial is bumped. - Preview returns the diff and a fingerprint: the SHA-256 of the sorted ETags of the zone's rows. Apply repeats parsing and diffing inside the zone transaction and answers
409when the fingerprint changed. Onezone_importaudit row holds the changed rows before and after.
14. Logging
log/slog with a text handler on stderr and the level semantics of dpsapi (ERROR, WARN, INFO, DEBUG, custom TRACE below DEBUG).
INFO: startup with version and commit; one record per request (method, path, status, duration, user, role, origin), except/healthand/static/which log atDEBUG; one record per committed change (operation, zone, record id, target user, actor).WARN: failed logins, rate-limited logins,403refusals, zone routes answered404because the zone is not delegated to the user, ETag and fingerprint conflicts, zone lock timeouts.ERROR: database errors, failed audit inserts, unexpected errors behind every500.DEBUG: configuration (without secrets), contract check, migrations, lock acquisition, validation failures, CLI dispatch, session cleanup counts, shutdown.TRACE: function entry and exit and every SQL statement with the identifiers of the rows it touches.
Passwords, password hashes, session tokens, cookies and the DSN never appear in logs at any level.
15. File structure
The package stays flat, as in dpsapi, with boundaries that keep every part testable on its own:
coredns-web-ui/
├── .dockerignore
├── .gitignore
├── .gitea/workflows/test.yaml
├── .gitea/workflows/image.yaml
├── LICENSE
├── README.md
├── compose.yaml
├── env.example
├── vars.example
├── dockerfile
├── makefile
├── initialize.sh
├── version.sh
├── deploy.sh
├── go.mod
├── go.sum
├── main.go
├── config.go
├── logger.go
├── type_webserver.go
├── routes.go
├── middleware.go
├── version.go
├── database.go
├── migrations.go
├── migrations/001_initial.sql
├── records_store.go
├── user_store.go
├── session_store.go
├── delegation_store.go
├── audit_store.go
├── auth.go
├── authz.go
├── audit.go
├── ratelimit.go
├── records.go
├── names.go
├── rules.go
├── check.go
├── serial.go
├── zonefile.go
├── handlers_pages.go
├── handlers_api.go
├── cli.go
├── templates/html/layout.html
├── templates/html/version.html
├── templates/html/pages/*.html
├── templates/html/partials/*.html
├── static/css/app.css
├── static/js/*.js
├── dev/Corefile
├── dev/mysql-init.sql
├── scripts/integration.sh
├── scripts/test-image.sh
├── e2e/
└── *_test.go
records.go: types, content decoding and canonical encoding, conversion tomiekg/dnsRRs, packing check.names.go: zone, owner name, host and mailbox normalization.rules.go: per-type and zone rules;check.gobuilds on them.authz.go: roles, zone visibility and delegation checks of section 8, as pure functions over the user, the role and the delegated zones.audit.go: the route to operation table, the audit row builder and the visibility filter of section 9; every API handler goes through it, so no route can skip its audit row.- Stores take a
*sql.DBor*sql.Txbehind narrow interfaces; handlers depend on the interfaces, so handler tests use fakes. - The clock and the random source are injectable.
main.goonly dispatches and decides exit codes; lower layers return errors and never callos.Exit.
Go dependencies: github.com/gorilla/mux, github.com/go-sql-driver/mysql, github.com/miekg/dns, golang.org/x/crypto, golang.org/x/term. Nothing else at runtime.
16. Dockerfile
Following netbox-mcp-server:
buildstage:${GO_BUILDER}:${GO_VERSION}(defaultgolang:1.27-alpine),go mod downloadbefore copying the sources,CGO_ENABLED=0,-trimpath,-ldflags "-w -s -X main.APP_VERSION=... -X main.COMMIT_ID=...", output/app.teststage:gofmt -lmust be empty,go vet ./...(also with-tags integration),staticcheck ./...,go test -race -count=1 ./....- Final stage
FROM scratchwith OCI labels (source,revision,version,licenses),/app, the CA bundle at/etc/ssl/cert.pem(forDB_TLS),USER 65532:65532,EXPOSE 8080,HEALTHCHECK CMD ["/app", "healthcheck"],ENTRYPOINT ["/app"].
No shell, package manager or other runtime tool in the final image.
17. Makefile and CI
The makefile follows the style of the reference repositories, with .vars (bootstrapped from vars.example on first use, as in ping.it). Go and Node commands run in containers.
| Target | Action |
|---|---|
default |
version |
clean |
remove the local binary and this project's images |
build |
static binary through the builder image |
docker |
build the image with the build arguments and labels |
dockerpush |
push ${CONTAINER_ORG}/${CONTAINER_IMAGE}:${APP_VERSION} |
test |
go test -count=1 ./... in the builder image |
lint / test-race |
docker build --target test |
integration |
scripts/integration.sh: integration tests against a MySQL container |
test-e2e |
Playwright suite against the compose test stack (section 18) |
test-image |
scripts/test-image.sh against the built image |
run |
development stack from compose.yaml |
dockerrun |
run the image with --env-file .env on ${CONTAINER_IP}:${CONTAINER_PORT} |
version |
./version.sh |
deploy |
./deploy.sh |
vars.example holds the usual build and deployment variables (GIT_HOST, GO_BUILDER, GO_VERSION, REPO_ORG, REPO_NAME, CONTAINER_ORG, CONTAINER_IMAGE, CONTAINER_IP, CONTAINER_PORT, deployment host and paths) plus MYSQL_IMAGE (mysql:8.4), COREDNS_IMAGE (git.bjphoster.com/docker/coredns-mysql:latest) and PLAYWRIGHT_IMAGE (the official Playwright image, pinned to an exact version).
Gitea Actions, as in netbox-mcp-server:
test.yaml: on pushes tomain, weekly and manually; runs theteststage, the integration tests, the E2E suite and the image tests.image.yaml: on semantic version tags; runs the same tests, builds the image with version and commit, runstest-image.sh, publishesgit.bjphoster.com/source/coredns-web-ui:<version>and, for non-prerelease tags,latest; removes the local images at the end.
18. Testing strategy
Every function and every meaningful branch has automated coverage. Tests clean up every container, volume and image they create, also after failures, and never remove images that existed before the run.
Unit tests
- Configuration: defaults, every variable valid and invalid, empty values, port and duration boundaries, CIDR lists, prefix pattern,
DB_PASSWORDnever in error messages. - Logger: level parsing and filtering,
TRACE, secrets never emitted. - Names: zones, owner names (apex,
@, wildcards, absolute in and out of zone, uppercase, length limits, underscores, invalid characters), hosts, mailbox conversion with escaped dots. - Records: every type with valid values, every boundary (0, 65535, 65536, 2147483647, 2147483648, 4096-byte TXT, 4097, backslash, non-ASCII, control characters), IPv4-mapped AAAA, IPv6 in A; canonical encoding; tolerant decoding of other writers' JSON (key order, extra keys, numbers as strings refused); RR conversion identical to the plugin's for each type; packing.
- Zone rules and check: each error and warning code with a minimal triggering zone and a minimal non-triggering one; mixed broken rows.
- Serial: new zone (
YYYYMMDD00), first change of the day, consecutive changes on the same day, the 100th change of a day (99) and the next one (the following day's00), a serial already ahead of today, a serial from an earlier day, uint32 wrap,0skipped, dynamic serial untouched, one bump per transaction. - ETag computation including
NULLmarkers. - Zone files: export ordering, TTL 0, skipped rows; import of every supported type, unsupported types, out-of-zone names,
$INCLUDE,$GENERATE, the record limit, multi-string TXT, merge and replace diffs, SOA handling, fingerprint. - Auth: argon2id hash and verify, PHC parsing, dummy hash path, rate limiter windows and bounds, session expiry with an injected clock, token generation, sessions of deleted users refused, role read on every request.
- Users: username pattern, reserved
cli, usernames of deleted users taken, password rules, roles, the last active admin rule, the own account rules of the users routes. - Authorization: a matrix of every page and API route against an admin, a user with the zone delegated, a user without it, a promoted user, a demoted admin, the session of a deleted user and no session, with the expected status; lists, the check of all zones and audit reads filtered to the visible zones;
404responses for missing and for non-delegated zones identical in status and body. - Audit: exactly one row per operation for every route and outcome, with the exact columns; change rows written in the change transaction; a failing audit insert rolls the change back and turns a read into
500without data; no password, hash, token, cookie or body in any row; the operation table covers every route. - Client origin with and without trusted proxies, IPv4 and IPv6.
- HTTP handlers with fake stores: every route, method, status code, error body shape,
If-Matchhandling, body limits, content types, redirects withnext, security headers, cross-origin refusal. - CLI: every command, exact usage text, every usage error, stdin password handling (terminal and pipe), exact padded output, exit codes, stdout and stderr routing.
Integration tests
Build tag integration, run by scripts/integration.sh against a disposable mysql:8.4 container with the records table created as the plugin documents it:
- Contract check: missing table, missing column, incompatible type, non-default prefix.
- Migrations: fresh database, idempotent rerun, two processes migrating at the same time.
- The least-privilege grants of section 6 are sufficient for every operation, and the CoreDNS user cannot read the application tables.
- The application user cannot
DELETEusers norUPDATEorDELETEaudit rows, and the foreign keys of sessions, delegations and audit rows hold. - Two admins demoting each other at the same time leave one active admin; a revocation, demotion or user deletion racing a write either blocks the write or happens after it, never in between.
- Every store operation, transactions and rollback (a forced failure after the record write leaves neither the record nor the audit row),
DATETIME(6)UTC round trip, utf8mb4 data in audit rows. - Zone lock contention and timeout; ETag conflicts caused by a direct
UPDATEfrom another connection; import fingerprint conflicts.
End-to-end tests
Playwright Test, running in a container built from the pinned Playwright image with dnsutils added, against a compose stack on an isolated network: MySQL, CoreDNS from git.bjphoster.com/docker/coredns-mysql with a Corefile using the mysql plugin, zone_update_interval 1s and no cache, and the application image under test. Each test group gets its own database and users.
The central invariant: every change made through the UI is verified three ways, through the UI, through the rows in MySQL (exact zone, name, ttl, record_type and canonical content) and through dig against CoreDNS (rcode, answer section, TTL, authority SOA serial). Every row the application writes is served by CoreDNS without SERVFAIL or NOTIMP and with exactly the entered data.
Core flow:
- Start the stack and wait for
/health. - The login page shows the bootstrap command; create the first admin through
docker exec ... /app user add <username> admin, log in. - Create a zone, wait for the plugin's zone reload, verify SOA and NS answers.
- Create, edit and delete records of all nine types, including wildcards, CNAME chains, null MX and SRV
.targets, verifying each change withdigand the SOA serial bump. - Bulk delete; export; replace-import of the export produces no changes; merge and replace imports with diffs verified.
- Check panel and
checkCLI against rows broken on purpose through direct SQL (each error code), and the UI's repair of those rows. - Users and delegation: the admin creates two users with role
userand 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 withdig; the second sees no zone; both get404on every other zone and403on 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 withdeleted_atset 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. - Audit: every operation of the previous steps, reads and refused requests included, has exactly one row in MySQL with the expected columns; the audit page and the
auditCLI show them; users see only their rows. - Password change, logout, session expiry, deletion of the zone and of its delegations.
Personas, as in dpsapi:
- Power user: dozens of zones and thousands of records, dozens of users with overlapping delegations, every type, two browser contexts editing the same records (conflict shown, no lost update), several sessions, application restart mid-session, large imports, zones page and zone page within performance budgets (zone with 10000 records interactive within 2 s).
- Stupid user: IPv6 in an A record, missing or extra trailing dots,
www.example.orgwithout dot in the name field (FQDN preview shows the doubled name), CNAME at the apex or next to an A record, deleting the last NS or the SOA, double submits, back button after deletion, expired session mid-form, wrong zone name or username in the deletion confirmations, short passwords, a new user with the username of a deleted one, an admin trying to demote or delete themselves, delegating a zone to an admin. - Malicious user: script payloads in every field and in usernames rendered on the audit page, requests from a second origin served by the test stack (refused), SQL injection in every field, path parameter and filter, path traversal in
/static/and{zone}, record ids from another zone, a user reaching zones not delegated to them through URLs, record ids, bulk delete ids, import, export, check and audit filters, a user calling admin routes, changing their own role or delegating zones to themselves, sessions reused after demotion, revocation or deletion, zone names guessed through status codes or timing, session fixation and cookie tampering, brute force (429), forgedX-Forwarded-Forfrom an untrusted peer, oversized and deeply nested bodies,$INCLUDE /etc/passwdand$GENERATEexplosions in imports, control characters, NUL bytes, confusable Unicode. - Fuzzer: seeded random API payloads for every endpoint and record type, failing seeds recorded; assertions are no unexpected
5xx, bounded errors, no secret disclosure, the zone check reports no errors for application-written rows, CoreDNS never answers SERVFAIL or NOTIMP for them, every request with a session has exactly one audit row, and valid operations keep working afterwards.
A long operator session mixes valid, mistaken, hostile and random actions on one live instance and checks the invariants periodically. Accessibility is checked with axe-core (no serious or critical violations) on every page in both themes; screenshots at 360 px and 1440 px in both themes are kept as artifacts. Reports redact cookies and passwords.
Image tests
scripts/test-image.sh: labels match version and commit, the image runs as 65532, contains no shell, version, help and healthcheck work through docker exec, the container becomes healthy against a MySQL container, the user CLI works through docker exec (user add with both roles, user role, user delete leaving the row with deleted_at, user list all), SIGTERM stops it with exit 0 within the grace period.
19. Development stack and deployment
compose.yaml runs the development stack bound to 127.0.0.1: mysql:8.4 initialized by dev/mysql-init.sql (database, records table as documented by the plugin, the CoreDNS read-only user, the application user with the grants of section 6), CoreDNS from git.bjphoster.com/docker/coredns-mysql with dev/Corefile (mysql plugin, DSN from the environment, zone_update_interval 10s) published on a high UDP and TCP port, and the application built from the working tree. env.example lists every variable of section 4 with development values.
Production runs the published image from its repository in the deployments organization, following the conventions of the other services there, behind the HTTPS reverse proxy with COOKIE_SECURE=true and TRUSTED_PROXIES set to the proxy's network. The application needs no volume. deploy.sh follows the usual flow (pull, set the version in .env, docker compose pull, docker compose up -d).
20. README requirements
Document only the implemented behavior: purpose, the relationship with the CoreDNS mysql plugin and its table, required MySQL grants, environment variables and defaults, the plugin behaviors of section 3 visible to users (zone reload interval, SOA serial, TTL 0), CLI usage with the exact usage text, roles and zone delegation, user management and deletion through deleted_at, the audit table and what it records, first admin bootstrap through docker exec, /health, the development stack, build and test commands, and the deployment contract. No sections about future features or plans.
21. Implementation order
- Scaffolding: environment configuration, logger, server lifecycle,
/version,/health, CLI dispatch withhelp,version,healthcheck, dockerfile, makefile, CI, compose stack. - Database layer: connection, contract check, migrations, stores, integration tests.
- Record model: names, records, rules, check, serial, ETags, with unit tests.
- Authentication, authorization and audit: user CLI with roles, argon2id, sessions, login and logout, rate limiting, roles and zone delegation checks, the audit writer and its operation table, middleware, security headers.
- JSON API: zones, records, SOA, bulk delete, check, audit, account, users, delegations.
- UI pages, Users and User pages included.
- Import and export.
checkandauditCLI.- E2E suite, image tests, README.
Each phase ends with all tests green and its commits.
22. Definition of done
- The binary starts the HTTP server with no arguments and provides
help,version,healthcheck,user list|add|passwd|role|delete,check [zone]andaudit [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.
- 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.
- 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 row written by the application is served by CoreDNS with exactly the entered data, verified end to end with
dig. - The zone check reports every condition of section 12 and the UI can repair broken rows.
- Export and import round-trip without changes.
- Authentication, sessions, rate limiting, cross-origin protection and security headers behave as specified; secrets never reach logs, audit rows or HTTP responses.
- The final image is built in stages, runs from
scratchas a non-root user, has a workingHEALTHCHECKand carries the OCI labels. - No YAML configuration, no front-end build step, no Node on the host.
- Unit, integration, E2E and image tests pass in containers, locally and in Gitea Actions.