generated from flashbots/go-template
-
Notifications
You must be signed in to change notification settings - Fork 2
Vault integration for secret storage #72
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
5581bed
vault integration for secret storage
canercidam 8368b8f
add package commit
canercidam 226bc28
fix linter error
canercidam 1551e1d
add k8s auth for vault and test with k8s mock in integration tests
canercidam de18f2a
switch to the more widely used and tested library
canercidam cee6aa1
address feedback
canercidam 3eae862
fix linter error
canercidam 3ea67d6
remove config merge
canercidam 3d57a75
revert change
canercidam File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,162 @@ | ||
| package secrets | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "errors" | ||
| "fmt" | ||
| "log/slog" | ||
| "time" | ||
|
|
||
| vault "github.com/hashicorp/vault/api" | ||
| authkubernetes "github.com/hashicorp/vault/api/auth/kubernetes" | ||
| ) | ||
|
|
||
| type hashicorpVaultService struct { | ||
| client *vault.Client | ||
| secretPath string | ||
| mountPath string | ||
| log *slog.Logger | ||
| } | ||
|
|
||
| type VaultConfig struct { | ||
| Address string // Vault server address (e.g., http://localhost:8200) | ||
| Token string // Vault token for authentication (used when AuthMethod=="token") | ||
| SecretPrefix string // Path prefix for secrets (e.g., "secrets/builder-hub") | ||
| MountPath string // Vault KV v2 mount path (e.g., "secret", defaults to "secret") | ||
| AuthMethod string // "token" (default) or "kubernetes" | ||
| Role string // Role name for Kubernetes auth (required if AuthMethod=="kubernetes") | ||
| Jwt string // ServiceAccount JWT for Kubernetes auth (required if AuthMethod=="kubernetes") | ||
| } | ||
|
|
||
| func NewHashicorpVaultService(ctx context.Context, log *slog.Logger, cfg VaultConfig) (*hashicorpVaultService, error) { | ||
| if cfg.MountPath == "" { | ||
| cfg.MountPath = "secret" | ||
| } | ||
|
|
||
| if cfg.AuthMethod != "token" && cfg.AuthMethod != "kubernetes" && cfg.AuthMethod != "" { | ||
| return nil, fmt.Errorf("unsupported AuthMethod %s", cfg.AuthMethod) | ||
| } | ||
|
|
||
| vcfg := vault.DefaultConfig() | ||
| vcfg.Address = cfg.Address | ||
| client, err := vault.NewClient(vcfg) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to create Vault client: %w", err) | ||
| } | ||
|
|
||
| svc := &hashicorpVaultService{ | ||
| client: client, | ||
| secretPath: cfg.SecretPrefix, | ||
| mountPath: cfg.MountPath, | ||
| log: log, | ||
| } | ||
|
|
||
| if cfg.AuthMethod == "kubernetes" { | ||
| if cfg.Jwt == "" { | ||
| return nil, fmt.Errorf("JWT is required for Kubernetes auth") | ||
| } | ||
| k8sAuth, err := authkubernetes.NewKubernetesAuth(cfg.Role, authkubernetes.WithServiceAccountToken(cfg.Jwt)) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to initialize Kubernetes auth: %w", err) | ||
| } | ||
| authInfo, err := client.Auth().Login(ctx, k8sAuth) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("kubernetes auth failed: %w", err) | ||
| } | ||
| watcher, err := client.NewLifetimeWatcher(&vault.LifetimeWatcherInput{Secret: authInfo}) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to create token lifetime watcher: %w", err) | ||
| } | ||
| go svc.watchTokenRenewal(ctx, watcher) | ||
| } else { | ||
| if cfg.Token == "" { | ||
| return nil, errors.New("token is required for vault auth") | ||
| } | ||
| client.SetToken(cfg.Token) | ||
| } | ||
|
|
||
| // Verify connection by attempting a read (404 is fine β path may not exist yet) | ||
| verifyCtx, cancel := context.WithTimeout(ctx, 10*time.Second) | ||
| defer cancel() | ||
| _, verifyErr := client.KVv2(cfg.MountPath).Get(verifyCtx, cfg.SecretPrefix) | ||
| if verifyErr != nil && !isVault404(verifyErr) { | ||
| return nil, fmt.Errorf("failed to verify Vault connection: %w", verifyErr) | ||
| } | ||
|
|
||
| return svc, nil | ||
| } | ||
|
|
||
| func (s *hashicorpVaultService) watchTokenRenewal(ctx context.Context, watcher *vault.LifetimeWatcher) { | ||
| go watcher.Start() | ||
| defer watcher.Stop() | ||
|
|
||
| for { | ||
| select { | ||
| case <-ctx.Done(): | ||
| return | ||
| case err := <-watcher.DoneCh(): | ||
| if err != nil { | ||
| s.log.Error("vault token renewal stopped", "err", err) | ||
| } | ||
| return | ||
| case <-watcher.RenewCh(): | ||
| s.log.Debug("vault token renewed") | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func isVault404(err error) bool { | ||
| var responseErr *vault.ResponseError | ||
| return errors.As(err, &responseErr) && responseErr.StatusCode == 404 | ||
| } | ||
|
|
||
| func (s *hashicorpVaultService) secretKVPath(builderName string) string { | ||
| if s.secretPath == "" { | ||
| return builderName | ||
| } | ||
| return fmt.Sprintf("%s/%s", s.secretPath, builderName) | ||
| } | ||
|
|
||
| // GetSecretValues retrieves secrets for a specific builder from Vault KV v2. | ||
| // Implements application.SecretAccessor interface. | ||
| func (s *hashicorpVaultService) GetSecretValues(ctx context.Context, builderName string) (json.RawMessage, error) { | ||
| path := s.secretKVPath(builderName) | ||
|
|
||
| secret, err := s.client.KVv2(s.mountPath).Get(ctx, path) | ||
| if err != nil { | ||
| if isVault404(err) { | ||
| return json.RawMessage("{}"), nil | ||
| } | ||
| return nil, fmt.Errorf("failed to read secret from Vault: %w", err) | ||
| } | ||
|
|
||
| if secret == nil || secret.Data == nil { | ||
| return json.RawMessage("{}"), nil | ||
| } | ||
|
|
||
| secretJSON, err := json.Marshal(secret.Data) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to marshal Vault secret: %w", err) | ||
| } | ||
|
|
||
| return json.RawMessage(secretJSON), nil | ||
| } | ||
|
|
||
| // SetSecretValues stores secrets for a specific builder in Vault KV v2. | ||
| // Implements ports.AdminSecretService interface. | ||
| func (s *hashicorpVaultService) SetSecretValues(ctx context.Context, builderName string, values json.RawMessage) error { | ||
| path := s.secretKVPath(builderName) | ||
|
|
||
| var dataMap map[string]any | ||
| if err := json.Unmarshal(values, &dataMap); err != nil { | ||
| return fmt.Errorf("failed to unmarshal secret values: %w", err) | ||
| } | ||
|
|
||
| _, err := s.client.KVv2(s.mountPath).Put(ctx, path, dataMap) | ||
| if err != nil { | ||
| return fmt.Errorf("failed to write secret to Vault: %w", err) | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.