vault

package module
v1.3.63 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 23, 2026 License: Apache-2.0 Imports: 6 Imported by: 0

README

Go Reference Go Report Card

Vault Package

Description

The vault package is a Go library designed to simplify interactions with HashiCorp Vault. It provides a testable, interface-based design with utilities for securely managing secrets, tokens, and configurations within your Go applications.

Features

  • Interface-based design for easy testing and mocking
  • AppRole authentication support
  • KV v2 secrets engine integration
  • Azure dynamic credentials support
  • Configurable authentication strategies
  • Environment-based configuration using Viper

Installation

To install the vault package, use go get:

go get github.com/MyCarrier-DevOps/goLibMyCarrier/vault

Reference

Configuration

The package uses environment variables for configuration:

export VAULT_ADDRESS="https://vault.example.com:8200"
export VAULT_ROLE_ID="your-role-id"
export VAULT_SECRET_ID="your-secret-id"

Usage

package main

import (
    "context"
    "log"
    
    "github.com/MyCarrier-DevOps/goLibMyCarrier/vault"
)

func main() {
    ctx := context.Background()
    
    // Load configuration from environment variables
    config, err := vault.VaultLoadConfig()
    if err != nil {
        log.Fatalf("Error loading vault config: %v", err)
    }
    
    // Create vault client with AppRole authentication
    vaultClient, err := vault.CreateVaultClient(ctx, config)
    if err != nil {
        log.Fatalf("Error creating vault client: %v", err)
    }
    
    // Read KV secret
    secretData, err := vaultClient.GetKVSecret(ctx, "myapp/config", "secret")
    if err != nil {
        log.Fatalf("Error reading secret: %v", err)
    }
    
    log.Printf("Secret read successfully: %+v", secretData)
    
    // Get Azure dynamic credentials
    azureCreds, err := vaultClient.GetAzureDynamicCredentials(ctx, "my-azure-role")
    if err != nil {
        log.Fatalf("Error getting Azure credentials: %v", err)
    }
    
    log.Printf("Azure credentials: %+v", azureCreds)
}
Advanced Usage with Custom Configuration
package main

import (
    "context"
    "log"
    
    "github.com/MyCarrier-DevOps/goLibMyCarrier/vault"
)

func main() {
    ctx := context.Background()
    
    // Create custom configuration
    config := &vault.VaultConfig{
        VaultAddress: "https://vault.example.com:8200",
        Credentials: vault.Credentials{
            RoleID:   "your-role-id",
            SecretID: "your-secret-id",
        },
    }
    
    // Use custom authenticator
    authenticator := &vault.AppRoleAuthenticator{}
    
    // Create vault client with dependency injection
    vaultClient, err := vault.NewVaultClient(ctx, config, authenticator)
    if err != nil {
        log.Fatalf("Error creating vault client: %v", err)
    }
    
    // Use the client...
}
Testing with Mocks
package main

import (
    "context"
    "testing"
    
    "github.com/MyCarrier-DevOps/goLibMyCarrier/vault"
)

// Mock implementation for testing
type MockVaultClient struct {
    secrets map[string]interface{}
}

func (m *MockVaultClient) GetKVSecret(ctx context.Context, path string, mount string) (map[string]interface{}, error) {
    return m.secrets, nil
}

func (m *MockVaultClient) GetAzureDynamicCredentials(ctx context.Context, azureRole string) (map[string]interface{}, error) {
    return map[string]interface{}{
        "client_id":     "test-client-id",
        "client_secret": "test-client-secret",
    }, nil
}

func (m *MockVaultClient) SetToken(token string) error {
    return nil
}

func TestMyFunction(t *testing.T) {
    mockClient := &MockVaultClient{
        secrets: map[string]interface{}{
            "username": "testuser",
            "password": "testpass",
        },
    }
    
    // Use mockClient in your tests...
    ctx := context.Background()
    secrets, err := mockClient.GetKVSecret(ctx, "test/path", "secret")
    if err != nil {
        t.Errorf("Unexpected error: %v", err)
    }
    
    if secrets["username"] != "testuser" {
        t.Errorf("Expected username 'testuser', got %v", secrets["username"])
    }
}

Interfaces

VaultClientInterface
type VaultClientInterface interface {
    GetKVSecret(ctx context.Context, path string, mount string) (map[string]interface{}, error)
    GetAzureDynamicCredentials(ctx context.Context, azureRole string) (map[string]interface{}, error)
    SetToken(token string) error
}
ConfigLoader
type ConfigLoader interface {
    LoadConfig() (*VaultConfig, error)
}
VaultAuthenticator
type VaultAuthenticator interface {
    Authenticate(ctx context.Context, client *vault.Client, config *VaultConfig) error
}

Backward Compatibility

The package maintains backward compatibility with the old API:

// Legacy usage (deprecated)
vaultClient, err := vault.LegacyVaultClient(ctx, config)
if err != nil {
    log.Fatalf("Error: %v", err)
}

secretData, err := vault.GetKVSecret(ctx, vaultClient, "path", "mount")

Error Handling

All functions return detailed errors with context:

vaultClient, err := vault.CreateVaultClient(ctx, config)
if err != nil {
    // Handle specific error types
    log.Printf("Vault client creation failed: %v", err)
    return
}

Environment Variables

Variable Description Required
VAULT_ADDRESS Vault server address Yes
VAULT_ROLE_ID AppRole Role ID No*
VAULT_SECRET_ID AppRole Secret ID No*

*Required for AppRole authentication

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetAzureDynamicCredentials

func GetAzureDynamicCredentials(
	ctx context.Context,
	client *vault.Client,
	azure_role string,
) (map[string]interface{}, error)

func GetKVSecret

func GetKVSecret(ctx context.Context, client *vault.Client, path, mount string) (map[string]interface{}, error)

func LegacyVaultClient added in v1.3.9

func LegacyVaultClient(ctx context.Context, config *VaultConfig) (*vault.Client, error)

LegacyVaultClient maintains backward compatibility with the old function signature

func VaultValidateConfig

func VaultValidateConfig(config *VaultConfig) error

validateConfig validates the loaded configuration.

Types

type AppRoleAuthenticator added in v1.3.9

type AppRoleAuthenticator struct{}

AppRoleAuthenticator implements authentication using AppRole

func (*AppRoleAuthenticator) Authenticate added in v1.3.9

func (a *AppRoleAuthenticator) Authenticate(ctx context.Context, client *vault.Client, config *VaultConfig) error

AppRoleAuthenticator implements VaultAuthenticator interface

type ConfigLoader added in v1.3.9

type ConfigLoader interface {
	LoadConfig() (*VaultConfig, error)
}

ConfigLoader interface allows for dependency injection of configuration loading

type Credentials added in v1.3.9

type Credentials struct {
	RoleID   string `mapstructure:"role_id"`
	SecretID string `mapstructure:"secret_id"`
}

type VaultAuthenticator added in v1.3.9

type VaultAuthenticator interface {
	Authenticate(ctx context.Context, client *vault.Client, config *VaultConfig) error
}

VaultAuthenticator interface for authentication strategies

type VaultClient

type VaultClient struct {
	// contains filtered or unexported fields
}

VaultClient wraps the actual Vault client and implements VaultClientInterface

func CreateVaultClient added in v1.3.9

func CreateVaultClient(ctx context.Context, config *VaultConfig) (*VaultClient, error)

CreateVaultClient is a convenience function that uses AppRole authentication

func NewVaultClient added in v1.3.9

func NewVaultClient(ctx context.Context, config *VaultConfig, authenticator VaultAuthenticator) (*VaultClient, error)

NewVaultClient creates a new Vault client with the given configuration and authenticator

func (*VaultClient) GetAzureDynamicCredentials added in v1.3.9

func (vc *VaultClient) GetAzureDynamicCredentials(
	ctx context.Context,
	azureRole string,
) (map[string]interface{}, error)

func (*VaultClient) GetKVSecret added in v1.3.9

func (vc *VaultClient) GetKVSecret(ctx context.Context, path, mount string) (map[string]interface{}, error)

VaultClient methods implementing VaultClientInterface

func (*VaultClient) GetKVSecretList added in v1.3.9

func (vc *VaultClient) GetKVSecretList(ctx context.Context, path, mount string) ([]string, error)

func (*VaultClient) SetToken added in v1.3.9

func (vc *VaultClient) SetToken(token string) error

type VaultClientInterface added in v1.3.9

type VaultClientInterface interface {
	GetKVSecret(ctx context.Context, path, mount string) (map[string]interface{}, error)
	GetKVSecretList(ctx context.Context, path, mount string) ([]string, error)
	GetAzureDynamicCredentials(ctx context.Context, azureRole string) (map[string]interface{}, error)
	SetToken(token string) error
}

VaultClientInterface defines the interface for Vault operations

type VaultConfig

type VaultConfig struct {
	VaultAddress string      `mapstructure:"vaultaddress"`
	Credentials  Credentials `mapstructure:"credentials"`
}

func VaultLoadConfig

func VaultLoadConfig() (*VaultConfig, error)

VaultLoadConfig is a convenience function that uses the default ViperConfigLoader

type ViperConfigLoader added in v1.3.9

type ViperConfigLoader struct{}

ViperConfigLoader implements configuration loading using Viper

func (*ViperConfigLoader) LoadConfig added in v1.3.9

func (v *ViperConfigLoader) LoadConfig() (*VaultConfig, error)

ViperConfigLoader implements ConfigLoader interface

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL