Support a separate database for Web UI tables
This commit is contained in:
1 parent
a2f8e59d9b
commit
f464dc0af9
38 files changed
+857
-279
No files matched your search
@@ -86,7 +86,7 @@ CREATE TABLE `coredns_records` (
|
||||
) 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.
|
||||
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 queries `information_schema.COLUMNS` with `TABLE_SCHEMA` set to `DB_NAME` and verifies that the table has the six columns with compatible types. If the check fails, the application exits with an 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
|
||||
|
||||
@@ -138,6 +138,8 @@ Configuration comes from environment variables only. No configuration file is re
|
||||
| `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` |
|
||||
| `DB_WEBUI_NAME` | no | `DB_NAME` | Existing database for Web UI tables on the same server; `^[A-Za-z0-9_$-]{1,64}$` |
|
||||
| `DB_WEBUI_TABLE_PREFIX` | no | `DB_TABLE_PREFIX` | Optional prefix for Web UI tables; an explicit empty value is valid |
|
||||
| `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 |
|
||||
@@ -147,7 +149,7 @@ Configuration comes from environment variables only. No configuration file is re
|
||||
| `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`.
|
||||
Validation happens before any other work. Missing required variables and invalid values produce a message naming the variable and exit code `2`. Both table prefixes must match `^[A-Za-z0-9_]{0,32}$`. Empty values are accepted for the two table prefixes and `TRUSTED_PROXIES`.
|
||||
|
||||
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.
|
||||
|
||||
@@ -211,7 +213,7 @@ Usage errors are fixed messages prefixed by `coredns-web-ui: usage error: ` that
|
||||
|
||||
## 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.
|
||||
The application keeps its own tables in `DB_WEBUI_NAME`, using `DB_WEBUI_TABLE_PREFIX` before `webui_`. Both settings default to the records settings for existing installations. The single pool selects `DB_WEBUI_NAME` and uses database-qualified table names for both schemas. Migrations use validated identifiers and run in `DB_WEBUI_NAME` under the migration row lock in that database. They apply the embedded SQL files (`migrations/001_initial.sql`, ...) in order and store the version in the single row of `<prefix>webui_schema`.
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS `coredns_webui_schema` (
|
||||
@@ -301,7 +303,7 @@ GRANT SELECT, INSERT, DELETE, CREATE, ALTER, INDEX, REFERENCES ON `coredns`.`cor
|
||||
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.
|
||||
With a separate Web UI database, apply the six `webui_` grants there using its configured prefix. 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.
|
||||
|
||||
@@ -352,6 +354,8 @@ Warnings:
|
||||
|
||||
### Concurrency
|
||||
|
||||
When the two databases differ, each DNS write uses one InnoDB transaction spanning both schemas on the same server.
|
||||
|
||||
Every write starts a transaction and updates its zone key in `<prefix>webui_locks` (10 s acquisition timeout, HTTP 503 "zone busy" on timeout or deadlock). Changing this row supplies a Galera certification key. The application then checks 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), reads the zone's rows, applies the rules, writes the records, SOA serial and audit row, and commits, releasing 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.
|
||||
@@ -756,10 +760,12 @@ Every function and every meaningful branch has automated coverage. Tests clean u
|
||||
|
||||
### 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:
|
||||
Build tag `integration`, run by `scripts/integration.sh` in shared and separate database layouts against a disposable `mysql:8.4` container with the plugin's records table:
|
||||
|
||||
- Contract check: missing table, missing column, incompatible type, non-default prefix.
|
||||
- Migrations: fresh database, idempotent rerun, two processes migrating at the same time.
|
||||
- Moving an existing installation with `RENAME TABLE` preserves audit rows, delegations and foreign keys.
|
||||
- A Web UI account with only table-level DML on the records database and full grants on its own database can migrate, run CLI commands and commit or roll back writes across both databases.
|
||||
- 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 `DELETE` users nor `UPDATE` or `DELETE` audit 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.
|
||||
@@ -768,7 +774,7 @@ Build tag `integration`, run by `scripts/integration.sh` against a disposable `m
|
||||
|
||||
### 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.
|
||||
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 records database and users. The suite exercises shared and separate Web UI databases, an independent Web UI prefix, and database-level grants confined to the Web UI database.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -115,7 +115,7 @@ GRANT SELECT, INSERT, DELETE, CREATE, ALTER, INDEX, REFERENCES ON `coredns`.`cor
|
||||
GRANT SELECT, INSERT, CREATE, ALTER, INDEX, REFERENCES ON `coredns`.`coredns_webui_audit` TO 'coredns_webui'@'%';
|
||||
```
|
||||
|
||||
Replace `coredns` with the database and `coredns_` with the table prefix. 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.
|
||||
Use `DB_NAME` and `DB_TABLE_PREFIX` for the records grant. Use `DB_WEBUI_NAME` and `DB_WEBUI_TABLE_PREFIX` for the six `webui_` grants. A database-level grant confined to a dedicated Web UI database also works. The table grants shown here enforce additional limits on the application account, including keeping users and audit entries from being deleted and keeping audit entries from being updated.
|
||||
|
||||
The CoreDNS user keeps `SELECT` on `coredns_records` only, so it cannot read password hashes, sessions, delegations or the audit:
|
||||
|
||||
@@ -126,7 +126,7 @@ GRANT SELECT ON `coredns`.`coredns_records` TO 'coredns'@'%';
|
||||
|
||||
### Application schema and migrations
|
||||
|
||||
Migrations are embedded SQL files (`migrations/001_initial.sql`, ...) applied in order. The current version is the single row of `<prefix>webui_schema`. The table prefix is substituted into the SQL after validation; it is the only value ever interpolated into SQL. Startup creates `<prefix>webui_locks` if absent and locks the migration row with a 30-second acquisition budget. The migration transaction holds that row while a separate connection runs the DDL, which commits implicitly. This serializes startup on a single database writer. For Galera, route all application connections to the same writer during migrations, for example through a single-writer ProxySQL hostgroup.
|
||||
Migrations are embedded SQL files (`migrations/001_initial.sql`, ...) applied in order in `DB_WEBUI_NAME`. The current version is the single row of `<prefix>webui_schema`. The migration SQL uses the validated Web UI database and table prefix. Startup creates `<prefix>webui_locks` in that database if absent and locks its migration row with a 30-second acquisition budget. The migration transaction holds that row while a separate connection from the same pool runs the DDL, which commits implicitly. This serializes startup on a single database writer. For Galera, route all application connections to the same writer during migrations, for example through a single-writer ProxySQL hostgroup.
|
||||
|
||||
| Table | Content |
|
||||
|---|---|
|
||||
@@ -139,9 +139,28 @@ Migrations are embedded SQL files (`migrations/001_initial.sql`, ...) applied in
|
||||
|
||||
All times are UTC. Rows of the users table are never deleted, so the foreign keys from sessions, delegations and audit rows always resolve. Audit rows have no foreign key to the records table, so deleted records keep their history. The audit `record_id` column is `BIGINT` to preserve IDs across the full range of an `INT UNSIGNED` records table.
|
||||
|
||||
### Move an existing installation to a separate database
|
||||
|
||||
1. Stop all Web UI instances and pause its database-writing CLI commands. Back up the six application tables. Use the database writer for the following operations.
|
||||
2. As a database administrator, create an empty database on the same server and move the six tables in one `RENAME TABLE` statement. This example keeps the `coredns_` prefix and moves the application tables from `coredns` to `coredns_webui`.
|
||||
|
||||
```sql
|
||||
CREATE DATABASE `coredns_webui` DEFAULT CHARACTER SET utf8mb4;
|
||||
RENAME TABLE
|
||||
`coredns`.`coredns_webui_schema` TO `coredns_webui`.`coredns_webui_schema`,
|
||||
`coredns`.`coredns_webui_locks` TO `coredns_webui`.`coredns_webui_locks`,
|
||||
`coredns`.`coredns_webui_users` TO `coredns_webui`.`coredns_webui_users`,
|
||||
`coredns`.`coredns_webui_sessions` TO `coredns_webui`.`coredns_webui_sessions`,
|
||||
`coredns`.`coredns_webui_zone_delegations` TO `coredns_webui`.`coredns_webui_zone_delegations`,
|
||||
`coredns`.`coredns_webui_audit` TO `coredns_webui`.`coredns_webui_audit`;
|
||||
```
|
||||
|
||||
3. Apply the six Web UI table grants shown above to the destination database. Table-specific grants stay on the old names after a rename. Revoke those old grants and keep the records-table grants for the application and CoreDNS accounts.
|
||||
4. Set `DB_WEBUI_NAME=coredns_webui` on every Web UI instance and for the CLI. Leave `DB_WEBUI_TABLE_PREFIX` unset to retain `DB_TABLE_PREFIX`. If you also change the prefix, change all six destination names and grants accordingly. Restart the Web UI and verify that `/health` reports ready and an existing administrator can sign in.
|
||||
|
||||
## Configuration
|
||||
|
||||
Configuration comes only from environment variables. No configuration file is read. A variable that is set but empty is an error, except `DB_TABLE_PREFIX` (an empty prefix is valid) and `TRUSTED_PROXIES` (empty means no trusted proxy).
|
||||
Configuration comes only from environment variables. No configuration file is read. Empty values are accepted for `DB_TABLE_PREFIX`, `DB_WEBUI_TABLE_PREFIX` and `TRUSTED_PROXIES`.
|
||||
|
||||
| Variable | Required | Default | Accepted values |
|
||||
|---|---|---|---|
|
||||
@@ -152,6 +171,8 @@ Configuration comes only from environment variables. No configuration file is re
|
||||
| `DB_NAME` | yes | none | Database holding the records table; at most 64 characters, no control characters |
|
||||
| `DB_TLS` | no | `false` | `false`, `true`, `skip-verify` or `preferred` |
|
||||
| `DB_TABLE_PREFIX` | no | `coredns_` | `^[A-Za-z0-9_]{0,32}$`; must equal the plugin's `table_prefix` |
|
||||
| `DB_WEBUI_NAME` | no | `DB_NAME` | Existing database for the Web UI tables on the same server; `^[A-Za-z0-9_$-]{1,64}$` |
|
||||
| `DB_WEBUI_TABLE_PREFIX` | no | `DB_TABLE_PREFIX` | `^[A-Za-z0-9_]{0,32}$`; an explicit empty value uses names such as `webui_users` |
|
||||
| `HTTP_ADDR` | no | `0.0.0.0` | A literal IPv4 or IPv6 address (no host names, ports or zones) |
|
||||
| `HTTP_PORT` | no | `8080` | Integer from `1` to `65535`, ASCII digits only |
|
||||
| `LOG_LEVEL` | no | `INFO` | `ERROR`, `WARN`, `INFO`, `DEBUG`, `TRACE`, case-insensitive |
|
||||
@@ -165,6 +186,8 @@ Validation happens before any other work. The first problem is reported as `core
|
||||
|
||||
The database connection is built with `mysql.Config` from `github.com/go-sql-driver/mysql` (`ParseTime`, UTC, charset `utf8mb4` via `SET NAMES`, connect timeout 5 s, read and write timeouts 30 s, no multi statements, no client-side interpolation). The pool holds at most 10 open and 10 idle connections with a connection lifetime of 1 minute. The DSN and the password are never logged.
|
||||
|
||||
The connection selects `DB_WEBUI_NAME` as its default database and qualifies tables with their configured database. The records contract checks `DB_NAME`. The same pool and credentials serve both databases, and each DNS write commits the records, SOA serial and audit together under the Web UI's zone lock.
|
||||
|
||||
Use a database with the `utf8mb4` character set and InnoDB. The database may use any `utf8mb4` collation. Usernames and delegation keys use exact matching, and zone names are normalized before DNS comparisons. Existing application tables keep their collations and data. On new databases the audit tables store JSON payloads as text; existing native JSON columns still work. CI tests MySQL 5.7, MySQL 8.4, MariaDB 10.11 standalone and MariaDB 10.11 Galera.
|
||||
|
||||
`TRUSTED_PROXIES` controls the client origin stored in sessions and audit rows. By default it is the TCP peer address. When the peer is inside a trusted CIDR, it is the rightmost `X-Forwarded-For` entry that is not itself trusted; forwarding headers from other peers are ignored.
|
||||
|
||||
@@ -176,7 +176,7 @@ func (m *matrixSQL) exec(w *matrixWorld, query string, args []any) fdbResponse {
|
||||
switch {
|
||||
case has("webui_locks"):
|
||||
return fdbResponse{rowsAffected: 1}
|
||||
case has("FROM `coredns_webui_users` u WHERE u.`id` = ?"):
|
||||
case has("FROM `webui`.`coredns_webui_users` u WHERE u.`id` = ?"):
|
||||
id := args[0].(int64)
|
||||
for _, u := range w.state.users {
|
||||
if u.ID == id {
|
||||
@@ -184,7 +184,7 @@ func (m *matrixSQL) exec(w *matrixWorld, query string, args []any) fdbResponse {
|
||||
}
|
||||
}
|
||||
return fdbResponse{}
|
||||
case has("SELECT 1 FROM `coredns_webui_zone_delegations` WHERE `zone` = CAST(? AS BINARY) AND `user_id` = ?"):
|
||||
case has("SELECT 1 FROM `webui`.`coredns_webui_zone_delegations` WHERE `zone` = CAST(? AS BINARY) AND `user_id` = ?"):
|
||||
if _, ok := w.state.delegations[delegationKey{args[0].(string), args[1].(int64)}]; ok {
|
||||
return fdbResponse{rows: fdbRow(int64(1))}
|
||||
}
|
||||
@@ -220,7 +220,7 @@ func (m *matrixSQL) exec(w *matrixWorld, query string, args []any) fdbResponse {
|
||||
rows = append(rows, []driver.Value{d.Zone, d.UserID, d.Username, d.CreatedAt, d.CreatedBy})
|
||||
}
|
||||
return fdbResponse{rows: rows}
|
||||
case has("DELETE FROM `coredns_webui_zone_delegations` WHERE `zone` = CAST(? AS BINARY)"):
|
||||
case has("DELETE FROM `webui`.`coredns_webui_zone_delegations` WHERE `zone` = CAST(? AS BINARY)"):
|
||||
var n int64
|
||||
for k := range w.state.delegations {
|
||||
if k.zone == args[0] {
|
||||
@@ -229,14 +229,14 @@ func (m *matrixSQL) exec(w *matrixWorld, query string, args []any) fdbResponse {
|
||||
}
|
||||
}
|
||||
return fdbResponse{rowsAffected: n}
|
||||
case has("INSERT INTO `coredns_records`"):
|
||||
case has("INSERT INTO `coredns`.`coredns_records`"):
|
||||
w.nextID++
|
||||
w.records = append(w.records, recordRow{
|
||||
ID: w.nextID, Zone: args[0].(string), Name: args[1].(string), TTL: matrixNullInt(args[2]),
|
||||
Content: matrixNullString(args[3]), RecordType: args[4].(string),
|
||||
})
|
||||
return fdbResponse{lastInsertID: w.nextID, rowsAffected: 1}
|
||||
case has("UPDATE `coredns_records`"):
|
||||
case has("UPDATE `coredns`.`coredns_records`"):
|
||||
i := slices.IndexFunc(w.records, func(r recordRow) bool { return r.ID == args[5] })
|
||||
if i < 0 {
|
||||
return fdbResponse{}
|
||||
@@ -246,15 +246,15 @@ func (m *matrixSQL) exec(w *matrixWorld, query string, args []any) fdbResponse {
|
||||
Content: matrixNullString(args[3]), RecordType: args[4].(string),
|
||||
}
|
||||
return fdbResponse{rowsAffected: 1}
|
||||
case has("DELETE FROM `coredns_records` WHERE `id` = ?"):
|
||||
case has("DELETE FROM `coredns`.`coredns_records` WHERE `id` = ?"):
|
||||
n := len(w.records)
|
||||
w.records = slices.DeleteFunc(w.records, func(r recordRow) bool { return r.ID == args[0] })
|
||||
return fdbResponse{rowsAffected: int64(n - len(w.records))}
|
||||
case has("DELETE FROM `coredns_records`" + zoneRowsWhere):
|
||||
case has("DELETE FROM `coredns`.`coredns_records`" + zoneRowsWhere):
|
||||
n := len(w.records)
|
||||
w.records = slices.DeleteFunc(w.records, func(r recordRow) bool { return zoneAPITestKey(r.Zone) == args[0] })
|
||||
return fdbResponse{rowsAffected: int64(n - len(w.records))}
|
||||
case has("INSERT INTO `coredns_webui_audit`"):
|
||||
case has("INSERT INTO `webui`.`coredns_webui_audit`"):
|
||||
e := auditEntry{
|
||||
Time: args[0].(time.Time), UserID: matrixNullInt(args[1]), Actor: args[2].(string), Origin: args[3].(string),
|
||||
Operation: args[4].(string), Status: matrixNullInt(args[5]), Error: matrixNullString(args[6]),
|
||||
|
||||
@@ -172,7 +172,7 @@ func matrixZoneCases() []matrixCase {
|
||||
{name: "addressed zone of a refusal", op: opZoneCreate, method: "POST", path: "/zones", persona: "alice", body: mxCreateNew,
|
||||
status: 403, msg: msgAdminRequired, zone: "new.org."},
|
||||
{name: "record insert failure", op: opZoneCreate, method: "POST", path: "/zones", persona: "admin", body: mxCreateStale,
|
||||
status: 500, msg: msgInternalError, zone: mxStale, setup: mxSQLFail(errMatrixInternal, "INSERT INTO `coredns_records`"),
|
||||
status: 500, msg: msgInternalError, zone: mxStale, setup: mxSQLFail(errMatrixInternal, "INSERT INTO `coredns`.`coredns_records`"),
|
||||
check: func(t *testing.T, env *matrixEnv, res webResult) {
|
||||
mxUnchanged(t, env, res)
|
||||
if !env.h.store.hasDelegation(mxStale, mxUserID("alice")) {
|
||||
@@ -180,7 +180,7 @@ func matrixZoneCases() []matrixCase {
|
||||
}
|
||||
}},
|
||||
{name: "change audit failure", op: opZoneCreate, method: "POST", path: "/zones", persona: "admin", body: mxCreateNew,
|
||||
status: 500, msg: msgInternalError, zone: "new.org.", setup: mxSQLFail(errMatrixInternal, "INSERT INTO `coredns_webui_audit`"), check: mxUnchanged},
|
||||
status: 500, msg: msgInternalError, zone: "new.org.", setup: mxSQLFail(errMatrixInternal, "INSERT INTO `webui`.`coredns_webui_audit`"), check: mxUnchanged},
|
||||
{name: "zone busy", op: opZoneCreate, method: "POST", path: "/zones", persona: "admin", body: mxCreateNew,
|
||||
status: 503, msg: msgZoneBusy, zone: "new.org.", setup: mxBusy},
|
||||
{name: "connection failure", op: opZoneCreate, method: "POST", path: "/zones", persona: "admin", body: mxCreateNew,
|
||||
@@ -217,7 +217,7 @@ func matrixZoneCases() []matrixCase {
|
||||
{name: "confirmation mismatch", op: opZoneDelete, method: "DELETE", path: "/zones/example.org.", persona: "admin", body: `{"confirm":"other.org"}`,
|
||||
status: 422, msg: "validation failed", zone: mxZone, check: mxUnchanged},
|
||||
{name: "change audit failure", op: opZoneDelete, method: "DELETE", path: "/zones/example.org.", persona: "admin", body: `{"confirm":"example.org"}`,
|
||||
status: 500, msg: msgInternalError, zone: mxZone, setup: mxSQLFail(errMatrixInternal, "INSERT INTO `coredns_webui_audit`"),
|
||||
status: 500, msg: msgInternalError, zone: mxZone, setup: mxSQLFail(errMatrixInternal, "INSERT INTO `webui`.`coredns_webui_audit`"),
|
||||
check: func(t *testing.T, env *matrixEnv, res webResult) {
|
||||
mxUnchanged(t, env, res)
|
||||
if !env.h.store.hasDelegation(mxZone, mxUserID("alice")) {
|
||||
@@ -227,7 +227,7 @@ func matrixZoneCases() []matrixCase {
|
||||
{name: "zone busy", op: opZoneDelete, method: "DELETE", path: "/zones/example.org.", persona: "admin", body: `{"confirm":"example.org"}`,
|
||||
status: 503, msg: msgZoneBusy, zone: mxZone, setup: mxBusy, check: mxUnchanged},
|
||||
{name: "connection failure", op: opZoneDelete, method: "DELETE", path: "/zones/example.org.", persona: "admin", body: `{"confirm":"example.org"}`,
|
||||
status: 503, msg: msgDatabaseDown, zone: mxZone, setup: mxSQLFail(errMatrixNet, "DELETE FROM `coredns_records`"), check: mxUnchanged},
|
||||
status: 503, msg: msgDatabaseDown, zone: mxZone, setup: mxSQLFail(errMatrixNet, "DELETE FROM `coredns`.`coredns_records`"), check: mxUnchanged},
|
||||
|
||||
{name: "admin", op: opZoneCheck, method: "GET", path: "/zones/example.org./check", persona: "admin", status: 200, zone: mxZone},
|
||||
{name: "user", op: opZoneCheck, method: "GET", path: "/zones/example.org./check", persona: "alice", status: 200, zone: mxZone},
|
||||
@@ -265,7 +265,7 @@ func matrixRecordCases() []matrixCase {
|
||||
return []matrixCase{
|
||||
{name: "change audit failure", op: op, method: method, path: path, persona: "admin", body: body, ifMatch: ifMatch,
|
||||
status: 500, msg: msgInternalError, zone: mxZone, record: changed,
|
||||
setup: mxSQLFail(errMatrixInternal, "INSERT INTO `coredns_webui_audit`"), check: mxUnchanged},
|
||||
setup: mxSQLFail(errMatrixInternal, "INSERT INTO `webui`.`coredns_webui_audit`"), check: mxUnchanged},
|
||||
{name: "zone busy", op: op, method: method, path: path, persona: "alice", body: body, ifMatch: ifMatch,
|
||||
status: 503, msg: msgZoneBusy, zone: mxZone, record: record, setup: mxBusy, check: mxUnchanged},
|
||||
{name: "connection failure", op: op, method: method, path: path, persona: "admin", body: body, ifMatch: ifMatch,
|
||||
@@ -415,9 +415,9 @@ func matrixFileCases() []matrixCase {
|
||||
body: strings.Replace(apply, "192.0.2.10", "not-an-address", 1), status: 422, msg: "the file has errors", zone: mxZone, check: mxUnchanged},
|
||||
}
|
||||
for _, c := range []matrixCase{
|
||||
{name: "change audit failure", persona: "admin", status: 500, msg: msgInternalError, setup: mxSQLFail(errMatrixInternal, "INSERT INTO `coredns_webui_audit`")},
|
||||
{name: "change audit failure", persona: "admin", status: 500, msg: msgInternalError, setup: mxSQLFail(errMatrixInternal, "INSERT INTO `webui`.`coredns_webui_audit`")},
|
||||
{name: "zone busy", persona: "alice", status: 503, msg: msgZoneBusy, setup: mxBusy},
|
||||
{name: "connection failure", persona: "admin", status: 503, msg: msgDatabaseDown, setup: mxSQLFail(errMatrixNet, "INSERT INTO `coredns_records`")},
|
||||
{name: "connection failure", persona: "admin", status: 503, msg: msgDatabaseDown, setup: mxSQLFail(errMatrixNet, "INSERT INTO `coredns`.`coredns_records`")},
|
||||
} {
|
||||
c.op, c.method, c.path, c.body, c.zone, c.check = opZoneImport, "POST", "/zones/example.org./import/apply", apply, mxZone, mxUnchanged
|
||||
cases = append(cases, c)
|
||||
|
||||
@@ -145,7 +145,7 @@ func (a *app) runDatabaseCommand(ctx context.Context, args []string) (err error)
|
||||
}
|
||||
|
||||
func (a *app) connectDatabase(ctx context.Context, cfg Config, log *slog.Logger) (*sql.DB, tableNames, error) {
|
||||
t, err := newTableNames(cfg.DBTablePrefix)
|
||||
t, err := tableNamesFor(cfg)
|
||||
if err != nil {
|
||||
return nil, tableNames{}, err
|
||||
}
|
||||
|
||||
+5
-5
@@ -197,7 +197,7 @@ type cliHarness struct {
|
||||
func newCLIHarness(t *testing.T, stdin string) *cliHarness {
|
||||
h := &cliHarness{
|
||||
env: map[string]string{
|
||||
"DB_HOST": "db", "DB_USER": "u", "DB_PASSWORD": "dbpass-secret", "DB_NAME": "coredns", "LOG_LEVEL": "error",
|
||||
"DB_HOST": "db", "DB_USER": "u", "DB_PASSWORD": "dbpass-secret", "DB_NAME": "coredns", "DB_WEBUI_NAME": "webui", "LOG_LEVEL": "error",
|
||||
},
|
||||
users: &fakeUsers{zones: map[int64]int64{}, sessions: map[int64]int64{}},
|
||||
}
|
||||
@@ -852,7 +852,7 @@ func TestSQLReadBackend(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
q := state.Queries()
|
||||
if len(q) != 3 || !strings.Contains(q[0], "GROUP BY") || !strings.Contains(q[1], "`coredns_records`") || !strings.Contains(q[2], "`coredns_webui_audit`") {
|
||||
if len(q) != 3 || !strings.Contains(q[0], "GROUP BY") || !strings.Contains(q[1], "`coredns`.`coredns_records`") || !strings.Contains(q[2], "`webui`.`coredns_webui_audit`") {
|
||||
t.Fatal(q)
|
||||
}
|
||||
}
|
||||
@@ -962,9 +962,9 @@ func TestFormatCLITime(t *testing.T) {
|
||||
func cliSQLHandler() fdbHandler {
|
||||
return func(q string, args []any) fdbResponse {
|
||||
switch {
|
||||
case strings.HasPrefix(q, "INSERT INTO `coredns_webui_users`"):
|
||||
case strings.HasPrefix(q, "INSERT INTO `webui`.`coredns_webui_users`"):
|
||||
return fdbResponse{lastInsertID: 7}
|
||||
case strings.HasPrefix(q, "INSERT INTO `coredns_webui_audit`"):
|
||||
case strings.HasPrefix(q, "INSERT INTO `webui`.`coredns_webui_audit`"):
|
||||
return fdbResponse{lastInsertID: 1}
|
||||
case strings.Contains(q, "COUNT(*)"):
|
||||
return fdbResponse{rows: [][]driver.Value{append(userValues(7, "alice", "admin", false), int64(0))}}
|
||||
@@ -990,7 +990,7 @@ func TestSQLUserBackend(t *testing.T) {
|
||||
t.Fatalf("commits %d", state.commits)
|
||||
}
|
||||
q := state.Queries()
|
||||
if len(q) != 3 || !strings.HasPrefix(q[1], "INSERT INTO `coredns_webui_users`") || !strings.HasPrefix(q[2], "INSERT INTO `coredns_webui_audit`") {
|
||||
if len(q) != 3 || !strings.HasPrefix(q[1], "INSERT INTO `webui`.`coredns_webui_users`") || !strings.HasPrefix(q[2], "INSERT INTO `webui`.`coredns_webui_audit`") {
|
||||
t.Fatalf("queries %v", q)
|
||||
}
|
||||
audit := state.Calls()[2].args
|
||||
|
||||
@@ -45,6 +45,8 @@ services:
|
||||
DB_NAME: ${DB_NAME:-coredns}
|
||||
DB_TLS: ${DB_TLS:-false}
|
||||
DB_TABLE_PREFIX: ${DB_TABLE_PREFIX:-coredns_}
|
||||
DB_WEBUI_NAME:
|
||||
DB_WEBUI_TABLE_PREFIX:
|
||||
HTTP_ADDR: 0.0.0.0
|
||||
HTTP_PORT: "8080"
|
||||
LOG_LEVEL: ${LOG_LEVEL:-DEBUG}
|
||||
|
||||
@@ -25,6 +25,8 @@ const (
|
||||
envDBName = "DB_NAME"
|
||||
envDBTLS = "DB_TLS"
|
||||
envDBTablePrefix = "DB_TABLE_PREFIX"
|
||||
envDBWebUIName = "DB_WEBUI_NAME"
|
||||
envDBWebUIPrefix = "DB_WEBUI_TABLE_PREFIX"
|
||||
envHTTPAddr = "HTTP_ADDR"
|
||||
envHTTPPort = "HTTP_PORT"
|
||||
envLogLevel = "LOG_LEVEL"
|
||||
@@ -55,6 +57,8 @@ var errConfig = errors.New("configuration error")
|
||||
|
||||
var tablePrefixPattern = regexp.MustCompile(`^[A-Za-z0-9_]{0,32}$`)
|
||||
|
||||
var dbNamePattern = regexp.MustCompile(`^[A-Za-z0-9_$-]{1,64}$`)
|
||||
|
||||
var dbHostPattern = regexp.MustCompile(`^[A-Za-z0-9_]([A-Za-z0-9_.-]{0,252}[A-Za-z0-9_])?$`)
|
||||
|
||||
var dbTLSModes = []string{"false", "true", "skip-verify", "preferred"}
|
||||
@@ -67,6 +71,8 @@ type Config struct {
|
||||
DBName string
|
||||
DBTLS string
|
||||
DBTablePrefix string
|
||||
DBWebUIName string
|
||||
DBWebUIPrefix string
|
||||
HTTPAddr string
|
||||
HTTPPort int
|
||||
LogLevel slog.Level
|
||||
@@ -137,6 +143,8 @@ func loadConfig(lookupEnv func(string) (string, bool)) (Config, error) {
|
||||
loadDBName,
|
||||
loadDBTLS,
|
||||
loadDBTablePrefix,
|
||||
loadDBWebUIName,
|
||||
loadDBWebUIPrefix,
|
||||
loadHTTPAddr,
|
||||
loadHTTPPort,
|
||||
loadLogLevel,
|
||||
@@ -216,13 +224,29 @@ func loadDBName(env envReader, cfg *Config) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !validConfigText(v, maxDBIdentifierLength) {
|
||||
if !validDBIdentifier(v) {
|
||||
return configErrorf("invalid %s: must be at most %d characters without control characters", envDBName, maxDBIdentifierLength)
|
||||
}
|
||||
cfg.DBName = v
|
||||
return nil
|
||||
}
|
||||
|
||||
func loadDBWebUIName(env envReader, cfg *Config) error {
|
||||
v, ok, err := env.optional(envDBWebUIName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
cfg.DBWebUIName = cfg.DBName
|
||||
return nil
|
||||
}
|
||||
if !validDBName(v) {
|
||||
return configErrorf("invalid %s: must match ^[A-Za-z0-9_$-]{1,64}$", envDBWebUIName)
|
||||
}
|
||||
cfg.DBWebUIName = v
|
||||
return nil
|
||||
}
|
||||
|
||||
func loadDBTLS(env envReader, cfg *Config) error {
|
||||
v, ok, err := env.optional(envDBTLS)
|
||||
if err != nil || !ok {
|
||||
@@ -249,6 +273,19 @@ func loadDBTablePrefix(env envReader, cfg *Config) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func loadDBWebUIPrefix(env envReader, cfg *Config) error {
|
||||
v, ok := env.lookupEnv(envDBWebUIPrefix)
|
||||
if !ok {
|
||||
cfg.DBWebUIPrefix = cfg.DBTablePrefix
|
||||
return nil
|
||||
}
|
||||
if !validTablePrefix(v) {
|
||||
return configErrorf("invalid %s: must match ^[A-Za-z0-9_]{0,32}$", envDBWebUIPrefix)
|
||||
}
|
||||
cfg.DBWebUIPrefix = v
|
||||
return nil
|
||||
}
|
||||
|
||||
func loadHTTPAddr(env envReader, cfg *Config) error {
|
||||
v, ok, err := env.optional(envHTTPAddr)
|
||||
if err != nil || !ok {
|
||||
@@ -381,6 +418,14 @@ func validTablePrefix(prefix string) bool {
|
||||
return tablePrefixPattern.MatchString(prefix)
|
||||
}
|
||||
|
||||
func validDBName(name string) bool {
|
||||
return dbNamePattern.MatchString(name)
|
||||
}
|
||||
|
||||
func validDBIdentifier(name string) bool {
|
||||
return name != "" && validConfigText(name, maxDBIdentifierLength)
|
||||
}
|
||||
|
||||
func validConfigText(v string, maxRunes int) bool {
|
||||
if !utf8.ValidString(v) || utf8.RuneCountInString(v) > maxRunes {
|
||||
return false
|
||||
|
||||
@@ -45,6 +45,8 @@ func TestLoadConfigDefaults(t *testing.T) {
|
||||
DBName: "coredns",
|
||||
DBTLS: "false",
|
||||
DBTablePrefix: "coredns_",
|
||||
DBWebUIName: "coredns",
|
||||
DBWebUIPrefix: "coredns_",
|
||||
HTTPAddr: "0.0.0.0",
|
||||
HTTPPort: 8080,
|
||||
LogLevel: slog.LevelInfo,
|
||||
@@ -67,6 +69,8 @@ func TestLoadConfigAllSet(t *testing.T) {
|
||||
"DB_PORT": "13306",
|
||||
"DB_TLS": "skip-verify",
|
||||
"DB_TABLE_PREFIX": "dns_",
|
||||
"DB_WEBUI_NAME": "dns-webui",
|
||||
"DB_WEBUI_TABLE_PREFIX": "",
|
||||
"HTTP_ADDR": "::",
|
||||
"HTTP_PORT": "65535",
|
||||
"LOG_LEVEL": "trace",
|
||||
@@ -80,6 +84,7 @@ func TestLoadConfigAllSet(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.DBHost != "2001:db8::1" || cfg.DBPort != 13306 || cfg.DBTLS != "skip-verify" || cfg.DBTablePrefix != "dns_" ||
|
||||
cfg.DBName != "coredns" || cfg.DBWebUIName != "dns-webui" || cfg.DBWebUIPrefix != "" ||
|
||||
cfg.HTTPAddr != "::" || cfg.HTTPPort != 65535 || cfg.LogLevel != LevelTrace || cfg.AppName != "My DNS" ||
|
||||
cfg.CookieSecure || cfg.SessionIdleTimeout != time.Minute || cfg.SessionMaxAge != time.Minute {
|
||||
t.Fatalf("unexpected %+v", cfg)
|
||||
@@ -116,6 +121,14 @@ func TestLoadConfigAccepted(t *testing.T) {
|
||||
{"TRUSTED_PROXIES": "192.0.2.10/32"},
|
||||
{"APP_NAME": strings.Repeat("x", 100)},
|
||||
{"DB_NAME": strings.Repeat("d", 64)},
|
||||
{"DB_NAME": "dns_infra_bjphoster_cloud"},
|
||||
{"DB_NAME": "my-db$1"},
|
||||
{"DB_NAME": "legacy `dns"},
|
||||
{"DB_WEBUI_NAME": "dns_infra_bjphoster_cloud"},
|
||||
{"DB_WEBUI_NAME": strings.Repeat("w", 64)},
|
||||
{"DB_WEBUI_NAME": "coredns"},
|
||||
{"DB_WEBUI_TABLE_PREFIX": ""},
|
||||
{"DB_WEBUI_TABLE_PREFIX": strings.Repeat("a", 32)},
|
||||
{"DB_USER": "user with space"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
@@ -150,6 +163,14 @@ func TestLoadConfigErrors(t *testing.T) {
|
||||
{env: map[string]string{"DB_USER": strings.Repeat("u", 65)}, want: "invalid DB_USER"},
|
||||
{env: map[string]string{"DB_NAME": "bad\x00name"}, want: "invalid DB_NAME"},
|
||||
{env: map[string]string{"DB_NAME": "bad\xffname"}, want: "invalid DB_NAME"},
|
||||
{env: map[string]string{"DB_NAME": strings.Repeat("d", 65)}, want: "invalid DB_NAME"},
|
||||
{env: map[string]string{"DB_WEBUI_NAME": ""}, want: "DB_WEBUI_NAME must not be empty"},
|
||||
{env: map[string]string{"DB_WEBUI_NAME": "a`b"}, want: "invalid DB_WEBUI_NAME"},
|
||||
{env: map[string]string{"DB_WEBUI_NAME": "db.table"}, want: "invalid DB_WEBUI_NAME"},
|
||||
{env: map[string]string{"DB_WEBUI_NAME": "x\ny"}, want: "invalid DB_WEBUI_NAME"},
|
||||
{env: map[string]string{"DB_WEBUI_NAME": strings.Repeat("w", 65)}, want: "invalid DB_WEBUI_NAME"},
|
||||
{env: map[string]string{"DB_WEBUI_TABLE_PREFIX": "bad-prefix"}, want: "invalid DB_WEBUI_TABLE_PREFIX"},
|
||||
{env: map[string]string{"DB_WEBUI_TABLE_PREFIX": strings.Repeat("a", 33)}, want: "invalid DB_WEBUI_TABLE_PREFIX"},
|
||||
{env: map[string]string{"DB_TLS": ""}, want: "DB_TLS must not be empty"},
|
||||
{env: map[string]string{"DB_TLS": "TRUE"}, want: "invalid DB_TLS"},
|
||||
{env: map[string]string{"DB_TLS": "custom"}, want: "invalid DB_TLS"},
|
||||
@@ -209,6 +230,8 @@ func TestLoadConfigNeverEchoesValues(t *testing.T) {
|
||||
{"DB_PASSWORD": secret, "TRUSTED_PROXIES": secret},
|
||||
{"DB_PASSWORD": secret, "SESSION_IDLE_TIMEOUT": secret},
|
||||
{"DB_PASSWORD": secret, "DB_HOST": secret + " x"},
|
||||
{"DB_PASSWORD": secret, "DB_NAME": secret + "\n"},
|
||||
{"DB_PASSWORD": secret, "DB_WEBUI_NAME": secret + " x"},
|
||||
}
|
||||
for _, env := range envs {
|
||||
_, err := loadConfig(cfgEnv(env))
|
||||
@@ -261,6 +284,30 @@ func TestParsePort(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebUIDefaultsFollowRecords(t *testing.T) {
|
||||
cfg, err := loadConfig(cfgEnv(map[string]string{"DB_NAME": "dns", "DB_TABLE_PREFIX": "p_"}))
|
||||
if err != nil || cfg.DBWebUIName != "dns" || cfg.DBWebUIPrefix != "p_" {
|
||||
t.Fatalf("%+v %v", cfg, err)
|
||||
}
|
||||
cfg, err = loadConfig(cfgEnv(map[string]string{"DB_NAME": "dns", "DB_TABLE_PREFIX": "p_", "DB_WEBUI_NAME": "ui"}))
|
||||
if err != nil || cfg.DBName != "dns" || cfg.DBWebUIName != "ui" || cfg.DBWebUIPrefix != "p_" {
|
||||
t.Fatalf("%+v %v", cfg, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidDBName(t *testing.T) {
|
||||
for _, n := range []string{"coredns", "dns_infra_bjphoster_cloud", "a-b", "a$b", "1", strings.Repeat("z", 64)} {
|
||||
if !validDBName(n) {
|
||||
t.Errorf("%q refused", n)
|
||||
}
|
||||
}
|
||||
for _, n := range []string{"", "a b", "a.b", "a`b", "a'b", "é", "a;", "a\n", strings.Repeat("z", 65)} {
|
||||
if validDBName(n) {
|
||||
t.Errorf("%q accepted", n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidTablePrefix(t *testing.T) {
|
||||
for _, p := range []string{"", "coredns_", "A_1", strings.Repeat("z", 32)} {
|
||||
if !validTablePrefix(p) {
|
||||
|
||||
+55
-23
@@ -61,7 +61,10 @@ type pinger interface {
|
||||
}
|
||||
|
||||
type tableNames struct {
|
||||
prefix string
|
||||
recordsSchema string
|
||||
recordsTable string
|
||||
webuiSchema string
|
||||
webuiPrefix string
|
||||
records string
|
||||
schema string
|
||||
users string
|
||||
@@ -71,24 +74,53 @@ type tableNames struct {
|
||||
locks string
|
||||
}
|
||||
|
||||
func newTableNames(prefix string) (tableNames, error) {
|
||||
if !validTablePrefix(prefix) {
|
||||
type tableLayout struct {
|
||||
recordsSchema string
|
||||
recordsPrefix string
|
||||
webuiSchema string
|
||||
webuiPrefix string
|
||||
}
|
||||
|
||||
func tableNamesFor(cfg Config) (tableNames, error) {
|
||||
return newTableNames(tableLayout{
|
||||
recordsSchema: cfg.DBName,
|
||||
recordsPrefix: cfg.DBTablePrefix,
|
||||
webuiSchema: cfg.DBWebUIName,
|
||||
webuiPrefix: cfg.DBWebUIPrefix,
|
||||
})
|
||||
}
|
||||
|
||||
func newTableNames(l tableLayout) (tableNames, error) {
|
||||
if !validTablePrefix(l.recordsPrefix) || !validTablePrefix(l.webuiPrefix) {
|
||||
return tableNames{}, errors.New("invalid table prefix")
|
||||
}
|
||||
if !validDBIdentifier(l.recordsSchema) || !validDBIdentifier(l.webuiSchema) {
|
||||
return tableNames{}, errors.New("invalid database name")
|
||||
}
|
||||
webui := func(name string) string {
|
||||
return qualifiedIdent(l.webuiSchema, l.webuiPrefix+"webui_"+name)
|
||||
}
|
||||
return tableNames{
|
||||
prefix: prefix,
|
||||
records: quoteIdent(prefix + "records"),
|
||||
schema: quoteIdent(prefix + "webui_schema"),
|
||||
users: quoteIdent(prefix + "webui_users"),
|
||||
sessions: quoteIdent(prefix + "webui_sessions"),
|
||||
delegations: quoteIdent(prefix + "webui_zone_delegations"),
|
||||
audit: quoteIdent(prefix + "webui_audit"),
|
||||
locks: quoteIdent(prefix + "webui_locks"),
|
||||
recordsSchema: l.recordsSchema,
|
||||
recordsTable: l.recordsPrefix + "records",
|
||||
webuiSchema: l.webuiSchema,
|
||||
webuiPrefix: l.webuiPrefix,
|
||||
records: qualifiedIdent(l.recordsSchema, l.recordsPrefix+"records"),
|
||||
schema: webui("schema"),
|
||||
users: webui("users"),
|
||||
sessions: webui("sessions"),
|
||||
delegations: webui("zone_delegations"),
|
||||
audit: webui("audit"),
|
||||
locks: webui("locks"),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func qualifiedIdent(schema, name string) string {
|
||||
return quoteIdent(schema) + "." + quoteIdent(name)
|
||||
}
|
||||
|
||||
func quoteIdent(name string) string {
|
||||
return "`" + name + "`"
|
||||
return "`" + strings.ReplaceAll(name, "`", "``") + "`"
|
||||
}
|
||||
|
||||
func (t tableNames) sql(query string) string {
|
||||
@@ -104,12 +136,12 @@ func (t tableNames) sql(query string) string {
|
||||
}
|
||||
|
||||
func (t tableNames) migrateLockName() string {
|
||||
return t.prefix + "webui_migrate"
|
||||
return t.webuiPrefix + "webui_migrate"
|
||||
}
|
||||
|
||||
func (t tableNames) zoneLockName(zone string) string {
|
||||
sum := sha256.Sum256([]byte(zone))
|
||||
return t.prefix + "webui:" + hex.EncodeToString(sum[:])[:16]
|
||||
return t.webuiPrefix + "webui:" + hex.EncodeToString(sum[:])[:16]
|
||||
}
|
||||
|
||||
func mysqlConfig(cfg Config) *mysql.Config {
|
||||
@@ -118,7 +150,7 @@ func mysqlConfig(cfg Config) *mysql.Config {
|
||||
mc.Passwd = cfg.DBPassword
|
||||
mc.Net = "tcp"
|
||||
mc.Addr = cfg.DBAddress()
|
||||
mc.DBName = cfg.DBName
|
||||
mc.DBName = cfg.DBWebUIName
|
||||
mc.ParseTime = true
|
||||
mc.Loc = time.UTC
|
||||
_ = mc.Apply(mysql.Charset("utf8mb4", ""))
|
||||
@@ -144,7 +176,7 @@ func openDatabase(cfg Config, log *slog.Logger) (*sql.DB, error) {
|
||||
db.SetMaxOpenConns(dbMaxOpenConns)
|
||||
db.SetMaxIdleConns(dbMaxIdleConns)
|
||||
db.SetConnMaxLifetime(dbConnMaxLifetime)
|
||||
log.Debug("database pool opened", "host", cfg.DBHost, "port", cfg.DBPort, "user", cfg.DBUser, "database", cfg.DBName, "tls", cfg.DBTLS)
|
||||
log.Debug("database pool opened", "host", cfg.DBHost, "port", cfg.DBPort, "user", cfg.DBUser, "database", cfg.DBName, "webui_database", cfg.DBWebUIName, "tls", cfg.DBTLS)
|
||||
return db, nil
|
||||
}
|
||||
|
||||
@@ -246,10 +278,10 @@ var recordsContract = []contractColumn{
|
||||
}
|
||||
|
||||
func verifyRecordsContract(ctx context.Context, q dbtx, t tableNames, log *slog.Logger) error {
|
||||
table := t.prefix + "records"
|
||||
table := t.recordsTable
|
||||
rows, err := q.QueryContext(ctx,
|
||||
"SELECT COLUMN_NAME, DATA_TYPE, COLUMN_TYPE, CHARACTER_MAXIMUM_LENGTH FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?",
|
||||
table)
|
||||
"SELECT COLUMN_NAME, DATA_TYPE, COLUMN_TYPE, CHARACTER_MAXIMUM_LENGTH FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?",
|
||||
t.recordsSchema, table)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read records table columns: %w", err)
|
||||
}
|
||||
@@ -266,16 +298,16 @@ func verifyRecordsContract(ctx context.Context, q dbtx, t tableNames, log *slog.
|
||||
if err := rows.Err(); err != nil {
|
||||
return fmt.Errorf("read records table columns: %w", err)
|
||||
}
|
||||
if err := checkRecordsColumns(table, columns); err != nil {
|
||||
if err := checkRecordsColumns(t.recordsSchema, table, columns); err != nil {
|
||||
return err
|
||||
}
|
||||
log.DebugContext(ctx, "records table contract verified", "table", table)
|
||||
log.DebugContext(ctx, "records table contract verified", "database", t.recordsSchema, "table", table)
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkRecordsColumns(table string, columns map[string]columnInfo) error {
|
||||
func checkRecordsColumns(schema, table string, columns map[string]columnInfo) error {
|
||||
if len(columns) == 0 {
|
||||
return fmt.Errorf("%w: table %s does not exist in the configured database", errContract, table)
|
||||
return fmt.Errorf("%w: table %s does not exist in database %s or is not readable", errContract, table, schema)
|
||||
}
|
||||
for _, c := range recordsContract {
|
||||
info, ok := columns[c.name]
|
||||
|
||||
+76
-23
@@ -22,33 +22,76 @@ import (
|
||||
)
|
||||
|
||||
func TestNewTableNames(t *testing.T) {
|
||||
tn, err := newTableNames("dns_")
|
||||
tn, err := newTableNames(tableLayout{recordsSchema: "dns", recordsPrefix: "dns_", webuiSchema: "dns-ui", webuiPrefix: "ui_"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := tableNames{
|
||||
prefix: "dns_",
|
||||
records: "`dns_records`",
|
||||
schema: "`dns_webui_schema`",
|
||||
users: "`dns_webui_users`",
|
||||
sessions: "`dns_webui_sessions`",
|
||||
delegations: "`dns_webui_zone_delegations`",
|
||||
audit: "`dns_webui_audit`",
|
||||
locks: "`dns_webui_locks`",
|
||||
recordsSchema: "dns",
|
||||
recordsTable: "dns_records",
|
||||
webuiSchema: "dns-ui",
|
||||
webuiPrefix: "ui_",
|
||||
records: "`dns`.`dns_records`",
|
||||
schema: "`dns-ui`.`ui_webui_schema`",
|
||||
users: "`dns-ui`.`ui_webui_users`",
|
||||
sessions: "`dns-ui`.`ui_webui_sessions`",
|
||||
delegations: "`dns-ui`.`ui_webui_zone_delegations`",
|
||||
audit: "`dns-ui`.`ui_webui_audit`",
|
||||
locks: "`dns-ui`.`ui_webui_locks`",
|
||||
}
|
||||
if tn != want {
|
||||
t.Fatalf("got %+v", tn)
|
||||
}
|
||||
got := tn.sql("{records} {schema} {users} {sessions} {delegations} {audit} {locks} {other}")
|
||||
if got != "`dns_records` `dns_webui_schema` `dns_webui_users` `dns_webui_sessions` `dns_webui_zone_delegations` `dns_webui_audit` `dns_webui_locks` {other}" {
|
||||
if got != "`dns`.`dns_records` `dns-ui`.`ui_webui_schema` `dns-ui`.`ui_webui_users` `dns-ui`.`ui_webui_sessions` `dns-ui`.`ui_webui_zone_delegations` `dns-ui`.`ui_webui_audit` `dns-ui`.`ui_webui_locks` {other}" {
|
||||
t.Fatalf("sql %s", got)
|
||||
}
|
||||
if _, err := newTableNames("bad`prefix"); err == nil {
|
||||
t.Fatal("invalid prefix accepted")
|
||||
valid := tableLayout{recordsSchema: "coredns", recordsPrefix: "coredns_", webuiSchema: "coredns", webuiPrefix: "coredns_"}
|
||||
for _, change := range []func(*tableLayout){
|
||||
func(l *tableLayout) { l.recordsPrefix = "bad`prefix" },
|
||||
func(l *tableLayout) { l.webuiPrefix = "bad-prefix" },
|
||||
func(l *tableLayout) { l.recordsSchema = "" },
|
||||
func(l *tableLayout) { l.webuiSchema = "" },
|
||||
func(l *tableLayout) { l.recordsSchema = "bad\x00db" },
|
||||
func(l *tableLayout) { l.webuiSchema = "bad\ndb" },
|
||||
func(l *tableLayout) { l.webuiSchema = strings.Repeat("d", 65) },
|
||||
} {
|
||||
l := valid
|
||||
change(&l)
|
||||
if _, err := newTableNames(l); err == nil {
|
||||
t.Fatalf("invalid layout accepted: %+v", l)
|
||||
}
|
||||
empty, err := newTableNames("")
|
||||
if err != nil || empty.records != "`records`" || empty.migrateLockName() != "webui_migrate" {
|
||||
t.Fatalf("%+v %v", empty, err)
|
||||
}
|
||||
empty := valid
|
||||
empty.recordsPrefix, empty.webuiPrefix = "", ""
|
||||
tn, err = newTableNames(empty)
|
||||
if err != nil || tn.records != "`coredns`.`records`" || tn.users != "`coredns`.`webui_users`" || tn.migrateLockName() != "webui_migrate" {
|
||||
t.Fatalf("%+v %v", tn, err)
|
||||
}
|
||||
legacy := tableLayout{recordsSchema: "legacy `dns", webuiSchema: "legacy `dns"}
|
||||
tn, err = newTableNames(legacy)
|
||||
if err != nil || tn.records != "`legacy ``dns`.`records`" || tn.users != "`legacy ``dns`.`webui_users`" {
|
||||
t.Fatalf("legacy layout %+v %v", tn, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTableNamesFor(t *testing.T) {
|
||||
cfg, err := loadConfig(cfgEnv(nil))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tn, err := tableNamesFor(cfg)
|
||||
if err != nil || tn.records != "`coredns`.`coredns_records`" || tn.users != "`coredns`.`coredns_webui_users`" || tn.locks != "`coredns`.`coredns_webui_locks`" {
|
||||
t.Fatalf("shared layout %+v %v", tn, err)
|
||||
}
|
||||
cfg, err = loadConfig(cfgEnv(map[string]string{"DB_WEBUI_NAME": "dns_infra", "DB_WEBUI_TABLE_PREFIX": ""}))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tn, err = tableNamesFor(cfg)
|
||||
if err != nil || tn.records != "`coredns`.`coredns_records`" || tn.users != "`dns_infra`.`webui_users`" ||
|
||||
!strings.HasPrefix(tn.zoneLockName("a."), "webui:") || tn.migrateLockName() != "webui_migrate" {
|
||||
t.Fatalf("separate layout %+v %v", tn, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,7 +105,7 @@ func TestLockNames(t *testing.T) {
|
||||
if got := tn.zoneLockName("example.org."); got != want || len(got) != len("coredns_webui:")+16 {
|
||||
t.Fatalf("got %s want %s", got, want)
|
||||
}
|
||||
long, _ := newTableNames(strings.Repeat("p", 32))
|
||||
long, _ := newTableNames(tableLayout{recordsSchema: "coredns", recordsPrefix: "coredns_", webuiSchema: "webui", webuiPrefix: strings.Repeat("p", 32)})
|
||||
if n := len(long.zoneLockName("x.")); n > 64 {
|
||||
t.Fatalf("lock name too long: %d", n)
|
||||
}
|
||||
@@ -91,6 +134,16 @@ func TestMySQLConfig(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMySQLConfigUsesWebUIDatabase(t *testing.T) {
|
||||
cfg, err := loadConfig(cfgEnv(map[string]string{"DB_WEBUI_NAME": "dns_infra"}))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if mc := mysqlConfig(cfg); mc.DBName != "dns_infra" || cfg.DBName != "coredns" {
|
||||
t.Fatalf("connection database %q, records database %q", mc.DBName, cfg.DBName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenDatabase(t *testing.T) {
|
||||
cfg, _ := loadConfig(cfgEnv(nil))
|
||||
var buf bytes.Buffer
|
||||
@@ -228,7 +281,7 @@ func validColumns() map[string]columnInfo {
|
||||
}
|
||||
|
||||
func TestCheckRecordsColumns(t *testing.T) {
|
||||
if err := checkRecordsColumns("coredns_records", validColumns()); err != nil {
|
||||
if err := checkRecordsColumns("coredns", "coredns_records", validColumns()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, alt := range []map[string]columnInfo{
|
||||
@@ -239,17 +292,17 @@ func TestCheckRecordsColumns(t *testing.T) {
|
||||
{"id": column("int"), "zone": column("longtext"), "name": column("text"), "ttl": column("bigint"),
|
||||
"content": column("mediumtext"), "record_type": column("mediumtext")},
|
||||
} {
|
||||
if err := checkRecordsColumns("coredns_records", alt); err != nil {
|
||||
if err := checkRecordsColumns("coredns", "coredns_records", alt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := checkRecordsColumns("coredns_records", map[string]columnInfo{}); !errors.Is(err, errContract) || !strings.Contains(err.Error(), "coredns_records does not exist") {
|
||||
if err := checkRecordsColumns("coredns", "coredns_records", map[string]columnInfo{}); !errors.Is(err, errContract) || !strings.Contains(err.Error(), "coredns_records does not exist") {
|
||||
t.Fatalf("got %v", err)
|
||||
}
|
||||
for _, col := range []string{"id", "zone", "name", "ttl", "content", "record_type"} {
|
||||
cols := validColumns()
|
||||
delete(cols, col)
|
||||
err := checkRecordsColumns("coredns_records", cols)
|
||||
err := checkRecordsColumns("coredns", "coredns_records", cols)
|
||||
if !errors.Is(err, errContract) || !strings.Contains(err.Error(), "has no column "+col) {
|
||||
t.Fatalf("%s: %v", col, err)
|
||||
}
|
||||
@@ -279,7 +332,7 @@ func TestCheckRecordsColumns(t *testing.T) {
|
||||
} {
|
||||
cols := validColumns()
|
||||
cols[c.col] = column(c.typ)
|
||||
err := checkRecordsColumns("coredns_records", cols)
|
||||
err := checkRecordsColumns("coredns", "coredns_records", cols)
|
||||
want := "column " + c.col + " of table coredns_records has incompatible type " + c.typ + ", it must be " + c.requirement
|
||||
if !errors.Is(err, errContract) || !strings.Contains(err.Error(), want) {
|
||||
t.Fatalf("%s %s: %v", c.col, c.typ, err)
|
||||
@@ -287,7 +340,7 @@ func TestCheckRecordsColumns(t *testing.T) {
|
||||
}
|
||||
cols := validColumns()
|
||||
cols["id"] = columnInfo{dataType: "bigint"}
|
||||
if err := checkRecordsColumns("coredns_records", cols); err == nil || !strings.Contains(err.Error(), "incompatible type bigint,") {
|
||||
if err := checkRecordsColumns("coredns", "coredns_records", cols); err == nil || !strings.Contains(err.Error(), "incompatible type bigint,") {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -301,7 +354,7 @@ func TestVerifyRecordsContract(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
calls := st.Calls()
|
||||
if len(calls) != 1 || calls[0].args[0] != "coredns_records" || !strings.Contains(calls[0].query, "TABLE_SCHEMA = DATABASE()") {
|
||||
if len(calls) != 1 || calls[0].args[0] != "coredns" || calls[0].args[1] != "coredns_records" || !strings.Contains(calls[0].query, "TABLE_SCHEMA = ? AND") {
|
||||
t.Fatalf("calls %+v", calls)
|
||||
}
|
||||
db, _ = newFakeDB(t, fdbRules(fdbRule{"COLUMNS", fdbResponse{rows: [][]driver.Value{{"id", "int", "int", nil}}}}))
|
||||
|
||||
@@ -162,6 +162,7 @@ services:
|
||||
DB_USER: webui_harness
|
||||
DB_PASSWORD: webui-harness-e2e-pass
|
||||
DB_NAME: e2e_harness
|
||||
DB_WEBUI_NAME: e2e_harness_webui
|
||||
|
||||
app-core:
|
||||
<<: *app
|
||||
@@ -171,6 +172,7 @@ services:
|
||||
DB_USER: webui_core
|
||||
DB_PASSWORD: webui-core-e2e-pass
|
||||
DB_NAME: e2e_core
|
||||
DB_WEBUI_NAME: e2e_core_webui
|
||||
|
||||
app-session:
|
||||
<<: *app
|
||||
@@ -191,6 +193,7 @@ services:
|
||||
DB_USER: webui_power
|
||||
DB_PASSWORD: webui-power-e2e-pass
|
||||
DB_NAME: e2e_power
|
||||
DB_WEBUI_NAME: e2e_power_webui
|
||||
|
||||
app-stupid:
|
||||
<<: *app
|
||||
@@ -209,6 +212,8 @@ services:
|
||||
DB_USER: webui_malicious
|
||||
DB_PASSWORD: webui-malicious-e2e-pass
|
||||
DB_NAME: e2e_malicious
|
||||
DB_WEBUI_NAME: e2e_malicious_webui
|
||||
DB_WEBUI_TABLE_PREFIX: mal_
|
||||
DB_TABLE_PREFIX: e2e_
|
||||
LOG_LEVEL: TRACE
|
||||
TRUSTED_PROXIES: 192.0.2.0/24
|
||||
@@ -221,6 +226,7 @@ services:
|
||||
DB_USER: webui_fuzzer
|
||||
DB_PASSWORD: webui-fuzzer-e2e-pass
|
||||
DB_NAME: e2e_fuzzer
|
||||
DB_WEBUI_NAME: e2e_fuzzer_webui
|
||||
LOG_LEVEL: TRACE
|
||||
|
||||
app-operator:
|
||||
@@ -231,6 +237,7 @@ services:
|
||||
DB_USER: webui_operator
|
||||
DB_PASSWORD: webui-operator-e2e-pass
|
||||
DB_NAME: e2e_operator
|
||||
DB_WEBUI_NAME: e2e_operator_webui
|
||||
|
||||
app-a11y:
|
||||
<<: *app
|
||||
@@ -240,6 +247,7 @@ services:
|
||||
DB_USER: webui_a11y
|
||||
DB_PASSWORD: webui-a11y-e2e-pass
|
||||
DB_NAME: e2e_a11y
|
||||
DB_WEBUI_NAME: e2e_a11y_webui
|
||||
|
||||
runner:
|
||||
image: ${E2E_RUNNER_IMAGE}
|
||||
|
||||
+10
-4
@@ -24,6 +24,9 @@ export interface GroupConfig {
|
||||
service: string;
|
||||
database: string;
|
||||
prefix: string;
|
||||
webuiDatabase: string;
|
||||
webuiPrefix: string;
|
||||
webuiGrants: 'tables' | 'database';
|
||||
appUser: string;
|
||||
appPassword: string;
|
||||
dnsUser: string;
|
||||
@@ -42,6 +45,9 @@ function group(name: GroupName, dnsPort: number, extra: Partial<GroupConfig> = {
|
||||
service: `app-${name}`,
|
||||
database: `e2e_${name}`,
|
||||
prefix: 'coredns_',
|
||||
webuiDatabase: `e2e_${name}_webui`,
|
||||
webuiPrefix: 'coredns_',
|
||||
webuiGrants: 'tables',
|
||||
appUser: `webui_${name}`,
|
||||
appPassword: `webui-${name}-e2e-pass`,
|
||||
dnsUser: `dns_${name}`,
|
||||
@@ -57,12 +63,12 @@ function group(name: GroupName, dnsPort: number, extra: Partial<GroupConfig> = {
|
||||
}
|
||||
|
||||
export const GROUPS: Readonly<Record<GroupName, GroupConfig>> = {
|
||||
harness: group('harness', 5300),
|
||||
harness: group('harness', 5300, { webuiGrants: 'database' }),
|
||||
core: group('core', 5301),
|
||||
session: group('session', 5302, { idleTimeoutMs: 60_000, maxAgeMs: 180_000 }),
|
||||
session: group('session', 5302, { webuiDatabase: 'e2e_session', idleTimeoutMs: 60_000, maxAgeMs: 180_000 }),
|
||||
power: group('power', 5303),
|
||||
stupid: group('stupid', 5304),
|
||||
malicious: group('malicious', 5305, { prefix: 'e2e_', logLevel: 'TRACE', trustedProxies: '192.0.2.0/24' }),
|
||||
stupid: group('stupid', 5304, { webuiDatabase: 'e2e_stupid' }),
|
||||
malicious: group('malicious', 5305, { prefix: 'e2e_', webuiPrefix: 'mal_', logLevel: 'TRACE', trustedProxies: '192.0.2.0/24' }),
|
||||
fuzzer: group('fuzzer', 5306, { logLevel: 'TRACE' }),
|
||||
operator: group('operator', 5307),
|
||||
a11y: group('a11y', 5308),
|
||||
|
||||
+22
-12
@@ -63,6 +63,10 @@ export interface SessionRow {
|
||||
export type RawRecord = { zone: string; name: string; ttl: number | null; content: string | null; record_type: string };
|
||||
|
||||
const INIT_TEMPLATE = path.resolve(process.cwd(), 'stack', 'mysql-init.sql');
|
||||
const WEBUI_GRANT_TEMPLATES = {
|
||||
tables: path.resolve(process.cwd(), 'stack', 'mysql-webui-tables.sql'),
|
||||
database: path.resolve(process.cwd(), 'stack', 'mysql-webui-database.sql'),
|
||||
} as const;
|
||||
|
||||
function connectionOptions(database?: string): mysql.ConnectionOptions {
|
||||
return {
|
||||
@@ -85,11 +89,17 @@ function q(identifier: string): string {
|
||||
return '`' + identifier + '`';
|
||||
}
|
||||
|
||||
function qualified(schema: string, table: string): string {
|
||||
return `${q(schema)}.${q(table)}`;
|
||||
}
|
||||
|
||||
export function initSql(g: GroupConfig): string {
|
||||
const template = fs.readFileSync(INIT_TEMPLATE, 'utf8');
|
||||
const template = fs.readFileSync(INIT_TEMPLATE, 'utf8') + '\n' + fs.readFileSync(WEBUI_GRANT_TEMPLATES[g.webuiGrants], 'utf8');
|
||||
const values: Record<string, string> = {
|
||||
DATABASE: g.database,
|
||||
PREFIX: g.prefix,
|
||||
WEBUI_DATABASE: g.webuiDatabase,
|
||||
WEBUI_PREFIX: g.webuiPrefix,
|
||||
DNS_USER: g.dnsUser,
|
||||
DNS_PASSWORD: g.dnsPassword,
|
||||
APP_USER: g.appUser,
|
||||
@@ -101,7 +111,7 @@ export function initSql(g: GroupConfig): string {
|
||||
.join('\n')
|
||||
.replace(/\{\{([A-Z_]+)\}\}/g, (_m, k: string) => {
|
||||
const v = values[k];
|
||||
if (v === undefined || !/^[A-Za-z0-9_-]+$/.test(v)) throw new HarnessError('infrastructure', `bad template value ${k}`);
|
||||
if (v === undefined || !/^[A-Za-z0-9_-]*$/.test(v) || (v === '' && !k.endsWith('PREFIX'))) throw new HarnessError('infrastructure', `bad template value ${k}`);
|
||||
return v;
|
||||
});
|
||||
}
|
||||
@@ -140,14 +150,14 @@ export class Db {
|
||||
|
||||
constructor(readonly group: GroupConfig) {
|
||||
this.pool = mysql.createPool({ ...connectionOptions(group.database), connectionLimit: 4 });
|
||||
const p = group.prefix;
|
||||
const ui = (table: string) => qualified(group.webuiDatabase, `${group.webuiPrefix}webui_${table}`);
|
||||
this.t = {
|
||||
records: q(`${p}records`),
|
||||
users: q(`${p}webui_users`),
|
||||
sessions: q(`${p}webui_sessions`),
|
||||
delegations: q(`${p}webui_zone_delegations`),
|
||||
audit: q(`${p}webui_audit`),
|
||||
schema: q(`${p}webui_schema`),
|
||||
records: qualified(group.database, `${group.prefix}records`),
|
||||
users: ui('users'),
|
||||
sessions: ui('sessions'),
|
||||
delegations: ui('zone_delegations'),
|
||||
audit: ui('audit'),
|
||||
schema: ui('schema'),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -289,9 +299,9 @@ export class Db {
|
||||
return Number(rows[0].n);
|
||||
}
|
||||
|
||||
async tableExists(name: string): Promise<boolean> {
|
||||
const rows = await this.query<{ n: number }>('SELECT COUNT(*) AS n FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?', [name]);
|
||||
return Number(rows[0].n) === 1;
|
||||
async tables(schema: string): Promise<string[]> {
|
||||
const rows = await this.query<{ name: string }>('SELECT TABLE_NAME AS name FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME', [schema]);
|
||||
return rows.map((r) => r.name);
|
||||
}
|
||||
|
||||
async snapshot(): Promise<string> {
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
|
||||
CREATE DATABASE `{{DATABASE}}` DEFAULT CHARSET = utf8mb4;
|
||||
|
||||
CREATE DATABASE IF NOT EXISTS `{{WEBUI_DATABASE}}` DEFAULT CHARSET = utf8mb4;
|
||||
|
||||
CREATE TABLE `{{DATABASE}}`.`{{PREFIX}}records` (
|
||||
`id` INT NOT NULL AUTO_INCREMENT,
|
||||
`zone` VARCHAR(255) NOT NULL,
|
||||
@@ -18,9 +20,3 @@ GRANT SELECT ON `{{DATABASE}}`.`{{PREFIX}}records` TO '{{DNS_USER}}'@'%';
|
||||
|
||||
CREATE USER '{{APP_USER}}'@'%' IDENTIFIED BY '{{APP_PASSWORD}}';
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON `{{DATABASE}}`.`{{PREFIX}}records` TO '{{APP_USER}}'@'%';
|
||||
GRANT SELECT, INSERT, UPDATE, CREATE ON `{{DATABASE}}`.`{{PREFIX}}webui_locks` TO '{{APP_USER}}'@'%';
|
||||
GRANT SELECT, INSERT, UPDATE, CREATE, ALTER, INDEX, REFERENCES ON `{{DATABASE}}`.`{{PREFIX}}webui_schema` TO '{{APP_USER}}'@'%';
|
||||
GRANT SELECT, INSERT, UPDATE, CREATE, ALTER, INDEX, REFERENCES ON `{{DATABASE}}`.`{{PREFIX}}webui_users` TO '{{APP_USER}}'@'%';
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, INDEX, REFERENCES ON `{{DATABASE}}`.`{{PREFIX}}webui_sessions` TO '{{APP_USER}}'@'%';
|
||||
GRANT SELECT, INSERT, DELETE, CREATE, ALTER, INDEX, REFERENCES ON `{{DATABASE}}`.`{{PREFIX}}webui_zone_delegations` TO '{{APP_USER}}'@'%';
|
||||
GRANT SELECT, INSERT, CREATE, ALTER, INDEX, REFERENCES ON `{{DATABASE}}`.`{{PREFIX}}webui_audit` TO '{{APP_USER}}'@'%';
|
||||
@@ -0,0 +1,4 @@
|
||||
-- SPDX-License-Identifier: GPL-2.0-or-later
|
||||
-- Copyright (C) 2026 Bryan Joshua Pedini
|
||||
|
||||
GRANT ALL PRIVILEGES ON `{{WEBUI_DATABASE}}`.* TO '{{APP_USER}}'@'%';
|
||||
@@ -0,0 +1,9 @@
|
||||
-- SPDX-License-Identifier: GPL-2.0-or-later
|
||||
-- Copyright (C) 2026 Bryan Joshua Pedini
|
||||
|
||||
GRANT SELECT, INSERT, UPDATE, CREATE ON `{{WEBUI_DATABASE}}`.`{{WEBUI_PREFIX}}webui_locks` TO '{{APP_USER}}'@'%';
|
||||
GRANT SELECT, INSERT, UPDATE, CREATE, ALTER, INDEX, REFERENCES ON `{{WEBUI_DATABASE}}`.`{{WEBUI_PREFIX}}webui_schema` TO '{{APP_USER}}'@'%';
|
||||
GRANT SELECT, INSERT, UPDATE, CREATE, ALTER, INDEX, REFERENCES ON `{{WEBUI_DATABASE}}`.`{{WEBUI_PREFIX}}webui_users` TO '{{APP_USER}}'@'%';
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, INDEX, REFERENCES ON `{{WEBUI_DATABASE}}`.`{{WEBUI_PREFIX}}webui_sessions` TO '{{APP_USER}}'@'%';
|
||||
GRANT SELECT, INSERT, DELETE, CREATE, ALTER, INDEX, REFERENCES ON `{{WEBUI_DATABASE}}`.`{{WEBUI_PREFIX}}webui_zone_delegations` TO '{{APP_USER}}'@'%';
|
||||
GRANT SELECT, INSERT, CREATE, ALTER, INDEX, REFERENCES ON `{{WEBUI_DATABASE}}`.`{{WEBUI_PREFIX}}webui_audit` TO '{{APP_USER}}'@'%';
|
||||
+43
-11
@@ -5,7 +5,8 @@ import { test, expect } from '../harness/fixtures';
|
||||
import { run } from '../harness/proc';
|
||||
import { docker } from '../harness/docker';
|
||||
import { parseDig } from '../harness/dig';
|
||||
import { containerName, GROUPS, project, RUN_LABEL } from '../harness/env';
|
||||
import { containerName, GROUP_NAMES, GROUPS, project, RUN_LABEL } from '../harness/env';
|
||||
import { Db } from '../harness/mysql';
|
||||
import { decodedApiPath, matchRoute, sanitizeActor } from '../harness/ledger';
|
||||
import { parseTable, USAGE_TEXT } from '../harness/cli';
|
||||
import { rawRecord, sqlZone, canonicalContent, digData, bumpSerial, utcDay, type RawRecordInput } from '../harness/records';
|
||||
@@ -126,16 +127,47 @@ test.describe('harness self-checks', () => {
|
||||
expect(world.recorder.cli.length).toBeGreaterThanOrEqual(6);
|
||||
});
|
||||
|
||||
test('the application connects with the least-privilege grants of the plan', async ({ world }) => {
|
||||
const grants = (await world.db.query<Record<string, string>>(`SHOW GRANTS FOR '${world.g.appUser}'@'%'`)).map((r) => Object.values(r)[0]);
|
||||
const on = (table: string) => grants.find((g) => g.includes(`\`${world.g.database}\`.\`${world.g.prefix}${table}\``)) ?? '';
|
||||
expect(on('records')).toMatch(/GRANT SELECT, INSERT, UPDATE, DELETE ON/);
|
||||
expect(on('webui_users')).not.toMatch(/DELETE/);
|
||||
expect(on('webui_audit')).not.toMatch(/UPDATE|DELETE/);
|
||||
const dns = (await world.db.query<Record<string, string>>(`SHOW GRANTS FOR '${world.g.dnsUser}'@'%'`)).map((r) => Object.values(r)[0]);
|
||||
expect(dns.filter((g) => g.includes(world.g.database))).toEqual([`GRANT SELECT ON \`${world.g.database}\`.\`${world.g.prefix}records\` TO \`${world.g.dnsUser}\`@\`%\``]);
|
||||
for (const table of ['webui_schema', 'webui_users', 'webui_sessions', 'webui_zone_delegations', 'webui_audit']) {
|
||||
expect(await world.db.tableExists(`${world.g.prefix}${table}`), `${table} created by the migrations`).toBe(true);
|
||||
test('the application runs with grants on the records table only and full grants on its own database', async ({ world }) => {
|
||||
const g = world.g;
|
||||
expect(g.webuiDatabase).not.toBe(g.database);
|
||||
expect(g.webuiGrants).toBe('database');
|
||||
const grants = (await world.db.query<Record<string, string>>(`SHOW GRANTS FOR '${g.appUser}'@'%'`)).map((r) => Object.values(r)[0]);
|
||||
expect(grants.filter((x) => x.includes(`\`${g.database}\``))).toEqual([
|
||||
`GRANT SELECT, INSERT, UPDATE, DELETE ON \`${g.database}\`.\`${g.prefix}records\` TO \`${g.appUser}\`@\`%\``,
|
||||
]);
|
||||
expect(grants.filter((x) => x.includes(`\`${g.webuiDatabase}\``))).toEqual([`GRANT ALL PRIVILEGES ON \`${g.webuiDatabase}\`.* TO \`${g.appUser}\`@\`%\``]);
|
||||
const dns = (await world.db.query<Record<string, string>>(`SHOW GRANTS FOR '${g.dnsUser}'@'%'`)).map((r) => Object.values(r)[0]);
|
||||
expect(dns.filter((x) => x.includes(g.database))).toEqual([`GRANT SELECT ON \`${g.database}\`.\`${g.prefix}records\` TO \`${g.dnsUser}\`@\`%\``]);
|
||||
expect(await world.db.tables(g.database)).toEqual([`${g.prefix}records`]);
|
||||
const webuiTables = ['webui_audit', 'webui_locks', 'webui_schema', 'webui_sessions', 'webui_users', 'webui_zone_delegations'];
|
||||
expect(await world.db.tables(g.webuiDatabase)).toEqual(webuiTables.map((t) => `${g.webuiPrefix}${t}`));
|
||||
});
|
||||
|
||||
test('each group keeps the webui tables where its configuration puts them, with the least-privilege grants of the plan', async () => {
|
||||
for (const name of GROUP_NAMES) {
|
||||
const g = GROUPS[name];
|
||||
const db = new Db(g);
|
||||
try {
|
||||
const tables = await db.tables(g.database);
|
||||
const webui = ['webui_audit', 'webui_locks', 'webui_schema', 'webui_sessions', 'webui_users', 'webui_zone_delegations'].map((t) => `${g.webuiPrefix}${t}`);
|
||||
if (g.webuiDatabase === g.database) {
|
||||
expect(tables, name).toEqual([`${g.prefix}records`, ...webui].sort());
|
||||
} else {
|
||||
expect(tables, name).toEqual([`${g.prefix}records`]);
|
||||
expect(await db.tables(g.webuiDatabase), name).toEqual(webui);
|
||||
}
|
||||
if (g.webuiGrants !== 'tables') continue;
|
||||
const grants = (await db.query<Record<string, string>>(`SHOW GRANTS FOR '${g.appUser}'@'%'`)).map((r) => Object.values(r)[0]);
|
||||
const on = (schema: string, table: string) => grants.find((x) => x.includes(`\`${schema}\`.\`${table}\``)) ?? '';
|
||||
expect(on(g.database, `${g.prefix}records`), name).toMatch(/GRANT SELECT, INSERT, UPDATE, DELETE ON/);
|
||||
expect(on(g.webuiDatabase, `${g.webuiPrefix}webui_users`), name).toMatch(/GRANT .*INSERT/);
|
||||
expect(on(g.webuiDatabase, `${g.webuiPrefix}webui_users`), name).not.toMatch(/DELETE/);
|
||||
expect(on(g.webuiDatabase, `${g.webuiPrefix}webui_audit`), name).toMatch(/GRANT .*INSERT/);
|
||||
expect(on(g.webuiDatabase, `${g.webuiPrefix}webui_audit`), name).not.toMatch(/UPDATE|DELETE/);
|
||||
expect(grants.some((x) => / ON `[^`]+`\.\* /.test(x)), name).toBe(false);
|
||||
} finally {
|
||||
await db.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -5,6 +5,9 @@ DB_PASSWORD=coredns_webui_dev
|
||||
DB_NAME=coredns
|
||||
DB_TLS=false
|
||||
DB_TABLE_PREFIX=coredns_
|
||||
# Set DB_WEBUI_NAME after creating the database and granting access.
|
||||
# DB_WEBUI_NAME=coredns_webui
|
||||
# DB_WEBUI_TABLE_PREFIX=coredns_
|
||||
HTTP_ADDR=0.0.0.0
|
||||
HTTP_PORT=8080
|
||||
LOG_LEVEL=DEBUG
|
||||
|
||||
+1
-1
@@ -217,7 +217,7 @@ type fdbRule struct {
|
||||
|
||||
func fdbTables(t *testing.T) tableNames {
|
||||
t.Helper()
|
||||
tn, err := newTableNames("coredns_")
|
||||
tn, err := newTableNames(tableLayout{recordsSchema: "coredns", recordsPrefix: "coredns_", webuiSchema: "webui", webuiPrefix: "coredns_"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
+12
-12
@@ -1104,9 +1104,9 @@ func (f *zoneAPITestDB) query(query string, args []any) fdbResponse {
|
||||
return fdbResponse{rows: fdbRow(zoneAPITestValues(f.foreign)...)}
|
||||
}
|
||||
return fdbResponse{}
|
||||
case has("INSERT INTO `coredns_webui_audit`"):
|
||||
case has("INSERT INTO `webui`.`coredns_webui_audit`"):
|
||||
return fdbResponse{lastInsertID: 1, err: f.auditError}
|
||||
case has("INSERT INTO `coredns_records`"):
|
||||
case has("INSERT INTO `coredns`.`coredns_records`"):
|
||||
f.lastID++
|
||||
if f.hideInsert {
|
||||
return fdbResponse{lastInsertID: f.lastID}
|
||||
@@ -1116,7 +1116,7 @@ func (f *zoneAPITestDB) query(query string, args []any) fdbResponse {
|
||||
Content: sql.NullString{String: args[3].(string), Valid: true}, RecordType: args[4].(string),
|
||||
})
|
||||
return fdbResponse{lastInsertID: f.lastID, err: f.writeError}
|
||||
case has("UPDATE `coredns_records`"):
|
||||
case has("UPDATE `coredns`.`coredns_records`"):
|
||||
if i := slices.IndexFunc(f.rows, func(row recordRow) bool { return row.ID == args[5] }); i >= 0 {
|
||||
f.rows[i] = recordRow{
|
||||
ID: args[5].(int64), Zone: args[0].(string), Name: args[1].(string), RecordType: args[4].(string),
|
||||
@@ -1124,7 +1124,7 @@ func (f *zoneAPITestDB) query(query string, args []any) fdbResponse {
|
||||
}
|
||||
}
|
||||
return fdbResponse{rowsAffected: 1, err: f.writeError}
|
||||
case has("DELETE FROM `coredns_records`"):
|
||||
case has("DELETE FROM `coredns`.`coredns_records`"):
|
||||
f.rows = slices.DeleteFunc(f.rows, func(row recordRow) bool {
|
||||
return row.ID == args[0] || has(zoneRowsWhere) && zoneAPITestKey(row.Zone) == args[0]
|
||||
})
|
||||
@@ -1266,7 +1266,7 @@ func TestZoneAPIWriteHandlers(t *testing.T) {
|
||||
server, state := f.server()
|
||||
c := zoneAPITestRequest(server, f.actor, tc.operation, zone, tc.id, tc.etag, tc.body)
|
||||
resp := zoneAPITestStatus(t, t.Context(), c, tc.status)
|
||||
audits := zoneAPITestingSQL(state, "INSERT INTO `coredns_webui_audit`")
|
||||
audits := zoneAPITestingSQL(state, "INSERT INTO `webui`.`coredns_webui_audit`")
|
||||
if len(audits) != 1 || state.commits != 1 || state.rollbacks != 0 || !c.auditDone ||
|
||||
c.Entry.RecordID.Int64 != tc.recordID || c.Entry.RecordID.Valid != (tc.recordID != 0) ||
|
||||
audits[0].args[5] != int64(tc.status) || audits[0].args[7] != zoneAPITestName {
|
||||
@@ -1275,12 +1275,12 @@ func TestZoneAPIWriteHandlers(t *testing.T) {
|
||||
zoneAPITestAuditIDs(t, c.Entry.Before, tc.before)
|
||||
zoneAPITestAuditIDs(t, c.Entry.After, tc.after)
|
||||
if f.stale && (!strings.Contains(string(c.Entry.Before)+string(c.Entry.After), `{"zone":"example.org.","username":"bob"}`) ||
|
||||
len(zoneAPITestingSQL(state, "DELETE FROM `coredns_webui_zone_delegations`")) != 1) {
|
||||
len(zoneAPITestingSQL(state, "DELETE FROM `webui`.`coredns_webui_zone_delegations`")) != 1) {
|
||||
t.Fatal("delegation cleanup is missing")
|
||||
}
|
||||
if tc.serial {
|
||||
var serials []uint32
|
||||
for _, update := range zoneAPITestingSQL(state, "UPDATE `coredns_records`") {
|
||||
for _, update := range zoneAPITestingSQL(state, "UPDATE `coredns`.`coredns_records`") {
|
||||
if update.args[4] == "SOA" {
|
||||
row := recordRow{Content: sql.NullString{String: update.args[3].(string), Valid: true}}
|
||||
serial, _ := storedSOASerial(row)
|
||||
@@ -1302,7 +1302,7 @@ func TestZoneAPIWriteHandlers(t *testing.T) {
|
||||
}
|
||||
calls := state.Queries()
|
||||
if !strings.Contains(calls[0], "webui_locks") || !strings.HasSuffix(calls[1], "LOCK IN SHARE MODE") ||
|
||||
!strings.HasSuffix(calls[2], "FOR UPDATE") || !strings.Contains(calls[len(calls)-1], "INSERT INTO `coredns_webui_audit`") {
|
||||
!strings.HasSuffix(calls[2], "FOR UPDATE") || !strings.Contains(calls[len(calls)-1], "INSERT INTO `webui`.`coredns_webui_audit`") {
|
||||
t.Fatalf("write query order: %v", calls)
|
||||
}
|
||||
})
|
||||
@@ -1446,7 +1446,7 @@ func TestZoneAPIWarningsAndSerialModes(t *testing.T) {
|
||||
c := zoneAPITestRequest(server, f.actor, "record_create", zoneAPITestName, "", "", body)
|
||||
resp := zoneAPITestStatus(t, t.Context(), c, 201)
|
||||
if !strings.Contains(zoneAPITestJSON(t, resp.Body), "target_no_address") ||
|
||||
len(zoneAPITestingSQL(state, "UPDATE `coredns_records`")) != 0 ||
|
||||
len(zoneAPITestingSQL(state, "UPDATE `coredns`.`coredns_records`")) != 0 ||
|
||||
len(zoneAPITestingSQL(state, "zone_delegations` WHERE `zone` = CAST(? AS BINARY) AND `user_id` = ? LOCK IN SHARE MODE")) != 1 {
|
||||
t.Fatalf("response = %+v, SQL = %v", resp, state.Queries())
|
||||
}
|
||||
@@ -1459,7 +1459,7 @@ func TestZoneAPIWarningsAndSerialModes(t *testing.T) {
|
||||
c = zoneAPITestRequest(server, f.actor, "soa_update", zoneAPITestName, "", recordETag(rows[0]), `{"managed_serial":true,`+zoneAPITestSOA[1:])
|
||||
resp = zoneAPITestStatus(t, t.Context(), c, 200)
|
||||
if !c.auditDone || !strings.Contains(zoneAPITestJSON(t, resp.Body), `"serial":`+strconv.FormatUint(uint64(newSOASerial(modelNow)), 10)) ||
|
||||
len(zoneAPITestingSQL(state, "UPDATE `coredns_records`")) != 1 {
|
||||
len(zoneAPITestingSQL(state, "UPDATE `coredns`.`coredns_records`")) != 1 {
|
||||
t.Fatalf("SOA managed update: %+v, %s, SQL = %v", c.Entry, zoneAPITestJSON(t, resp.Body), state.Queries())
|
||||
}
|
||||
}
|
||||
@@ -1547,9 +1547,9 @@ func TestZoneAPIImport(t *testing.T) {
|
||||
}
|
||||
zoneAPITestAuditIDs(t, c.Entry.Before, []int64{1, 3, 4})
|
||||
zoneAPITestAuditIDs(t, c.Entry.After, []int64{1, 3, 5})
|
||||
updates := zoneAPITestingSQL(state, "UPDATE `coredns_records`")
|
||||
updates := zoneAPITestingSQL(state, "UPDATE `coredns`.`coredns_records`")
|
||||
if len(updates) != 2 || updates[0].args[4] != "SOA" || !strings.Contains(updates[0].args[3].(string), strconv.FormatUint(uint64(newSOASerial(modelNow)+1), 10)) ||
|
||||
len(zoneAPITestingSQL(state, "INSERT INTO `coredns_webui_audit`")) != 1 {
|
||||
len(zoneAPITestingSQL(state, "INSERT INTO `webui`.`coredns_webui_audit`")) != 1 {
|
||||
t.Fatalf("incorrect import SQL: %v", state.Calls())
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
|
||||
@@ -53,13 +53,13 @@ func TestZoneAPIFailurePaths(t *testing.T) {
|
||||
{name: "create malformed body", operation: "zone_create", body: "{", status: 400},
|
||||
{name: "create stale grant lookup", operation: "zone_create", body: zoneAPITestCreate, setup: rowsWithStale, failOn: []string{"ORDER BY username FOR UPDATE"}},
|
||||
{name: "create after removing stale grants", operation: "zone_create", body: zoneAPITestCreate, setup: rowsWithStale,
|
||||
failOn: []string{"INSERT INTO `coredns_records`"}, ran: "DELETE FROM `coredns_webui_zone_delegations`"},
|
||||
{name: "create written rows", operation: "zone_create", body: zoneAPITestCreate, setup: rowsWithStale, failOn: zoneRead, ran: "INSERT INTO `coredns_records`"},
|
||||
failOn: []string{"INSERT INTO `coredns`.`coredns_records`"}, ran: "DELETE FROM `webui`.`coredns_webui_zone_delegations`"},
|
||||
{name: "create written rows", operation: "zone_create", body: zoneAPITestCreate, setup: rowsWithStale, failOn: zoneRead, ran: "INSERT INTO `coredns`.`coredns_records`"},
|
||||
{name: "delete malformed body", operation: "zone_delete", body: `{"confirm":`, status: 400},
|
||||
{name: "delete grants", operation: "zone_delete", body: `{"confirm":"example.org"}`, setup: func(f *zoneAPITestDB, _ *apiContext) { f.stale = true },
|
||||
failOn: []string{"DELETE FROM `coredns_webui_zone_delegations`"}},
|
||||
failOn: []string{"DELETE FROM `webui`.`coredns_webui_zone_delegations`"}},
|
||||
{name: "delete after removing grants", operation: "zone_delete", body: `{"confirm":"example.org"}`, setup: func(f *zoneAPITestDB, _ *apiContext) { f.stale = true },
|
||||
failOn: []string{"DELETE FROM `coredns_records`"}, ran: "DELETE FROM `coredns_webui_zone_delegations`"},
|
||||
failOn: []string{"DELETE FROM `coredns`.`coredns_records`"}, ran: "DELETE FROM `webui`.`coredns_webui_zone_delegations`"},
|
||||
{name: "record lookup outside the zone", operation: "record_update", id: "99", etag: `"x"`, body: zoneAPITestRecord, failOn: []string{"WHERE `id` = ?", "SELECT"}},
|
||||
{name: "update malformed replacement", operation: "record_update", id: "3", etag: recordETag(rows[2]), body: `{"name":`, status: 400},
|
||||
{name: "update unknown field", operation: "record_update", id: "3", etag: recordETag(rows[2]), body: `{"name":"first","bogus":1}`, status: 400},
|
||||
@@ -68,10 +68,10 @@ func TestZoneAPIFailurePaths(t *testing.T) {
|
||||
{name: "update into a second SOA", operation: "record_update", id: "3", etag: recordETag(rows[2]), body: zoneAPITestSOARecord("@"), status: 422, field: "type"},
|
||||
{name: "update content not an object", operation: "record_update", id: "3", etag: recordETag(rows[2]),
|
||||
body: `{"name":"first","type":"A","ttl":60,"data":"192.0.2.1"}`, status: 422, field: "data"},
|
||||
{name: "update write", operation: "record_update", id: "3", etag: recordETag(rows[2]), body: zoneAPITestRecord, failOn: []string{"UPDATE `coredns_records`", "!`id` = 1"}},
|
||||
{name: "update write", operation: "record_update", id: "3", etag: recordETag(rows[2]), body: zoneAPITestRecord, failOn: []string{"UPDATE `coredns`.`coredns_records`", "!`id` = 1"}},
|
||||
{name: "update written rows", operation: "record_update", id: "3", etag: recordETag(rows[2]), body: zoneAPITestRecord, failOn: zoneRead},
|
||||
{name: "delete invalid id", operation: "record_delete", id: "x", etag: recordETag(rows[2]), status: 400},
|
||||
{name: "delete write", operation: "record_delete", id: "3", etag: recordETag(rows[2]), failOn: []string{"DELETE FROM `coredns_records`"}},
|
||||
{name: "delete write", operation: "record_delete", id: "3", etag: recordETag(rows[2]), failOn: []string{"DELETE FROM `coredns`.`coredns_records`"}},
|
||||
{name: "bulk malformed body", operation: "record_bulk_delete", body: `{"records":[`, status: 400},
|
||||
{name: "bulk SOA in the batch", operation: "record_bulk_delete",
|
||||
body: `{"records":[{"id":3,"etag":` + zoneAPITestJSON(t, recordETag(rows[2])) + `},{"id":1,"etag":` + zoneAPITestJSON(t, recordETag(rows[0])) + `}]}`,
|
||||
@@ -84,10 +84,10 @@ func TestZoneAPIFailurePaths(t *testing.T) {
|
||||
status: 422, field: "records"},
|
||||
{name: "bulk write", operation: "record_bulk_delete",
|
||||
body: `{"records":[{"id":3,"etag":` + zoneAPITestJSON(t, recordETag(rows[2])) + `},{"id":4,"etag":` + zoneAPITestJSON(t, recordETag(rows[3])) + `}]}`,
|
||||
failOn: []string{"DELETE FROM `coredns_records`"}},
|
||||
failOn: []string{"DELETE FROM `coredns`.`coredns_records`"}},
|
||||
{name: "SOA malformed body", operation: "soa_update", etag: recordETag(rows[0]), body: "[", status: 400},
|
||||
{name: "SOA write", operation: "soa_update", etag: recordETag(rows[0]), body: strings.Replace(zoneAPITestSOA, `"retry":600`, `"retry":700`, 1),
|
||||
failOn: []string{"UPDATE `coredns_records`"}},
|
||||
failOn: []string{"UPDATE `coredns`.`coredns_records`"}},
|
||||
{name: "SOA relative primary name server", operation: "soa_update", etag: recordETag(rows[0]),
|
||||
body: strings.Replace(zoneAPITestSOA, "ns.example.net", "ns..example.net", 1), status: 422, field: "ns"},
|
||||
{name: "import malformed body", operation: "zone_import", body: `{"mode":"merge",`, status: 400},
|
||||
@@ -95,7 +95,7 @@ func TestZoneAPIFailurePaths(t *testing.T) {
|
||||
{name: "import missing content preview", operation: "zone_import_preview", body: `{"mode":"replace"}`, status: 422, field: "content"},
|
||||
{name: "import write", operation: "zone_import",
|
||||
body: `{"mode":"merge","content":"new 60 A 192.0.2.9\n","fingerprint":"` + zoneFingerprint(rows) + `"}`,
|
||||
failOn: []string{"INSERT INTO `coredns_records`"}},
|
||||
failOn: []string{"INSERT INTO `coredns`.`coredns_records`"}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := zoneAPITestDBFor(t, rows)
|
||||
|
||||
+14
-14
@@ -41,7 +41,7 @@ func TestIntegrationUserCLI(t *testing.T) {
|
||||
t.Fatalf("%d %q", code, cli.stderr.String())
|
||||
}
|
||||
var hash string
|
||||
if err := d.root.QueryRow("SELECT `password_hash` FROM `coredns_webui_users` WHERE `username` = 'alice'").Scan(&hash); err != nil || hash != "$test$first password here" {
|
||||
if err := d.root.QueryRow(d.sql("SELECT `password_hash` FROM {users} WHERE `username` = 'alice'")).Scan(&hash); err != nil || hash != "$test$first password here" {
|
||||
t.Fatal(hash, err)
|
||||
}
|
||||
if code := cli.run("user", "list"); code != 0 {
|
||||
@@ -59,14 +59,14 @@ func TestIntegrationUserCLI(t *testing.T) {
|
||||
if code := cli.run("user", "delete", "alice"); code != 1 || !strings.Contains(cli.stderr.String(), "last active admin") {
|
||||
t.Fatalf("%d %q", code, cli.stderr.String())
|
||||
}
|
||||
bobID := int64(d.count(t, "SELECT `id` FROM `coredns_webui_users` WHERE `username` = 'bob'"))
|
||||
d.rootExec(t, "INSERT INTO `coredns_webui_sessions` VALUES (UNHEX(SHA2('a', 256)), ?, NOW(6), NOW(6), NOW(6), 'x', 'y')", bobID)
|
||||
d.rootExec(t, "INSERT INTO `coredns_webui_sessions` VALUES (UNHEX(SHA2('b', 256)), ?, NOW(6), NOW(6), NOW(6), 'x', 'y')", bobID)
|
||||
bobID := int64(d.count(t, "SELECT `id` FROM {users} WHERE `username` = 'bob'"))
|
||||
d.rootExec(t, "INSERT INTO {sessions} VALUES (UNHEX(SHA2('a', 256)), ?, NOW(6), NOW(6), NOW(6), 'x', 'y')", bobID)
|
||||
d.rootExec(t, "INSERT INTO {sessions} VALUES (UNHEX(SHA2('b', 256)), ?, NOW(6), NOW(6), NOW(6), 'x', 'y')", bobID)
|
||||
cli = d.cli(t, "new bob password\n", now.Add(time.Minute))
|
||||
if code := cli.run("user", "passwd", "bob"); code != 0 {
|
||||
t.Fatalf("%d %q", code, cli.stderr.String())
|
||||
}
|
||||
if d.count(t, "SELECT COUNT(*) FROM `coredns_webui_sessions`") != 0 {
|
||||
if d.count(t, "SELECT COUNT(*) FROM {sessions}") != 0 {
|
||||
t.Fatal("sessions survived passwd")
|
||||
}
|
||||
if code := cli.run("user", "role", "bob", "admin"); code != 0 {
|
||||
@@ -75,14 +75,14 @@ func TestIntegrationUserCLI(t *testing.T) {
|
||||
if code := cli.run("user", "role", "alice", "user"); code != 0 {
|
||||
t.Fatalf("%d %q", code, cli.stderr.String())
|
||||
}
|
||||
d.rootExec(t, "INSERT INTO `coredns_webui_sessions` VALUES (UNHEX(SHA2('c', 256)), (SELECT `id` FROM `coredns_webui_users` WHERE `username` = 'alice'), NOW(6), NOW(6), NOW(6), 'x', 'y')")
|
||||
d.rootExec(t, "INSERT INTO {sessions} VALUES (UNHEX(SHA2('c', 256)), (SELECT `id` FROM {users} WHERE `username` = 'alice'), NOW(6), NOW(6), NOW(6), 'x', 'y')")
|
||||
if code := cli.run("user", "delete", "alice"); code != 0 {
|
||||
t.Fatalf("%d %q", code, cli.stderr.String())
|
||||
}
|
||||
if d.count(t, "SELECT COUNT(*) FROM `coredns_webui_sessions`") != 0 {
|
||||
if d.count(t, "SELECT COUNT(*) FROM {sessions}") != 0 {
|
||||
t.Fatal("sessions survived delete")
|
||||
}
|
||||
if d.count(t, "SELECT COUNT(*) FROM `coredns_webui_users` WHERE `username` = 'alice' AND `deleted_at` IS NOT NULL") != 1 {
|
||||
if d.count(t, "SELECT COUNT(*) FROM {users} WHERE `username` = 'alice' AND `deleted_at` IS NOT NULL") != 1 {
|
||||
t.Fatal("deleted user row missing")
|
||||
}
|
||||
for _, args := range [][]string{{"user", "passwd", "alice"}, {"user", "role", "alice", "admin"}, {"user", "delete", "alice"}, {"user", "passwd", "nobody"}} {
|
||||
@@ -99,7 +99,7 @@ func TestIntegrationUserCLI(t *testing.T) {
|
||||
t.Fatalf("%d\n%s", code, cli.stdout.String())
|
||||
}
|
||||
|
||||
rows, err := d.root.Query("SELECT `user_id`, `actor`, `origin`, `operation`, `status`, `error`, `zone`, `record_id`, `target_user_id`, `before_value`, `after_value` FROM `coredns_webui_audit` ORDER BY `id`")
|
||||
rows, err := d.root.Query(d.sql("SELECT `user_id`, `actor`, `origin`, `operation`, `status`, `error`, `zone`, `record_id`, `target_user_id`, `before_value`, `after_value` FROM {audit} ORDER BY `id`"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -163,10 +163,10 @@ func TestIntegrationLastAdminRace(t *testing.T) {
|
||||
if codes[0]+codes[1] != 1 {
|
||||
t.Fatalf("round %d: exit codes %v", round, codes)
|
||||
}
|
||||
if n := d.count(t, "SELECT COUNT(*) FROM `coredns_webui_users` WHERE `role` = 'admin' AND `deleted_at` IS NULL"); n != 1 {
|
||||
if n := d.count(t, "SELECT COUNT(*) FROM {users} WHERE `role` = 'admin' AND `deleted_at` IS NULL"); n != 1 {
|
||||
t.Fatalf("round %d: %d active admins", round, n)
|
||||
}
|
||||
if n := d.count(t, "SELECT COUNT(*) FROM `coredns_webui_audit` WHERE `operation` IN ('user_role', 'user_delete')"); n != 1 {
|
||||
if n := d.count(t, "SELECT COUNT(*) FROM {audit} WHERE `operation` IN ('user_role', 'user_delete')"); n != 1 {
|
||||
t.Fatalf("round %d: %d change rows", round, n)
|
||||
}
|
||||
}
|
||||
@@ -179,10 +179,10 @@ func TestIntegrationCheckAndAuditCommands(t *testing.T) {
|
||||
if code := c.run("check"); code != 0 || c.stdout.String() != "ZONE NAME TYPE ID SEVERITY PROBLEM\n" {
|
||||
t.Fatalf("%d %q %q", code, c.stdout.String(), c.stderr.String())
|
||||
}
|
||||
if d.count(t, "SELECT `version` FROM `dns_webui_schema`") != 2 {
|
||||
if d.count(t, "SELECT `version` FROM {schema}") != 2 {
|
||||
t.Fatal("check did not migrate")
|
||||
}
|
||||
d.rootExec(t, "INSERT INTO `dns_records` (`zone`, `name`, `ttl`, `content`, `record_type`) VALUES ('example.org.', 'www', NULL, '{\"ip\": \"192.0.2.1\"}', 'A')")
|
||||
d.rootExec(t, "INSERT INTO {records} (`zone`, `name`, `ttl`, `content`, `record_type`) VALUES ('example.org.', 'www', NULL, '{\"ip\": \"192.0.2.1\"}', 'A')")
|
||||
c = d.cli(t, "", time.Now())
|
||||
if code := c.run("check", "EXAMPLE.org"); code != 3 || !strings.Contains(c.stdout.String(), "ttl_null") || !strings.Contains(c.stdout.String(), "soa_missing") {
|
||||
t.Fatalf("%d %q %q", code, c.stdout.String(), c.stderr.String())
|
||||
@@ -240,7 +240,7 @@ func TestIntegrationServer(t *testing.T) {
|
||||
if results["/health"] != `200 OK {"status":"ok"}` || !strings.Contains(results["/version"], "CoreDNS Web UI") {
|
||||
t.Fatalf("%v", results)
|
||||
}
|
||||
if d.count(t, "SELECT `version` FROM `coredns_webui_schema`") != 2 {
|
||||
if d.count(t, "SELECT `version` FROM {schema}") != 2 {
|
||||
t.Fatal("server did not migrate")
|
||||
}
|
||||
}
|
||||
+38
-41
@@ -74,18 +74,18 @@ func TestIntegrationContractCheck(t *testing.T) {
|
||||
if code := run([]string{"user", "list"}, cli.a); code != 1 || !strings.Contains(cli.stderr.String(), c.want) {
|
||||
t.Fatalf("%s: cli %d %q", c.name, code, cli.stderr.String())
|
||||
}
|
||||
if n := d.count(t, "SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE '%webui%'"); n != 0 {
|
||||
if n := d.count(t, "SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA IN (?, ?) AND TABLE_NAME LIKE '%webui%'", d.name, d.webui); n != 0 {
|
||||
t.Fatalf("%s: migrations ran after a failed contract check", c.name)
|
||||
}
|
||||
}
|
||||
for _, prefix := range []string{"dns_", "", "P_2"} {
|
||||
d := newITDatabase(t, itOptions{prefix: prefix})
|
||||
db, tn := d.migrated(t)
|
||||
other, _ := newTableNames("coredns_")
|
||||
other, _ := newTableNames(tableLayout{recordsSchema: d.name, recordsPrefix: "coredns_", webuiSchema: d.webui, webuiPrefix: prefix})
|
||||
if err := verifyRecordsContract(ctx, db, other, discardLogger()); !errors.Is(err, errContract) {
|
||||
t.Fatalf("prefix %q: default prefix accepted: %v", prefix, err)
|
||||
}
|
||||
if n := d.count(t, "SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?", prefix+"webui_users"); n != 1 {
|
||||
if n := d.count(t, "SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?", d.webui, prefix+"webui_users"); n != 1 {
|
||||
t.Fatalf("prefix %q: users table missing", prefix)
|
||||
}
|
||||
if _, err := newUserStore(db, tn).CreateUser(ctx, "alice", "admin", "$h", time.Now()); err != nil {
|
||||
@@ -102,14 +102,14 @@ func TestIntegrationContractCheck(t *testing.T) {
|
||||
|
||||
func TestIntegrationMigrationRestartsAfterEveryDDL(t *testing.T) {
|
||||
const prefix = "resume_"
|
||||
migrations, err := loadMigrations(migrationFiles, prefix)
|
||||
migrations, err := loadMigrations(migrationFiles, "count", prefix)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
statements := migrations[0].statements
|
||||
for boundary := 1; boundary <= len(statements); boundary++ {
|
||||
for boundary := 1; boundary <= len(migrations[0].statements); boundary++ {
|
||||
t.Run(fmt.Sprintf("after_ddl_%d", boundary), func(t *testing.T) {
|
||||
d := newITDatabase(t, itOptions{prefix: prefix})
|
||||
statements := d.migrations(t)[0].statements
|
||||
tn := d.tables(t)
|
||||
db := d.openApp(t)
|
||||
ctx := t.Context()
|
||||
@@ -128,7 +128,7 @@ func TestIntegrationMigrationRestartsAfterEveryDDL(t *testing.T) {
|
||||
if v, err := schemaVersion(ctx, db, tn); err != nil || v != 2 {
|
||||
t.Fatalf("restarted schema version = %d, %v", v, err)
|
||||
}
|
||||
if n := d.count(t, "SELECT COUNT(*) FROM information_schema.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = DATABASE()"); n != 5 {
|
||||
if n := d.count(t, "SELECT COUNT(*) FROM information_schema.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = ?", d.webui); n != 5 {
|
||||
t.Fatalf("restarted schema has %d foreign keys", n)
|
||||
}
|
||||
})
|
||||
@@ -174,31 +174,31 @@ func TestIntegrationMigrations(t *testing.T) {
|
||||
// MariaDB can report a charset-prefixed collation alias in TABLES
|
||||
// even when its COLLATIONS view only lists the unprefixed name.
|
||||
for _, table := range []string{"coredns_webui_schema", "coredns_webui_users", "coredns_webui_sessions", "coredns_webui_zone_delegations", "coredns_webui_audit"} {
|
||||
if d.count(t, "SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND LEFT(TABLE_COLLATION, 8) = 'utf8mb4_' AND ENGINE = 'InnoDB'", table) != 1 {
|
||||
if d.count(t, "SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND LEFT(TABLE_COLLATION, 8) = 'utf8mb4_' AND ENGINE = 'InnoDB'", d.webui, table) != 1 {
|
||||
t.Fatalf("%s missing or has a different character set or engine", table)
|
||||
}
|
||||
}
|
||||
if n := d.count(t, "SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND DATA_TYPE = 'datetime' AND DATETIME_PRECISION = 6"); n != 9 {
|
||||
if n := d.count(t, "SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA IN (?, ?) AND DATA_TYPE = 'datetime' AND DATETIME_PRECISION = 6", d.name, d.webui); n != 9 {
|
||||
t.Fatalf("DATETIME(6) columns: %d", n)
|
||||
}
|
||||
if n := d.count(t, "SELECT COUNT(*) FROM information_schema.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = DATABASE()"); n != 5 {
|
||||
if n := d.count(t, "SELECT COUNT(*) FROM information_schema.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_SCHEMA IN (?, ?)", d.name, d.webui); n != 5 {
|
||||
t.Fatalf("foreign keys: %d", n)
|
||||
}
|
||||
if err := migrateDatabase(ctx, db, tn, discardLogger()); err != nil {
|
||||
t.Fatalf("rerun: %v", err)
|
||||
}
|
||||
if n := d.count(t, "SELECT COUNT(*) FROM `coredns_webui_schema`"); n != 1 {
|
||||
if n := d.count(t, "SELECT COUNT(*) FROM {schema}"); n != 1 {
|
||||
t.Fatalf("schema rows %d", n)
|
||||
}
|
||||
if n := d.count(t, "SELECT `version` FROM `coredns_webui_schema` WHERE `id` = 1"); n != 2 {
|
||||
if n := d.count(t, "SELECT `version` FROM {schema} WHERE `id` = 1"); n != 2 {
|
||||
t.Fatalf("version %d", n)
|
||||
}
|
||||
if d.hasCheckConstraint(t, "webui_schema") {
|
||||
if _, err := d.root.Exec("INSERT INTO `coredns_webui_schema` (`id`, `version`) VALUES (2, 1)"); err == nil {
|
||||
if _, err := d.root.Exec(d.sql("INSERT INTO {schema} (`id`, `version`) VALUES (2, 1)")); err == nil {
|
||||
t.Fatal("second schema row accepted")
|
||||
}
|
||||
}
|
||||
d.rootExec(t, "UPDATE `coredns_webui_schema` SET `version` = 3")
|
||||
d.rootExec(t, "UPDATE {schema} SET `version` = 3")
|
||||
if err := migrateDatabase(ctx, db, tn, discardLogger()); err == nil || !strings.Contains(err.Error(), "newer") {
|
||||
t.Fatalf("newer schema: %v", err)
|
||||
}
|
||||
@@ -216,13 +216,10 @@ func TestIntegrationAcceptsExistingJSONAuditColumns(t *testing.T) {
|
||||
|
||||
func TestIntegrationAuditRecordIDMigration(t *testing.T) {
|
||||
const prefix = "audit_id_"
|
||||
migrations, err := loadMigrations(migrationFiles, prefix)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, name := range []string{"upgrade", "restart_after_ddl"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
d := newITDatabase(t, itOptions{prefix: prefix})
|
||||
migrations := d.migrations(t)
|
||||
db, tables := d.openApp(t), d.tables(t)
|
||||
ctx := t.Context()
|
||||
if err := applyMigrations(ctx, db, tables, migrations[:1], discardLogger()); err != nil {
|
||||
@@ -290,7 +287,7 @@ func TestIntegrationConcurrentMigrations(t *testing.T) {
|
||||
t.Fatalf("round %d: %v", round, err)
|
||||
}
|
||||
}
|
||||
if n := d.count(t, "SELECT `version` FROM `coredns_webui_schema` WHERE `id` = 1"); n != 2 {
|
||||
if n := d.count(t, "SELECT `version` FROM {schema} WHERE `id` = 1"); n != 2 {
|
||||
t.Fatalf("version %d", n)
|
||||
}
|
||||
}
|
||||
@@ -310,37 +307,37 @@ func TestIntegrationGrants(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
denied := []string{
|
||||
"DELETE FROM `coredns_webui_users` WHERE `id` = " + strconv.FormatInt(u.ID, 10),
|
||||
"UPDATE `coredns_webui_audit` SET `actor` = 'x'",
|
||||
"DELETE FROM `coredns_webui_audit`",
|
||||
"UPDATE `coredns_webui_zone_delegations` SET `zone` = 'x.'",
|
||||
"DROP TABLE `coredns_webui_audit`",
|
||||
"DROP TABLE `coredns_records`",
|
||||
"ALTER TABLE `coredns_records` ADD COLUMN `x` INT",
|
||||
"TRUNCATE TABLE `coredns_webui_audit`",
|
||||
"DELETE FROM {users} WHERE `id` = " + strconv.FormatInt(u.ID, 10),
|
||||
"UPDATE {audit} SET `actor` = 'x'",
|
||||
"DELETE FROM {audit}",
|
||||
"UPDATE {delegations} SET `zone` = 'x.'",
|
||||
"DROP TABLE {audit}",
|
||||
"DROP TABLE {records}",
|
||||
"ALTER TABLE {records} ADD COLUMN `x` INT",
|
||||
"TRUNCATE TABLE {audit}",
|
||||
}
|
||||
for _, q := range denied {
|
||||
_, err := db.ExecContext(ctx, q)
|
||||
_, err := db.ExecContext(ctx, d.sql(q))
|
||||
if n := mysqlErrNumber(err); n != 1142 {
|
||||
t.Errorf("%s: %v", q, err)
|
||||
}
|
||||
}
|
||||
if d.count(t, "SELECT COUNT(*) FROM `coredns_webui_users`") != 1 || d.count(t, "SELECT COUNT(*) FROM `coredns_webui_audit`") != 1 {
|
||||
if d.count(t, "SELECT COUNT(*) FROM {users}") != 1 || d.count(t, "SELECT COUNT(*) FROM {audit}") != 1 {
|
||||
t.Fatal("rows changed")
|
||||
}
|
||||
dns := d.openDNS(t)
|
||||
d.rootExec(t, "INSERT INTO `coredns_records` (`zone`, `name`, `ttl`, `content`, `record_type`) VALUES ('a.org.', '', 60, '{}', 'NS')")
|
||||
d.rootExec(t, "INSERT INTO {records} (`zone`, `name`, `ttl`, `content`, `record_type`) VALUES ('a.org.', '', 60, '{}', 'NS')")
|
||||
var n int
|
||||
if err := dns.QueryRow("SELECT COUNT(*) FROM `coredns_records`").Scan(&n); err != nil || n != 1 {
|
||||
if err := dns.QueryRow(d.sql("SELECT COUNT(*) FROM {records}")).Scan(&n); err != nil || n != 1 {
|
||||
t.Fatal(n, err)
|
||||
}
|
||||
for _, table := range []string{"coredns_webui_schema", "coredns_webui_users", "coredns_webui_sessions", "coredns_webui_zone_delegations", "coredns_webui_audit"} {
|
||||
err := dns.QueryRow("SELECT COUNT(*) FROM `" + table + "`").Scan(&n)
|
||||
for _, table := range []string{"{schema}", "{users}", "{sessions}", "{delegations}", "{audit}", "{locks}"} {
|
||||
err := dns.QueryRow(d.sql("SELECT COUNT(*) FROM " + table)).Scan(&n)
|
||||
if mysqlErrNumber(err) != 1142 {
|
||||
t.Errorf("coredns user reads %s: %v", table, err)
|
||||
}
|
||||
}
|
||||
if _, err := dns.Exec("DELETE FROM `coredns_records`"); mysqlErrNumber(err) != 1142 {
|
||||
if _, err := dns.Exec(d.sql("DELETE FROM {records}")); mysqlErrNumber(err) != 1142 {
|
||||
t.Errorf("coredns user writes records: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -382,18 +379,18 @@ func TestIntegrationForeignKeys(t *testing.T) {
|
||||
t.Errorf("check %d: %v", i, err)
|
||||
}
|
||||
}
|
||||
if _, err := d.root.Exec("DELETE FROM `coredns_webui_users` WHERE `id` = ?", u.ID); err != nil {
|
||||
if _, err := d.root.Exec(d.sql("DELETE FROM {users} WHERE `id` = ?"), u.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u2, _ := newUserStore(db, tn).CreateUser(ctx, "bob", "user", "$h", now)
|
||||
if _, err := newDelegationStore(db, tn).GrantDelegation(ctx, "a.org.", u2.ID, u2.ID, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := d.root.Exec("DELETE FROM `coredns_webui_users` WHERE `id` = ?", u2.ID); mysqlErrNumber(err) != 1451 {
|
||||
if _, err := d.root.Exec(d.sql("DELETE FROM {users} WHERE `id` = ?"), u2.ID); mysqlErrNumber(err) != 1451 {
|
||||
t.Fatalf("referenced user deleted: %v", err)
|
||||
}
|
||||
if d.hasCheckConstraint(t, "webui_users") {
|
||||
_, err := d.root.Exec("INSERT INTO `coredns_webui_users` (`username`, `role`, `password_hash`, `created_at`, `updated_at`) VALUES ('x', 'root', 'h', NOW(6), NOW(6))")
|
||||
_, err := d.root.Exec(d.sql("INSERT INTO {users} (`username`, `role`, `password_hash`, `created_at`, `updated_at`) VALUES ('x', 'root', 'h', NOW(6), NOW(6))"))
|
||||
if n := mysqlErrNumber(err); n != 3819 && n != 4025 {
|
||||
t.Fatalf("role check: %v", err)
|
||||
}
|
||||
@@ -419,7 +416,7 @@ func TestIntegrationTransactionRollback(t *testing.T) {
|
||||
if !errors.Is(err, forced) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if d.count(t, "SELECT COUNT(*) FROM `coredns_records`") != 0 || d.count(t, "SELECT COUNT(*) FROM `coredns_webui_audit`") != 0 {
|
||||
if d.count(t, "SELECT COUNT(*) FROM {records}") != 0 || d.count(t, "SELECT COUNT(*) FROM {audit}") != 0 {
|
||||
t.Fatal("rollback left rows")
|
||||
}
|
||||
err = runInTx(ctx, db, func(tx *sql.Tx) error {
|
||||
@@ -430,7 +427,7 @@ func TestIntegrationTransactionRollback(t *testing.T) {
|
||||
_, err = newAuditStore(tx, tn).InsertAudit(ctx, auditEntry{Time: time.Now(), Actor: "x", Origin: "x", Operation: "record_create"})
|
||||
return err
|
||||
})
|
||||
if err != nil || d.count(t, "SELECT COUNT(*) FROM `coredns_records`") != 1 || d.count(t, "SELECT COUNT(*) FROM `coredns_webui_audit`") != 1 {
|
||||
if err != nil || d.count(t, "SELECT COUNT(*) FROM {records}") != 1 || d.count(t, "SELECT COUNT(*) FROM {audit}") != 1 {
|
||||
t.Fatalf("commit: %v", err)
|
||||
}
|
||||
err = runInTx(ctx, db, func(tx *sql.Tx) error {
|
||||
@@ -440,7 +437,7 @@ func TestIntegrationTransactionRollback(t *testing.T) {
|
||||
_, err := newAuditStore(tx, tn).InsertAudit(ctx, auditEntry{Time: time.Now(), Actor: "x", Origin: "x", Operation: strings.Repeat("o", 40)})
|
||||
return err
|
||||
})
|
||||
if err == nil || d.count(t, "SELECT COUNT(*) FROM `coredns_records`") != 1 {
|
||||
if err == nil || d.count(t, "SELECT COUNT(*) FROM {records}") != 1 {
|
||||
t.Fatalf("failed audit insert did not roll back the change: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -464,7 +461,7 @@ func TestIntegrationDatetimeUTC(t *testing.T) {
|
||||
t.Fatalf("got %v want %v", got.CreatedAt, want)
|
||||
}
|
||||
var raw string
|
||||
if err := d.root.QueryRow("SELECT DATE_FORMAT(`created_at`, '%Y-%m-%d %H:%i:%s.%f') FROM `coredns_webui_users`").Scan(&raw); err != nil || raw != "2026-03-28 21:30:45.123456" {
|
||||
if err := d.root.QueryRow(d.sql("SELECT DATE_FORMAT(`created_at`, '%Y-%m-%d %H:%i:%s.%f') FROM {users}")).Scan(&raw); err != nil || raw != "2026-03-28 21:30:45.123456" {
|
||||
t.Fatalf("stored %q %v", raw, err)
|
||||
}
|
||||
conn, err := db.Conn(ctx)
|
||||
|
||||
+80
-10
@@ -88,6 +88,8 @@ type itDatabase struct {
|
||||
server itServer
|
||||
name string
|
||||
prefix string
|
||||
webui string
|
||||
webuiPrefix string
|
||||
appUser string
|
||||
appPassword string
|
||||
dnsUser string
|
||||
@@ -98,17 +100,24 @@ type itDatabase struct {
|
||||
// InnoDB on older servers only refreshes its lock metadata after 100 ms of idle time.
|
||||
const itLockPollInterval = 150 * time.Millisecond
|
||||
|
||||
func (d *itDatabase) table(suffix string) (string, string) {
|
||||
if suffix == "records" {
|
||||
return d.name, d.prefix + suffix
|
||||
}
|
||||
return d.webui, d.webuiPrefix + suffix
|
||||
}
|
||||
|
||||
func (d *itDatabase) rowLockWaiting(ctx context.Context, suffix string) (bool, error) {
|
||||
table := d.prefix + suffix
|
||||
schema, table := d.table(suffix)
|
||||
var waiting bool
|
||||
err := d.root.QueryRowContext(ctx, "SELECT EXISTS (SELECT 1 FROM performance_schema.data_lock_waits w "+
|
||||
"JOIN performance_schema.data_locks l ON l.ENGINE = w.ENGINE AND l.ENGINE_LOCK_ID = w.REQUESTING_ENGINE_LOCK_ID "+
|
||||
"WHERE l.OBJECT_SCHEMA = ? AND l.OBJECT_NAME = ?)", d.name, table).Scan(&waiting)
|
||||
"WHERE l.OBJECT_SCHEMA = ? AND l.OBJECT_NAME = ?)", schema, table).Scan(&waiting)
|
||||
if mysqlErrNumber(err) == 1146 {
|
||||
// MySQL 5.7 and MariaDB expose the same wait through InnoDB metadata.
|
||||
err = d.root.QueryRowContext(ctx, "SELECT EXISTS (SELECT 1 FROM information_schema.INNODB_LOCK_WAITS w "+
|
||||
"JOIN information_schema.INNODB_LOCKS l ON l.LOCK_ID = w.REQUESTED_LOCK_ID "+
|
||||
"WHERE l.LOCK_TABLE = ?)", "`"+d.name+"`.`"+table+"`").Scan(&waiting)
|
||||
"WHERE l.LOCK_TABLE = ?)", qualifiedIdent(schema, table)).Scan(&waiting)
|
||||
}
|
||||
return waiting, err
|
||||
}
|
||||
@@ -116,7 +125,7 @@ func (d *itDatabase) rowLockWaiting(ctx context.Context, suffix string) (bool, e
|
||||
func (d *itDatabase) hasCheckConstraint(t *testing.T, suffix string) bool {
|
||||
t.Helper()
|
||||
var tableName, ddl string
|
||||
if err := d.root.QueryRow("SHOW CREATE TABLE `"+d.prefix+suffix+"`").Scan(&tableName, &ddl); err != nil {
|
||||
if err := d.root.QueryRow("SHOW CREATE TABLE "+qualifiedIdent(d.table(suffix))).Scan(&tableName, &ddl); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// MySQL 5.7 parses CHECK constraints and omits them from the table.
|
||||
@@ -127,6 +136,24 @@ type itOptions struct {
|
||||
prefix string
|
||||
recordDDL string
|
||||
noRecords bool
|
||||
layout string
|
||||
webuiPrefix *string
|
||||
webuiGrants []string
|
||||
}
|
||||
|
||||
const (
|
||||
itLayoutShared = "shared"
|
||||
itLayoutSeparate = "separate"
|
||||
)
|
||||
|
||||
func itLayout(opts itOptions) string {
|
||||
if opts.layout != "" {
|
||||
return opts.layout
|
||||
}
|
||||
if os.Getenv("IT_WEBUI_LAYOUT") == itLayoutSeparate {
|
||||
return itLayoutSeparate
|
||||
}
|
||||
return itLayoutShared
|
||||
}
|
||||
|
||||
func newITDatabase(t *testing.T, opts itOptions) *itDatabase {
|
||||
@@ -137,11 +164,19 @@ func newITDatabase(t *testing.T, opts itOptions) *itDatabase {
|
||||
server: srv,
|
||||
name: "it_" + id,
|
||||
prefix: opts.prefix,
|
||||
webui: "it_" + id,
|
||||
webuiPrefix: opts.prefix,
|
||||
appUser: "it_" + id + "_app",
|
||||
appPassword: itRandom(12),
|
||||
dnsUser: "it_" + id + "_dns",
|
||||
dnsPassword: itRandom(12),
|
||||
}
|
||||
if itLayout(opts) == itLayoutSeparate {
|
||||
d.webui = "it_" + id + "_webui"
|
||||
}
|
||||
if opts.webuiPrefix != nil {
|
||||
d.webuiPrefix = *opts.webuiPrefix
|
||||
}
|
||||
admin := srv.open(t, "root", srv.rootPassword, "")
|
||||
ctx := context.Background()
|
||||
exec := func(operation, query string) {
|
||||
@@ -151,7 +186,11 @@ func newITDatabase(t *testing.T, opts itOptions) *itDatabase {
|
||||
}
|
||||
}
|
||||
exec("create database", "CREATE DATABASE `"+d.name+"` DEFAULT CHARSET = utf8mb4")
|
||||
if d.webui != d.name {
|
||||
exec("create webui database", "CREATE DATABASE `"+d.webui+"` DEFAULT CHARSET = utf8mb4")
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_, _ = admin.ExecContext(ctx, "DROP DATABASE IF EXISTS `"+d.webui+"`")
|
||||
_, _ = admin.ExecContext(ctx, "DROP DATABASE IF EXISTS `"+d.name+"`")
|
||||
_, _ = admin.ExecContext(ctx, "DROP USER IF EXISTS '"+d.appUser+"'@'%'")
|
||||
_, _ = admin.ExecContext(ctx, "DROP USER IF EXISTS '"+d.dnsUser+"'@'%'")
|
||||
@@ -166,10 +205,13 @@ func newITDatabase(t *testing.T, opts itOptions) *itDatabase {
|
||||
exec("create application user", "CREATE USER '"+d.appUser+"'@'%' IDENTIFIED BY '"+d.appPassword+"'")
|
||||
exec("create dns user", "CREATE USER '"+d.dnsUser+"'@'%' IDENTIFIED BY '"+d.dnsPassword+"'")
|
||||
for _, g := range itAppGrants {
|
||||
if !g.create && opts.noRecords {
|
||||
if !g.create && opts.noRecords || g.create && opts.webuiGrants != nil {
|
||||
continue
|
||||
}
|
||||
exec("grant application privileges on "+g.table, fmt.Sprintf("GRANT %s ON `%s`.`%s%s` TO '%s'@'%%'", g.privs, d.name, d.prefix, g.table, d.appUser))
|
||||
exec("grant application privileges on "+g.table, fmt.Sprintf("GRANT %s ON %s TO '%s'@'%%'", g.privs, qualifiedIdent(d.table(g.table)), d.appUser))
|
||||
}
|
||||
for _, grant := range opts.webuiGrants {
|
||||
exec("grant application privileges on the webui database", fmt.Sprintf("GRANT %s ON `%s`.* TO '%s'@'%%'", grant, d.webui, d.appUser))
|
||||
}
|
||||
if !opts.noRecords {
|
||||
exec("grant dns read privileges", fmt.Sprintf("GRANT SELECT ON `%s`.`%srecords` TO '%s'@'%%'", d.name, d.prefix, d.dnsUser))
|
||||
@@ -198,7 +240,7 @@ func TestIntegrationSetupErrorRedactsSQL(t *testing.T) {
|
||||
}
|
||||
|
||||
func (d *itDatabase) env() map[string]string {
|
||||
return map[string]string{
|
||||
env := map[string]string{
|
||||
"DB_HOST": d.server.host,
|
||||
"DB_PORT": strconv.Itoa(d.server.port),
|
||||
"DB_USER": d.appUser,
|
||||
@@ -207,6 +249,13 @@ func (d *itDatabase) env() map[string]string {
|
||||
"DB_TABLE_PREFIX": d.prefix,
|
||||
"LOG_LEVEL": "ERROR",
|
||||
}
|
||||
if d.webui != d.name {
|
||||
env["DB_WEBUI_NAME"] = d.webui
|
||||
}
|
||||
if d.webuiPrefix != d.prefix {
|
||||
env["DB_WEBUI_TABLE_PREFIX"] = d.webuiPrefix
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
func (d *itDatabase) config(t *testing.T) Config {
|
||||
@@ -221,13 +270,34 @@ func (d *itDatabase) config(t *testing.T) Config {
|
||||
|
||||
func (d *itDatabase) tables(t *testing.T) tableNames {
|
||||
t.Helper()
|
||||
tn, err := newTableNames(d.prefix)
|
||||
tn, err := d.tableNames()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return tn
|
||||
}
|
||||
|
||||
func (d *itDatabase) tableNames() (tableNames, error) {
|
||||
return newTableNames(tableLayout{recordsSchema: d.name, recordsPrefix: d.prefix, webuiSchema: d.webui, webuiPrefix: d.webuiPrefix})
|
||||
}
|
||||
|
||||
func (d *itDatabase) migrations(t *testing.T) []migration {
|
||||
t.Helper()
|
||||
ms, err := loadMigrations(migrationFiles, d.webui, d.webuiPrefix)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
|
||||
func (d *itDatabase) sql(query string) string {
|
||||
tn, err := d.tableNames()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return tn.sql(query)
|
||||
}
|
||||
|
||||
func (d *itDatabase) openApp(t *testing.T) *sql.DB {
|
||||
t.Helper()
|
||||
db, err := openDatabase(d.config(t), discardLogger())
|
||||
@@ -262,7 +332,7 @@ func (d *itDatabase) migrated(t *testing.T) (*sql.DB, tableNames) {
|
||||
func (d *itDatabase) count(t *testing.T, query string, args ...any) int {
|
||||
t.Helper()
|
||||
var n int
|
||||
if err := d.root.QueryRow(query, args...).Scan(&n); err != nil {
|
||||
if err := d.root.QueryRow(d.sql(query), args...).Scan(&n); err != nil {
|
||||
t.Fatalf("%s: %v", query, err)
|
||||
}
|
||||
return n
|
||||
@@ -270,7 +340,7 @@ func (d *itDatabase) count(t *testing.T, query string, args ...any) int {
|
||||
|
||||
func (d *itDatabase) rootExec(t *testing.T, query string, args ...any) sql.Result {
|
||||
t.Helper()
|
||||
res, err := d.root.Exec(query, args...)
|
||||
res, err := d.root.Exec(d.sql(query), args...)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", query, err)
|
||||
}
|
||||
|
||||
@@ -470,7 +470,7 @@ func TestIntegrationUserCreateAuditRollback(t *testing.T) {
|
||||
it := newITHTTP(t)
|
||||
admin := it.createUser(t, "admin", roleAdmin)
|
||||
tn := it.server.tables
|
||||
it.database.rootExec(t, tn.sql("CREATE TRIGGER fail_create_audit BEFORE INSERT ON {audit} FOR EACH ROW "+
|
||||
it.database.rootExec(t, tn.sql("CREATE TRIGGER "+qualifiedIdent(it.database.webui, "fail_create_audit")+" BEFORE INSERT ON {audit} FOR EACH ROW "+
|
||||
"BEGIN IF NEW.operation = 'user_create' AND NEW.status = 201 THEN "+
|
||||
"SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'forced success audit failure'; END IF; END"))
|
||||
response := it.do(t.Context(), webRequest{method: "POST", path: apiPrefix + "/users", token: it.token(t, admin),
|
||||
|
||||
@@ -63,7 +63,7 @@ func TestIntegrationRecordStore(t *testing.T) {
|
||||
}
|
||||
ids[key] = id
|
||||
}
|
||||
d.rootExec(t, "INSERT INTO `coredns_records` (`zone`, `name`, `ttl`, `content`, `record_type`) VALUES ('a.org.', 'broken', NULL, NULL, 'soa')")
|
||||
d.rootExec(t, "INSERT INTO {records} (`zone`, `name`, `ttl`, `content`, `record_type`) VALUES ('a.org.', 'broken', NULL, NULL, 'soa')")
|
||||
zones, err := s.ListZones(ctx)
|
||||
if err != nil || len(zones) != 2 {
|
||||
t.Fatal(zones, err)
|
||||
@@ -361,7 +361,7 @@ func TestIntegrationSessionStore(t *testing.T) {
|
||||
if n, err := s.DeleteUserSessions(ctx, u.ID); n != 1 || err != nil {
|
||||
t.Fatal(n, err)
|
||||
}
|
||||
if d.count(t, "SELECT COUNT(*) FROM `coredns_webui_sessions`") != 1 {
|
||||
if d.count(t, "SELECT COUNT(*) FROM {sessions}") != 1 {
|
||||
t.Fatal("unexpected sessions left")
|
||||
}
|
||||
}
|
||||
@@ -434,10 +434,10 @@ func TestIntegrationDelegationStore(t *testing.T) {
|
||||
if err != nil || len(deleted) != 3 || deleted[0].Username != "admin" || deleted[1].Username != "bob" || deleted[2].Username != "dave" || deleted[1].CreatedBy != admin.ID {
|
||||
t.Fatalf("%+v %v", deleted, err)
|
||||
}
|
||||
if d.count(t, "SELECT COUNT(*) FROM `coredns_webui_zone_delegations` WHERE `zone` = 'a.org.'") != 0 {
|
||||
if d.count(t, "SELECT COUNT(*) FROM {delegations} WHERE `zone` = 'a.org.'") != 0 {
|
||||
t.Fatal("delegations left")
|
||||
}
|
||||
if d.count(t, "SELECT COUNT(*) FROM `coredns_webui_zone_delegations`") != 1 {
|
||||
if d.count(t, "SELECT COUNT(*) FROM {delegations}") != 1 {
|
||||
t.Fatal("other zone delegations deleted")
|
||||
}
|
||||
if rows, err := s.DeleteZoneDelegations(ctx, "a.org."); rows != nil || err != nil {
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
// Copyright (C) 2026 Bryan Joshua Pedini
|
||||
|
||||
//go:build integration
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func itTablesIn(t *testing.T, d *itDatabase, schema string) []string {
|
||||
t.Helper()
|
||||
rows, err := d.root.Query("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME", schema)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var names []string
|
||||
for rows.Next() {
|
||||
var name string
|
||||
if err := rows.Scan(&name); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
names = append(names, name)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
func TestIntegrationSeparateWebUIDatabaseRestrictedGrants(t *testing.T) {
|
||||
t.Parallel()
|
||||
webuiPrefix := ""
|
||||
opts := itOptions{prefix: "coredns_", layout: itLayoutSeparate, webuiPrefix: &webuiPrefix, webuiGrants: []string{"ALL PRIVILEGES"}}
|
||||
it := newITZoneAPIWith(t, opts)
|
||||
d := it.db
|
||||
if d.webui == d.name {
|
||||
t.Fatal("the test database does not use a separate webui schema")
|
||||
}
|
||||
if got := itTablesIn(t, d, d.name); !slices.Equal(got, []string{"coredns_records"}) {
|
||||
t.Fatalf("records database tables = %v", got)
|
||||
}
|
||||
want := []string{"webui_audit", "webui_locks", "webui_schema", "webui_sessions", "webui_users", "webui_zone_delegations"}
|
||||
if got := itTablesIn(t, d, d.webui); !slices.Equal(got, want) {
|
||||
t.Fatalf("webui database tables = %v", got)
|
||||
}
|
||||
|
||||
it.call(t, it.admin, "zone_create", "", "", zoneAPITestCreate, 201)
|
||||
it.grant(t, zoneAPITestName)
|
||||
it.call(t, it.user, "record_create", "", "", zoneAPITestRecord, 201)
|
||||
it.audit(t, "zone_create", 1)
|
||||
it.audit(t, "record_create", 1)
|
||||
if n := d.count(t, "SELECT COUNT(*) FROM {records} WHERE `zone` = ?", zoneAPITestName); n != 4 {
|
||||
t.Fatalf("records in the zone = %d", n)
|
||||
}
|
||||
if n := d.count(t, "SELECT COUNT(*) FROM {locks} WHERE `name` = ?", it.server.tables.zoneLockName(zoneAPITestName)); n != 1 {
|
||||
t.Fatalf("zone lock rows = %d", n)
|
||||
}
|
||||
|
||||
ctx := t.Context()
|
||||
app := d.openApp(t)
|
||||
denied := []string{
|
||||
"CREATE TABLE `" + d.name + "`.`coredns_webui_users` (`id` INT)",
|
||||
"CREATE TABLE `" + d.name + "`.`intruder` (`id` INT)",
|
||||
"ALTER TABLE {records} ADD COLUMN `x` INT",
|
||||
"DROP TABLE {records}",
|
||||
}
|
||||
for _, q := range denied {
|
||||
if _, err := app.ExecContext(ctx, d.sql(q)); mysqlErrNumber(err) != 1142 {
|
||||
t.Errorf("%s: %v", q, err)
|
||||
}
|
||||
}
|
||||
if got := itTablesIn(t, d, d.name); !slices.Equal(got, []string{"coredns_records"}) {
|
||||
t.Fatalf("records database tables after the denied statements = %v", got)
|
||||
}
|
||||
|
||||
tn := it.server.tables
|
||||
forced := errors.New("forced failure after both schemas were written")
|
||||
err := runZoneTx(ctx, app, tn, zoneAPITestName, discardLogger(), func(tx *sql.Tx) error {
|
||||
id, err := newRecordStore(tx, tn).InsertRecord(ctx, recordRow{Zone: zoneAPITestName, Name: "rollback", TTL: sql.NullInt64{Int64: 60, Valid: true}, Content: sql.NullString{String: `{"ip":"192.0.2.9"}`, Valid: true}, RecordType: "A"})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := newAuditStore(tx, tn).InsertAudit(ctx, auditEntry{Time: time.Now(), Actor: "alice", Origin: "local", Operation: opRecordCreate, Zone: sql.NullString{String: zoneAPITestName, Valid: true}, RecordID: sql.NullInt64{Int64: id, Valid: true}}); err != nil {
|
||||
return err
|
||||
}
|
||||
return forced
|
||||
})
|
||||
if !errors.Is(err, forced) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if d.count(t, "SELECT COUNT(*) FROM {records} WHERE `name` = 'rollback'") != 0 {
|
||||
t.Fatal("the record survived the rolled back transaction")
|
||||
}
|
||||
it.audit(t, "record_create", 1)
|
||||
|
||||
cli := d.cli(t, "a-long-password\n", time.Date(2026, 11, 21, 9, 0, 0, 0, time.UTC))
|
||||
if code := cli.run("user", "add", "carol", "admin"); code != 0 {
|
||||
t.Fatalf("%d %q", code, cli.stderr.String())
|
||||
}
|
||||
cli = d.cli(t, "", time.Now())
|
||||
if code := cli.run("check", zoneAPITestName); code != 0 {
|
||||
t.Fatalf("%d %q %q", code, cli.stdout.String(), cli.stderr.String())
|
||||
}
|
||||
if n := d.count(t, "SELECT COUNT(*) FROM {users} WHERE `username` = 'carol'"); n != 1 {
|
||||
t.Fatalf("carol rows = %d", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationSeparateWebUIDatabaseMissing(t *testing.T) {
|
||||
t.Parallel()
|
||||
d := newITDatabase(t, itOptions{prefix: "coredns_", layout: itLayoutSeparate})
|
||||
d.rootExec(t, "DROP DATABASE `"+d.webui+"`")
|
||||
db := d.openApp(t)
|
||||
err := pingDatabase(context.Background(), db, backoff{maxWait: 0, attemptTimeout: 5 * time.Second, now: time.Now}, discardLogger())
|
||||
if !errors.Is(err, errDatabase) || !strings.Contains(err.Error(), d.webui) {
|
||||
t.Fatalf("missing webui database: %v", err)
|
||||
}
|
||||
if got := itTablesIn(t, d, d.name); !slices.Equal(got, []string{"coredns_records"}) {
|
||||
t.Fatalf("records database tables = %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationSharedLayoutKeepsTablesTogether(t *testing.T) {
|
||||
t.Parallel()
|
||||
d := newITDatabase(t, itOptions{prefix: "coredns_", layout: itLayoutShared})
|
||||
cli := d.cli(t, "a-long-password\n", time.Now())
|
||||
if code := cli.run("user", "add", "alice", "admin"); code != 0 {
|
||||
t.Fatalf("%d %q", code, cli.stderr.String())
|
||||
}
|
||||
if _, ok := d.env()["DB_WEBUI_NAME"]; ok {
|
||||
t.Fatal("the shared layout sets DB_WEBUI_NAME")
|
||||
}
|
||||
want := []string{"coredns_records", "coredns_webui_audit", "coredns_webui_locks", "coredns_webui_schema", "coredns_webui_sessions", "coredns_webui_users", "coredns_webui_zone_delegations"}
|
||||
if got := itTablesIn(t, d, d.name); !slices.Equal(got, want) {
|
||||
t.Fatalf("tables = %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationMoveWebUITables(t *testing.T) {
|
||||
t.Parallel()
|
||||
it := newITZoneAPIWith(t, itOptions{prefix: "coredns_", layout: itLayoutShared})
|
||||
d := it.db
|
||||
it.call(t, it.admin, "zone_create", "", "", zoneAPITestCreate, 201)
|
||||
it.grant(t, zoneAPITestName)
|
||||
it.call(t, it.user, "record_create", "", "", zoneAPITestRecord, 201)
|
||||
|
||||
target := d.name + "_webui"
|
||||
d.rootExec(t, "CREATE DATABASE "+quoteIdent(target)+" DEFAULT CHARSET = utf8mb4")
|
||||
t.Cleanup(func() { _, _ = d.root.Exec("DROP DATABASE " + quoteIdent(target)) })
|
||||
account := "'" + d.appUser + "'@'%'"
|
||||
var moves []string
|
||||
for _, suffix := range []string{"webui_schema", "webui_locks", "webui_users", "webui_sessions", "webui_zone_delegations", "webui_audit"} {
|
||||
table := d.prefix + suffix
|
||||
moves = append(moves, qualifiedIdent(d.name, table)+" TO "+qualifiedIdent(target, table))
|
||||
}
|
||||
d.rootExec(t, "RENAME TABLE "+strings.Join(moves, ", "))
|
||||
for _, g := range itAppGrants {
|
||||
if g.table == "records" {
|
||||
continue
|
||||
}
|
||||
table := d.prefix + g.table
|
||||
d.rootExec(t, "GRANT "+g.privs+" ON "+qualifiedIdent(target, table)+" TO "+account)
|
||||
d.rootExec(t, "REVOKE "+g.privs+" ON "+qualifiedIdent(d.name, table)+" FROM "+account)
|
||||
}
|
||||
if tables := itTablesIn(t, d, d.name); !slices.Equal(tables, []string{"coredns_records"}) {
|
||||
t.Fatalf("records database tables = %v", tables)
|
||||
}
|
||||
moved := *d
|
||||
moved.webui = target
|
||||
cli := moved.cli(t, "", time.Now())
|
||||
if code := cli.run("check", zoneAPITestName); code != 0 {
|
||||
t.Fatalf("%d %q %q", code, cli.stdout.String(), cli.stderr.String())
|
||||
}
|
||||
if n := moved.count(t, "SELECT COUNT(*) FROM {audit} WHERE `operation` = 'record_create'"); n != 1 {
|
||||
t.Fatalf("record audit rows after moving the tables = %d", n)
|
||||
}
|
||||
if n := moved.count(t, "SELECT COUNT(*) FROM {delegations} WHERE `zone` = ?", zoneAPITestName); n != 1 {
|
||||
t.Fatalf("delegations after moving the tables = %d", n)
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,12 @@ type itZoneAPI struct {
|
||||
|
||||
func newITZoneAPI(t *testing.T) itZoneAPI {
|
||||
t.Helper()
|
||||
d := newITDatabase(t, itOptions{prefix: "zones_"})
|
||||
return newITZoneAPIWith(t, itOptions{prefix: "zones_"})
|
||||
}
|
||||
|
||||
func newITZoneAPIWith(t *testing.T, opts itOptions) itZoneAPI {
|
||||
t.Helper()
|
||||
d := newITDatabase(t, opts)
|
||||
db, tables := d.migrated(t)
|
||||
users := newUserStore(db, tables)
|
||||
admin, err := users.CreateUser(t.Context(), "alice", "admin", "test", modelNow)
|
||||
@@ -544,7 +549,7 @@ func TestIntegrationZoneAPIAuditRollback(t *testing.T) {
|
||||
it := newITZoneAPI(t)
|
||||
it.call(t, it.admin, "zone_create", "", "", zoneAPITestCreate, 201)
|
||||
tn := it.server.tables
|
||||
it.db.rootExec(t, tn.sql("CREATE TRIGGER fail_zone_audit BEFORE INSERT ON {audit} FOR EACH ROW "+
|
||||
it.db.rootExec(t, tn.sql("CREATE TRIGGER "+qualifiedIdent(it.db.webui, "fail_zone_audit")+" BEFORE INSERT ON {audit} FOR EACH ROW "+
|
||||
"BEGIN IF NEW.operation = 'record_create' AND EXISTS (SELECT 1 FROM {records} WHERE name = 'new') "+
|
||||
"THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'forced audit failure'; END IF; END"))
|
||||
c := it.request(it.admin, "record_create", "", "", zoneAPITestRecord)
|
||||
@@ -558,7 +563,7 @@ func TestIntegrationZoneAPIAuditRollback(t *testing.T) {
|
||||
}
|
||||
it.audit(t, "record_create", 0)
|
||||
it.serial(t, newSOASerial(modelNow))
|
||||
it.db.rootExec(t, "DROP TRIGGER fail_zone_audit")
|
||||
it.db.rootExec(t, "DROP TRIGGER "+qualifiedIdent(it.db.webui, "fail_zone_audit"))
|
||||
it.call(t, it.admin, "record_create", "", "", zoneAPITestRecord, 201)
|
||||
}
|
||||
|
||||
|
||||
+4
-4
@@ -858,9 +858,9 @@ func TestDelegationGrantCommitsWithZoneLock(t *testing.T) {
|
||||
fdbRule{"webui_locks", fdbResponse{rowsAffected: 1}},
|
||||
fdbRule{"x.`token_hash` = ?", fdbResponse{rows: [][]driver.Value{session}}},
|
||||
fdbRule{"ORDER BY u.`id` FOR UPDATE", fdbResponse{rows: [][]driver.Value{userValues(1, "admin", roleAdmin)}}},
|
||||
fdbRule{"SELECT 1 FROM `coredns_records`", fdbResponse{rows: fdbRow(int64(1))}},
|
||||
fdbRule{"SELECT 1 FROM `coredns`.`coredns_records`", fdbResponse{rows: fdbRow(int64(1))}},
|
||||
fdbRule{"u.`username` = CAST(? AS BINARY) FOR UPDATE", fdbResponse{rows: [][]driver.Value{userValues(2, "bob", roleUser)}}},
|
||||
fdbRule{"INSERT INTO `coredns_webui_audit`", fdbResponse{lastInsertID: 1, rowsAffected: 1}},
|
||||
fdbRule{"INSERT INTO `webui`.`coredns_webui_audit`", fdbResponse{lastInsertID: 1, rowsAffected: 1}},
|
||||
))
|
||||
var logs bytes.Buffer
|
||||
s := newWebServer(Config{CookieSecure: true, SessionIdleTimeout: time.Hour, SessionMaxAge: 12 * time.Hour}, newLogger(&logs, slog.LevelDebug), db, fdbTables(t), func() time.Time { return webNow })
|
||||
@@ -875,12 +875,12 @@ func TestDelegationGrantCommitsWithZoneLock(t *testing.T) {
|
||||
var audits, grants int
|
||||
for _, c := range st.Calls() {
|
||||
switch {
|
||||
case strings.HasPrefix(c.query, "INSERT INTO `coredns_webui_audit`"):
|
||||
case strings.HasPrefix(c.query, "INSERT INTO `webui`.`coredns_webui_audit`"):
|
||||
audits++
|
||||
if c.args[4] != opDelegationGrant || c.args[5] != int64(204) || c.args[6] != nil {
|
||||
t.Fatalf("audit row %v", c.args)
|
||||
}
|
||||
case strings.HasPrefix(c.query, "INSERT INTO `coredns_webui_zone_delegations`"):
|
||||
case strings.HasPrefix(c.query, "INSERT INTO `webui`.`coredns_webui_zone_delegations`"):
|
||||
grants++
|
||||
}
|
||||
}
|
||||
|
||||
+25
-14
@@ -21,7 +21,10 @@ import (
|
||||
//go:embed migrations/*.sql
|
||||
var migrationFiles embed.FS
|
||||
|
||||
const migrationPrefixPlaceholder = "{prefix}"
|
||||
const (
|
||||
migrationPrefixPlaceholder = "{prefix}"
|
||||
migrationDatabasePlaceholder = "{database}"
|
||||
)
|
||||
|
||||
type migration struct {
|
||||
version int
|
||||
@@ -29,10 +32,14 @@ type migration struct {
|
||||
statements []string
|
||||
}
|
||||
|
||||
func loadMigrations(fsys fs.FS, prefix string) ([]migration, error) {
|
||||
func loadMigrations(fsys fs.FS, database, prefix string) ([]migration, error) {
|
||||
if !validTablePrefix(prefix) {
|
||||
return nil, errors.New("invalid table prefix")
|
||||
}
|
||||
if !validDBIdentifier(database) {
|
||||
return nil, errors.New("invalid database name")
|
||||
}
|
||||
placeholders := strings.NewReplacer(migrationPrefixPlaceholder, prefix, migrationDatabasePlaceholder, quoteIdent(database))
|
||||
entries, err := fs.ReadDir(fsys, "migrations")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read migrations: %w", err)
|
||||
@@ -60,10 +67,13 @@ func loadMigrations(fsys fs.FS, prefix string) ([]migration, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read migration %s: %w", name, err)
|
||||
}
|
||||
statements := splitSQLStatements(strings.ReplaceAll(string(content), migrationPrefixPlaceholder, prefix))
|
||||
statements := splitSQLStatements(string(content))
|
||||
if len(statements) == 0 {
|
||||
return nil, fmt.Errorf("migration %s has no statements", name)
|
||||
}
|
||||
for i, statement := range statements {
|
||||
statements[i] = placeholders.Replace(statement)
|
||||
}
|
||||
migrations = append(migrations, migration{version: version, name: name, statements: statements})
|
||||
}
|
||||
sort.Slice(migrations, func(i, j int) bool { return migrations[i].version < migrations[j].version })
|
||||
@@ -109,7 +119,7 @@ const createLockTableSQL = "CREATE TABLE IF NOT EXISTS {locks} (" +
|
||||
"`name` VARBINARY(64) NOT NULL PRIMARY KEY, `generation` TINYINT NOT NULL) ENGINE = InnoDB"
|
||||
|
||||
func migrateDatabase(ctx context.Context, db *sql.DB, t tableNames, log *slog.Logger) error {
|
||||
migrations, err := loadMigrations(migrationFiles, t.prefix)
|
||||
migrations, err := loadMigrations(migrationFiles, t.webuiSchema, t.webuiPrefix)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -210,11 +220,12 @@ var appSchema = []schemaColumn{
|
||||
var appTables = []string{"webui_schema", "webui_users", "webui_sessions", "webui_zone_delegations", "webui_audit"}
|
||||
|
||||
func verifyAppSchema(ctx context.Context, q dbtx, t tableNames, log *slog.Logger) error {
|
||||
args := make([]any, len(appTables))
|
||||
for i, name := range appTables {
|
||||
args[i] = t.prefix + name
|
||||
args := make([]any, 0, len(appTables)+1)
|
||||
args = append(args, t.webuiSchema)
|
||||
for _, name := range appTables {
|
||||
args = append(args, t.webuiPrefix+name)
|
||||
}
|
||||
rows, err := q.QueryContext(ctx, "SELECT TABLE_NAME, COLUMN_NAME, COLUMN_TYPE FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME IN (?, ?, ?, ?, ?)", args...)
|
||||
rows, err := q.QueryContext(ctx, "SELECT TABLE_NAME, COLUMN_NAME, COLUMN_TYPE FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME IN (?, ?, ?, ?, ?)", args...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read application schema: %w", err)
|
||||
}
|
||||
@@ -231,7 +242,7 @@ func verifyAppSchema(ctx context.Context, q dbtx, t tableNames, log *slog.Logger
|
||||
return fmt.Errorf("read application schema: %w", err)
|
||||
}
|
||||
for _, c := range appSchema {
|
||||
table := t.prefix + c.table
|
||||
table := t.webuiPrefix + c.table
|
||||
got, ok := found[strings.ToLower(table)+"."+c.column]
|
||||
if !ok {
|
||||
return fmt.Errorf("application schema: table %s has no column %s", table, c.column)
|
||||
@@ -267,15 +278,15 @@ func appColumnTypeMatches(got, want string) bool {
|
||||
func verifyAppForeignKeys(ctx context.Context, q dbtx, t tableNames) error {
|
||||
var n int
|
||||
err := q.QueryRowContext(ctx, "SELECT COUNT(DISTINCT TABLE_NAME, COLUMN_NAME) FROM information_schema.KEY_COLUMN_USAGE "+
|
||||
"WHERE TABLE_SCHEMA = DATABASE() AND REFERENCED_TABLE_SCHEMA = DATABASE() AND REFERENCED_TABLE_NAME = ? AND REFERENCED_COLUMN_NAME = 'id' "+
|
||||
"WHERE TABLE_SCHEMA = ? AND REFERENCED_TABLE_SCHEMA = ? AND REFERENCED_TABLE_NAME = ? AND REFERENCED_COLUMN_NAME = 'id' "+
|
||||
"AND ((TABLE_NAME = ? AND COLUMN_NAME = 'user_id') OR (TABLE_NAME = ? AND COLUMN_NAME IN ('user_id', 'created_by')) "+
|
||||
"OR (TABLE_NAME = ? AND COLUMN_NAME IN ('user_id', 'target_user_id')))",
|
||||
t.prefix+"webui_users", t.prefix+"webui_sessions", t.prefix+"webui_zone_delegations", t.prefix+"webui_audit").Scan(&n)
|
||||
t.webuiSchema, t.webuiSchema, t.webuiPrefix+"webui_users", t.webuiPrefix+"webui_sessions", t.webuiPrefix+"webui_zone_delegations", t.webuiPrefix+"webui_audit").Scan(&n)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read application foreign keys: %w", err)
|
||||
}
|
||||
if n != 5 {
|
||||
return fmt.Errorf("application schema: expected 5 foreign keys to %swebui_users.id, found %d", t.prefix, n)
|
||||
return fmt.Errorf("application schema: expected 5 foreign keys to %swebui_users.id, found %d", t.webuiPrefix, n)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -283,8 +294,8 @@ func verifyAppForeignKeys(ctx context.Context, q dbtx, t tableNames) error {
|
||||
func schemaVersion(ctx context.Context, q dbtx, t tableNames) (int, error) {
|
||||
var count int
|
||||
if err := q.QueryRowContext(ctx,
|
||||
"SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?",
|
||||
t.prefix+"webui_schema").Scan(&count); err != nil {
|
||||
"SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?",
|
||||
t.webuiSchema, t.webuiPrefix+"webui_schema").Scan(&count); err != nil {
|
||||
return 0, fmt.Errorf("read schema version: %w", err)
|
||||
}
|
||||
if count == 0 {
|
||||
|
||||
+10
-10
@@ -1,14 +1,14 @@
|
||||
-- SPDX-License-Identifier: GPL-2.0-or-later
|
||||
-- Copyright (C) 2026 Bryan Joshua Pedini
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `{prefix}webui_schema` (
|
||||
CREATE TABLE IF NOT EXISTS {database}.`{prefix}webui_schema` (
|
||||
`id` TINYINT NOT NULL,
|
||||
`version` INT NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
CHECK (`id` = 1)
|
||||
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `{prefix}webui_users` (
|
||||
CREATE TABLE IF NOT EXISTS {database}.`{prefix}webui_users` (
|
||||
`id` INT NOT NULL AUTO_INCREMENT,
|
||||
`username` VARCHAR(64) COLLATE utf8mb4_bin NOT NULL,
|
||||
`role` VARCHAR(8) NOT NULL,
|
||||
@@ -22,7 +22,7 @@ CREATE TABLE IF NOT EXISTS `{prefix}webui_users` (
|
||||
CHECK (`role` IN ('admin', 'user'))
|
||||
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `{prefix}webui_sessions` (
|
||||
CREATE TABLE IF NOT EXISTS {database}.`{prefix}webui_sessions` (
|
||||
`token_hash` BINARY(32) NOT NULL,
|
||||
`user_id` INT NOT NULL,
|
||||
`created_at` DATETIME(6) NOT NULL,
|
||||
@@ -33,21 +33,21 @@ CREATE TABLE IF NOT EXISTS `{prefix}webui_sessions` (
|
||||
PRIMARY KEY (`token_hash`),
|
||||
KEY `user_id` (`user_id`),
|
||||
KEY `expires_at` (`expires_at`),
|
||||
FOREIGN KEY (`user_id`) REFERENCES `{prefix}webui_users` (`id`)
|
||||
FOREIGN KEY (`user_id`) REFERENCES {database}.`{prefix}webui_users` (`id`)
|
||||
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `{prefix}webui_zone_delegations` (
|
||||
CREATE TABLE IF NOT EXISTS {database}.`{prefix}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 `{prefix}webui_users` (`id`),
|
||||
FOREIGN KEY (`created_by`) REFERENCES `{prefix}webui_users` (`id`)
|
||||
FOREIGN KEY (`user_id`) REFERENCES {database}.`{prefix}webui_users` (`id`),
|
||||
FOREIGN KEY (`created_by`) REFERENCES {database}.`{prefix}webui_users` (`id`)
|
||||
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `{prefix}webui_audit` (
|
||||
CREATE TABLE IF NOT EXISTS {database}.`{prefix}webui_audit` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT,
|
||||
`time` DATETIME(6) NOT NULL,
|
||||
`user_id` INT NULL,
|
||||
@@ -66,6 +66,6 @@ CREATE TABLE IF NOT EXISTS `{prefix}webui_audit` (
|
||||
KEY `zone_time` (`zone`, `time`),
|
||||
KEY `user_time` (`user_id`, `time`),
|
||||
KEY `operation_time` (`operation`, `time`),
|
||||
FOREIGN KEY (`user_id`) REFERENCES `{prefix}webui_users` (`id`),
|
||||
FOREIGN KEY (`target_user_id`) REFERENCES `{prefix}webui_users` (`id`)
|
||||
FOREIGN KEY (`user_id`) REFERENCES {database}.`{prefix}webui_users` (`id`),
|
||||
FOREIGN KEY (`target_user_id`) REFERENCES {database}.`{prefix}webui_users` (`id`)
|
||||
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
|
||||
@@ -1,4 +1,4 @@
|
||||
-- SPDX-License-Identifier: GPL-2.0-or-later
|
||||
-- Copyright (C) 2026 Bryan Joshua Pedini
|
||||
|
||||
ALTER TABLE `{prefix}webui_audit` MODIFY COLUMN `record_id` BIGINT NULL;
|
||||
ALTER TABLE {database}.`{prefix}webui_audit` MODIFY COLUMN `record_id` BIGINT NULL;
|
||||
+34
-21
@@ -16,7 +16,7 @@ import (
|
||||
)
|
||||
|
||||
func TestLoadEmbeddedMigrations(t *testing.T) {
|
||||
ms, err := loadMigrations(migrationFiles, "dns_")
|
||||
ms, err := loadMigrations(migrationFiles, "dns-ui", "dns_")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -24,12 +24,12 @@ func TestLoadEmbeddedMigrations(t *testing.T) {
|
||||
t.Fatalf("got %+v", ms)
|
||||
}
|
||||
if ms[1].version != 2 || ms[1].name != "002_wide_audit_record_id.sql" || !reflect.DeepEqual(ms[1].statements,
|
||||
[]string{"ALTER TABLE `dns_webui_audit` MODIFY COLUMN `record_id` BIGINT NULL"}) {
|
||||
[]string{"ALTER TABLE `dns-ui`.`dns_webui_audit` MODIFY COLUMN `record_id` BIGINT NULL"}) {
|
||||
t.Fatalf("got %+v", ms[1])
|
||||
}
|
||||
wantTables := []string{"`dns_webui_schema`", "`dns_webui_users`", "`dns_webui_sessions`", "`dns_webui_zone_delegations`", "`dns_webui_audit`"}
|
||||
wantTables := []string{"`dns-ui`.`dns_webui_schema`", "`dns-ui`.`dns_webui_users`", "`dns-ui`.`dns_webui_sessions`", "`dns-ui`.`dns_webui_zone_delegations`", "`dns-ui`.`dns_webui_audit`"}
|
||||
for i, stmt := range ms[0].statements {
|
||||
if strings.Contains(stmt, "{prefix}") || strings.Contains(stmt, "coredns_") || strings.Contains(stmt, "--") {
|
||||
if strings.Contains(stmt, "{prefix}") || strings.Contains(stmt, "{database}") || strings.Contains(stmt, "coredns_") || strings.Contains(stmt, "--") {
|
||||
t.Fatalf("statement %d not substituted: %s", i, stmt)
|
||||
}
|
||||
if !strings.Contains(stmt, "CREATE TABLE") || !strings.Contains(stmt, wantTables[i]) {
|
||||
@@ -39,25 +39,34 @@ func TestLoadEmbeddedMigrations(t *testing.T) {
|
||||
t.Fatalf("statement %d: %s", i, stmt)
|
||||
}
|
||||
}
|
||||
if !strings.HasPrefix(ms[0].statements[0], "CREATE TABLE IF NOT EXISTS `dns_webui_schema`") {
|
||||
if !strings.HasPrefix(ms[0].statements[0], "CREATE TABLE IF NOT EXISTS `dns-ui`.`dns_webui_schema`") {
|
||||
t.Fatal(ms[0].statements[0])
|
||||
}
|
||||
if !strings.Contains(ms[0].statements[2], "REFERENCES `dns_webui_users` (`id`)") {
|
||||
if !strings.Contains(ms[0].statements[2], "REFERENCES `dns-ui`.`dns_webui_users` (`id`)") {
|
||||
t.Fatal(ms[0].statements[2])
|
||||
}
|
||||
if _, err := loadMigrations(migrationFiles, "bad-prefix"); err == nil {
|
||||
if _, err := loadMigrations(migrationFiles, "dns-ui", "bad-prefix"); err == nil {
|
||||
t.Fatal("invalid prefix accepted")
|
||||
}
|
||||
for _, name := range []string{"", "bad\nname", strings.Repeat("d", 65)} {
|
||||
if _, err := loadMigrations(migrationFiles, name, "dns_"); err == nil {
|
||||
t.Fatalf("invalid database name %q accepted", name)
|
||||
}
|
||||
}
|
||||
legacy, err := loadMigrations(migrationFiles, "legacy; `dns", "dns_")
|
||||
if err != nil || len(legacy[0].statements) != 5 || !strings.Contains(legacy[0].statements[0], "`legacy; ``dns`.`dns_webui_schema`") {
|
||||
t.Fatalf("legacy migrations: %+v %v", legacy, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadMigrationsFS(t *testing.T) {
|
||||
good := fstest.MapFS{
|
||||
"migrations/002_second.sql": {Data: []byte("CREATE TABLE `{prefix}b` (a INT);")},
|
||||
"migrations/002_second.sql": {Data: []byte("CREATE TABLE {database}.`{prefix}b` (a INT);")},
|
||||
"migrations/001_first.sql": {Data: []byte("-- header\nCREATE TABLE `{prefix}a` (a INT);\nINSERT INTO `{prefix}a` VALUES (1)")},
|
||||
"migrations/README.txt": {Data: []byte("ignored")},
|
||||
"migrations/sub/003_x.sql": {Data: []byte("ignored")},
|
||||
}
|
||||
ms, err := loadMigrations(good, "p_")
|
||||
ms, err := loadMigrations(good, "db", "p_")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -67,6 +76,9 @@ func TestLoadMigrationsFS(t *testing.T) {
|
||||
if !reflect.DeepEqual(ms[0].statements, []string{"CREATE TABLE `p_a` (a INT)", "INSERT INTO `p_a` VALUES (1)"}) {
|
||||
t.Fatalf("statements %q", ms[0].statements)
|
||||
}
|
||||
if !reflect.DeepEqual(ms[1].statements, []string{"CREATE TABLE `db`.`p_b` (a INT)"}) {
|
||||
t.Fatalf("statements %q", ms[1].statements)
|
||||
}
|
||||
bad := []fstest.MapFS{
|
||||
{"migrations/initial.sql": {Data: []byte("SELECT 1;")}},
|
||||
{"migrations/x1_initial.sql": {Data: []byte("SELECT 1;")}},
|
||||
@@ -78,7 +90,7 @@ func TestLoadMigrationsFS(t *testing.T) {
|
||||
{"other/001_a.sql": {Data: []byte("SELECT 1;")}},
|
||||
}
|
||||
for i, fsys := range bad {
|
||||
if _, err := loadMigrations(fsys, "p_"); err == nil {
|
||||
if _, err := loadMigrations(fsys, "db", "p_"); err == nil {
|
||||
t.Errorf("case %d accepted", i)
|
||||
}
|
||||
}
|
||||
@@ -119,13 +131,14 @@ func appSchemaRows(prefix string, change func(rows [][]driver.Value) [][]driver.
|
||||
}
|
||||
|
||||
func (m *migrationDB) handler(q string, args []any) fdbResponse {
|
||||
q = strings.ReplaceAll(q, "`coredns`.`coredns_webui_", "`webui`.`coredns_webui_")
|
||||
if m.failOn != "" && strings.Contains(q, m.failOn) {
|
||||
return fdbResponse{err: m.failErr}
|
||||
}
|
||||
switch {
|
||||
case strings.HasPrefix(q, "INSERT IGNORE INTO `coredns_webui_locks`"):
|
||||
case strings.HasPrefix(q, "INSERT IGNORE INTO `webui`.`coredns_webui_locks`"):
|
||||
return fdbResponse{rowsAffected: 1}
|
||||
case strings.HasPrefix(q, "SELECT `name` FROM `coredns_webui_locks`"):
|
||||
case strings.HasPrefix(q, "SELECT `name` FROM `webui`.`coredns_webui_locks`"):
|
||||
return fdbResponse{rows: fdbRow(args[0])}
|
||||
case strings.Contains(q, "information_schema.TABLES"):
|
||||
return fdbResponse{rows: fdbRow(m.tableCount)}
|
||||
@@ -137,9 +150,9 @@ func (m *migrationDB) handler(q string, args []any) fdbResponse {
|
||||
case strings.HasPrefix(q, "UPDATE"):
|
||||
m.versionWrite = append(m.versionWrite, "update", args[0])
|
||||
return fdbResponse{rowsAffected: m.updateRows}
|
||||
case strings.HasPrefix(q, "SELECT COUNT(*) FROM `coredns_webui_schema`"):
|
||||
case strings.HasPrefix(q, "SELECT COUNT(*) FROM `webui`.`coredns_webui_schema`"):
|
||||
return fdbResponse{rows: fdbRow(m.existsCount)}
|
||||
case strings.HasPrefix(q, "INSERT INTO `coredns_webui_schema`"):
|
||||
case strings.HasPrefix(q, "INSERT INTO `webui`.`coredns_webui_schema`"):
|
||||
m.versionWrite = append(m.versionWrite, "insert", args[0])
|
||||
m.updateRows = 1
|
||||
return fdbResponse{}
|
||||
@@ -207,7 +220,7 @@ func TestSetSchemaVersion(t *testing.T) {
|
||||
func TestApplyMigrations(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
tn := fdbTables(t)
|
||||
ms, err := loadMigrations(migrationFiles, "coredns_")
|
||||
ms, err := loadMigrations(migrationFiles, "webui", "coredns_")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -252,7 +265,7 @@ func TestApplyMigrations(t *testing.T) {
|
||||
t.Fatalf("got %v %v", err, m.versionWrite)
|
||||
}
|
||||
|
||||
for _, fail := range []string{"information_schema", "INSERT INTO `coredns_webui_schema`"} {
|
||||
for _, fail := range []string{"information_schema", "INSERT INTO `webui`.`coredns_webui_schema`"} {
|
||||
m = &migrationDB{tableCount: 0, failOn: fail, failErr: errors.New("x")}
|
||||
db, _ = newFakeDB(t, m.handler)
|
||||
if err := applyMigrations(ctx, db, tn, ms, discardLogger()); err == nil {
|
||||
@@ -269,13 +282,13 @@ func TestMigrateDatabase(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
calls := st.Calls()
|
||||
if !strings.HasPrefix(calls[0].query, "INSERT IGNORE INTO `coredns_webui_locks`") || calls[0].args[0] != "coredns_webui_migrate" {
|
||||
if !strings.HasPrefix(calls[0].query, "INSERT IGNORE INTO `webui`.`coredns_webui_locks`") || calls[0].args[0] != "coredns_webui_migrate" {
|
||||
t.Fatalf("initial call %+v", calls[0])
|
||||
}
|
||||
if !strings.HasSuffix(calls[1].query, "FOR UPDATE") || calls[1].args[0] != "coredns_webui_migrate" || st.commits != 1 {
|
||||
t.Fatalf("guard call %+v, commits %d", calls[1], st.commits)
|
||||
}
|
||||
bad := tableNames{prefix: "bad-prefix"}
|
||||
bad := tableNames{webuiSchema: "webui", webuiPrefix: "bad-prefix"}
|
||||
if err := migrateDatabase(ctx, db, bad, discardLogger()); err == nil {
|
||||
t.Fatal("invalid prefix accepted")
|
||||
}
|
||||
@@ -285,7 +298,7 @@ func TestMigrationBootstrapRetriesDeadlock(t *testing.T) {
|
||||
m := &migrationDB{tableCount: 0}
|
||||
seeds := 0
|
||||
db, state := newFakeDB(t, func(q string, args []any) fdbResponse {
|
||||
if strings.HasPrefix(q, "INSERT IGNORE INTO `coredns_webui_locks`") {
|
||||
if strings.HasPrefix(q, "INSERT IGNORE INTO `webui`.`coredns_webui_locks`") {
|
||||
seeds++
|
||||
switch seeds {
|
||||
case 1:
|
||||
@@ -317,10 +330,10 @@ func TestVerifyAppSchema(t *testing.T) {
|
||||
verify = c
|
||||
}
|
||||
}
|
||||
if len(verify.args) != 5 || verify.args[0] != "coredns_webui_schema" || verify.args[4] != "coredns_webui_audit" {
|
||||
if len(verify.args) != 6 || verify.args[0] != "webui" || verify.args[1] != "coredns_webui_schema" || verify.args[5] != "coredns_webui_audit" {
|
||||
t.Fatalf("%+v", verify)
|
||||
}
|
||||
all, err := loadMigrations(migrationFiles, "coredns_")
|
||||
all, err := loadMigrations(migrationFiles, "webui", "coredns_")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
+21
-5
@@ -9,6 +9,7 @@ IT_ID=${IT_ID:-$$}
|
||||
IT_NAME=${IT_NAME:-cdwu-it-${IT_ID}}
|
||||
MYSQL_IMAGE=${MYSQL_IMAGE:-mysql:8.4}
|
||||
IT_GALERA=${IT_GALERA:-0}
|
||||
IT_WEBUI_LAYOUTS=${IT_WEBUI_LAYOUTS:-shared separate}
|
||||
network="$IT_NAME"
|
||||
mysql="${IT_NAME}-mysql"
|
||||
mysql_data="${IT_NAME}-data"
|
||||
@@ -18,12 +19,12 @@ image="${IT_NAME}:integration"
|
||||
require_free_docker_name network "$network"
|
||||
require_free_docker_name container "$mysql"
|
||||
require_free_docker_name volume "$mysql_data"
|
||||
require_free_docker_name container "$tests"
|
||||
require_free_docker_name image "$image"
|
||||
|
||||
network_id=
|
||||
mysql_id=
|
||||
tests_id=
|
||||
tests_ids=
|
||||
volume=
|
||||
tmp=$(mktemp -d)
|
||||
owner=${tmp##*/}
|
||||
@@ -35,7 +36,7 @@ cleanup() {
|
||||
if [ "$status" -ne 0 ] && [ -n "$mysql_id" ]; then
|
||||
docker logs --tail 80 "$mysql_id" >&2 2>&1 || true
|
||||
fi
|
||||
for container in "$tests_id" "$mysql_id"; do
|
||||
for container in $tests_ids "$mysql_id"; do
|
||||
if [ -n "$container" ]; then
|
||||
docker rm --force --volumes "$container" >/dev/null 2>&1 || true
|
||||
fi
|
||||
@@ -65,9 +66,21 @@ fi
|
||||
network_id=$(docker network create --internal "$network")
|
||||
require_free_docker_name image "$image"
|
||||
docker build --target integration --file dockerfile --tag "$image" --iidfile "$tmp/image-id" .
|
||||
tests_id=$(docker create --name "$tests" --network "$network_id" \
|
||||
--env IT_GALERA="$IT_GALERA" --env IT_MYSQL_HOST=mysql --env IT_MYSQL_PORT=3306 --env IT_MYSQL_ROOT_PASSWORD="$root_password" \
|
||||
for layout in $IT_WEBUI_LAYOUTS; do
|
||||
case "$layout" in
|
||||
shared|separate) ;;
|
||||
*)
|
||||
echo "unknown IT_WEBUI_LAYOUTS entry: $layout" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
require_free_docker_name container "${tests}-${layout}"
|
||||
tests_id=$(docker create --name "${tests}-${layout}" --network "$network_id" \
|
||||
--env IT_GALERA="$IT_GALERA" --env IT_WEBUI_LAYOUT="$layout" \
|
||||
--env IT_MYSQL_HOST=mysql --env IT_MYSQL_PORT=3306 --env IT_MYSQL_ROOT_PASSWORD="$root_password" \
|
||||
"$(cat "$tmp/image-id")")
|
||||
tests_ids="$tests_ids $tests_id"
|
||||
done
|
||||
set --
|
||||
if [ "$IT_GALERA" = 1 ]; then
|
||||
set -- --wsrep-on=ON --wsrep-provider=/usr/lib/galera/libgalera_smm.so \
|
||||
@@ -89,4 +102,7 @@ until docker exec --env MYSQL_PWD="$root_password" "$mysql_id" sh -c '
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
docker start --attach "$tests_id"
|
||||
for tests_id in $tests_ids; do
|
||||
echo "running $(docker inspect --format '{{.Name}}' "$tests_id")"
|
||||
docker start --attach "$tests_id"
|
||||
done
|
||||
+15
-15
@@ -75,12 +75,12 @@ func TestRecordStoreZones(t *testing.T) {
|
||||
t.Fatalf("got %+v", zones)
|
||||
}
|
||||
c := onlyCall(t, st)
|
||||
expectQuery(t, c, "FROM `coredns_records` r", "GROUP BY `zone_key`", "ORDER BY k.`zone_key`", "CAST(s.`record_type` AS BINARY) = 'SOA'")
|
||||
expectQuery(t, c, "FROM `coredns`.`coredns_records` r", "GROUP BY `zone_key`", "ORDER BY k.`zone_key`", "CAST(s.`record_type` AS BINARY) = 'SOA'")
|
||||
if _, err := s.ListZonesOfUser(ctx, 7); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c = st.Calls()[1]
|
||||
expectQuery(t, c, "`coredns_webui_zone_delegations` d WHERE d.`user_id` = ?")
|
||||
expectQuery(t, c, "`webui`.`coredns_webui_zone_delegations` d WHERE d.`user_id` = ?")
|
||||
expectArgs(t, c, int64(7))
|
||||
|
||||
fs := newRecordStore(failingDB(t), fdbTables(t))
|
||||
@@ -173,12 +173,12 @@ func TestRecordStoreWrites(t *testing.T) {
|
||||
if err != nil || id != 42 {
|
||||
t.Fatal(id, err)
|
||||
}
|
||||
expectQuery(t, st.Calls()[0], "INSERT INTO `coredns_records` (`zone`, `name`, `ttl`, `content`, `record_type`)")
|
||||
expectQuery(t, st.Calls()[0], "INSERT INTO `coredns`.`coredns_records` (`zone`, `name`, `ttl`, `content`, `record_type`)")
|
||||
expectArgs(t, st.Calls()[0], "a.org.", "www", int64(60), "{}", "A")
|
||||
if err := s.UpdateRecord(ctx, r); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expectQuery(t, st.Calls()[1], "UPDATE `coredns_records` SET", "WHERE `id` = ?")
|
||||
expectQuery(t, st.Calls()[1], "UPDATE `coredns`.`coredns_records` SET", "WHERE `id` = ?")
|
||||
expectArgs(t, st.Calls()[1], "a.org.", "www", int64(60), "{}", "A", int64(5))
|
||||
if ok, err := s.DeleteRecord(ctx, 5); err != nil || !ok {
|
||||
t.Fatal(ok, err)
|
||||
@@ -187,7 +187,7 @@ func TestRecordStoreWrites(t *testing.T) {
|
||||
if n, err := s.DeleteZoneRecords(ctx, "a.org."); err != nil || n != 3 {
|
||||
t.Fatal(n, err)
|
||||
}
|
||||
expectQuery(t, st.Calls()[3], "DELETE FROM `coredns_records`"+zoneRowsWhere)
|
||||
expectQuery(t, st.Calls()[3], "DELETE FROM `coredns`.`coredns_records`"+zoneRowsWhere)
|
||||
db, _ = newFakeDB(t, func(string, []any) fdbResponse { return fdbResponse{rowsAffected: 0} })
|
||||
if ok, err := newRecordStore(db, fdbTables(t)).DeleteRecord(ctx, 5); ok || err != nil {
|
||||
t.Fatal(ok, err)
|
||||
@@ -228,7 +228,7 @@ func TestUserStoreCreate(t *testing.T) {
|
||||
if u.ID != 9 || u.Username != "alice" || u.Role != "admin" || u.PasswordHash != "$hash" || !u.CreatedAt.Equal(created) || !u.UpdatedAt.Equal(created) {
|
||||
t.Fatalf("got %+v", u)
|
||||
}
|
||||
expectQuery(t, st.Calls()[0], "INSERT INTO `coredns_webui_users`")
|
||||
expectQuery(t, st.Calls()[0], "INSERT INTO `webui`.`coredns_webui_users`")
|
||||
expectArgs(t, st.Calls()[0], "alice", "admin", "$hash", created, created)
|
||||
db, _ = newFakeDB(t, func(string, []any) fdbResponse { return fdbResponse{err: &mysql.MySQLError{Number: 1062}} })
|
||||
if _, err := newUserStore(db, fdbTables(t)).CreateUser(ctx, "alice", "admin", "$hash", storeTime); !errors.Is(err, errUsernameTaken) {
|
||||
@@ -261,7 +261,7 @@ func TestUserStoreLookups(t *testing.T) {
|
||||
if err != nil || u.ID != 3 || u.Username != "bob" || !u.DeletedAt.Valid || u.LastLoginAt.Valid || u.CreatedAt.Location() != time.UTC {
|
||||
t.Fatalf("%d: %+v %v", i, u, err)
|
||||
}
|
||||
expectQuery(t, st.Calls()[i], c.fragment, "FROM `coredns_webui_users` u")
|
||||
expectQuery(t, st.Calls()[i], c.fragment, "FROM `webui`.`coredns_webui_users` u")
|
||||
expectArgs(t, st.Calls()[i], c.arg)
|
||||
}
|
||||
db, _ = newFakeDB(t, nil)
|
||||
@@ -292,7 +292,7 @@ func TestUserStoreLists(t *testing.T) {
|
||||
if strings.Contains(st.Calls()[0].query, "deleted_at` IS NULL") {
|
||||
t.Fatal("all users filtered")
|
||||
}
|
||||
expectQuery(t, st.Calls()[0], "FROM `coredns_webui_zone_delegations` d WHERE d.`user_id` = u.`id`", "ORDER BY u.`username`")
|
||||
expectQuery(t, st.Calls()[0], "FROM `webui`.`coredns_webui_zone_delegations` d WHERE d.`user_id` = u.`id`", "ORDER BY u.`username`")
|
||||
if _, err := s.ListUsers(ctx, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -405,13 +405,13 @@ func TestSessionStore(t *testing.T) {
|
||||
if err := s.CreateSession(ctx, row); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expectQuery(t, st.Calls()[0], "INSERT INTO `coredns_webui_sessions`")
|
||||
expectQuery(t, st.Calls()[0], "INSERT INTO `webui`.`coredns_webui_sessions`")
|
||||
expectArgs(t, st.Calls()[0], []byte("hash-32"), int64(5), ts, ts, ts.Add(time.Hour), "192.0.2.7", "agent")
|
||||
got, err := s.SessionByTokenHash(ctx, []byte("hash-32"))
|
||||
if err != nil || got.User.Username != "carol" || got.Session.UserID != 5 || string(got.Session.TokenHash) != "hash-32" || got.Session.UserAgent != "agent" || got.Session.ExpiresAt.Location() != time.UTC {
|
||||
t.Fatalf("%+v %v", got, err)
|
||||
}
|
||||
expectQuery(t, st.Calls()[1], "JOIN `coredns_webui_users` u ON u.`id` = x.`user_id` WHERE x.`token_hash` = ?")
|
||||
expectQuery(t, st.Calls()[1], "JOIN `webui`.`coredns_webui_users` u ON u.`id` = x.`user_id` WHERE x.`token_hash` = ?")
|
||||
if err := s.TouchSession(ctx, []byte("h"), storeTime); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -477,7 +477,7 @@ func TestDelegationStore(t *testing.T) {
|
||||
if ok, err := s.GrantDelegation(ctx, "a.org.", 5, 1, storeTime); !ok || err != nil {
|
||||
t.Fatal(ok, err)
|
||||
}
|
||||
expectQuery(t, st.Calls()[0], "INSERT INTO `coredns_webui_zone_delegations`")
|
||||
expectQuery(t, st.Calls()[0], "INSERT INTO `webui`.`coredns_webui_zone_delegations`")
|
||||
expectArgs(t, st.Calls()[0], "a.org.", int64(5), ts, int64(1))
|
||||
if ok, err := s.RevokeDelegation(ctx, "a.org.", 5); !ok || err != nil {
|
||||
t.Fatal(ok, err)
|
||||
@@ -492,13 +492,13 @@ func TestDelegationStore(t *testing.T) {
|
||||
if err != nil || len(zones) != 2 || !zones[0].ZoneExists || zones[1].ZoneExists || zones[1].Zone != "gone.org." {
|
||||
t.Fatal(zones, err)
|
||||
}
|
||||
expectQuery(t, st.Calls()[3], "EXISTS (SELECT 1 FROM `coredns_records` r WHERE "+recordZoneKey("r.`zone`")+" = CAST(d.`zone` AS BINARY))")
|
||||
expectQuery(t, st.Calls()[3], "EXISTS (SELECT 1 FROM `coredns`.`coredns_records` r WHERE "+recordZoneKey("r.`zone`")+" = CAST(d.`zone` AS BINARY))")
|
||||
deleted, err := s.DeleteZoneDelegations(ctx, "a.org.")
|
||||
if err != nil || len(deleted) != 1 || deleted[0].Username != "carol" || deleted[0].CreatedBy != 1 {
|
||||
t.Fatal(deleted, err)
|
||||
}
|
||||
expectQuery(t, st.Calls()[4], "ORDER BY username FOR UPDATE")
|
||||
expectQuery(t, st.Calls()[5], "DELETE FROM `coredns_webui_zone_delegations` WHERE `zone` = CAST(? AS BINARY)")
|
||||
expectQuery(t, st.Calls()[5], "DELETE FROM `webui`.`coredns_webui_zone_delegations` WHERE `zone` = CAST(? AS BINARY)")
|
||||
if ok, err := s.HasDelegation(ctx, "a.org.", 5); !ok || err != nil {
|
||||
t.Fatal(ok, err)
|
||||
}
|
||||
@@ -594,7 +594,7 @@ func TestAuditStoreInsert(t *testing.T) {
|
||||
t.Fatal(id, err)
|
||||
}
|
||||
c := st.Calls()[0]
|
||||
expectQuery(t, c, "INSERT INTO `coredns_webui_audit`")
|
||||
expectQuery(t, c, "INSERT INTO `webui`.`coredns_webui_audit`")
|
||||
if c.args[0] != storeTime.Truncate(time.Microsecond) || c.args[2] != strings.Repeat("é", 64) || c.args[4] != "login" ||
|
||||
c.args[6] != strings.Repeat("x", 255) || c.args[10] != `{"a":1}` || c.args[11] != nil {
|
||||
t.Fatalf("args %#v", c.args)
|
||||
@@ -660,7 +660,7 @@ func TestAuditStoreLists(t *testing.T) {
|
||||
t.Fatalf("%+v %v", rows, err)
|
||||
}
|
||||
c := st.Calls()[0]
|
||||
expectQuery(t, c, "LEFT JOIN `coredns_webui_users` tu", "WHERE a.`zone` = CAST(? AS BINARY) ORDER BY a.`id` DESC LIMIT ?")
|
||||
expectQuery(t, c, "LEFT JOIN `webui`.`coredns_webui_users` tu", "WHERE a.`zone` = CAST(? AS BINARY) ORDER BY a.`id` DESC LIMIT ?")
|
||||
expectArgs(t, c, "a.org.", int64(50))
|
||||
latest, err := s.LatestAudit(ctx, 3)
|
||||
if err != nil || len(latest) != 3 || latest[0].ID != 1 || latest[2].ID != 3 {
|
||||
|
||||
+2
-1
@@ -33,7 +33,8 @@ func logConfig(ctx context.Context, log *slog.Logger, cfg Config) {
|
||||
}
|
||||
log.DebugContext(ctx, "configuration loaded",
|
||||
"db_host", cfg.DBHost, "db_port", cfg.DBPort, "db_user", cfg.DBUser, "db_name", cfg.DBName,
|
||||
"db_tls", cfg.DBTLS, "db_table_prefix", cfg.DBTablePrefix, "http_addr", cfg.HTTPAddr, "http_port", cfg.HTTPPort,
|
||||
"db_tls", cfg.DBTLS, "db_table_prefix", cfg.DBTablePrefix,
|
||||
"db_webui_name", cfg.DBWebUIName, "db_webui_table_prefix", cfg.DBWebUIPrefix, "http_addr", cfg.HTTPAddr, "http_port", cfg.HTTPPort,
|
||||
"log_level", logLevelName(cfg.LogLevel), "app_name", cfg.AppName, "cookie_secure", cfg.CookieSecure,
|
||||
"session_idle_timeout", cfg.SessionIdleTimeout, "session_max_age", cfg.SessionMaxAge,
|
||||
"trusted_proxies", strings.Join(proxies, ","))
|
||||
|
||||
@@ -307,7 +307,7 @@ func TestLogConfigOmitsSecrets(t *testing.T) {
|
||||
func serverDBHandler(columns [][]driver.Value) fdbHandler {
|
||||
m := &migrationDB{tableCount: 1, version: int64(2)}
|
||||
return func(q string, args []any) fdbResponse {
|
||||
if strings.Contains(q, "information_schema.COLUMNS") && args[0] == "coredns_records" {
|
||||
if strings.Contains(q, "information_schema.COLUMNS") && len(args) == 2 && args[1] == "coredns_records" {
|
||||
return fdbResponse{rows: columns}
|
||||
}
|
||||
return m.handler(q, args)
|
||||
@@ -394,7 +394,7 @@ func TestConnectDatabase(t *testing.T) {
|
||||
h.a.openDB = func(Config, *slog.Logger) (*sql.DB, error) { return db, nil }
|
||||
h.a.pingBackoff = defaultPingBackoff()
|
||||
got, tn, err := h.a.connectDatabase(ctx, cfg, discardLogger())
|
||||
if err != nil || got != db || tn.records != "`coredns_records`" {
|
||||
if err != nil || got != db || tn.records != "`coredns`.`coredns_records`" {
|
||||
t.Fatal(got, tn, err)
|
||||
}
|
||||
|
||||
@@ -428,7 +428,7 @@ func TestConnectDatabase(t *testing.T) {
|
||||
}
|
||||
|
||||
newer, _ := newFakeDB(t, func(q string, args []any) fdbResponse {
|
||||
if strings.Contains(q, "information_schema.COLUMNS") && args[0] == "coredns_records" {
|
||||
if strings.Contains(q, "information_schema.COLUMNS") && len(args) == 2 && args[1] == "coredns_records" {
|
||||
return fdbResponse{rows: validContractRows}
|
||||
}
|
||||
m := &migrationDB{tableCount: 1, version: int64(99)}
|
||||
|
||||
Reference in new issue
Block a user