feat: configure MariaDB TLS for setup and runtime connections (#5)
This commit is contained in:
1 parent
15f81e053c
commit
370407d3ba
9 files changed
+325
-9
No files matched your search
@@ -444,3 +444,12 @@ MariaDB:
|
|||||||
- there is no GORM `AutoMigrate` against MariaDB: it retypes production columns to match the
|
- there is no GORM `AutoMigrate` against MariaDB: it retypes production columns to match the
|
||||||
running binary's models. On 2026-09-24 a stale v1.18 binary run with the old AutoMigrate
|
running binary's models. On 2026-09-24 a stale v1.18 binary run with the old AutoMigrate
|
||||||
`-migrate` did exactly that, which is why it was removed.
|
`-migrate` did exactly that, which is why it was removed.
|
||||||
|
|
||||||
|
## Connection transport
|
||||||
|
|
||||||
|
`connection_settings.tls_mode` defaults to `preferred`; `tls_ca_pem` stores an
|
||||||
|
optional public CA certificate bundle. SQLite startup adds these columns for
|
||||||
|
legacy settings. Every runtime/setup MariaDB DSN uses `internal/mariadb` to
|
||||||
|
apply the policy documented in [05-config.md](05-config.md). Private keys are
|
||||||
|
never part of the CA field. No mode silently falls back to plaintext except
|
||||||
|
`preferred`.
|
||||||
@@ -79,3 +79,17 @@ They are stored in SQLite and encrypted with `local_encryption.key` unless `QUOT
|
|||||||
`QFS_RESET_LOCAL_DB` is no longer supported. Reset requires an explicit CLI flag
|
`QFS_RESET_LOCAL_DB` is no longer supported. Reset requires an explicit CLI flag
|
||||||
on each launch. A forced reset still stops if the safety backup cannot be created
|
on each launch. A forced reset still stops if the safety backup cannot be created
|
||||||
and verified. See [06-backup.md](06-backup.md).
|
and verified. See [06-backup.md](06-backup.md).
|
||||||
|
|
||||||
|
## MariaDB TLS
|
||||||
|
|
||||||
|
`/setup` stores `tls_mode` and `tls_ca_pem` in SQLite `connection_settings`,
|
||||||
|
alongside encrypted credentials. Existing and new connections default to
|
||||||
|
`preferred`, which encrypts when advertised by MariaDB but can fall back to
|
||||||
|
plaintext and does not authenticate the server. `required` mandates encryption
|
||||||
|
without verifying the certificate. `verify-ca` requires a PEM CA and validates
|
||||||
|
the server certificate chain without checking its hostname. `verify-full`
|
||||||
|
validates both chain and hostname, using the supplied PEM or system roots.
|
||||||
|
Only the verification modes accept CA input; invalid modes/PEM are rejected.
|
||||||
|
Use `verify-full` for authenticated server connections. The setup form tests
|
||||||
|
the selected policy before saving. Sync, setup checks and migration tooling
|
||||||
|
share the same TLS configuration builder.
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package handlers
|
package handlers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"html/template"
|
"html/template"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
@@ -13,8 +14,10 @@ import (
|
|||||||
"git.mchus.pro/mchus/quoteforge/internal/appmeta"
|
"git.mchus.pro/mchus/quoteforge/internal/appmeta"
|
||||||
"git.mchus.pro/mchus/quoteforge/internal/db"
|
"git.mchus.pro/mchus/quoteforge/internal/db"
|
||||||
"git.mchus.pro/mchus/quoteforge/internal/localdb"
|
"git.mchus.pro/mchus/quoteforge/internal/localdb"
|
||||||
|
"git.mchus.pro/mchus/quoteforge/internal/mariadb"
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
mysqlDriver "github.com/go-sql-driver/mysql"
|
mysqlDriver "github.com/go-sql-driver/mysql"
|
||||||
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
type SetupHandler struct {
|
type SetupHandler struct {
|
||||||
@@ -83,7 +86,7 @@ func (h *SetupHandler) TestConnection(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
settings, err := h.localDB.GetSettings()
|
settings, err := h.localDB.GetSettings()
|
||||||
if err != nil {
|
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
_ = c.Error(err)
|
_ = c.Error(err)
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to read settings"})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to read settings"})
|
||||||
return
|
return
|
||||||
@@ -94,7 +97,12 @@ func (h *SetupHandler) TestConnection(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
dsn := buildMySQLDSN(host, port, database, user, password, 5*time.Second)
|
tlsMode, caPEM := c.DefaultPostForm("tls_mode", "preferred"), c.PostForm("tls_ca_pem")
|
||||||
|
dsn, err := buildMySQLDSNWithTLS(host, port, database, user, password, 5*time.Second, tlsMode, caPEM)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
lotCount, canWrite, err := db.ValidateMariaDBConnection(dsn)
|
lotCount, canWrite, err := db.ValidateMariaDBConnection(dsn)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = c.Error(err)
|
_ = c.Error(err)
|
||||||
@@ -115,7 +123,12 @@ func (h *SetupHandler) TestConnection(c *gin.Context) {
|
|||||||
|
|
||||||
// SaveConnection saves the connection settings and signals restart
|
// SaveConnection saves the connection settings and signals restart
|
||||||
func (h *SetupHandler) SaveConnection(c *gin.Context) {
|
func (h *SetupHandler) SaveConnection(c *gin.Context) {
|
||||||
existingSettings, _ := h.localDB.GetSettings()
|
existingSettings, settingsErr := h.localDB.GetSettings()
|
||||||
|
if settingsErr != nil && !errors.Is(settingsErr, gorm.ErrRecordNotFound) {
|
||||||
|
_ = c.Error(settingsErr)
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to read settings"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
host := c.PostForm("host")
|
host := c.PostForm("host")
|
||||||
portStr := c.PostForm("port")
|
portStr := c.PostForm("port")
|
||||||
@@ -135,7 +148,12 @@ func (h *SetupHandler) SaveConnection(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Test connection first
|
// Test connection first
|
||||||
dsn := buildMySQLDSN(host, port, database, user, password, 5*time.Second)
|
tlsMode, caPEM := c.DefaultPostForm("tls_mode", "preferred"), c.PostForm("tls_ca_pem")
|
||||||
|
dsn, err := buildMySQLDSNWithTLS(host, port, database, user, password, 5*time.Second, tlsMode, caPEM)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
if _, _, err := db.ValidateMariaDBConnection(dsn); err != nil {
|
if _, _, err := db.ValidateMariaDBConnection(dsn); err != nil {
|
||||||
_ = c.Error(err)
|
_ = c.Error(err)
|
||||||
c.JSON(http.StatusBadRequest, gin.H{
|
c.JSON(http.StatusBadRequest, gin.H{
|
||||||
@@ -146,7 +164,7 @@ func (h *SetupHandler) SaveConnection(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Save settings
|
// Save settings
|
||||||
if err := h.localDB.SaveSettings(host, port, database, user, password); err != nil {
|
if err := h.localDB.SaveSettingsWithTLS(host, port, database, user, password, tlsMode, caPEM); err != nil {
|
||||||
_ = c.Error(err)
|
_ = c.Error(err)
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{
|
c.JSON(http.StatusInternalServerError, gin.H{
|
||||||
"success": false,
|
"success": false,
|
||||||
@@ -169,7 +187,8 @@ func (h *SetupHandler) SaveConnection(c *gin.Context) {
|
|||||||
existingSettings.Port != port ||
|
existingSettings.Port != port ||
|
||||||
existingSettings.Database != database ||
|
existingSettings.Database != database ||
|
||||||
existingSettings.User != user ||
|
existingSettings.User != user ||
|
||||||
existingSettings.PasswordEncrypted != password
|
existingSettings.PasswordEncrypted != password ||
|
||||||
|
existingSettings.TLSMode != tlsMode || existingSettings.TLSCAPEM != caPEM
|
||||||
|
|
||||||
restartQueued := settingsChanged && h.restartSig != nil
|
restartQueued := settingsChanged && h.restartSig != nil
|
||||||
c.JSON(http.StatusOK, gin.H{
|
c.JSON(http.StatusOK, gin.H{
|
||||||
@@ -199,7 +218,7 @@ func (h *SetupHandler) GetStatus(c *gin.Context) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func buildMySQLDSN(host string, port int, database, user, password string, timeout time.Duration) string {
|
func buildMySQLDSNWithTLS(host string, port int, database, user, password string, timeout time.Duration, tlsMode, caPEM string) (string, error) {
|
||||||
cfg := mysqlDriver.NewConfig()
|
cfg := mysqlDriver.NewConfig()
|
||||||
cfg.User = user
|
cfg.User = user
|
||||||
cfg.Passwd = password
|
cfg.Passwd = password
|
||||||
@@ -212,7 +231,10 @@ func buildMySQLDSN(host string, port int, database, user, password string, timeo
|
|||||||
cfg.Params = map[string]string{
|
cfg.Params = map[string]string{
|
||||||
"charset": "utf8mb4",
|
"charset": "utf8mb4",
|
||||||
}
|
}
|
||||||
return cfg.FormatDSN()
|
if err := mariadb.ConfigureTLS(cfg, tlsMode, caPEM); err != nil {
|
||||||
|
return "", fmt.Errorf("configure TLS: %w", err)
|
||||||
|
}
|
||||||
|
return cfg.FormatDSN(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// setupPassword reuses a credential only for its saved destination and account.
|
// setupPassword reuses a credential only for its saved destination and account.
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.mchus.pro/mchus/quoteforge/internal/localdb"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSetupFreshSettingsValidateTLS(t *testing.T) {
|
||||||
|
local, err := localdb.New(filepath.Join(t.TempDir(), "qfs.db"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer local.Close()
|
||||||
|
handler := &SetupHandler{localDB: local}
|
||||||
|
for _, test := range []struct {
|
||||||
|
path string
|
||||||
|
handler gin.HandlerFunc
|
||||||
|
}{{"/setup/test", handler.TestConnection}, {"/setup", handler.SaveConnection}} {
|
||||||
|
router := gin.New()
|
||||||
|
router.POST(test.path, test.handler)
|
||||||
|
body := url.Values{"host": {"db.example"}, "user": {"example"}, "tls_mode": {"invalid"}}.Encode()
|
||||||
|
req := httptest.NewRequest(http.MethodPost, test.path, strings.NewReader(body))
|
||||||
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(w, req)
|
||||||
|
if w.Code != http.StatusUnprocessableEntity {
|
||||||
|
t.Fatalf("%s: status=%d body=%s", test.path, w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@ import (
|
|||||||
|
|
||||||
"git.mchus.pro/mchus/quoteforge/internal/appmeta"
|
"git.mchus.pro/mchus/quoteforge/internal/appmeta"
|
||||||
"git.mchus.pro/mchus/quoteforge/internal/appstate"
|
"git.mchus.pro/mchus/quoteforge/internal/appstate"
|
||||||
|
"git.mchus.pro/mchus/quoteforge/internal/mariadb"
|
||||||
"github.com/glebarez/sqlite"
|
"github.com/glebarez/sqlite"
|
||||||
mysqlDriver "github.com/go-sql-driver/mysql"
|
mysqlDriver "github.com/go-sql-driver/mysql"
|
||||||
uuidpkg "github.com/google/uuid"
|
uuidpkg "github.com/google/uuid"
|
||||||
@@ -24,6 +25,8 @@ import (
|
|||||||
|
|
||||||
// ConnectionSettings stores MariaDB connection credentials
|
// ConnectionSettings stores MariaDB connection credentials
|
||||||
type ConnectionSettings struct {
|
type ConnectionSettings struct {
|
||||||
|
TLSMode string `gorm:"default:preferred"`
|
||||||
|
TLSCAPEM string
|
||||||
ID uint `gorm:"primaryKey"`
|
ID uint `gorm:"primaryKey"`
|
||||||
Host string `gorm:"not null"`
|
Host string `gorm:"not null"`
|
||||||
Port int `gorm:"not null;default:3306"`
|
Port int `gorm:"not null;default:3306"`
|
||||||
@@ -507,6 +510,14 @@ func (l *LocalDB) GetSettings() (*ConnectionSettings, error) {
|
|||||||
|
|
||||||
// SaveSettings saves connection settings with encrypted password
|
// SaveSettings saves connection settings with encrypted password
|
||||||
func (l *LocalDB) SaveSettings(host string, port int, database, user, password string) error {
|
func (l *LocalDB) SaveSettings(host string, port int, database, user, password string) error {
|
||||||
|
return l.SaveSettingsWithTLS(host, port, database, user, password, "preferred", "")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *LocalDB) SaveSettingsWithTLS(host string, port int, database, user, password, tlsMode, caPEM string) error {
|
||||||
|
if err := mariadb.ConfigureTLS(mysqlDriver.NewConfig(), tlsMode, caPEM); err != nil {
|
||||||
|
return fmt.Errorf("validate connection TLS: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
// Encrypt password
|
// Encrypt password
|
||||||
encrypted, err := Encrypt(password)
|
encrypted, err := Encrypt(password)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -515,6 +526,8 @@ func (l *LocalDB) SaveSettings(host string, port int, database, user, password s
|
|||||||
|
|
||||||
settings := ConnectionSettings{
|
settings := ConnectionSettings{
|
||||||
ID: 1, // Always use ID=1 for single settings row
|
ID: 1, // Always use ID=1 for single settings row
|
||||||
|
TLSMode: tlsMode,
|
||||||
|
TLSCAPEM: caPEM,
|
||||||
Host: host,
|
Host: host,
|
||||||
Port: port,
|
Port: port,
|
||||||
Database: database,
|
Database: database,
|
||||||
@@ -560,6 +573,9 @@ func (l *LocalDB) GetDSN() (string, error) {
|
|||||||
"charset": "utf8mb4",
|
"charset": "utf8mb4",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := mariadb.ConfigureTLS(cfg, settings.TLSMode, settings.TLSCAPEM); err != nil {
|
||||||
|
return "", fmt.Errorf("configure connection TLS: %w", err)
|
||||||
|
}
|
||||||
return cfg.FormatDSN(), nil
|
return cfg.FormatDSN(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package localdb
|
||||||
|
|
||||||
|
import (
|
||||||
|
mysql "github.com/go-sql-driver/mysql"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSettingsTLSRoundTrip(t *testing.T) {
|
||||||
|
t.Setenv("QFS_STATE_DIR", t.TempDir())
|
||||||
|
local := newModeDB(t)
|
||||||
|
for _, mode := range []string{"preferred", "required", "verify-full"} {
|
||||||
|
if err := local.SaveSettingsWithTLS("db.example", 3306, "example", "example", "example", mode, ""); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
settings, err := local.GetSettings()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if settings.TLSMode != mode {
|
||||||
|
t.Fatalf("mode=%s, want %s", settings.TLSMode, mode)
|
||||||
|
}
|
||||||
|
dsn, err := local.GetDSN()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cfg, err := mysql.ParseDSN(dsn)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if cfg.TLS == nil || cfg.AllowFallbackToPlaintext != (mode == "preferred") {
|
||||||
|
t.Fatalf("wrong TLS policy for %s", mode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
package mariadb
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"crypto/tls"
|
||||||
|
"crypto/x509"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
mysql "github.com/go-sql-driver/mysql"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ConfigureTLS configures the DSN so setup and runtime use the same TLS policy.
|
||||||
|
func ConfigureTLS(cfg *mysql.Config, mode, caPEM string) error {
|
||||||
|
mode = strings.TrimSpace(mode)
|
||||||
|
if mode == "" {
|
||||||
|
mode = "preferred"
|
||||||
|
}
|
||||||
|
caPEM = strings.TrimSpace(caPEM)
|
||||||
|
if caPEM != "" && mode != "verify-ca" && mode != "verify-full" {
|
||||||
|
return fmt.Errorf("CA certificate requires verify-ca or verify-full")
|
||||||
|
}
|
||||||
|
switch mode {
|
||||||
|
case "preferred":
|
||||||
|
cfg.TLSConfig = "preferred"
|
||||||
|
return nil
|
||||||
|
case "required":
|
||||||
|
cfg.TLSConfig = "skip-verify"
|
||||||
|
return nil
|
||||||
|
case "verify-full":
|
||||||
|
if caPEM == "" {
|
||||||
|
cfg.TLSConfig = "true"
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
case "verify-ca":
|
||||||
|
if caPEM == "" {
|
||||||
|
return fmt.Errorf("verify-ca requires a CA certificate")
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("unsupported MariaDB TLS mode")
|
||||||
|
}
|
||||||
|
roots := x509.NewCertPool()
|
||||||
|
if !roots.AppendCertsFromPEM([]byte(caPEM)) {
|
||||||
|
return fmt.Errorf("invalid CA certificate PEM")
|
||||||
|
}
|
||||||
|
tlsConfig := &tls.Config{MinVersion: tls.VersionTLS12, RootCAs: roots}
|
||||||
|
if mode == "verify-ca" {
|
||||||
|
// Verify the certificate chain explicitly; this mode omits hostname checks.
|
||||||
|
tlsConfig.InsecureSkipVerify = true
|
||||||
|
tlsConfig.VerifyConnection = func(state tls.ConnectionState) error {
|
||||||
|
if len(state.PeerCertificates) == 0 {
|
||||||
|
return fmt.Errorf("MariaDB did not provide a certificate")
|
||||||
|
}
|
||||||
|
intermediates := x509.NewCertPool()
|
||||||
|
for _, cert := range state.PeerCertificates[1:] {
|
||||||
|
intermediates.AddCert(cert)
|
||||||
|
}
|
||||||
|
_, err := state.PeerCertificates[0].Verify(x509.VerifyOptions{Roots: roots, Intermediates: intermediates, KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}})
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("verify MariaDB certificate: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
name := fmt.Sprintf("qfs-%x", sha256.Sum256([]byte(mode+"\n"+caPEM)))
|
||||||
|
if err := mysql.RegisterTLSConfig(name, tlsConfig); err != nil {
|
||||||
|
return fmt.Errorf("register MariaDB TLS: %w", err)
|
||||||
|
}
|
||||||
|
cfg.TLSConfig = name
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
package mariadb
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/elliptic"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/tls"
|
||||||
|
"crypto/x509"
|
||||||
|
"crypto/x509/pkix"
|
||||||
|
"encoding/pem"
|
||||||
|
"math/big"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
mysql "github.com/go-sql-driver/mysql"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTLSPolicy(t *testing.T) {
|
||||||
|
ca, cert := testCertificate(t)
|
||||||
|
_, other := testCertificate(t)
|
||||||
|
for _, tt := range []struct {
|
||||||
|
mode, ca string
|
||||||
|
wantError, fallback, insecure bool
|
||||||
|
}{
|
||||||
|
{"", "", false, true, true},
|
||||||
|
{"preferred", "", false, true, true},
|
||||||
|
{"required", "", false, false, true},
|
||||||
|
{"verify-full", "", false, false, false},
|
||||||
|
{"verify-full", ca, false, false, false},
|
||||||
|
{"verify-ca", ca, false, false, true},
|
||||||
|
{"verify-ca", "", true, false, false},
|
||||||
|
{"verify-full", "invalid", true, false, false},
|
||||||
|
{"preferred", ca, true, false, false},
|
||||||
|
{"false", "", true, false, false},
|
||||||
|
} {
|
||||||
|
t.Run(tt.mode+tt.ca[:min(len(tt.ca), 5)], func(t *testing.T) {
|
||||||
|
cfg := mysql.NewConfig()
|
||||||
|
cfg.Net, cfg.Addr = "tcp", "db.example:3306"
|
||||||
|
err := ConfigureTLS(cfg, tt.mode, tt.ca)
|
||||||
|
if (err != nil) != tt.wantError {
|
||||||
|
t.Fatalf("configure: %v", err)
|
||||||
|
}
|
||||||
|
if tt.wantError {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
parsed, err := mysql.ParseDSN(cfg.FormatDSN())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if parsed.TLS == nil || parsed.AllowFallbackToPlaintext != tt.fallback || parsed.TLS.InsecureSkipVerify != tt.insecure {
|
||||||
|
t.Fatalf("unexpected TLS policy for %s", tt.mode)
|
||||||
|
}
|
||||||
|
if tt.mode == "verify-ca" {
|
||||||
|
if err := parsed.TLS.VerifyConnection(tls.ConnectionState{PeerCertificates: []*x509.Certificate{cert}}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, chain := range [][]*x509.Certificate{nil, {other}} {
|
||||||
|
if err := parsed.TLS.VerifyConnection(tls.ConnectionState{PeerCertificates: chain}); err == nil {
|
||||||
|
t.Fatal("untrusted certificate accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if tt.mode == "verify-full" && tt.ca != "" {
|
||||||
|
if parsed.TLS.ServerName != "db.example" {
|
||||||
|
t.Fatalf("missing hostname verification: %s", parsed.TLS.ServerName)
|
||||||
|
}
|
||||||
|
if _, err := cert.Verify(x509.VerifyOptions{Roots: parsed.TLS.RootCAs, DNSName: parsed.TLS.ServerName}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := other.Verify(x509.VerifyOptions{Roots: parsed.TLS.RootCAs, DNSName: parsed.TLS.ServerName}); err == nil {
|
||||||
|
t.Fatal("untrusted certificate accepted")
|
||||||
|
}
|
||||||
|
if _, err := cert.Verify(x509.VerifyOptions{Roots: parsed.TLS.RootCAs, DNSName: "other.example"}); err == nil {
|
||||||
|
t.Fatal("wrong hostname accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testCertificate(t *testing.T) (string, *x509.Certificate) {
|
||||||
|
t.Helper()
|
||||||
|
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
template := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "example"}, DNSNames: []string{"db.example"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}}
|
||||||
|
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cert, err := x509.ParseCertificate(der)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})), cert
|
||||||
|
}
|
||||||
@@ -75,10 +75,26 @@
|
|||||||
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
|
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
placeholder="{{if .Settings}}********{{else}}password{{end}}">
|
placeholder="{{if .Settings}}********{{else}}password{{end}}">
|
||||||
{{if .Settings}}
|
{{if .Settings}}
|
||||||
<p class="text-xs text-gray-500 mt-1">Оставьте пустым, чтобы сохранить текущий пароль</p>
|
<p class="text-xs text-gray-500 mt-1">Оставьте пустым, чтобы сохранить пароль для того же хоста, порта и пользователя</p>
|
||||||
{{end}}
|
{{end}}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label class="block text-sm font-medium text-gray-700 mb-1" for="tls_mode">TLS</label>
|
||||||
|
<select name="tls_mode" id="tls_mode" class="w-full px-3 py-2 border rounded-md">
|
||||||
|
<option value="preferred" {{if .Settings}}{{if eq .Settings.TLSMode "preferred"}}selected{{end}}{{end}}>Preferred: шифрование, если сервер поддерживает</option>
|
||||||
|
<option value="required" {{if .Settings}}{{if eq .Settings.TLSMode "required"}}selected{{end}}{{end}}>Required: обязательное шифрование</option>
|
||||||
|
<option value="verify-ca" {{if .Settings}}{{if eq .Settings.TLSMode "verify-ca"}}selected{{end}}{{end}}>Verify CA: проверка сертификата</option>
|
||||||
|
<option value="verify-full" {{if .Settings}}{{if eq .Settings.TLSMode "verify-full"}}selected{{end}}{{end}}>Verify full: проверка сертификата и имени сервера</option>
|
||||||
|
</select>
|
||||||
|
<p class="text-xs text-gray-500 mt-1">Preferred допускает соединение без TLS. Для проверки подлинности сервера выберите Verify full.</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="block text-sm font-medium text-gray-700 mb-1" for="tls_ca_pem">CA-сертификат (PEM)</label>
|
||||||
|
<textarea name="tls_ca_pem" id="tls_ca_pem" rows="3" class="w-full px-3 py-2 border rounded-md font-mono text-xs">{{if .Settings}}{{.Settings.TLSCAPEM}}{{end}}</textarea>
|
||||||
|
<p class="text-xs text-gray-500 mt-1">Для Verify CA обязателен; Verify full без PEM использует системные сертификаты.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div id="status" class="hidden p-3 rounded-md text-sm"></div>
|
<div id="status" class="hidden p-3 rounded-md text-sm"></div>
|
||||||
|
|
||||||
<div class="flex space-x-3 pt-4 mt-auto">
|
<div class="flex space-x-3 pt-4 mt-auto">
|
||||||
|
|||||||
Reference in new issue
Block a user