forked from open-telemetry/opentelemetry-collector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
oidc_authenticator.go
234 lines (196 loc) · 6.38 KB
/
oidc_authenticator.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
// Copyright The OpenTelemetry 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 authenticationprocessor
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
"strings"
"time"
"github.com/coreos/go-oidc"
"go.opentelemetry.io/collector/component"
"go.uber.org/zap"
"google.golang.org/grpc/metadata"
)
type subject struct{}
type groups struct{}
type oidcAuthenticator struct {
config OIDC
logger *zap.Logger
provider *oidc.Provider
verifier *oidc.IDTokenVerifier
}
var (
_ authenticator = (*oidcAuthenticator)(nil)
// Subject is the context key holding the Subject from this request
Subject = subject{}
// Groups is the context key holding the groups the subject from this request belongs to
Groups = groups{}
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")
)
func newOIDCAuthenticator(logger *zap.Logger, config OIDC) *oidcAuthenticator {
return &oidcAuthenticator{
logger: logger.With(zap.String("authenticator", "oidc")),
config: config,
}
}
func (o *oidcAuthenticator) authenticate(ctx context.Context) (bool, error) {
// TODO: check also if we can get the HTTP headers, in case the gRPC one yields no token
md, _ := metadata.FromIncomingContext(ctx)
headers := md.Get("authorization")
o.logger.Debug("received trace")
authenticated := false
for _, header := range headers {
parts := strings.Split(header, " ")
if len(parts) != 2 {
return false, errInvalidAuthenticationHeaderFormat
}
idToken, err := o.verifier.Verify(ctx, parts[1])
if err != nil {
o.logger.Debug("failed to verify token", zap.Error(err))
return false, err
}
claims := map[string]interface{}{}
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
// swalling the error, it's better to make this future-proof, in case the underlying
// code changes
return false, errFailedToObtainClaimsFromToken
}
subject, err := getSubjectFromClaims(claims, o.config.UsernameClaim, idToken.Subject)
if err != nil {
return false, err
}
ctx = context.WithValue(ctx, Subject, subject)
groups, err := getGroupsFromClaims(claims, o.config.GroupsClaim)
if err != nil {
return false, err
}
ctx = context.WithValue(ctx, Groups, groups)
o.logger.Debug("authentication succeeded for batch")
authenticated = true
}
return authenticated, nil
}
func (o *oidcAuthenticator) start(context.Context, component.Host) error {
provider, err := getProviderForConfig(o.config)
if err != nil {
return err
}
o.provider = provider
o.verifier = o.provider.Verifier(&oidc.Config{
ClientID: o.config.Audience,
})
return nil
}
func (o *oidcAuthenticator) shutdown(context.Context) error {
return nil
}
func getSubjectFromClaims(claims map[string]interface{}, 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]interface{}, 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 []interface{}:
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 getProviderForConfig(config OIDC) (*oidc.Provider, error) {
t := &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 nil, err // the errors from this path have enough context already
}
if cert != nil {
t.TLSClientConfig = &tls.Config{
RootCAs: x509.NewCertPool(),
}
t.TLSClientConfig.RootCAs.AddCert(cert)
}
client := &http.Client{
Timeout: 5 * time.Second,
Transport: t,
}
oidcContext := oidc.ClientContext(context.Background(), client)
return oidc.NewProvider(oidcContext, config.IssuerURL)
}
func getIssuerCACertFromPath(path string) (*x509.Certificate, error) {
if path == "" {
return nil, nil
}
rawCA, err := ioutil.ReadFile(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)
}