...
1
16
17 package secrets
18
19 import (
20 "regexp"
21 "strings"
22 "time"
23
24 v1 "k8s.io/api/core/v1"
25 "k8s.io/apimachinery/pkg/util/sets"
26 "k8s.io/cluster-bootstrap/token/api"
27 legacyutil "k8s.io/cluster-bootstrap/token/util"
28 "k8s.io/klog/v2"
29 )
30
31 var (
32 secretNameRe = regexp.MustCompile(`^` + regexp.QuoteMeta(api.BootstrapTokenSecretPrefix) + `([a-z0-9]{6})$`)
33 )
34
35
36
37 func GetData(secret *v1.Secret, key string) string {
38 if secret.Data == nil {
39 return ""
40 }
41 if val, ok := secret.Data[key]; ok {
42 return string(val)
43 }
44 return ""
45 }
46
47
48 func HasExpired(secret *v1.Secret, currentTime time.Time) bool {
49 _, expired := GetExpiration(secret, currentTime)
50
51 return expired
52 }
53
54
55
56
57
58
59 func GetExpiration(secret *v1.Secret, currentTime time.Time) (timeRemaining time.Duration, isExpired bool) {
60 expiration := GetData(secret, api.BootstrapTokenExpirationKey)
61 if len(expiration) == 0 {
62 return 0, false
63 }
64 expTime, err := time.Parse(time.RFC3339, expiration)
65 if err != nil {
66 klog.V(3).Infof("Unparseable expiration time (%s) in %s/%s Secret: %v. Treating as expired.",
67 expiration, secret.Namespace, secret.Name, err)
68 return 0, true
69 }
70
71 timeRemaining = expTime.Sub(currentTime)
72 if timeRemaining <= 0 {
73 klog.V(3).Infof("Expired bootstrap token in %s/%s Secret: %v",
74 secret.Namespace, secret.Name, expiration)
75 return 0, true
76 }
77 return timeRemaining, false
78 }
79
80
81 func ParseName(name string) (secretID string, ok bool) {
82 r := secretNameRe.FindStringSubmatch(name)
83 if r == nil {
84 return "", false
85 }
86 return r[1], true
87 }
88
89
90
91
92 func GetGroups(secret *v1.Secret) ([]string, error) {
93
94 groups := sets.NewString(api.BootstrapDefaultGroup)
95
96
97 extraGroupsString := GetData(secret, api.BootstrapTokenExtraGroupsKey)
98 if extraGroupsString == "" {
99 return groups.List(), nil
100 }
101
102
103 for _, group := range strings.Split(extraGroupsString, ",") {
104 if err := legacyutil.ValidateBootstrapGroupName(group); err != nil {
105 return nil, err
106 }
107 groups.Insert(group)
108 }
109
110
111 return groups.List(), nil
112 }
113
View as plain text