-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathextension.go
243 lines (208 loc) · 6.76 KB
/
extension.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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package oidcauthextension // import "github.com/open-telemetry/opentelemetry-collector-contrib/extension/oidcauthextension"
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/coreos/go-oidc/v3/oidc"
"go.opentelemetry.io/collector/client"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/extension"
"go.opentelemetry.io/collector/extension/extensionauth"
"go.uber.org/zap"
)
var (
_ extension.Extension = (*oidcExtension)(nil)
_ extensionauth.Server = (*oidcExtension)(nil)
)
type oidcExtension struct {
cfg *Config
provider *oidc.Provider
verifier *oidc.IDTokenVerifier
client *http.Client
logger *zap.Logger
transport *http.Transport
}
var (
errNoAudienceProvided = errors.New("no Audience provided for the OIDC configuration")
errNoIssuerURL = errors.New("no IssuerURL provided for the OIDC configuration")
errInvalidAuthenticationHeaderFormat = errors.New("invalid authorization header format")
errFailedToObtainClaimsFromToken = errors.New("failed to get the subject from the token issued by the OIDC provider")
errClaimNotFound = errors.New("username claim from the OIDC configuration not found on the token returned by the OIDC provider")
errUsernameNotString = errors.New("the username returned by the OIDC provider isn't a regular string")
errGroupsClaimNotFound = errors.New("groups claim from the OIDC configuration not found on the token returned by the OIDC provider")
errNotAuthenticated = errors.New("authentication didn't succeed")
)
func newExtension(cfg *Config, logger *zap.Logger) extension.Extension {
if cfg.Attribute == "" {
cfg.Attribute = defaultAttribute
}
return &oidcExtension{
cfg: cfg,
logger: logger,
}
}
func (e *oidcExtension) Start(ctx context.Context, _ component.Host) error {
err := e.setProviderConfig(ctx, e.cfg)
if err != nil {
return fmt.Errorf("failed to get configuration from the auth server: %w", err)
}
e.verifier = e.provider.Verifier(&oidc.Config{
ClientID: e.cfg.Audience,
SkipClientIDCheck: e.cfg.IgnoreAudience,
})
return nil
}
func (e *oidcExtension) Shutdown(context.Context) error {
if e.client != nil {
e.client.CloseIdleConnections()
}
if e.transport != nil {
e.transport.CloseIdleConnections()
}
return nil
}
// authenticate checks whether the given context contains valid auth data. Successfully authenticated calls will always return a nil error and a context with the auth data.
func (e *oidcExtension) Authenticate(ctx context.Context, headers map[string][]string) (context.Context, error) {
var authHeaders []string
for k, v := range headers {
if strings.EqualFold(k, e.cfg.Attribute) {
authHeaders = v
break
}
}
if len(authHeaders) == 0 {
return ctx, errNotAuthenticated
}
// we only use the first header, if multiple values exist
parts := strings.Split(authHeaders[0], " ")
if len(parts) != 2 {
return ctx, errInvalidAuthenticationHeaderFormat
}
raw := parts[1]
idToken, err := e.verifier.Verify(ctx, raw)
if err != nil {
return ctx, fmt.Errorf("failed to verify token: %w", err)
}
claims := map[string]any{}
if err = idToken.Claims(&claims); err != nil {
// currently, this isn't a valid condition, the Verify call a few lines above
// will already attempt to parse the payload as a json and set it as the claims
// for the token. As we are using a map to hold the claims, there's no way to fail
// to read the claims. It could fail if we were using a custom struct. Instead of
// swallowing the error, it's better to make this future-proof, in case the underlying
// code changes
return ctx, errFailedToObtainClaimsFromToken
}
subject, err := getSubjectFromClaims(claims, e.cfg.UsernameClaim, idToken.Subject)
if err != nil {
return ctx, fmt.Errorf("failed to get subject from claims in the token: %w", err)
}
membership, err := getGroupsFromClaims(claims, e.cfg.GroupsClaim)
if err != nil {
return ctx, fmt.Errorf("failed to get groups from claims in the token: %w", err)
}
cl := client.FromContext(ctx)
cl.Auth = &authData{
raw: raw,
subject: subject,
membership: membership,
}
return client.NewContext(ctx, cl), nil
}
func (e *oidcExtension) setProviderConfig(ctx context.Context, config *Config) error {
e.transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 5 * time.Second,
KeepAlive: 10 * time.Second,
DualStack: true,
}).DialContext,
ForceAttemptHTTP2: true,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 5 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
cert, err := getIssuerCACertFromPath(config.IssuerCAPath)
if err != nil {
return err // the errors from this path have enough context already
}
if cert != nil {
e.transport.TLSClientConfig = &tls.Config{
RootCAs: x509.NewCertPool(),
}
e.transport.TLSClientConfig.RootCAs.AddCert(cert)
}
e.client = &http.Client{
Timeout: 5 * time.Second,
Transport: e.transport,
}
oidcContext := oidc.ClientContext(ctx, e.client)
provider, err := oidc.NewProvider(oidcContext, config.IssuerURL)
e.provider = provider
return err
}
func getSubjectFromClaims(claims map[string]any, usernameClaim string, fallback string) (string, error) {
if len(usernameClaim) > 0 {
username, found := claims[usernameClaim]
if !found {
return "", errClaimNotFound
}
sUsername, ok := username.(string)
if !ok {
return "", errUsernameNotString
}
return sUsername, nil
}
return fallback, nil
}
func getGroupsFromClaims(claims map[string]any, groupsClaim string) ([]string, error) {
if len(groupsClaim) > 0 {
var groups []string
rawGroup, ok := claims[groupsClaim]
if !ok {
return nil, errGroupsClaimNotFound
}
switch v := rawGroup.(type) {
case string:
groups = append(groups, v)
case []string:
groups = v
case []any:
groups = make([]string, 0, len(v))
for i := range v {
groups = append(groups, fmt.Sprintf("%v", v[i]))
}
}
return groups, nil
}
return []string{}, nil
}
func getIssuerCACertFromPath(path string) (*x509.Certificate, error) {
if path == "" {
return nil, nil
}
rawCA, err := os.ReadFile(filepath.Clean(path))
if err != nil {
return nil, fmt.Errorf("could not read the CA file %q: %w", path, err)
}
if len(rawCA) == 0 {
return nil, fmt.Errorf("could not read the CA file %q: empty file", path)
}
block, _ := pem.Decode(rawCA)
if block == nil {
return nil, fmt.Errorf("cannot decode the contents of the CA file %q: %w", path, err)
}
return x509.ParseCertificate(block.Bytes)
}