-
Notifications
You must be signed in to change notification settings - Fork 0
/
token.go
83 lines (74 loc) · 2.17 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
package teleport
import (
"context"
"fmt"
"time"
"github.com/go-logr/logr"
tt "github.com/gravitational/teleport/api/types"
"github.com/giantswarm/microerror"
"github.com/giantswarm/teleport-operator/internal/pkg/key"
)
func (t *Teleport) IsTokenValid(ctx context.Context, registerName string, oldToken string, tokenType string) (bool, error) {
tokens, err := t.TeleportClient.GetTokens(ctx)
if err != nil {
return false, microerror.Mask(err)
}
for _, token := range tokens {
if token.GetMetadata().Labels["cluster"] == registerName && token.GetMetadata().Labels["type"] == tokenType {
if token.GetName() == oldToken {
return true, nil
}
return false, nil
}
}
return false, nil
}
func (t *Teleport) GenerateToken(ctx context.Context, registerName string, tokenType string) (string, error) {
var (
tokenValidity time.Time
tokenRole tt.SystemRole
)
switch tokenType {
case "kube":
tokenValidity = time.Now().Add(key.TeleportKubeTokenValidity)
tokenRole = tt.RoleKube
case "node":
tokenValidity = time.Now().Add(key.TeleportNodeTokenValidity)
tokenRole = tt.RoleNode
default:
return "", microerror.Mask(fmt.Errorf("token type %s is not supported", tokenType))
}
token, err := tt.NewProvisionToken(t.TokenGenerator.Generate(), []tt.SystemRole{tokenRole}, tokenValidity)
if err != nil {
return "", microerror.Mask(err)
}
// Set cluster label to token
{
m := token.GetMetadata()
m.Labels = map[string]string{
"cluster": registerName,
"type": tokenType,
}
token.SetMetadata(m)
if err := t.TeleportClient.UpsertToken(ctx, token); err != nil {
return "", microerror.Mask(err)
}
}
return token.GetName(), nil
}
func (t *Teleport) DeleteToken(ctx context.Context, log logr.Logger, registerName string) error {
tokens, err := t.TeleportClient.GetTokens(ctx)
if err != nil {
return err
}
for _, token := range tokens {
if token.GetMetadata().Labels["cluster"] == registerName {
if err := t.TeleportClient.DeleteToken(ctx, token.GetName()); err != nil {
return microerror.Mask(err)
}
log.Info("Deleted teleport node/kube join token for the cluster", "registerName", registerName)
return nil
}
}
return nil
}