-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathbackend.go
256 lines (211 loc) · 6.29 KB
/
backend.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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package azuresecrets
import (
"context"
"fmt"
"strings"
"sync"
"time"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/consts"
"github.com/hashicorp/vault/sdk/helper/locksutil"
"github.com/hashicorp/vault/sdk/logical"
)
const (
userAgentPluginName = "secrets-azure"
// operationPrefixAzure is used as a prefix for OpenAPI operation id's.
operationPrefixAzure = "azure"
)
type azureSecretBackend struct {
*framework.Backend
getProvider func(context.Context, hclog.Logger, logical.SystemView, *clientSettings) (AzureProvider, error)
client *client
settings *clientSettings
lock sync.RWMutex
// Creating/deleting passwords against a single Application is a PATCH
// operation that must be locked per Application Object ID.
appLocks []*locksutil.LockEntry
updatePassword bool
}
func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) {
b := backend()
if err := b.Setup(ctx, conf); err != nil {
return nil, err
}
return b, nil
}
func backend() *azureSecretBackend {
b := azureSecretBackend{
updatePassword: true,
}
b.Backend = &framework.Backend{
Help: strings.TrimSpace(backendHelp),
PathsSpecial: &logical.Paths{
LocalStorage: []string{
framework.WALPrefix,
},
SealWrapStorage: []string{
"config",
},
},
Paths: framework.PathAppend(
pathsRole(&b),
[]*framework.Path{
pathConfig(&b),
pathServicePrincipal(&b),
pathRotateRoot(&b),
},
),
Secrets: []*framework.Secret{
secretServicePrincipal(&b),
secretStaticServicePrincipal(&b),
},
BackendType: logical.TypeLogical,
Invalidate: b.invalidate,
// Role assignment can take up to a few minutes, so ensure we don't try
// to roll back during creation.
WALRollbackMinAge: 10 * time.Minute,
WALRollback: b.walRollback,
PeriodicFunc: b.periodicFunc,
}
b.getProvider = newAzureProvider
b.appLocks = locksutil.CreateLocks()
return &b
}
func (b *azureSecretBackend) periodicFunc(ctx context.Context, sys *logical.Request) error {
// Root rotation through the periodic func writes to storage. Only run this on the
// active instance in the primary cluster or local mounts. The periodic func doesn't
// run on perf standbys or DR secondaries, but we still protect against this here.
replicationState := b.System().ReplicationState()
if (b.System().LocalMount() || !replicationState.HasState(consts.ReplicationPerformanceSecondary)) &&
!replicationState.HasState(consts.ReplicationDRSecondary) &&
!replicationState.HasState(consts.ReplicationPerformanceStandby) {
b.Logger().Debug("starting periodic func")
if !b.updatePassword {
b.Logger().Debug("periodic func", "rotate-root", "no rotate-root update")
return nil
}
config, err := b.getConfig(ctx, sys.Storage)
if err != nil {
return err
}
// Config can be nil if deleted or when the engine is enabled
// but not yet configured.
if config == nil {
return nil
}
// Password should be at least a minute old before we process it
if config.NewClientSecret == "" || (time.Since(config.NewClientSecretCreated) < time.Minute) {
return nil
}
b.Logger().Debug("periodic func", "rotate-root", "new password detected, swapping in storage")
client, err := b.getClient(ctx, sys.Storage)
if err != nil {
return err
}
apps, err := client.provider.ListApplications(ctx, fmt.Sprintf("appId eq '%s'", config.ClientID))
if err != nil {
return err
}
if len(apps) == 0 {
return fmt.Errorf("no application found")
}
if len(apps) > 1 {
return fmt.Errorf("multiple applications found - double check your client_id")
}
app := apps[0]
credsToDelete := []string{}
for _, cred := range app.PasswordCredentials {
if cred.KeyID != config.NewClientSecretKeyID {
credsToDelete = append(credsToDelete, cred.KeyID)
}
}
if len(credsToDelete) != 0 {
b.Logger().Debug("periodic func", "rotate-root", "removing old passwords from Azure")
err = removeApplicationPasswords(ctx, client.provider, app.AppObjectID, credsToDelete...)
if err != nil {
return err
}
}
b.Logger().Debug("periodic func", "rotate-root", "updating config with new password")
config.ClientSecret = config.NewClientSecret
config.ClientSecretKeyID = config.NewClientSecretKeyID
config.RootPasswordExpirationDate = config.NewClientSecretExpirationDate
config.NewClientSecret = ""
config.NewClientSecretKeyID = ""
config.NewClientSecretCreated = time.Time{}
err = b.saveConfig(ctx, config, sys.Storage)
if err != nil {
return err
}
b.updatePassword = false
}
return nil
}
// reset clears the backend's cached client
// This is used when the configuration changes and a new client should be
// created with the updated settings.
func (b *azureSecretBackend) reset() {
b.lock.Lock()
defer b.lock.Unlock()
b.settings = nil
b.client = nil
}
func (b *azureSecretBackend) invalidate(ctx context.Context, key string) {
switch key {
case "config":
b.reset()
}
}
func (b *azureSecretBackend) getClient(ctx context.Context, s logical.Storage) (*client, error) {
b.lock.RLock()
if b.client.Valid() {
b.lock.RUnlock()
return b.client, nil
}
b.lock.RUnlock()
b.lock.Lock()
defer b.lock.Unlock()
if b.client.Valid() {
return b.client, nil
}
config, err := b.getConfig(ctx, s)
if err != nil {
return nil, err
}
if b.settings == nil {
if config == nil {
config = new(azureConfig)
}
settings, err := b.getClientSettings(ctx, config)
if err != nil {
return nil, err
}
b.settings = settings
}
if config == nil {
return nil, fmt.Errorf("config is nil")
}
p, err := b.getProvider(ctx, b.Logger(), b.System(), b.settings)
if err != nil {
return nil, err
}
c := &client{
provider: p,
settings: b.settings,
expiration: time.Now().Add(clientLifetime),
}
b.client = c
return c, nil
}
const backendHelp = `
The Azure secrets backend dynamically generates Azure service
principals. The SP credentials have a configurable lease and
are automatically revoked at the end of the lease.
After mounting this backend, credentials to manage Azure resources
must be configured with the "config/" endpoints and policies must be
written using the "roles/" endpoints before any credentials can be
generated.
`