-
Notifications
You must be signed in to change notification settings - Fork 140
/
mysql.go
213 lines (173 loc) · 5.62 KB
/
mysql.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
// Copyright 2021-2024 Zenauth Ltd.
// SPDX-License-Identifier: Apache-2.0
package mysql
import (
"context"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"os"
"github.com/doug-martin/goqu/v9"
// Import the MySQL dialect.
_ "github.com/doug-martin/goqu/v9/dialect/mysql"
"github.com/go-sql-driver/mysql"
"github.com/cerbos/cerbos/internal/config"
"github.com/cerbos/cerbos/internal/observability/logging"
"github.com/cerbos/cerbos/internal/policy"
"github.com/cerbos/cerbos/internal/storage"
"github.com/cerbos/cerbos/internal/storage/db/internal"
)
const (
DriverName = "mysql"
urlToSchemaDocs = "https://docs.cerbos.dev/cerbos/latest/configuration/storage.html#mysql-schema"
constraintViolationErrCode = 1062
)
var (
_ storage.SourceStore = (*Store)(nil)
_ storage.MutableStore = (*Store)(nil)
)
func init() {
storage.RegisterDriver(DriverName, func(ctx context.Context, confW *config.Wrapper) (storage.Store, error) {
conf := new(Conf)
if err := confW.GetSection(conf); err != nil {
return nil, err
}
return NewStore(ctx, conf)
})
}
func NewStore(ctx context.Context, conf *Conf) (*Store, error) {
log := logging.FromContext(ctx).Named("mysql")
log.Info("Initializing MySQL storage")
dsn, err := buildDSN(conf)
if err != nil {
return nil, err
}
db, err := internal.ConnectWithRetries("mysql", dsn, conf.ConnRetry)
if err != nil {
return nil, fmt.Errorf("failed to connect to database: %w", err)
}
conf.ConnPool.Configure(db)
s, err := internal.NewDBStorage(ctx, goqu.New("mysql", db), internal.WithUpsertPolicy(upsertPolicy), internal.WithSourceAttributes(policy.SourceDriver(DriverName)))
if err != nil {
return nil, err
}
if !conf.SkipSchemaCheck {
if err := s.CheckSchema(ctx); err != nil {
return nil, fmt.Errorf("schema check failed. Ensure that the schema is correctly defined as documented at %s: %w", urlToSchemaDocs, err)
}
}
return &Store{DBStorage: s}, nil
}
func buildDSN(conf *Conf) (string, error) {
if err := registerTLS(conf); err != nil {
return "", err
}
if err := registerServerPubKeys(conf); err != nil {
return "", err
}
dbConf, err := mysql.ParseDSN(conf.DSN)
if err != nil {
return "", fmt.Errorf("failed to parse DSN: %w", err)
}
return dbConf.FormatDSN(), nil
}
func registerTLS(conf *Conf) error {
for name, tlsConf := range conf.TLS {
cert, err := tls.LoadX509KeyPair(tlsConf.Cert, tlsConf.Key)
if err != nil {
return fmt.Errorf("failed to load TLS certificate: %w", err)
}
// Most MySQL versions have not caught up to modern TLS settings so we can't use utils.DefaultTLSConfig here.
c := &tls.Config{Certificates: []tls.Certificate{cert}} //nolint:gosec
if tlsConf.CACert != "" {
caPEM, err := os.ReadFile(tlsConf.CACert)
if err != nil {
return fmt.Errorf("failed to load CA certificate: %w", err)
}
certPool := x509.NewCertPool()
if ok := certPool.AppendCertsFromPEM(caPEM); !ok {
return errors.New("failed to add CA certificate to pool")
}
c.RootCAs = certPool
}
if err := mysql.RegisterTLSConfig(name, c); err != nil {
return err
}
}
return nil
}
func registerServerPubKeys(conf *Conf) error {
for name, pkPath := range conf.ServerPubKey {
data, err := os.ReadFile(pkPath)
if err != nil {
return fmt.Errorf("failed to read public key from [%s]: %w", pkPath, err)
}
block, _ := pem.Decode(data)
if block == nil || block.Type != "PUBLIC KEY" {
return fmt.Errorf("file does not contain a valid public key: %s", pkPath)
}
pk, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return fmt.Errorf("failed to parse public key; %w", err)
}
rsaPK, ok := pk.(*rsa.PublicKey)
if !ok {
return fmt.Errorf("file does not contain a RSA public key: %s", pkPath)
}
mysql.RegisterServerPubKey(name, rsaPK)
}
return nil
}
func upsertPolicy(ctx context.Context, tx *goqu.TxDatabase, p policy.Wrapper) error {
pr := internal.Policy{
ID: p.ID,
Kind: p.Kind.String(),
Name: p.Name,
Version: p.Version,
Scope: p.Scope,
Description: p.Description,
Disabled: p.Disabled,
Definition: internal.PolicyDefWrapper{Policy: p.Policy},
}
if _, err := tx.Insert(internal.PolicyTbl).Prepared(true).Rows(pr).Executor().ExecContext(ctx); err != nil {
mysqlErr := new(mysql.MySQLError)
if !errors.As(err, &mysqlErr) || mysqlErr.Number != constraintViolationErrCode {
return fmt.Errorf("failed to insert policy %s: %w", p.FQN, err)
}
// Check if the existing policy name matches the name of the policy we are trying to insert.
// The reason for not doing an UPDATE WHERE and checking the number of affected rows is because MySQL
// returns 0 if the update did not change any of the columns as well.
var existingName string
ok, err := tx.Select(goqu.C(internal.PolicyTblNameCol)).
From(internal.PolicyTbl).
Where(goqu.C(internal.PolicyTblIDCol).Eq(pr.ID)).
Executor().ScanValContext(ctx, &existingName)
if !ok || err != nil {
return fmt.Errorf("failed to lookup policy %s: %w", p.FQN, err)
}
if existingName != pr.Name {
return fmt.Errorf("failed to insert policy %s.%s: %w", p.Name, p.Version, storage.ErrPolicyIDCollision)
}
// attempt update
if _, err := tx.Update(internal.PolicyTbl).
Prepared(true).
Set(pr).
Where(goqu.And(
goqu.C(internal.PolicyTblIDCol).Eq(pr.ID),
goqu.C(internal.PolicyTblNameCol).Eq(pr.Name),
)).Executor().ExecContext(ctx); err != nil {
return fmt.Errorf("failed to update policy %s: %w", p.FQN, err)
}
return nil
}
return nil
}
type Store struct {
internal.DBStorage
}
func (s *Store) Driver() string {
return DriverName
}