88 lines
2.5 KiB
Go

package vault
import (
"context"
"time"
"github.com/hashicorp/vault-client-go"
"github.com/hashicorp/vault-client-go/schema"
log "github.com/sirupsen/logrus"
)
func WhatAmI() {
// prepare a client with the given base address
client, err := vault.New(
vault.WithAddress("http://localhost:8200"),
vault.WithRequestTimeout(30*time.Second),
)
if err != nil {
log.Fatal(err)
}
//client.SetRequestCallbacks(func(req *http.Request) {
// log.Println("REQUEST:", *req.URL)
//})
// authenticate with a root token (insecure)
if err := client.SetToken("hvs.XD2NNAznvWucjo7B8RhtXpQZ"); err != nil {
log.Fatal(err)
}
}
// WritingAPIKeyToVault writes the API key to a Vault using the given secret data.
//
// The function converts the secret data into a map and writes it to the Vault.
// If any error occurs during this process, it returns the error.
//
// Parameters:
// - ctx: The context for the operation.
// - client: The Vault client used to perform the write operation.
// - secretData: The secret data to be written to the Vault.
//
// Returns an error if the operation fails.
func WritingAPIKeyToVault[T SecretDataTypes](ctx context.Context, client *vault.Client, secretData SecretData[T]) error {
secret, err := SecretToMap(secretData)
if err != nil {
return err
}
request := schema.KvV2WriteRequest{
Data: secret,
}
_, err = client.Secrets.KvV2Write(ctx, secretData.UserSourceID, request, vault.WithMountPath(secretData.Secret.GetMountPath()))
if err != nil {
log.Fatal(err)
}
return nil
}
// ReadingApiKeyFromVault reads the API key from a Vault and populates the given secret data.
//
// The function reads the data from the Vault, converts it back into the appropriate secret type,
// and assigns it to the provided secret data structure.
// If any error occurs during this process, it returns the error.
//
// Parameters:
// - ctx: The context for the operation.
// - client: The Vault client used to perform the read operation.
// - secretData: A pointer to the secret data structure to be populated with the read data.
//
// Returns an error if the operation fails.
func ReadingApiKeyFromVault[T SecretDataTypes](ctx context.Context, client *vault.Client, secretData *SecretData[T]) error {
data, err := client.Secrets.KvV2Read(ctx, secretData.UserSourceID, vault.WithMountPath(secretData.Secret.GetMountPath()))
if err != nil {
log.Fatal(err)
}
secret, err := MapToSecret[T](data.Data.Data)
if err != nil {
return err
}
secretData.Secret = secret
return nil
}