open-vault/api/kv_v1.go
VAL 64448b62a4
KV helper methods for api package (#15305)
* Add Read methods for KVClient

* KV write helper

* Add changelog

* Add Delete method

* Use extractVersionMetadata inside extractDataAndVersionMetadata

* Return nil, nil for v1 writes

* Add test for extracting version metadata

* Split kv client into v1 and v2-specific clients

* Add ability to set options on Put

* Add test for KV helpers

* Add custom metadata to top level and allow for getting versions as sorted slice

* Update tests

* Separate KV v1 and v2 into different files

* Add test for GetVersionsAsList, rename Metadata key to VersionMetadata for clarity

* Move structs and godoc comments to more appropriate files

* Add more tests for extract methods

* Rework custom metadata helper to be more consistent with other helpers

* Remove KVSecret from custom metadata test now that we don't append to it as part of helper method

* Return early for readability and make test value name less confusing
2022-05-25 11:17:13 -07:00

58 lines
1.5 KiB
Go

package api
import (
"context"
"fmt"
)
type kvv1 struct {
c *Client
mountPath string
}
// Get returns a secret from the KV v1 secrets engine.
func (kv *kvv1) Get(ctx context.Context, secretPath string) (*KVSecret, error) {
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 {
return nil, fmt.Errorf("no secret found at %s", pathToRead)
}
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.
func (kv *kvv1) Put(ctx context.Context, secretPath string, data map[string]interface{}) error {
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.
func (kv *kvv1) Delete(ctx context.Context, secretPath string) error {
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
}