-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.go
More file actions
435 lines (376 loc) · 14 KB
/
config.go
File metadata and controls
435 lines (376 loc) · 14 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
// Package config provides application configuration loaded from environment
// variables.
package config
import (
"context"
"encoding/json"
"log/slog"
"os"
"strconv"
"strings"
"sync"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/ssm"
"github.com/cockroachdb/errors"
"github.com/cruxstack/github-ops-app/internal/types"
)
// Config holds all application configuration loaded from environment
// variables.
type Config struct {
// General
DebugEnabled bool
BasePath string
// GitHub App
GitHubOrg string
GitHubAppID int64
GitHubAppPrivateKey []byte
GitHubInstallationID int64
GitHubWebhookSecret string
GitHubBaseURL string
// PR Compliance
PRComplianceEnabled bool
PRMonitoredBranches []string
// Okta
OktaDomain string
OktaClientID string
OktaPrivateKey []byte
OktaPrivateKeyID string
OktaScopes []string
OktaBaseURL string
OktaGitHubUserField string
OktaSyncRules []types.SyncRule
OktaSyncSafetyThreshold float64
OktaOrphanedUserNotifications bool
// Slack
SlackEnabled bool
SlackToken string
SlackChannel string
SlackChannelPRBypass string
SlackChannelOktaSync string
SlackChannelOrphanedUsers string
SlackPRBypassFooterNote string
SlackAPIURL string
}
var (
ssmClient *ssm.Client
ssmClientOnce sync.Once
ssmClientErr error
)
// getSSMClient initializes and returns a cached SSM client.
// lazy initialization ensures we only create the client when SSM parameters
// are actually needed.
func getSSMClient(ctx context.Context) (*ssm.Client, error) {
ssmClientOnce.Do(func() {
cfg, err := config.LoadDefaultConfig(ctx)
if err != nil {
ssmClientErr = errors.Wrap(err, "failed to load aws config for ssm")
return
}
ssmClient = ssm.NewFromConfig(cfg)
})
return ssmClient, ssmClientErr
}
// resolveEnvValue resolves an environment variable value.
// if the value starts with "arn:aws:ssm:", fetches the parameter from SSM.
// automatically decrypts SecureString parameters.
func resolveEnvValue(ctx context.Context, key, value string) (string, error) {
if value == "" {
return "", nil
}
if !strings.HasPrefix(value, "arn:aws:ssm:") {
return value, nil
}
client, err := getSSMClient(ctx)
if err != nil {
return "", errors.Wrapf(err, "failed to init ssm client for %s", key)
}
paramName := strings.TrimPrefix(value, "arn:aws:ssm:")
idx := strings.Index(paramName, ":parameter/")
if idx == -1 {
return "", errors.Newf("invalid ssm parameter arn format for %s: %s", key, value)
}
paramName = "/" + paramName[idx+len(":parameter/"):]
input := &ssm.GetParameterInput{
Name: ¶mName,
WithDecryption: aws.Bool(true),
}
result, err := client.GetParameter(ctx, input)
if err != nil {
return "", errors.Wrapf(err, "failed to get ssm parameter '%s' for %s", paramName, key)
}
if result.Parameter == nil || result.Parameter.Value == nil {
return "", errors.Newf("ssm parameter '%s' for %s returned nil value", paramName, key)
}
return *result.Parameter.Value, nil
}
// getEnv retrieves an environment variable and resolves SSM parameters if
// needed.
func getEnv(ctx context.Context, key string) (string, error) {
value := os.Getenv(key)
return resolveEnvValue(ctx, key, value)
}
// NewConfig loads configuration from environment variables.
// returns error if required values are missing or invalid.
// supports SSM parameter references in format:
// arn:aws:ssm:REGION:ACCOUNT:parameter/path/to/param
func NewConfig() (*Config, error) {
return NewConfigWithContext(context.Background())
}
// NewConfigWithContext loads configuration from environment variables with
// the given context. supports SSM parameter resolution with automatic
// decryption.
func NewConfigWithContext(ctx context.Context) (*Config, error) {
debugEnabled, _ := strconv.ParseBool(os.Getenv("APP_DEBUG_ENABLED"))
oktaGitHubUserField := os.Getenv("APP_OKTA_GITHUB_USER_FIELD")
if oktaGitHubUserField == "" {
oktaGitHubUserField = "githubUsername"
}
oktaSyncSafetyThreshold := 0.5
if thresholdStr := os.Getenv("APP_OKTA_SYNC_SAFETY_THRESHOLD"); thresholdStr != "" {
if threshold, err := strconv.ParseFloat(thresholdStr, 64); err == nil && threshold >= 0 && threshold <= 1 {
oktaSyncSafetyThreshold = threshold
}
}
githubWebhookSecret, err := getEnv(ctx, "APP_GITHUB_WEBHOOK_SECRET")
if err != nil {
return nil, err
}
slackToken, err := getEnv(ctx, "APP_SLACK_TOKEN")
if err != nil {
return nil, err
}
cfg := Config{
DebugEnabled: debugEnabled,
GitHubOrg: os.Getenv("APP_GITHUB_ORG"),
GitHubWebhookSecret: githubWebhookSecret,
GitHubBaseURL: os.Getenv("APP_GITHUB_BASE_URL"),
OktaDomain: os.Getenv("APP_OKTA_DOMAIN"),
OktaClientID: os.Getenv("APP_OKTA_CLIENT_ID"),
OktaBaseURL: os.Getenv("APP_OKTA_BASE_URL"),
OktaGitHubUserField: oktaGitHubUserField,
OktaSyncSafetyThreshold: oktaSyncSafetyThreshold,
SlackToken: slackToken,
SlackChannel: os.Getenv("APP_SLACK_CHANNEL"),
SlackChannelPRBypass: os.Getenv("APP_SLACK_CHANNEL_PR_BYPASS"),
SlackChannelOktaSync: os.Getenv("APP_SLACK_CHANNEL_OKTA_SYNC"),
SlackChannelOrphanedUsers: os.Getenv("APP_SLACK_CHANNEL_ORPHANED_USERS"),
SlackPRBypassFooterNote: os.Getenv("APP_SLACK_FOOTER_NOTE_PR_BYPASS"),
SlackAPIURL: os.Getenv("APP_SLACK_API_URL"),
}
if appIDStr := os.Getenv("APP_GITHUB_APP_ID"); appIDStr != "" {
appID, err := strconv.ParseInt(appIDStr, 10, 64)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse APP_GITHUB_APP_ID '%s'", appIDStr)
}
cfg.GitHubAppID = appID
}
if privateKeyPath := os.Getenv("APP_GITHUB_APP_PRIVATE_KEY_PATH"); privateKeyPath != "" {
privateKey, err := os.ReadFile(privateKeyPath)
if err != nil {
return nil, errors.Wrapf(err, "failed to read private key from %s", privateKeyPath)
}
cfg.GitHubAppPrivateKey = privateKey
} else if privateKeyEnv, err := getEnv(ctx, "APP_GITHUB_APP_PRIVATE_KEY"); err != nil {
return nil, err
} else if privateKeyEnv != "" {
cfg.GitHubAppPrivateKey = []byte(privateKeyEnv)
}
if installIDStr := os.Getenv("APP_GITHUB_INSTALLATION_ID"); installIDStr != "" {
installID, err := strconv.ParseInt(installIDStr, 10, 64)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse APP_GITHUB_INSTALLATION_ID '%s'", installIDStr)
}
cfg.GitHubInstallationID = installID
}
if privateKeyPath := os.Getenv("APP_OKTA_PRIVATE_KEY_PATH"); privateKeyPath != "" {
privateKey, err := os.ReadFile(privateKeyPath)
if err != nil {
return nil, errors.Wrapf(err, "failed to read okta private key from %s", privateKeyPath)
}
cfg.OktaPrivateKey = privateKey
} else if privateKeyEnv, err := getEnv(ctx, "APP_OKTA_PRIVATE_KEY"); err != nil {
return nil, err
} else if privateKeyEnv != "" {
cfg.OktaPrivateKey = []byte(privateKeyEnv)
}
cfg.OktaPrivateKeyID = os.Getenv("APP_OKTA_PRIVATE_KEY_ID")
if scopesStr := os.Getenv("APP_OKTA_SCOPES"); scopesStr != "" {
scopes := strings.Split(scopesStr, ",")
for i := range scopes {
scopes[i] = strings.TrimSpace(scopes[i])
}
cfg.OktaScopes = scopes
} else {
cfg.OktaScopes = []string{"okta.groups.read", "okta.users.read"}
}
prComplianceEnabled, _ := strconv.ParseBool(os.Getenv("APP_PR_COMPLIANCE_ENABLED"))
cfg.PRComplianceEnabled = prComplianceEnabled
monitoredBranchesStr := os.Getenv("APP_PR_MONITORED_BRANCHES")
if monitoredBranchesStr != "" {
branches := strings.Split(monitoredBranchesStr, ",")
for i := range branches {
branches[i] = strings.TrimSpace(branches[i])
}
cfg.PRMonitoredBranches = branches
} else {
cfg.PRMonitoredBranches = []string{"main", "master"}
}
syncRulesJSON := os.Getenv("APP_OKTA_SYNC_RULES")
if syncRulesJSON != "" {
var rules []types.SyncRule
if err := json.Unmarshal([]byte(syncRulesJSON), &rules); err != nil {
return nil, errors.Wrap(err, "failed to parse APP_OKTA_SYNC_RULES")
}
cfg.OktaSyncRules = rules
}
cfg.SlackEnabled = cfg.SlackToken != "" && cfg.SlackChannel != ""
basePath := os.Getenv("APP_BASE_PATH")
if basePath != "" {
basePath = "/" + strings.Trim(basePath, "/")
}
cfg.BasePath = basePath
orphanedUserNotifications, _ := strconv.ParseBool(os.Getenv("APP_OKTA_ORPHANED_USER_NOTIFICATIONS"))
if os.Getenv("APP_OKTA_ORPHANED_USER_NOTIFICATIONS") == "" {
orphanedUserNotifications = cfg.IsOktaSyncEnabled()
}
cfg.OktaOrphanedUserNotifications = orphanedUserNotifications
return &cfg, nil
}
// NewLogger creates a new structured logger.
// uses JSON format in Lambda, text format elsewhere.
// sets log level to debug when APP_DEBUG_ENABLED is true.
func NewLogger() *slog.Logger {
var handler slog.Handler
debugEnabled, _ := strconv.ParseBool(os.Getenv("APP_DEBUG_ENABLED"))
level := slog.LevelInfo
if debugEnabled {
level = slog.LevelDebug
}
if os.Getenv("AWS_LAMBDA_FUNCTION_NAME") != "" {
handler = slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: level,
})
} else {
handler = slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
Level: level,
})
}
return slog.New(handler)
}
// IsOktaSyncEnabled returns true if Okta sync is fully configured.
func (c *Config) IsOktaSyncEnabled() bool {
return c.OktaDomain != "" && c.OktaClientID != "" && len(c.OktaPrivateKey) > 0 && len(c.OktaSyncRules) > 0
}
// IsPRComplianceEnabled returns true if PR compliance checking is enabled.
func (c *Config) IsPRComplianceEnabled() bool {
return c.PRComplianceEnabled && c.IsGitHubConfigured()
}
// IsGitHubConfigured returns true if GitHub App credentials are configured.
func (c *Config) IsGitHubConfigured() bool {
return c.GitHubOrg != "" &&
c.GitHubAppID != 0 &&
len(c.GitHubAppPrivateKey) > 0 &&
c.GitHubInstallationID != 0
}
// ShouldMonitorBranch returns true if the given branch should be monitored
// for PR compliance.
func (c *Config) ShouldMonitorBranch(branch string) bool {
if !c.IsPRComplianceEnabled() {
return false
}
branch = strings.TrimPrefix(branch, "refs/heads/")
for _, monitored := range c.PRMonitoredBranches {
if branch == monitored {
return true
}
}
return false
}
// RedactedConfig contains configuration with sensitive values redacted.
// safe for logging and API responses.
type RedactedConfig struct {
// General
DebugEnabled bool `json:"debug_enabled"`
BasePath string `json:"base_path"`
// GitHub App
GitHubOrg string `json:"github_org"`
GitHubAppID int64 `json:"github_app_id"`
GitHubAppPrivateKey string `json:"github_app_private_key"`
GitHubInstallationID int64 `json:"github_installation_id"`
GitHubWebhookSecret string `json:"github_webhook_secret"`
GitHubBaseURL string `json:"github_base_url"`
// PR Compliance
PRComplianceEnabled bool `json:"pr_compliance_enabled"`
PRMonitoredBranches []string `json:"pr_monitored_branches"`
// Okta
OktaDomain string `json:"okta_domain"`
OktaClientID string `json:"okta_client_id"`
OktaPrivateKey string `json:"okta_private_key"`
OktaPrivateKeyID string `json:"okta_private_key_id"`
OktaScopes []string `json:"okta_scopes"`
OktaBaseURL string `json:"okta_base_url"`
OktaGitHubUserField string `json:"okta_github_user_field"`
OktaSyncRules []types.SyncRule `json:"okta_sync_rules"`
OktaSyncSafetyThreshold float64 `json:"okta_sync_safety_threshold"`
OktaOrphanedUserNotifications bool `json:"okta_orphaned_user_notifications"`
// Slack
SlackEnabled bool `json:"slack_enabled"`
SlackToken string `json:"slack_token"`
SlackChannel string `json:"slack_channel"`
SlackChannelPRBypass string `json:"slack_channel_pr_bypass"`
SlackChannelOktaSync string `json:"slack_channel_okta_sync"`
SlackChannelOrphanedUsers string `json:"slack_channel_orphaned_users"`
SlackPRBypassFooterNote string `json:"slack_pr_bypass_footer_note"`
SlackAPIURL string `json:"slack_api_url"`
}
// Redacted returns a copy of the config with secrets redacted.
func (c *Config) Redacted() RedactedConfig {
redact := func(s string) string {
if s == "" {
return ""
}
return "***REDACTED***"
}
redactBytes := func(b []byte) string {
if len(b) == 0 {
return ""
}
return "***REDACTED***"
}
return RedactedConfig{
// General
DebugEnabled: c.DebugEnabled,
BasePath: c.BasePath,
// GitHub App
GitHubOrg: c.GitHubOrg,
GitHubAppID: c.GitHubAppID,
GitHubAppPrivateKey: redactBytes(c.GitHubAppPrivateKey),
GitHubInstallationID: c.GitHubInstallationID,
GitHubWebhookSecret: redact(c.GitHubWebhookSecret),
GitHubBaseURL: c.GitHubBaseURL,
// PR Compliance
PRComplianceEnabled: c.PRComplianceEnabled,
PRMonitoredBranches: c.PRMonitoredBranches,
// Okta
OktaDomain: c.OktaDomain,
OktaClientID: redact(c.OktaClientID),
OktaPrivateKey: redactBytes(c.OktaPrivateKey),
OktaPrivateKeyID: c.OktaPrivateKeyID,
OktaScopes: c.OktaScopes,
OktaBaseURL: c.OktaBaseURL,
OktaGitHubUserField: c.OktaGitHubUserField,
OktaSyncRules: c.OktaSyncRules,
OktaSyncSafetyThreshold: c.OktaSyncSafetyThreshold,
OktaOrphanedUserNotifications: c.OktaOrphanedUserNotifications,
// Slack
SlackEnabled: c.SlackEnabled,
SlackToken: redact(c.SlackToken),
SlackChannel: c.SlackChannel,
SlackChannelPRBypass: c.SlackChannelPRBypass,
SlackChannelOktaSync: c.SlackChannelOktaSync,
SlackChannelOrphanedUsers: c.SlackChannelOrphanedUsers,
SlackPRBypassFooterNote: c.SlackPRBypassFooterNote,
SlackAPIURL: c.SlackAPIURL,
}
}