forked from hashicorp/vault
-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
347 lines (300 loc) · 8.5 KB
/
router.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
package vault
import (
"fmt"
"strings"
"sync"
"time"
"github.com/armon/go-metrics"
"github.com/armon/go-radix"
"github.com/hashicorp/vault/helper/salt"
"github.com/hashicorp/vault/logical"
)
// Router is used to do prefix based routing of a request to a logical backend
type Router struct {
l sync.RWMutex
root *radix.Tree
tokenStoreSalt *salt.Salt
}
// NewRouter returns a new router
func NewRouter() *Router {
r := &Router{
root: radix.New(),
}
return r
}
// routeEntry is used to represent a mount point in the router
type routeEntry struct {
tainted bool
backend logical.Backend
mountEntry *MountEntry
storageView *BarrierView
rootPaths *radix.Tree
loginPaths *radix.Tree
}
// SaltID is used to apply a salt and hash to an ID to make sure its not reversible
func (re *routeEntry) SaltID(id string) string {
return salt.SaltID(re.mountEntry.UUID, id, salt.SHA1Hash)
}
// Mount is used to expose a logical backend at a given prefix, using a unique salt,
// and the barrier view for that path.
func (r *Router) Mount(backend logical.Backend, prefix string, mountEntry *MountEntry, storageView *BarrierView) error {
r.l.Lock()
defer r.l.Unlock()
// Check if this is a nested mount
if existing, _, ok := r.root.LongestPrefix(prefix); ok && existing != "" {
return fmt.Errorf("cannot mount under existing mount '%s'", existing)
}
// Build the paths
paths := backend.SpecialPaths()
if paths == nil {
paths = new(logical.Paths)
}
// Create a mount entry
re := &routeEntry{
tainted: false,
backend: backend,
mountEntry: mountEntry,
storageView: storageView,
rootPaths: pathsToRadix(paths.Root),
loginPaths: pathsToRadix(paths.Unauthenticated),
}
r.root.Insert(prefix, re)
return nil
}
// Unmount is used to remove a logical backend from a given prefix
func (r *Router) Unmount(prefix string) error {
r.l.Lock()
defer r.l.Unlock()
// Call backend's Cleanup routine
re, ok := r.root.Get(prefix)
if ok {
re.(*routeEntry).backend.Cleanup()
}
r.root.Delete(prefix)
return nil
}
// Remount is used to change the mount location of a logical backend
func (r *Router) Remount(src, dst string) error {
r.l.Lock()
defer r.l.Unlock()
// Check for existing mount
raw, ok := r.root.Get(src)
if !ok {
return fmt.Errorf("no mount at '%s'", src)
}
// Update the mount point
r.root.Delete(src)
r.root.Insert(dst, raw)
return nil
}
// Taint is used to mark a path as tainted. This means only RollbackOperation
// RevokeOperation requests are allowed to proceed
func (r *Router) Taint(path string) error {
r.l.Lock()
defer r.l.Unlock()
_, raw, ok := r.root.LongestPrefix(path)
if ok {
raw.(*routeEntry).tainted = true
}
return nil
}
// Untaint is used to unmark a path as tainted.
func (r *Router) Untaint(path string) error {
r.l.Lock()
defer r.l.Unlock()
_, raw, ok := r.root.LongestPrefix(path)
if ok {
raw.(*routeEntry).tainted = false
}
return nil
}
// MatchingMount returns the mount prefix that would be used for a path
func (r *Router) MatchingMount(path string) string {
r.l.RLock()
mount, _, ok := r.root.LongestPrefix(path)
r.l.RUnlock()
if !ok {
return ""
}
return mount
}
// MatchingView returns the view used for a path
func (r *Router) MatchingStorageView(path string) *BarrierView {
r.l.RLock()
_, raw, ok := r.root.LongestPrefix(path)
r.l.RUnlock()
if !ok {
return nil
}
return raw.(*routeEntry).storageView
}
// MatchingMountEntry returns the MountEntry used for a path
func (r *Router) MatchingMountEntry(path string) *MountEntry {
r.l.RLock()
_, raw, ok := r.root.LongestPrefix(path)
r.l.RUnlock()
if !ok {
return nil
}
return raw.(*routeEntry).mountEntry
}
// MatchingMountEntry returns the MountEntry used for a path
func (r *Router) MatchingBackend(path string) logical.Backend {
r.l.RLock()
_, raw, ok := r.root.LongestPrefix(path)
r.l.RUnlock()
if !ok {
return nil
}
return raw.(*routeEntry).backend
}
// MatchingSystemView returns the SystemView used for a path
func (r *Router) MatchingSystemView(path string) logical.SystemView {
r.l.RLock()
_, raw, ok := r.root.LongestPrefix(path)
r.l.RUnlock()
if !ok {
return nil
}
return raw.(*routeEntry).backend.System()
}
// Route is used to route a given request
func (r *Router) Route(req *logical.Request) (*logical.Response, error) {
resp, _, _, err := r.routeCommon(req, false)
return resp, err
}
// Route is used to route a given existence check request
func (r *Router) RouteExistenceCheck(req *logical.Request) (bool, bool, error) {
_, ok, exists, err := r.routeCommon(req, true)
return ok, exists, err
}
func (r *Router) routeCommon(req *logical.Request, existenceCheck bool) (*logical.Response, bool, bool, error) {
// Find the mount point
r.l.RLock()
mount, raw, ok := r.root.LongestPrefix(req.Path)
if !ok {
// Re-check for a backend by appending a slash. This lets "foo" mean
// "foo/" at the root level which is almost always what we want.
req.Path += "/"
mount, raw, ok = r.root.LongestPrefix(req.Path)
}
r.l.RUnlock()
if !ok {
return logical.ErrorResponse(fmt.Sprintf("no handler for route '%s'", req.Path)), false, false, logical.ErrUnsupportedPath
}
defer metrics.MeasureSince([]string{"route", string(req.Operation),
strings.Replace(mount, "/", "-", -1)}, time.Now())
re := raw.(*routeEntry)
// If the path is tainted, we reject any operation except for
// Rollback and Revoke
if re.tainted {
switch req.Operation {
case logical.RevokeOperation, logical.RollbackOperation:
default:
return logical.ErrorResponse(fmt.Sprintf("no handler for route '%s'", req.Path)), false, false, logical.ErrUnsupportedPath
}
}
// Adjust the path to exclude the routing prefix
original := req.Path
req.Path = strings.TrimPrefix(req.Path, mount)
req.MountPoint = mount
if req.Path == "/" {
req.Path = ""
}
// Attach the storage view for the request
req.Storage = re.storageView
// Hash the request token unless this is the token backend
clientToken := req.ClientToken
switch {
case strings.HasPrefix(original, "auth/token/"):
case strings.HasPrefix(original, "cubbyhole/"):
// In order for the token store to revoke later, we need to have the same
// salted ID, so we double-salt what's going to the cubbyhole backend
req.ClientToken = re.SaltID(r.tokenStoreSalt.SaltID(req.ClientToken))
default:
req.ClientToken = re.SaltID(req.ClientToken)
}
// Cache the pointer to the original connection object
originalConn := req.Connection
// Cache the identifier of the request
originalReqID := req.ID
// Reset the request before returning
defer func() {
req.Path = original
req.MountPoint = ""
req.Connection = originalConn
req.ID = originalReqID
req.Storage = nil
req.ClientToken = clientToken
}()
// Invoke the backend
if existenceCheck {
ok, exists, err := re.backend.HandleExistenceCheck(req)
return nil, ok, exists, err
} else {
resp, err := re.backend.HandleRequest(req)
return resp, false, false, err
}
}
// RootPath checks if the given path requires root privileges
func (r *Router) RootPath(path string) bool {
r.l.RLock()
mount, raw, ok := r.root.LongestPrefix(path)
r.l.RUnlock()
if !ok {
return false
}
re := raw.(*routeEntry)
// Trim to get remaining path
remain := strings.TrimPrefix(path, mount)
// Check the rootPaths of this backend
match, raw, ok := re.rootPaths.LongestPrefix(remain)
if !ok {
return false
}
prefixMatch := raw.(bool)
// Handle the prefix match case
if prefixMatch {
return strings.HasPrefix(remain, match)
}
// Handle the exact match case
return match == remain
}
// LoginPath checks if the given path is used for logins
func (r *Router) LoginPath(path string) bool {
r.l.RLock()
mount, raw, ok := r.root.LongestPrefix(path)
r.l.RUnlock()
if !ok {
return false
}
re := raw.(*routeEntry)
// Trim to get remaining path
remain := strings.TrimPrefix(path, mount)
// Check the loginPaths of this backend
match, raw, ok := re.loginPaths.LongestPrefix(remain)
if !ok {
return false
}
prefixMatch := raw.(bool)
// Handle the prefix match case
if prefixMatch {
return strings.HasPrefix(remain, match)
}
// Handle the exact match case
return match == remain
}
// pathsToRadix converts a the mapping of special paths to a mapping
// of special paths to radix trees.
func pathsToRadix(paths []string) *radix.Tree {
tree := radix.New()
for _, path := range paths {
// Check if this is a prefix or exact match
prefixMatch := len(path) >= 1 && path[len(path)-1] == '*'
if prefixMatch {
path = path[:len(path)-1]
}
tree.Insert(path, prefixMatch)
}
return tree
}