-
Notifications
You must be signed in to change notification settings - Fork 8
/
teleport.go
289 lines (250 loc) · 8.6 KB
/
teleport.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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package teleport
import (
"context"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"net/url"
"os"
"os/exec"
"time"
"github.com/gravitational/teleport/api/profile"
"google.golang.org/protobuf/proto"
"k8s.io/apimachinery/pkg/runtime"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
"namespacelabs.dev/foundation/internal/artifacts/oci"
"namespacelabs.dev/foundation/internal/build/registry"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/internal/runtime/kubernetes/client"
"namespacelabs.dev/foundation/std/cfg"
"namespacelabs.dev/foundation/universe/teleport/configuration"
)
const (
tshBin = "tsh"
tbotBin = "tbot"
appLoginTTLMins = "720" // 12h
)
var (
loginMinValidityTTL = time.Minute * 10
teleportConfigType = cfg.DefineConfigType[*configuration.Teleport]()
)
func Register() {
client.RegisterConfigurationProvider("teleport", provideCluster)
cfg.RegisterConfigurationProvider(func(conf *configuration.Configuration) ([]proto.Message, error) {
if conf.GetTeleport() == nil {
return nil, fnerrors.BadInputError("teleport configuration must be specified")
}
if conf.Registry == "" {
return nil, fnerrors.BadInputError("registry must be specified")
}
if conf.GetTeleport().GetEcrCredentialsProxyApp() != "" {
oci.RegisterDomainKeychain(registryHost(conf.Registry), ecrTeleportKeychain{conf: conf}, oci.Keychain_UseAlways)
}
regTransport, err := registryTransport(conf)
if err != nil {
return nil, err
}
messages := []proto.Message{
&client.HostEnv{Provider: "teleport"},
®istry.Registry{
Url: conf.Registry,
Transport: regTransport,
},
conf.Teleport,
}
return messages, nil
})
}
func provideCluster(ctx context.Context, cfg cfg.Configuration) (client.ClusterConfiguration, error) {
conf, ok := teleportConfigType.CheckGet(cfg)
if !ok {
return client.ClusterConfiguration{}, fnerrors.InternalError("missing configuration")
}
switch {
case conf.GetUserProfile() != "":
if err := tshEnsureLogin(ctx, conf); err != nil {
return client.ClusterConfiguration{}, err
}
return teleportUserKubeconfig(ctx, conf)
case conf.GetKubeCertsDir() != "":
return teleportBotKubeconfig(ctx, conf)
default:
return client.ClusterConfiguration{}, fnerrors.BadInputError("either user_profile or kube_certs_dir must be set")
}
}
func teleportUserKubeconfig(ctx context.Context, conf *configuration.Teleport) (client.ClusterConfiguration, error) {
profile, err := profile.FromDir("", conf.GetUserProfile())
if err != nil {
return client.ClusterConfiguration{}, fnerrors.InternalError("failed to resolve teleport profile")
}
tshBinPath, err := exec.LookPath(tshBin)
if err != nil {
return client.ClusterConfiguration{}, fnerrors.InternalError("missing tsh binary")
}
caData, err := os.ReadFile(profile.TLSCAPathCluster(profile.SiteName))
if err != nil {
return client.ClusterConfiguration{}, fnerrors.InternalError("failed to read CA")
}
kubeClusterName := conf.GetKubeCluster()
contextName := fmt.Sprintf("%s-%s", profile.SiteName, kubeClusterName)
return client.ClusterConfiguration{
Config: clientcmdapi.Config{
Clusters: map[string]*clientcmdapi.Cluster{
kubeClusterName: {
Server: fmt.Sprintf("https://%s", profile.KubeProxyAddr),
TLSServerName: "kube-teleport-proxy-alpn." + profile.SiteName,
CertificateAuthorityData: caData,
},
},
Contexts: map[string]*clientcmdapi.Context{
contextName: {
Cluster: kubeClusterName,
Extensions: map[string]runtime.Object{
// We need to wrap the kubeName in quotes to make sure it is parsed as a string.
"teleport.kube.name": &runtime.Unknown{Raw: []byte(fmt.Sprintf("%q", kubeClusterName))},
},
AuthInfo: contextName,
},
},
CurrentContext: contextName,
AuthInfos: map[string]*clientcmdapi.AuthInfo{
contextName: {
Exec: &clientcmdapi.ExecConfig{
APIVersion: "client.authentication.k8s.io/v1beta1",
Command: tshBinPath,
Args: []string{
"kube", "credentials", "--kube-cluster", conf.GetKubeCluster(),
"--teleport-cluster", profile.SiteName, "--proxy", profile.KubeProxyAddr,
},
InteractiveMode: clientcmdapi.NeverExecInteractiveMode,
},
},
},
},
}, nil
}
func teleportBotKubeconfig(ctx context.Context, conf *configuration.Teleport) (client.ClusterConfiguration, error) {
if conf.GetProxyUrl() == "" {
return client.ClusterConfiguration{}, fnerrors.InternalError("missing teleport proxy_url configuration")
}
tbotBinPath, err := exec.LookPath(tbotBin)
if err != nil {
return client.ClusterConfiguration{}, fnerrors.InternalError("missing tbot binary")
}
caFile := fmt.Sprintf("%s/teleport-host-ca.crt", conf.GetKubeCertsDir())
caData, err := os.ReadFile(caFile)
if err != nil {
return client.ClusterConfiguration{}, fnerrors.InternalError("failed to read CA")
}
ca, err := parseCertificate(ctx, caFile)
if err != nil {
return client.ClusterConfiguration{}, fnerrors.InternalError("failed to parse CA")
}
teleportCluster := ca.Subject.CommonName
kubeClusterName := conf.GetKubeCluster()
contextName := fmt.Sprintf("%s-%s", teleportCluster, kubeClusterName)
return client.ClusterConfiguration{
Config: clientcmdapi.Config{
Clusters: map[string]*clientcmdapi.Cluster{
kubeClusterName: {
Server: fmt.Sprintf("https://%s", conf.GetProxyUrl()),
TLSServerName: "kube-teleport-proxy-alpn." + teleportCluster,
CertificateAuthorityData: caData,
},
},
Contexts: map[string]*clientcmdapi.Context{
contextName: {
Cluster: kubeClusterName,
Extensions: map[string]runtime.Object{
// We need to wrap the kubeName in quotes to make sure it is parsed as a string.
"teleport.kube.name": &runtime.Unknown{Raw: []byte(fmt.Sprintf("%q", kubeClusterName))},
},
AuthInfo: contextName,
},
},
CurrentContext: contextName,
AuthInfos: map[string]*clientcmdapi.AuthInfo{
contextName: {
Exec: &clientcmdapi.ExecConfig{
APIVersion: "client.authentication.k8s.io/v1beta1",
Command: tbotBinPath,
Args: []string{
"kube", "credentials",
"--destination-dir", conf.GetKubeCertsDir(),
},
InteractiveMode: clientcmdapi.NeverExecInteractiveMode,
},
},
},
},
}, nil
}
func tshEnsureLogin(ctx context.Context, conf *configuration.Teleport) error {
profile, err := profile.FromDir("", conf.GetUserProfile())
if err != nil {
return fnerrors.InternalError("failed to resolve teleport profile")
}
cert, err := parseCertificate(ctx, profile.TLSCertPath())
if err != nil {
return fnerrors.InternalError("failed to load user's certificate")
}
if time.Until(cert.NotAfter) < loginMinValidityTTL {
usage := fmt.Sprintf("Login with 'tsh login --proxy=%s --user=%s %s'",
profile.WebProxyAddr, profile.Username, profile.SiteName,
)
return fnerrors.UsageError(usage, "Teleport credentials have expired or expire soon.")
}
var appsLogin []string
if app := conf.GetRegistryApp(); app != "" {
appsLogin = append(appsLogin, app)
}
if app := conf.GetEcrCredentialsProxyApp(); app != "" {
appsLogin = append(appsLogin, app)
}
for _, app := range appsLogin {
if err := tshAppsLogin(ctx, app, profile.AppCertPath(app)); err != nil {
return fnerrors.InvocationError("tsh", "failed to login to app %q", app)
}
}
return nil
}
func parseCertificate(ctx context.Context, certPath string) (*x509.Certificate, error) {
b, err := os.ReadFile(certPath)
if err != nil {
return nil, err
}
certData, _ := pem.Decode(b)
if certData == nil {
return nil, errors.New("not a pem formatted certificate")
}
return x509.ParseCertificate(certData.Bytes)
}
func registryHost(registry string) string {
rHost := registry
if u, _ := url.Parse(registry); u != nil && u.Host != "" {
rHost = u.Host
}
return rHost
}
func registryTransport(conf *configuration.Configuration) (*registry.RegistryTransport, error) {
registryApp := conf.GetTeleport().GetRegistryApp()
// If Teleport Registry App is not configured, then no need for custom transport as we access directly registry.
appCreds, err := resolveTeleportAppCreds(conf.GetTeleport(), registryApp)
if err != nil {
return nil, err
}
if appCreds == nil {
return nil, nil
}
return ®istry.RegistryTransport{
Tls: ®istry.RegistryTransport_TLS{
Endpoint: appCreds.endpoint,
Cert: appCreds.certFile,
Key: appCreds.keyFile,
},
}, nil
}