1package dependency
2
3import (
4	"github.com/hashicorp/vault/api"
5	"github.com/pkg/errors"
6)
7
8var (
9	// Ensure implements
10	_ Dependency = (*VaultTokenQuery)(nil)
11)
12
13// VaultTokenQuery is the dependency to Vault for a secret
14type VaultTokenQuery struct {
15	stopCh      chan struct{}
16	secret      *Secret
17	vaultSecret *api.Secret
18}
19
20// NewVaultTokenQuery creates a new dependency.
21func NewVaultTokenQuery(token string) (*VaultTokenQuery, error) {
22	vaultSecret := &api.Secret{
23		Auth: &api.SecretAuth{
24			ClientToken:   token,
25			Renewable:     true,
26			LeaseDuration: 1,
27		},
28	}
29	return &VaultTokenQuery{
30		stopCh:      make(chan struct{}, 1),
31		vaultSecret: vaultSecret,
32		secret:      transformSecret(vaultSecret),
33	}, nil
34}
35
36// Fetch queries the Vault API
37func (d *VaultTokenQuery) Fetch(clients *ClientSet, opts *QueryOptions,
38) (interface{}, *ResponseMetadata, error) {
39	select {
40	case <-d.stopCh:
41		return nil, nil, ErrStopped
42	default:
43	}
44
45	if vaultSecretRenewable(d.secret) {
46		err := renewSecret(clients, d)
47		if err != nil {
48			return nil, nil, errors.Wrap(err, d.String())
49		}
50	}
51
52	return nil, nil, ErrLeaseExpired
53}
54
55func (d *VaultTokenQuery) stopChan() chan struct{} {
56	return d.stopCh
57}
58
59func (d *VaultTokenQuery) secrets() (*Secret, *api.Secret) {
60	return d.secret, d.vaultSecret
61}
62
63// CanShare returns if this dependency is shareable.
64func (d *VaultTokenQuery) CanShare() bool {
65	return false
66}
67
68// Stop halts the dependency's fetch function.
69func (d *VaultTokenQuery) Stop() {
70	close(d.stopCh)
71}
72
73// String returns the human-friendly version of this dependency.
74func (d *VaultTokenQuery) String() string {
75	return "vault.token"
76}
77
78// Type returns the type of this dependency.
79func (d *VaultTokenQuery) Type() Type {
80	return TypeVault
81}
82