-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
intentions_endpoint.go
568 lines (469 loc) · 16.4 KB
/
intentions_endpoint.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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
package agent
import (
"fmt"
"net/http"
"strings"
cachetype "github.com/hashicorp/consul/agent/cache-types"
"github.com/hashicorp/consul/agent/consul"
"github.com/hashicorp/consul/agent/structs"
)
// /v1/connect/intentions
func (s *HTTPHandlers) IntentionEndpoint(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
switch req.Method {
case "GET":
return s.IntentionList(resp, req)
case "POST":
return s.IntentionCreate(resp, req)
default:
return nil, MethodNotAllowedError{req.Method, []string{"GET", "POST"}}
}
}
// GET /v1/connect/intentions
func (s *HTTPHandlers) IntentionList(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
// Method is tested in IntentionEndpoint
var args structs.IntentionListRequest
if done := s.parse(resp, req, &args.Datacenter, &args.QueryOptions); done {
return nil, nil
}
if err := s.parseEntMeta(req, &args.EnterpriseMeta); err != nil {
return nil, err
}
var reply structs.IndexedIntentions
defer setMeta(resp, &reply.QueryMeta)
if err := s.agent.RPC("Intention.List", &args, &reply); err != nil {
return nil, err
}
return reply.Intentions, nil
}
// POST /v1/connect/intentions
func (s *HTTPHandlers) IntentionCreate(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
// Method is tested in IntentionEndpoint
var entMeta structs.EnterpriseMeta
if err := s.parseEntMetaNoWildcard(req, &entMeta); err != nil {
return nil, err
}
args := structs.IntentionRequest{
Op: structs.IntentionOpCreate,
}
s.parseDC(req, &args.Datacenter)
s.parseToken(req, &args.Token)
if err := decodeBody(req.Body, &args.Intention); err != nil {
return nil, fmt.Errorf("Failed to decode request body: %s", err)
}
args.Intention.FillNonDefaultNamespaces(&entMeta)
if err := s.validateEnterpriseIntention(args.Intention); err != nil {
return nil, err
}
var reply string
if err := s.agent.RPC("Intention.Apply", &args, &reply); err != nil {
return nil, err
}
return intentionCreateResponse{reply}, nil
}
func (s *HTTPHandlers) validateEnterpriseIntention(ixn *structs.Intention) error {
if err := s.validateEnterpriseIntentionNamespace("SourceNS", ixn.SourceNS, true); err != nil {
return err
}
if err := s.validateEnterpriseIntentionNamespace("DestinationNS", ixn.DestinationNS, true); err != nil {
return err
}
return nil
}
// GET /v1/connect/intentions/match
func (s *HTTPHandlers) IntentionMatch(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
// Prepare args
args := &structs.IntentionQueryRequest{Match: &structs.IntentionQueryMatch{}}
if done := s.parse(resp, req, &args.Datacenter, &args.QueryOptions); done {
return nil, nil
}
var entMeta structs.EnterpriseMeta
if err := s.parseEntMetaNoWildcard(req, &entMeta); err != nil {
return nil, err
}
q := req.URL.Query()
// Extract the "by" query parameter
if by, ok := q["by"]; !ok || len(by) != 1 {
return nil, fmt.Errorf("required query parameter 'by' not set")
} else {
switch v := structs.IntentionMatchType(by[0]); v {
case structs.IntentionMatchSource, structs.IntentionMatchDestination:
args.Match.Type = v
default:
return nil, fmt.Errorf("'by' parameter must be one of 'source' or 'destination'")
}
}
// Extract all the match names
names, ok := q["name"]
if !ok || len(names) == 0 {
return nil, fmt.Errorf("required query parameter 'name' not set")
}
// Build the entries in order. The order matters since that is the
// order of the returned responses.
args.Match.Entries = make([]structs.IntentionMatchEntry, len(names))
for i, n := range names {
ns, name, err := parseIntentionStringComponent(n, &entMeta)
if err != nil {
return nil, fmt.Errorf("name %q is invalid: %s", n, err)
}
args.Match.Entries[i] = structs.IntentionMatchEntry{
Namespace: ns,
Name: name,
}
}
// Make the RPC request
var out structs.IndexedIntentionMatches
defer setMeta(resp, &out.QueryMeta)
if s.agent.config.HTTPUseCache && args.QueryOptions.UseCache {
raw, m, err := s.agent.cache.Get(req.Context(), cachetype.IntentionMatchName, args)
if err != nil {
return nil, err
}
defer setCacheMeta(resp, &m)
reply, ok := raw.(*structs.IndexedIntentionMatches)
if !ok {
// This should never happen, but we want to protect against panics
return nil, fmt.Errorf("internal error: response type not correct")
}
out = *reply
} else {
RETRY_ONCE:
if err := s.agent.RPC("Intention.Match", args, &out); err != nil {
return nil, err
}
if args.QueryOptions.AllowStale && args.MaxStaleDuration > 0 && args.MaxStaleDuration < out.LastContact {
args.AllowStale = false
args.MaxStaleDuration = 0
goto RETRY_ONCE
}
}
out.ConsistencyLevel = args.QueryOptions.ConsistencyLevel()
// We must have an identical count of matches
if len(out.Matches) != len(names) {
return nil, fmt.Errorf("internal error: match response count didn't match input count")
}
// Use empty list instead of nil.
response := make(map[string]structs.Intentions)
for i, ixns := range out.Matches {
response[names[i]] = ixns
}
return response, nil
}
// GET /v1/connect/intentions/check
func (s *HTTPHandlers) IntentionCheck(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
// Prepare args
args := &structs.IntentionQueryRequest{Check: &structs.IntentionQueryCheck{}}
if done := s.parse(resp, req, &args.Datacenter, &args.QueryOptions); done {
return nil, nil
}
var entMeta structs.EnterpriseMeta
if err := s.parseEntMetaNoWildcard(req, &entMeta); err != nil {
return nil, err
}
q := req.URL.Query()
// Set the source type if set
args.Check.SourceType = structs.IntentionSourceConsul
if sourceType, ok := q["source-type"]; ok && len(sourceType) > 0 {
args.Check.SourceType = structs.IntentionSourceType(sourceType[0])
}
// Extract the source/destination
source, ok := q["source"]
if !ok || len(source) != 1 {
return nil, fmt.Errorf("required query parameter 'source' not set")
}
destination, ok := q["destination"]
if !ok || len(destination) != 1 {
return nil, fmt.Errorf("required query parameter 'destination' not set")
}
// We parse them the same way as matches to extract namespace/name
args.Check.SourceName = source[0]
if args.Check.SourceType == structs.IntentionSourceConsul {
ns, name, err := parseIntentionStringComponent(source[0], &entMeta)
if err != nil {
return nil, fmt.Errorf("source %q is invalid: %s", source[0], err)
}
args.Check.SourceNS = ns
args.Check.SourceName = name
}
// The destination is always in the Consul format
ns, name, err := parseIntentionStringComponent(destination[0], &entMeta)
if err != nil {
return nil, fmt.Errorf("destination %q is invalid: %s", destination[0], err)
}
args.Check.DestinationNS = ns
args.Check.DestinationName = name
var reply structs.IntentionQueryCheckResponse
if err := s.agent.RPC("Intention.Check", args, &reply); err != nil {
return nil, err
}
return &reply, nil
}
// GET /v1/connect/intentions/exact
func (s *HTTPHandlers) IntentionGetExact(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
var entMeta structs.EnterpriseMeta
if err := s.parseEntMetaNoWildcard(req, &entMeta); err != nil {
return nil, err
}
args := structs.IntentionQueryRequest{
Exact: &structs.IntentionQueryExact{},
}
if done := s.parse(resp, req, &args.Datacenter, &args.QueryOptions); done {
return nil, nil
}
q := req.URL.Query()
// Extract the source/destination
source, ok := q["source"]
if !ok || len(source) != 1 {
return nil, fmt.Errorf("required query parameter 'source' not set")
}
destination, ok := q["destination"]
if !ok || len(destination) != 1 {
return nil, fmt.Errorf("required query parameter 'destination' not set")
}
{
ns, name, err := parseIntentionStringComponent(source[0], &entMeta)
if err != nil {
return nil, fmt.Errorf("source %q is invalid: %s", source[0], err)
}
args.Exact.SourceNS = ns
args.Exact.SourceName = name
}
{
ns, name, err := parseIntentionStringComponent(destination[0], &entMeta)
if err != nil {
return nil, fmt.Errorf("destination %q is invalid: %s", destination[0], err)
}
args.Exact.DestinationNS = ns
args.Exact.DestinationName = name
}
var reply structs.IndexedIntentions
if err := s.agent.RPC("Intention.Get", &args, &reply); err != nil {
// We have to check the string since the RPC sheds the error type
if err.Error() == consul.ErrIntentionNotFound.Error() {
resp.WriteHeader(http.StatusNotFound)
fmt.Fprint(resp, err.Error())
return nil, nil
}
// Not ideal, but there are a number of error scenarios that are not
// user error (400). We look for a specific case of invalid UUID
// to detect a parameter error and return a 400 response. The error
// is not a constant type or message, so we have to use strings.Contains
if strings.Contains(err.Error(), "UUID") {
return nil, BadRequestError{Reason: err.Error()}
}
return nil, err
}
// This shouldn't happen since the called API documents it shouldn't,
// but we check since the alternative if it happens is a panic.
if len(reply.Intentions) == 0 {
resp.WriteHeader(http.StatusNotFound)
return nil, nil
}
return reply.Intentions[0], nil
}
// IntentionExact handles the endpoint for /v1/connect/intentions/exact
func (s *HTTPHandlers) IntentionExact(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
switch req.Method {
case "GET":
return s.IntentionGetExact(resp, req)
case "PUT":
return s.IntentionPutExact(resp, req)
case "DELETE":
return s.IntentionDeleteExact(resp, req)
default:
return nil, MethodNotAllowedError{req.Method, []string{"GET", "PUT", "DELETE"}}
}
}
// IntentionSpecific handles the endpoint for /v1/connect/intentions/:id
func (s *HTTPHandlers) IntentionSpecific(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
id := strings.TrimPrefix(req.URL.Path, "/v1/connect/intentions/")
switch req.Method {
case "GET":
return s.IntentionSpecificGet(id, resp, req)
case "PUT":
return s.IntentionSpecificUpdate(id, resp, req)
case "DELETE":
return s.IntentionSpecificDelete(id, resp, req)
default:
return nil, MethodNotAllowedError{req.Method, []string{"GET", "PUT", "DELETE"}}
}
}
// GET /v1/connect/intentions/:id
func (s *HTTPHandlers) IntentionSpecificGet(id string, resp http.ResponseWriter, req *http.Request) (interface{}, error) {
// Method is tested in IntentionEndpoint
args := structs.IntentionQueryRequest{
IntentionID: id,
}
if done := s.parse(resp, req, &args.Datacenter, &args.QueryOptions); done {
return nil, nil
}
var reply structs.IndexedIntentions
if err := s.agent.RPC("Intention.Get", &args, &reply); err != nil {
// We have to check the string since the RPC sheds the error type
if err.Error() == consul.ErrIntentionNotFound.Error() {
resp.WriteHeader(http.StatusNotFound)
fmt.Fprint(resp, err.Error())
return nil, nil
}
// Not ideal, but there are a number of error scenarios that are not
// user error (400). We look for a specific case of invalid UUID
// to detect a parameter error and return a 400 response. The error
// is not a constant type or message, so we have to use strings.Contains
if strings.Contains(err.Error(), "UUID") {
return nil, BadRequestError{Reason: err.Error()}
}
return nil, err
}
// This shouldn't happen since the called API documents it shouldn't,
// but we check since the alternative if it happens is a panic.
if len(reply.Intentions) == 0 {
resp.WriteHeader(http.StatusNotFound)
return nil, nil
}
return reply.Intentions[0], nil
}
// PUT /v1/connect/intentions/:id
func (s *HTTPHandlers) IntentionSpecificUpdate(id string, resp http.ResponseWriter, req *http.Request) (interface{}, error) {
// Method is tested in IntentionEndpoint
var entMeta structs.EnterpriseMeta
if err := s.parseEntMetaNoWildcard(req, &entMeta); err != nil {
return nil, err
}
args := structs.IntentionRequest{
Op: structs.IntentionOpUpdate,
}
s.parseDC(req, &args.Datacenter)
s.parseToken(req, &args.Token)
if err := decodeBody(req.Body, &args.Intention); err != nil {
return nil, BadRequestError{Reason: fmt.Sprintf("Request decode failed: %v", err)}
}
args.Intention.FillNonDefaultNamespaces(&entMeta)
// Use the ID from the URL
args.Intention.ID = id
var reply string
if err := s.agent.RPC("Intention.Apply", &args, &reply); err != nil {
return nil, err
}
// Update uses the same create response
return intentionCreateResponse{reply}, nil
}
// PUT /v1/connect/intentions/exact
func (s *HTTPHandlers) IntentionPutExact(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
var entMeta structs.EnterpriseMeta
if err := s.parseEntMetaNoWildcard(req, &entMeta); err != nil {
return nil, err
}
exact, err := parseIntentionQueryExact(req, &entMeta)
if err != nil {
return nil, err
}
args := structs.IntentionRequest{
Op: structs.IntentionOpUpsert,
}
s.parseDC(req, &args.Datacenter)
s.parseToken(req, &args.Token)
if err := decodeBody(req.Body, &args.Intention); err != nil {
return nil, BadRequestError{Reason: fmt.Sprintf("Request decode failed: %v", err)}
}
// Explicitly CLEAR the old legacy ID field
args.Intention.ID = ""
// Use the intention identity from the URL.
args.Intention.SourceNS = exact.SourceNS
args.Intention.SourceName = exact.SourceName
args.Intention.DestinationNS = exact.DestinationNS
args.Intention.DestinationName = exact.DestinationName
args.Intention.FillNonDefaultNamespaces(&entMeta)
var ignored string
if err := s.agent.RPC("Intention.Apply", &args, &ignored); err != nil {
return nil, err
}
return true, nil
}
// DELETE /v1/connect/intentions/:id
func (s *HTTPHandlers) IntentionSpecificDelete(id string, resp http.ResponseWriter, req *http.Request) (interface{}, error) {
// Method is tested in IntentionEndpoint
args := structs.IntentionRequest{
Op: structs.IntentionOpDelete,
Intention: &structs.Intention{ID: id},
}
s.parseDC(req, &args.Datacenter)
s.parseToken(req, &args.Token)
var reply string
if err := s.agent.RPC("Intention.Apply", &args, &reply); err != nil {
return nil, err
}
return true, nil
}
// DELETE /v1/connect/intentions/exact
func (s *HTTPHandlers) IntentionDeleteExact(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
var entMeta structs.EnterpriseMeta
if err := s.parseEntMetaNoWildcard(req, &entMeta); err != nil {
return nil, err
}
exact, err := parseIntentionQueryExact(req, &entMeta)
if err != nil {
return nil, err
}
args := structs.IntentionRequest{
Op: structs.IntentionOpDelete,
Intention: &structs.Intention{
// NOTE: ID is explicitly empty here
SourceNS: exact.SourceNS,
SourceName: exact.SourceName,
DestinationNS: exact.DestinationNS,
DestinationName: exact.DestinationName,
},
}
s.parseDC(req, &args.Datacenter)
s.parseToken(req, &args.Token)
var ignored string
if err := s.agent.RPC("Intention.Apply", &args, &ignored); err != nil {
return nil, err
}
return true, nil
}
// intentionCreateResponse is the response structure for creating an intention.
type intentionCreateResponse struct{ ID string }
func parseIntentionQueryExact(req *http.Request, entMeta *structs.EnterpriseMeta) (*structs.IntentionQueryExact, error) {
q := req.URL.Query()
// Extract the source/destination
source, ok := q["source"]
if !ok || len(source) != 1 || source[0] == "" {
return nil, fmt.Errorf("required query parameter 'source' not set")
}
destination, ok := q["destination"]
if !ok || len(destination) != 1 || destination[0] == "" {
return nil, fmt.Errorf("required query parameter 'destination' not set")
}
var exact structs.IntentionQueryExact
{
ns, name, err := parseIntentionStringComponent(source[0], entMeta)
if err != nil {
return nil, fmt.Errorf("source %q is invalid: %s", source[0], err)
}
exact.SourceNS = ns
exact.SourceName = name
}
{
ns, name, err := parseIntentionStringComponent(destination[0], entMeta)
if err != nil {
return nil, fmt.Errorf("destination %q is invalid: %s", destination[0], err)
}
exact.DestinationNS = ns
exact.DestinationName = name
}
return &exact, nil
}
func parseIntentionStringComponent(input string, entMeta *structs.EnterpriseMeta) (string, string, error) {
// Get the index to the '/'. If it doesn't exist, we have just a name
// so just set that and return.
idx := strings.IndexByte(input, '/')
if idx == -1 {
ns := entMeta.NamespaceOrEmpty()
return ns, input, nil
}
ns, name := input[:idx], input[idx+1:]
if strings.IndexByte(name, '/') != -1 {
return "", "", fmt.Errorf("input can contain at most one '/'")
}
return ns, name, nil
}