From 46d7ccda4d49b6c2cc77b1e711771bca7d925610 Mon Sep 17 00:00:00 2001 From: Mikhail Chusavitin Date: Mon, 26 Oct 2026 21:10:24 +0300 Subject: [PATCH] test: verify TLS policies against disposable MariaDB servers (#5) --- bible-local/07-dev.md | 2 + bible-local/issue-plan-2026-10-26.md | 14 ++- internal/mariadb/tls_integration_test.go | 128 +++++++++++++++++++++++ 3 files changed, 143 insertions(+), 1 deletion(-) create mode 100644 internal/mariadb/tls_integration_test.go diff --git a/bible-local/07-dev.md b/bible-local/07-dev.md index 3a177e1..fa0d970 100644 --- a/bible-local/07-dev.md +++ b/bible-local/07-dev.md @@ -10,6 +10,8 @@ go run ./cmd/migrate_project_updated_at go test ./... go vet ./... make security-check # pinned govulncheck, blocks reachable vulnerabilities +# Optional live transport checks; owns disposable Docker containers: +go test -tags integration ./internal/mariadb -run TestMariaDBTLSIntegration -count=1 make build-release make install-hooks ``` diff --git a/bible-local/issue-plan-2026-10-26.md b/bible-local/issue-plan-2026-10-26.md index 35230af..4e7ab9c 100644 --- a/bible-local/issue-plan-2026-10-26.md +++ b/bible-local/issue-plan-2026-10-26.md @@ -12,7 +12,7 @@ on `fix/issue-acceptance-and-migration-safety`. | 1 | [#2](https://git.mchus.pro/mchus/QuoteForge/issues/2) | Block foreign Host/Origin/Referer and cross-site browser requests in both routers; validate API body types; refuse saved-password reuse for a changed host/port/user. Middleware and real setup/runtime router tests reject attacks without changing saved credentials or user data. | Acceptance passed | | 2 | [#4](https://git.mchus.pro/mchus/QuoteForge/issues/4) | Move LOT-bearing cart/rental events to delegated listeners and escaped data attributes; escape BOM and sync output; share HTML escaping; render toast as text. Malicious LOT regression checks and headless Chrome DOM checks pass. | Acceptance passed | | 3 | [#7](https://git.mchus.pro/mchus/QuoteForge/issues/7) | Require a fresh verified archive outside rotation before reset, refuse unsynced/legacy states without explicit force, use transactional deletion, remove environment-triggered reset. Verified refusal, ZIP restore, backup failure, rollback and CLI startup after restore. | Acceptance passed | -| 4 | [#5](https://git.mchus.pro/mchus/QuoteForge/issues/5) | Persist TLS mode/CA in SQLite, expose setup controls, share policy across setup/sync/migration DSNs. Verify certificate trust, hostname checks, plaintext fallback policy and settings round-trip. | Implemented | +| 4 | [#5](https://git.mchus.pro/mchus/QuoteForge/issues/5) | Persist TLS mode/CA in SQLite, expose setup controls, share policy across setup/sync/migration DSNs. Verified certificate trust, hostname checks, fallback policy, settings round-trip and live MariaDB 11.8 transport. | Acceptance passed | | 5 | [#3](https://git.mchus.pro/mchus/QuoteForge/issues/3) | Keep each migration file in one session, execute verify headers before history insertion, propagate FK failures. Verify failed queries/checks never enter history. | Implemented | | 6 | [#6](https://git.mchus.pro/mchus/QuoteForge/issues/6) | Require Go 1.27.3, update vulnerable dependencies, block release on pinned govulncheck. Full tests, vet, security scan and macOS/Windows builds must pass. | Implemented | @@ -79,3 +79,15 @@ The test restores ZIP contents and reopens the database through normal startup: connection settings and the pending queue survive. It deliberately selects `-migrate-status` with an unavailable loopback database to stop startup before HTTP/browser launch; no production database or user state is touched. + +### Issue #5 + +`go test -tags integration ./internal/mariadb -run TestMariaDBTLSIntegration -count=1` +starts its own disposable MariaDB 11.8 containers on random loopback ports, with +TLS enabled and disabled, and removes both afterward. The test verifies the +actual session cipher: preferred encrypts with a TLS server and falls back only +with a plaintext server; required and verification modes reject plaintext. +Correct trust succeeds, unrelated roots and wrong hostname fail. Certificates, +private keys and database storage are temporary; no saved user DSN is used. +The matching image must already exist locally (`docker pull mariadb:11.8`). +Setup policy, local settings and synthetic TLS tests also pass. diff --git a/internal/mariadb/tls_integration_test.go b/internal/mariadb/tls_integration_test.go new file mode 100644 index 0000000..9bcdaad --- /dev/null +++ b/internal/mariadb/tls_integration_test.go @@ -0,0 +1,128 @@ +//go:build integration + +package mariadb + +import ( + "context" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "crypto/x509/pkix" + "database/sql" + "encoding/pem" + "math/big" + "net" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + mysql "github.com/go-sql-driver/mysql" +) + +func TestMariaDBTLSIntegration(t *testing.T) { + dir := t.TempDir() + if err := os.Chmod(dir, 0755); err != nil { + t.Fatal(err) + } + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatal(err) + } + cert := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "example"}, + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), + IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}} + der, err := x509.CreateCertificate(rand.Reader, cert, cert, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + ca := string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})) + for name, data := range map[string][]byte{"server.crt": []byte(ca), "server.key": pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})} { + // Docker's mysql user must read these disposable test files. + if err := os.WriteFile(filepath.Join(dir, name), data, 0644); err != nil { + t.Fatal(err) + } + } + otherCA, _ := testCertificate(t) + for _, tlsEnabled := range []bool{true, false} { + t.Run(map[bool]string{true: "TLS", false: "plaintext"}[tlsEnabled], func(t *testing.T) { + args := []string{"run", "--detach", "--rm", "--pull=never", "-p", "127.0.0.1::3306", + "-e", "MARIADB_ALLOW_EMPTY_ROOT_PASSWORD=1", "-e", "MARIADB_ROOT_HOST=%", "-v", dir + ":/qfs-tls:ro", "mariadb:11.8"} + if tlsEnabled { + args = append(args, "--ssl-cert=/qfs-tls/server.crt", "--ssl-key=/qfs-tls/server.key") + } else { + args = append(args, "--skip-ssl") + } + out, err := exec.Command("docker", args...).CombinedOutput() + if err != nil { + t.Fatalf("start disposable MariaDB: %v: %s", err, out) + } + id := strings.TrimSpace(string(out)) + t.Cleanup(func() { + if out, err := exec.Command("docker", "stop", "-t", "2", id).CombinedOutput(); err != nil { + t.Errorf("stop test MariaDB: %v: %s", err, out) + } + }) + out, err = exec.Command("docker", "port", id, "3306/tcp").CombinedOutput() + if err != nil { + t.Fatalf("test MariaDB port: %v: %s", err, out) + } + addr := strings.TrimSpace(string(out)) + connect := func(mode, roots, serverName string) (string, error) { + cfg := mysql.NewConfig() + cfg.User, cfg.Net, cfg.Addr, cfg.Timeout = "root", "tcp", addr, time.Second + if err := ConfigureTLS(cfg, mode, roots); err != nil { + return "", err + } + cfg, err = mysql.ParseDSN(cfg.FormatDSN()) + if err != nil { + return "", err + } + if serverName != "" { + cfg.TLS.ServerName = serverName + } + connector, err := mysql.NewConnector(cfg) + if err != nil { + return "", err + } + db := sql.OpenDB(connector) + defer db.Close() + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + var name, cipher string + err = db.QueryRowContext(ctx, "SHOW SESSION STATUS LIKE 'Ssl_cipher'").Scan(&name, &cipher) + return cipher, err + } + deadline := time.Now().Add(45 * time.Second) + for { + if _, err := connect("preferred", "", ""); err == nil { + break + } + if time.Now().After(deadline) { + t.Fatal("test MariaDB did not become ready") + } + time.Sleep(100 * time.Millisecond) + } + for _, tt := range []struct { + mode, roots, name string + success bool + }{ + {"preferred", "", "", true}, {"required", "", "", tlsEnabled}, + {"verify-ca", ca, "", tlsEnabled}, {"verify-full", ca, "", tlsEnabled}, + {"verify-ca", otherCA, "", false}, {"verify-full", otherCA, "", false}, + {"verify-full", ca, "wrong.example", false}, + } { + cipher, err := connect(tt.mode, tt.roots, tt.name) + if (err == nil) != tt.success { + t.Errorf("mode=%s name=%s success=%v error=%v", tt.mode, tt.name, tt.success, err) + } + if err == nil && (cipher != "") != tlsEnabled { + t.Errorf("mode=%s cipher=%q TLS=%v", tt.mode, cipher, tlsEnabled) + } + } + }) + } +}