fix: Secure sql connection (#332)

* feat: sql ssl connection

* fix: simpler implementation of ssl-config in sql

* fix(config): set db ssl connection by env vars
This commit is contained in:
Silvan
2020-07-03 12:44:08 +02:00
committed by GitHub
parent a71b5e35d7
commit 6736b2867e
6 changed files with 103 additions and 67 deletions

View File

@@ -21,7 +21,7 @@ type AuthRequestCache struct {
}
func Start(conf Config) (*AuthRequestCache, error) {
client, err := sql.Open("postgres", conf.Connection.ConnectionString())
client, err := conf.Connection.Start()
if err != nil {
return nil, caos_errs.ThrowPreconditionFailed(err, "SQL-9qBtr", "unable to open database connection")
}

View File

@@ -4,35 +4,74 @@ import (
"database/sql"
"strings"
"github.com/caos/logging"
"github.com/caos/zitadel/internal/errors"
)
const (
sslDisabledMode = "disable"
)
type SQL struct {
Host string
Port string
User string
Password string
Database string
SSLmode string
SSL *ssl
}
func (s *SQL) ConnectionString() string {
type ssl struct {
// type of connection security
Mode string
// RootCert Path to the CA certificate
RootCert string
// Cert Path to the client certificate
Cert string
// Key Path to the client private key
Key string
}
func (s *SQL) connectionString() string {
fields := []string{
"host=" + s.Host,
"port=" + s.Port,
"user=" + s.User,
"password=" + s.Password,
"dbname=" + s.Database,
"sslmode=" + s.SSLmode,
"sslmode=" + s.SSL.Mode,
}
if s.SSL.Mode != sslDisabledMode {
fields = append(fields, []string{
"ssl=true",
"sslrootcert=" + s.SSL.RootCert,
"sslcert=" + s.SSL.Cert,
"sslkey=" + s.SSL.Key,
}...)
}
return strings.Join(fields, " ")
}
func (s *SQL) Start() (*sql.DB, error) {
client, err := sql.Open("postgres", s.ConnectionString())
s.checkSSL()
client, err := sql.Open("postgres", s.connectionString())
if err != nil {
return nil, errors.ThrowPreconditionFailed(err, "TYPES-9qBtr", "unable to open database connection")
}
return client, nil
}
func (s *SQL) checkSSL() {
if s.SSL == nil || s.SSL.Mode == sslDisabledMode {
s.SSL = &ssl{Mode: sslDisabledMode}
return
}
if s.SSL.Cert == "" || s.SSL.Key == "" || s.SSL.RootCert == "" {
logging.LogWithFields("TYPES-LFdzP",
"cert set", s.SSL.Cert != "",
"key set", s.SSL.Key != "",
"rootCert set", s.SSL.RootCert != "",
).Fatal("fields for secure connection missing")
}
}

View File

@@ -2,6 +2,7 @@ package repository
import (
"database/sql"
"github.com/caos/zitadel/internal/config/types"
"github.com/caos/zitadel/internal/errors"
"github.com/jinzhu/gorm"
@@ -12,7 +13,7 @@ type ViewConfig struct {
}
func Start(conf ViewConfig) (*sql.DB, *gorm.DB, error) {
sqlClient, err := sql.Open("postgres", conf.SQL.ConnectionString())
sqlClient, err := conf.SQL.Start()
if err != nil {
return nil, nil, errors.ThrowPreconditionFailed(err, "SQL-9qBtr", "unable to open database connection")
}