diff --git a/pkg/config.go b/pkg/config.go index b5a362f..102029b 100644 --- a/pkg/config.go +++ b/pkg/config.go @@ -321,6 +321,23 @@ func LoadConfig(configFiles []string, deploymentId int) (*Config, error) { config.Inbound.Wireguard.LocalAddress = token.WireguardCredential.LocalAddress config.Inbound.Wireguard.PrivateKey = token.WireguardCredential.PrivateKey + log.WithField("source", "broker_token").Info("Loaded WireGuard private key from broker token") + } + + // Step 1a: Apply private key from environment variable if provided (takes precedence over broker token) + if privateKeyEnv := os.Getenv("SEMGREP_NETWORK_BROKER_PRIVATE_KEY"); privateKeyEnv != "" { + // Check if we're overwriting a previously set private key + if len(config.Inbound.Wireguard.PrivateKey) > 0 { + log.WithField("source", "environment_variable").Warn("SEMGREP_NETWORK_BROKER_PRIVATE_KEY environment variable taking precedence over the provided config file's private key") + } + + privateKeyBytes, err := base64.StdEncoding.DecodeString(privateKeyEnv) + if err != nil { + return nil, fmt.Errorf("failed to decode SEMGREP_NETWORK_BROKER_PRIVATE_KEY: %v", err) + } + + config.Inbound.Wireguard.PrivateKey = SensitiveBase64String(privateKeyBytes) + log.WithField("source", "environment_variable").Info("Loaded WireGuard private key from SEMGREP_NETWORK_BROKER_PRIVATE_KEY environment variable") } // Step 2: Apply config values from semgrep.dev/api/broker/{deployment_id}/default-config, if a deployment ID is provided diff --git a/pkg/config_test.go b/pkg/config_test.go index b7fdded..372d7d7 100644 --- a/pkg/config_test.go +++ b/pkg/config_test.go @@ -3,6 +3,7 @@ package pkg import ( "encoding/base64" "fmt" + "os" "reflect" "testing" @@ -135,3 +136,28 @@ func TestHttpMethodsDecodeHook(t *testing.T) { t.Error(fmt.Errorf("No match: %+v != %+v", output.Methods, expected)) } } + +func TestPrivateKeyEnvironmentVariable(t *testing.T) { + // Test that SEMGREP_NETWORK_BROKER_PRIVATE_KEY environment variable is properly loaded + testPrivateKey := "KJR4EeL83nexOFihmdYciri7Mo7ciAq/b5/S0lREcns=" + + // Set the environment variable + os.Setenv("SEMGREP_NETWORK_BROKER_PRIVATE_KEY", testPrivateKey) + defer os.Unsetenv("SEMGREP_NETWORK_BROKER_PRIVATE_KEY") + + // Load config + config, err := LoadConfig(nil, 0) + if err != nil { + t.Fatalf("Failed to load config: %v", err) + } + + // Verify the private key was loaded correctly + expectedBytes, err := base64.StdEncoding.DecodeString(testPrivateKey) + if err != nil { + t.Fatalf("Failed to decode test private key: %v", err) + } + + if !reflect.DeepEqual(config.Inbound.Wireguard.PrivateKey, SensitiveBase64String(expectedBytes)) { + t.Errorf("Private key not loaded correctly from environment variable") + } +}