-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathtoken_claim_create.go
263 lines (251 loc) · 7.43 KB
/
token_claim_create.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
package client
import (
"context"
"fmt"
"os"
"strconv"
"strings"
"time"
"github.com/google/uuid"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/serializer/json"
"k8s.io/client-go/kubernetes/scheme"
"github.com/skupperproject/skupper/api/types"
"github.com/skupperproject/skupper/pkg/kube"
)
func getSiteId(service *corev1.Service) string {
for _, ref := range service.ObjectMeta.OwnerReferences {
if ref.Name == "skupper-site" {
return string(ref.UID)
}
}
return ""
}
func getClaimsPort(service *corev1.Service) int32 {
for _, port := range service.Spec.Ports {
if port.Name == types.ClaimRedemptionPortName {
return port.Port
}
}
return 0
}
func getClaimsNodePort(service *corev1.Service) (int32, error) {
for _, port := range service.Spec.Ports {
if port.Name == types.ClaimRedemptionPortName {
return port.NodePort, nil
}
}
return 0, fmt.Errorf("NodePort for claims not found.")
}
func (cli *VanClient) getControllerIngressHost() (string, error) {
config, err := cli.SiteConfigInspect(context.TODO(), nil)
if err != nil {
return "", err
}
if host := config.Spec.GetControllerIngressHost(); host != "" {
return host, nil
}
return "", fmt.Errorf("Controller ingress host not defined, cannot use claims for nodeport without it. A certificate token can be generated directly with --token-type=cert.")
}
func (cli *VanClient) TokenClaimCreateFile(ctx context.Context, name string, password []byte, expiry time.Duration, uses int, secretFile string) error {
policy := NewPolicyValidatorAPI(cli)
res, err := policy.IncomingLink()
if err != nil {
return err
}
if !res.Allowed {
return res.Err()
}
claim, localOnly, err := cli.TokenClaimCreate(ctx, name, password, expiry, uses)
if err != nil {
return err
}
s := json.NewYAMLSerializer(json.DefaultMetaFactory, scheme.Scheme, scheme.Scheme)
out, err := os.Create(secretFile)
if err != nil {
return fmt.Errorf("Could not write to file " + secretFile + ": " + err.Error())
}
err = s.Encode(claim, out)
if err != nil {
return fmt.Errorf("Could not write out generated secret: " + err.Error())
} else {
var extra string
if localOnly {
extra = "(Note: token will only be valid for local cluster)"
}
fmt.Printf("Token written to %s %s", secretFile, extra)
fmt.Println()
return nil
}
}
func getContourProxyClaimsHostSuffix(cli *VanClient) string {
config, err := cli.SiteConfigInspect(context.TODO(), nil)
if err != nil {
fmt.Printf("Failed to look up site config: %s, ", err)
fmt.Println()
return ""
}
if config != nil && config.Spec.IsIngressContourHttpProxy() {
return config.Spec.GetControllerIngressHost()
}
return ""
}
func (cli *VanClient) TokenClaimTemplateCreate(ctx context.Context, name string, password []byte, recordName string) (*corev1.Secret, *corev1.Service, bool, error) {
policy := NewClusterPolicyValidator(cli)
res := policy.ValidateIncomingLink()
if !res.Allowed() {
return nil, nil, false, fmt.Errorf("incoming links are not allowed")
}
current, err := cli.getRouterConfig(ctx, "")
if err != nil {
return nil, nil, false, err
}
if current.IsEdge() {
return nil, nil, false, fmt.Errorf("Edge configuration cannot accept connections")
}
service, err := cli.KubeClient.CoreV1().Services(cli.Namespace).Get(ctx, types.ControllerServiceName, metav1.GetOptions{})
if err != nil {
return nil, nil, false, err
}
port := getClaimsPort(service)
if port == 0 {
return nil, nil, false, fmt.Errorf("Site cannot accept connections")
}
host := fmt.Sprintf("%s.%s", types.ControllerServiceName, cli.Namespace)
localOnly := true
ok, err := configureClaimHostFromRoutes(&host, cli)
if err != nil {
return nil, nil, false, err
} else if ok {
// host configured from route
port = 443
localOnly = false
} else if service.Spec.Type == corev1.ServiceTypeLoadBalancer {
host = kube.GetLoadBalancerHostOrIp(service)
localOnly = false
} else if service.Spec.Type == corev1.ServiceTypeNodePort {
host, err = cli.getControllerIngressHost()
if err != nil {
return nil, nil, false, err
}
port, err = getClaimsNodePort(service)
if err != nil {
return nil, nil, false, err
}
localOnly = false
} else if suffix := getContourProxyClaimsHostSuffix(cli); suffix != "" {
host = strings.Join([]string{types.ClaimsIngressPrefix, cli.Namespace, suffix}, ".")
port = 443
localOnly = false
} else {
ingressRoutes, err := kube.GetIngressRoutes(types.IngressName, cli.Namespace, cli)
if err != nil {
return nil, nil, false, err
}
if len(ingressRoutes) > 0 {
for _, route := range ingressRoutes {
if route.ServicePort == int(types.ClaimRedemptionPort) {
host = route.Host
port = 443
localOnly = false
break
}
}
}
}
protocol := "https"
url := fmt.Sprintf("%s://%s:%d/%s", protocol, host, port, recordName)
caSecret, err := cli.KubeClient.CoreV1().Secrets(cli.Namespace).Get(ctx, types.SiteCaSecret, metav1.GetOptions{})
if err != nil {
return nil, nil, false, err
}
claim := corev1.Secret{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "Secret",
},
ObjectMeta: metav1.ObjectMeta{
Name: name,
Labels: map[string]string{
types.SkupperTypeQualifier: types.TypeClaimRequest,
},
Annotations: map[string]string{
types.ClaimUrlAnnotationKey: url,
types.SiteVersion: current.GetSiteMetadata().Version,
},
},
Data: map[string][]byte{
types.ClaimPasswordDataKey: password,
types.ClaimCaCertDataKey: caSecret.Data["tls.crt"],
},
}
siteId := getSiteId(service)
if siteId != "" {
claim.ObjectMeta.Annotations[types.TokenGeneratedBy] = siteId
}
return &claim, service, localOnly, nil
}
func (cli *VanClient) TokenClaimCreate(ctx context.Context, name string, password []byte, expiry time.Duration, uses int) (*corev1.Secret, bool, error) {
if name == "" {
id, err := uuid.NewUUID()
if err != nil {
return nil, false, err
}
name = id.String()
}
claim, service, localOnly, err := cli.TokenClaimTemplateCreate(ctx, name, password, name)
if err != nil {
return nil, false, err
}
siteMetadata, err := cli.GetSiteMetadata()
if err != nil {
return nil, false, err
}
record := corev1.Secret{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "Secret",
},
ObjectMeta: metav1.ObjectMeta{
Name: name,
Labels: map[string]string{
types.SkupperTypeQualifier: types.TypeClaimRecord,
},
Annotations: map[string]string{
types.SiteVersion: siteMetadata.Version,
},
},
Data: map[string][]byte{
types.ClaimPasswordDataKey: password,
},
}
record.ObjectMeta.OwnerReferences = service.ObjectMeta.OwnerReferences
if expiry > 0 {
expiration := time.Now().Add(expiry)
record.ObjectMeta.Annotations[types.ClaimExpiration] = expiration.Format(time.RFC3339)
}
if uses > 0 {
record.ObjectMeta.Annotations[types.ClaimsRemaining] = strconv.Itoa(uses)
}
_, err = cli.KubeClient.CoreV1().Secrets(cli.Namespace).Create(ctx, &record, metav1.CreateOptions{})
if err != nil {
return nil, false, err
}
return claim, localOnly, nil
}
func configureClaimHostFromRoutes(host *string, cli *VanClient) (bool, error) {
if cli.RouteClient == nil {
return false, nil
}
route, err := cli.RouteClient.Routes(cli.Namespace).Get(context.TODO(), types.ClaimRedemptionRouteName, metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
return false, nil
}
return false, err
}
*host = route.Spec.Host
return true, nil
}