-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathbearertokenauth.go
More file actions
262 lines (227 loc) · 8.03 KB
/
bearertokenauth.go
File metadata and controls
262 lines (227 loc) · 8.03 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
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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package bearertokenauthextension // import "github.com/open-telemetry/opentelemetry-collector-contrib/extension/bearertokenauthextension"
import (
"context"
"crypto/subtle"
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"sync/atomic"
"github.com/fsnotify/fsnotify"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/extension"
"go.opentelemetry.io/collector/extension/extensionauth"
"go.uber.org/zap"
"google.golang.org/grpc/credentials"
)
var _ credentials.PerRPCCredentials = (*perRPCAuth)(nil)
// PerRPCAuth is a gRPC credentials.PerRPCCredentials implementation that returns an 'authorization' header.
type perRPCAuth struct {
auth *bearerTokenAuth
}
// GetRequestMetadata returns the request metadata to be used with the RPC.
func (c *perRPCAuth) GetRequestMetadata(context.Context, ...string) (map[string]string, error) {
return map[string]string{strings.ToLower(c.auth.header): c.auth.authorizationValue()}, nil
}
// RequireTransportSecurity always returns true for this implementation. Passing bearer tokens in plain-text connections is a bad idea.
func (*perRPCAuth) RequireTransportSecurity() bool {
return true
}
var (
_ extension.Extension = (*bearerTokenAuth)(nil)
_ extensionauth.Server = (*bearerTokenAuth)(nil)
_ extensionauth.HTTPClient = (*bearerTokenAuth)(nil)
_ extensionauth.GRPCClient = (*bearerTokenAuth)(nil)
)
// BearerTokenAuth is an implementation of extensionauth interfaces. It embeds a static authorization "bearer" token in every rpc call.
type bearerTokenAuth struct {
header string
scheme string
authorizationValuesAtomic atomic.Value
shutdownCH chan struct{}
filename string
logger *zap.Logger
}
func newBearerTokenAuth(cfg *Config, logger *zap.Logger) *bearerTokenAuth {
if cfg.Filename != "" && (cfg.BearerToken != "" || len(cfg.Tokens) > 0) {
logger.Warn("a filename is specified. Configured token(s) is ignored!")
}
a := &bearerTokenAuth{
header: cfg.Header,
scheme: cfg.Scheme,
filename: cfg.Filename,
logger: logger,
}
switch {
case len(cfg.Tokens) > 0:
tokens := make([]string, len(cfg.Tokens))
for i, token := range cfg.Tokens {
tokens[i] = string(token)
}
a.setAuthorizationValues(tokens) // Store tokens
case cfg.BearerToken != "":
a.setAuthorizationValues([]string{string(cfg.BearerToken)}) // Store token
case cfg.Filename != "":
a.refreshToken() // Load tokens from file
}
return a
}
// Start of BearerTokenAuth does nothing and returns nil if no filename
// is specified. Otherwise a routine is started to monitor the file containing
// the token to be transferred.
func (b *bearerTokenAuth) Start(ctx context.Context, _ component.Host) error {
if b.filename == "" {
return nil
}
if b.shutdownCH != nil {
return errors.New("bearerToken file monitoring is already running")
}
// Read file once
b.refreshToken()
b.shutdownCH = make(chan struct{})
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
// start file watcher
go b.startWatcher(ctx, watcher)
// Watch the parent directory instead of the file directly to handle atomic replacements
// This eliminates race conditions with fsnotify when files are atomically replaced
watchDir := filepath.Dir(b.filename)
return watcher.Add(watchDir)
}
func (b *bearerTokenAuth) startWatcher(ctx context.Context, watcher *fsnotify.Watcher) {
defer watcher.Close()
for {
select {
case _, ok := <-b.shutdownCH:
_ = ok
return
case <-ctx.Done():
return
case event, ok := <-watcher.Events:
if !ok {
continue
}
// Only process events for our target file by filtering events
// Since we're watching the parent directory, we get events for all files in it
if event.Name != b.filename {
continue
}
// Handle file events for our target file
// Since we're watching the directory, we don't need to manage watch add/remove
// The directory watch persists even when files are atomically replaced
if event.Op&fsnotify.Write == fsnotify.Write ||
event.Op&fsnotify.Create == fsnotify.Create ||
event.Op&fsnotify.Remove == fsnotify.Remove ||
event.Op&fsnotify.Chmod == fsnotify.Chmod {
b.refreshToken()
}
}
}
}
// Reloads token from file
func (b *bearerTokenAuth) refreshToken() {
b.logger.Info("refresh token", zap.String("filename", b.filename))
tokenData, err := os.ReadFile(b.filename)
if err != nil {
b.logger.Error(err.Error())
return
}
tokens := strings.Split(string(tokenData), "\n")
for i, token := range tokens {
tokens[i] = strings.TrimSpace(token)
}
b.setAuthorizationValues(tokens) // Stores new tokens
}
func (b *bearerTokenAuth) setAuthorizationValues(tokens []string) {
values := make([]string, len(tokens))
for i, token := range tokens {
if b.scheme != "" {
values[i] = b.scheme + " " + token
} else {
values[i] = token
}
}
b.authorizationValuesAtomic.Store(values)
}
// authorizationValues returns the Authorization header/metadata values
// to set for client auth, and expected values for server auth.
func (b *bearerTokenAuth) authorizationValues() []string {
return b.authorizationValuesAtomic.Load().([]string)
}
// authorizationValue returns the first Authorization header/metadata value
// to set for client auth, and expected value for server auth.
func (b *bearerTokenAuth) authorizationValue() string {
values := b.authorizationValues()
if len(values) > 0 {
return values[0] // Return the first token
}
return ""
}
// Shutdown of BearerTokenAuth does nothing and returns nil
func (b *bearerTokenAuth) Shutdown(_ context.Context) error {
if b.filename == "" {
return nil
}
if b.shutdownCH == nil {
return errors.New("bearerToken file monitoring is not running")
}
b.shutdownCH <- struct{}{}
close(b.shutdownCH)
b.shutdownCH = nil
return nil
}
// PerRPCCredentials returns PerRPCAuth an implementation of credentials.PerRPCCredentials that
func (b *bearerTokenAuth) PerRPCCredentials() (credentials.PerRPCCredentials, error) {
return &perRPCAuth{
auth: b,
}, nil
}
// RoundTripper is not implemented by BearerTokenAuth
func (b *bearerTokenAuth) RoundTripper(base http.RoundTripper) (http.RoundTripper, error) {
return &bearerAuthRoundTripper{
header: b.header,
baseTransport: base,
auth: b,
}, nil
}
// Authenticate checks whether the given context contains valid auth data. Validates tokens from clients trying to access the service (incoming requests)
func (b *bearerTokenAuth) Authenticate(ctx context.Context, headers map[string][]string) (context.Context, error) {
// Use canonical header key to match how Go's HTTP server stores headers
auth, ok := headers[http.CanonicalHeaderKey(b.header)]
// Also check lower-case header key to support gRPC metadata format
if !ok {
auth, ok = headers[strings.ToLower(b.header)]
}
if !ok || len(auth) == 0 {
return ctx, fmt.Errorf("missing or empty authorization header: %s", b.header)
}
token := auth[0] // Extract token from authorization header
expectedTokens := b.authorizationValues()
for _, expectedToken := range expectedTokens {
if subtle.ConstantTimeCompare([]byte(expectedToken), []byte(token)) == 1 {
return ctx, nil // Authentication successful, token is valid
}
}
return ctx, errors.New("provided authorization does not match expected scheme or token") // Token is invalid
}
// BearerAuthRoundTripper intercepts and adds Bearer token Authorization headers to each http request.
type bearerAuthRoundTripper struct {
header string
baseTransport http.RoundTripper
auth *bearerTokenAuth
}
// RoundTrip modifies the original request and adds Bearer token Authorization headers. Incoming requests support multiple tokens, but outgoing requests only use one.
func (interceptor *bearerAuthRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
req2 := req.Clone(req.Context())
if req2.Header == nil {
req2.Header = make(http.Header)
}
req2.Header.Set(interceptor.header, interceptor.auth.authorizationValue())
return interceptor.baseTransport.RoundTrip(req2)
}