-
Notifications
You must be signed in to change notification settings - Fork 139
/
Copy pathconfig.go
2413 lines (2133 loc) · 103 KB
/
config.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 2013-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"
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
_ "net/http/pprof"
"net/url"
"os"
"os/signal"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/go-jose/go-jose/v4"
"golang.org/x/crypto/bcrypt"
sgbucket "github.com/couchbase/sg-bucket"
"github.com/couchbase/sync_gateway/auth"
"github.com/couchbase/sync_gateway/base"
"github.com/couchbase/sync_gateway/db"
"github.com/couchbase/sync_gateway/db/functions"
"github.com/couchbaselabs/rosmar"
)
var (
DefaultPublicInterface = ":4984"
DefaultAdminInterface = "127.0.0.1:4985" // Only accessible on localhost!
DefaultMetricsInterface = "127.0.0.1:4986" // Only accessible on localhost!
DefaultDiagnosticInterface = "" // Disabled by default
DefaultMinimumTLSVersionConst = tls.VersionTLS12
// The value of defaultLogFilePath is populated by -defaultLogFilePath by command line flag from service scripts.
defaultLogFilePath string
// serverContextGlobalsInitialized is set the first time that a server context has been initialized
serverContextGlobalsInitialized = atomic.Bool{}
)
const (
eeOnlyWarningMsg = "EE only configuration option %s=%v - Reverting to default value for CE: %v"
minValueErrorMsg = "minimum value for %s is: %v"
rangeValueErrorMsg = "valid range for %s is: %s"
// Default value of LegacyServerConfig.MaxIncomingConnections
DefaultMaxIncomingConnections = 0
// Default value of LegacyServerConfig.MaxFileDescriptors
DefaultMaxFileDescriptors uint64 = 5000
// Default number of index replicas
DefaultNumIndexReplicas = uint(1)
DefaultUseTLSServer = true
DefaultMinConfigFetchInterval = time.Second
tapFeedType = "tap"
)
// serverType indicates which type of HTTP server sync gateway is running
type serverType string
const (
// serverTypePublic indicates the public interface for sync gateway
publicServer serverType = "public"
// serverTypeAdmin indicates the admin interface for sync gateway
adminServer serverType = "admin"
// serverTypeMetrics indicates the metrics interface for sync gateway
metricsServer serverType = "metrics"
// serverTypeDiagnostic indicates the diagnostic interface for sync gateway
diagnosticServer serverType = "diagnostic"
)
// Bucket configuration elements - used by db, index
type BucketConfig struct {
Server *string `json:"server,omitempty"` // Couchbase server URL
DeprecatedPool *string `json:"pool,omitempty"` // Couchbase pool name - This is now deprecated and forced to be "default"
Bucket *string `json:"bucket,omitempty"` // Bucket name
Username string `json:"username,omitempty"` // Username for authenticating to server
Password string `json:"password,omitempty"` // Password for authenticating to server
CertPath string `json:"certpath,omitempty"` // Cert path (public key) for X.509 bucket auth
KeyPath string `json:"keypath,omitempty"` // Key path (private key) for X.509 bucket auth
CACertPath string `json:"cacertpath,omitempty"` // Root CA cert path for X.509 bucket auth
KvTLSPort int `json:"kv_tls_port,omitempty"` // Memcached TLS port, if not default (11207)
MaxConcurrentQueryOps *int `json:"max_concurrent_query_ops,omitempty"` // Max concurrent query ops
}
// MakeBucketSpec creates a BucketSpec from the DatabaseConfig. Will return an error if the server value is not valid after basic parsing.
func (dc *DbConfig) MakeBucketSpec(server string) base.BucketSpec {
bc := &dc.BucketConfig
bucketName := ""
tlsPort := 11207
// treat all walrus: as in memory storage, any persistent storage would have to be converted to rosmar
if strings.HasPrefix(server, "walrus:") {
server = rosmar.InMemoryURL
}
if bc.Bucket != nil {
bucketName = *bc.Bucket
}
if bc.KvTLSPort != 0 {
tlsPort = bc.KvTLSPort
}
return base.BucketSpec{
Server: server,
BucketName: bucketName,
Keypath: bc.KeyPath,
Certpath: bc.CertPath,
CACertPath: bc.CACertPath,
KvTLSPort: tlsPort,
Auth: bc,
MaxConcurrentQueryOps: bc.MaxConcurrentQueryOps,
}
}
// Implementation of AuthHandler interface for BucketConfig
func (bucketConfig *BucketConfig) GetCredentials() (username string, password string, bucketname string) {
return base.TransformBucketCredentials(bucketConfig.Username, bucketConfig.Password, *bucketConfig.Bucket)
}
// DbConfig defines a database configuration used in a config file or the REST API.
type DbConfig struct {
BucketConfig
Scopes ScopesConfig `json:"scopes,omitempty"` // Scopes and collection specific config
Name string `json:"name,omitempty"` // Database name in REST API (stored as key in JSON)
Sync *string `json:"sync,omitempty"` // The sync function applied to write operations in the _default scope and collection
Users map[string]*auth.PrincipalConfig `json:"users,omitempty"` // Initial user accounts
Roles map[string]*auth.PrincipalConfig `json:"roles,omitempty"` // Initial roles
RevsLimit *uint32 `json:"revs_limit,omitempty"` // Max depth a document's revision tree can grow to
AutoImport interface{} `json:"import_docs,omitempty"` // Whether to automatically import Couchbase Server docs into SG. Xattrs must be enabled. true or "continuous" both enable this.
ImportPartitions *uint16 `json:"import_partitions,omitempty"` // Number of partitions for import sharding. Impacts the total DCP concurrency for import
ImportFilter *string `json:"import_filter,omitempty"` // The import filter applied to import operations in the _default scope and collection
ImportBackupOldRev *bool `json:"import_backup_old_rev,omitempty"` // Whether import should attempt to create a temporary backup of the previous revision body, when available.
EventHandlers *EventHandlerConfig `json:"event_handlers,omitempty"` // Event handlers (webhook)
FeedType string `json:"feed_type,omitempty"` // Feed type - "DCP" only, "TAP" is ignored
AllowEmptyPassword *bool `json:"allow_empty_password,omitempty"` // Allow empty passwords? Defaults to false
CacheConfig *CacheConfig `json:"cache,omitempty"` // Cache settings
DeprecatedRevCacheSize *uint32 `json:"rev_cache_size,omitempty"` // Maximum number of revisions to store in the revision cache (deprecated, CBG-356)
StartOffline *bool `json:"offline,omitempty"` // start the DB in the offline state, defaults to false
Unsupported *db.UnsupportedOptions `json:"unsupported,omitempty"` // Config for unsupported features
OIDCConfig *auth.OIDCOptions `json:"oidc,omitempty"` // Config properties for OpenID Connect authentication
LocalJWTConfig auth.LocalJWTConfig `json:"local_jwt,omitempty"`
OldRevExpirySeconds *uint32 `json:"old_rev_expiry_seconds,omitempty"` // The number of seconds before old revs are removed from CBS bucket
ViewQueryTimeoutSecs *uint32 `json:"view_query_timeout_secs,omitempty"` // The view query timeout in seconds
LocalDocExpirySecs *uint32 `json:"local_doc_expiry_secs,omitempty"` // The _local doc expiry time in seconds
EnableXattrs *bool `json:"enable_shared_bucket_access,omitempty"` // Whether to use extended attributes to store _sync metadata
SecureCookieOverride *bool `json:"session_cookie_secure,omitempty"` // Override cookie secure flag
SessionCookieName string `json:"session_cookie_name,omitempty"` // Custom per-database session cookie name
SessionCookieHTTPOnly *bool `json:"session_cookie_http_only,omitempty"` // HTTP only cookies
AllowConflicts *bool `json:"allow_conflicts,omitempty"` // Deprecated: False forbids creating conflicts
NumIndexReplicas *uint `json:"num_index_replicas,omitempty"` // Number of GSI index replicas used for core indexes, deprecated for IndexConfig.NumReplicas
Index *IndexConfig `json:"index,omitempty"` // Index options
UseViews *bool `json:"use_views,omitempty"` // Force use of views instead of GSI
SendWWWAuthenticateHeader *bool `json:"send_www_authenticate_header,omitempty"` // If false, disables setting of 'WWW-Authenticate' header in 401 responses. Implicitly false if disable_password_auth is true.
DisablePasswordAuth *bool `json:"disable_password_auth,omitempty"` // If true, disables user/pass authentication, only permitting OIDC or guest access
BucketOpTimeoutMs *uint32 `json:"bucket_op_timeout_ms,omitempty"` // How long bucket ops should block returning "operation timed out". If nil, uses GoCB default. GoCB buckets only.
SlowQueryWarningThresholdMs *uint32 `json:"slow_query_warning_threshold,omitempty"` // Log warnings if N1QL queries take this many ms
DeltaSync *DeltaSyncConfig `json:"delta_sync,omitempty"` // Config for delta sync
CompactIntervalDays *float32 `json:"compact_interval_days,omitempty"` // Interval between scheduled compaction runs (in days) - 0 means don't run
SGReplicateEnabled *bool `json:"sgreplicate_enabled,omitempty"` // When false, node will not be assigned replications
SGReplicateWebsocketPingInterval *int `json:"sgreplicate_websocket_heartbeat_secs,omitempty"` // If set, uses this duration as a custom heartbeat interval for websocket ping frames
Replications map[string]*db.ReplicationConfig `json:"replications,omitempty"` // sg-replicate replication definitions
ServeInsecureAttachmentTypes *bool `json:"serve_insecure_attachment_types,omitempty"` // Attachment content type will bypass the content-disposition handling, default false
QueryPaginationLimit *int `json:"query_pagination_limit,omitempty"` // Query limit to be used during pagination of large queries
UserXattrKey *string `json:"user_xattr_key,omitempty"` // Key of user xattr that will be accessible from the Sync Function. If empty or nil the feature will be disabled.
ClientPartitionWindowSecs *int `json:"client_partition_window_secs,omitempty"` // How long clients can remain offline for without losing replication metadata. Default 30 days (in seconds)
Guest *auth.PrincipalConfig `json:"guest,omitempty"` // Guest user settings
JavascriptTimeoutSecs *uint32 `json:"javascript_timeout_secs,omitempty"` // The amount of seconds a Javascript function can run for. Set to 0 for no timeout.
UserFunctions *functions.FunctionsConfig `json:"functions,omitempty"` // Named JS fns for clients to call
Suspendable *bool `json:"suspendable,omitempty"` // Allow the database to be suspended
ChangesRequestPlus *bool `json:"changes_request_plus,omitempty"` // If set, is used as the default value of request_plus for non-continuous replications
CORS *auth.CORSConfig `json:"cors,omitempty"` // Per-database CORS config
Logging *DbLoggingConfig `json:"logging,omitempty"` // Per-database Logging config
UpdatedAt *time.Time `json:"updated_at,omitempty"` // Time at which the database config was last updated
CreatedAt *time.Time `json:"created_at,omitempty"` // Time at which the database config was created
}
type ScopesConfig map[string]ScopeConfig
type ScopeConfig struct {
Collections CollectionsConfig `json:"collections,omitempty"` // Collection-specific config options.
}
type CollectionsConfig map[string]*CollectionConfig
type CollectionConfig struct {
SyncFn *string `json:"sync,omitempty"` // The sync function applied to write operations in this collection.
ImportFilter *string `json:"import_filter,omitempty"` // The import filter applied to import operations in this collection.
}
type DeltaSyncConfig struct {
Enabled *bool `json:"enabled,omitempty"` // Whether delta sync is enabled (requires EE)
RevMaxAgeSeconds *uint32 `json:"rev_max_age_seconds,omitempty"` // The number of seconds deltas for old revs are available for
}
type DbConfigMap map[string]*DbConfig
type EventHandlerConfig struct {
MaxEventProc uint `json:"max_processes,omitempty"` // Max concurrent event handling goroutines
WaitForProcess string `json:"wait_for_process,omitempty"` // Max wait time when event queue is full (ms)
DocumentChanged []*EventConfig `json:"document_changed,omitempty"` // Document changed
DBStateChanged []*EventConfig `json:"db_state_changed,omitempty"` // DB state change
}
type EventConfig struct {
HandlerType string `json:"handler,omitempty"` // Handler type
Url string `json:"url,omitempty"` // Url (webhook)
Filter string `json:"filter,omitempty"` // Filter function (webhook)
Timeout *uint64 `json:"timeout,omitempty"` // Timeout (webhook)
Options map[string]interface{} `json:"options,omitempty"` // Options can be specified per-handler, and are specific to each type.
}
type CacheConfig struct {
RevCacheConfig *RevCacheConfig `json:"rev_cache,omitempty"` // Revision Cache Config Settings
ChannelCacheConfig *ChannelCacheConfig `json:"channel_cache,omitempty"` // Channel Cache Config Settings
DeprecatedCacheConfig
}
// Deprecated: Kept around for CBG-356 backwards compatibility
type DeprecatedCacheConfig struct {
DeprecatedCachePendingSeqMaxWait *uint32 `json:"max_wait_pending,omitempty"` // Max wait for pending sequence before skipping
DeprecatedCachePendingSeqMaxNum *int `json:"max_num_pending,omitempty"` // Max number of pending sequences before skipping
DeprecatedCacheSkippedSeqMaxWait *uint32 `json:"max_wait_skipped,omitempty"` // Max wait for skipped sequence before abandoning
DeprecatedEnableStarChannel *bool `json:"enable_star_channel,omitempty"` // Enable star channel
DeprecatedChannelCacheMaxLength *int `json:"channel_cache_max_length,omitempty"` // Maximum number of entries maintained in cache per channel
DeprecatedChannelCacheMinLength *int `json:"channel_cache_min_length,omitempty"` // Minimum number of entries maintained in cache per channel
DeprecatedChannelCacheAge *int `json:"channel_cache_expiry,omitempty"` // Time (seconds) to keep entries in cache beyond the minimum retained
}
type RevCacheConfig struct {
MaxItemCount *uint32 `json:"size,omitempty"` // Maximum number of revisions to store in the revision cache
MaxMemoryCountMB *uint32 `json:"max_memory_count_mb,omitempty"` // Maximum amount of memory the rev cache should consume in MB, when configured it will work in tandem with max items
ShardCount *uint16 `json:"shard_count,omitempty"` // Number of shards the rev cache should be split into
}
type ChannelCacheConfig struct {
MaxNumber *int `json:"max_number,omitempty"` // Maximum number of channel caches which will exist at any one point
HighWatermarkPercent *int `json:"compact_high_watermark_pct,omitempty"` // High watermark for channel cache eviction (percent)
LowWatermarkPercent *int `json:"compact_low_watermark_pct,omitempty"` // Low watermark for channel cache eviction (percent)
MaxWaitPending *uint32 `json:"max_wait_pending,omitempty"` // Max wait for pending sequence before skipping
MaxNumPending *int `json:"max_num_pending,omitempty"` // Max number of pending sequences before skipping
MaxWaitSkipped *uint32 `json:"max_wait_skipped,omitempty"` // Max wait for skipped sequence before abandoning
EnableStarChannel *bool `json:"enable_star_channel,omitempty"` // Deprecated: Enable star channel
MaxLength *int `json:"max_length,omitempty"` // Maximum number of entries maintained in cache per channel
MinLength *int `json:"min_length,omitempty"` // Minimum number of entries maintained in cache per channel
ExpirySeconds *int `json:"expiry_seconds,omitempty"` // Time (seconds) to keep entries in cache beyond the minimum retained
DeprecatedQueryLimit *int `json:"query_limit,omitempty"` // Limit used for channel queries, if not specified by client DEPRECATED in favour of db.QueryPaginationLimit
}
// DbLoggingConfig allows per-database logging overrides
type DbLoggingConfig struct {
Console *DbConsoleLoggingConfig `json:"console,omitempty"`
Audit *DbAuditLoggingConfig `json:"audit,omitempty"`
}
// DbConsoleLoggingConfig are per-db options configurable for console logging
type DbConsoleLoggingConfig struct {
LogLevel *base.LogLevel `json:"log_level,omitempty"`
LogKeys []string `json:"log_keys,omitempty"`
}
// DbAuditLoggingConfig are per-db options configurable for audit logging
type DbAuditLoggingConfig struct {
Enabled *bool `json:"enabled,omitempty"` // Whether audit logging is enabled for this database
EnabledEvents *[]uint `json:"enabled_events,omitempty"` // List of audit event IDs that are enabled - pointer to differentiate between empty slice and nil
DisabledUsers []base.AuditLoggingPrincipal `json:"disabled_users,omitempty"` // List of users to disable audit logging for
DisabledRoles []base.AuditLoggingPrincipal `json:"disabled_roles,omitempty"` // List of roles to disable audit logging for
}
type IndexConfig struct {
NumReplicas *uint `json:"num_replicas,omitempty"` // Number of replicas for GSI indexes
NumPartitions *uint32 `json:"num_partitions,omitempty"` // Number of partitions for GSI indexes
}
func GetTLSVersionFromString(stringV *string) uint16 {
if stringV != nil {
switch *stringV {
case "tlsv1":
return tls.VersionTLS10
case "tlsv1.1":
return tls.VersionTLS11
case "tlsv1.2":
return tls.VersionTLS12
case "tlsv1.3":
return tls.VersionTLS13
}
}
return uint16(DefaultMinimumTLSVersionConst)
}
type invalidConfigInfo struct {
logged bool
configBucketName string
persistedBucketName string
collectionConflicts bool
databaseError *db.DatabaseError
}
type invalidDatabaseConfigs struct {
dbNames map[string]*invalidConfigInfo
m sync.RWMutex
}
// CollectionMap returns the set of collections defined in the ScopesConfig as a map of collections in scope.collection form.
// Used for comparing sets of collections between configs
func (sc *ScopesConfig) CollectionMap() map[string]struct{} {
collectionMap := make(map[string]struct{})
if sc == nil {
collectionMap["_default._default"] = struct{}{}
return collectionMap
}
for scopeName, scope := range *sc {
for collectionName, _ := range scope.Collections {
scName := scopeName + "." + collectionName
collectionMap[scName] = struct{}{}
}
}
return collectionMap
}
func (sc *ScopesConfig) HasNewCollection(previousCollectionMap map[string]struct{}) bool {
if sc == nil {
_, hasDefault := previousCollectionMap["_default._default"]
return !hasDefault
}
for scopeName, scope := range *sc {
for collectionName, _ := range scope.Collections {
scName := scopeName + "." + collectionName
if _, ok := previousCollectionMap[scName]; !ok {
return true
}
}
}
return false
}
// addInvalidDatabase adds a db to invalid dbconfig map if it doesn't exist in there yet and will log for it at warning level
// if the db already exists there we will calculate if we need to log again according to the config update interval
func (d *invalidDatabaseConfigs) addInvalidDatabase(ctx context.Context, dbname string, cnf DatabaseConfig, bucket string, databaseErr *db.DatabaseError) {
d.m.Lock()
defer d.m.Unlock()
if d.dbNames[dbname] == nil {
// db hasn't been tracked as invalid config yet so add it
d.dbNames[dbname] = &invalidConfigInfo{
configBucketName: *cnf.Bucket,
persistedBucketName: bucket,
collectionConflicts: cnf.Version == invalidDatabaseConflictingCollectionsVersion,
databaseError: databaseErr,
}
}
logMessage := "Must repair invalid database config for %q for it to be usable!"
logArgs := []interface{}{base.MD(dbname)}
// build log message
if isBucketMismatch := *cnf.Bucket != bucket; isBucketMismatch {
base.SyncGatewayStats.GlobalStats.ConfigStat.DatabaseBucketMismatches.Add(1)
logMessage += " Mismatched buckets (config bucket: %q, actual bucket: %q)"
logArgs = append(logArgs, base.MD(d.dbNames[dbname].configBucketName), base.MD(d.dbNames[dbname].persistedBucketName))
} else if cnf.Version == invalidDatabaseConflictingCollectionsVersion {
base.SyncGatewayStats.GlobalStats.ConfigStat.DatabaseRollbackCollectionCollisions.Add(1)
logMessage += " Conflicting collections detected"
} else if databaseErr != nil {
logMessage += " Error encountered loading database."
} else {
// Nothing is expected to hit this case, but we might add more invalid sentinel values and forget to update this code.
logMessage += " Database was marked invalid. See logs for details."
}
// if we get here we already have the db logged as an invalid config, so now we need to work out iof we should log for it now
if !d.dbNames[dbname].logged {
// we need to log at warning if we haven't already logged for this particular corrupt db config
base.WarnfCtx(ctx, logMessage, logArgs...)
d.dbNames[dbname].logged = true
} else {
// already logged this entry at warning so need to log at info now
base.InfofCtx(ctx, base.KeyConfig, logMessage, logArgs...)
}
}
func (d *invalidDatabaseConfigs) exists(dbname string) (*invalidConfigInfo, bool) {
d.m.RLock()
defer d.m.RUnlock()
config, ok := d.dbNames[dbname]
return config, ok
}
func (d *invalidDatabaseConfigs) remove(dbname string) {
d.m.Lock()
defer d.m.Unlock()
delete(d.dbNames, dbname)
}
// removeNonExistingConfigs will remove any configs from invalid config tracking map that aren't present in fetched configs
func (d *invalidDatabaseConfigs) removeNonExistingConfigs(fetchedConfigs map[string]bool) {
d.m.Lock()
defer d.m.Unlock()
for dbName := range d.dbNames {
if ok := fetchedConfigs[dbName]; !ok {
// this invalid db config was not found in config polling, so lets remove
delete(d.dbNames, dbName)
}
}
}
// inheritFromBootstrap sets any empty Couchbase Server values from the given bootstrap config.
func (dbc *DbConfig) inheritFromBootstrap(b BootstrapConfig) {
if dbc.Username == "" {
dbc.Username = b.Username
}
if dbc.Password == "" {
dbc.Password = b.Password
}
if dbc.CACertPath == "" {
dbc.CACertPath = b.CACertPath
}
if dbc.CertPath == "" {
dbc.CertPath = b.X509CertPath
}
if dbc.KeyPath == "" {
dbc.KeyPath = b.X509KeyPath
}
if dbc.Server == nil || *dbc.Server == "" {
dbc.Server = &b.Server
}
}
func (dbConfig *DbConfig) setDatabaseCredentials(credentials base.CredentialsConfig) {
// X.509 overrides username/password
if credentials.X509CertPath != "" || credentials.X509KeyPath != "" {
dbConfig.CertPath = credentials.X509CertPath
dbConfig.KeyPath = credentials.X509KeyPath
dbConfig.Username = ""
dbConfig.Password = ""
} else {
dbConfig.Username = credentials.Username
dbConfig.Password = credentials.Password
dbConfig.CertPath = ""
dbConfig.KeyPath = ""
}
}
// setup populates fields in the dbConfig
func (dbConfig *DbConfig) setup(ctx context.Context, dbName string, bootstrapConfig BootstrapConfig, dbCredentials, bucketCredentials *base.CredentialsConfig, forcePerBucketAuth bool) error {
dbConfig.Name = dbName
// use db name as bucket if absent from config (handling for old non-stamped configs)
if dbConfig.Bucket == nil {
dbConfig.Bucket = &dbConfig.Name
}
dbConfig.inheritFromBootstrap(bootstrapConfig)
if bucketCredentials != nil {
dbConfig.setDatabaseCredentials(*bucketCredentials)
} else if forcePerBucketAuth {
return fmt.Errorf("unable to setup database on bucket %q since credentials are not defined in bucket_credentials", base.MD(*dbConfig.Bucket).Redact())
}
// Per db credentials override bootstrap and bucket level credentials
if dbCredentials != nil {
dbConfig.setDatabaseCredentials(*dbCredentials)
}
if dbConfig.Server != nil {
url, err := url.Parse(*dbConfig.Server)
if err != nil {
return err
}
if url.User != nil {
// Remove credentials from URL and put them into the DbConfig.Username and .Password:
if dbConfig.Username == "" {
dbConfig.Username = url.User.Username()
}
if dbConfig.Password == "" {
if password, exists := url.User.Password(); exists {
dbConfig.Password = password
}
}
url.User = nil
urlStr := url.String()
dbConfig.Server = &urlStr
}
}
insecureSkipVerify := false
if dbConfig.Unsupported != nil {
insecureSkipVerify = dbConfig.Unsupported.RemoteConfigTlsSkipVerify
}
// Load Sync Function.
if dbConfig.Sync != nil {
sync, err := loadJavaScript(ctx, *dbConfig.Sync, insecureSkipVerify)
if err != nil {
return &JavaScriptLoadError{
JSLoadType: SyncFunction,
Path: *dbConfig.Sync,
Err: err,
}
}
dbConfig.Sync = &sync
}
// Load Import Filter Function.
if dbConfig.ImportFilter != nil {
importFilter, err := loadJavaScript(ctx, *dbConfig.ImportFilter, insecureSkipVerify)
if err != nil {
return &JavaScriptLoadError{
JSLoadType: ImportFilter,
Path: *dbConfig.ImportFilter,
Err: err,
}
}
dbConfig.ImportFilter = &importFilter
}
// Load Conflict Resolution Function.
for _, rc := range dbConfig.Replications {
if rc.ConflictResolutionFn != "" {
conflictResolutionFn, err := loadJavaScript(ctx, rc.ConflictResolutionFn, insecureSkipVerify)
if err != nil {
return &JavaScriptLoadError{
JSLoadType: ConflictResolver,
Path: rc.ConflictResolutionFn,
Err: err,
}
}
rc.ConflictResolutionFn = conflictResolutionFn
}
}
return nil
}
// loadJavaScript loads the JavaScript source from an external file or and HTTP/HTTPS endpoint.
// If the specified path does not qualify for a valid file or an URI, it returns the input path
// as-is with the assumption that it is an inline JavaScript source. Returns error if there is
// any failure in reading the JavaScript file or URI.
func loadJavaScript(ctx context.Context, path string, insecureSkipVerify bool) (js string, err error) {
rc, err := readFromPath(ctx, path, insecureSkipVerify)
if errors.Is(err, ErrPathNotFound) {
// If rc is nil and readFromPath returns no error, treat the
// the given path as an inline JavaScript and return it as-is.
return path, nil
}
if err != nil {
if !insecureSkipVerify {
var unkAuthErr x509.UnknownAuthorityError
if errors.As(err, &unkAuthErr) {
return "", fmt.Errorf("%w. TLS certificate failed verification. TLS verification "+
"can be disabled using the unsupported \"remote_config_tls_skip_verify\" option", err)
}
return "", err
}
return "", err
}
defer func() { _ = rc.Close() }()
src, err := io.ReadAll(rc)
if err != nil {
return "", err
}
return string(src), nil
}
// JSLoadType represents a specific JavaScript load type.
// It is used to uniquely identify any potential errors during JavaScript load.
type JSLoadType int
const (
SyncFunction JSLoadType = iota // Sync Function JavaScript load.
ImportFilter // Import filter JavaScript load.
ConflictResolver // Conflict Resolver JavaScript load.
WebhookFilter // Webhook filter JavaScript load.
jsLoadTypeCount // Number of JSLoadType constants.
)
// jsLoadTypes represents the list of different possible JSLoadType.
var jsLoadTypes = []string{"SyncFunction", "ImportFilter", "ConflictResolver", "WebhookFilter"}
// String returns the string representation of a specific JSLoadType.
func (t JSLoadType) String() string {
if len(jsLoadTypes) < int(t) {
return fmt.Sprintf("JSLoadType(%d)", t)
}
return jsLoadTypes[t]
}
// JavaScriptLoadError is returned if there is any failure in loading JavaScript
// source from an external file or URL (HTTP/HTTPS endpoint).
type JavaScriptLoadError struct {
JSLoadType JSLoadType // A specific JavaScript load type.
Path string // Path of the JavaScript source.
Err error // Underlying error.
}
// Error returns string representation of the JavaScriptLoadError.
func (e *JavaScriptLoadError) Error() string {
return fmt.Sprintf("Error loading JavaScript (%s) from %q, Err: %v", e.JSLoadType, e.Path, e.Err)
}
// ErrPathNotFound means that the specified path or URL (HTTP/HTTPS endpoint)
// doesn't exist to construct a ReadCloser to read the bytes later on.
var ErrPathNotFound = errors.New("path not found")
// readFromPath creates a ReadCloser from the given path. The path must be either a valid file
// or an HTTP/HTTPS endpoint. Returns an error if there is any failure in building ReadCloser.
func readFromPath(ctx context.Context, path string, insecureSkipVerify bool) (rc io.ReadCloser, err error) {
messageFormat := "Loading content from [%s] ..."
if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") {
base.InfofCtx(ctx, base.KeyAll, messageFormat, path)
client := base.GetHttpClient(insecureSkipVerify)
resp, err := client.Get(path)
if err != nil {
return nil, err
} else if resp.StatusCode >= 300 {
_ = resp.Body.Close()
return nil, base.NewHTTPError(resp.StatusCode, http.StatusText(resp.StatusCode))
}
rc = resp.Body
} else if base.FileExists(path) {
base.InfofCtx(ctx, base.KeyAll, messageFormat, path)
rc, err = os.Open(path)
if err != nil {
return nil, err
}
} else {
return nil, ErrPathNotFound
}
return rc, nil
}
// GetBucketName returns the bucket name associated with the database config.
func (dbConfig *DbConfig) GetBucketName() string {
if dbConfig.Bucket != nil {
return *dbConfig.Bucket
}
// db name as fallback in the case of a `nil` bucket.
return dbConfig.Name
}
func (dbConfig *DbConfig) AutoImportEnabled(ctx context.Context) (bool, error) {
if dbConfig.AutoImport == nil {
if !dbConfig.UseXattrs() {
return false, nil
}
return base.DefaultAutoImport, nil
}
if b, ok := dbConfig.AutoImport.(bool); ok {
return b, nil
}
str, ok := dbConfig.AutoImport.(string)
if ok && str == "continuous" {
base.WarnfCtx(ctx, `Using deprecated config value for "import_docs": "continuous". Use "import_docs": true instead.`)
return true, nil
}
return false, fmt.Errorf("Unrecognized value for import_docs: %#v. Valid values are true and false.", dbConfig.AutoImport)
}
const dbConfigFieldNotAllowedErrorMsg = "Persisted database config does not support customization of the %q field"
// validatePersistentDbConfig checks for fields that are only allowed in non-persistent mode.
func (dbConfig *DbConfig) validatePersistentDbConfig() (errorMessages error) {
var multiError *base.MultiError
if dbConfig.Server != nil {
multiError = multiError.Append(fmt.Errorf(dbConfigFieldNotAllowedErrorMsg, "server"))
}
if dbConfig.Username != "" {
multiError = multiError.Append(fmt.Errorf(dbConfigFieldNotAllowedErrorMsg, "username"))
}
if dbConfig.Password != "" {
multiError = multiError.Append(fmt.Errorf(dbConfigFieldNotAllowedErrorMsg, "password"))
}
if dbConfig.CertPath != "" {
multiError = multiError.Append(fmt.Errorf(dbConfigFieldNotAllowedErrorMsg, "certpath"))
}
if dbConfig.KeyPath != "" {
multiError = multiError.Append(fmt.Errorf(dbConfigFieldNotAllowedErrorMsg, "keypath"))
}
if dbConfig.CACertPath != "" {
multiError = multiError.Append(fmt.Errorf(dbConfigFieldNotAllowedErrorMsg, "cacertpath"))
}
if dbConfig.Users != nil {
multiError = multiError.Append(fmt.Errorf(dbConfigFieldNotAllowedErrorMsg, "users"))
}
if dbConfig.Roles != nil {
multiError = multiError.Append(fmt.Errorf(dbConfigFieldNotAllowedErrorMsg, "roles"))
}
return multiError.ErrorOrNil()
}
// validateConfigUpdate combines the results of validate and validateChanges.
func (dbConfig *DbConfig) validateConfigUpdate(ctx context.Context, old DbConfig, validateOIDCConfig bool) error {
validateReplications := false
err := dbConfig.validate(ctx, validateOIDCConfig, validateReplications)
var multiErr *base.MultiError
if !errors.As(err, &multiErr) {
multiErr = multiErr.Append(err)
}
multiErr = multiErr.Append(dbConfig.validateChanges(ctx, old))
return multiErr.ErrorOrNil()
}
// validateChanges compares the current DbConfig with the "old" config, and returns an error if any disallowed changes
// are attempted.
func (dbConfig *DbConfig) validateChanges(ctx context.Context, old DbConfig) error {
// allow switching from implicit `_default` to explicit `_default` scope
_, newIsDefaultScope := dbConfig.Scopes[base.DefaultScope]
if old.Scopes == nil && len(dbConfig.Scopes) == 1 && newIsDefaultScope {
return nil
}
// early exit
if len(dbConfig.Scopes) != len(old.Scopes) {
return fmt.Errorf("cannot change scopes after database creation")
}
newScopes := make(base.Set, len(dbConfig.Scopes))
oldScopes := make(base.Set, len(old.Scopes))
for scopeName := range dbConfig.Scopes {
newScopes.Add(scopeName)
}
for scopeName := range old.Scopes {
oldScopes.Add(scopeName)
}
if !newScopes.Equals(oldScopes) {
return fmt.Errorf("cannot change scopes after database creation")
}
return nil
}
// validate checks the DbConfig for any invalid or unsupported values and return a http error. If validateReplications is true, return an error if any replications are not valid. Otherwise issue a warning.
func (dbConfig *DbConfig) validate(ctx context.Context, validateOIDCConfig, validateReplications bool) error {
return dbConfig.validateVersion(ctx, base.IsEnterpriseEdition(), validateOIDCConfig, validateReplications)
}
func (dbConfig *DbConfig) validateVersion(ctx context.Context, isEnterpriseEdition, validateOIDCConfig, validateReplications bool) error {
var multiError *base.MultiError
// Make sure a non-zero compact_interval_days config is within the valid range
if val := dbConfig.CompactIntervalDays; val != nil && *val != 0 &&
(*val < db.CompactIntervalMinDays || *val > db.CompactIntervalMaxDays) {
multiError = multiError.Append(fmt.Errorf(rangeValueErrorMsg, "compact_interval_days",
fmt.Sprintf("%g-%g", db.CompactIntervalMinDays, db.CompactIntervalMaxDays)))
}
if dbConfig.CacheConfig != nil {
if dbConfig.CacheConfig.ChannelCacheConfig != nil {
// EE: channel cache
if !isEnterpriseEdition {
if val := dbConfig.CacheConfig.ChannelCacheConfig.MaxNumber; val != nil {
base.WarnfCtx(ctx, eeOnlyWarningMsg, "cache.channel_cache.max_number", *val, db.DefaultChannelCacheMaxNumber)
dbConfig.CacheConfig.ChannelCacheConfig.MaxNumber = nil
}
if val := dbConfig.CacheConfig.ChannelCacheConfig.HighWatermarkPercent; val != nil {
base.WarnfCtx(ctx, eeOnlyWarningMsg, "cache.channel_cache.compact_high_watermark_pct", *val, db.DefaultCompactHighWatermarkPercent)
dbConfig.CacheConfig.ChannelCacheConfig.HighWatermarkPercent = nil
}
if val := dbConfig.CacheConfig.ChannelCacheConfig.LowWatermarkPercent; val != nil {
base.WarnfCtx(ctx, eeOnlyWarningMsg, "cache.channel_cache.compact_low_watermark_pct", *val, db.DefaultCompactLowWatermarkPercent)
dbConfig.CacheConfig.ChannelCacheConfig.LowWatermarkPercent = nil
}
}
if dbConfig.CacheConfig.ChannelCacheConfig.MaxNumPending != nil && *dbConfig.CacheConfig.ChannelCacheConfig.MaxNumPending < 1 {
multiError = multiError.Append(fmt.Errorf(minValueErrorMsg, "cache.channel_cache.max_num_pending", 1))
}
if dbConfig.CacheConfig.ChannelCacheConfig.MaxWaitPending != nil && *dbConfig.CacheConfig.ChannelCacheConfig.MaxWaitPending < 1 {
multiError = multiError.Append(fmt.Errorf(minValueErrorMsg, "cache.channel_cache.max_wait_pending", 1))
}
if dbConfig.CacheConfig.ChannelCacheConfig.MaxWaitSkipped != nil && *dbConfig.CacheConfig.ChannelCacheConfig.MaxWaitSkipped < 1 {
multiError = multiError.Append(fmt.Errorf(minValueErrorMsg, "cache.channel_cache.max_wait_skipped", 1))
}
if dbConfig.CacheConfig.ChannelCacheConfig.MaxLength != nil && *dbConfig.CacheConfig.ChannelCacheConfig.MaxLength < 1 {
multiError = multiError.Append(fmt.Errorf(minValueErrorMsg, "cache.channel_cache.max_length", 1))
}
if dbConfig.CacheConfig.ChannelCacheConfig.MinLength != nil && *dbConfig.CacheConfig.ChannelCacheConfig.MinLength < 1 {
multiError = multiError.Append(fmt.Errorf(minValueErrorMsg, "cache.channel_cache.min_length", 1))
}
if dbConfig.CacheConfig.ChannelCacheConfig.ExpirySeconds != nil && *dbConfig.CacheConfig.ChannelCacheConfig.ExpirySeconds < 1 {
multiError = multiError.Append(fmt.Errorf(minValueErrorMsg, "cache.channel_cache.expiry_seconds", 1))
}
if dbConfig.CacheConfig.ChannelCacheConfig.MaxNumber != nil && *dbConfig.CacheConfig.ChannelCacheConfig.MaxNumber < db.MinimumChannelCacheMaxNumber {
multiError = multiError.Append(fmt.Errorf(minValueErrorMsg, "cache.channel_cache.max_number", db.MinimumChannelCacheMaxNumber))
}
// Compact watermark validation
hwm := db.DefaultCompactHighWatermarkPercent
lwm := db.DefaultCompactLowWatermarkPercent
if dbConfig.CacheConfig.ChannelCacheConfig.HighWatermarkPercent != nil {
if *dbConfig.CacheConfig.ChannelCacheConfig.HighWatermarkPercent < 1 || *dbConfig.CacheConfig.ChannelCacheConfig.HighWatermarkPercent > 100 {
multiError = multiError.Append(fmt.Errorf(rangeValueErrorMsg, "cache.channel_cache.compact_high_watermark_pct", "0-100"))
}
hwm = *dbConfig.CacheConfig.ChannelCacheConfig.HighWatermarkPercent
}
if dbConfig.CacheConfig.ChannelCacheConfig.LowWatermarkPercent != nil {
if *dbConfig.CacheConfig.ChannelCacheConfig.LowWatermarkPercent < 1 || *dbConfig.CacheConfig.ChannelCacheConfig.LowWatermarkPercent > 100 {
multiError = multiError.Append(fmt.Errorf(rangeValueErrorMsg, "cache.channel_cache.compact_low_watermark_pct", "0-100"))
}
lwm = *dbConfig.CacheConfig.ChannelCacheConfig.LowWatermarkPercent
}
if lwm >= hwm {
multiError = multiError.Append(fmt.Errorf("cache.channel_cache.compact_high_watermark_pct (%v) must be greater than cache.channel_cache.compact_low_watermark_pct (%v)", hwm, lwm))
}
}
if dbConfig.CacheConfig.RevCacheConfig != nil {
// EE: disable revcache
revCacheSize := dbConfig.CacheConfig.RevCacheConfig.MaxItemCount
if !isEnterpriseEdition && revCacheSize != nil && *revCacheSize == 0 {
base.WarnfCtx(ctx, eeOnlyWarningMsg, "cache.rev_cache.size", *revCacheSize, db.DefaultRevisionCacheSize)
dbConfig.CacheConfig.RevCacheConfig.MaxItemCount = nil
}
revCacheMemoryLimit := dbConfig.CacheConfig.RevCacheConfig.MaxMemoryCountMB
if !isEnterpriseEdition && revCacheMemoryLimit != nil && *revCacheMemoryLimit != 0 {
base.WarnfCtx(ctx, eeOnlyWarningMsg, "cache.rev_cache.max_memory_count_mb", *revCacheMemoryLimit, "no memory limit")
dbConfig.CacheConfig.RevCacheConfig.MaxMemoryCountMB = nil
}
if dbConfig.CacheConfig.RevCacheConfig.ShardCount != nil {
if *dbConfig.CacheConfig.RevCacheConfig.ShardCount < 1 {
multiError = multiError.Append(fmt.Errorf(minValueErrorMsg, "cache.rev_cache.shard_count", 1))
}
}
}
}
// EE: delta sync
if !isEnterpriseEdition && dbConfig.DeltaSync != nil && dbConfig.DeltaSync.Enabled != nil {
base.WarnfCtx(ctx, eeOnlyWarningMsg, "delta_sync.enabled", *dbConfig.DeltaSync.Enabled, false)
dbConfig.DeltaSync.Enabled = nil
}
// Import validation
autoImportEnabled, err := dbConfig.AutoImportEnabled(ctx)
if err != nil {
multiError = multiError.Append(err)
}
if dbConfig.FeedType == tapFeedType && autoImportEnabled == true {
multiError = multiError.Append(fmt.Errorf("Invalid configuration for Sync Gw. TAP feed type can not be used with auto-import"))
}
if dbConfig.AutoImport != nil && autoImportEnabled && !dbConfig.UseXattrs() {
multiError = multiError.Append(fmt.Errorf("Invalid configuration - import_docs enabled, but enable_shared_bucket_access not enabled"))
}
if dbConfig.ImportPartitions != nil {
if !isEnterpriseEdition {
base.WarnfCtx(ctx, eeOnlyWarningMsg, "import_partitions", *dbConfig.ImportPartitions, nil)
dbConfig.ImportPartitions = nil
} else if !dbConfig.UseXattrs() {
multiError = multiError.Append(fmt.Errorf("Invalid configuration - import_partitions set, but enable_shared_bucket_access not enabled"))
} else if !autoImportEnabled {
multiError = multiError.Append(fmt.Errorf("Invalid configuration - import_partitions set, but import_docs disabled"))
} else if *dbConfig.ImportPartitions < 1 || *dbConfig.ImportPartitions > 1024 {
multiError = multiError.Append(fmt.Errorf(rangeValueErrorMsg, "import_partitions", "1-1024"))
}
}
if dbConfig.DeprecatedPool != nil {
base.WarnfCtx(ctx, `"pool" config option is not supported. The pool will be set to "default". The option should be removed from config file.`)
}
if isEmpty, err := validateJavascriptFunction(dbConfig.Sync); err != nil {
multiError = multiError.Append(fmt.Errorf("sync function error: %w", err))
} else if isEmpty {
dbConfig.Sync = nil
}
if isEmpty, err := validateJavascriptFunction(dbConfig.ImportFilter); err != nil {
multiError = multiError.Append(fmt.Errorf("import filter error: %w", err))
} else if isEmpty {
dbConfig.ImportFilter = nil
}
if err := db.ValidateDatabaseName(dbConfig.Name); err != nil {
multiError = multiError.Append(err)
}
if dbConfig.Unsupported != nil && dbConfig.Unsupported.WarningThresholds != nil {
warningThresholdXattrSize := dbConfig.Unsupported.WarningThresholds.XattrSize
if warningThresholdXattrSize != nil {
lowerLimit := 0.1 * 1024 * 1024 // 0.1 MB
upperLimit := 1 * 1024 * 1024 // 1 MB
if *warningThresholdXattrSize < uint32(lowerLimit) {
multiError = multiError.Append(fmt.Errorf("xattr_size warning threshold cannot be lower than %d bytes", uint32(lowerLimit)))
} else if *warningThresholdXattrSize > uint32(upperLimit) {
multiError = multiError.Append(fmt.Errorf("xattr_size warning threshold cannot be higher than %d bytes", uint32(upperLimit)))
}
}
warningThresholdChannelsPerDoc := dbConfig.Unsupported.WarningThresholds.ChannelsPerDoc
if warningThresholdChannelsPerDoc != nil {
lowerLimit := 5
if *warningThresholdChannelsPerDoc < uint32(lowerLimit) {
multiError = multiError.Append(fmt.Errorf("channels_per_doc warning threshold cannot be lower than %d", lowerLimit))
}
}
warningThresholdGrantsPerDoc := dbConfig.Unsupported.WarningThresholds.GrantsPerDoc
if warningThresholdGrantsPerDoc != nil {
lowerLimit := 5
if *warningThresholdGrantsPerDoc < uint32(lowerLimit) {
multiError = multiError.Append(fmt.Errorf("access_and_role_grants_per_doc warning threshold cannot be lower than %d", lowerLimit))
}
}
}
revsLimit := dbConfig.RevsLimit
if revsLimit != nil {
if *dbConfig.ConflictsAllowed() {
if *revsLimit < 20 {
multiError = multiError.Append(fmt.Errorf("The revs_limit (%v) value in your Sync Gateway configuration cannot be set lower than 20.", *revsLimit))
}
} else {
if *revsLimit <= 0 {
multiError = multiError.Append(fmt.Errorf("The revs_limit (%v) value in your Sync Gateway configuration must be greater than zero.", *revsLimit))
}
}
}
seenIssuers := make(map[string]int)
if dbConfig.OIDCConfig != nil {
validProviders := len(dbConfig.OIDCConfig.Providers)
for name, oidc := range dbConfig.OIDCConfig.Providers {
if oidc.Issuer == "" || base.ValDefault(oidc.ClientID, "") == "" {
// TODO: rather than being an error, this skips the current provider to avoid a backwards compatibility issue (previously valid
// configs becoming invalid). This also means it's duplicated in NewDatabaseContext.
base.WarnfCtx(ctx, "Issuer and Client ID not defined for provider %q - skipping", base.UD(name))
validProviders--
continue
}
if oidc.ValidationKey == nil {
base.WarnfCtx(ctx, "Validation Key not defined in config for provider %q - auth code flow will not be supported for this provider", base.UD(name))
}
if strings.Contains(name, "_") {
multiError = multiError.Append(fmt.Errorf("OpenID Connect provider names cannot contain underscore: %s", name))
validProviders--
continue
}
seenIssuers[oidc.Issuer]++
if validateOIDCConfig {
_, _, err := oidc.DiscoverConfig(ctx)
if err != nil {
multiError = multiError.Append(fmt.Errorf("failed to validate OIDC configuration for %s: %w", name, err))
validProviders--
}
}
}
if validProviders == 0 {
multiError = multiError.Append(fmt.Errorf("OpenID Connect defined in config, but no valid providers specified"))
}
}
for name, local := range dbConfig.LocalJWTConfig {
if local.Issuer == "" {
multiError = multiError.Append(fmt.Errorf("Issuer required for Local JWT provider %s", name))
}
if local.ClientID == nil {
multiError = multiError.Append(fmt.Errorf("Client ID required for Local JWT provider %s (set to \"\" to disable audience validation)", name))
}
if len(local.Algorithms) == 0 {
multiError = multiError.Append(fmt.Errorf("algorithms required for Local JWT provider %s", name))
}
if len(local.Keys) == 0 && len(local.JWKSURI) == 0 {
multiError = multiError.Append(fmt.Errorf("either 'keys' or 'jwks_uri' must be specified for Local JWT provider %s", name))
}
if len(local.Keys) > 0 && len(local.JWKSURI) > 0 {
multiError = multiError.Append(fmt.Errorf("'keys' and 'jwks_uri' are mutually exclusive for Local JWT provider %s", name))
}
didReportKIDError := false
for i, key := range local.Keys {
if key.KeyID == "" && len(local.Keys) > 1 && !didReportKIDError {
multiError = multiError.Append(fmt.Errorf("%s: 'kid' property required on all keys when more than one key is defined", name))
didReportKIDError = true
}
var keyLabel string
if key.KeyID != "" {
keyLabel = "\"" + key.KeyID + "\""