-
Notifications
You must be signed in to change notification settings - Fork 327
/
settings.go
358 lines (293 loc) · 9.16 KB
/
settings.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
package service
import (
"context"
"fmt"
"strings"
"sync"
"time"
"github.com/cortezaproject/corteza/server/pkg/actionlog"
"github.com/spf13/cast"
"github.com/cortezaproject/corteza/server/pkg/errors"
"github.com/cortezaproject/corteza/server/pkg/logger"
"github.com/cortezaproject/corteza/server/pkg/options"
"github.com/cortezaproject/corteza/server/store"
"github.com/cortezaproject/corteza/server/system/types"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type (
settings struct {
actionlog actionlog.Recorder
store store.SettingValues
accessControl accessController
logger *zap.Logger
m sync.RWMutex
webappsConf options.WebappOpt
// Holds reference to the "current" settings that
// are used by the services
current interface{}
// update channel we'll write set of changed settings when change occurs
update chan types.SettingValueSet
listeners []registeredSettingsListener
}
accessController interface {
CanReadSettings(ctx context.Context) bool
CanManageSettings(ctx context.Context) bool
}
SettingsChangeListener func(ctx context.Context, current interface{}, set types.SettingValueSet)
registeredSettingsListener struct {
prefix string
fn SettingsChangeListener
}
)
func Settings(ctx context.Context, s store.SettingValues, log *zap.Logger, ac accessController, al actionlog.Recorder, current interface{}, webappsConf options.WebappOpt) *settings {
svc := &settings{
actionlog: al,
store: s,
accessControl: ac,
logger: log.Named("settings"),
current: current,
webappsConf: webappsConf,
listeners: make([]registeredSettingsListener, 0, 2),
update: make(chan types.SettingValueSet, 0),
}
svc.watch(ctx)
return svc
}
func (svc *settings) Register(prefix string, listener SettingsChangeListener) {
svc.logger.Debug("registering new settings change listener", zap.String("prefix", prefix))
svc.m.Lock()
defer svc.m.Unlock()
svc.listeners = append(svc.listeners, registeredSettingsListener{
prefix: prefix,
fn: listener,
})
}
func (svc *settings) watch(ctx context.Context) {
go func() {
for {
select {
case vv := <-svc.update:
svc.notify(ctx, vv)
case <-ctx.Done():
return
}
}
}()
}
func (svc *settings) notify(ctx context.Context, vv types.SettingValueSet) {
svc.m.RLock()
defer svc.m.RUnlock()
for _, l := range svc.listeners {
go func(l registeredSettingsListener, vv types.SettingValueSet) {
if len(l.prefix) > 0 {
vv = vv.FilterByPrefix(l.prefix)
}
svc.logger.Debug(
"notifying listener",
zap.String("prefix", l.prefix),
zap.Int("changes", len(vv)),
)
if len(vv) > 0 {
l.fn(ctx, svc.current, vv)
}
}(l, vv)
}
}
func (svc *settings) log(ctx context.Context, fields ...zapcore.Field) *zap.Logger {
return logger.AddRequestID(ctx, svc.logger).With(fields...)
}
func (svc *settings) FindByPrefix(ctx context.Context, pp ...string) (types.SettingValueSet, error) {
if !svc.accessControl.CanReadSettings(ctx) {
return nil, SettingsErrNotAllowedToRead()
}
return svc.findByPrefix(ctx, pp...)
}
func (svc *settings) findByPrefix(ctx context.Context, pp ...string) (types.SettingValueSet, error) {
var (
f = types.SettingsFilter{
Prefix: strings.Join(pp, "."),
Check: func(*types.SettingValue) (bool, error) { return true, nil },
}
)
vv, _, err := store.SearchSettingValues(ctx, svc.store, f)
return vv, err
}
func (svc *settings) Get(ctx context.Context, name string, ownedBy uint64) (out *types.SettingValue, err error) {
if !svc.accessControl.CanReadSettings(ctx) {
return nil, SettingsErrNotAllowedToRead()
}
out, err = store.LookupSettingValueByNameOwnedBy(ctx, svc.store, name, ownedBy)
if err != nil && !errors.IsNotFound(err) {
return nil, err
}
return out, nil
}
func (svc *settings) UpdateCurrent(ctx context.Context) error {
if vv, err := svc.findByPrefix(ctx); err != nil {
return err
} else {
return svc.updateCurrent(ctx, vv)
}
}
func (svc *settings) updateCurrent(ctx context.Context, vv types.SettingValueSet) (err error) {
// update current settings with new values
if err = vv.KV().Decode(svc.current); err != nil {
return fmt.Errorf("could not decode settings into KV: %w", err)
}
// push message over update chan so that we can notify all settings listeners
select {
case svc.update <- vv:
case <-ctx.Done():
return ctx.Err()
case <-time.After(time.Second):
svc.logger.Warn("timed-out while waiting to update current settings")
}
return nil
}
func (svc *settings) Set(ctx context.Context, v *types.SettingValue) (err error) {
if !svc.accessControl.CanManageSettings(ctx) {
return SettingsErrNotAllowedToManage()
}
if _, err = check(v); err != nil {
return
}
var current *types.SettingValue
current, err = store.LookupSettingValueByNameOwnedBy(ctx, svc.store, v.Name, v.OwnedBy)
if errors.IsNotFound(err) {
v.UpdatedAt = *now()
err = store.CreateSettingValue(ctx, svc.store, v)
} else if err != nil {
return err
}
if !current.Eq(v) {
v.UpdatedAt = *now()
err = store.UpdateSettingValue(ctx, svc.store, v)
}
if err != nil || current.Eq(v) {
// Return on error or when there is nothing to update (same value)
return
}
svc.logChange(ctx, v)
return svc.updateCurrent(ctx, types.SettingValueSet{v})
}
func (svc *settings) BulkSet(ctx context.Context, vv types.SettingValueSet) (err error) {
if !svc.accessControl.CanManageSettings(ctx) {
return SettingsErrNotAllowedToManage()
}
if _, err = check(vv...); err != nil {
return
}
// Load current settings and get changed values
var current, old, new types.SettingValueSet
if current, err = svc.FindByPrefix(ctx); err != nil {
return
} else {
vv = current.Changed(vv)
_ = vv.Walk(func(v *types.SettingValue) error {
v.UpdatedAt = *now()
return nil
})
old = current.Old(vv)
new = current.New(vv)
}
if err = store.UpdateSettingValue(ctx, svc.store, old...); err != nil {
return
}
if err = store.CreateSettingValue(ctx, svc.store, new...); err != nil {
return
}
if err = store.DeleteSettingValue(ctx, svc.store, vv.Trash()...); err != nil {
return
}
for _, v := range vv {
// if any of webapps stylesheet settings is updated, we need to recompute and update affected theme css
if v.Name == "ui.studio.themes" || v.Name == "ui.studio.custom-css" {
var compStyles *types.SettingValue
if v.Name == "ui.studio.themes" {
compStyles = current.FindByName("ui.studio.custom-css")
} else {
compStyles = current.FindByName("ui.studio.themes")
}
updateCSS(v, current.FindByName(v.Name), compStyles, v.Name, svc.webappsConf.ScssDirPath, svc.logger)
}
svc.logChange(ctx, v)
}
return svc.updateCurrent(ctx, vv)
}
func (svc *settings) logChange(ctx context.Context, v *types.SettingValue) {
svc.log(ctx,
zap.String("name", v.Name),
logger.Uint64("owned-by", v.OwnedBy),
zap.Stringer("value", v.Value)).
WithOptions(zap.AddCallerSkip(1)).
Debug("setting value updated")
}
func (svc *settings) Delete(ctx context.Context, name string, ownedBy uint64) error {
if !svc.accessControl.CanManageSettings(ctx) {
return SettingsErrNotAllowedToManage()
}
current, err := store.LookupSettingValueByNameOwnedBy(ctx, svc.store, name, ownedBy)
if errors.IsNotFound(err) {
return nil
} else if err != nil {
return err
}
err = store.DeleteSettingValue(ctx, svc.store, current)
if err != nil {
return err
}
vv := types.SettingValueSet{current}
svc.log(ctx,
zap.String("name", name),
logger.Uint64("owned-by", ownedBy)).Info("setting value removed")
return svc.updateCurrent(ctx, vv)
}
// Check validates settings values
func check(vv ...*types.SettingValue) (ok bool, err error) {
set := append(types.SettingValueSet{}, vv...)
err = set.Walk(func(val *types.SettingValue) error {
if val == nil || val.Value == nil {
return err
}
vs := val.String()
if len(vs) == 0 && len(val.Value.String()) > 0 {
vs = val.Value.String()
}
// Password constraints: The min password length should be 8
if val.Name == "auth.internal.password-constraints.min-length" {
if cast.ToInt(vs) < passwordMinLength {
return SettingsErrInvalidPasswordMinLength()
}
}
// Password constraints: The min upper case count should not be a negative number
if val.Name == "auth.internal.password-constraints.min-upper-case" {
if cast.ToInt(vs) < 0 {
return SettingsErrInvalidPasswordMinUpperCase()
}
}
// Password constraints: The min lower case count should not be a negative number
if val.Name == "auth.internal.password-constraints.min-lower-case" {
if cast.ToInt(vs) < 0 {
return SettingsErrInvalidPasswordMinLowerCase()
}
}
// Password constraints: The min number of numeric characters should not be a negative number
if val.Name == "auth.internal.password-constraints.min-num-count" {
if cast.ToInt(vs) < 0 {
return SettingsErrInvalidPasswordMinNumCount()
}
}
// Password constraints: The min number of special characters should not be a negative number
if val.Name == "auth.internal.password-constraints.min-special-count" {
if cast.ToInt(vs) < 0 {
return SettingsErrInvalidPasswordMinSpecialCharCount()
}
}
return err
})
if err != nil {
return false, err
}
return true, nil
}