2023-03-15 19:00:52 +03:00
|
|
|
// Copyright (c) HashiCorp, Inc.
|
|
|
|
// SPDX-License-Identifier: MPL-2.0
|
|
|
|
|
2022-05-25 21:17:13 +03:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
)
|
|
|
|
|
2022-06-08 21:14:55 +03:00
|
|
|
type KVv1 struct {
|
2022-05-25 21:17:13 +03:00
|
|
|
c *Client
|
|
|
|
mountPath string
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get returns a secret from the KV v1 secrets engine.
|
2022-06-08 21:14:55 +03:00
|
|
|
func (kv *KVv1) Get(ctx context.Context, secretPath string) (*KVSecret, error) {
|
2022-05-25 21:17:13 +03:00
|
|
|
pathToRead := fmt.Sprintf("%s/%s", kv.mountPath, secretPath)
|
|
|
|
|
|
|
|
secret, err := kv.c.Logical().ReadWithContext(ctx, pathToRead)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("error encountered while reading secret at %s: %w", pathToRead, err)
|
|
|
|
}
|
|
|
|
if secret == nil {
|
2022-08-13 02:29:42 +03:00
|
|
|
return nil, fmt.Errorf("%w: at %s", ErrSecretNotFound, pathToRead)
|
2022-05-25 21:17:13 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return &KVSecret{
|
|
|
|
Data: secret.Data,
|
|
|
|
VersionMetadata: nil,
|
|
|
|
Raw: secret,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Put inserts a key-value secret (e.g. {"password": "Hashi123"}) into the
|
|
|
|
// KV v1 secrets engine.
|
|
|
|
//
|
|
|
|
// If the secret already exists, it will be overwritten.
|
2022-06-08 21:14:55 +03:00
|
|
|
func (kv *KVv1) Put(ctx context.Context, secretPath string, data map[string]interface{}) error {
|
2022-05-25 21:17:13 +03:00
|
|
|
pathToWriteTo := fmt.Sprintf("%s/%s", kv.mountPath, secretPath)
|
|
|
|
|
|
|
|
_, err := kv.c.Logical().WriteWithContext(ctx, pathToWriteTo, data)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("error writing secret to %s: %w", pathToWriteTo, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Delete deletes a secret from the KV v1 secrets engine.
|
2022-06-08 21:14:55 +03:00
|
|
|
func (kv *KVv1) Delete(ctx context.Context, secretPath string) error {
|
2022-05-25 21:17:13 +03:00
|
|
|
pathToDelete := fmt.Sprintf("%s/%s", kv.mountPath, secretPath)
|
|
|
|
|
|
|
|
_, err := kv.c.Logical().DeleteWithContext(ctx, pathToDelete)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("error deleting secret at %s: %w", pathToDelete, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|