-
Notifications
You must be signed in to change notification settings - Fork 139
/
Copy pathadmin_api.go
2390 lines (2039 loc) · 76.7 KB
/
admin_api.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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
// in that file, in accordance with the Business Source License, use of this
// software will be governed by the Apache License, Version 2.0, included in
// the file licenses/APL2.txt.
package rest
import (
"bytes"
"cmp"
"context"
"errors"
"fmt"
"io"
"net/http"
"strings"
"sync/atomic"
"time"
"github.com/couchbase/sync_gateway/auth"
"github.com/couchbase/sync_gateway/base"
"github.com/couchbase/sync_gateway/db"
"github.com/google/uuid"
"github.com/gorilla/mux"
pkgerrors "github.com/pkg/errors"
)
const kDefaultDBOnlineDelay = 0
const paramDisableOIDCValidation = "disable_oidc_validation"
// GetUsers - GET /{db}/_user/
const paramNameOnly = "name_only"
const paramLimit = "limit"
const paramDeleted = "deleted"
// ////// DATABASE MAINTENANCE:
// "Create" a database (actually just register an existing bucket)
func (h *handler) handleCreateDB() error {
contextNoCancel := base.NewNonCancelCtx()
h.assertAdminOnly()
dbName := h.PathVar("newdb")
rawBytes, config, err := h.readSanitizeDbConfigJSON()
if err != nil {
return err
}
validateOIDC := !h.getBoolQuery(paramDisableOIDCValidation)
if config.Name != "" && dbName != config.Name {
return base.HTTPErrorf(http.StatusBadRequest, "When providing a name in the JSON body (%s), ensure it matches the name in the path (%s).", config.Name, dbName)
}
config.Name = dbName
if h.server.persistentConfig {
if err := config.validatePersistentDbConfig(); err != nil {
return base.NewHTTPError(http.StatusBadRequest, err.Error())
}
validateReplications := true
if err := config.validate(h.ctx(), validateOIDC, validateReplications); err != nil {
return base.NewHTTPError(http.StatusBadRequest, err.Error())
}
version, err := GenerateDatabaseConfigVersionID(h.ctx(), "", config)
if err != nil {
return err
}
bucket := config.GetBucketName()
// Before computing metadata ID or taking a copy of the "persistedDbConfig", stamp bucket if missing...
// Ensures all newly persisted configs have a bucket field set to detect bucket moves via backup/restore or XDCR
if config.Bucket == nil {
config.Bucket = &bucket
}
metadataID, metadataIDError := h.server.BootstrapContext.ComputeMetadataIDForDbConfig(h.ctx(), config)
if metadataIDError != nil {
base.WarnfCtx(h.ctx(), "Unable to compute metadata ID - using standard metadataID. Error: %v", metadataIDError)
metadataID = h.server.BootstrapContext.standardMetadataID(config.Name)
}
// copy config before setup to persist the raw config the user supplied
var persistedDbConfig DbConfig
if err := base.DeepCopyInefficient(&persistedDbConfig, config); err != nil {
return base.HTTPErrorf(http.StatusInternalServerError, "couldn't create copy of db config: %v", err)
}
dbCreds, _ := h.server.Config.DatabaseCredentials[dbName]
bucketCreds, _ := h.server.Config.BucketCredentials[bucket]
if err := config.setup(h.ctx(), dbName, h.server.Config.Bootstrap, dbCreds, bucketCreds, h.server.Config.IsServerless()); err != nil {
return err
}
loadedConfig := DatabaseConfig{
Version: version,
MetadataID: metadataID,
DbConfig: *config,
}
persistedConfig := DatabaseConfig{
Version: version,
MetadataID: metadataID,
DbConfig: persistedDbConfig,
SGVersion: base.ProductVersion.String(),
}
h.server.lock.Lock()
defer h.server.lock.Unlock()
if _, exists := h.server.databases_[dbName]; exists {
return base.HTTPErrorf(http.StatusPreconditionFailed, // what CouchDB returns
"Duplicate database name %q", dbName)
}
_, err = h.server._applyConfig(contextNoCancel, loadedConfig, true, false, false)
if err != nil {
return databaseLoadErrorAsHTTPError(err)
}
// now we've started the db successfully, we can persist it to the cluster first checking if this db used to be a corrupt db
// if it used to be corrupt we need to remove it from the invalid database map on server context and remove the old corrupt config from the bucket
err = h.removeCorruptConfigIfExists(contextNoCancel.Ctx, bucket, h.server.Config.Bootstrap.ConfigGroupID, dbName)
if err != nil {
// we cannot continue on with database creation with possibility of the corrupt database config in the bucket for this db
// thus we need to unload the requested database config to prevent the cluster being in an inconsistent state
h.server._removeDatabase(contextNoCancel.Ctx, dbName)
return err
}
cas, err := h.server.BootstrapContext.InsertConfig(contextNoCancel.Ctx, bucket, h.server.Config.Bootstrap.ConfigGroupID, &persistedConfig)
if err != nil {
// unload the requested database config to prevent the cluster being in an inconsistent state
h.server._removeDatabase(contextNoCancel.Ctx, dbName)
var httpError *base.HTTPError
if errors.As(err, &httpError) {
// Collection conflict returned as http error with conflict details
return err
} else if errors.Is(err, base.ErrAuthError) {
return base.HTTPErrorf(http.StatusForbidden, "auth failure accessing provided bucket using bootstrap credentials: %s", bucket)
} else if errors.Is(err, base.ErrAlreadyExists) {
// on-demand config load if someone else beat us to db creation
if _, err := h.server._fetchAndLoadDatabase(contextNoCancel, dbName, false); err != nil {
base.WarnfCtx(h.ctx(), "Couldn't load database after conflicting create: %v", err)
}
return base.HTTPErrorf(http.StatusPreconditionFailed, // what CouchDB returns
"Duplicate database name %q", dbName)
}
return base.HTTPErrorf(http.StatusInternalServerError, "couldn't save database config: %v", err)
}
// store the cas in the loaded config after a successful insert
h.server.dbConfigs[dbName].cfgCas = cas
} else {
// Intentionally pass in an empty BootstrapConfig to avoid inheriting any credentials or server when running with a legacy config (CBG-1764)
if err := config.setup(h.ctx(), dbName, BootstrapConfig{}, nil, nil, false); err != nil {
return err
}
// load database in-memory for non-persistent nodes
if _, err := h.server.AddDatabaseFromConfigFailFast(contextNoCancel, DatabaseConfig{DbConfig: *config}); err != nil {
return databaseLoadErrorAsHTTPError(err)
}
}
configStr, err := redactConfigAsStr(h.ctx(), string(rawBytes))
if err != nil {
base.WarnfCtx(h.ctx(), "Error redacting config for audit logging: %v", err)
}
base.Audit(h.ctx(), base.AuditIDCreateDatabase,
base.AuditFields{
base.AuditFieldDatabase: dbName,
base.AuditFieldPayload: configStr,
},
)
return base.HTTPErrorf(http.StatusCreated, "created")
}
// getAuthScopeHandleCreateDB determines the auth scope for a PUT /{db}/ request.
// This is a special case because we don't have a database initialized yet, so we need to infer the bucket from db config.
func getAuthScopeHandleCreateDB(ctx context.Context, h *handler) (bucketName string, err error) {
// grab a copy of the request body and restore body buffer for later handlers
bodyJSON, readErr := h.readBody()
if readErr != nil {
return "", base.HTTPErrorf(http.StatusInternalServerError, "Unable to read body: %v", readErr)
}
// mark the body as already read to avoid double-counting bytes for stats once it gets read again
h.requestBody.bodyRead = true
h.requestBody.reader = io.NopCloser(bytes.NewReader(bodyJSON))
var dbConfigBody struct {
Bucket string `json:"bucket"`
}
bodyJSON, err = sanitiseConfig(ctx, bodyJSON, h.server.Config.Unsupported.AllowDbConfigEnvVars)
if err != nil {
return "", err
}
d := base.JSONDecoder(bytes.NewBuffer(bodyJSON))
err = d.Decode(&dbConfigBody)
if err != nil {
return "", err
}
if dbConfigBody.Bucket == "" {
dbName := h.PathVar("newdb")
if dbName == "" {
return "", base.HTTPErrorf(http.StatusBadRequest, "bucket or db name not specified in request")
}
// imply bucket name from db name in path if not in body
return dbName, nil
}
return dbConfigBody.Bucket, nil
}
// Take a DB online, first reload the DB config
func (h *handler) handleDbOnline() error {
h.assertAdminOnly()
dbState := atomic.LoadUint32(&h.db.State)
// If the DB is already transitioning to: online or is online silently return
if dbState == db.DBOnline || dbState == db.DBStarting {
return nil
}
// If the DB is currently re-syncing return an error asking the user to retry later
if dbState == db.DBResyncing {
return base.HTTPErrorf(http.StatusServiceUnavailable, "Database _resync is in progress, this may take some time, try again later")
}
body, err := h.readBody()
if err != nil {
return err
}
var input struct {
Delay int `json:"delay"`
}
input.Delay = kDefaultDBOnlineDelay
_ = base.JSONUnmarshal(body, &input)
base.InfofCtx(h.ctx(), base.KeyCRUD, "Taking Database : %v, online in %v seconds", base.MD(h.db.Name), input.Delay)
go func() {
time.Sleep(time.Duration(input.Delay) * time.Second)
h.server.TakeDbOnline(base.NewNonCancelCtx(), h.db.DatabaseContext)
}()
base.Audit(h.ctx(), base.AuditIDDatabaseOnline, nil)
return nil
}
// Take a DB offline
func (h *handler) handleDbOffline() error {
h.assertAdminOnly()
if err := h.db.TakeDbOffline(base.NewNonCancelCtx(), "ADMIN Request"); err != nil {
base.InfofCtx(h.ctx(), base.KeyCRUD, "Unable to take Database : %v, offline", base.MD(h.db.Name))
return err
}
base.Audit(h.ctx(), base.AuditIDDatabaseOffline, nil)
return nil
}
// handleIndexInit allows async index initialization status to be viewed
func (h *handler) handleGetIndexInit() error {
b, err := h.db.AsyncIndexInitManager.GetStatus(h.ctx())
if err != nil {
return err
}
h.writeRawJSON(b)
return nil
}
type PostIndexInitRequest struct {
NumPartitions *uint32 `json:"num_partitions"`
}
func (req PostIndexInitRequest) Validate() error {
if req.NumPartitions == nil {
return base.HTTPErrorf(http.StatusBadRequest, "num_partitions is required")
}
if *req.NumPartitions < 1 {
return base.HTTPErrorf(http.StatusBadRequest, "num_partitions must be greater than 0")
}
return nil
}
// handleIndexInit allows async index initialization to be run or managed
func (h *handler) handlePostIndexInit() error {
action := cmp.Or(h.getQuery("action"), "start")
if action == "stop" {
h.server.DatabaseInitManager.Cancel(h.db.Name)
if err := h.db.AsyncIndexInitManager.Stop(); err != nil {
return err
}
b, err := h.db.AsyncIndexInitManager.GetStatus(h.ctx())
if err != nil {
return err
}
h.writeRawJSON(b)
return nil
}
if action != "start" {
return base.HTTPErrorf(http.StatusBadRequest, "action %q not supported... must be either 'start' or 'stop'", action)
}
var req PostIndexInitRequest
if err := h.readJSONInto(&req); err != nil {
return err
}
if err := req.Validate(); err != nil {
return err
}
currentDbConfig := h.server.GetDatabaseConfig(h.db.Name)
if currentDbConfig.NumIndexPartitions() == *req.NumPartitions {
return base.HTTPErrorf(http.StatusBadRequest, "num_partitions is already %d", *req.NumPartitions)
}
if h.db.UseViews() {
return base.HTTPErrorf(http.StatusBadRequest, "_index_init is a GSI-only feature and is not supported when using views")
}
var newDbConfig DatabaseConfig
if err := base.DeepCopyInefficient(&newDbConfig, currentDbConfig); err != nil {
return err
}
newDbConfig.Index.NumPartitions = req.NumPartitions
var statusMap = make(db.IndexStatusByCollection, len(newDbConfig.Scopes))
for scope := range newDbConfig.Scopes {
statusMap[scope] = make(map[string]db.CollectionIndexStatus)
}
// init _default scope because it's still possible that a named scope can still initialize metadata indexes in _default._default
if _, ok := statusMap[base.DefaultScope]; !ok {
statusMap[base.DefaultScope] = make(map[string]db.CollectionIndexStatus, 1)
}
var statusCallback CollectionCallbackFunc = func(dbName string, scName base.ScopeAndCollectionName, status db.CollectionIndexStatus) {
statusMap[scName.ScopeName()][scName.CollectionName()] = status
if err := h.db.AsyncIndexInitManager.UpdateStatusClusterAware(h.ctx()); err != nil {
base.WarnfCtx(h.ctx(), "Unable to update async index job status on cluster : %v", err)
}
}
useLegacySyncDocsIndex := true // TODO: CBG-4615: Change when this API is updated to support the new principal indexes
done, err := h.server.DatabaseInitManager.InitializeDatabaseWithStatusCallback(h.ctx(), h.server.initialStartupConfig, &newDbConfig, statusCallback, useLegacySyncDocsIndex)
if err != nil {
return err
}
opts := map[string]interface{}{
"statusMap": &statusMap,
"doneChan": done,
}
err = h.db.AsyncIndexInitManager.Start(h.ctx(), opts)
if err != nil {
return err
}
b, err := h.db.AsyncIndexInitManager.GetStatus(h.ctx())
if err != nil {
return err
}
h.writeRawJSON(b)
return nil
}
// Get admin database info
func (h *handler) handleGetDbConfig() error {
if redact, _ := h.getOptBoolQuery("redact", true); !redact {
return base.HTTPErrorf(http.StatusBadRequest, "redact=false is no longer supported")
}
// load config from bucket once for:
// - Populate an up to date ETag header
// - Applying if refresh_config is set
// - Returning if include_runtime=false
var responseConfig *DbConfig
if h.server.BootstrapContext.Connection != nil {
found, dbConfig, err := h.server.fetchDatabase(h.ctx(), h.db.Name)
if err != nil {
return err
}
if !found || dbConfig == nil {
return base.HTTPErrorf(http.StatusNotFound, "database config not found")
}
h.setEtag(dbConfig.Version)
// refresh_config=true forces the config loaded out of the bucket to be applied on the node
if h.getBoolQuery("refresh_config") && h.server.BootstrapContext.Connection != nil {
// set cas=0 to force a refresh
dbConfig.cfgCas = 0
h.server.applyConfigs(h.ctx(), map[string]DatabaseConfig{h.db.Name: *dbConfig})
}
responseConfig = &dbConfig.DbConfig
// Strip out bootstrap credentials that are stamped into the config
responseConfig.Username = ""
responseConfig.Password = ""
responseConfig.CACertPath = ""
responseConfig.KeyPath = ""
responseConfig.CertPath = ""
} else {
// non-persistent mode just returns running database config
responseConfig = h.server.GetDbConfig(h.db.Name)
}
// include_runtime controls whether to return the raw bucketDbConfig, or the runtime version populated with default values, etc.
includeRuntime, _ := h.getOptBoolQuery("include_runtime", false)
if includeRuntime {
var err error
responseConfig, err = MergeDatabaseConfigWithDefaults(h.server.Config, h.server.GetDbConfig(h.db.Name))
if err != nil {
return err
}
}
// defensive check - there could've been an in-flight request to remove the database between entering the handler and getting the config above.
if responseConfig == nil {
return base.HTTPErrorf(http.StatusNotFound, "database config not found")
}
var err error
responseConfig, err = responseConfig.Redacted(h.ctx())
if err != nil {
return err
}
// include_javascript=false omits config fields that contain javascript code
includeJavascript, _ := h.getOptBoolQuery("include_javascript", true)
if !includeJavascript {
responseConfig.Sync = nil
responseConfig.ImportFilter = nil
if responseConfig.EventHandlers != nil {
for _, evt := range responseConfig.EventHandlers.DocumentChanged {
evt.Filter = ""
}
for _, evt := range responseConfig.EventHandlers.DBStateChanged {
evt.Filter = ""
}
}
}
base.Audit(h.ctx(), base.AuditIDReadDatabaseConfig, nil)
h.writeJSON(responseConfig)
return nil
}
type RunTimeServerConfigResponse struct {
*StartupConfig
RuntimeInformation `json:"runtime_information"`
Databases map[string]*DbConfig `json:"databases"`
}
// RuntimeInformation is a struct that holds runtime-only info in without interfering or being lost inside the actual StartupConfig properties.
type RuntimeInformation struct {
ClusterUUID string `json:"cluster_uuid"`
}
// Get admin config info
func (h *handler) handleGetConfig() error {
if redact, _ := h.getOptBoolQuery("redact", true); !redact {
return base.HTTPErrorf(http.StatusBadRequest, "redact=false is no longer supported")
}
includeRuntime, _ := h.getOptBoolQuery("include_runtime", false)
if includeRuntime {
cfg := RunTimeServerConfigResponse{}
var err error
allDbNames := h.server.AllDatabaseNames()
databaseMap := make(map[string]*DbConfig, len(allDbNames))
cfg.StartupConfig, err = h.server.Config.Redacted()
if err != nil {
return err
}
for _, dbName := range allDbNames {
// defensive check - in-flight requests could've removed this database since we got the name of it
dbConfig := h.server.GetDbConfig(dbName)
if dbConfig == nil {
continue
}
dbConfig, err := MergeDatabaseConfigWithDefaults(h.server.Config, dbConfig)
if err != nil {
return err
}
databaseMap[dbName], err = dbConfig.Redacted(h.ctx())
if err != nil {
return err
}
}
for dbName, dbConfig := range databaseMap {
database, err := h.server.GetDatabase(h.ctx(), dbName)
if err != nil {
return err
}
replications, err := database.SGReplicateMgr.GetReplications()
if err != nil {
return err
}
dbConfig.Replications = make(map[string]*db.ReplicationConfig, len(replications))
for replicationName, replicationConfig := range replications {
dbConfig.Replications[replicationName] = replicationConfig.ReplicationConfig.Redacted(h.ctx())
}
}
// grab cluster uuid for runtime config
clusterUUID, err := h.server.getClusterUUID(h.ctx())
if err != nil {
base.InfofCtx(h.ctx(), base.KeyConfig, "Could not determine cluster UUID: %s", err)
}
cfg.ClusterUUID = clusterUUID
// because loggers can be changed at runtime, we need to work backwards to get the config that would've created the actually running instances
cfg.Logging = *base.BuildLoggingConfigFromLoggers(h.server.Config.Logging)
cfg.Databases = databaseMap
h.writeJSON(cfg)
} else {
cfg, err := h.server.initialStartupConfig.Redacted()
if err != nil {
return err
}
h.writeJSON(cfg)
}
return nil
}
func (h *handler) handlePutConfig() error {
type FileLoggerPutConfig struct {
Enabled *bool `json:"enabled,omitempty"`
}
type ConsoleLoggerPutConfig struct {
LogLevel *base.LogLevel `json:"log_level,omitempty"`
LogKeys []string `json:"log_keys,omitempty"`
}
// Probably need to make our own to remove log file path / redaction level
type ServerPutConfig struct {
Logging struct {
Console *ConsoleLoggerPutConfig `json:"console,omitempty"`
Error FileLoggerPutConfig `json:"error,omitempty"`
Warn FileLoggerPutConfig `json:"warn,omitempty"`
Info FileLoggerPutConfig `json:"info,omitempty"`
Debug FileLoggerPutConfig `json:"debug,omitempty"`
Trace FileLoggerPutConfig `json:"trace,omitempty"`
Stats FileLoggerPutConfig `json:"stats,omitempty"`
Audit FileLoggerPutConfig `json:"audit,omitempty"`
} `json:"logging"`
ReplicationLimit *int `json:"max_concurrent_replications,omitempty"`
}
var config ServerPutConfig
err := base.WrapJSONUnknownFieldErr(ReadJSONFromMIMERawErr(h.rq.Header, h.requestBody, &config))
if err != nil {
if pkgerrors.Cause(err) == base.ErrUnknownField {
return base.HTTPErrorf(http.StatusBadRequest, "Unable to configure given options at runtime: %v", err)
}
return err
}
// Go over all loggers and use
if config.Logging.Console != nil {
if config.Logging.Console.LogLevel != nil {
base.ConsoleLogLevel().Set(*config.Logging.Console.LogLevel)
}
if config.Logging.Console.LogKeys != nil {
testMap := make(map[string]bool)
for _, key := range config.Logging.Console.LogKeys {
testMap[key] = true
}
base.UpdateLogKeys(h.ctx(), testMap, true)
}
}
if config.Logging.Error.Enabled != nil {
base.EnableErrorLogger(*config.Logging.Error.Enabled)
}
if config.Logging.Warn.Enabled != nil {
base.EnableWarnLogger(*config.Logging.Warn.Enabled)
}
if config.Logging.Info.Enabled != nil {
base.EnableInfoLogger(*config.Logging.Info.Enabled)
}
if config.Logging.Debug.Enabled != nil {
base.EnableDebugLogger(*config.Logging.Debug.Enabled)
}
if config.Logging.Trace.Enabled != nil {
base.EnableTraceLogger(*config.Logging.Trace.Enabled)
}
if config.Logging.Stats.Enabled != nil {
base.EnableStatsLogger(*config.Logging.Stats.Enabled)
}
if config.Logging.Audit.Enabled != nil {
base.EnableAuditLogger(h.ctx(), *config.Logging.Audit.Enabled)
}
if config.ReplicationLimit != nil {
if *config.ReplicationLimit < 0 {
return base.HTTPErrorf(http.StatusBadRequest, "replication limit cannot be less than 0")
}
h.server.Config.Replicator.MaxConcurrentReplications = *config.ReplicationLimit
h.server.ActiveReplicationsCounter.lock.Lock()
h.server.ActiveReplicationsCounter.activeReplicatorLimit = *config.ReplicationLimit
h.server.ActiveReplicationsCounter.lock.Unlock()
}
return base.HTTPErrorf(http.StatusOK, "Updated")
}
// handlePutDbConfig Upserts a new database config
func (h *handler) handlePutDbConfig() (err error) {
h.assertAdminOnly()
contextNoCancel := base.NewNonCancelCtx()
var dbConfig *DbConfig
auditFields := base.AuditFields{}
if h.permissionsResults[PermUpdateDb.PermissionName] {
// user authorized to change all fields
var err error
var rawBytes []byte
rawBytes, dbConfig, err = h.readSanitizeDbConfigJSON()
if err != nil {
return err
}
configStr, err := redactConfigAsStr(h.ctx(), string(rawBytes))
if err != nil {
base.WarnfCtx(h.ctx(), "Error redacting config for audit logging: %v", err)
}
auditFields[base.AuditFieldPayload] = configStr
} else {
hasAuthPerm := h.permissionsResults[PermConfigureAuth.PermissionName]
hasSyncPerm := h.permissionsResults[PermConfigureSyncFn.PermissionName]
var rawBytes []byte
rawBytes, err := io.ReadAll(h.requestBody)
if err != nil {
return err
}
configStr, err := redactConfigAsStr(h.ctx(), string(rawBytes))
if err != nil {
base.WarnfCtx(h.ctx(), "Error redacting config for audit logging: %v", err)
}
auditFields[base.AuditFieldPayload] = configStr
var mapDbConfig map[string]interface{}
err = ReadJSONFromMIMERawErr(h.rq.Header, io.NopCloser(bytes.NewReader(rawBytes)), &mapDbConfig)
if err != nil {
return err
}
unknownFileKeys := make([]string, 0)
for key, _ := range mapDbConfig {
if key == "sync" && hasSyncPerm || key == "guest" && hasAuthPerm {
continue
}
unknownFileKeys = append(unknownFileKeys, key)
}
if len(unknownFileKeys) > 0 {
return base.HTTPErrorf(http.StatusForbidden, "not authorized to update field: %s", strings.Join(unknownFileKeys, ","))
}
err = ReadJSONFromMIMERawErr(h.rq.Header, io.NopCloser(bytes.NewReader(rawBytes)), &dbConfig)
if err != nil {
return err
}
}
bucket := h.db.Bucket.GetName()
if dbConfig.Bucket != nil {
bucket = *dbConfig.Bucket
}
// Set dbName based on path value (since db doesn't necessarily exist), and update in incoming config in case of insert
dbName := h.PathVar("db")
if dbConfig.Name != "" && dbName != dbConfig.Name {
return base.HTTPErrorf(http.StatusBadRequest, "Cannot update database name. "+
"This requires removing and re-creating the database with a new name")
}
if dbConfig.Name == "" {
dbConfig.Name = dbName
}
validateOIDC := !h.getBoolQuery(paramDisableOIDCValidation)
validateReplications := true
err = dbConfig.validate(h.ctx(), validateOIDC, validateReplications)
if err != nil {
return base.NewHTTPError(http.StatusBadRequest, err.Error())
}
if !h.server.persistentConfig {
updatedDbConfig := &DatabaseConfig{DbConfig: *dbConfig}
oldDBConfig := h.server.GetDatabaseConfig(h.db.Name).DatabaseConfig.DbConfig
err = updatedDbConfig.validateConfigUpdate(h.ctx(), oldDBConfig,
validateOIDC)
if err != nil {
return base.NewHTTPError(http.StatusBadRequest, err.Error())
}
dbCreds, _ := h.server.Config.DatabaseCredentials[dbName]
if err := updatedDbConfig.setup(h.ctx(), dbName, h.server.Config.Bootstrap, dbCreds, nil, false); err != nil {
return err
}
if err := h.server.ReloadDatabaseWithConfig(contextNoCancel, *updatedDbConfig); err != nil {
return err
}
base.Audit(h.ctx(), base.AuditIDUpdateDatabaseConfig, auditFields)
return base.HTTPErrorf(http.StatusCreated, "updated")
}
var updatedDbConfig *DatabaseConfig
var previousAuditEnabled, updatedAuditEnabled bool
var updatedAuditEvents []uint
cas, err := h.server.BootstrapContext.UpdateConfig(h.ctx(), bucket, h.server.Config.Bootstrap.ConfigGroupID, dbConfig.Name, func(bucketDbConfig *DatabaseConfig) (updatedConfig *DatabaseConfig, err error) {
if h.headerDoesNotMatchEtag(bucketDbConfig.Version) {
return nil, base.HTTPErrorf(http.StatusPreconditionFailed, "Provided If-Match header does not match current config version")
}
oldBucketDbConfig := bucketDbConfig.DbConfig
previousCollectionMap := bucketDbConfig.Scopes.CollectionMap()
previousAuditEnabled, _ = oldBucketDbConfig.IsAuditLoggingEnabled()
if h.rq.Method == http.MethodPost {
base.TracefCtx(h.ctx(), base.KeyConfig, "merging upserted config into bucket config")
if err := base.ConfigMerge(&bucketDbConfig.DbConfig, dbConfig); err != nil {
return nil, err
}
} else {
base.TracefCtx(h.ctx(), base.KeyConfig, "using config as-is without merge")
bucketDbConfig.DbConfig = *dbConfig
}
// Update ImportVersion if new collections are being added to the database
if bucketDbConfig.Scopes.HasNewCollection(previousCollectionMap) {
bucketDbConfig.ImportVersion++
base.InfofCtx(h.ctx(), base.KeyConfig, "Import version incremented to %d, new collections detected", bucketDbConfig.ImportVersion)
}
if err := dbConfig.validatePersistentDbConfig(); err != nil {
return nil, base.NewHTTPError(http.StatusBadRequest, err.Error())
}
if err := bucketDbConfig.validateConfigUpdate(h.ctx(), oldBucketDbConfig, validateOIDC); err != nil {
return nil, base.NewHTTPError(http.StatusBadRequest, err.Error())
}
bucketDbConfig.Version, err = GenerateDatabaseConfigVersionID(h.ctx(), bucketDbConfig.Version, &bucketDbConfig.DbConfig)
if err != nil {
return nil, err
}
bucketDbConfig.SGVersion = base.ProductVersion.String()
updatedDbConfig = bucketDbConfig
// take a copy to stamp credentials and load before we persist
var tmpConfig DatabaseConfig
if err = base.DeepCopyInefficient(&tmpConfig, bucketDbConfig); err != nil {
return nil, err
}
// we need to set the new dbConfig cfgCas to the old version to avoid the background task polling server for config changes from reloading a
// previous persisted config during the update dbConfig process
tmpConfig.cfgCas = bucketDbConfig.cfgCas
dbCreds, _ := h.server.Config.DatabaseCredentials[dbName]
bucketCreds, _ := h.server.Config.BucketCredentials[bucket]
if err := tmpConfig.setup(h.ctx(), dbName, h.server.Config.Bootstrap, dbCreds, bucketCreds, h.server.Config.IsServerless()); err != nil {
return nil, err
}
// Load the new dbConfig before we persist the update.
err = h.server.ReloadDatabaseWithConfig(contextNoCancel, tmpConfig)
if err != nil {
return nil, err
}
updatedAuditEnabled, updatedAuditEvents = bucketDbConfig.IsAuditLoggingEnabled()
return bucketDbConfig, nil
})
if err != nil {
base.WarnfCtx(h.ctx(), "Couldn't update config for database - rolling back: %v", err)
// failed to start the new database config - rollback and return the original error for the user
// pass forceReload flag down stack to reset the cas to force the reload of the previous config from the bucket
if _, err := h.server.fetchAndLoadDatabase(contextNoCancel, dbName, true); err != nil {
base.WarnfCtx(h.ctx(), "got error rolling back database %q after failed update: %v", base.UD(dbName), err)
}
return err
}
auditDbAuditEnabled(h.ctx(), dbName, previousAuditEnabled, updatedAuditEnabled, updatedAuditEvents)
// store the cas in the loaded config after a successful update
h.setEtag(updatedDbConfig.Version)
h.server.lock.Lock()
defer h.server.lock.Unlock()
h.server.dbConfigs[dbName].cfgCas = cas
base.Audit(h.ctx(), base.AuditIDUpdateDatabaseConfig, auditFields)
return base.HTTPErrorf(http.StatusCreated, "updated")
}
type HandleDbAuditConfigBody struct {
Enabled *bool `json:"enabled,omitempty"`
Events map[string]any `json:"events,omitempty"`
DisabledUsers []base.AuditLoggingPrincipal `json:"disabled_users,omitempty"`
DisabledRoles []base.AuditLoggingPrincipal `json:"disabled_roles,omitempty"`
}
type HandleDbAuditConfigBodyVerboseEvent struct {
Name *string `json:"name,omitempty"`
Description *string `json:"description,omitempty"`
Enabled *bool `json:"enabled,omitempty"`
Filterable *bool `json:"filterable,omitempty"`
}
// GET audit config for database
func (h *handler) handleGetDbAuditConfig() error {
h.assertAdminOnly()
showOnlyFilterable := h.getBoolQuery("filterable")
verbose := h.getBoolQuery("verbose")
var (
etagVersion string
dbAuditEnabled bool
dbAuditDisabledUsers []base.AuditLoggingPrincipal
dbAuditDisabledRoles []base.AuditLoggingPrincipal
enabledEvents = make(map[base.AuditID]struct{})
)
if h.server.BootstrapContext.Connection != nil {
found, dbConfig, err := h.server.fetchDatabase(h.ctx(), h.db.Name)
if err != nil {
return err
}
if !found {
return base.HTTPErrorf(http.StatusNotFound, "database config not found")
}
etagVersion = dbConfig.Version
runtimeConfig, err := MergeDatabaseConfigWithDefaults(h.server.Config, &dbConfig.DbConfig)
if err != nil {
return err
}
// grab runtime version of config, so that we can see what events would be enabled
if runtimeConfig.Logging != nil && runtimeConfig.Logging.Audit != nil {
dbAuditEnabled = base.ValDefault(runtimeConfig.Logging.Audit.Enabled, false)
if runtimeConfig.Logging.Audit.EnabledEvents != nil {
for _, event := range *runtimeConfig.Logging.Audit.EnabledEvents {
enabledEvents[base.AuditID(event)] = struct{}{}
}
}
dbAuditDisabledUsers = runtimeConfig.Logging.Audit.DisabledUsers
dbAuditDisabledRoles = runtimeConfig.Logging.Audit.DisabledRoles
}
} else {
return base.HTTPErrorf(http.StatusServiceUnavailable, "audit config not available in non-persistent mode")
}
events := make(map[string]any, len(base.AuditEvents))
for id, descriptor := range base.AuditEvents {
// skip global and non-filterable events
if descriptor.IsGlobalEvent || (showOnlyFilterable && !descriptor.FilteringPermitted) {
continue
}
idStr := id.String()
_, eventEnabled := enabledEvents[id]
if verbose {
events[idStr] = HandleDbAuditConfigBodyVerboseEvent{
Name: stringPtrOrNil(descriptor.Name),
Description: stringPtrOrNil(descriptor.Description),
Enabled: &eventEnabled,
Filterable: base.Ptr(descriptor.FilteringPermitted),
}
} else {
events[idStr] = &eventEnabled
}
}
resp := HandleDbAuditConfigBody{
Enabled: &dbAuditEnabled,
Events: events,
DisabledUsers: dbAuditDisabledUsers,
DisabledRoles: dbAuditDisabledRoles,
}
h.setEtag(etagVersion)
h.writeJSON(resp)
return nil
}
// PUT/POST audit config for database
func (h *handler) handlePutDbAuditConfig() error {
var bodyRaw []byte
var previousAuditEnabled, updatedAuditEnabled bool
var updatedAuditEvents []uint
err := h.mutateDbConfig(func(config *DbConfig) error {
previousAuditEnabled, _ = config.IsAuditLoggingEnabled()
bodyRaw, err := h.readBody()
if err != nil {
return err
}
var body HandleDbAuditConfigBody
if err := base.JSONUnmarshal(bodyRaw, &body); err != nil {
return err
}
// isReplace if the request is a PUT, and we want to overwrite existing config
isReplace := h.rq.Method == http.MethodPut
// This API endpoint takes audit config in a format that does not match the actual DbConfig stored, so translate the request here.
toChange := make(map[base.AuditID]bool, len(body.Events))
var multiError *base.MultiError
for id, val := range body.Events {
// find the event
auditID, err := base.ParseAuditID(id)
if err != nil {
multiError = multiError.Append(fmt.Errorf("invalid audit event ID: %q", id))
continue
}
_, ok := base.AuditEvents[auditID]
if !ok {
multiError = multiError.Append(fmt.Errorf("unknown audit event ID: %q", auditID))
continue
}
var eventEnabled bool
switch valT := val.(type) {
case bool:
eventEnabled = valT
case map[string]any:
// verbose format
eventEnabled = valT["enabled"].(bool)
}
// check if explicitly disabled events are allowed to be filtered
// we'll ensure that non-filterable events are always considered enabled at runtime instead of at config persistence time
// this will ensure we are able to add events in the future that are non-filterable and have them work correctly
if e, ok := base.AuditEvents[auditID]; !ok {
multiError = multiError.Append(fmt.Errorf("unknown audit event ID: %q", auditID))
} else if e.IsGlobalEvent {
multiError = multiError.Append(fmt.Errorf("event %q is not configurable at the database level", auditID))
} else if !e.FilteringPermitted && !eventEnabled {
multiError = multiError.Append(fmt.Errorf("event %q is not filterable and cannot be disabled", auditID))
} else {
toChange[auditID] = eventEnabled
}
}
if err := multiError.ErrorOrNil(); err != nil {
return base.HTTPErrorf(http.StatusBadRequest, "couldn't update audit configuration: %s", err)
}
if config.Logging == nil {
config.Logging = &DbLoggingConfig{}
}
if config.Logging.Audit == nil {
config.Logging.Audit = &DbAuditLoggingConfig{}
}
mutateConfigFromDbAuditConfigBody(isReplace, config.Logging.Audit, &body, toChange)
updatedAuditEnabled, updatedAuditEvents = config.IsAuditLoggingEnabled()
return nil
})
if err != nil {
return err
}