diff --git a/bible-local/03-database.md b/bible-local/03-database.md index 10fd1c6..29c99e1 100644 --- a/bible-local/03-database.md +++ b/bible-local/03-database.md @@ -444,3 +444,12 @@ MariaDB: - 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 `-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`. diff --git a/bible-local/05-config.md b/bible-local/05-config.md index bcad189..fcf1236 100644 --- a/bible-local/05-config.md +++ b/bible-local/05-config.md @@ -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 on each launch. A forced reset still stops if the safety backup cannot be created 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. diff --git a/internal/handlers/setup.go b/internal/handlers/setup.go index 567b268..f341fa1 100644 --- a/internal/handlers/setup.go +++ b/internal/handlers/setup.go @@ -1,6 +1,7 @@ package handlers import ( + "errors" "fmt" "html/template" "log/slog" @@ -13,8 +14,10 @@ import ( "git.mchus.pro/mchus/quoteforge/internal/appmeta" "git.mchus.pro/mchus/quoteforge/internal/db" "git.mchus.pro/mchus/quoteforge/internal/localdb" + "git.mchus.pro/mchus/quoteforge/internal/mariadb" "github.com/gin-gonic/gin" mysqlDriver "github.com/go-sql-driver/mysql" + "gorm.io/gorm" ) type SetupHandler struct { @@ -83,7 +86,7 @@ func (h *SetupHandler) TestConnection(c *gin.Context) { } settings, err := h.localDB.GetSettings() - if err != nil { + if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { _ = c.Error(err) c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to read settings"}) return @@ -94,7 +97,12 @@ func (h *SetupHandler) TestConnection(c *gin.Context) { 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) if err != nil { _ = c.Error(err) @@ -115,7 +123,12 @@ func (h *SetupHandler) TestConnection(c *gin.Context) { // SaveConnection saves the connection settings and signals restart 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") portStr := c.PostForm("port") @@ -135,7 +148,12 @@ func (h *SetupHandler) SaveConnection(c *gin.Context) { } // 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 { _ = c.Error(err) c.JSON(http.StatusBadRequest, gin.H{ @@ -146,7 +164,7 @@ func (h *SetupHandler) SaveConnection(c *gin.Context) { } // 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.JSON(http.StatusInternalServerError, gin.H{ "success": false, @@ -169,7 +187,8 @@ func (h *SetupHandler) SaveConnection(c *gin.Context) { existingSettings.Port != port || existingSettings.Database != database || existingSettings.User != user || - existingSettings.PasswordEncrypted != password + existingSettings.PasswordEncrypted != password || + existingSettings.TLSMode != tlsMode || existingSettings.TLSCAPEM != caPEM restartQueued := settingsChanged && h.restartSig != nil 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.User = user cfg.Passwd = password @@ -212,7 +231,10 @@ func buildMySQLDSN(host string, port int, database, user, password string, timeo cfg.Params = map[string]string{ "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. diff --git a/internal/handlers/setup_tls_test.go b/internal/handlers/setup_tls_test.go new file mode 100644 index 0000000..0813a3a --- /dev/null +++ b/internal/handlers/setup_tls_test.go @@ -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()) + } + } +} diff --git a/internal/localdb/localdb.go b/internal/localdb/localdb.go index bd2cbf5..9ee1fdc 100644 --- a/internal/localdb/localdb.go +++ b/internal/localdb/localdb.go @@ -14,6 +14,7 @@ import ( "git.mchus.pro/mchus/quoteforge/internal/appmeta" "git.mchus.pro/mchus/quoteforge/internal/appstate" + "git.mchus.pro/mchus/quoteforge/internal/mariadb" "github.com/glebarez/sqlite" mysqlDriver "github.com/go-sql-driver/mysql" uuidpkg "github.com/google/uuid" @@ -24,6 +25,8 @@ import ( // ConnectionSettings stores MariaDB connection credentials type ConnectionSettings struct { + TLSMode string `gorm:"default:preferred"` + TLSCAPEM string ID uint `gorm:"primaryKey"` Host string `gorm:"not null"` Port int `gorm:"not null;default:3306"` @@ -507,6 +510,14 @@ func (l *LocalDB) GetSettings() (*ConnectionSettings, error) { // SaveSettings saves connection settings with encrypted password 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 encrypted, err := Encrypt(password) if err != nil { @@ -515,6 +526,8 @@ func (l *LocalDB) SaveSettings(host string, port int, database, user, password s settings := ConnectionSettings{ ID: 1, // Always use ID=1 for single settings row + TLSMode: tlsMode, + TLSCAPEM: caPEM, Host: host, Port: port, Database: database, @@ -560,6 +573,9 @@ func (l *LocalDB) GetDSN() (string, error) { "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 } diff --git a/internal/localdb/settings_tls_test.go b/internal/localdb/settings_tls_test.go new file mode 100644 index 0000000..9a87aa3 --- /dev/null +++ b/internal/localdb/settings_tls_test.go @@ -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) + } + } +} diff --git a/internal/mariadb/tls.go b/internal/mariadb/tls.go new file mode 100644 index 0000000..118f48f --- /dev/null +++ b/internal/mariadb/tls.go @@ -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 +} diff --git a/internal/mariadb/tls_test.go b/internal/mariadb/tls_test.go new file mode 100644 index 0000000..eb27806 --- /dev/null +++ b/internal/mariadb/tls_test.go @@ -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 +} diff --git a/web/templates/setup.html b/web/templates/setup.html index 5f38e1a..55346d4 100644 --- a/web/templates/setup.html +++ b/web/templates/setup.html @@ -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" placeholder="{{if .Settings}}********{{else}}password{{end}}"> {{if .Settings}} -
Оставьте пустым, чтобы сохранить текущий пароль
+Оставьте пустым, чтобы сохранить пароль для того же хоста, порта и пользователя
{{end}} +Preferred допускает соединение без TLS. Для проверки подлинности сервера выберите Verify full.
+Для Verify CA обязателен; Verify full без PEM использует системные сертификаты.
+