-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathconfig.go
More file actions
604 lines (488 loc) · 17.5 KB
/
Copy pathconfig.go
File metadata and controls
604 lines (488 loc) · 17.5 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
package config
import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
"os/user"
"path/filepath"
"runtime"
"runtime/debug"
"strings"
"sync"
"github.com/serverlessworkflow/sdk-go/v3/model"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
"github.com/subosito/gotenv"
"github.com/thand-io/agent/internal/common"
"github.com/thand-io/agent/internal/config/environment"
"github.com/thand-io/agent/internal/sessions"
)
var ErrNoActiveLoginSession = fmt.Errorf(
"you must login first. No valid session found to sync with login server")
func DefaultConfig() *Config {
v := viper.New()
// Set default values
setDefaults(v)
var config Config
if err := v.Unmarshal(&config); err != nil {
log.Fatalf("error unmarshaling default config: %v", err)
}
return &config
}
// Load loads the configuration from various sources
func Load(configFile string) (*Config, error) {
if err := loadEnvFile(); err != nil {
return nil, err
}
v := viper.New()
if err := setupViperConfig(v, configFile); err != nil {
return nil, err
}
bindEnvironmentVariables(v)
config, err := readAndUnmarshalConfig(v)
if err != nil {
return nil, err
}
if err := setupLogging(config, v); err != nil {
return nil, err
}
return config, nil
}
// loadEnvFile loads the .env file if it exists
func loadEnvFile() error {
if err := gotenv.Load(); err != nil {
// .env file not found, that's okay - continue with other sources
if !os.IsNotExist(err) {
fmt.Printf("Warning: Error loading .env file: %v\n", err)
}
}
return nil
}
// setupViperConfig configures viper with file paths and defaults
func setupViperConfig(v *viper.Viper, configFile string) error {
// Set configuration file details
v.SetConfigName("config")
v.SetConfigType("yaml")
v.AddConfigPath(".")
v.AddConfigPath("./config")
v.AddConfigPath("/etc/thand")
v.AddConfigPath("~/.config/thand")
if len(configFile) > 0 {
v.SetConfigFile(configFile)
}
if err := setupHomeConfigPath(v); err != nil {
return err
}
// Set default values
setDefaults(v)
// Set environment variable settings
v.SetEnvPrefix("THAND")
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
v.AutomaticEnv()
v.AllowEmptyEnv(true)
return nil
}
// setupHomeConfigPath adds the home directory config path if available
func setupHomeConfigPath(v *viper.Viper) error {
home := os.Getenv("HOME")
if len(home) == 0 {
return nil
}
// Get the user's home directory
usr, err := user.Current()
if err != nil {
log.Fatalf("Failed to get current user: %v", err)
}
// Expand the session manager path to use the actual home directory
sessionPath := filepath.Join(usr.HomeDir, ".config", "thand")
v.AddConfigPath(sessionPath)
// Check if the folder exists and create it if it does not exist
if _, err := os.Stat(sessionPath); os.IsNotExist(err) {
if err := os.MkdirAll(sessionPath, os.ModePerm); err != nil {
logrus.Errorf("Failed to create config directory: %v", err)
}
}
return nil
}
// bindEnvironmentVariables binds all environment variables to viper
func bindEnvironmentVariables(v *viper.Viper) {
// Set base environment variables
v.BindEnv("login.endpoint", "THAND_LOGIN_ENDPOINT")
v.BindEnv("login.endpoint", "THAND_BASE_URL")
// Platform environment variables
v.BindEnv("environment.platform", "THAND_ENVIRONMENT_PLATFORM")
// Default api key and timeout
v.BindEnv("environment.config.api_key", "THAND_ENVIRONMENT_CONFIG_API_KEY")
v.BindEnv("environment.config.timeout", "THAND_ENVIRONMENT_CONFIG_TIMEOUT")
bindCloudProviderEnvVars(v)
bindVaultEnvVars(v)
bindLoggingEnvVars(v)
bindServiceEnvVars(v)
}
// bindCloudProviderEnvVars binds cloud provider specific environment variables
func bindCloudProviderEnvVars(v *viper.Viper) {
// GCP environment variables
v.BindEnv("environment.config.project_id", "THAND_ENVIRONMENT_CONFIG_PROJECT_ID")
v.BindEnv("environment.config.location", "THAND_ENVIRONMENT_CONFIG_LOCATION")
v.BindEnv("environment.config.key_ring", "THAND_ENVIRONMENT_CONFIG_KEY_RING")
v.BindEnv("environment.config.key_name", "THAND_ENVIRONMENT_CONFIG_KEY_NAME")
// Azure environment variables
v.BindEnv("environment.config.vault_url", "THAND_ENVIRONMENT_CONFIG_VAULT_URL")
// AWS environment variables
v.BindEnv("environment.config.profile", "THAND_ENVIRONMENT_CONFIG_PROFILE")
v.BindEnv("environment.config.region", "THAND_ENVIRONMENT_CONFIG_REGION")
v.BindEnv("environment.config.access_key_id", "THAND_ENVIRONMENT_CONFIG_ACCESS_KEY_ID")
v.BindEnv("environment.config.secret_access_key", "THAND_ENVIRONMENT_CONFIG_SECRET_ACCESS_KEY")
v.BindEnv("environment.config.kms_arn", "THAND_ENVIRONMENT_CONFIG_KMS_ARN")
v.BindEnv("environment.config.imds_disable", "THAND_ENVIRONMENT_CONFIG_IMDS_DISABLE")
}
// bindVaultEnvVars binds HashiCorp Vault and secret management environment variables
func bindVaultEnvVars(v *viper.Viper) {
// HashiCorp Vault environment variables
v.BindEnv("environment.config.secret_path", "THAND_ENVIRONMENT_CONFIG_SECRET_PATH")
v.BindEnv("environment.config.mount_path", "THAND_ENVIRONMENT_CONFIG_MOUNT_PATH")
// Define vault names for secret key lookups
v.BindEnv("roles.vault", "THAND_ROLES_VAULT")
v.BindEnv("workflows.vault", "THAND_WORKFLOWS_VAULT")
v.BindEnv("providers.vault", "THAND_PROVIDERS_VAULT")
}
// bindLoggingEnvVars binds logging configuration environment variables
func bindLoggingEnvVars(v *viper.Viper) {
v.BindEnv("logging.level", "THAND_LOGGING_LEVEL")
v.BindEnv("logging.format", "THAND_LOGGING_FORMAT")
v.BindEnv("logging.output", "THAND_LOGGING_OUTPUT")
}
// bindServiceEnvVars binds service configuration environment variables
func bindServiceEnvVars(v *viper.Viper) {
// LLM service environment variables
v.BindEnv("services.llm.provider", "THAND_SERVICES_LLM_PROVIDER")
v.BindEnv("services.llm.api_key", "THAND_SERVICES_LLM_API_KEY")
v.BindEnv("services.llm.base_url", "THAND_SERVICES_LLM_BASE_URL")
v.BindEnv("services.llm.model", "THAND_SERVICES_LLM_MODEL")
// Temporal service environment variables
v.BindEnv("services.temporal.host", "THAND_SERVICES_TEMPORAL_HOST")
v.BindEnv("services.temporal.port", "THAND_SERVICES_TEMPORAL_PORT")
v.BindEnv("services.temporal.namespace", "THAND_SERVICES_TEMPORAL_NAMESPACE")
v.BindEnv("services.temporal.mtls_pem", "THAND_SERVICES_TEMPORAL_MTLS_PEM")
v.BindEnv("services.temporal.api_key", "THAND_SERVICES_TEMPORAL_API_KEY")
}
// readAndUnmarshalConfig reads the configuration file and unmarshals it
func readAndUnmarshalConfig(v *viper.Viper) (*Config, error) {
// Read configuration file
if err := v.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
return nil, fmt.Errorf("error reading config file: %w", err)
}
// Config file not found; proceed with defaults and environment variables
}
var config Config
if err := v.Unmarshal(&config); err != nil {
return nil, fmt.Errorf("error unmarshaling config: %w", err)
}
return &config, nil
}
// setupLogging configures the logging system based on the config
func setupLogging(config *Config, v *viper.Viper) error {
// Set logging level
logrusLevel, err := logrus.ParseLevel(config.Logging.Level)
if err != nil {
return fmt.Errorf("error parsing log level: %w", err)
}
logrus.SetLevel(logrusLevel)
config.logger = *NewThandLogger()
logrus.AddHook(&config.logger)
// Set logging format
switch strings.ToLower(config.Logging.Format) {
case "json":
logrus.SetFormatter(&logrus.JSONFormatter{})
case "text":
logrus.SetFormatter(&logrus.TextFormatter{
FullTimestamp: true,
})
default:
logrus.WithFields(logrus.Fields{
"format": config.Logging.Format,
}).Warn("Unknown log format")
}
// Dump out the config settings if in debug mode
if logrusLevel >= logrus.DebugLevel {
for key, value := range v.AllSettings() {
logrus.Debugf("Config '%s': %v\n", key, value)
}
}
return nil
}
func (c *Config) ReloadConfig() error {
var wg sync.WaitGroup
var mu sync.Mutex
var foundErrors []error
// Load roles in parallel
wg.Go(func() {
roles, err := c.LoadRoles()
if err != nil {
logrus.WithError(err).Errorln("Error loading roles")
mu.Lock()
foundErrors = append(foundErrors, fmt.Errorf("loading roles: %w", err))
mu.Unlock()
} else if len(roles) > 0 {
logrus.Infoln("Loaded roles from external source:", len(roles))
mu.Lock()
c.Roles.Definitions = roles
mu.Unlock()
} else {
logrus.Warningln("No roles loaded from external source")
}
})
// Load workflows in parallel
wg.Go(func() {
workflows, err := c.LoadWorkflows()
if err != nil {
logrus.WithError(err).Errorln("Error loading workflows")
mu.Lock()
foundErrors = append(foundErrors, fmt.Errorf("loading workflows: %w", err))
mu.Unlock()
} else if len(workflows) > 0 {
logrus.Infoln("Loaded workflows from external source:", len(workflows))
mu.Lock()
c.Workflows.Definitions = workflows
mu.Unlock()
} else {
logrus.Warningln("No workflows loaded from external source")
}
})
// Load providers in parallel
wg.Go(func() {
providers, err := c.LoadProviders()
if err != nil {
logrus.WithError(err).Errorln("Error loading providers")
mu.Lock()
foundErrors = append(foundErrors, fmt.Errorf("loading providers: %w", err))
mu.Unlock()
} else if len(providers) > 0 {
logrus.Infoln("Loaded providers from external source:", len(providers))
mu.Lock()
c.Providers.Definitions = providers
mu.Unlock()
} else {
logrus.Warningln("No providers loaded from external source")
}
})
// Wait for all goroutines to complete
wg.Wait()
// Return first error if any occurred
if len(foundErrors) > 0 {
return errors.Join(foundErrors...)
}
return nil
}
func (c *Config) HasLoginServer() bool {
return len(c.Login.Endpoint) > 0
}
func (c *Config) SyncWithLoginServer() error {
if len(c.Login.Endpoint) == 0 {
return fmt.Errorf("no login server endpoint configured")
}
// Providers need to be hard synced. Everything else
// can be done async
apiUrl := c.DiscoverLoginServerApiUrl()
sessionManager := sessions.GetSessionManager()
loginServer, err := sessionManager.GetLoginServer(c.GetLoginServerHostname())
if err != nil {
return fmt.Errorf("failed to get login server session: %w", err)
}
localToken := ""
if c.HasAPIKey() {
logrus.Debugln("Using API key for login server authentication")
localToken = c.GetAPIKey()
} else {
logrus.Debugf("Looking for valid session to sync with login server at: %s", apiUrl)
localSessions := loginServer.GetSessions()
// Find the first non-expired session token
for providerName, session := range localSessions {
if !session.IsExpired() {
logrus.Debugf("Found valid session for provider '%s'", providerName)
localToken = session.GetEncodedLocalSession()
break
}
}
if len(localToken) == 0 {
return ErrNoActiveLoginSession
}
}
// Lets make our registration request. This will pull down our
// remote configuration and also register this instance with the login server
_, err = c.RegisterWithLoginServer(localToken)
if err != nil {
return fmt.Errorf("failed to register with login server: %w", err)
}
logrus.Debugf("Syncing configuration with login server at: %s", apiUrl)
// Overwrite everything.
c.Providers = ProviderConfig{
URL: &model.Endpoint{
EndpointConfig: &model.EndpointConfiguration{
URI: &model.LiteralUri{Value: fmt.Sprintf("%s/providers", apiUrl)},
Authentication: &model.ReferenceableAuthenticationPolicy{
AuthenticationPolicy: &model.AuthenticationPolicy{
Bearer: &model.BearerAuthenticationPolicy{
Token: localToken,
},
},
},
},
},
}
c.Roles = RoleConfig{
URL: &model.Endpoint{
EndpointConfig: &model.EndpointConfiguration{
URI: &model.LiteralUri{Value: fmt.Sprintf("%s/roles", apiUrl)},
Authentication: &model.ReferenceableAuthenticationPolicy{
AuthenticationPolicy: &model.AuthenticationPolicy{
Bearer: &model.BearerAuthenticationPolicy{
Token: localToken,
},
},
},
},
},
}
c.Workflows = WorkflowConfig{
URL: &model.Endpoint{
EndpointConfig: &model.EndpointConfiguration{
URI: &model.LiteralUri{Value: fmt.Sprintf("%s/workflows", apiUrl)},
Authentication: &model.ReferenceableAuthenticationPolicy{
AuthenticationPolicy: &model.AuthenticationPolicy{
Bearer: &model.BearerAuthenticationPolicy{
Token: localToken,
},
},
},
},
},
}
err = c.ReloadConfig()
if err != nil {
logrus.WithError(err).Errorln("Failed to sync configuration with login server")
}
// Update all providers, roles and workflows to be enabled
// TODO Reload environment?
return nil
}
func (c *Config) RegisterWithLoginServer(localToken string) (*RegistrationResponse, error) {
reqBody, err := json.Marshal(RegistrationRequest{
Environment: &c.Environment,
})
if err != nil {
return nil, fmt.Errorf("failed to marshal registration request: %w", err)
}
// No need for an API key we need to use the session
// info
res, err := common.InvokeHttpRequest(&model.HTTPArguments{
Method: http.MethodPost,
Endpoint: &model.Endpoint{
EndpointConfig: &model.EndpointConfiguration{
URI: &model.LiteralUri{Value: c.DiscoverLoginServerApiUrl() + "/register"},
Authentication: &model.ReferenceableAuthenticationPolicy{
AuthenticationPolicy: &model.AuthenticationPolicy{
Bearer: &model.BearerAuthenticationPolicy{
Token: localToken,
},
},
},
},
},
Body: reqBody,
})
if err != nil {
return nil, fmt.Errorf("failed to invoke registration request: %w", err)
}
if res.StatusCode() != 200 {
return nil, fmt.Errorf("registration request failed with status: %s", res.Status())
}
var registrationResponse RegistrationResponse
err = json.Unmarshal(res.Body(), ®istrationResponse)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal registration response: %w", err)
}
if !registrationResponse.Success {
return nil, fmt.Errorf("registration request was not successful")
}
logrus.Infoln("Successfully registered with login server")
return ®istrationResponse, nil
}
// setDefaults sets default configuration values
func setDefaults(v *viper.Viper) {
v.SetDefault("config.path", "./config")
v.SetDefault("environment.name", environment.DetectSystemName())
v.SetDefault("environment.hostname", environment.DetectHostname())
v.SetDefault("environment.os", environment.DetectOperatingSystem())
v.SetDefault("environment.os_version", environment.DetectOSVersion())
v.SetDefault("environment.arch", runtime.GOARCH)
v.SetDefault("environment.platform", environment.DetectPlatform())
v.SetDefault("environment.ephemeral", environment.IsEphemeralEnvironment())
// Environment config defaults
v.SetDefault("environment.config.timeout", "5s") // Timeout for any config fetch operations
v.SetDefault("environment.config.key", common.DefaultServerSecret) // Default encryption key name
v.SetDefault("environment.config.salt", common.DefaultServerSecret) // Default encryption salt
// Login server defaults
v.SetDefault("login.endpoint", common.DefaultLoginServerEndpoint)
v.SetDefault("login.base", "/")
// Server defaults
v.SetDefault("server.host", "0.0.0.0")
v.SetDefault("server.port", 5225)
// API defaults
v.SetDefault("api.version", "v1")
// Metrics defaults
v.SetDefault("server.metrics.enabled", true)
v.SetDefault("server.metrics.path", "/metrics")
v.SetDefault("server.metrics.namespace", "thand")
// Health defaults
v.SetDefault("server.health.enabled", true)
v.SetDefault("server.health.path", "/health")
// Ready defaults
v.SetDefault("server.ready.enabled", true)
v.SetDefault("server.ready.path", "/ready")
// Security defaults
v.SetDefault("server.cors.allowed_origins", []string{"https://thand.io", "https://*.thand.io"})
v.SetDefault("server.cors.allowed_methods", []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"})
v.SetDefault("server.cors.allowed_headers", []string{"Authorization", "Content-Type", "X-Requested-With"})
v.SetDefault("server.cors.max_age", 86400)
// API defaults
v.SetDefault("server.limits.read_timeout", "30s")
v.SetDefault("server.limits.write_timeout", "30s")
v.SetDefault("server.limits.idle_timeout", "120s")
v.SetDefault("server.limits.requests_per_minute", 100)
v.SetDefault("server.limits.burst", 10)
// OIDC defaults
v.SetDefault("oidc.scopes", []string{"openid", "profile", "email"})
// Session defaults
v.SetDefault("secret", common.DefaultServerSecret)
// Logging defaults
v.SetDefault("logging.level", "info")
v.SetDefault("logging.format", "json")
v.SetDefault("logging.output", "stdout")
// Where to load in roles and workflows from
v.SetDefault("workflows.path", "./examples/workflows") // load any json or yaml files from this directory
v.SetDefault("roles.path", "./examples/roles") // load any json or yaml files from this directory
v.SetDefault("providers.path", "./examples/providers") // load any json or yaml files from this directory
// Allow a url to pull in roles and workflows
// v.SetDefault("roles.url", "https://raw.githubusercontent.com/thand-io/agent/refs/heads/main/examples/roles/roles.yaml")
// v.SetDefault("workflows.url", "https://raw.githubusercontent.com/thand-io/agent/refs/heads/main/examples/workflows/workflows.yaml")
// v.SetDefault("providers.url", "https://raw.githubusercontent.com/thand-io/agent/refs/heads/main/examples/providers/providers.example.yaml")
}
func GetModuleBuildInfo() (string, string, bool) {
if info, ok := debug.ReadBuildInfo(); ok {
version := info.Main.Version
var gitCommit string
for _, setting := range info.Settings {
if setting.Key == "vcs.revision" {
gitCommit = setting.Value
break
}
}
return version, gitCommit, true
}
return "", "", false
}