-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
extension.go
248 lines (206 loc) · 6.27 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
244
245
246
247
248
// 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 basicauthextension // import "github.com/open-telemetry/opentelemetry-collector-contrib/extension/basicauthextension"
import (
"context"
"encoding/base64"
"errors"
"fmt"
"io"
"net/http"
"os"
"strings"
"github.com/tg123/go-htpasswd"
"go.opentelemetry.io/collector/client"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/config/configauth"
creds "google.golang.org/grpc/credentials"
)
var (
errNoAuth = errors.New("no basic auth provided")
errInvalidCredentials = errors.New("invalid credentials")
errInvalidSchemePrefix = errors.New("invalid authorization scheme prefix")
errInvalidFormat = errors.New("invalid authorization format")
)
type basicAuth struct {
htpasswd *HtpasswdSettings
clientAuth *ClientAuthSettings
matchFunc func(username, password string) bool
}
func newClientAuthExtension(cfg *Config) (configauth.ClientAuthenticator, error) {
if cfg.ClientAuth == nil || cfg.ClientAuth.Username == "" {
return nil, errNoCredentialSource
}
ba := basicAuth{
clientAuth: cfg.ClientAuth,
}
return configauth.NewClientAuthenticator(
configauth.WithClientRoundTripper(ba.roundTripper),
configauth.WithPerRPCCredentials(ba.perRPCCredentials),
), nil
}
func newServerAuthExtension(cfg *Config) (configauth.ServerAuthenticator, error) {
if cfg.Htpasswd == nil || (cfg.Htpasswd.File == "" && cfg.Htpasswd.Inline == "") {
return nil, errNoCredentialSource
}
ba := basicAuth{
htpasswd: cfg.Htpasswd,
}
return configauth.NewServerAuthenticator(
configauth.WithStart(ba.serverStart),
configauth.WithAuthenticate(ba.authenticate),
), nil
}
func (ba *basicAuth) serverStart(ctx context.Context, host component.Host) error {
var rs []io.Reader
if ba.htpasswd.File != "" {
f, err := os.Open(ba.htpasswd.File)
if err != nil {
return fmt.Errorf("open htpasswd file: %w", err)
}
defer f.Close()
rs = append(rs, f)
rs = append(rs, strings.NewReader("\n"))
}
// Ensure that the inline content is read the last.
// This way the inline content will override the content from file.
rs = append(rs, strings.NewReader(ba.htpasswd.Inline))
mr := io.MultiReader(rs...)
htp, err := htpasswd.NewFromReader(mr, htpasswd.DefaultSystems, nil)
if err != nil {
return fmt.Errorf("read htpasswd content: %w", err)
}
ba.matchFunc = htp.Match
return nil
}
func (ba *basicAuth) authenticate(ctx context.Context, headers map[string][]string) (context.Context, error) {
auth := getAuthHeader(headers)
if auth == "" {
return ctx, errNoAuth
}
authData, err := parseBasicAuth(auth)
if err != nil {
return ctx, err
}
if !ba.matchFunc(authData.username, authData.password) {
return ctx, errInvalidCredentials
}
cl := client.FromContext(ctx)
cl.Auth = authData
return client.NewContext(ctx, cl), nil
}
func getAuthHeader(h map[string][]string) string {
const (
canonicalHeaderKey = "Authorization"
metadataKey = "authorization"
)
authHeaders, ok := h[canonicalHeaderKey]
if !ok {
authHeaders, ok = h[metadataKey]
}
if !ok {
for k, v := range h {
if strings.EqualFold(k, metadataKey) {
authHeaders = v
break
}
}
}
if len(authHeaders) == 0 {
return ""
}
return authHeaders[0]
}
// See: https://github.com/golang/go/blob/1a8b4e05b1ff7a52c6d40fad73bcad612168d094/src/net/http/request.go#L950
func parseBasicAuth(auth string) (*authData, error) {
const prefix = "Basic "
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
return nil, errInvalidSchemePrefix
}
encoded := auth[len(prefix):]
decodedBytes, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
return nil, errInvalidFormat
}
decoded := string(decodedBytes)
si := strings.IndexByte(decoded, ':')
if si < 0 {
return nil, errInvalidFormat
}
return &authData{
username: decoded[:si],
password: decoded[si+1:],
raw: encoded,
}, nil
}
var _ client.AuthData = (*authData)(nil)
type authData struct {
username string
password string
raw string
}
func (a *authData) GetAttribute(name string) interface{} {
switch name {
case "username":
return a.username
case "raw":
return a.raw
default:
return nil
}
}
func (*authData) GetAttributeNames() []string {
return []string{"username", "raw"}
}
// perRPCAuth is a gRPC credentials.PerRPCCredentials implementation that returns an 'authorization' header.
type perRPCAuth struct {
metadata map[string]string
}
// GetRequestMetadata returns the request metadata to be used with the RPC.
func (p *perRPCAuth) GetRequestMetadata(context.Context, ...string) (map[string]string, error) {
return p.metadata, nil
}
// RequireTransportSecurity always returns true for this implementation.
func (p *perRPCAuth) RequireTransportSecurity() bool {
return true
}
type basicAuthRoundTripper struct {
base http.RoundTripper
authData *ClientAuthSettings
}
func (b *basicAuthRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) {
newRequest := request.Clone(request.Context())
newRequest.SetBasicAuth(b.authData.Username, b.authData.Password)
return b.base.RoundTrip(newRequest)
}
func (ba *basicAuth) roundTripper(base http.RoundTripper) (http.RoundTripper, error) {
if strings.Contains(ba.clientAuth.Username, ":") {
return nil, errInvalidFormat
}
return &basicAuthRoundTripper{
base: base,
authData: ba.clientAuth,
}, nil
}
func (ba *basicAuth) perRPCCredentials() (creds.PerRPCCredentials, error) {
if strings.Contains(ba.clientAuth.Username, ":") {
return nil, errInvalidFormat
}
encoded := base64.StdEncoding.EncodeToString([]byte(ba.clientAuth.Username + ":" + ba.clientAuth.Password))
return &perRPCAuth{
metadata: map[string]string{
"authorization": fmt.Sprintf("Basic %s", encoded),
},
}, nil
}