forked from gravitational/teleport
/
server.go
603 lines (513 loc) · 16.9 KB
/
server.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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
/*
Copyright 2020 Gravitational, Inc.
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 types
import (
"fmt"
"regexp"
"sort"
"strings"
"time"
"github.com/gogo/protobuf/proto"
"github.com/gravitational/trace"
"github.com/zmb3/teleport/api/constants"
"github.com/zmb3/teleport/api/utils"
)
// Server represents a Node, Proxy or Auth server in a Teleport cluster
type Server interface {
// ResourceWithLabels provides common resource headers
ResourceWithLabels
// GetTeleportVersion returns the teleport version the server is running on
GetTeleportVersion() string
// GetAddr return server address
GetAddr() string
// GetHostname returns server hostname
GetHostname() string
// GetNamespace returns server namespace
GetNamespace() string
// GetLabels returns server's static label key pairs
GetLabels() map[string]string
// GetCmdLabels gets command labels
GetCmdLabels() map[string]CommandLabel
// SetCmdLabels sets command labels.
SetCmdLabels(cmdLabels map[string]CommandLabel)
// GetPublicAddr is an optional field that returns the public address this cluster can be reached at.
GetPublicAddr() string
// GetRotation gets the state of certificate authority rotation.
GetRotation() Rotation
// SetRotation sets the state of certificate authority rotation.
SetRotation(Rotation)
// GetUseTunnel gets if a reverse tunnel should be used to connect to this node.
GetUseTunnel() bool
// SetUseTunnel sets if a reverse tunnel should be used to connect to this node.
SetUseTunnel(bool)
// String returns string representation of the server
String() string
// SetAddr sets server address
SetAddr(addr string)
// SetPublicAddr sets the public address this cluster can be reached at.
SetPublicAddr(string)
// SetNamespace sets server namespace
SetNamespace(namespace string)
// GetApps gets the list of applications this server is proxying.
// DELETE IN 9.0.
GetApps() []*App
// GetApps gets the list of applications this server is proxying.
// DELETE IN 9.0.
SetApps([]*App)
// GetKubeClusters returns the kubernetes clusters directly handled by this
// server.
// DELETE IN 12.0.0
GetKubernetesClusters() []*KubernetesCluster
// SetKubeClusters sets the kubernetes clusters handled by this server.
// DELETE IN 12.0.0
SetKubernetesClusters([]*KubernetesCluster)
// GetPeerAddr returns the peer address of the server.
GetPeerAddr() string
// SetPeerAddr sets the peer address of the server.
SetPeerAddr(string)
// ProxiedService provides common methods for a proxied service.
ProxiedService
// MatchAgainst takes a map of labels and returns True if this server
// has ALL of them
//
// Any server matches against an empty label set
MatchAgainst(labels map[string]string) bool
// LabelsString returns a comma separated string with all node's labels
LabelsString() string
// DeepCopy creates a clone of this server value
DeepCopy() Server
}
// NewServer creates an instance of Server.
func NewServer(name, kind string, spec ServerSpecV2) (Server, error) {
return NewServerWithLabels(name, kind, spec, map[string]string{})
}
// NewServerWithLabels is a convenience method to create
// ServerV2 with a specific map of labels.
func NewServerWithLabels(name, kind string, spec ServerSpecV2, labels map[string]string) (Server, error) {
server := &ServerV2{
Kind: kind,
Metadata: Metadata{
Name: name,
Labels: labels,
},
Spec: spec,
}
if err := server.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
return server, nil
}
// GetVersion returns resource version
func (s *ServerV2) GetVersion() string {
return s.Version
}
// GetTeleportVersion returns the teleport version the server is running on
func (s *ServerV2) GetTeleportVersion() string {
return s.Spec.Version
}
// GetKind returns resource kind
func (s *ServerV2) GetKind() string {
return s.Kind
}
// GetSubKind returns resource sub kind
func (s *ServerV2) GetSubKind() string {
return s.SubKind
}
// SetSubKind sets resource subkind
func (s *ServerV2) SetSubKind(sk string) {
s.SubKind = sk
}
// GetResourceID returns resource ID
func (s *ServerV2) GetResourceID() int64 {
return s.Metadata.ID
}
// SetResourceID sets resource ID
func (s *ServerV2) SetResourceID(id int64) {
s.Metadata.ID = id
}
// GetMetadata returns metadata
func (s *ServerV2) GetMetadata() Metadata {
return s.Metadata
}
// SetNamespace sets server namespace
func (s *ServerV2) SetNamespace(namespace string) {
s.Metadata.Namespace = namespace
}
// SetAddr sets server address
func (s *ServerV2) SetAddr(addr string) {
s.Spec.Addr = addr
}
// SetExpiry sets expiry time for the object
func (s *ServerV2) SetExpiry(expires time.Time) {
s.Metadata.SetExpiry(expires)
}
// Expiry returns object expiry setting
func (s *ServerV2) Expiry() time.Time {
return s.Metadata.Expiry()
}
// SetPublicAddr sets the public address this cluster can be reached at.
func (s *ServerV2) SetPublicAddr(addr string) {
s.Spec.PublicAddr = addr
}
// GetName returns server name
func (s *ServerV2) GetName() string {
return s.Metadata.Name
}
// SetName sets the name of the TrustedCluster.
func (s *ServerV2) SetName(e string) {
s.Metadata.Name = e
}
// GetAddr return server address
func (s *ServerV2) GetAddr() string {
return s.Spec.Addr
}
// GetPublicAddr is an optional field that returns the public address this cluster can be reached at.
func (s *ServerV2) GetPublicAddr() string {
return s.Spec.PublicAddr
}
// GetRotation gets the state of certificate authority rotation.
func (s *ServerV2) GetRotation() Rotation {
return s.Spec.Rotation
}
// SetRotation sets the state of certificate authority rotation.
func (s *ServerV2) SetRotation(r Rotation) {
s.Spec.Rotation = r
}
// GetUseTunnel gets if a reverse tunnel should be used to connect to this node.
func (s *ServerV2) GetUseTunnel() bool {
return s.Spec.UseTunnel
}
// SetUseTunnel sets if a reverse tunnel should be used to connect to this node.
func (s *ServerV2) SetUseTunnel(useTunnel bool) {
s.Spec.UseTunnel = useTunnel
}
// GetHostname returns server hostname
func (s *ServerV2) GetHostname() string {
return s.Spec.Hostname
}
// GetLabels and GetStaticLabels are the same, and that is intentional. GetLabels
// exists to preserve backwards compatibility, while GetStaticLabels exists to
// implement ResourcesWithLabels.
// GetLabels returns server's static label key pairs
func (s *ServerV2) GetLabels() map[string]string {
return s.Metadata.Labels
}
// GetStaticLabels returns the server static labels.
func (s *ServerV2) GetStaticLabels() map[string]string {
return s.Metadata.Labels
}
// SetStaticLabels sets the server static labels.
func (s *ServerV2) SetStaticLabels(sl map[string]string) {
s.Metadata.Labels = sl
}
// GetCmdLabels returns command labels
func (s *ServerV2) GetCmdLabels() map[string]CommandLabel {
if s.Spec.CmdLabels == nil {
return nil
}
return V2ToLabels(s.Spec.CmdLabels)
}
// Origin returns the origin value of the resource.
func (s *ServerV2) Origin() string {
return s.Metadata.Origin()
}
// SetOrigin sets the origin value of the resource.
func (s *ServerV2) SetOrigin(origin string) {
s.Metadata.SetOrigin(origin)
}
// SetCmdLabels sets dynamic labels.
func (s *ServerV2) SetCmdLabels(cmdLabels map[string]CommandLabel) {
s.Spec.CmdLabels = LabelsToV2(cmdLabels)
}
// GetApps gets the list of applications this server is proxying.
func (s *ServerV2) GetApps() []*App {
return s.Spec.Apps
}
// SetApps sets the list of applications this server is proxying.
func (s *ServerV2) SetApps(apps []*App) {
s.Spec.Apps = apps
}
func (s *ServerV2) String() string {
return fmt.Sprintf("Server(name=%v, namespace=%v, addr=%v, labels=%v)", s.Metadata.Name, s.Metadata.Namespace, s.Spec.Addr, s.Metadata.Labels)
}
// GetNamespace returns server namespace
func (s *ServerV2) GetNamespace() string {
return ProcessNamespace(s.Metadata.Namespace)
}
// GetProxyID returns the proxy id this server is connected to.
func (s *ServerV2) GetProxyIDs() []string {
return s.Spec.ProxyIDs
}
// SetProxyID sets the proxy ids this server is connected to.
func (s *ServerV2) SetProxyIDs(proxyIDs []string) {
s.Spec.ProxyIDs = proxyIDs
}
// GetAllLabels returns the full key:value map of both static labels and
// "command labels"
func (s *ServerV2) GetAllLabels() map[string]string {
// server labels (static and dynamic)
labels := CombineLabels(s.Metadata.Labels, s.Spec.CmdLabels)
// server-specific labels
switch s.Kind {
case KindKubeService:
for _, cluster := range s.Spec.KubernetesClusters {
// Combine cluster static and dynamic labels, and merge into
// `labels`.
for name, value := range CombineLabels(cluster.StaticLabels, cluster.DynamicLabels) {
labels[name] = value
}
}
}
return labels
}
// CombineLabels combines the passed in static and dynamic labels.
func CombineLabels(static map[string]string, dynamic map[string]CommandLabelV2) map[string]string {
lmap := make(map[string]string)
for key, value := range static {
lmap[key] = value
}
for key, cmd := range dynamic {
lmap[key] = cmd.Result
}
return lmap
}
// GetKubernetesClusters returns the kubernetes clusters directly handled by this
// server.
// DEPRECATED, remove in 12.0.0
func (s *ServerV2) GetKubernetesClusters() []*KubernetesCluster { return s.Spec.KubernetesClusters }
// SetKubernetesClusters sets the kubernetes clusters handled by this server.
// DEPRECATED, remove in 12.0.0
func (s *ServerV2) SetKubernetesClusters(clusters []*KubernetesCluster) {
s.Spec.KubernetesClusters = clusters
}
// GetPeerAddr returns the peer address of the server.
func (s *ServerV2) GetPeerAddr() string {
return s.Spec.PeerAddr
}
// SetPeerAddr sets the peer address of the server.
func (s *ServerV2) SetPeerAddr(addr string) {
s.Spec.PeerAddr = addr
}
// MatchAgainst takes a map of labels and returns True if this server
// has ALL of them
//
// Any server matches against an empty label set
func (s *ServerV2) MatchAgainst(labels map[string]string) bool {
return MatchLabels(s, labels)
}
// LabelsString returns a comma separated string of all labels.
func (s *ServerV2) LabelsString() string {
return LabelsAsString(s.Metadata.Labels, s.Spec.CmdLabels)
}
// LabelsAsString combines static and dynamic labels and returns a comma
// separated string.
func LabelsAsString(static map[string]string, dynamic map[string]CommandLabelV2) string {
labels := []string{}
for key, val := range static {
labels = append(labels, fmt.Sprintf("%s=%s", key, val))
}
for key, val := range dynamic {
labels = append(labels, fmt.Sprintf("%s=%s", key, val.Result))
}
sort.Strings(labels)
return strings.Join(labels, ",")
}
// setStaticFields sets static resource header and metadata fields.
func (s *ServerV2) setStaticFields() {
s.Version = V2
}
// CheckAndSetDefaults checks and set default values for any missing fields.
func (s *ServerV2) CheckAndSetDefaults() error {
// TODO(awly): default s.Metadata.Expiry if not set (use
// defaults.ServerAnnounceTTL).
s.setStaticFields()
if err := s.Metadata.CheckAndSetDefaults(); err != nil {
return trace.Wrap(err)
}
if s.Kind == "" {
return trace.BadParameter("server Kind is empty")
}
for key := range s.Spec.CmdLabels {
if !IsValidLabelKey(key) {
return trace.BadParameter("invalid label key: %q", key)
}
}
for _, kc := range s.Spec.KubernetesClusters {
if !validKubeClusterName.MatchString(kc.Name) {
return trace.BadParameter("invalid kubernetes cluster name: %q", kc.Name)
}
}
return nil
}
// MatchSearch goes through select field values and tries to
// match against the list of search values.
func (s *ServerV2) MatchSearch(values []string) bool {
var fieldVals []string
var custom func(val string) bool
if s.GetKind() == KindNode {
fieldVals = append(utils.MapToStrings(s.GetAllLabels()), s.GetName(), s.GetHostname(), s.GetAddr())
if s.GetUseTunnel() {
custom = func(val string) bool {
return strings.EqualFold(val, "tunnel")
}
}
}
return MatchSearch(fieldVals, values, custom)
}
// DeepCopy creates a clone of this server value
func (s *ServerV2) DeepCopy() Server {
return proto.Clone(s).(*ServerV2)
}
// IsAWSConsole returns true if this app is AWS management console.
func (a *App) IsAWSConsole() bool {
return strings.HasPrefix(a.URI, constants.AWSConsoleURL)
}
// GetAWSAccountID returns value of label containing AWS account ID on this app.
func (a *App) GetAWSAccountID() string {
return a.StaticLabels[constants.AWSAccountIDLabel]
}
// CommandLabel is a label that has a value as a result of the
// output generated by running command, e.g. hostname
type CommandLabel interface {
// GetPeriod returns label period
GetPeriod() time.Duration
// SetPeriod sets label period
SetPeriod(time.Duration)
// GetResult returns label result
GetResult() string
// SetResult sets label result
SetResult(string)
// GetCommand returns to execute and set as a label result
GetCommand() []string
// Clone returns label copy
Clone() CommandLabel
}
// Clone returns non-shallow copy of the label
func (c *CommandLabelV2) Clone() CommandLabel {
command := make([]string, len(c.Command))
copy(command, c.Command)
return &CommandLabelV2{
Command: command,
Period: c.Period,
Result: c.Result,
}
}
// SetResult sets label result
func (c *CommandLabelV2) SetResult(r string) {
c.Result = r
}
// SetPeriod sets label period
func (c *CommandLabelV2) SetPeriod(p time.Duration) {
c.Period = Duration(p)
}
// GetPeriod returns label period
func (c *CommandLabelV2) GetPeriod() time.Duration {
return c.Period.Duration()
}
// GetResult returns label result
func (c *CommandLabelV2) GetResult() string {
return c.Result
}
// GetCommand returns to execute and set as a label result
func (c *CommandLabelV2) GetCommand() []string {
return c.Command
}
// V2ToLabels converts concrete type to command label interface.
func V2ToLabels(l map[string]CommandLabelV2) map[string]CommandLabel {
out := make(map[string]CommandLabel, len(l))
for key := range l {
val := l[key]
out[key] = &val
}
return out
}
// LabelsToV2 converts labels from interface to V2 spec
func LabelsToV2(labels map[string]CommandLabel) map[string]CommandLabelV2 {
out := make(map[string]CommandLabelV2, len(labels))
for key, val := range labels {
out[key] = CommandLabelV2{
Period: NewDuration(val.GetPeriod()),
Result: val.GetResult(),
Command: val.GetCommand(),
}
}
return out
}
// validKubeClusterName filters the allowed characters in kubernetes cluster
// names. We need this because cluster names are used for cert filenames on the
// client side, in the ~/.tsh directory. Restricting characters helps with
// sneaky cluster names being used for client directory traversal and exploits.
var validKubeClusterName = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)
// Servers represents a list of servers.
type Servers []Server
// Len returns the slice length.
func (s Servers) Len() int { return len(s) }
// Less compares servers by name.
func (s Servers) Less(i, j int) bool {
return s[i].GetName() < s[j].GetName()
}
// Swap swaps two servers.
func (s Servers) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// SortByCustom custom sorts by given sort criteria.
func (s Servers) SortByCustom(sortBy SortBy) error {
if sortBy.Field == "" {
return nil
}
isDesc := sortBy.IsDesc
switch sortBy.Field {
case ResourceMetadataName:
sort.SliceStable(s, func(i, j int) bool {
return stringCompare(s[i].GetName(), s[j].GetName(), isDesc)
})
case ResourceSpecHostname:
sort.SliceStable(s, func(i, j int) bool {
return stringCompare(s[i].GetHostname(), s[j].GetHostname(), isDesc)
})
case ResourceSpecAddr:
sort.SliceStable(s, func(i, j int) bool {
return stringCompare(s[i].GetAddr(), s[j].GetAddr(), isDesc)
})
default:
return trace.NotImplemented("sorting by field %q for resource %q is not supported", sortBy.Field, KindNode)
}
return nil
}
// AsResources returns as type resources with labels.
func (s Servers) AsResources() []ResourceWithLabels {
resources := make([]ResourceWithLabels, 0, len(s))
for _, server := range s {
resources = append(resources, ResourceWithLabels(server))
}
return resources
}
// GetFieldVals returns list of select field values.
func (s Servers) GetFieldVals(field string) ([]string, error) {
vals := make([]string, 0, len(s))
switch field {
case ResourceMetadataName:
for _, server := range s {
vals = append(vals, server.GetName())
}
case ResourceSpecHostname:
for _, server := range s {
vals = append(vals, server.GetHostname())
}
case ResourceSpecAddr:
for _, server := range s {
vals = append(vals, server.GetAddr())
}
default:
return nil, trace.NotImplemented("getting field %q for resource %q is not supported", field, KindNode)
}
return vals, nil
}