-
Notifications
You must be signed in to change notification settings - Fork 1
/
token.go
146 lines (129 loc) · 3.45 KB
/
token.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
// Copyright 2022 VaultOperator Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package vault
// Initial version from: authn-authz/customer-credential-service/blob/develop/pkg/vault/vault.go
import (
"sync"
"time"
"github.com/go-logr/logr"
"github.com/hashicorp/vault/api"
)
// TokenHandler automatically deals with the renewal of tokens used for authentication with the
// Vault API. It uses the AuthMethod to generate new tokens if required (e.g. if the current token
// is not renewable anymore).
type TokenHandler struct {
client *Client
method AuthMethod
log logr.Logger
tokens chan string
mu sync.Mutex
closed bool
renewer *api.Renewer
}
// NewTokenHandler creates a new TokenHandler.
func NewTokenHandler(c *Client, m AuthMethod) *TokenHandler {
h := &TokenHandler{
client: c,
method: m,
log: c.log.WithName("TokenHandler"),
tokens: make(chan string),
}
if h.method.IsRenewable() {
go h.run()
}
return h
}
// WaitForToken blocks until a renewed token or the initial token has been received. It returns an
// error if no token is received before the timeout is reached.
func (h *TokenHandler) WaitForToken(timeout time.Duration) error {
if h.method.IsRenewable() {
select {
case <-h.tokens:
case <-time.After(timeout):
return ErrTimeout
}
} else {
secret, err := h.method.Login(h.client)
if err != nil {
return err
}
h.client.SetToken(secret.Auth.ClientToken)
}
return nil
}
// Close the token handler and stop the background renewal process.
func (h *TokenHandler) Close() {
h.mu.Lock()
defer h.mu.Unlock()
h.closed = true
if h.renewer != nil {
h.renewer.Stop()
}
}
func (h *TokenHandler) run() {
h.log.Info("Starting token renewal loop.")
for {
h.mu.Lock()
if h.closed {
h.mu.Unlock()
break
}
h.mu.Unlock()
secret, err := h.method.Login(h.client)
if err != nil {
h.log.Error(err, "Failed to request client token")
time.Sleep(500 * time.Millisecond)
continue
}
if secret == nil {
h.log.Info("Received empty token response. Retrying...")
time.Sleep(500 * time.Millisecond)
continue
}
token := secret.Auth.ClientToken
h.log.V(2).Info("Setting client-token", "token", token)
h.client.SetToken(token)
select {
case h.tokens <- token:
default:
}
renewer, err := h.client.NewLifetimeWatcher(&api.RenewerInput{Secret: secret})
if err != nil {
h.log.Error(err, "Failed to start token renewer.")
}
h.mu.Lock()
h.renewer = renewer
h.mu.Unlock()
go h.renewer.Renew()
h.monitorRenewal()
}
}
func (h *TokenHandler) monitorRenewal() {
for {
select {
case err := <-h.renewer.DoneCh():
if err != nil {
h.log.Error(err, "Vault token renewer returned error.")
}
return
case result := <-h.renewer.RenewCh():
h.log.V(2).Info(
"Renewed Vault client token.",
"token", result.Secret.Auth.ClientToken,
"lease", time.Duration(result.Secret.Auth.LeaseDuration)*time.Second,
"renewable", result.Secret.Auth.Renewable,
)
}
}
}