-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathconfig.go
More file actions
1164 lines (973 loc) · 38.6 KB
/
config.go
File metadata and controls
1164 lines (973 loc) · 38.6 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
/*
* SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package config
import (
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"sync"
"time"
cauth "github.com/NVIDIA/ncx-infra-controller-rest/auth/pkg/config"
cconfig "github.com/NVIDIA/ncx-infra-controller-rest/common/pkg/config"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
var (
_, cur, _, _ = runtime.Caller(0)
// ProjectRoot describes the folder path of this project
ProjectRoot = filepath.Join(filepath.Dir(cur), "../..")
)
const (
// ConfigFilePath specifies the path to the config file, this contains the default path
ConfigFilePath = "config.file"
// ConfigFilePathEnv specifies the environment variable name for the config file path
ConfigFilePathEnv = "CONFIG_FILE_PATH"
// ConfigEnvDev specifies if the service is running in development mode
ConfigEnvDev = "env.dev"
// ConfigEnvDisconnected specifies if the service is running in disconnected mode
ConfigEnvDisconnected = "env.disconnected"
// ConfigAPIName specifies the name of the API
ConfigAPIName = "api.name"
// ConfigAPIRouteVersion specifies the version of the API
ConfigAPIRouteVersion = "api.route.version"
// ConfigLogLevel specifies the log level
ConfigLogLevel = "log.level"
// ConfigSentryDSN is the DSN for Sentry
ConfigSentryDSN = "log.sentry.dsn"
// ConfigDBHost specifies the host of the database
ConfigDBHost = "db.host"
// ConfigDBPort specifies the port of the database
ConfigDBPort = "db.port"
// ConfigDBName specifies the name of the database
ConfigDBName = "db.name"
// ConfigDBUser specifies the user of the database
ConfigDBUser = "db.user"
// ConfigDBPasswordPath specifies the path for file containing password of the database
ConfigDBPasswordPath = "db.passwordPath"
// ConfigDBPassword specifies the password of the database, not read from config file, rather from file specified by db.passwordPath
ConfigDBPassword = "db.password"
// ConfigTemporalHost specifies the hostname for Temporal
ConfigTemporalHost = "temporal.host"
// ConfigTemporalPort specifies the port for Temporal
ConfigTemporalPort = "temporal.port"
// ConfigTemporalServerName specifies the server name for Temporal
ConfigTemporalServerName = "temporal.serverName"
// ConfigTemporalNamespace specifies the namespace for Temporal
ConfigTemporalNamespace = "temporal.namespace"
// ConfigTemporalQueue specifies the queue for Temporal
ConfigTemporalQueue = "temporal.queue"
// ConfigTemporalTlsEnabled specifies if TLS should be used with Temporal
ConfigTemporalTlsEnabled = "temporal.tls.enabled"
// ConfigTemporalCertPath specifies the path for client cert
ConfigTemporalCertPath = "temporal.tls.certPath"
// ConfigTemporalKeyPath specifies the path for client key
ConfigTemporalKeyPath = "temporal.tls.keyPath"
// ConfigTemporalCaPath specifies the path for server CA cert
ConfigTemporalCaPath = "temporal.tls.caPath"
// ConfigTemporalEncryptionKey specifies the data encryption key for Temporal
ConfigTemporalEncryptionKey = "temporal.encryptionKey"
// ConfigTemporalEncryptionKeyPath specifies the path for file containing data encryption key for Temporal
ConfigTemporalEncryptionKeyPath = "temporal.encryptionKeyPath"
// ConfigSiteManagerEnabled is a feature flag for site manager
ConfigSiteManagerEnabled = "siteManager.enabled"
// ConfigSiteManagerEndpoint is the service endpoint for site manager
ConfigSiteManagerEndpoint = "siteManager.svcEndpoint"
// ConfigSitePhoneHomeUrl is a phone home url from the site
ConfigSitePhoneHomeUrl = "site.phoneHomeUrl"
// ConfigMetricsEnabled is a feature flag for Prometheus metrics
ConfigMetricsEnabled = "metrics.enabled"
// ConfigMetricsPort specifies the port for Prometheus metrics
ConfigMetricsPort = "metrics.port"
// ConfigTracingEnabled is a feature flag for tracing
ConfigTracingEnabled = "tracing.enabled"
// ConfigTracingServiceName is the name of the tracing service
ConfigTracingServiceName = "tracing.serviceName"
// ConfigKeycloakEnabled is a feature flag for Keycloak authentication
ConfigKeycloakEnabled = "keycloak.enabled"
// ConfigKeycloakBaseURL is the base URL of the Keycloak server
ConfigKeycloakBaseURL = "keycloak.baseURL"
// ConfigKeycloakExternalBaseURL is the external base URL of the Keycloak server
ConfigKeycloakExternalBaseURL = "keycloak.externalBaseURL"
// ConfigKeycloakRealm is the Keycloak realm name
ConfigKeycloakRealm = "keycloak.realm"
// ConfigKeycloakClientID is the Keycloak client ID
ConfigKeycloakClientID = "keycloak.clientID"
// ConfigKeycloakClientSecretPath is the path to the file containing the client secret
ConfigKeycloakClientSecretPath = "keycloak.clientSecretPath"
// ConfigKeycloakClientSecret is the client secret, read from the secret file
ConfigKeycloakClientSecret = "keycloak.clientSecret"
// ConfigKeycloakServiceAccountEnabled is a feature flag for service account support
ConfigKeycloakServiceAccountEnabled = "keycloak.serviceAccount"
// ConfigRateLimiterEnabled is a feature flag for rate limiter
ConfigRateLimiterEnabled = "rateLimiter.enabled"
// ConfigRateLimiterRate specifies the rate limit (requests per second)
ConfigRateLimiterRate = "rateLimiter.rate"
// ConfigRateLimiterBurst specifies the burst size
ConfigRateLimiterBurst = "rateLimiter.burst"
// ConfigRateLimiterExpiresIn specifies the expiration time in seconds
ConfigRateLimiterExpiresIn = "rateLimiter.expiresIn"
)
// IssuerConfig represents a single issuer configuration entry
// This is the preferred configuration format that supports claim mappings
type IssuerConfig struct {
Name string `mapstructure:"name"`
Origin string `mapstructure:"origin"` // String: "kas-legacy", "kas-ssa", "keycloak", "custom"
JWKS string `mapstructure:"jwks"`
Issuer string `mapstructure:"issuer"`
ServiceAccount bool `mapstructure:"serviceAccount"`
Audiences []string `mapstructure:"audiences"`
Scopes []string `mapstructure:"scopes"`
JWKSTimeout string `mapstructure:"jwksTimeout"` // e.g. "5s", "1m"
ClaimMappings []cauth.ClaimMapping `mapstructure:"claimMappings"`
AllowDuplicateStaticOrgNames bool `mapstructure:"allowDuplicateStaticOrgNames"` // When true, allows duplicate static org names across issuers
}
// GetOrigin parses the origin and returns it as a string constant
func (ic *IssuerConfig) GetOrigin() (string, error) {
return ParseOriginString(ic.Origin)
}
// GetJWKSTimeout parses and returns the JWKS timeout duration
func (ic *IssuerConfig) GetJWKSTimeout() (time.Duration, error) {
if ic.JWKSTimeout == "" {
return 0, nil // Use default
}
return time.ParseDuration(ic.JWKSTimeout)
}
// GetAllowDuplicateStaticOrgNames returns whether duplicate static org names are allowed
// Defaults to false (duplicates not allowed) if not specified
func (ic *IssuerConfig) GetAllowDuplicateStaticOrgNames() bool {
return ic.AllowDuplicateStaticOrgNames
}
// ParseOriginString converts a string origin to its string constant
func ParseOriginString(origin string) (string, error) {
normalized := strings.ToLower(origin)
if normalized == "" {
return cauth.TokenOriginCustom, nil
}
if slices.Contains(cauth.AllowedOrigins, normalized) {
return normalized, nil
}
return "", fmt.Errorf("unknown origin: %s", origin)
}
// RateLimiterConfig holds configuration for rate limiting
type RateLimiterConfig struct {
Enabled bool
Rate float64 // requests per second
Burst int // maximum burst size
ExpiresIn int // expiration time in seconds
}
// Maintain a global config object
var config *Config
// Config represents configurations for the service
type Config struct {
sync.RWMutex
v *viper.Viper
db *cconfig.DBConfig
temporal *cconfig.TemporalConfig
JwtOriginConfig *cauth.JWTOriginConfig
SiteConfig *SiteConfig
KeycloakConfig *cauth.KeycloakConfig
}
// NewConfig creates a new config object
func NewConfig() *Config {
if config != nil {
return config
}
c := Config{
v: viper.New(),
}
// Set defaults
c.v.SetDefault(ConfigLogLevel, "info")
c.v.SetDefault(ConfigEnvDev, false)
c.v.SetDefault(ConfigEnvDisconnected, false)
// Set API name
c.v.SetDefault(ConfigAPIName, "carbide")
c.v.SetDefault(ConfigAPIRouteVersion, "v1")
// Set config file
// Check environment variable. If not set, use default
defaultPath := ProjectRoot + "/config.yaml"
if os.Getenv(ConfigFilePathEnv) != "" {
c.v.SetDefault(ConfigFilePath, os.Getenv(ConfigFilePathEnv))
} else {
log.Warn().Msg("config file path not set, using default")
c.v.SetDefault(ConfigFilePath, defaultPath)
}
c.v.SetDefault(ConfigDBHost, "localhost")
c.v.SetDefault(ConfigDBPort, 5432)
c.v.SetDefault(ConfigTemporalHost, "localhost")
c.v.SetDefault(ConfigTemporalPort, 7233)
c.v.SetDefault(ConfigTemporalTlsEnabled, true)
c.v.SetDefault(ConfigMetricsEnabled, true)
c.v.SetDefault(ConfigMetricsPort, 9360)
c.v.SetDefault(ConfigTracingEnabled, false)
// SiteConfig default phone home url
c.v.SetDefault(ConfigSitePhoneHomeUrl, "http://localhost")
// Keycloak needs to be explicitly enabled via config
c.v.SetDefault(ConfigKeycloakEnabled, false)
// Service account support is disabled by default
c.v.SetDefault(ConfigKeycloakServiceAccountEnabled, false)
// Rate limiter is disabled by default
c.v.SetDefault(ConfigRateLimiterEnabled, false)
c.v.SetDefault(ConfigRateLimiterRate, 10.0) // 10 requests per second
c.v.SetDefault(ConfigRateLimiterBurst, 30) // burst of 30 requests
c.v.SetDefault(ConfigRateLimiterExpiresIn, 180) // 180 seconds (3 minutes)
c.v.AutomaticEnv()
c.v.SetConfigFile(c.GetPathToConfig())
log.Warn().Str("config.file", c.GetPathToConfig()).Msg("loading config")
err := c.v.ReadInConfig() // Find and read the config file
if _, ok := err.(*os.PathError); ok {
log.Warn().Msgf("no config file '%s' not found. Using default values", c.GetPathToConfig())
} else if err != nil { // Handle other errors that occurred while reading the config file
log.Panic().Err(err).Msgf("fatal error while reading the config file: %s", err)
}
// Set values
c.setLogLevel()
if c.GetDBPasswordPath() != "" {
c.setDBPassword()
}
if c.GetKeycloakEnabled() {
if c.GetKeycloakClientSecretPath() != "" {
log.Info().Str("keycloak.clientSecretPath", c.GetKeycloakClientSecretPath()).Msg("Keycloak is enabled, reading client secret")
c.SetKeycloakClientSecret()
} else {
log.Panic().Msg("Keycloak is enabled but client secret path is not set")
}
} else {
log.Info().Bool("keycloak.enabled", c.GetKeycloakEnabled()).Msg("Keycloak is disabled")
}
if c.GetTemporalEncryptionKey() == "" {
if c.GetTemporalEncryptionKeyPath() != "" {
c.SetTemporalEncryptionKey()
} else {
log.Panic().Msg("Temporal encryption key path is not set")
}
}
// Validate config
c.Validate()
// Watch secret files
c.WatchSecretFilePaths()
config = &c
return config
}
// Validate validates the config
func (c *Config) Validate() {
// Check configs that are essential but were not set
if c.GetDBName() == "" {
log.Panic().Msg("DB name config must be specified")
}
if c.GetDBUser() == "" {
log.Panic().Msg("DB user config must be specified")
}
if value := os.Getenv("NO_DB_PASSWORD_OK"); strings.EqualFold(value, "true") {
log.Info().Msg("connecting to DB without password")
} else {
if c.GetDBPassword() == "" && c.GetDBPasswordPath() == "" {
log.Panic().Msg("DB password or password path config must be specified")
}
}
if c.GetTemporalTlsEnabled() {
if c.GetTemporalCertPath() == "" {
log.Panic().Msg("Temporal cert path config must be specified")
}
if c.GetTemporalKeyPath() == "" {
log.Panic().Msg("Temporal key path config must be specified")
}
if c.GetTemporalCaPath() == "" {
log.Panic().Msg("Temporal CA path config must be specified")
}
}
if c.GetTemporalEncryptionKey() == "" {
log.Error().Msg("temporal encryption key config was not specified, arguments won't be encrypted")
}
// SiteConfig validations
if err := c.ValidateSiteConfig(); err != nil {
log.Panic().Err(err).Msg("SiteConfig must be specified")
}
// Validate that at least one auth method is configured
issuersConfig := c.GetIssuersConfig()
if len(issuersConfig) > 0 {
if err := c.ValidateIssuersConfig(issuersConfig); err != nil {
log.Panic().Err(err).Msg("Invalid issuers configuration")
}
}
keycloakEnabled := c.GetKeycloakEnabled()
// Keycloak validations
if err := c.ValidateKeycloakConfig(); err != nil {
log.Panic().Err(err).Msg("Keycloak config must be specified")
}
if len(issuersConfig) == 0 && !keycloakEnabled {
log.Panic().Msg("No JWT issuer based auth configured and Keycloak is disabled")
} else if len(issuersConfig) > 0 && keycloakEnabled {
log.Panic().Msg("KeyCloak is enabled, we cannot support any JWT issuer based configuration")
} else if len(issuersConfig) > 0 {
log.Info().Msgf("Loaded a total of %d JWT issuer based auth configuration", len(issuersConfig))
} else if keycloakEnabled {
log.Info().Msg("Keycloak authentication is enabled")
}
}
// Config setters
// setLogLevel sets the log level
func (c *Config) setLogLevel() {
logLevel := c.GetLogLevel()
log.Warn().Str("level", logLevel).Msg("setting log level")
level, err := zerolog.ParseLevel(logLevel)
if err != nil {
log.Err(err).Str("level", logLevel).Msg("failed to parse log level from config")
}
zerolog.SetGlobalLevel(level)
}
// setDBPassword sets the password for the database
func (c *Config) setDBPassword() {
log.Warn().Str("db.passwordPath", c.GetDBPasswordPath()).Msg("setting password by reading from password path")
passwordBytes, err := os.ReadFile(c.GetDBPasswordPath())
if err != nil {
log.Err(err).Str("db.passwordPath", c.GetDBPasswordPath()).Msg("failed to read password from file")
}
c.Lock()
defer c.Unlock()
c.v.Set(ConfigDBPassword, string(passwordBytes))
}
/* Get sub-configurations */
// GetDBConfig returns the database config
func (c *Config) GetDBConfig() *cconfig.DBConfig {
if c.db == nil {
c.db = cconfig.NewDBConfig(c.GetDBHost(), c.GetDBPort(), c.GetDBName(), c.GetDBUser(), c.GetDBPassword())
}
return c.db
}
// GetTemporalConfig returns the temporal config
func (c *Config) GetTemporalConfig() (*cconfig.TemporalConfig, error) {
var err error
if c.temporal == nil {
c.temporal, err = cconfig.NewTemporalConfig(c.GetTemporalHost(), c.GetTemporalPort(), c.GetTemporalServerName(), c.GetTemporalNamespace(), c.GetTemporalQueue(), c.GetTemporalEncryptionKey(), c.GetTemporalTlsEnabled(), c.GetTemporalCertPath(), c.GetTemporalKeyPath(), c.GetTemporalCaPath())
}
return c.temporal, err
}
// GetOrInitJWTOrigin returns the JWT origin config with all configured auth providers
func (c *Config) GetOrInitJWTOriginConfig() *cauth.JWTOriginConfig {
if c.JwtOriginConfig == nil {
c.JwtOriginConfig = cauth.NewJWTOriginConfig()
// Load and validate issuers config
issuersConfig := c.GetIssuersConfig()
if err := c.ValidateIssuersConfig(issuersConfig); err != nil {
log.Panic().Err(err).Msg("Invalid issuers configuration")
}
// First pass: collect all static org names (lowercased) from all issuers
reservedOrgNames := make(map[string]bool)
for _, issuerCfg := range issuersConfig {
for _, mapping := range issuerCfg.ClaimMappings {
if mapping.OrgName != "" {
reservedOrgNames[strings.ToLower(mapping.OrgName)] = true
}
}
}
// Second pass: create jwksConfigs and assign reservedOrgNames only to those with dynamic mappings
for _, issuerCfg := range issuersConfig {
origin, _ := issuerCfg.GetOrigin() // Already validated
jwksTimeout, _ := issuerCfg.GetJWKSTimeout()
// Normalize org names in claim mappings and check for dynamic mappings
normalizedMappings := make([]cauth.ClaimMapping, len(issuerCfg.ClaimMappings))
hasDynamicMapping := false
for i, mapping := range issuerCfg.ClaimMappings {
normalizedMappings[i] = mapping
if mapping.OrgName != "" {
normalizedMappings[i].OrgName = strings.ToLower(mapping.OrgName)
}
if mapping.OrgAttribute != "" {
hasDynamicMapping = true
}
}
jwksCfg := cauth.NewJwksConfig(
issuerCfg.Name,
issuerCfg.JWKS,
issuerCfg.Issuer,
origin,
issuerCfg.ServiceAccount,
issuerCfg.Audiences,
issuerCfg.Scopes,
)
jwksCfg.JWKSTimeout = jwksTimeout
jwksCfg.ClaimMappings = normalizedMappings
// Only assign reservedOrgNames to configs with dynamic claim mappings
if hasDynamicMapping {
jwksCfg.ReservedOrgNames = reservedOrgNames
}
c.JwtOriginConfig.AddJwksConfig(jwksCfg)
}
// Add Keycloak configuration if enabled
if c.GetKeycloakEnabled() {
keycloakConfig, err := c.GetOrInitKeycloakConfig()
if err != nil {
log.Warn().Err(err).Msg("Failed to get Keycloak config, skipping Keycloak JWT origin")
} else {
jwksConfig, err := keycloakConfig.GetJwksConfig()
if err != nil {
log.Warn().Err(err).Msg("Failed to get Keycloak JWKS config, skipping Keycloak JWT origin")
} else {
c.JwtOriginConfig.AddJwksConfig(jwksConfig)
}
}
}
// Initialize JWKS data
if err := c.JwtOriginConfig.UpdateAllJWKS(); err != nil {
log.Warn().Err(err).Msg("Failed to update JWKS data")
return nil
} else {
log.Info().Msg("Successfully updated JWKS data")
}
}
return c.JwtOriginConfig
}
// GetSiteConfig returns the Site config
func (c *Config) GetSiteConfig() *SiteConfig {
if c.SiteConfig == nil {
c.SiteConfig = NewSiteConfig(c.GetEnvDisconnected(), c.GetSitePhoneHomeUrl())
}
return c.SiteConfig
}
// GetMetricsConfig returns the Metrics config
func (c *Config) GetMetricsConfig() *MetricsConfig {
return NewMetricsConfig(c.GetMetricsEnabled(), c.GetMetricsPort())
}
// GetRateLimiterConfig returns the rate limiter config
func (c *Config) GetRateLimiterConfig() *RateLimiterConfig {
return NewRateLimiterConfig(c.GetRateLimiterEnabled(), c.GetRateLimiterRate(), c.GetRateLimiterBurst(), c.GetRateLimiterExpiresIn())
}
// NewRateLimiterConfig initializes and returns a configuration object for rate limiting
func NewRateLimiterConfig(enabled bool, rate float64, burst int, expiresIn int) *RateLimiterConfig {
return &RateLimiterConfig{
Enabled: enabled,
Rate: rate,
Burst: burst,
ExpiresIn: expiresIn,
}
}
// GetIssuersConfig returns the issuer configurations from the config file
func (c *Config) GetIssuersConfig() []IssuerConfig {
var issuersConfig []IssuerConfig
if err := c.v.UnmarshalKey("issuers", &issuersConfig); err != nil {
log.Warn().Err(err).Msg("Failed to unmarshal issuer configurations, using empty list")
return []IssuerConfig{}
}
return issuersConfig
}
// ValidateIssuersConfig validates the issuer configurations
func (c *Config) ValidateIssuersConfig(issuers []IssuerConfig) error {
seenNames := make(map[string]bool)
seenURLs := make(map[string]bool)
seenStaticOrgs := make(map[string]bool)
seenDynamicOrg := false
for i, issuer := range issuers {
// Validate required fields
if issuer.Name == "" {
return fmt.Errorf("issuer %d: name is required", i)
}
if issuer.JWKS == "" {
return fmt.Errorf("issuer %s: jwks URL is required", issuer.Name)
}
if issuer.Issuer == "" {
return fmt.Errorf("issuer %s: issuer is required", issuer.Name)
}
// Check for duplicate names
if seenNames[issuer.Name] {
return fmt.Errorf("duplicate issuer name: %s", issuer.Name)
}
seenNames[issuer.Name] = true
// Check for duplicate JWKS URLs
if seenURLs[issuer.JWKS] {
return fmt.Errorf("duplicate JWKS URL: %s (issuer: %s)", issuer.JWKS, issuer.Name)
}
seenURLs[issuer.JWKS] = true
// Validate origin
origin, err := issuer.GetOrigin()
if err != nil {
return fmt.Errorf("issuer %s: %w", issuer.Name, err)
}
// ClaimMappings are only allowed for custom origin issuers
// keycloak, kas-ssa, and kas-legacy have their own predefined claim extraction logic
if len(issuer.ClaimMappings) > 0 && origin != cauth.TokenOriginCustom {
return fmt.Errorf("issuer %s: claimMappings are only allowed for custom origin issuers (origin: %s)", issuer.Name, origin)
}
// Validate JWKS timeout if specified
if issuer.JWKSTimeout != "" {
if _, err := issuer.GetJWKSTimeout(); err != nil {
return fmt.Errorf("issuer %s: invalid jwksTimeout: %w", issuer.Name, err)
}
}
for j, mapping := range issuer.ClaimMappings {
if mapping.OrgAttribute == "" && mapping.OrgName == "" {
return fmt.Errorf("issuer %s: claimMapping %d: either orgAttribute or orgName must be specified", issuer.Name, j)
}
if mapping.OrgAttribute != "" && mapping.OrgName != "" {
return fmt.Errorf("issuer %s: claimMapping %d: cannot specify both orgAttribute and orgName", issuer.Name, j)
}
// orgDisplayName can only be specified with orgName (static org), not with orgAttribute (dynamic org)
if mapping.OrgDisplayName != "" && mapping.OrgName == "" {
return fmt.Errorf("issuer %s: claimMapping %d: orgDisplayName can only be specified when orgName is specified", issuer.Name, j)
}
// roles and rolesAttribute are mutually exclusive
if len(mapping.Roles) > 0 && mapping.RolesAttribute != "" {
return fmt.Errorf("issuer %s: claimMapping %d: cannot specify both roles and rolesAttribute", issuer.Name, j)
}
// Service account validation
if mapping.IsServiceAccount {
if len(mapping.Roles) > 0 {
return fmt.Errorf("issuer %s: claimMapping %d: roles cannot be specified when isServiceAccount is true", issuer.Name, j)
}
if mapping.RolesAttribute != "" {
return fmt.Errorf("issuer %s: claimMapping %d: rolesAttribute cannot be specified when isServiceAccount is true", issuer.Name, j)
}
if mapping.OrgAttribute != "" {
return fmt.Errorf("issuer %s: claimMapping %d: orgAttribute cannot be specified when isServiceAccount is true", issuer.Name, j)
}
}
// Dynamic org mapping
if mapping.OrgAttribute != "" {
if seenDynamicOrg {
return fmt.Errorf("issuer %s: only one dynamic org mapping is allowed", issuer.Name)
}
seenDynamicOrg = true
}
// Static org mapping - check for duplicates unless allowDuplicateStaticOrgNames is true
if mapping.OrgName != "" {
normalizedOrg := strings.ToLower(mapping.OrgName)
if seenStaticOrgs[normalizedOrg] && !issuer.GetAllowDuplicateStaticOrgNames() {
return fmt.Errorf("issuer %s: duplicate static org: %s", issuer.Name, mapping.OrgName)
}
seenStaticOrgs[normalizedOrg] = true
}
// Validate roles - skip if service account (uses predefined roles)
if !mapping.IsServiceAccount && len(mapping.Roles) == 0 && mapping.RolesAttribute == "" {
return fmt.Errorf("issuer %s: claimMapping %d: either roles or rolesAttribute must be specified (unless isServiceAccount is true)", issuer.Name, j)
}
// Validate role values if specified
for _, role := range mapping.Roles {
if !cauth.IsValidRole(role) {
return fmt.Errorf("issuer %s: claimMapping %d: invalid role: %s", issuer.Name, j, role)
}
}
}
// Service account validation
if issuer.ServiceAccount {
if !c.GetEnvDisconnected() {
return fmt.Errorf("issuer %s: service account is only supported in disconnected mode", issuer.Name)
}
}
}
return nil
}
/* Config getters */
// GetPathToConfig returns the path to the config file
func (c *Config) GetPathToConfig() string {
return c.v.GetString(ConfigFilePath)
}
// GetEnvDev returns if the service is running in development mode
func (c *Config) GetEnvDev() bool {
s := c.v.GetBool(ConfigEnvDev)
return s
}
// GetEnvDisconnected returns if the service is running in disconnected mode
func (c *Config) GetEnvDisconnected() bool {
return c.v.GetBool(ConfigEnvDisconnected)
}
// GetAPIName returns the name of the API
func (c *Config) GetAPIName() string {
return c.v.GetString(ConfigAPIName)
}
// GetAPIRouteVersion returns the version of the API
func (c *Config) GetAPIRouteVersion() string {
return c.v.GetString(ConfigAPIRouteVersion)
}
// GetLogLevel returns the log level
func (c *Config) GetLogLevel() string {
return c.v.GetString(ConfigLogLevel)
}
// GetSentryDSN returns the DSN for Sentry
func (c *Config) GetSentryDSN() string {
return c.v.GetString(ConfigSentryDSN)
}
// GetDBHost returns the host of the database
func (c *Config) GetDBHost() string {
return c.v.GetString(ConfigDBHost)
}
// GetDBPort returns the port of the database
func (c *Config) GetDBPort() int {
return c.v.GetInt(ConfigDBPort)
}
// GetDBName returns the name of the database
func (c *Config) GetDBName() string {
return c.v.GetString(ConfigDBName)
}
// GetDBUser returns the user of the database
func (c *Config) GetDBUser() string {
return c.v.GetString(ConfigDBUser)
}
// GetDBPasswordPath returns the path for file containing password of the database
func (c *Config) GetDBPasswordPath() string {
return c.v.GetString(ConfigDBPasswordPath)
}
// GetDBPassword returns the password of the database
func (c *Config) GetDBPassword() string {
c.RLock()
defer c.RUnlock()
return c.v.GetString(ConfigDBPassword)
}
// GetTemporalHost returns the hostname for Temporal
func (c *Config) GetTemporalHost() string {
return c.v.GetString(ConfigTemporalHost)
}
// GetTemporalPort returns the port for Temporal
func (c *Config) GetTemporalPort() int {
return c.v.GetInt(ConfigTemporalPort)
}
// GetTemporalServerName returns the server name for Temporal
func (c *Config) GetTemporalServerName() string {
return c.v.GetString(ConfigTemporalServerName)
}
// GetTemporalNamespace returns the namespace for Temporal
func (c *Config) GetTemporalNamespace() string {
return c.v.GetString(ConfigTemporalNamespace)
}
// GetTemporalQueue returns the queue for Temporal
func (c *Config) GetTemporalQueue() string {
return c.v.GetString(ConfigTemporalQueue)
}
// GetTemporalTlsEnabled returns true if TLS is enabled for Temporal connection
func (c *Config) GetTemporalTlsEnabled() bool {
return c.v.GetBool(ConfigTemporalTlsEnabled)
}
// GetTemporalCertPath returns the path for client cert for Temporal
func (c *Config) GetTemporalCertPath() string {
return c.v.GetString(ConfigTemporalCertPath)
}
// SetTemporalCertPath set the path for client cert for Temporal
func (c *Config) SetTemporalCertPath(value string) {
c.v.Set(ConfigTemporalCertPath, value)
}
// GetTemporalKeyPath returns the path for client key for Temporal
func (c *Config) GetTemporalKeyPath() string {
return c.v.GetString(ConfigTemporalKeyPath)
}
// SetTemporalKeyPath set the path for client key for Temporal
func (c *Config) SetTemporalKeyPath(value string) {
c.v.Set(ConfigTemporalKeyPath, value)
}
// GetTemporalCaPath returns the path for ca cert for Temporal
func (c *Config) GetTemporalCaPath() string {
return c.v.GetString(ConfigTemporalCaPath)
}
// SetTemporalCaPath sets the path for ca for Temporal
func (c *Config) SetTemporalCaPath(value string) {
c.v.Set(ConfigTemporalCaPath, value)
}
// GetTemporalEncryptionKeyPath returns the path for file containing encryption key for Temporal
func (c *Config) GetTemporalEncryptionKeyPath() string {
return c.v.GetString(ConfigTemporalEncryptionKeyPath)
}
// SetTemporalEncryptionKeyPath sets the path for file containing encryption key for Temporal
func (c *Config) SetTemporalEncryptionKeyPath(value string) {
c.v.Set(ConfigTemporalEncryptionKeyPath, value)
}
// GetTemporalEncryptionKey returns the encryption key for Temporal
func (c *Config) GetTemporalEncryptionKey() string {
return c.v.GetString(ConfigTemporalEncryptionKey)
}
// SetTemporalEncryptionKey sets the encryption key for Temporal
func (c *Config) SetTemporalEncryptionKey() {
log.Warn().Str("temporal.encryptionKeyPath", c.GetTemporalEncryptionKeyPath()).Msg("setting Temporal encryption key by reading from file")
encryptionKeyBytes, err := os.ReadFile(c.GetTemporalEncryptionKeyPath())
if err != nil {
log.Panic().Err(err).Msgf("failed to read encryption key file: %s", err)
}
encryptionKey := strings.TrimSpace(string(encryptionKeyBytes))
c.v.Set(ConfigTemporalEncryptionKey, encryptionKey)
}
// ValidateSiteConfig validates Site configs
func (c *Config) ValidateSiteConfig() error {
if c.GetSitePhoneHomeUrl() == "" {
return fmt.Errorf("invalid Site PhoneHome url")
}
return nil
}
// SetSiteManagerEnabled sets the enabled field
func (c *Config) SetSiteManagerEnabled(value bool) {
c.v.Set(ConfigSiteManagerEnabled, value)
}
// GetSiteManagerEnabled sets the enabled field
func (c *Config) GetSiteManagerEnabled() bool {
return c.v.GetBool(ConfigSiteManagerEnabled)
}
// SetSiteManagerEndpoint sets the endpoint
func (c *Config) SetSiteManagerEndpoint(value string) {
c.v.Set(ConfigSiteManagerEndpoint, value)
}
// GetSiteManagerEndpoint gets the path for site manager service endpoint
func (c *Config) GetSiteManagerEndpoint() string {
return c.v.GetString(ConfigSiteManagerEndpoint)
}
// SetSitePhoneHomeUrl sets the url for PhoneHome
func (c *Config) SetSitePhoneHomeUrl(value string) {
c.v.Set(ConfigSitePhoneHomeUrl, value)
}
// GetSitePhoneHomeUrl gets the url for PhoneHome
func (c *Config) GetSitePhoneHomeUrl() string {
return c.v.GetString(ConfigSitePhoneHomeUrl)
}
// GetMetricsEnabled gets the enabled field for Metrics
func (c *Config) GetMetricsEnabled() bool {
return c.v.GetBool(ConfigMetricsEnabled)
}
// GetZincSearchPort gets the port for Metrics
func (c *Config) GetMetricsPort() int {
return c.v.GetInt(ConfigMetricsPort)
}
// GetTracingEnabled gets the enabled field for tracing
func (c *Config) GetTracingEnabled() bool {
return c.v.GetBool(ConfigTracingEnabled)
}
// GetTracingServiceName gets the service name for tracing
func (c *Config) GetTracingServiceName() string {
return c.v.GetString(ConfigTracingServiceName)
}
// Keycloak configuration methods
// GetKeycloakEnabled gets the enabled field for Keycloak
func (c *Config) GetKeycloakEnabled() bool {
return c.v.GetBool(ConfigKeycloakEnabled)
}
// SetKeycloakEnabled sets the enabled field for Keycloak
func (c *Config) SetKeycloakEnabled(value bool) {
c.v.Set(ConfigKeycloakEnabled, value)
}
// GetKeycloakBaseURL gets the base URL for Keycloak
func (c *Config) GetKeycloakBaseURL() string {
return c.v.GetString(ConfigKeycloakBaseURL)
}
// SetKeycloakBaseURL sets the base URL for Keycloak
func (c *Config) SetKeycloakBaseURL(value string) {
c.v.Set(ConfigKeycloakBaseURL, value)
}
// GetKeycloakExternalBaseURL gets the external base URL for Keycloak
func (c *Config) GetKeycloakExternalBaseURL() string {
return c.v.GetString(ConfigKeycloakExternalBaseURL)
}
// SetKeycloakExternalBaseURL sets the external base URL for Keycloak
func (c *Config) SetKeycloakExternalBaseURL(value string) {
c.v.Set(ConfigKeycloakExternalBaseURL, value)
}
// GetKeycloakRealm gets the realm for Keycloak
func (c *Config) GetKeycloakRealm() string {
return c.v.GetString(ConfigKeycloakRealm)
}
// SetKeycloakRealm sets the realm for Keycloak
func (c *Config) SetKeycloakRealm(value string) {
c.v.Set(ConfigKeycloakRealm, value)
}
// GetKeycloakClientID gets the client ID for Keycloak
func (c *Config) GetKeycloakClientID() string {
return c.v.GetString(ConfigKeycloakClientID)
}
// SetKeycloakClientID sets the client ID for Keycloak
func (c *Config) SetKeycloakClientID(value string) {
c.v.Set(ConfigKeycloakClientID, value)
}
// GetKeycloakClientSecretPath gets the client secret path for Keycloak
func (c *Config) GetKeycloakClientSecretPath() string {
return c.v.GetString(ConfigKeycloakClientSecretPath)
}
// SetKeycloakClientSecretPath sets the client secret path for Keycloak
func (c *Config) SetKeycloakClientSecretPath(value string) {
c.v.Set(ConfigKeycloakClientSecretPath, value)
}
// GetKeycloakClientSecret gets the client secret for Keycloak
func (c *Config) GetKeycloakClientSecret() string {
return c.v.GetString(ConfigKeycloakClientSecret)
}
// SetKeycloakClientSecret sets the client secret for Keycloak
func (c *Config) SetKeycloakClientSecret() {
log.Warn().Str("keycloak.clientSecretPath", c.GetKeycloakClientSecretPath()).Msg("setting keycloak client secret by reading from secret path")
secretBytes, err := os.ReadFile(c.GetKeycloakClientSecretPath())
if err != nil {
log.Panic().Err(err).Msgf("failed to read keycloak client secret file: %s", err)
}
secret := strings.TrimSpace(string(secretBytes))
c.v.Set(ConfigKeycloakClientSecret, secret)
}
// GetKeycloakServiceAccountEnabled gets the service account enabled flag for Keycloak
func (c *Config) GetKeycloakServiceAccountEnabled() bool {
return c.v.GetBool(ConfigKeycloakServiceAccountEnabled)
}
// SetKeycloakServiceAccountEnabled sets the service account enabled flag for Keycloak
func (c *Config) SetKeycloakServiceAccountEnabled(value bool) {
c.v.Set(ConfigKeycloakServiceAccountEnabled, value)
}
// GetOrInitKeycloakConfig gets the Keycloak configuration
func (c *Config) GetOrInitKeycloakConfig() (*cauth.KeycloakConfig, error) {
if c.KeycloakConfig == nil {
if !c.GetKeycloakEnabled() {
log.Info().Msg("Keycloak is disabled in configuration")
return nil, errors.New("Keycloak is not enabled")
}
log.Info().Str("baseURL", c.GetKeycloakBaseURL()).
Str("externalBaseURL", c.GetKeycloakExternalBaseURL()).
Str("realm", c.GetKeycloakRealm()).
Str("clientID", c.GetKeycloakClientID()).
Str("clientSecretPath", c.GetKeycloakClientSecretPath()).
Msg("Creating new Keycloak configuration")