Skip to content

jaredpetersen/vaultx

Repository files navigation

vaultx

CI Go Reference

vaultx is an alternative to the official Vault Go package that is designed with the developer in mind.

The official Vault package is very useful, but it has a number of issues that make it difficult to integrate Vault into your applications:

  • Tied tightly to the HTTP API, making accomplishing basic functionality involve writing expansive blocks of code
  • Types are very generic, so you lose out on type safety and must know the HTTP API in order interact with it
  • Automatic renewal of authentication credentials is not well-supported

vaultx seeks to address these issues and make Vault a joy to use in Go.

Usage

To create your vault client, create a new configuration struct and pass it to vaultx's New() function:

package main

import (
	"context"
	"fmt"
	"os"

	"github.com/jaredpetersen/vaultx"
	vaultxauth "github.com/jaredpetersen/vaultx/auth"
)

const k8sRole = "my-app"
const vaultKVSecretPath = "my-secret"
const vaultTransitKey = "transit-key"

func main() {
	ctx := context.Background()

	cfg := vaultx.NewConfig("https://vault.mydomain.com")
	cfg.Auth.Method = vaultxauth.NewKubernetesMethod(vaultxauth.KubernetesConfig{Role: k8sRole})

	vltx := vaultx.New(cfg)

	err := vltx.Auth().Login(ctx)
	if err != nil {
		fmt.Println("Failed to authenticate against Vault")
		os.Exit(1)
	}

	// Store secret
	secretData := map[string]interface{}{
		"username": "dbuser",
		"password": "3hvu2ZLxwauHrNaZjJbJARHE",
	}
	err = vltx.KV().UpsertSecret(ctx, vaultKVSecretPath, secretData)
	if err != nil {
		fmt.Println("Failed to store secret")
		os.Exit(1)
	}

	// Get secret
	secret, err := vltx.KV().GetSecret(ctx, vaultKVSecretPath)
	if err != nil {
		fmt.Println("Failed to retrieve secret")
		os.Exit(1)
	}

	fmt.Printf("secret username: %s\n", secret.Data["username"])
	fmt.Printf("secret password: %s\n", secret.Data["password"])

	// Encrypt data
	plaintext := "encrypt me"
	encrypted, err := vltx.Transit().Encrypt(ctx, vaultTransitKey, []byte(plaintext))
	if err != nil {
		fmt.Println("Failed to encrypt data")
		os.Exit(1)
	}

	fmt.Printf("encrypted: %s\n", encrypted)

	// Decrypt data
	decrypted, err := vltx.Transit().Decrypt(ctx, vaultTransitKey, encrypted)
	if err != nil {
		fmt.Println("Failed to decrypt data")
		os.Exit(1)
	}

	fmt.Printf("decrypted: %s\n", string(decrypted))
}

Install

go get github.com/jaredpetersen/vaultx

Sponsorship

If you or your company uses vaultx, please consider contributing to the project via GitHub Sponsors. There's some cool work that we'd like to do -- like end-to-end integration tests -- but cloud computing isn't free.