fix: support utf8mb4 across MySQL and MariaDB
This commit is contained in:
1 parent
cce17c5fa4
commit
d34894c9cd
28 files changed
+221
-118
No files matched your search
@@ -29,7 +29,10 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
set -eu
|
set -eu
|
||||||
docker build --pull --target test --output type=cacheonly -f dockerfile .
|
docker build --pull --target test --output type=cacheonly -f dockerfile .
|
||||||
IT_ID="${GITHUB_RUN_ID}" scripts/integration.sh
|
for database in mysql:5.7 mysql:8.4 mariadb:10.11; do
|
||||||
|
echo "Running integration tests against $database"
|
||||||
|
MYSQL_IMAGE="$database" IT_ID="${GITHUB_RUN_ID}" scripts/integration.sh
|
||||||
|
done
|
||||||
- name: Build and test image
|
- name: Build and test image
|
||||||
id: build
|
id: build
|
||||||
env:
|
env:
|
||||||
|
|||||||
@@ -22,10 +22,13 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
set -eu
|
set -eu
|
||||||
docker build --pull --target test --output type=cacheonly -f dockerfile .
|
docker build --pull --target test --output type=cacheonly -f dockerfile .
|
||||||
- name: Integration tests against MySQL
|
- name: Integration tests against MySQL and MariaDB
|
||||||
run: |
|
run: |
|
||||||
set -eu
|
set -eu
|
||||||
IT_ID="${GITHUB_RUN_ID}" scripts/integration.sh
|
for database in mysql:5.7 mysql:8.4 mariadb:10.11; do
|
||||||
|
echo "Running integration tests against $database"
|
||||||
|
MYSQL_IMAGE="$database" IT_ID="${GITHUB_RUN_ID}" scripts/integration.sh
|
||||||
|
done
|
||||||
- name: Image and end-to-end tests
|
- name: Image and end-to-end tests
|
||||||
run: |
|
run: |
|
||||||
set -eu
|
set -eu
|
||||||
|
|||||||
@@ -83,7 +83,7 @@ CREATE TABLE `coredns_records` (
|
|||||||
`content` TEXT,
|
`content` TEXT,
|
||||||
`record_type` VARCHAR(255) NOT NULL,
|
`record_type` VARCHAR(255) NOT NULL,
|
||||||
PRIMARY KEY (`id`)
|
PRIMARY KEY (`id`)
|
||||||
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci;
|
) 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 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.
|
||||||
@@ -149,7 +149,7 @@ Configuration comes from environment variables only. No configuration file is re
|
|||||||
|
|
||||||
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. A missing required variable, an empty value, an invalid port, address, duration, boolean, CIDR, log level or TLS mode, or a table prefix not matching `^[A-Za-z0-9_]{0,32}$` produces a message naming the variable (never its value for `DB_PASSWORD`) and exit code `2`.
|
||||||
|
|
||||||
The connection is built with `mysql.Config` from `github.com/go-sql-driver/mysql`, never by string concatenation: `Net=tcp`, `ParseTime=true`, `Loc=UTC`, collation `utf8mb4_0900_ai_ci`, 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.
|
The connection is built with `mysql.Config` from `github.com/go-sql-driver/mysql`, never by string concatenation: `Net=tcp`, `ParseTime=true`, `Loc=UTC`, charset `utf8mb4` via `SET NAMES`, connect timeout 5 s, read and write timeouts 30 s, `MultiStatements=false`, `InterpolateParams=false`, TLS from `DB_TLS`. The pool uses the plugin's defaults: at most 10 open and 10 idle connections, connection lifetime 1 minute. The DSN and the password are never logged; logs carry host, port, user and database only.
|
||||||
|
|
||||||
## 5. Process and command behavior
|
## 5. Process and command behavior
|
||||||
|
|
||||||
@@ -219,11 +219,11 @@ CREATE TABLE IF NOT EXISTS `coredns_webui_schema` (
|
|||||||
`version` INT NOT NULL,
|
`version` INT NOT NULL,
|
||||||
PRIMARY KEY (`id`),
|
PRIMARY KEY (`id`),
|
||||||
CHECK (`id` = 1)
|
CHECK (`id` = 1)
|
||||||
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci;
|
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
|
||||||
|
|
||||||
CREATE TABLE `coredns_webui_users` (
|
CREATE TABLE `coredns_webui_users` (
|
||||||
`id` INT NOT NULL AUTO_INCREMENT,
|
`id` INT NOT NULL AUTO_INCREMENT,
|
||||||
`username` VARCHAR(64) NOT NULL,
|
`username` VARCHAR(64) COLLATE utf8mb4_bin NOT NULL,
|
||||||
`role` VARCHAR(8) NOT NULL,
|
`role` VARCHAR(8) NOT NULL,
|
||||||
`password_hash` VARCHAR(255) NOT NULL,
|
`password_hash` VARCHAR(255) NOT NULL,
|
||||||
`created_at` DATETIME(6) NOT NULL,
|
`created_at` DATETIME(6) NOT NULL,
|
||||||
@@ -233,7 +233,7 @@ CREATE TABLE `coredns_webui_users` (
|
|||||||
PRIMARY KEY (`id`),
|
PRIMARY KEY (`id`),
|
||||||
UNIQUE KEY `username` (`username`),
|
UNIQUE KEY `username` (`username`),
|
||||||
CHECK (`role` IN ('admin', 'user'))
|
CHECK (`role` IN ('admin', 'user'))
|
||||||
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci;
|
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
|
||||||
|
|
||||||
CREATE TABLE `coredns_webui_sessions` (
|
CREATE TABLE `coredns_webui_sessions` (
|
||||||
`token_hash` BINARY(32) NOT NULL,
|
`token_hash` BINARY(32) NOT NULL,
|
||||||
@@ -247,10 +247,10 @@ CREATE TABLE `coredns_webui_sessions` (
|
|||||||
KEY `user_id` (`user_id`),
|
KEY `user_id` (`user_id`),
|
||||||
KEY `expires_at` (`expires_at`),
|
KEY `expires_at` (`expires_at`),
|
||||||
FOREIGN KEY (`user_id`) REFERENCES `coredns_webui_users` (`id`)
|
FOREIGN KEY (`user_id`) REFERENCES `coredns_webui_users` (`id`)
|
||||||
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci;
|
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
|
||||||
|
|
||||||
CREATE TABLE `coredns_webui_zone_delegations` (
|
CREATE TABLE `coredns_webui_zone_delegations` (
|
||||||
`zone` VARCHAR(255) NOT NULL,
|
`zone` VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,
|
||||||
`user_id` INT NOT NULL,
|
`user_id` INT NOT NULL,
|
||||||
`created_at` DATETIME(6) NOT NULL,
|
`created_at` DATETIME(6) NOT NULL,
|
||||||
`created_by` INT NOT NULL,
|
`created_by` INT NOT NULL,
|
||||||
@@ -258,7 +258,7 @@ CREATE TABLE `coredns_webui_zone_delegations` (
|
|||||||
KEY `user_id` (`user_id`),
|
KEY `user_id` (`user_id`),
|
||||||
FOREIGN KEY (`user_id`) REFERENCES `coredns_webui_users` (`id`),
|
FOREIGN KEY (`user_id`) REFERENCES `coredns_webui_users` (`id`),
|
||||||
FOREIGN KEY (`created_by`) REFERENCES `coredns_webui_users` (`id`)
|
FOREIGN KEY (`created_by`) REFERENCES `coredns_webui_users` (`id`)
|
||||||
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci;
|
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
|
||||||
|
|
||||||
CREATE TABLE `coredns_webui_audit` (
|
CREATE TABLE `coredns_webui_audit` (
|
||||||
`id` BIGINT NOT NULL AUTO_INCREMENT,
|
`id` BIGINT NOT NULL AUTO_INCREMENT,
|
||||||
@@ -272,8 +272,8 @@ CREATE TABLE `coredns_webui_audit` (
|
|||||||
`zone` VARCHAR(255) NULL,
|
`zone` VARCHAR(255) NULL,
|
||||||
`record_id` BIGINT NULL,
|
`record_id` BIGINT NULL,
|
||||||
`target_user_id` INT NULL,
|
`target_user_id` INT NULL,
|
||||||
`before_value` JSON NULL,
|
`before_value` LONGTEXT NULL,
|
||||||
`after_value` JSON NULL,
|
`after_value` LONGTEXT NULL,
|
||||||
PRIMARY KEY (`id`),
|
PRIMARY KEY (`id`),
|
||||||
KEY `time` (`time`),
|
KEY `time` (`time`),
|
||||||
KEY `zone_time` (`zone`, `time`),
|
KEY `zone_time` (`zone`, `time`),
|
||||||
@@ -281,7 +281,7 @@ CREATE TABLE `coredns_webui_audit` (
|
|||||||
KEY `operation_time` (`operation`, `time`),
|
KEY `operation_time` (`operation`, `time`),
|
||||||
FOREIGN KEY (`user_id`) REFERENCES `coredns_webui_users` (`id`),
|
FOREIGN KEY (`user_id`) REFERENCES `coredns_webui_users` (`id`),
|
||||||
FOREIGN KEY (`target_user_id`) REFERENCES `coredns_webui_users` (`id`)
|
FOREIGN KEY (`target_user_id`) REFERENCES `coredns_webui_users` (`id`)
|
||||||
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci;
|
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
|
||||||
```
|
```
|
||||||
|
|
||||||
All times are UTC. Rows of `<prefix>webui_users` are never deleted (section 8), so, as with the tokens referenced by the audit table of `dpsapi`, the foreign keys from sessions, delegations and audit rows always resolve. Audit rows have no foreign key to the records table, so deleted records keep their history. The audit `record_id` column holds the full ID range of an `INT UNSIGNED` records table.
|
All times are UTC. Rows of `<prefix>webui_users` are never deleted (section 8), so, as with the tokens referenced by the audit table of `dpsapi`, the foreign keys from sessions, delegations and audit rows always resolve. Audit rows have no foreign key to the records table, so deleted records keep their history. The audit `record_id` column holds the full ID range of an `INT UNSIGNED` records table.
|
||||||
@@ -351,7 +351,7 @@ Warnings:
|
|||||||
|
|
||||||
### Concurrency
|
### Concurrency
|
||||||
|
|
||||||
Every write runs on a dedicated connection: take the named lock `<prefix>webui:<first 16 hex chars of sha256(zone)>` with `GET_LOCK` (10 s timeout, HTTP 503 "zone busy" on timeout), begin the transaction, check again that the actor may operate on the zone (the user row and, for role `user`, the delegation row read with `FOR SHARE`, so a concurrent revocation, demotion or deletion waits for the write or wins before it), read the zone's rows, apply the rules, write records, SOA serial and audit row, commit, release the lock. The lock serializes writers of this application; other writers of the table are detected through ETags.
|
Every write runs on a dedicated connection: take the named lock `<prefix>webui:<first 16 hex chars of sha256(zone)>` with `GET_LOCK` (10 s timeout, HTTP 503 "zone busy" on timeout), begin the transaction, check again that the actor may operate on the zone (the user row and, for role `user`, the delegation row read with `LOCK IN SHARE MODE`, so a concurrent revocation, demotion or deletion waits for the write or wins before it), read the zone's rows, apply the rules, write records, SOA serial and audit row, commit, release the lock. The lock serializes writers of this application; other writers of the table are detected through ETags.
|
||||||
|
|
||||||
Every record carries an ETag: the hex SHA-256 of `id`, `zone`, `name`, `ttl`, `record_type` and the raw `content`, with explicit markers for `NULL`. Updates and deletes require `If-Match`; inside the transaction the row is read with `SELECT ... FOR UPDATE` and compared. A missing `If-Match` is HTTP 428, a mismatch or a missing row is HTTP 412 and the UI offers to reload.
|
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.
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# coredns-web-ui
|
# coredns-web-ui
|
||||||
|
|
||||||
A web application, shipped as a container image, to manage the DNS zones and records that CoreDNS serves through the `mysql` plugin (`github.com/cloud66-oss/coredns_mysql`, built into `git.bjphoster.com/docker/coredns-mysql`). It reads and writes the plugin's records table in MySQL directly. CoreDNS reads the same table. The application never talks to CoreDNS, never edits the Corefile and never starts, stops or reloads CoreDNS.
|
A web application, shipped as a container image, to manage the DNS zones and records that CoreDNS serves through the `mysql` plugin (`github.com/cloud66-oss/coredns_mysql`, built into `git.bjphoster.com/docker/coredns-mysql`). It reads and writes the plugin's records table in MySQL or MariaDB directly. CoreDNS reads the same table. The application never talks to CoreDNS, never edits the Corefile and never starts, stops or reloads CoreDNS.
|
||||||
|
|
||||||
The same binary starts the HTTP server when run without arguments and provides subcommands for user management, zone checks, audit inspection, health checks, version and help. Configuration comes from environment variables only.
|
The same binary starts the HTTP server when run without arguments and provides subcommands for user management, zone checks, audit inspection, health checks, version and help. Configuration comes from environment variables only.
|
||||||
|
|
||||||
@@ -32,7 +32,7 @@ CREATE TABLE `coredns_records` (
|
|||||||
`content` TEXT,
|
`content` TEXT,
|
||||||
`record_type` VARCHAR(255) NOT NULL,
|
`record_type` VARCHAR(255) NOT NULL,
|
||||||
PRIMARY KEY (`id`)
|
PRIMARY KEY (`id`)
|
||||||
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci;
|
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4;
|
||||||
```
|
```
|
||||||
|
|
||||||
At startup (and before every database CLI command) the application reads `information_schema.COLUMNS` of the configured database and exits with a message naming the table or column when the contract is not met. The contract accepts:
|
At startup (and before every database CLI command) the application reads `information_schema.COLUMNS` of the configured database and exits with a message naming the table or column when the contract is not met. The contract accepts:
|
||||||
@@ -100,7 +100,7 @@ Every write takes a MySQL named lock per zone (`<prefix>webui:<first 16 hex char
|
|||||||
|
|
||||||
Export writes `$ORIGIN`, the SOA first and the other records in UI order, each with an explicit TTL. Rows with check errors are not exported; each produces a `; skipped id=<id>: <code>` line at the end. Import accepts a master file (at most 2 MiB and 10000 records, `$INCLUDE` disabled, class `IN` only, default TTL 3600), previews the diff and applies it in `merge` mode (adds missing records and updates the TTL of matching ones) or `replace` mode (also deletes records that are not in the file). Applying requires the fingerprint returned by the preview and answers `409` when the zone changed in between. The serial of an imported SOA is ignored and the managed serial is bumped.
|
Export writes `$ORIGIN`, the SOA first and the other records in UI order, each with an explicit TTL. Rows with check errors are not exported; each produces a `; skipped id=<id>: <code>` line at the end. Import accepts a master file (at most 2 MiB and 10000 records, `$INCLUDE` disabled, class `IN` only, default TTL 3600), previews the diff and applies it in `merge` mode (adds missing records and updates the TTL of matching ones) or `replace` mode (also deletes records that are not in the file). Applying requires the fingerprint returned by the preview and answers `409` when the zone changed in between. The serial of an imported SOA is ignored and the managed serial is bumped.
|
||||||
|
|
||||||
## MySQL grants
|
## Database grants
|
||||||
|
|
||||||
The application user needs `SELECT`, `INSERT`, `UPDATE` and `DELETE` on the records table, and table-level grants on its own tables, which MySQL allows before the tables exist when `CREATE` is included. This is least privilege (`dev/mysql-init.sql` applies exactly these grants):
|
The application user needs `SELECT`, `INSERT`, `UPDATE` and `DELETE` on the records table, and table-level grants on its own tables, which MySQL allows before the tables exist when `CREATE` is included. This is least privilege (`dev/mysql-init.sql` applies exactly these grants):
|
||||||
|
|
||||||
@@ -143,7 +143,7 @@ Configuration comes only from environment variables. No configuration file is re
|
|||||||
|
|
||||||
| Variable | Required | Default | Accepted values |
|
| Variable | Required | Default | Accepted values |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| `DB_HOST` | yes | none | Host name or IP address of MySQL |
|
| `DB_HOST` | yes | none | Host name or IP address of the database server |
|
||||||
| `DB_PORT` | no | `3306` | Integer from `1` to `65535`, ASCII digits only |
|
| `DB_PORT` | no | `3306` | Integer from `1` to `65535`, ASCII digits only |
|
||||||
| `DB_USER` | yes | none | At most 64 characters, no control characters |
|
| `DB_USER` | yes | none | At most 64 characters, no control characters |
|
||||||
| `DB_PASSWORD` | yes | none | Any non-empty value; never printed in messages |
|
| `DB_PASSWORD` | yes | none | Any non-empty value; never printed in messages |
|
||||||
@@ -161,7 +161,9 @@ Configuration comes only from environment variables. No configuration file is re
|
|||||||
|
|
||||||
Validation happens before any other work. The first problem is reported as `coredns-web-ui: configuration error: <message>` with a message that names the variable and never its value for `DB_PASSWORD`, and the process exits with code `2`. Copy `env.example` for a ready-made set of development values.
|
Validation happens before any other work. The first problem is reported as `coredns-web-ui: configuration error: <message>` with a message that names the variable and never its value for `DB_PASSWORD`, and the process exits with code `2`. Copy `env.example` for a ready-made set of development values.
|
||||||
|
|
||||||
The database connection is built with `mysql.Config` from `github.com/go-sql-driver/mysql` (`ParseTime`, UTC, collation `utf8mb4_0900_ai_ci`, 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 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.
|
||||||
|
|
||||||
|
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 and MariaDB 10.11.
|
||||||
|
|
||||||
`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.
|
`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.
|
||||||
|
|
||||||
@@ -417,7 +419,7 @@ docker run --rm -v "$PWD":/src -w /src -v coredns-web-ui-gomod:/go/pkg/mod -e GO
|
|||||||
|
|
||||||
### Integration tests
|
### Integration tests
|
||||||
|
|
||||||
`scripts/integration.sh` builds the dockerfile's `integration` stage and runs the tests with the build tag `integration` against a disposable MySQL container (`MYSQL_IMAGE`, default `mysql:8.4`) on an internal Docker network with random credentials. Nothing is published on the host. It covers the records table contract, migrations (including two processes migrating at the same time), the least-privilege grants, the foreign keys, the stores and transactions, the zone lock and the races between role, delegation and user changes and writes. It needs only Docker. Containers, network, volume and image are named `cdwu-it-<id>` (`IT_ID`, default the shell's process id) and are removed at exit, also after failures.
|
`scripts/integration.sh` builds the dockerfile's `integration` stage and runs the tests with the build tag `integration` against a disposable MySQL or MariaDB container (`MYSQL_IMAGE`, default `mysql:8.4`) on an internal Docker network with random credentials. Nothing is published on the host. It covers the records table contract, migrations (including two processes migrating at the same time), the least-privilege grants, the foreign keys, the stores and transactions, the zone lock and the races between role, delegation and user changes and writes. Run with `MYSQL_IMAGE=mysql:5.7` or `MYSQL_IMAGE=mariadb:10.11` to use the other databases in CI. It needs only Docker. Containers, network, volume and image are named `cdwu-it-<id>` (`IT_ID`, default the shell's process id) and are removed at exit, also after failures.
|
||||||
|
|
||||||
### Image tests
|
### Image tests
|
||||||
|
|
||||||
|
|||||||
@@ -184,7 +184,7 @@ func (m *matrixSQL) exec(w *matrixWorld, query string, args []any) fdbResponse {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
return fdbResponse{}
|
return fdbResponse{}
|
||||||
case has("SELECT 1 FROM `coredns_webui_zone_delegations` WHERE `zone` = ? AND `user_id` = ?"):
|
case has("SELECT 1 FROM `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 {
|
if _, ok := w.state.delegations[delegationKey{args[0].(string), args[1].(int64)}]; ok {
|
||||||
return fdbResponse{rows: fdbRow(int64(1))}
|
return fdbResponse{rows: fdbRow(int64(1))}
|
||||||
}
|
}
|
||||||
@@ -206,7 +206,7 @@ func (m *matrixSQL) exec(w *matrixWorld, query string, args []any) fdbResponse {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
return fdbResponse{}
|
return fdbResponse{}
|
||||||
case has("FOR UPDATE OF d"):
|
case has("ORDER BY username FOR UPDATE"):
|
||||||
var out []delegationRow
|
var out []delegationRow
|
||||||
for k, d := range w.state.delegations {
|
for k, d := range w.state.delegations {
|
||||||
if k.zone == args[0] {
|
if k.zone == args[0] {
|
||||||
@@ -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})
|
rows = append(rows, []driver.Value{d.Zone, d.UserID, d.Username, d.CreatedAt, d.CreatedBy})
|
||||||
}
|
}
|
||||||
return fdbResponse{rows: rows}
|
return fdbResponse{rows: rows}
|
||||||
case has("DELETE FROM `coredns_webui_zone_delegations` WHERE `zone` = ?"):
|
case has("DELETE FROM `coredns_webui_zone_delegations` WHERE `zone` = CAST(? AS BINARY)"):
|
||||||
var n int64
|
var n int64
|
||||||
for k := range w.state.delegations {
|
for k := range w.state.delegations {
|
||||||
if k.zone == args[0] {
|
if k.zone == args[0] {
|
||||||
|
|||||||
@@ -271,7 +271,7 @@ func matrixRecordCases() []matrixCase {
|
|||||||
{name: "connection failure", op: op, method: method, path: path, persona: "admin", body: body, ifMatch: ifMatch,
|
{name: "connection failure", op: op, method: method, path: path, persona: "admin", body: body, ifMatch: ifMatch,
|
||||||
status: 503, msg: msgDatabaseDown, zone: mxZone, record: record, setup: mxSQLFail(errMatrixNet, "FOR UPDATE"), check: mxUnchanged},
|
status: 503, msg: msgDatabaseDown, zone: mxZone, record: record, setup: mxSQLFail(errMatrixNet, "FOR UPDATE"), check: mxUnchanged},
|
||||||
{name: "store failure", op: op, method: method, path: path, persona: "admin", body: body, ifMatch: ifMatch,
|
{name: "store failure", op: op, method: method, path: path, persona: "admin", body: body, ifMatch: ifMatch,
|
||||||
status: 500, msg: msgInternalError, zone: mxZone, record: record, setup: mxSQLFail(errMatrixInternal, "FOR SHARE"), check: mxUnchanged},
|
status: 500, msg: msgInternalError, zone: mxZone, record: record, setup: mxSQLFail(errMatrixInternal, "LOCK IN SHARE MODE"), check: mxUnchanged},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
zoneRows := []string{"SELECT `id`", zoneRowsWhere}
|
zoneRows := []string{"SELECT `id`", zoneRowsWhere}
|
||||||
|
|||||||
+3
-3
@@ -101,11 +101,11 @@ func auditFilterSQL(f auditFilter) (string, []any, error) {
|
|||||||
var conds []string
|
var conds []string
|
||||||
var args []any
|
var args []any
|
||||||
if f.Zone != "" {
|
if f.Zone != "" {
|
||||||
conds = append(conds, "a.`zone` = ?")
|
conds = append(conds, "a.`zone` = CAST(? AS BINARY)")
|
||||||
args = append(args, f.Zone)
|
args = append(args, f.Zone)
|
||||||
}
|
}
|
||||||
if f.Actor != "" {
|
if f.Actor != "" {
|
||||||
conds = append(conds, "a.`actor` = ?")
|
conds = append(conds, "LOWER(CONVERT(a.`actor` USING utf8mb4) COLLATE utf8mb4_bin) = CAST(LOWER(CONVERT(? USING utf8mb4) COLLATE utf8mb4_bin) AS BINARY)")
|
||||||
args = append(args, f.Actor)
|
args = append(args, f.Actor)
|
||||||
}
|
}
|
||||||
if f.Operation != "" {
|
if f.Operation != "" {
|
||||||
@@ -141,7 +141,7 @@ func auditFilterSQL(f auditFilter) (string, []any, error) {
|
|||||||
args = append(args, f.BeforeID)
|
args = append(args, f.BeforeID)
|
||||||
}
|
}
|
||||||
if f.RestrictToUserID.Valid {
|
if f.RestrictToUserID.Valid {
|
||||||
conds = append(conds, "(a.`user_id` = ? OR a.`zone` IN (SELECT d.`zone` FROM {delegations} d WHERE d.`user_id` = ?))")
|
conds = append(conds, "(a.`user_id` = ? OR CAST(a.`zone` AS BINARY) IN (SELECT CAST(d.`zone` AS BINARY) FROM {delegations} d WHERE d.`user_id` = ?))")
|
||||||
args = append(args, f.RestrictToUserID.Int64, f.RestrictToUserID.Int64)
|
args = append(args, f.RestrictToUserID.Int64, f.RestrictToUserID.Int64)
|
||||||
}
|
}
|
||||||
if len(conds) == 0 {
|
if len(conds) == 0 {
|
||||||
|
|||||||
+1
-2
@@ -22,7 +22,6 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
dbCollation = "utf8mb4_0900_ai_ci"
|
|
||||||
dbConnectTimeout = 5 * time.Second
|
dbConnectTimeout = 5 * time.Second
|
||||||
dbReadTimeout = 30 * time.Second
|
dbReadTimeout = 30 * time.Second
|
||||||
dbWriteTimeout = 30 * time.Second
|
dbWriteTimeout = 30 * time.Second
|
||||||
@@ -118,7 +117,7 @@ func mysqlConfig(cfg Config) *mysql.Config {
|
|||||||
mc.DBName = cfg.DBName
|
mc.DBName = cfg.DBName
|
||||||
mc.ParseTime = true
|
mc.ParseTime = true
|
||||||
mc.Loc = time.UTC
|
mc.Loc = time.UTC
|
||||||
mc.Collation = dbCollation
|
_ = mc.Apply(mysql.Charset("utf8mb4", ""))
|
||||||
mc.Timeout = dbConnectTimeout
|
mc.Timeout = dbConnectTimeout
|
||||||
mc.ReadTimeout = dbReadTimeout
|
mc.ReadTimeout = dbReadTimeout
|
||||||
mc.WriteTimeout = dbWriteTimeout
|
mc.WriteTimeout = dbWriteTimeout
|
||||||
|
|||||||
+2
-2
@@ -77,7 +77,7 @@ func TestMySQLConfig(t *testing.T) {
|
|||||||
}
|
}
|
||||||
mc := mysqlConfig(cfg)
|
mc := mysqlConfig(cfg)
|
||||||
if mc.User != "coredns_webui" || mc.Passwd != "s3cret-Pa55word" || mc.Net != "tcp" || mc.Addr != "db.example.org:3307" ||
|
if mc.User != "coredns_webui" || mc.Passwd != "s3cret-Pa55word" || mc.Net != "tcp" || mc.Addr != "db.example.org:3307" ||
|
||||||
mc.DBName != "coredns" || !mc.ParseTime || mc.Loc != time.UTC || mc.Collation != "utf8mb4_0900_ai_ci" ||
|
mc.DBName != "coredns" || !mc.ParseTime || mc.Loc != time.UTC || mc.Collation != "" || !strings.Contains(mc.FormatDSN(), "charset=utf8mb4") ||
|
||||||
mc.Timeout != 5*time.Second || mc.ReadTimeout != 30*time.Second || mc.WriteTimeout != 30*time.Second ||
|
mc.Timeout != 5*time.Second || mc.ReadTimeout != 30*time.Second || mc.WriteTimeout != 30*time.Second ||
|
||||||
mc.MultiStatements || mc.InterpolateParams || mc.TLSConfig != "preferred" {
|
mc.MultiStatements || mc.InterpolateParams || mc.TLSConfig != "preferred" {
|
||||||
t.Fatalf("unexpected %+v", mc)
|
t.Fatalf("unexpected %+v", mc)
|
||||||
@@ -596,7 +596,7 @@ func TestTraceConnector(t *testing.T) {
|
|||||||
out := logs.String()
|
out := logs.String()
|
||||||
for _, want := range []string{
|
for _, want := range []string{
|
||||||
"level=TRACE", `msg="sql statement"`, "caller=\"userStore.queryUser < userStore.UserByUsername\"",
|
"level=TRACE", `msg="sql statement"`, "caller=\"userStore.queryUser < userStore.UserByUsername\"",
|
||||||
"caller=\"userStore.exec < userStore.SetPassword\"", "caller=\"sessionStore.CreateSession", "WHERE u.`username` = ?",
|
"caller=\"userStore.exec < userStore.SetPassword\"", "caller=\"sessionStore.CreateSession", "WHERE u.`username` = CAST(? AS BINARY)",
|
||||||
"args=[alice]", "[redacted] 2026-11-18 12:00:00 +0000 UTC 7]", "args=\"[[redacted] 7 2026-11-18",
|
"args=[alice]", "[redacted] 2026-11-18 12:00:00 +0000 UTC 7]", "args=\"[[redacted] 7 2026-11-18",
|
||||||
`msg="function entry" func=userStore.UserByUsername`, `msg="function exit" func=userStore.UserByUsername`,
|
`msg="function entry" func=userStore.UserByUsername`, `msg="function exit" func=userStore.UserByUsername`,
|
||||||
`msg="function entry" func=recordStore.UpdateRecord`, `msg="function exit" func=recordStore.UpdateRecord`,
|
`msg="function entry" func=recordStore.UpdateRecord`, `msg="function exit" func=recordStore.UpdateRecord`,
|
||||||
|
|||||||
+9
-7
@@ -50,7 +50,7 @@ func (s delegationStore) GrantDelegation(ctx context.Context, zone string, userI
|
|||||||
|
|
||||||
func (s delegationStore) RevokeDelegation(ctx context.Context, zone string, userID int64) (bool, error) {
|
func (s delegationStore) RevokeDelegation(ctx context.Context, zone string, userID int64) (bool, error) {
|
||||||
defer traceStore(ctx, "delegationStore.RevokeDelegation")()
|
defer traceStore(ctx, "delegationStore.RevokeDelegation")()
|
||||||
res, err := s.q.ExecContext(ctx, s.t.sql("DELETE FROM {delegations} WHERE `zone` = ? AND `user_id` = ?"), zone, userID)
|
res, err := s.q.ExecContext(ctx, s.t.sql("DELETE FROM {delegations} WHERE `zone` = CAST(? AS BINARY) AND `user_id` = ?"), zone, userID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, fmt.Errorf("revoke delegation: %w", err)
|
return false, fmt.Errorf("revoke delegation: %w", err)
|
||||||
}
|
}
|
||||||
@@ -65,7 +65,7 @@ func (s delegationStore) ZoneUsers(ctx context.Context, zone string) ([]userRow,
|
|||||||
defer traceStore(ctx, "delegationStore.ZoneUsers")()
|
defer traceStore(ctx, "delegationStore.ZoneUsers")()
|
||||||
rows, err := s.q.QueryContext(ctx,
|
rows, err := s.q.QueryContext(ctx,
|
||||||
s.t.sql("SELECT "+userColumns+" FROM {delegations} d JOIN {users} u ON u.`id` = d.`user_id` "+
|
s.t.sql("SELECT "+userColumns+" FROM {delegations} d JOIN {users} u ON u.`id` = d.`user_id` "+
|
||||||
"WHERE d.`zone` = ? AND u.`role` = 'user' AND u.`deleted_at` IS NULL ORDER BY u.`username`"), zone)
|
"WHERE d.`zone` = CAST(? AS BINARY) AND u.`role` = 'user' AND u.`deleted_at` IS NULL ORDER BY u.`username`"), zone)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("zone users: %w", err)
|
return nil, fmt.Errorf("zone users: %w", err)
|
||||||
}
|
}
|
||||||
@@ -98,9 +98,11 @@ func (s delegationStore) UserZones(ctx context.Context, userID int64) ([]userZon
|
|||||||
|
|
||||||
func (s delegationStore) DeleteZoneDelegations(ctx context.Context, zone string) ([]delegationRow, error) {
|
func (s delegationStore) DeleteZoneDelegations(ctx context.Context, zone string) ([]delegationRow, error) {
|
||||||
defer traceStore(ctx, "delegationStore.DeleteZoneDelegations")()
|
defer traceStore(ctx, "delegationStore.DeleteZoneDelegations")()
|
||||||
|
// Lock delegations only. Usernames are immutable and the foreign key
|
||||||
|
// keeps the referenced users present.
|
||||||
rows, err := s.q.QueryContext(ctx,
|
rows, err := s.q.QueryContext(ctx,
|
||||||
s.t.sql("SELECT d.`zone`, d.`user_id`, u.`username`, d.`created_at`, d.`created_by` FROM {delegations} d "+
|
s.t.sql("SELECT d.`zone`, d.`user_id`, (SELECT u.`username` FROM {users} u WHERE u.`id` = d.`user_id`) AS username, d.`created_at`, d.`created_by` "+
|
||||||
"JOIN {users} u ON u.`id` = d.`user_id` WHERE d.`zone` = ? ORDER BY u.`username` FOR UPDATE OF d"), zone)
|
"FROM {delegations} d WHERE d.`zone` = CAST(? AS BINARY) ORDER BY username FOR UPDATE"), zone)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("delete zone delegations: %w", err)
|
return nil, fmt.Errorf("delete zone delegations: %w", err)
|
||||||
}
|
}
|
||||||
@@ -122,7 +124,7 @@ func (s delegationStore) DeleteZoneDelegations(ctx context.Context, zone string)
|
|||||||
if len(deleted) == 0 {
|
if len(deleted) == 0 {
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
if _, err := s.q.ExecContext(ctx, s.t.sql("DELETE FROM {delegations} WHERE `zone` = ?"), zone); err != nil {
|
if _, err := s.q.ExecContext(ctx, s.t.sql("DELETE FROM {delegations} WHERE `zone` = CAST(? AS BINARY)"), zone); err != nil {
|
||||||
return nil, fmt.Errorf("delete zone delegations: %w", err)
|
return nil, fmt.Errorf("delete zone delegations: %w", err)
|
||||||
}
|
}
|
||||||
return deleted, nil
|
return deleted, nil
|
||||||
@@ -142,10 +144,10 @@ func (s delegationStore) hasDelegation(ctx context.Context, query, zone string,
|
|||||||
|
|
||||||
func (s delegationStore) HasDelegation(ctx context.Context, zone string, userID int64) (bool, error) {
|
func (s delegationStore) HasDelegation(ctx context.Context, zone string, userID int64) (bool, error) {
|
||||||
defer traceStore(ctx, "delegationStore.HasDelegation")()
|
defer traceStore(ctx, "delegationStore.HasDelegation")()
|
||||||
return s.hasDelegation(ctx, "SELECT 1 FROM {delegations} WHERE `zone` = ? AND `user_id` = ?", zone, userID)
|
return s.hasDelegation(ctx, "SELECT 1 FROM {delegations} WHERE `zone` = CAST(? AS BINARY) AND `user_id` = ?", zone, userID)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s delegationStore) HasDelegationForShare(ctx context.Context, zone string, userID int64) (bool, error) {
|
func (s delegationStore) HasDelegationForShare(ctx context.Context, zone string, userID int64) (bool, error) {
|
||||||
defer traceStore(ctx, "delegationStore.HasDelegationForShare")()
|
defer traceStore(ctx, "delegationStore.HasDelegationForShare")()
|
||||||
return s.hasDelegation(ctx, "SELECT 1 FROM {delegations} WHERE `zone` = ? AND `user_id` = ? FOR SHARE", zone, userID)
|
return s.hasDelegation(ctx, "SELECT 1 FROM {delegations} WHERE `zone` = CAST(? AS BINARY) AND `user_id` = ? LOCK IN SHARE MODE", zone, userID)
|
||||||
}
|
}
|
||||||
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
-- SPDX-License-Identifier: GPL-2.0-or-later
|
-- SPDX-License-Identifier: GPL-2.0-or-later
|
||||||
-- Copyright (C) 2026 Bryan Joshua Pedini
|
-- Copyright (C) 2026 Bryan Joshua Pedini
|
||||||
|
|
||||||
CREATE DATABASE IF NOT EXISTS `coredns` DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci;
|
CREATE DATABASE IF NOT EXISTS `coredns` DEFAULT CHARSET = utf8mb4;
|
||||||
|
|
||||||
USE `coredns`;
|
USE `coredns`;
|
||||||
|
|
||||||
@@ -13,7 +13,7 @@ CREATE TABLE `coredns_records` (
|
|||||||
`content` TEXT,
|
`content` TEXT,
|
||||||
`record_type` VARCHAR(255) NOT NULL,
|
`record_type` VARCHAR(255) NOT NULL,
|
||||||
PRIMARY KEY (`id`)
|
PRIMARY KEY (`id`)
|
||||||
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci;
|
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4;
|
||||||
|
|
||||||
CREATE USER 'coredns'@'%' IDENTIFIED BY 'coredns_dev';
|
CREATE USER 'coredns'@'%' IDENTIFIED BY 'coredns_dev';
|
||||||
GRANT SELECT ON `coredns`.`coredns_records` TO 'coredns'@'%';
|
GRANT SELECT ON `coredns`.`coredns_records` TO 'coredns'@'%';
|
||||||
|
|||||||
+15
-9
@@ -75,7 +75,7 @@ function connectionOptions(database?: string): mysql.ConnectionOptions {
|
|||||||
dateStrings: true,
|
dateStrings: true,
|
||||||
supportBigNumbers: true,
|
supportBigNumbers: true,
|
||||||
bigNumberStrings: false,
|
bigNumberStrings: false,
|
||||||
charset: 'utf8mb4_0900_ai_ci',
|
charset: 'utf8mb4_general_ci',
|
||||||
connectTimeout: 10_000,
|
connectTimeout: 10_000,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -263,18 +263,24 @@ export class Db {
|
|||||||
return Number(rows[0].id ?? 0);
|
return Number(rows[0].id ?? 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
async auditSince(id: number): Promise<AuditRow[]> {
|
private async auditRows(clause: string, value: number): Promise<AuditRow[]> {
|
||||||
return this.query<AuditRow>(
|
const rows = await this.query<AuditRow>(
|
||||||
`SELECT id, DATE_FORMAT(time, '%Y-%m-%dT%H:%i:%s.%fZ') AS time, user_id, actor, origin, operation, status, error, zone, record_id, target_user_id, before_value, after_value FROM ${this.t.audit} WHERE id > ? ORDER BY id`,
|
`SELECT id, DATE_FORMAT(time, '%Y-%m-%dT%H:%i:%s.%fZ') AS time, user_id, actor, origin, operation, status, error, zone, record_id, target_user_id, CAST(before_value AS CHAR) AS before_value, CAST(after_value AS CHAR) AS after_value FROM ${this.t.audit} ${clause}`,
|
||||||
[id],
|
[value],
|
||||||
);
|
);
|
||||||
|
return rows.map(row => ({
|
||||||
|
...row,
|
||||||
|
before_value: row.before_value === null ? null : JSON.parse(String(row.before_value)),
|
||||||
|
after_value: row.after_value === null ? null : JSON.parse(String(row.after_value)),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
async auditSince(id: number): Promise<AuditRow[]> {
|
||||||
|
return this.auditRows('WHERE id > ? ORDER BY id', id);
|
||||||
}
|
}
|
||||||
|
|
||||||
async auditTail(n: number): Promise<AuditRow[]> {
|
async auditTail(n: number): Promise<AuditRow[]> {
|
||||||
const rows = await this.query<AuditRow>(
|
const rows = await this.auditRows('ORDER BY id DESC LIMIT ?', n);
|
||||||
`SELECT id, DATE_FORMAT(time, '%Y-%m-%dT%H:%i:%s.%fZ') AS time, user_id, actor, origin, operation, status, error, zone, record_id, target_user_id, before_value, after_value FROM ${this.t.audit} ORDER BY id DESC LIMIT ?`,
|
|
||||||
[n],
|
|
||||||
);
|
|
||||||
return rows.reverse();
|
return rows.reverse();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
-- SPDX-License-Identifier: GPL-2.0-or-later
|
-- SPDX-License-Identifier: GPL-2.0-or-later
|
||||||
-- Copyright (C) 2026 Bryan Joshua Pedini
|
-- Copyright (C) 2026 Bryan Joshua Pedini
|
||||||
|
|
||||||
CREATE DATABASE `{{DATABASE}}` DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci;
|
CREATE DATABASE `{{DATABASE}}` DEFAULT CHARSET = utf8mb4;
|
||||||
|
|
||||||
CREATE TABLE `{{DATABASE}}`.`{{PREFIX}}records` (
|
CREATE TABLE `{{DATABASE}}`.`{{PREFIX}}records` (
|
||||||
`id` INT NOT NULL AUTO_INCREMENT,
|
`id` INT NOT NULL AUTO_INCREMENT,
|
||||||
@@ -11,7 +11,7 @@ CREATE TABLE `{{DATABASE}}`.`{{PREFIX}}records` (
|
|||||||
`content` TEXT,
|
`content` TEXT,
|
||||||
`record_type` VARCHAR(255) NOT NULL,
|
`record_type` VARCHAR(255) NOT NULL,
|
||||||
PRIMARY KEY (`id`)
|
PRIMARY KEY (`id`)
|
||||||
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci;
|
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4;
|
||||||
|
|
||||||
CREATE USER '{{DNS_USER}}'@'%' IDENTIFIED BY '{{DNS_PASSWORD}}';
|
CREATE USER '{{DNS_USER}}'@'%' IDENTIFIED BY '{{DNS_PASSWORD}}';
|
||||||
GRANT SELECT ON `{{DATABASE}}`.`{{PREFIX}}records` TO '{{DNS_USER}}'@'%';
|
GRANT SELECT ON `{{DATABASE}}`.`{{PREFIX}}records` TO '{{DNS_USER}}'@'%';
|
||||||
|
|||||||
@@ -1065,13 +1065,13 @@ func (f *zoneAPITestDB) query(query string, args []any) fdbResponse {
|
|||||||
return fdbResponse{rows: fdbRow(int64(1))}
|
return fdbResponse{rows: fdbRow(int64(1))}
|
||||||
case has("RELEASE_LOCK"):
|
case has("RELEASE_LOCK"):
|
||||||
return fdbResponse{rows: fdbRow(int64(1))}
|
return fdbResponse{rows: fdbRow(int64(1))}
|
||||||
case has("SELECT u.") && has("FOR SHARE"):
|
case has("SELECT u.") && has("LOCK IN SHARE MODE"):
|
||||||
if !f.hasActor {
|
if !f.hasActor {
|
||||||
return fdbResponse{}
|
return fdbResponse{}
|
||||||
}
|
}
|
||||||
deleted, _ := f.actor.DeletedAt.Value()
|
deleted, _ := f.actor.DeletedAt.Value()
|
||||||
return fdbResponse{rows: fdbRow(f.actor.ID, f.actor.Username, f.actor.Role, "hash", modelNow, modelNow, nil, deleted)}
|
return fdbResponse{rows: fdbRow(f.actor.ID, f.actor.Username, f.actor.Role, "hash", modelNow, modelNow, nil, deleted)}
|
||||||
case has("SELECT 1 FROM") && has("zone_delegations") && has("FOR SHARE"):
|
case has("SELECT 1 FROM") && has("zone_delegations") && has("LOCK IN SHARE MODE"):
|
||||||
if f.delegated {
|
if f.delegated {
|
||||||
return fdbResponse{rows: fdbRow(int64(1))}
|
return fdbResponse{rows: fdbRow(int64(1))}
|
||||||
}
|
}
|
||||||
@@ -1088,7 +1088,7 @@ func (f *zoneAPITestDB) query(query string, args []any) fdbResponse {
|
|||||||
rows = append(rows, []driver.Value{f.foreign.Zone, int64(1), nil})
|
rows = append(rows, []driver.Value{f.foreign.Zone, int64(1), nil})
|
||||||
}
|
}
|
||||||
return fdbResponse{rows: rows}
|
return fdbResponse{rows: rows}
|
||||||
case has("SELECT d.") && has("FOR UPDATE OF d"):
|
case has("SELECT d.") && has("ORDER BY username FOR UPDATE"):
|
||||||
if f.stale {
|
if f.stale {
|
||||||
return fdbResponse{rows: fdbRow(args[0], int64(18), "bob", modelNow, f.actor.ID)}
|
return fdbResponse{rows: fdbRow(args[0], int64(18), "bob", modelNow, f.actor.ID)}
|
||||||
}
|
}
|
||||||
@@ -1291,7 +1291,7 @@ func TestZoneAPIWriteHandlers(t *testing.T) {
|
|||||||
t.Fatalf("delegations in the after snapshot: %s", c.Entry.After)
|
t.Fatalf("delegations in the after snapshot: %s", c.Entry.After)
|
||||||
}
|
}
|
||||||
calls := state.Queries()
|
calls := state.Queries()
|
||||||
if !strings.Contains(calls[0], "GET_LOCK") || !strings.HasSuffix(calls[1], "FOR SHARE") ||
|
if !strings.Contains(calls[0], "GET_LOCK") || !strings.HasSuffix(calls[1], "LOCK IN SHARE MODE") ||
|
||||||
!strings.HasSuffix(calls[2], "FOR UPDATE") || !strings.Contains(calls[len(calls)-2], "INSERT INTO `coredns_webui_audit`") ||
|
!strings.HasSuffix(calls[2], "FOR UPDATE") || !strings.Contains(calls[len(calls)-2], "INSERT INTO `coredns_webui_audit`") ||
|
||||||
!strings.Contains(calls[len(calls)-1], "RELEASE_LOCK") {
|
!strings.Contains(calls[len(calls)-1], "RELEASE_LOCK") {
|
||||||
t.Fatalf("write query order: %v", calls)
|
t.Fatalf("write query order: %v", calls)
|
||||||
@@ -1438,7 +1438,7 @@ func TestZoneAPIWarningsAndSerialModes(t *testing.T) {
|
|||||||
resp := zoneAPITestStatus(t, t.Context(), c, 201)
|
resp := zoneAPITestStatus(t, t.Context(), c, 201)
|
||||||
if !strings.Contains(zoneAPITestJSON(t, resp.Body), "target_no_address") ||
|
if !strings.Contains(zoneAPITestJSON(t, resp.Body), "target_no_address") ||
|
||||||
len(zoneAPITestingSQL(state, "UPDATE `coredns_records`")) != 0 ||
|
len(zoneAPITestingSQL(state, "UPDATE `coredns_records`")) != 0 ||
|
||||||
len(zoneAPITestingSQL(state, "zone_delegations` WHERE `zone` = ? AND `user_id` = ? FOR SHARE")) != 1 {
|
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())
|
t.Fatalf("response = %+v, SQL = %v", resp, state.Queries())
|
||||||
}
|
}
|
||||||
c = zoneAPITestRequest(server, f.actor, "soa_update", zoneAPITestName, "", recordETag(rows[0]), zoneAPITestSOA)
|
c = zoneAPITestRequest(server, f.actor, "soa_update", zoneAPITestName, "", recordETag(rows[0]), zoneAPITestSOA)
|
||||||
|
|||||||
@@ -48,10 +48,10 @@ func TestZoneAPIFailurePaths(t *testing.T) {
|
|||||||
ran string
|
ran string
|
||||||
}{
|
}{
|
||||||
{name: "actor lookup", operation: "record_create", body: zoneAPITestRecord, failOn: []string{"SELECT u."}},
|
{name: "actor lookup", operation: "record_create", body: zoneAPITestRecord, failOn: []string{"SELECT u."}},
|
||||||
{name: "delegation lookup", operation: "record_create", body: zoneAPITestRecord, setup: asUser, failOn: []string{"zone_delegations", "FOR SHARE"}},
|
{name: "delegation lookup", operation: "record_create", body: zoneAPITestRecord, setup: asUser, failOn: []string{"zone_delegations", "LOCK IN SHARE MODE"}},
|
||||||
{name: "zone rows lookup", operation: "record_create", body: zoneAPITestRecord, failOn: []string{zoneRowsWhere, "FOR UPDATE"}},
|
{name: "zone rows lookup", operation: "record_create", body: zoneAPITestRecord, failOn: []string{zoneRowsWhere, "FOR UPDATE"}},
|
||||||
{name: "create malformed body", operation: "zone_create", body: "{", status: 400},
|
{name: "create malformed body", operation: "zone_create", body: "{", status: 400},
|
||||||
{name: "create stale grant lookup", operation: "zone_create", body: zoneAPITestCreate, setup: rowsWithStale, failOn: []string{"FOR UPDATE OF d"}},
|
{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,
|
{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`"},
|
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`"},
|
{name: "create written rows", operation: "zone_create", body: zoneAPITestCreate, setup: rowsWithStale, failOn: zoneRead, ran: "INSERT INTO `coredns_records`"},
|
||||||
|
|||||||
+17
-2
@@ -144,7 +144,7 @@ func TestIntegrationMigrations(t *testing.T) {
|
|||||||
t.Fatal(version, err)
|
t.Fatal(version, err)
|
||||||
}
|
}
|
||||||
for _, table := range []string{"coredns_webui_schema", "coredns_webui_users", "coredns_webui_sessions", "coredns_webui_zone_delegations", "coredns_webui_audit"} {
|
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 TABLE_COLLATION = 'utf8mb4_0900_ai_ci' AND ENGINE = 'InnoDB'", table) != 1 {
|
if d.count(t, "SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND TABLE_COLLATION IN (SELECT COLLATION_NAME FROM information_schema.COLLATIONS WHERE CHARACTER_SET_NAME = 'utf8mb4') AND ENGINE = 'InnoDB'", table) != 1 {
|
||||||
t.Fatalf("%s missing", table)
|
t.Fatalf("%s missing", table)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -163,15 +163,27 @@ func TestIntegrationMigrations(t *testing.T) {
|
|||||||
if n := d.count(t, "SELECT `version` FROM `coredns_webui_schema` WHERE `id` = 1"); n != 2 {
|
if n := d.count(t, "SELECT `version` FROM `coredns_webui_schema` WHERE `id` = 1"); n != 2 {
|
||||||
t.Fatalf("version %d", n)
|
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("INSERT INTO `coredns_webui_schema` (`id`, `version`) VALUES (2, 1)"); err == nil {
|
||||||
t.Fatal("second schema row accepted")
|
t.Fatal("second schema row accepted")
|
||||||
}
|
}
|
||||||
|
}
|
||||||
d.rootExec(t, "UPDATE `coredns_webui_schema` SET `version` = 3")
|
d.rootExec(t, "UPDATE `coredns_webui_schema` SET `version` = 3")
|
||||||
if err := migrateDatabase(ctx, db, tn, discardLogger()); err == nil || !strings.Contains(err.Error(), "newer") {
|
if err := migrateDatabase(ctx, db, tn, discardLogger()); err == nil || !strings.Contains(err.Error(), "newer") {
|
||||||
t.Fatalf("newer schema: %v", err)
|
t.Fatalf("newer schema: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestIntegrationAcceptsExistingJSONAuditColumns(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
d := newITDatabase(t, itOptions{prefix: "legacy_"})
|
||||||
|
db, tn := d.migrated(t)
|
||||||
|
d.rootExec(t, tn.sql("ALTER TABLE {audit} MODIFY before_value JSON NULL, MODIFY after_value JSON NULL"))
|
||||||
|
if err := migrateDatabase(t.Context(), db, tn, discardLogger()); err != nil {
|
||||||
|
t.Fatalf("existing JSON audit columns: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestIntegrationAuditRecordIDMigration(t *testing.T) {
|
func TestIntegrationAuditRecordIDMigration(t *testing.T) {
|
||||||
const prefix = "audit_id_"
|
const prefix = "audit_id_"
|
||||||
migrations, err := loadMigrations(migrationFiles, prefix)
|
migrations, err := loadMigrations(migrationFiles, prefix)
|
||||||
@@ -350,9 +362,12 @@ func TestIntegrationForeignKeys(t *testing.T) {
|
|||||||
if _, err := d.root.Exec("DELETE FROM `coredns_webui_users` WHERE `id` = ?", u2.ID); mysqlErrNumber(err) != 1451 {
|
if _, err := d.root.Exec("DELETE FROM `coredns_webui_users` WHERE `id` = ?", u2.ID); mysqlErrNumber(err) != 1451 {
|
||||||
t.Fatalf("referenced user deleted: %v", err)
|
t.Fatalf("referenced user deleted: %v", err)
|
||||||
}
|
}
|
||||||
if _, 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))"); mysqlErrNumber(err) != 3819 {
|
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))")
|
||||||
|
if n := mysqlErrNumber(err); n != 3819 && n != 4025 {
|
||||||
t.Fatalf("role check: %v", err)
|
t.Fatalf("role check: %v", err)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestIntegrationTransactionRollback(t *testing.T) {
|
func TestIntegrationTransactionRollback(t *testing.T) {
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ const itRecordsDDL = "CREATE TABLE `%s`.`%srecords` (\n" +
|
|||||||
" `content` TEXT,\n" +
|
" `content` TEXT,\n" +
|
||||||
" `record_type` VARCHAR(255) NOT NULL,\n" +
|
" `record_type` VARCHAR(255) NOT NULL,\n" +
|
||||||
" PRIMARY KEY (`id`)\n" +
|
" PRIMARY KEY (`id`)\n" +
|
||||||
") ENGINE = INNODB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci"
|
") ENGINE = INNODB DEFAULT CHARSET = utf8mb4"
|
||||||
|
|
||||||
var itAppGrants = []struct {
|
var itAppGrants = []struct {
|
||||||
table string
|
table string
|
||||||
@@ -94,6 +94,34 @@ type itDatabase struct {
|
|||||||
root *sql.DB
|
root *sql.DB
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// InnoDB on older servers only refreshes its lock metadata after 100 ms of idle time.
|
||||||
|
const itLockPollInterval = 150 * time.Millisecond
|
||||||
|
|
||||||
|
func (d *itDatabase) rowLockWaiting(ctx context.Context, suffix string) (bool, error) {
|
||||||
|
table := d.prefix + 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)
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
return waiting, err
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// MySQL 5.7 parses CHECK constraints and omits them from the table.
|
||||||
|
return strings.Contains(ddl, "CHECK")
|
||||||
|
}
|
||||||
|
|
||||||
type itOptions struct {
|
type itOptions struct {
|
||||||
prefix string
|
prefix string
|
||||||
recordDDL string
|
recordDDL string
|
||||||
@@ -121,7 +149,7 @@ func newITDatabase(t *testing.T, opts itOptions) *itDatabase {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
exec("create database", "CREATE DATABASE `"+d.name+"` DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci")
|
exec("create database", "CREATE DATABASE `"+d.name+"` DEFAULT CHARSET = utf8mb4")
|
||||||
t.Cleanup(func() {
|
t.Cleanup(func() {
|
||||||
_, _ = admin.ExecContext(ctx, "DROP DATABASE IF EXISTS `"+d.name+"`")
|
_, _ = 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.appUser+"'@'%'")
|
||||||
|
|||||||
@@ -157,18 +157,17 @@ func (it itHTTP) race(t *testing.T, first, second webRequest, firstStatus, secon
|
|||||||
|
|
||||||
func (it itHTTP) waitForUserLock(t *testing.T, ctx context.Context, result <-chan *httptest.ResponseRecorder) {
|
func (it itHTTP) waitForUserLock(t *testing.T, ctx context.Context, result <-chan *httptest.ResponseRecorder) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
it.waitForLock(t, ctx, result, "user row lock", "SELECT EXISTS (SELECT 1 FROM performance_schema.data_lock_waits w "+
|
it.waitForLock(t, ctx, result, "user row lock", func() (bool, error) {
|
||||||
"JOIN performance_schema.data_locks l ON l.ENGINE = w.ENGINE AND l.ENGINE_LOCK_ID = w.REQUESTING_ENGINE_LOCK_ID "+
|
return it.database.rowLockWaiting(ctx, "webui_users")
|
||||||
"WHERE l.OBJECT_SCHEMA = ? AND l.OBJECT_NAME = ?)", it.database.name, it.database.prefix+"webui_users")
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (it itHTTP) waitForLock(t *testing.T, ctx context.Context, result <-chan *httptest.ResponseRecorder, lock, query string, args ...any) {
|
func (it itHTTP) waitForLock(t *testing.T, ctx context.Context, result <-chan *httptest.ResponseRecorder, lock string, observe func() (bool, error)) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
tick := time.NewTicker(20 * time.Millisecond)
|
tick := time.NewTicker(itLockPollInterval)
|
||||||
defer tick.Stop()
|
defer tick.Stop()
|
||||||
for {
|
for {
|
||||||
var waiting bool
|
waiting, err := observe()
|
||||||
err := it.database.root.QueryRowContext(ctx, query, args...).Scan(&waiting)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("observe %s: %v", lock, err)
|
t.Fatalf("observe %s: %v", lock, err)
|
||||||
}
|
}
|
||||||
@@ -378,8 +377,14 @@ func TestIntegrationZoneCreationDelegationRace(t *testing.T) {
|
|||||||
go func() { a <- it.do(ctx, first) }()
|
go func() { a <- it.do(ctx, first) }()
|
||||||
it.waitForUserLock(t, ctx, a)
|
it.waitForUserLock(t, ctx, a)
|
||||||
go func() { b <- it.do(ctx, second) }()
|
go func() { b <- it.do(ctx, second) }()
|
||||||
it.waitForLock(t, ctx, b, "zone named lock", "SELECT EXISTS (SELECT 1 FROM performance_schema.metadata_locks "+
|
it.waitForLock(t, ctx, b, "zone named lock", func() (bool, error) {
|
||||||
"WHERE OBJECT_TYPE = 'USER LEVEL LOCK' AND OBJECT_NAME = ? AND LOCK_STATUS = 'PENDING')", tables.zoneLockName(zone))
|
var waiting bool
|
||||||
|
// Each fixture has a separate database account. The only named
|
||||||
|
// lock wait for that account here is on this zone.
|
||||||
|
err := it.database.root.QueryRowContext(ctx, "SELECT EXISTS (SELECT 1 FROM information_schema.PROCESSLIST "+
|
||||||
|
"WHERE USER = ? AND LOWER(STATE) = 'user lock')", it.database.appUser).Scan(&waiting)
|
||||||
|
return waiting, err
|
||||||
|
})
|
||||||
if err := gate.Commit(); err != nil {
|
if err := gate.Commit(); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
"database/sql"
|
"database/sql"
|
||||||
"errors"
|
"errors"
|
||||||
"slices"
|
"slices"
|
||||||
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -19,6 +20,29 @@ func itRecord(zone, name, typ, content string, ttl int64) recordRow {
|
|||||||
return recordRow{Zone: zone, Name: name, TTL: sql.NullInt64{Int64: ttl, Valid: true}, Content: sql.NullString{String: content, Valid: true}, RecordType: typ}
|
return recordRow{Zone: zone, Name: name, TTL: sql.NullInt64{Int64: ttl, Valid: true}, Content: sql.NullString{String: content, Valid: true}, RecordType: typ}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestIntegrationZoneMatchingWithTurkishCollation(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
ctx := t.Context()
|
||||||
|
ddl := strings.Replace(itRecordsDDL, "DEFAULT CHARSET = utf8mb4", "DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_turkish_ci", 1)
|
||||||
|
d := newITDatabase(t, itOptions{prefix: "dns_", recordDDL: ddl})
|
||||||
|
db, tn := d.migrated(t)
|
||||||
|
records := newRecordStore(db, tn)
|
||||||
|
const content = `{"text":"DNS 🌐"}`
|
||||||
|
for _, zone := range []string{"ISTANBUL.example", "istanbul.example."} {
|
||||||
|
if _, err := records.InsertRecord(ctx, itRecord(zone, "", "TXT", content, 60)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
zones, err := records.ListZones(ctx)
|
||||||
|
if err != nil || len(zones) != 1 || zones[0].Zone != "istanbul.example." || zones[0].RecordCount != 2 {
|
||||||
|
t.Fatalf("zones: %+v, %v", zones, err)
|
||||||
|
}
|
||||||
|
rows, err := records.ZoneRows(ctx, "istanbul.example.")
|
||||||
|
if err != nil || len(rows) != 2 || rows[0].Content.String != content {
|
||||||
|
t.Fatalf("records: %+v, %v", rows, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestIntegrationRecordStore(t *testing.T) {
|
func TestIntegrationRecordStore(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
@@ -519,7 +543,7 @@ func TestIntegrationAuditStore(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
rows, err := s.ListAudit(ctx, auditFilter{Operation: "user_create", Limit: 1})
|
rows, err := s.ListAudit(ctx, auditFilter{Operation: "user_create", Limit: 1})
|
||||||
if err != nil || len(rows) != 1 || rows[0].TargetUsername.String != "carl" || rows[0].UserID.Valid || rows[0].Status.Valid || string(rows[0].After) != `{"id": 3}` || rows[0].Before != nil || !rows[0].Time.Equal(base.Add(4*time.Second)) {
|
if err != nil || len(rows) != 1 || rows[0].TargetUsername.String != "carl" || rows[0].UserID.Valid || rows[0].Status.Valid || string(rows[0].After) != `{"id":3}` || rows[0].Before != nil || !rows[0].Time.Equal(base.Add(4*time.Second)) {
|
||||||
t.Fatalf("%+v %v", rows, err)
|
t.Fatalf("%+v %v", rows, err)
|
||||||
}
|
}
|
||||||
if _, err := newDelegationStore(db, tn).RevokeDelegation(ctx, "a.org.", bob.ID); err != nil {
|
if _, err := newDelegationStore(db, tn).RevokeDelegation(ctx, "a.org.", bob.ID); err != nil {
|
||||||
|
|||||||
@@ -250,7 +250,7 @@ func TestIntegrationZoneAPIHandlers(t *testing.T) {
|
|||||||
soaID := view.Body.(zoneAPIView).SOA.ID
|
soaID := view.Body.(zoneAPIView).SOA.ID
|
||||||
zoneAPITestAuditIDs(t, audit.Before, []int64{soaID, record.ID})
|
zoneAPITestAuditIDs(t, audit.Before, []int64{soaID, record.ID})
|
||||||
zoneAPITestAuditIDs(t, audit.After, []int64{soaID, record.ID})
|
zoneAPITestAuditIDs(t, audit.After, []int64{soaID, record.ID})
|
||||||
if !strings.Contains(string(audit.Before), `"ttl": 180`) || !strings.Contains(string(audit.After), `"ttl": 60`) {
|
if !strings.Contains(string(audit.Before), `"ttl":180`) || !strings.Contains(string(audit.After), `"ttl":60`) {
|
||||||
t.Fatalf("update audit values: %s, %s", audit.Before, audit.After)
|
t.Fatalf("update audit values: %s, %s", audit.Before, audit.After)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -313,8 +313,8 @@ func TestIntegrationZoneAPIHandlers(t *testing.T) {
|
|||||||
it.call(t, user, "zone_import", "", "", zoneAPITestJSON(t, input), 200)
|
it.call(t, user, "zone_import", "", "", zoneAPITestJSON(t, input), 200)
|
||||||
it.serial(t, serial+8)
|
it.serial(t, serial+8)
|
||||||
imports := it.audit(t, "zone_import", 1)
|
imports := it.audit(t, "zone_import", 1)
|
||||||
if !strings.Contains(string(imports[0].Before), `"name": "broken"`) ||
|
if !strings.Contains(string(imports[0].Before), `"name":"broken"`) ||
|
||||||
!strings.Contains(string(imports[0].After), `"name": "second"`) ||
|
!strings.Contains(string(imports[0].After), `"name":"second"`) ||
|
||||||
strings.Contains(string(imports[0].After), "backup") {
|
strings.Contains(string(imports[0].After), "backup") {
|
||||||
t.Fatalf("import audit: %s, %s", imports[0].Before, imports[0].After)
|
t.Fatalf("import audit: %s, %s", imports[0].Before, imports[0].After)
|
||||||
}
|
}
|
||||||
@@ -332,7 +332,7 @@ func TestIntegrationZoneAPIHandlers(t *testing.T) {
|
|||||||
it.call(t, user, "zone_delete", "", "", `{"confirm":"example.org"}`, 403)
|
it.call(t, user, "zone_delete", "", "", `{"confirm":"example.org"}`, 403)
|
||||||
it.call(t, admin, "zone_delete", "", "", `{"confirm":"wrong.example.org"}`, 422)
|
it.call(t, admin, "zone_delete", "", "", `{"confirm":"wrong.example.org"}`, 422)
|
||||||
it.call(t, admin, "zone_delete", "", "", `{"confirm":"EXAMPLE.ORG"}`, 204)
|
it.call(t, admin, "zone_delete", "", "", `{"confirm":"EXAMPLE.ORG"}`, 204)
|
||||||
if len(it.rows(t)) != 0 || !strings.Contains(string(it.audit(t, "zone_delete", 1)[0].Before), `"username": "bob"`) {
|
if len(it.rows(t)) != 0 || !strings.Contains(string(it.audit(t, "zone_delete", 1)[0].Before), `"username":"bob"`) {
|
||||||
t.Fatal("zone deletion did not remove and audit the records and delegation")
|
t.Fatal("zone deletion did not remove and audit the records and delegation")
|
||||||
}
|
}
|
||||||
it.call(t, admin, "zone_read", "", "", "", 404)
|
it.call(t, admin, "zone_read", "", "", "", 404)
|
||||||
@@ -385,7 +385,7 @@ func TestIntegrationZoneAPIJSONColumnETags(t *testing.T) {
|
|||||||
response := it.call(t, admin, "record_create", "", "", zoneAPITestRecord, 201)
|
response := it.call(t, admin, "record_create", "", "", zoneAPITestRecord, 201)
|
||||||
row := response.Body.(map[string]any)["record"].(zoneAPIRecord)
|
row := response.Body.(map[string]any)["record"].(zoneAPIRecord)
|
||||||
stored, err := it.records.RecordByID(t.Context(), row.ID)
|
stored, err := it.records.RecordByID(t.Context(), row.ID)
|
||||||
if err != nil || row.ETag != recordETag(stored) || !strings.Contains(stored.Content.String, `": "`) {
|
if err != nil || row.ETag != recordETag(stored) {
|
||||||
t.Fatalf("record create ETag = %q, stored row %+v, error %v", row.ETag, stored, err)
|
t.Fatalf("record create ETag = %q, stored row %+v, error %v", row.ETag, stored, err)
|
||||||
}
|
}
|
||||||
id := strconv.FormatInt(row.ID, 10)
|
id := strconv.FormatInt(row.ID, 10)
|
||||||
@@ -405,10 +405,6 @@ func TestIntegrationZoneAPIJSONColumnETags(t *testing.T) {
|
|||||||
if check := zoneAPITestJSON(t, it.call(t, admin, "zone_check", "", "", "", 200).Body); check != `{"problems":[]}` {
|
if check := zoneAPITestJSON(t, it.call(t, admin, "zone_check", "", "", "", 200).Body); check != `{"problems":[]}` {
|
||||||
t.Fatalf("JSON column rows reported as not canonical: %s", check)
|
t.Fatalf("JSON column rows reported as not canonical: %s", check)
|
||||||
}
|
}
|
||||||
soa := zoneAPIFindSOA(it.rows(t))
|
|
||||||
if !strings.Contains(soa.Content.String, `"retry": 600, "expire"`) {
|
|
||||||
t.Fatalf("MySQL did not reformat the SOA content: %s", soa.Content.String)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestIntegrationZoneAPIRepairs(t *testing.T) {
|
func TestIntegrationZoneAPIRepairs(t *testing.T) {
|
||||||
@@ -568,13 +564,10 @@ func TestIntegrationZoneAPIAuditRollback(t *testing.T) {
|
|||||||
|
|
||||||
func (it itZoneAPI) waitForRowLock(t *testing.T, ctx context.Context, suffix string) {
|
func (it itZoneAPI) waitForRowLock(t *testing.T, ctx context.Context, suffix string) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
ticker := time.NewTicker(25 * time.Millisecond)
|
ticker := time.NewTicker(itLockPollInterval)
|
||||||
defer ticker.Stop()
|
defer ticker.Stop()
|
||||||
for {
|
for {
|
||||||
var waiting bool
|
waiting, err := it.db.rowLockWaiting(ctx, suffix)
|
||||||
err := it.db.root.QueryRowContext(ctx, "SELECT EXISTS (SELECT 1 FROM performance_schema.data_lock_waits w "+
|
|
||||||
"JOIN performance_schema.data_locks l ON l.ENGINE = w.ENGINE AND l.ENGINE_LOCK_ID = w.REQUESTING_ENGINE_LOCK_ID "+
|
|
||||||
"WHERE l.OBJECT_SCHEMA = ? AND l.OBJECT_NAME = ?)", it.db.name, it.db.prefix+suffix).Scan(&waiting)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -860,7 +860,7 @@ func TestZoneTxLockReleaseFailureKeepsTheCommittedChange(t *testing.T) {
|
|||||||
fdbRule{"x.`token_hash` = ?", fdbResponse{rows: [][]driver.Value{session}}},
|
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{"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_records`", fdbResponse{rows: fdbRow(int64(1))}},
|
||||||
fdbRule{"u.`username` = ? FOR UPDATE", fdbResponse{rows: [][]driver.Value{userValues(2, "bob", roleUser)}}},
|
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 `coredns_webui_audit`", fdbResponse{lastInsertID: 1, rowsAffected: 1}},
|
||||||
))
|
))
|
||||||
var logs bytes.Buffer
|
var logs bytes.Buffer
|
||||||
|
|||||||
+20
-3
@@ -156,8 +156,8 @@ var appSchema = []schemaColumn{
|
|||||||
{"webui_audit", "zone", "varchar(255)"},
|
{"webui_audit", "zone", "varchar(255)"},
|
||||||
{"webui_audit", "record_id", "bigint"},
|
{"webui_audit", "record_id", "bigint"},
|
||||||
{"webui_audit", "target_user_id", "int"},
|
{"webui_audit", "target_user_id", "int"},
|
||||||
{"webui_audit", "before_value", "json"},
|
{"webui_audit", "before_value", "longtext"},
|
||||||
{"webui_audit", "after_value", "json"},
|
{"webui_audit", "after_value", "longtext"},
|
||||||
}
|
}
|
||||||
|
|
||||||
var appTables = []string{"webui_schema", "webui_users", "webui_sessions", "webui_zone_delegations", "webui_audit"}
|
var appTables = []string{"webui_schema", "webui_users", "webui_sessions", "webui_zone_delegations", "webui_audit"}
|
||||||
@@ -189,7 +189,7 @@ func verifyAppSchema(ctx context.Context, q dbtx, t tableNames, log *slog.Logger
|
|||||||
if !ok {
|
if !ok {
|
||||||
return fmt.Errorf("application schema: table %s has no column %s", table, c.column)
|
return fmt.Errorf("application schema: table %s has no column %s", table, c.column)
|
||||||
}
|
}
|
||||||
if got != c.columnType {
|
if !appColumnTypeMatches(got, c.columnType) {
|
||||||
return fmt.Errorf("application schema: column %s of table %s has type %s, expected %s", c.column, table, got, c.columnType)
|
return fmt.Errorf("application schema: column %s of table %s has type %s, expected %s", c.column, table, got, c.columnType)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -200,6 +200,23 @@ func verifyAppSchema(ctx context.Context, q dbtx, t tableNames, log *slog.Logger
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func appColumnTypeMatches(got, want string) bool {
|
||||||
|
switch want {
|
||||||
|
case "tinyint", "smallint", "int", "bigint":
|
||||||
|
// Older MySQL and MariaDB report a display width for signed integers.
|
||||||
|
// A trailing modifier such as UNSIGNED or ZEROFILL is still rejected.
|
||||||
|
if base, width, ok := strings.Cut(got, "("); ok && base == want {
|
||||||
|
width, closed := strings.CutSuffix(width, ")")
|
||||||
|
_, err := strconv.Atoi(width)
|
||||||
|
return closed && err == nil
|
||||||
|
}
|
||||||
|
case "longtext":
|
||||||
|
// The original MySQL schema stores the same audit payloads as native JSON.
|
||||||
|
return got == want || got == "json"
|
||||||
|
}
|
||||||
|
return got == want
|
||||||
|
}
|
||||||
|
|
||||||
func verifyAppForeignKeys(ctx context.Context, q dbtx, t tableNames) error {
|
func verifyAppForeignKeys(ctx context.Context, q dbtx, t tableNames) error {
|
||||||
var n int
|
var n int
|
||||||
err := q.QueryRowContext(ctx, "SELECT COUNT(DISTINCT TABLE_NAME, COLUMN_NAME) FROM information_schema.KEY_COLUMN_USAGE "+
|
err := q.QueryRowContext(ctx, "SELECT COUNT(DISTINCT TABLE_NAME, COLUMN_NAME) FROM information_schema.KEY_COLUMN_USAGE "+
|
||||||
|
|||||||
@@ -6,11 +6,11 @@ CREATE TABLE IF NOT EXISTS `{prefix}webui_schema` (
|
|||||||
`version` INT NOT NULL,
|
`version` INT NOT NULL,
|
||||||
PRIMARY KEY (`id`),
|
PRIMARY KEY (`id`),
|
||||||
CHECK (`id` = 1)
|
CHECK (`id` = 1)
|
||||||
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci;
|
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS `{prefix}webui_users` (
|
CREATE TABLE IF NOT EXISTS `{prefix}webui_users` (
|
||||||
`id` INT NOT NULL AUTO_INCREMENT,
|
`id` INT NOT NULL AUTO_INCREMENT,
|
||||||
`username` VARCHAR(64) NOT NULL,
|
`username` VARCHAR(64) COLLATE utf8mb4_bin NOT NULL,
|
||||||
`role` VARCHAR(8) NOT NULL,
|
`role` VARCHAR(8) NOT NULL,
|
||||||
`password_hash` VARCHAR(255) NOT NULL,
|
`password_hash` VARCHAR(255) NOT NULL,
|
||||||
`created_at` DATETIME(6) NOT NULL,
|
`created_at` DATETIME(6) NOT NULL,
|
||||||
@@ -20,7 +20,7 @@ CREATE TABLE IF NOT EXISTS `{prefix}webui_users` (
|
|||||||
PRIMARY KEY (`id`),
|
PRIMARY KEY (`id`),
|
||||||
UNIQUE KEY `username` (`username`),
|
UNIQUE KEY `username` (`username`),
|
||||||
CHECK (`role` IN ('admin', 'user'))
|
CHECK (`role` IN ('admin', 'user'))
|
||||||
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci;
|
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS `{prefix}webui_sessions` (
|
CREATE TABLE IF NOT EXISTS `{prefix}webui_sessions` (
|
||||||
`token_hash` BINARY(32) NOT NULL,
|
`token_hash` BINARY(32) NOT NULL,
|
||||||
@@ -34,10 +34,10 @@ CREATE TABLE IF NOT EXISTS `{prefix}webui_sessions` (
|
|||||||
KEY `user_id` (`user_id`),
|
KEY `user_id` (`user_id`),
|
||||||
KEY `expires_at` (`expires_at`),
|
KEY `expires_at` (`expires_at`),
|
||||||
FOREIGN KEY (`user_id`) REFERENCES `{prefix}webui_users` (`id`)
|
FOREIGN KEY (`user_id`) REFERENCES `{prefix}webui_users` (`id`)
|
||||||
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci;
|
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS `{prefix}webui_zone_delegations` (
|
CREATE TABLE IF NOT EXISTS `{prefix}webui_zone_delegations` (
|
||||||
`zone` VARCHAR(255) NOT NULL,
|
`zone` VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,
|
||||||
`user_id` INT NOT NULL,
|
`user_id` INT NOT NULL,
|
||||||
`created_at` DATETIME(6) NOT NULL,
|
`created_at` DATETIME(6) NOT NULL,
|
||||||
`created_by` INT NOT NULL,
|
`created_by` INT NOT NULL,
|
||||||
@@ -45,7 +45,7 @@ CREATE TABLE IF NOT EXISTS `{prefix}webui_zone_delegations` (
|
|||||||
KEY `user_id` (`user_id`),
|
KEY `user_id` (`user_id`),
|
||||||
FOREIGN KEY (`user_id`) REFERENCES `{prefix}webui_users` (`id`),
|
FOREIGN KEY (`user_id`) REFERENCES `{prefix}webui_users` (`id`),
|
||||||
FOREIGN KEY (`created_by`) REFERENCES `{prefix}webui_users` (`id`)
|
FOREIGN KEY (`created_by`) REFERENCES `{prefix}webui_users` (`id`)
|
||||||
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci;
|
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS `{prefix}webui_audit` (
|
CREATE TABLE IF NOT EXISTS `{prefix}webui_audit` (
|
||||||
`id` BIGINT NOT NULL AUTO_INCREMENT,
|
`id` BIGINT NOT NULL AUTO_INCREMENT,
|
||||||
@@ -59,8 +59,8 @@ CREATE TABLE IF NOT EXISTS `{prefix}webui_audit` (
|
|||||||
`zone` VARCHAR(255) NULL,
|
`zone` VARCHAR(255) NULL,
|
||||||
`record_id` INT NULL,
|
`record_id` INT NULL,
|
||||||
`target_user_id` INT NULL,
|
`target_user_id` INT NULL,
|
||||||
`before_value` JSON NULL,
|
`before_value` LONGTEXT NULL,
|
||||||
`after_value` JSON NULL,
|
`after_value` LONGTEXT NULL,
|
||||||
PRIMARY KEY (`id`),
|
PRIMARY KEY (`id`),
|
||||||
KEY `time` (`time`),
|
KEY `time` (`time`),
|
||||||
KEY `zone_time` (`zone`, `time`),
|
KEY `zone_time` (`zone`, `time`),
|
||||||
@@ -68,4 +68,4 @@ CREATE TABLE IF NOT EXISTS `{prefix}webui_audit` (
|
|||||||
KEY `operation_time` (`operation`, `time`),
|
KEY `operation_time` (`operation`, `time`),
|
||||||
FOREIGN KEY (`user_id`) REFERENCES `{prefix}webui_users` (`id`),
|
FOREIGN KEY (`user_id`) REFERENCES `{prefix}webui_users` (`id`),
|
||||||
FOREIGN KEY (`target_user_id`) REFERENCES `{prefix}webui_users` (`id`)
|
FOREIGN KEY (`target_user_id`) REFERENCES `{prefix}webui_users` (`id`)
|
||||||
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci;
|
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
|
||||||
+1
-1
@@ -33,7 +33,7 @@ func TestLoadEmbeddedMigrations(t *testing.T) {
|
|||||||
if !strings.Contains(stmt, "CREATE TABLE") || !strings.Contains(stmt, wantTables[i]) {
|
if !strings.Contains(stmt, "CREATE TABLE") || !strings.Contains(stmt, wantTables[i]) {
|
||||||
t.Fatalf("statement %d: %s", i, stmt)
|
t.Fatalf("statement %d: %s", i, stmt)
|
||||||
}
|
}
|
||||||
if !strings.HasSuffix(stmt, "COLLATE = utf8mb4_0900_ai_ci") {
|
if !strings.HasSuffix(stmt, "DEFAULT CHARSET = utf8mb4") {
|
||||||
t.Fatalf("statement %d: %s", i, stmt)
|
t.Fatalf("statement %d: %s", i, stmt)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-3
@@ -28,14 +28,17 @@ func newRecordStore(q dbtx, t tableNames) recordStore {
|
|||||||
const recordColumns = "`id`, `zone`, `name`, `ttl`, `content`, `record_type`"
|
const recordColumns = "`id`, `zone`, `name`, `ttl`, `content`, `record_type`"
|
||||||
|
|
||||||
func recordZoneKey(column string) string {
|
func recordZoneKey(column string) string {
|
||||||
return "CAST(CASE WHEN " + column + " LIKE '%.' THEN LOWER(" + column + ") ELSE CONCAT(LOWER(" + column + "), '.') END AS BINARY)"
|
// Use the same ASCII case mapping as normalizeZone, including on
|
||||||
|
// servers where the records column uses a language-specific collation.
|
||||||
|
lower := "LOWER(CONVERT(" + column + " USING utf8mb4) COLLATE utf8mb4_bin)"
|
||||||
|
return "CAST(CASE WHEN RIGHT(" + column + ", 1) = CAST('.' AS BINARY) THEN " + lower + " ELSE CONCAT(" + lower + ", '.') END AS BINARY)"
|
||||||
}
|
}
|
||||||
|
|
||||||
var zoneRowsWhere = " WHERE " + recordZoneKey("`zone`") + " = ?"
|
var zoneRowsWhere = " WHERE " + recordZoneKey("`zone`") + " = ?"
|
||||||
|
|
||||||
func zoneSummarySelect(filter string) string {
|
func zoneSummarySelect(filter string) string {
|
||||||
return "SELECT k.`zone_key`, k.`record_count`, (SELECT s.`content` FROM {records} s WHERE " + recordZoneKey("s.`zone`") +
|
return "SELECT k.`zone_key`, k.`record_count`, (SELECT s.`content` FROM {records} s WHERE " + recordZoneKey("s.`zone`") +
|
||||||
" = k.`zone_key` AND CAST(s.`record_type` AS BINARY) = 'SOA' ORDER BY s.`name` <> '', s.`id` LIMIT 1) FROM (SELECT " +
|
" = k.`zone_key` AND CAST(s.`record_type` AS BINARY) = 'SOA' ORDER BY OCTET_LENGTH(s.`name`) <> 0, s.`id` LIMIT 1) FROM (SELECT " +
|
||||||
recordZoneKey("r.`zone`") + " AS `zone_key`, COUNT(*) AS `record_count` FROM {records} r" + filter +
|
recordZoneKey("r.`zone`") + " AS `zone_key`, COUNT(*) AS `record_count` FROM {records} r" + filter +
|
||||||
" GROUP BY `zone_key`) k ORDER BY k.`zone_key`"
|
" GROUP BY `zone_key`) k ORDER BY k.`zone_key`"
|
||||||
}
|
}
|
||||||
@@ -48,7 +51,7 @@ func (s recordStore) ListZones(ctx context.Context) ([]zoneSummary, error) {
|
|||||||
func (s recordStore) ListZonesOfUser(ctx context.Context, userID int64) ([]zoneSummary, error) {
|
func (s recordStore) ListZonesOfUser(ctx context.Context, userID int64) ([]zoneSummary, error) {
|
||||||
defer traceStore(ctx, "recordStore.ListZonesOfUser")()
|
defer traceStore(ctx, "recordStore.ListZonesOfUser")()
|
||||||
return s.queryZones(ctx, s.t.sql(zoneSummarySelect(" WHERE "+recordZoneKey("r.`zone`")+
|
return s.queryZones(ctx, s.t.sql(zoneSummarySelect(" WHERE "+recordZoneKey("r.`zone`")+
|
||||||
" IN (SELECT d.`zone` FROM {delegations} d WHERE d.`user_id` = ?)")), userID)
|
" IN (SELECT CAST(d.`zone` AS BINARY) FROM {delegations} d WHERE d.`user_id` = ?)")), userID)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s recordStore) queryZones(ctx context.Context, query string, args ...any) ([]zoneSummary, error) {
|
func (s recordStore) queryZones(ctx context.Context, query string, args ...any) ([]zoneSummary, error) {
|
||||||
|
|||||||
@@ -69,7 +69,10 @@ mysql_id=$(docker create --name "$mysql" --network "$network_id" --network-alias
|
|||||||
--env MYSQL_ROOT_PASSWORD="$root_password" "$MYSQL_IMAGE")
|
--env MYSQL_ROOT_PASSWORD="$root_password" "$MYSQL_IMAGE")
|
||||||
docker start "$mysql_id" >/dev/null
|
docker start "$mysql_id" >/dev/null
|
||||||
attempt=0
|
attempt=0
|
||||||
until docker exec --env MYSQL_PWD="$root_password" "$mysql_id" mysql --host=127.0.0.1 --user=root --execute 'SELECT 1' >/dev/null 2>&1; do
|
until docker exec --env MYSQL_PWD="$root_password" "$mysql_id" sh -c '
|
||||||
|
client=$(command -v mariadb || command -v mysql)
|
||||||
|
exec "$client" --host=127.0.0.1 --user=root --execute "SELECT 1"
|
||||||
|
' >/dev/null 2>&1; do
|
||||||
attempt=$((attempt + 1))
|
attempt=$((attempt + 1))
|
||||||
if [ "$attempt" -ge 120 ]; then
|
if [ "$attempt" -ge 120 ]; then
|
||||||
echo "mysql did not become ready" >&2
|
echo "mysql did not become ready" >&2
|
||||||
|
|||||||
+10
-10
@@ -250,10 +250,10 @@ func TestUserStoreLookups(t *testing.T) {
|
|||||||
fragment string
|
fragment string
|
||||||
arg any
|
arg any
|
||||||
}{
|
}{
|
||||||
{func() (userRow, error) { return s.UserByUsername(ctx, "bob") }, "u.`username` = ?", "bob"},
|
{func() (userRow, error) { return s.UserByUsername(ctx, "bob") }, "u.`username` = CAST(? AS BINARY)", "bob"},
|
||||||
{func() (userRow, error) { return s.UserByUsernameForUpdate(ctx, "bob") }, "u.`username` = ? FOR UPDATE", "bob"},
|
{func() (userRow, error) { return s.UserByUsernameForUpdate(ctx, "bob") }, "u.`username` = CAST(? AS BINARY) FOR UPDATE", "bob"},
|
||||||
{func() (userRow, error) { return s.UserByID(ctx, 3) }, "u.`id` = ?", int64(3)},
|
{func() (userRow, error) { return s.UserByID(ctx, 3) }, "u.`id` = ?", int64(3)},
|
||||||
{func() (userRow, error) { return s.UserByIDForShare(ctx, 3) }, "u.`id` = ? FOR SHARE", int64(3)},
|
{func() (userRow, error) { return s.UserByIDForShare(ctx, 3) }, "u.`id` = ? LOCK IN SHARE MODE", int64(3)},
|
||||||
{func() (userRow, error) { return s.UserByIDForUpdate(ctx, 3) }, "u.`id` = ? FOR UPDATE", int64(3)},
|
{func() (userRow, error) { return s.UserByIDForUpdate(ctx, 3) }, "u.`id` = ? FOR UPDATE", int64(3)},
|
||||||
}
|
}
|
||||||
for i, c := range calls {
|
for i, c := range calls {
|
||||||
@@ -497,18 +497,18 @@ func TestDelegationStore(t *testing.T) {
|
|||||||
if err != nil || len(deleted) != 1 || deleted[0].Username != "carol" || deleted[0].CreatedBy != 1 {
|
if err != nil || len(deleted) != 1 || deleted[0].Username != "carol" || deleted[0].CreatedBy != 1 {
|
||||||
t.Fatal(deleted, err)
|
t.Fatal(deleted, err)
|
||||||
}
|
}
|
||||||
expectQuery(t, st.Calls()[4], "FOR UPDATE OF d")
|
expectQuery(t, st.Calls()[4], "ORDER BY username FOR UPDATE")
|
||||||
expectQuery(t, st.Calls()[5], "DELETE FROM `coredns_webui_zone_delegations` WHERE `zone` = ?")
|
expectQuery(t, st.Calls()[5], "DELETE FROM `coredns_webui_zone_delegations` WHERE `zone` = CAST(? AS BINARY)")
|
||||||
if ok, err := s.HasDelegation(ctx, "a.org.", 5); !ok || err != nil {
|
if ok, err := s.HasDelegation(ctx, "a.org.", 5); !ok || err != nil {
|
||||||
t.Fatal(ok, err)
|
t.Fatal(ok, err)
|
||||||
}
|
}
|
||||||
if strings.Contains(st.Calls()[6].query, "FOR SHARE") {
|
if strings.Contains(st.Calls()[6].query, "LOCK IN SHARE MODE") {
|
||||||
t.Fatal("plain check locks")
|
t.Fatal("plain check locks")
|
||||||
}
|
}
|
||||||
if ok, err := s.HasDelegationForShare(ctx, "a.org.", 5); !ok || err != nil {
|
if ok, err := s.HasDelegationForShare(ctx, "a.org.", 5); !ok || err != nil {
|
||||||
t.Fatal(ok, err)
|
t.Fatal(ok, err)
|
||||||
}
|
}
|
||||||
expectQuery(t, st.Calls()[7], "FOR SHARE")
|
expectQuery(t, st.Calls()[7], "LOCK IN SHARE MODE")
|
||||||
|
|
||||||
db, st = newFakeDB(t, nil)
|
db, st = newFakeDB(t, nil)
|
||||||
s = newDelegationStore(db, fdbTables(t))
|
s = newDelegationStore(db, fdbTables(t))
|
||||||
@@ -628,8 +628,8 @@ func TestAuditFilterSQL(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
for _, f := range []string{"a.`zone` = ?", "a.`actor` = ?", "a.`operation` = ?", "a.`operation` NOT IN (", "a.`status` >= 400", "a.`id` < ?",
|
for _, f := range []string{"a.`zone` = CAST(? AS BINARY)", "LOWER(CONVERT(a.`actor` USING utf8mb4) COLLATE utf8mb4_bin) = CAST(LOWER(CONVERT(? USING utf8mb4) COLLATE utf8mb4_bin) AS BINARY)", "a.`operation` = ?", "a.`operation` NOT IN (", "a.`status` >= 400", "a.`id` < ?",
|
||||||
"(a.`user_id` = ? OR a.`zone` IN (SELECT d.`zone` FROM {delegations} d WHERE d.`user_id` = ?))"} {
|
"(a.`user_id` = ? OR CAST(a.`zone` AS BINARY) IN (SELECT CAST(d.`zone` AS BINARY) FROM {delegations} d WHERE d.`user_id` = ?))"} {
|
||||||
if !strings.Contains(where, f) {
|
if !strings.Contains(where, f) {
|
||||||
t.Fatalf("%q lacks %q", where, f)
|
t.Fatalf("%q lacks %q", where, f)
|
||||||
}
|
}
|
||||||
@@ -660,7 +660,7 @@ func TestAuditStoreLists(t *testing.T) {
|
|||||||
t.Fatalf("%+v %v", rows, err)
|
t.Fatalf("%+v %v", rows, err)
|
||||||
}
|
}
|
||||||
c := st.Calls()[0]
|
c := st.Calls()[0]
|
||||||
expectQuery(t, c, "LEFT JOIN `coredns_webui_users` tu", "WHERE a.`zone` = ? ORDER BY a.`id` DESC LIMIT ?")
|
expectQuery(t, c, "LEFT JOIN `coredns_webui_users` tu", "WHERE a.`zone` = CAST(? AS BINARY) ORDER BY a.`id` DESC LIMIT ?")
|
||||||
expectArgs(t, c, "a.org.", int64(50))
|
expectArgs(t, c, "a.org.", int64(50))
|
||||||
latest, err := s.LatestAudit(ctx, 3)
|
latest, err := s.LatestAudit(ctx, 3)
|
||||||
if err != nil || len(latest) != 3 || latest[0].ID != 1 || latest[2].ID != 3 {
|
if err != nil || len(latest) != 3 || latest[0].ID != 1 || latest[2].ID != 3 {
|
||||||
|
|||||||
+3
-3
@@ -87,12 +87,12 @@ func (s userStore) queryUser(ctx context.Context, query string, args ...any) (us
|
|||||||
|
|
||||||
func (s userStore) UserByUsername(ctx context.Context, username string) (userRow, error) {
|
func (s userStore) UserByUsername(ctx context.Context, username string) (userRow, error) {
|
||||||
defer traceStore(ctx, "userStore.UserByUsername")()
|
defer traceStore(ctx, "userStore.UserByUsername")()
|
||||||
return s.queryUser(ctx, "SELECT "+userColumns+" FROM {users} u WHERE u.`username` = ?", username)
|
return s.queryUser(ctx, "SELECT "+userColumns+" FROM {users} u WHERE u.`username` = CAST(? AS BINARY)", username)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s userStore) UserByUsernameForUpdate(ctx context.Context, username string) (userRow, error) {
|
func (s userStore) UserByUsernameForUpdate(ctx context.Context, username string) (userRow, error) {
|
||||||
defer traceStore(ctx, "userStore.UserByUsernameForUpdate")()
|
defer traceStore(ctx, "userStore.UserByUsernameForUpdate")()
|
||||||
return s.queryUser(ctx, "SELECT "+userColumns+" FROM {users} u WHERE u.`username` = ? FOR UPDATE", username)
|
return s.queryUser(ctx, "SELECT "+userColumns+" FROM {users} u WHERE u.`username` = CAST(? AS BINARY) FOR UPDATE", username)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s userStore) UserByID(ctx context.Context, id int64) (userRow, error) {
|
func (s userStore) UserByID(ctx context.Context, id int64) (userRow, error) {
|
||||||
@@ -102,7 +102,7 @@ func (s userStore) UserByID(ctx context.Context, id int64) (userRow, error) {
|
|||||||
|
|
||||||
func (s userStore) UserByIDForShare(ctx context.Context, id int64) (userRow, error) {
|
func (s userStore) UserByIDForShare(ctx context.Context, id int64) (userRow, error) {
|
||||||
defer traceStore(ctx, "userStore.UserByIDForShare")()
|
defer traceStore(ctx, "userStore.UserByIDForShare")()
|
||||||
return s.queryUser(ctx, "SELECT "+userColumns+" FROM {users} u WHERE u.`id` = ? FOR SHARE", id)
|
return s.queryUser(ctx, "SELECT "+userColumns+" FROM {users} u WHERE u.`id` = ? LOCK IN SHARE MODE", id)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s userStore) UserByIDForUpdate(ctx context.Context, id int64) (userRow, error) {
|
func (s userStore) UserByIDForUpdate(ctx context.Context, id int64) (userRow, error) {
|
||||||
|
|||||||
Reference in new issue
Block a user