-
Notifications
You must be signed in to change notification settings - Fork 242
Expand file tree
/
Copy pathroot.go
More file actions
1664 lines (1314 loc) · 52 KB
/
Copy pathroot.go
File metadata and controls
1664 lines (1314 loc) · 52 KB
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
package server
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"os"
"path"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
"time"
glob "github.com/bmatcuk/doublestar/v4"
"github.com/go-viper/mapstructure/v2"
distspec "github.com/opencontainers/distribution-spec/specs-go"
"github.com/spf13/cobra"
"github.com/spf13/viper"
zerr "zotregistry.dev/zot/v2/errors"
"zotregistry.dev/zot/v2/pkg/api"
"zotregistry.dev/zot/v2/pkg/api/config"
"zotregistry.dev/zot/v2/pkg/api/constants"
extconf "zotregistry.dev/zot/v2/pkg/extensions/config"
eventsconf "zotregistry.dev/zot/v2/pkg/extensions/config/events"
"zotregistry.dev/zot/v2/pkg/extensions/monitoring"
syncConstants "zotregistry.dev/zot/v2/pkg/extensions/sync/constants"
zlog "zotregistry.dev/zot/v2/pkg/log"
storageConstants "zotregistry.dev/zot/v2/pkg/storage/constants"
)
const (
defaultReadTimeout = 60 * time.Second
defaultWriteTimeout = 60 * time.Second
)
// metadataConfig reports metadata after parsing, which we use to track
// errors.
func metadataConfig(md *mapstructure.Metadata) viper.DecoderConfigOption {
return func(c *mapstructure.DecoderConfig) {
c.Metadata = md
}
}
func newServeCmd(conf *config.Config) *cobra.Command {
// "serve"
serveCmd := &cobra.Command{
Use: "serve <config>",
Aliases: []string{"serve"},
Short: "`serve` stores and distributes OCI images",
Long: "`serve` stores and distributes OCI images",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
logger := zlog.NewLogger("info", "")
if len(args) > 0 {
if err := LoadConfiguration(conf, args[0]); err != nil {
return err
}
}
ctlr := api.NewController(conf)
ldapCredentials := ""
if conf.HTTP.Auth != nil && conf.HTTP.Auth.LDAP != nil {
ldapCredentials = conf.HTTP.Auth.LDAP.CredentialsFile
}
// config reloader
hotReloader, err := NewHotReloader(ctlr, args[0], ldapCredentials)
if err != nil {
ctlr.Log.Error().Err(err).Msg("failed to create a new hot reloader")
return err
}
hotReloader.Start()
if err := ctlr.Init(); err != nil {
ctlr.Log.Error().Err(err).Msg("failed to init controller")
return err
}
initShutDownRoutine(ctlr)
if err := ctlr.Run(); err != nil {
logger.Error().Err(err).Msg("failed to start controller, exiting")
}
return nil
},
}
return serveCmd
}
func newScrubCmd(conf *config.Config) *cobra.Command {
// "scrub"
scrubCmd := &cobra.Command{
Use: "scrub <config>",
Aliases: []string{"scrub"},
Short: "`scrub` checks manifest/blob integrity",
Long: "`scrub` checks manifest/blob integrity",
RunE: func(cmd *cobra.Command, args []string) error {
logger := zlog.NewLogger("info", "")
if len(args) > 0 {
if err := LoadConfiguration(conf, args[0]); err != nil {
return err
}
} else {
if err := cmd.Usage(); err != nil {
return err
}
return nil
}
// Do not show usage on errors which are not related to cummand line arguments
cmd.SilenceUsage = true
// checking if the server is already running
req, err := http.NewRequestWithContext(context.Background(),
http.MethodGet,
fmt.Sprintf("http://%s/v2", net.JoinHostPort(conf.HTTP.Address, conf.HTTP.Port)),
nil)
if err != nil {
logger.Error().Err(err).Msg("failed to create a new http request")
return err
}
response, err := http.DefaultClient.Do(req)
if err == nil {
response.Body.Close()
logger.Warn().Err(zerr.ErrServerIsRunning).
Msg("server is running, in order to perform the scrub command the server should be shut down")
return zerr.ErrServerIsRunning
} else {
// server is down
ctlr := api.NewController(conf)
ctlr.Metrics = monitoring.NewMetricsServer(false, ctlr.Log)
if err := ctlr.InitImageStore(); err != nil {
return err
}
result, err := ctlr.StoreController.CheckAllBlobsIntegrity(cmd.Context())
if err != nil {
return err
}
result.PrintScrubResults(cmd.OutOrStdout())
}
return nil
},
}
return scrubCmd
}
func newVerifyCmd(conf *config.Config) *cobra.Command {
// verify
verifyCmd := &cobra.Command{
Use: "verify <config>",
Aliases: []string{"verify"},
Short: "`verify` validates a zot config file",
Long: "`verify` validates a zot config file",
RunE: func(cmd *cobra.Command, args []string) error {
logger := zlog.NewLogger("info", "")
if len(args) > 0 {
cmd.SilenceUsage = true
if err := LoadConfiguration(conf, args[0]); err != nil {
logger.Error().Str("config", args[0]).Msg("invalid config file")
return err
}
logger.Info().Str("config", args[0]).Msg("config file is valid")
}
return nil
},
}
return verifyCmd
}
func newVerifyFeatureCmd(conf *config.Config) *cobra.Command {
verifyFeatureCmd := &cobra.Command{
Use: "verify-feature",
Short: "`verify-feature` validates specific zot features",
Long: "`verify-feature` validates specific zot features",
}
// Add subcommands
verifyFeatureCmd.AddCommand(newVerifyFeatureRetentionCmd(conf))
return verifyFeatureCmd
}
// NewServerRootCmd creates a "zot" registry server command.
func NewServerRootCmd() *cobra.Command {
showVersion := false
conf := config.New()
rootCmd := &cobra.Command{
Use: "zot",
Short: "`zot`",
Long: "`zot`",
RunE: func(cmd *cobra.Command, args []string) error {
logger := zlog.NewLogger("info", "")
if showVersion {
commit, binaryType, goVersion, _ := conf.GetVersionInfo()
logger.Info().Str("distribution-spec", distspec.Version).Str("commit", commit).
Str("binary-type", binaryType).Str("go version", goVersion).Msg("version")
} else {
_ = cmd.Usage()
cmd.SilenceErrors = false
}
return nil
},
}
// "serve"
rootCmd.AddCommand(newServeCmd(conf))
// "verify"
rootCmd.AddCommand(newVerifyCmd(conf))
// "scrub"
rootCmd.AddCommand(newScrubCmd(conf))
// "schema"
rootCmd.AddCommand(newSchemaCmd())
// "verify-feature"
rootCmd.AddCommand(newVerifyFeatureCmd(conf))
// "version"
rootCmd.Flags().BoolVarP(&showVersion, "version", "v", false, "show the version and exit")
return rootCmd
}
// isPathInside checks if path1 is inside path2 (path1 is a subdirectory of path2)
// This function is platform-agnostic and handles Windows drive letters, UNC paths, and symlinks.
func isPathInside(path1, path2 string) bool {
// Normalize paths to absolute paths (handles platform-specific separators and symlinks)
abs1, err1 := filepath.Abs(path1)
abs2, err2 := filepath.Abs(path2)
if err1 != nil || err2 != nil {
return false
}
// On Windows, if paths are on different drives, filepath.Rel returns an error
// which we handle by returning false (paths on different drives are not nested)
rel, err := filepath.Rel(abs2, abs1)
if err != nil {
return false
}
// If the relative path doesn't start with "..", then path1 is inside path2
// Also check that it's not "." (same directory) or empty (same path)
// On Windows, filepath.Rel uses backslashes, but strings.HasPrefix works with any separator
return rel != "." && rel != "" && !strings.HasPrefix(rel, "..")
}
// pathsConflict checks if two paths conflict (identical or nested) and returns:
// - 0: no conflict
// - 1: paths are identical
// - 2: path1 is inside path2
// - 3: path2 is inside path1.
func pathsConflict(path1, path2 string) int {
if strings.EqualFold(path1, path2) {
return 1
}
if isPathInside(path1, path2) {
return 2
}
if isPathInside(path2, path1) {
return 3
}
return 0
}
// getStorageType returns the storage driver type name.
// Returns "local" if StorageDriver is nil, otherwise extracts the name from StorageDriver["name"].
func getStorageType(storageDriver map[string]any) string {
if storageDriver == nil {
return storageConstants.LocalStorageDriverName
}
storeName := fmt.Sprintf("%v", storageDriver["name"])
if storeName == storageConstants.S3StorageDriverName {
return storageConstants.S3StorageDriverName
}
if storeName == storageConstants.GCSStorageDriverName {
return storageConstants.GCSStorageDriverName
}
return storeName
}
func validateStorageConfig(cfg *config.Config, logger zlog.Logger) error {
storageConfig := cfg.CopyStorageConfig()
defaultRootDir := storageConfig.RootDirectory
defaultStorageType := getStorageType(storageConfig.StorageDriver)
// Collect all store root directories (default + substores) for nested path checking
type storeInfo struct {
route string // empty for default store
rootDir string
storageType string
}
allStores := make([]storeInfo, 0, 1+len(storageConfig.SubPaths))
allStores = append(allStores, storeInfo{route: "", rootDir: defaultRootDir, storageType: defaultStorageType})
for route, subStorageConfig := range storageConfig.SubPaths {
allStores = append(allStores, storeInfo{
route: route,
rootDir: subStorageConfig.RootDirectory,
storageType: getStorageType(subStorageConfig.StorageDriver),
})
}
// Sort stores by route to ensure deterministic ordering
slices.SortFunc(allStores, func(a, b storeInfo) int {
return strings.Compare(a.route, b.route)
})
// Validate each store
for _, store := range allStores {
route := store.route
rootDir := store.rootDir
storageType := store.storageType
// Check if this store conflicts with any other store of the same type (identical or nested paths)
conflictingIdx := slices.IndexFunc(allStores, func(other storeInfo) bool {
return other.route != route &&
other.storageType == storageType &&
pathsConflict(rootDir, other.rootDir) != 0
})
if conflictingIdx >= 0 {
other := allStores[conflictingIdx]
conflictType := pathsConflict(rootDir, other.rootDir)
var storeName, otherStoreName string
if route == "" {
storeName = "default storage"
} else {
storeName = fmt.Sprintf("substore (route: %s)", route)
}
if other.route == "" {
otherStoreName = "default storage"
} else {
otherStoreName = fmt.Sprintf("substore (route: %s)", other.route)
}
var msg string
switch conflictType {
case 1: // identical
msg = fmt.Sprintf("invalid storage config, %s and %s cannot use the same root directory", storeName, otherStoreName)
case 2: // rootDir is inside other.rootDir
msg = fmt.Sprintf("invalid storage config, %s root directory cannot be inside %s root directory",
storeName, otherStoreName)
case 3: // other.rootDir is inside rootDir
msg = fmt.Sprintf("invalid storage config, %s root directory cannot be inside %s root directory",
otherStoreName, storeName)
}
logger.Error().Err(zerr.ErrBadConfig).
Str("rootDir", rootDir).
Str("otherRootDir", other.rootDir).
Str("route", route).
Str("otherRoute", other.route).
Msg(msg)
return fmt.Errorf("%w: %s", zerr.ErrBadConfig, msg)
}
}
return nil
}
func validateCacheConfig(cfg *config.Config, logger zlog.Logger) error {
// global
storageConfig := cfg.CopyStorageConfig()
// dedupe true, remote storage, remoteCache true, but no cacheDriver (remote)
//nolint: lll
if storageConfig.Dedupe && storageConfig.StorageDriver != nil && storageConfig.RemoteCache && storageConfig.CacheDriver == nil {
msg := "invalid database config, dedupe set to true with remote storage and database, but no remote database configured"
logger.Error().Err(zerr.ErrBadConfig).Msg(msg)
return fmt.Errorf("%w: %s", zerr.ErrBadConfig, msg)
}
if storageConfig.CacheDriver != nil && storageConfig.RemoteCache {
// local storage with remote database
// redis is supported with both local and S3 storage, while dynamodb is only supported with S3
// redis is only supported with local storage in a non-clustering scenario with a single zot instance,
if storageConfig.StorageDriver == nil && storageConfig.CacheDriver["name"] != storageConstants.RedisDriverName {
msg := "invalid database config, cannot have local storage driver with remote database!"
logger.Error().Err(zerr.ErrBadConfig).Msg(msg)
return fmt.Errorf("%w: %s", zerr.ErrBadConfig, msg)
}
// unsupported database driver
if storageConfig.CacheDriver["name"] != storageConstants.DynamoDBDriverName &&
storageConfig.CacheDriver["name"] != storageConstants.RedisDriverName {
msg := "invalid database config, unsupported database driver"
logger.Error().Err(zerr.ErrBadConfig).Interface("cacheDriver", storageConfig.CacheDriver["name"]).Msg(msg)
return fmt.Errorf("%w: %s", zerr.ErrBadConfig, msg)
}
}
if !storageConfig.RemoteCache && storageConfig.CacheDriver != nil {
logger.Warn().Err(zerr.ErrBadConfig).Str("directory", storageConfig.RootDirectory).
Msg("invalid database config, remoteCache set to false but cacheDriver config (remote database)" +
" provided for directory will ignore and use local database")
}
// subpaths
for _, subPath := range storageConfig.SubPaths {
// dedupe true, remote storage, remoteCache true, but no cacheDriver (remote)
//nolint: lll
if subPath.Dedupe && subPath.StorageDriver != nil && subPath.RemoteCache && subPath.CacheDriver == nil {
msg := "invalid database config, dedupe set to true with remote storage and database, but no remote database configured!"
logger.Error().Err(zerr.ErrBadConfig).Msg(msg)
return fmt.Errorf("%w: %s", zerr.ErrBadConfig, msg)
}
if subPath.CacheDriver != nil && subPath.RemoteCache {
// local storage with remote caching
if subPath.StorageDriver == nil {
msg := "invalid database config, cannot have local storage driver with remote database!"
logger.Error().Err(zerr.ErrBadConfig).Msg(msg)
return fmt.Errorf("%w: %s", zerr.ErrBadConfig, msg)
}
// unsupported cache driver
if subPath.CacheDriver["name"] != storageConstants.DynamoDBDriverName {
msg := "invalid database config, unsupported database driver"
logger.Error().Err(zerr.ErrBadConfig).Interface("cacheDriver", subPath.CacheDriver["name"]).Msg(msg)
return fmt.Errorf("%w: %s", zerr.ErrBadConfig, msg)
}
}
if !subPath.RemoteCache && subPath.CacheDriver != nil {
logger.Warn().Err(zerr.ErrBadConfig).Str("directory", subPath.RootDirectory).
Msg("invalid database config, remoteCache set to false but cacheDriver config (remote database)" +
"provided for directory, will ignore and use local database")
}
}
return nil
}
func validateRemoteSessionStoreConfig(cfg *config.Config, logger zlog.Logger) error {
// it is okay for the session driver config to be nil
// this is backwards compatible for older configs
authConfig := cfg.CopyAuthConfig()
if authConfig == nil || authConfig.SessionDriver == nil {
return nil
}
sessionDriverName, ok := authConfig.SessionDriver["name"]
if !ok {
msg := "must provide session driver name!"
logger.Error().Err(zerr.ErrBadConfig).Msg(msg)
return fmt.Errorf("%w: %s", zerr.ErrBadConfig, msg)
}
allowedDriverNames := []string{
storageConstants.RedisDriverName,
storageConstants.LocalStorageDriverName,
}
isValidDriver := false
for _, allowedDriverName := range allowedDriverNames {
if allowedDriverName == sessionDriverName {
isValidDriver = true
break
}
}
if !isValidDriver {
msg := fmt.Sprintf("session store driver %s is not allowed!", sessionDriverName)
logger.Error().Err(zerr.ErrBadConfig).Msg(msg)
return fmt.Errorf("%w: %s", zerr.ErrBadConfig, msg)
}
// If the redis driver is being used, then session keys must not be configured
// as redis session store does not support these yet.
if sessionDriverName == storageConstants.RedisDriverName {
if authConfig.SessionKeysFile != "" {
msg := "session keys not supported when redis session driver is used!"
logger.Error().Err(zerr.ErrBadConfig).Msg(msg)
return fmt.Errorf("%w: %s", zerr.ErrBadConfig, msg)
}
}
return nil
}
func validateExtensionsConfig(cfg *config.Config, logger zlog.Logger) error {
extensionsConfig := cfg.CopyExtensionsConfig()
if extensionsConfig != nil && extensionsConfig.Mgmt != nil {
logger.Warn().Msg("mgmt extensions configuration option has been made redundant and will be ignored.")
}
if extensionsConfig != nil && extensionsConfig.APIKey != nil {
logger.Warn().Msg("apikey extension configuration will be ignored as API keys " +
"are now configurable in the HTTP settings.")
}
if extensionsConfig.IsUIEnabled() {
// it would make sense to also check for mgmt and user prefs to be enabled,
// but those are both enabled by having the search and ui extensions enabled
if !extensionsConfig.IsSearchEnabled() {
msg := "failed to enable ui, search extension must be enabled"
logger.Error().Err(zerr.ErrBadConfig).Msg(msg)
return fmt.Errorf("%w: %s", zerr.ErrBadConfig, msg)
}
}
//nolint:lll
storageConfig := cfg.CopyStorageConfig()
if storageConfig.StorageDriver != nil && extensionsConfig.IsCveScanningEnabled() {
msg := "failed to enable cve scanning due to incompatibility with remote storage, please disable cve"
logger.Error().Err(zerr.ErrBadConfig).Msg(msg)
return fmt.Errorf("%w: %s", zerr.ErrBadConfig, msg)
}
for _, subPath := range storageConfig.SubPaths {
//nolint:lll
if subPath.StorageDriver != nil && extensionsConfig.IsCveScanningEnabled() {
msg := "failed to enable cve scanning due to incompatibility with remote storage, please disable cve"
logger.Error().Err(zerr.ErrBadConfig).Msg(msg)
return fmt.Errorf("%w: %s", zerr.ErrBadConfig, msg)
}
}
return nil
}
func validateStorageConfigSection(
cfg *config.Config, logger zlog.Logger, storageConfig config.GlobalStorageConfig,
) error {
if len(storageConfig.StorageDriver) != 0 {
// enforce s3/gcs driver in case of using storage driver
if storageConfig.StorageDriver["name"] != storageConstants.S3StorageDriverName &&
storageConfig.StorageDriver["name"] != storageConstants.GCSStorageDriverName {
msg := "unsupported storage driver"
logger.Error().Err(zerr.ErrBadConfig).Interface("storageDriver", storageConfig.StorageDriver["name"]).Msg(msg)
return fmt.Errorf("%w: %s", zerr.ErrBadConfig, msg)
}
// enforce tmpDir in case sync + s3/gcs
extensionsConfig := cfg.CopyExtensionsConfig()
if extensionsConfig.IsSyncEnabled() && extensionsConfig.Sync.DownloadDir == "" {
msg := "using both sync and remote storage features needs config.Extensions.Sync.DownloadDir to be specified"
logger.Error().Err(zerr.ErrBadConfig).Msg(msg)
return fmt.Errorf("%w: %s", zerr.ErrBadConfig, msg)
}
}
// enforce s3/gcs driver on subpaths in case of using storage driver
if len(storageConfig.SubPaths) > 0 {
for route, subStorageConfig := range storageConfig.SubPaths {
if len(subStorageConfig.StorageDriver) != 0 {
if subStorageConfig.StorageDriver["name"] != storageConstants.S3StorageDriverName &&
subStorageConfig.StorageDriver["name"] != storageConstants.GCSStorageDriverName {
msg := "unsupported storage driver"
logger.Error().Err(zerr.ErrBadConfig).Str("subpath", route).Interface("storageDriver",
subStorageConfig.StorageDriver["name"]).Msg(msg)
return fmt.Errorf("%w: %s", zerr.ErrBadConfig, msg)
}
// enforce tmpDir in case sync + s3/gcs
extensionsConfig := cfg.CopyExtensionsConfig()
if extensionsConfig.IsSyncEnabled() && extensionsConfig.Sync.DownloadDir == "" {
msg := "using both sync and remote storage features needs config.Extensions.Sync.DownloadDir to be specified"
logger.Error().Err(zerr.ErrBadConfig).Msg(msg)
return fmt.Errorf("%w: %s", zerr.ErrBadConfig, msg)
}
}
}
}
return nil
}
func validateConfiguration(config *config.Config, logger zlog.Logger) error {
if err := validateHTTP(config, logger); err != nil {
return err
}
if err := validateGC(config, logger); err != nil {
return err
}
if err := validateLDAP(config, logger); err != nil {
return err
}
if err := validateMTLS(config, logger); err != nil {
return err
}
if err := validateOpenIDConfig(config, logger); err != nil {
return err
}
if err := validateBearerConfig(config, logger); err != nil {
return err
}
if err := validateSync(config, logger); err != nil {
return err
}
if err := validateStorageConfig(config, logger); err != nil {
return err
}
if err := validateCacheConfig(config, logger); err != nil {
return err
}
if err := validateRemoteSessionStoreConfig(config, logger); err != nil {
return err
}
if err := validateExtensionsConfig(config, logger); err != nil {
return err
}
// check authorization config, it should have basic auth enabled or ldap, api keys or OpenID
accessControlConfig := config.CopyAccessControlConfig()
if accessControlConfig != nil {
// checking for anonymous policy only authorization config: no users, no policies but anonymous policy
if err := validateAuthzPolicies(config, logger); err != nil {
return err
}
}
storageConfig := config.CopyStorageConfig()
if err := validateStorageConfigSection(config, logger, storageConfig); err != nil {
return err
}
// check glob patterns in authz config are compilable
if accessControlConfig != nil {
for pattern := range accessControlConfig.Repositories {
ok := glob.ValidatePattern(pattern)
if !ok {
msg := "failed to compile authorization pattern"
logger.Error().Err(glob.ErrBadPattern).Str("pattern", pattern).Msg(msg)
return fmt.Errorf("%w: %s", glob.ErrBadPattern, msg)
}
}
}
// check validity of scale out cluster config
if err := validateClusterConfig(config, logger); err != nil {
return err
}
return nil
}
func validateOpenIDConfig(cfg *config.Config, logger zlog.Logger) error {
authConfig := cfg.CopyAuthConfig()
// can't check with IsOpenIDAuthEnabled(), because it can't test invalid providers
if authConfig != nil && authConfig.OpenID != nil && len(authConfig.OpenID.Providers) > 0 {
for provider, providerConfig := range authConfig.OpenID.Providers {
//nolint: gocritic
if config.IsOpenIDSupported(provider) {
if providerConfig.ClientID == "" || providerConfig.Issuer == "" ||
len(providerConfig.Scopes) == 0 {
msg := "OpenID provider config requires clientid, issuer and scopes parameters"
logger.Error().Err(zerr.ErrBadConfig).Msg(msg)
return fmt.Errorf("%w: %s", zerr.ErrBadConfig, msg)
}
} else if config.IsOauth2Supported(provider) {
if providerConfig.ClientID == "" || len(providerConfig.Scopes) == 0 {
msg := "OAuth2 provider config requires clientid and scopes parameters"
logger.Error().Err(zerr.ErrBadConfig).Msg(msg)
return fmt.Errorf("%w: %s", zerr.ErrBadConfig, msg)
}
} else {
msg := "unsupported openid/oauth2 provider"
logger.Error().Err(zerr.ErrBadConfig).Msg(msg)
return fmt.Errorf("%w: %s", zerr.ErrBadConfig, msg)
}
}
}
return nil
}
func validateBearerConfig(cfg *config.Config, logger zlog.Logger) error {
authConfig := cfg.CopyAuthConfig()
if authConfig == nil || authConfig.Bearer == nil {
return nil
}
bearer := authConfig.Bearer
if bearer.Cert != "" && bearer.AWSSecretsManager != nil {
msg := "cannot configure both cert and awsSecretsManager for bearer authentication"
logger.Error().Err(zerr.ErrBadConfig).Msg(msg)
return fmt.Errorf("%w: %s", zerr.ErrBadConfig, msg)
}
if bearer.AWSSecretsManager != nil {
asm := bearer.AWSSecretsManager
if asm.Region == "" {
msg := "awsSecretsManager region must be specified"
logger.Error().Err(zerr.ErrBadConfig).Msg(msg)
return fmt.Errorf("%w: %s", zerr.ErrBadConfig, msg)
}
if asm.SecretName == "" {
msg := "awsSecretsManager secretName must be specified"
logger.Error().Err(zerr.ErrBadConfig).Msg(msg)
return fmt.Errorf("%w: %s", zerr.ErrBadConfig, msg)
}
if asm.RefreshInterval < 0 {
msg := "awsSecretsManager refreshInterval must be non-negative"
logger.Error().Err(zerr.ErrBadConfig).Msg(msg)
return fmt.Errorf("%w: %s", zerr.ErrBadConfig, msg)
}
}
return nil
}
func validateAuthzPolicies(config *config.Config, logger zlog.Logger) error {
authConfig := config.CopyAuthConfig()
accessControlConfig := config.CopyAccessControlConfig()
logger.Info().Msg("checking if anonymous authorization is the only type of authorization policy configured")
if !authConfig.IsBasicAuthnEnabled() && !config.IsMTLSAuthEnabled() && !authConfig.IsBearerAuthEnabled() &&
!accessControlConfig.ContainsOnlyAnonymousPolicy() {
msg := "access control config requires one of htpasswd, ldap, openid or mTLS authentication " +
"or using only 'anonymousPolicy' policies"
logger.Error().Err(zerr.ErrBadConfig).Msg(msg)
return fmt.Errorf("%w: %s", zerr.ErrBadConfig, msg)
}
if _, err := api.CompileAccessControl(accessControlConfig); err != nil {
logger.Error().Err(err).Msg("failed to compile access control policy conditions")
return fmt.Errorf("%w: %w", zerr.ErrBadConfig, err)
}
return nil
}
//nolint:gocyclo,cyclop,nestif
func applyDefaultValues(config *config.Config, viperInstance *viper.Viper, logger zlog.Logger) {
defaultVal := true
if config.Extensions == nil && viperInstance.Get("extensions") != nil {
config.Extensions = &extconf.ExtensionConfig{}
extMap := viperInstance.GetStringMap("extensions")
_, ok := extMap["metrics"]
if ok {
// we found a config like `"extensions": {"metrics": {}}`
// Note: In case metrics is not empty the config.Extensions will not be nil and we will not reach here
config.Extensions.Metrics = &extconf.MetricsConfig{}
}
_, ok = extMap["search"]
if ok {
// we found a config like `"extensions": {"search": {}}`
// Note: In case search is not empty the config.Extensions will not be nil and we will not reach here
config.Extensions.Search = &extconf.SearchConfig{}
}
_, ok = extMap["scrub"]
if ok {
// we found a config like `"extensions": {"scrub:": {}}`
// Note: In case scrub is not empty the config.Extensions will not be nil and we will not reach here
config.Extensions.Scrub = &extconf.ScrubConfig{}
}
_, ok = extMap["trust"]
if ok {
// we found a config like `"extensions": {"trust:": {}}`
// Note: In case trust is not empty the config.Extensions will not be nil and we will not reach here
config.Extensions.Trust = &extconf.ImageTrustConfig{}
}
_, ok = extMap["ui"]
if ok {
// we found a config like `"extensions": {"ui:": {}}`
// Note: In case UI is not empty the config.Extensions will not be nil and we will not reach here
config.Extensions.UI = &extconf.UIConfig{}
}
}
if config.Extensions != nil {
if config.Extensions.Sync != nil {
if config.Extensions.Sync.Enable == nil {
config.Extensions.Sync.Enable = &defaultVal
}
for idx := range config.Extensions.Sync.Registries {
regCfg := &config.Extensions.Sync.Registries[idx]
if regCfg.TLSVerify == nil {
regCfg.TLSVerify = &defaultVal
}
if regCfg.SyncTimeout == 0 {
regCfg.SyncTimeout = syncConstants.DefaultSyncTimeout
}
if regCfg.ResponseHeaderTimeout == 0 {
regCfg.ResponseHeaderTimeout = syncConstants.DefaultResponseHeaderTimeout
}
}
}
if config.Extensions.Search != nil {
if config.Extensions.Search.Enable == nil {
config.Extensions.Search.Enable = &defaultVal
}
if config.Extensions.Search.CVE != nil && config.Extensions.Search.CVE.Enable == nil {
config.Extensions.Search.CVE.Enable = &defaultVal
}
if *config.Extensions.Search.Enable && config.Extensions.Search.CVE != nil {
if config.Extensions.Search.CVE.Enable == nil || *config.Extensions.Search.CVE.Enable {
defaultUpdateInterval, _ := time.ParseDuration("2h")
if config.Extensions.Search.CVE.UpdateInterval < defaultUpdateInterval {
config.Extensions.Search.CVE.UpdateInterval = defaultUpdateInterval
logger.Warn().Msg("cve update interval set to too-short interval < 2h, " +
"changing update duration to 2 hours and continuing.")
}
if config.Extensions.Search.CVE.Trivy == nil {
config.Extensions.Search.CVE.Trivy = &extconf.TrivyConfig{}
}
if config.Extensions.Search.CVE.Trivy.DBRepository == "" {
defaultDBDownloadURL := "ghcr.io/aquasecurity/trivy-db"
logger.Info().Str("url", defaultDBDownloadURL).Str("component", "config").
Msg("using default trivy-db download URL.")
config.Extensions.Search.CVE.Trivy.DBRepository = defaultDBDownloadURL
}
if config.Extensions.Search.CVE.Trivy.JavaDBRepository == "" {
defaultJavaDBDownloadURL := "ghcr.io/aquasecurity/trivy-java-db"
logger.Info().Str("url", defaultJavaDBDownloadURL).Str("component", "config").
Msg("using default trivy-java-db download URL.")
config.Extensions.Search.CVE.Trivy.JavaDBRepository = defaultJavaDBDownloadURL
}
if len(config.Extensions.Search.CVE.Trivy.VulnSeveritySources) == 0 {
defaultVulnSeveritySources := []string{"auto"}
logger.Info().Strs("vulnSeveritySources", defaultVulnSeveritySources).Str("component", "config").
Msg("using default trivy vulnerability severity sources.")
config.Extensions.Search.CVE.Trivy.VulnSeveritySources = defaultVulnSeveritySources
}
}
}
}
if config.Extensions.Metrics != nil {
if config.Extensions.Metrics.Enable == nil {
config.Extensions.Metrics.Enable = &defaultVal
}
if config.Extensions.Metrics.Prometheus == nil {
config.Extensions.Metrics.Prometheus = &extconf.PrometheusConfig{Path: constants.DefaultMetricsExtensionRoute}
}
}
if config.Extensions.Scrub != nil {
if config.Extensions.Scrub.Enable == nil {
config.Extensions.Scrub.Enable = &defaultVal
}
if config.Extensions.Scrub.Interval == 0 {
config.Extensions.Scrub.Interval = 24 * time.Hour //nolint:mnd
}
// Validate minimum scrub interval
minScrubInterval, _ := time.ParseDuration("2h")
if config.Extensions.Scrub.Interval < minScrubInterval {
config.Extensions.Scrub.Interval = minScrubInterval
logger.Warn().Msg("scrub interval set to too-short interval < 2h, " +
"changing scrub duration to 2 hours and continuing.")
}
}
if config.Extensions.UI != nil {
if config.Extensions.UI.Enable == nil {
config.Extensions.UI.Enable = &defaultVal
}
}
if config.Extensions.Trust != nil {
if config.Extensions.Trust.Enable == nil {
config.Extensions.Trust.Enable = &defaultVal
}
}
}
// set default values in case GC is disabled
if !config.Storage.GC {
if viperInstance.Get("storage::gcdelay") == nil {
config.Storage.GCDelay = 0
}
if viperInstance.Get("storage::retention::delay") == nil {
config.Storage.Retention.Delay = 0
}
if viperInstance.Get("storage::gcinterval") == nil {
config.Storage.GCInterval = 0
}
} else if !viperInstance.IsSet("storage::retention::delay") {
// if GC is enabled, retentionDelay is set to gcDelay by default
// it could be default gcDelay or the custom value set in the config file
config.Storage.Retention.Delay = config.Storage.GCDelay
}
// apply deleteUntagged default
for idx := range config.Storage.Retention.Policies {
if !viperInstance.IsSet("storage::retention::policies::" + strconv.Itoa(idx) + "::deleteUntagged") {
config.Storage.Retention.Policies[idx].DeleteUntagged = &defaultVal
}
}
// cache settings
// global storage
// if dedupe is true but remoteCache bool not set in config file
// for cloud based storage, remoteCache defaults to true
if config.Storage.Dedupe && !viperInstance.IsSet("storage::remotecache") && config.Storage.StorageDriver != nil {
config.Storage.RemoteCache = true
}
if config.Storage.StorageDriver != nil {