-
Notifications
You must be signed in to change notification settings - Fork 151
/
auth.go
259 lines (208 loc) · 8.67 KB
/
auth.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
package auth
import (
"context"
"fmt"
"io"
"net/http"
"github.com/weaveworks/weave-gitops/pkg/services/auth/internal"
"github.com/go-git/go-git/v5/plumbing/transport/ssh"
"github.com/weaveworks/weave-gitops/pkg/flux"
"github.com/weaveworks/weave-gitops/pkg/git"
"github.com/weaveworks/weave-gitops/pkg/git/wrapper"
"github.com/weaveworks/weave-gitops/pkg/gitproviders"
"github.com/weaveworks/weave-gitops/pkg/logger"
"github.com/weaveworks/weave-gitops/pkg/services/automation"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/yaml"
)
// BlockingCLIAuthHandler takes over the terminal experience and returns a token when the user completes the flow.
type BlockingCLIAuthHandler func(context.Context, io.Writer) (string, error)
func NewAuthCLIHandler(name gitproviders.GitProviderName) (BlockingCLIAuthHandler, error) {
switch name {
case gitproviders.GitProviderGitHub:
return NewGithubDeviceFlowHandler(http.DefaultClient), nil
case gitproviders.GitProviderGitLab:
authFlow, err := NewGitlabAuthFlow(internal.GitlabRedirectUriCLI, http.DefaultClient)
if err != nil {
return nil, fmt.Errorf("could not create gitlab auth flow for CLI: %w", err)
}
return NewGitlabAuthFlowHandler(http.DefaultClient, authFlow), nil
}
return nil, fmt.Errorf("unsupported auth provider \"%s\"", name)
}
type SecretName struct {
Name automation.GeneratedSecretName
Namespace string
}
func (sn SecretName) String() string {
nn := types.NamespacedName{
Namespace: sn.Namespace,
Name: sn.Name.String(),
}
return nn.String()
}
func (sn SecretName) NamespacedName() types.NamespacedName {
return types.NamespacedName{
Namespace: sn.Namespace,
Name: sn.Name.String(),
}
}
type AuthService interface {
CreateGitClient(ctx context.Context, repoUrl gitproviders.RepoURL, targetName string, namespace string, dryRun bool) (git.Git, error)
GetGitProvider() gitproviders.GitProvider
}
type authSvc struct {
logger logger.Logger
fluxClient flux.Flux
// Note that this is a k8s go-client, NOT a wego kube.Kube interface.
// That interface wasn't providing any valuable abstraction for this service.
k8sClient client.Client
gitProvider gitproviders.GitProvider
}
// NewAuthService constructs an auth service for doing git operations with an authenticated client.
func NewAuthService(fluxClient flux.Flux, k8sClient client.Client, provider gitproviders.GitProvider, l logger.Logger) (AuthService, error) {
return &authSvc{
logger: l,
fluxClient: fluxClient,
k8sClient: k8sClient,
gitProvider: provider,
}, nil
}
// GetGitProvider returns the GitProvider associated with the AuthService instance
func (a *authSvc) GetGitProvider() gitproviders.GitProvider {
return a.gitProvider
}
// CreateGitClient creates a git.Git client instrumented with existing or generated deploy keys.
// This ensures that git operations are done with stored deploy keys instead of a user's local ssh-agent or equivalent.
func (a *authSvc) CreateGitClient(ctx context.Context, repoUrl gitproviders.RepoURL, targetName string, namespace string, dryRun bool) (git.Git, error) {
if dryRun {
d, _ := makePublicKey([]byte(""))
return git.New(d, wrapper.NewGoGit()), nil
}
secretName := SecretName{
Name: automation.CreateRepoSecretName(repoUrl),
Namespace: namespace,
}
pubKey, keyErr := a.setupDeployKey(ctx, secretName, targetName, repoUrl)
if keyErr != nil {
return nil, fmt.Errorf("error setting up deploy keys: %w", keyErr)
}
if pubKey == nil {
// Don't return git.New(pubkey, wrapper.NewGoGit()), nil here. It will fail
// "nil" of type *ssh.PublicKeys does not behave correctly
return git.New(nil, wrapper.NewGoGit()), nil
}
// Set the git client to use the existing deploy key.
return git.New(pubKey, wrapper.NewGoGit()), nil
}
// setupDeployKey creates a git.Git client instrumented with existing or generated deploy keys.
// This ensures that git operations are done with stored deploy keys instead of a user's local ssh-agent or equivalent.
func (a *authSvc) setupDeployKey(ctx context.Context, name SecretName, targetName string, repo gitproviders.RepoURL) (*ssh.PublicKeys, error) {
deployKeyExists, err := a.gitProvider.DeployKeyExists(ctx, repo)
if err != nil {
return nil, fmt.Errorf("failed check for existing deploy key: %w", err)
}
if deployKeyExists {
// The deploy key was found on the Git Provider, fetch it from the cluster.
secret, err := a.retrieveDeployKey(ctx, name)
if apierrors.IsNotFound(err) {
// Edge case where the deploy key exists on the Git Provider, but not on the cluster.
// Users might end up here if we uploaded the deploy key, but it failed to save on the cluster,
// or if a cluster was destroyed during development work.
// Create and upload a new deploy key.
a.logger.Warningf("A deploy key named %s was found on the git provider, but not in the cluster.", name.Name)
return a.provisionDeployKey(ctx, targetName, name, repo)
} else if err != nil {
return nil, fmt.Errorf("error retrieving deploy key: %w", err)
}
b := extractPrivateKey(secret)
pubKey, err := makePublicKey(b)
if err != nil {
return nil, fmt.Errorf("could not create public key from secret: %w", err)
}
// Set the git client to use the existing deploy key.
return pubKey, nil
}
return a.provisionDeployKey(ctx, targetName, name, repo)
}
func (a *authSvc) provisionDeployKey(ctx context.Context, targetName string, name SecretName, repo gitproviders.RepoURL) (*ssh.PublicKeys, error) {
deployKey, secret, err := a.generateDeployKey(targetName, name, repo)
if err != nil {
return nil, fmt.Errorf("error generating deploy key: %w", err)
}
publicKeyBytes := extractPublicKey(secret)
if err := a.gitProvider.UploadDeployKey(ctx, repo, publicKeyBytes); err != nil {
return nil, fmt.Errorf("error uploading deploy key: %w", err)
}
if err := a.storeDeployKey(ctx, secret); err != nil {
return nil, fmt.Errorf("error storing deploy key: %w", err)
}
a.logger.Println("Deploy key generated and uploaded to git provider")
return deployKey, nil
}
// Generates an ssh keypair for upload to the Git Provider and for use in a git.Git client.
func (a *authSvc) generateDeployKey(targetName string, secretName SecretName, repo gitproviders.RepoURL) (*ssh.PublicKeys, *corev1.Secret, error) {
secret, err := a.createKeyPairSecret(secretName, repo)
if err != nil {
return nil, nil, fmt.Errorf("could not create key-pair secret: %w", err)
}
privKeyBytes := extractPrivateKey(secret)
deployKey, err := makePublicKey(privKeyBytes)
if err != nil {
return nil, nil, fmt.Errorf("error creating new public keys: %w", err)
}
return deployKey, secret, nil
}
// Wrapper to abstract how the key is stored in case we want to change this later.
func (a *authSvc) storeDeployKey(ctx context.Context, secret *corev1.Secret) error {
if err := a.k8sClient.Create(ctx, secret); err != nil {
return fmt.Errorf("could not store secret: %w", err)
}
return nil
}
// Wrapper to abstract how a key is fetched.
func (a *authSvc) retrieveDeployKey(ctx context.Context, name SecretName) (*corev1.Secret, error) {
secret := &corev1.Secret{}
if err := a.k8sClient.Get(ctx, name.NamespacedName(), secret); err != nil {
return nil, fmt.Errorf("error getting deploy key secret: %w", err)
}
return secret, nil
}
// Uses flux to create a ssh key pair secret.
func (a *authSvc) createKeyPairSecret(name SecretName, repo gitproviders.RepoURL) (*corev1.Secret, error) {
secretData, err := a.fluxClient.CreateSecretGit(name.Name.String(), repo, name.Namespace)
if err != nil {
return nil, fmt.Errorf("could not create git secret: %w", err)
}
var secret corev1.Secret
err = yaml.Unmarshal(secretData, &secret)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal created secret: %w", err)
}
return &secret, nil
}
func makePublicKey(pemBytes []byte) (*ssh.PublicKeys, error) {
return ssh.NewPublicKeys("git", pemBytes, "")
}
// Helper to standardize how we extract data from a ssh key pair secret.
func extractSecretPart(secret *corev1.Secret, key string) []byte {
var data []byte
var ok bool
data, ok = secret.Data[string(key)]
if !ok {
// StringData is a write-only field, flux generates secrets on disk with StringData
// Once they get applied on the cluster, Kubernetes populates Data and removes StringData.
// Handle this case here to be able to extract data no matter the "state" of the object.
data = []byte(secret.StringData[string(key)])
}
return data
}
func extractPrivateKey(secret *corev1.Secret) []byte {
return extractSecretPart(secret, "identity")
}
func extractPublicKey(secret *corev1.Secret) []byte {
return extractSecretPart(secret, "identity.pub")
}