forked from fluxcd/pkg
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaccess_token.go
More file actions
204 lines (165 loc) · 6.24 KB
/
Copy pathaccess_token.go
File metadata and controls
204 lines (165 loc) · 6.24 KB
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
/*
Copyright 2025 The Flux authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package auth
import (
"context"
"fmt"
"strings"
authnv1 "k8s.io/api/authentication/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/fluxcd/pkg/cache"
)
// GetAccessToken returns an access token for accessing resources in the given cloud provider.
func GetAccessToken(ctx context.Context, provider Provider, opts ...Option) (Token, error) {
var o Options
o.Apply(opts...)
// Initialize access token fetcher for controller.
newAccessToken := func() (Token, error) {
token, err := provider.NewControllerToken(ctx, opts...)
if err != nil {
return nil, fmt.Errorf("failed to create provider access token for the controller: %w", err)
}
return token, nil
}
// Update access token fetcher for a service account if specified.
var serviceAccount *corev1.ServiceAccount
var providerIdentity string
var audiences []string
if o.ShouldGetServiceAccountToken() {
// Fetch service account details.
var err error
saRef := client.ObjectKey{
Name: o.ServiceAccountName,
Namespace: o.ServiceAccountNamespace,
}
serviceAccount, audiences, providerIdentity, err =
getServiceAccountAndProviderInfo(ctx, provider, o.Client, saRef, opts...)
if err != nil {
return nil, err
}
// Update the function to create an access token using the service account.
newAccessToken = func() (Token, error) {
// Check the feature gate for object-level workload identity.
if !IsObjectLevelWorkloadIdentityEnabled() {
return nil, ErrObjectLevelWorkloadIdentityNotEnabled
}
// Issue Kubernetes OIDC token for the service account.
tokenReq := &authnv1.TokenRequest{
Spec: authnv1.TokenRequestSpec{
Audiences: audiences,
},
}
if err := o.Client.SubResource("token").Create(ctx, serviceAccount, tokenReq); err != nil {
return nil, fmt.Errorf("failed to create kubernetes token for service account '%s/%s': %w",
serviceAccount.Namespace, serviceAccount.Name, err)
}
oidcToken := tokenReq.Status.Token
// Exchange the Kubernetes OIDC token for a provider access token.
token, err := provider.NewTokenForServiceAccount(ctx, oidcToken, *serviceAccount, opts...)
if err != nil {
return nil, fmt.Errorf("failed to create provider access token for service account '%s/%s': %w",
serviceAccount.Namespace, serviceAccount.Name, err)
}
return token, nil
}
}
// Bail out early if cache is disabled.
if o.Cache == nil {
return newAccessToken()
}
// Build cache key.
cacheKey := buildAccessTokenCacheKey(provider, audiences, providerIdentity, serviceAccount, opts...)
// Build involved object details.
kind := o.InvolvedObject.Kind
name := o.InvolvedObject.Name
namespace := o.InvolvedObject.Namespace
operation := o.InvolvedObject.Operation
// Get token from cache.
token, _, err := o.Cache.GetOrSet(ctx, cacheKey, func(ctx context.Context) (cache.Token, error) {
return newAccessToken()
}, cache.WithInvolvedObject(kind, name, namespace, operation))
if err != nil {
return nil, err
}
return token, nil
}
func getServiceAccountAndProviderInfo(ctx context.Context, provider Provider, client client.Client,
key client.ObjectKey, opts ...Option) (*corev1.ServiceAccount, []string, string, error) {
var o Options
o.Apply(opts...)
defaultSA := getDefaultServiceAccount()
var setDefaultSA bool
// Apply multi-tenancy lockdown: use default service account when .serviceAccountName
// is not explicitly specified in the object. This results in Object-Level Workload Identity.
if key.Name == "" && defaultSA != "" {
key.Name = defaultSA
setDefaultSA = true
}
// Get service account.
var serviceAccount corev1.ServiceAccount
if err := client.Get(ctx, key, &serviceAccount); err != nil {
if errors.IsNotFound(err) && setDefaultSA {
return nil, nil, "", fmt.Errorf("failed to get service account '%s': %w",
key, ErrDefaultServiceAccountNotFound)
}
return nil, nil, "", fmt.Errorf("failed to get service account '%s': %w",
key, err)
}
// Get provider audience.
audiences := o.Audiences
if len(audiences) == 0 {
var err error
audiences, err = provider.GetAudiences(ctx, serviceAccount)
if err != nil {
return nil, nil, "", fmt.Errorf("failed to get provider audience: %w", err)
}
}
// Get provider identity.
providerIdentity, err := provider.GetIdentity(serviceAccount)
if err != nil {
return nil, nil, "", fmt.Errorf("failed to get provider identity from service account '%s/%s' annotations: %w",
key.Namespace, key.Name, err)
}
return &serviceAccount, audiences, providerIdentity, nil
}
func buildAccessTokenCacheKey(provider Provider, audiences []string, providerIdentity string,
serviceAccount *corev1.ServiceAccount, opts ...Option) string {
var o Options
o.Apply(opts...)
var parts []string
parts = append(parts, fmt.Sprintf("provider=%s", provider.GetName()))
if serviceAccount != nil {
parts = append(parts, fmt.Sprintf("providerIdentity=%s", providerIdentity))
parts = append(parts, fmt.Sprintf("serviceAccountName=%s", serviceAccount.Name))
parts = append(parts, fmt.Sprintf("serviceAccountNamespace=%s", serviceAccount.Namespace))
parts = append(parts, fmt.Sprintf("serviceAccountTokenAudiences=%s", strings.Join(audiences, ",")))
}
if len(o.Scopes) > 0 {
parts = append(parts, fmt.Sprintf("scopes=%s", strings.Join(o.Scopes, ",")))
}
if o.STSRegion != "" {
parts = append(parts, fmt.Sprintf("stsRegion=%s", o.STSRegion))
}
if o.STSEndpoint != "" {
parts = append(parts, fmt.Sprintf("stsEndpoint=%s", o.STSEndpoint))
}
if o.ProxyURL != nil {
parts = append(parts, fmt.Sprintf("proxyURL=%s", o.ProxyURL))
}
if o.CAData != "" {
parts = append(parts, fmt.Sprintf("caData=%s", o.CAData))
}
return buildCacheKey(parts...)
}