/
generic_authenticator.go
354 lines (298 loc) · 10.7 KB
/
generic_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
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
// Copyright 2022 Dimitrij Drus <dadrus@gmx.de>
//
// 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.
//
// SPDX-License-Identifier: Apache-2.0
package authenticators
import (
"crypto/sha256"
"encoding/hex"
"errors"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/rs/zerolog"
"github.com/dadrus/heimdall/internal/cache"
"github.com/dadrus/heimdall/internal/heimdall"
"github.com/dadrus/heimdall/internal/rules/endpoint"
"github.com/dadrus/heimdall/internal/rules/mechanisms/authenticators/extractors"
"github.com/dadrus/heimdall/internal/rules/mechanisms/subject"
"github.com/dadrus/heimdall/internal/rules/mechanisms/template"
"github.com/dadrus/heimdall/internal/x"
"github.com/dadrus/heimdall/internal/x/errorchain"
"github.com/dadrus/heimdall/internal/x/stringx"
)
// by intention. Used only during application bootstrap
//
//nolint:gochecknoinits
func init() {
registerTypeFactory(
func(id string, typ string, conf map[string]any) (bool, Authenticator, error) {
if typ != AuthenticatorGeneric {
return false, nil, nil
}
auth, err := newGenericAuthenticator(id, conf)
return true, auth, err
})
}
type genericAuthenticator struct {
id string
e endpoint.Endpoint
ads extractors.AuthDataExtractStrategy
payload template.Template
fwdHeaders []string
fwdCookies []string
sf SubjectFactory
ttl time.Duration
sessionLifespanConf *SessionLifespanConfig
allowFallbackOnError bool
}
func newGenericAuthenticator(id string, rawConfig map[string]any) (*genericAuthenticator, error) {
type Config struct {
Endpoint endpoint.Endpoint `mapstructure:"identity_info_endpoint" validate:"required"` //nolint:lll
SubjectInfo SubjectInfo `mapstructure:"subject" validate:"required"` //nolint:lll
AuthDataSource extractors.CompositeExtractStrategy `mapstructure:"authentication_data_source" validate:"required"` //nolint:lll
ForwardHeaders []string `mapstructure:"forward_headers"`
ForwardCookies []string `mapstructure:"forward_cookies"`
Payload template.Template `mapstructure:"payload"`
SessionLifespanConfig *SessionLifespanConfig `mapstructure:"session_lifespan"`
CacheTTL *time.Duration `mapstructure:"cache_ttl"`
AllowFallbackOnError bool `mapstructure:"allow_fallback_on_error"`
}
var conf Config
if err := decodeConfig(AuthenticatorGeneric, rawConfig, &conf); err != nil {
return nil, err
}
return &genericAuthenticator{
id: id,
e: conf.Endpoint,
ads: conf.AuthDataSource,
payload: conf.Payload,
fwdHeaders: conf.ForwardHeaders,
fwdCookies: conf.ForwardCookies,
sf: &conf.SubjectInfo,
ttl: x.IfThenElseExec(conf.CacheTTL != nil,
func() time.Duration { return *conf.CacheTTL },
func() time.Duration { return 0 }),
allowFallbackOnError: conf.AllowFallbackOnError,
sessionLifespanConf: conf.SessionLifespanConfig,
}, nil
}
func (a *genericAuthenticator) Execute(ctx heimdall.Context) (*subject.Subject, error) {
logger := zerolog.Ctx(ctx.AppContext())
logger.Debug().Str("_id", a.id).Msg("Authenticating using generic authenticator")
authData, err := a.ads.GetAuthData(ctx)
if err != nil {
return nil, errorchain.
NewWithMessage(heimdall.ErrAuthentication, "failed to get authentication data from request").
WithErrorContext(a).
CausedBy(err)
}
payload, err := a.getSubjectInformation(ctx, authData)
if err != nil {
return nil, err
}
sub, err := a.sf.CreateSubject(payload)
if err != nil {
return nil, errorchain.
NewWithMessage(heimdall.ErrInternal, "failed to extract subject information from response").
WithErrorContext(a).
CausedBy(err)
}
return sub, nil
}
func (a *genericAuthenticator) WithConfig(config map[string]any) (Authenticator, error) {
// this authenticator allows ttl to be redefined on the rule level
if len(config) == 0 {
return a, nil
}
type Config struct {
CacheTTL *time.Duration `mapstructure:"cache_ttl"`
AllowFallbackOnError *bool `mapstructure:"allow_fallback_on_error"`
}
var conf Config
if err := decodeConfig(AuthenticatorGeneric, config, &conf); err != nil {
return nil, err
}
return &genericAuthenticator{
id: a.id,
e: a.e,
sf: a.sf,
ads: a.ads,
payload: a.payload,
fwdHeaders: a.fwdHeaders,
fwdCookies: a.fwdCookies,
ttl: x.IfThenElseExec(conf.CacheTTL != nil,
func() time.Duration { return *conf.CacheTTL },
func() time.Duration { return a.ttl }),
allowFallbackOnError: x.IfThenElseExec(conf.AllowFallbackOnError != nil,
func() bool { return *conf.AllowFallbackOnError },
func() bool { return a.allowFallbackOnError }),
sessionLifespanConf: a.sessionLifespanConf,
}, nil
}
func (a *genericAuthenticator) IsFallbackOnErrorAllowed() bool {
return a.allowFallbackOnError
}
func (a *genericAuthenticator) ID() string {
return a.id
}
func (a *genericAuthenticator) getSubjectInformation(ctx heimdall.Context, authData string) ([]byte, error) {
logger := zerolog.Ctx(ctx.AppContext())
cch := cache.Ctx(ctx.AppContext())
var (
cacheKey string
session *SessionLifespan
)
if a.ttl > 0 {
cacheKey = a.calculateCacheKey(authData)
if entry, err := cch.Get(ctx.AppContext(), cacheKey); err == nil {
logger.Debug().Msg("Reusing subject information from cache")
return entry, nil
}
}
payload, err := a.fetchSubjectInformation(ctx, authData)
if err != nil {
return nil, err
}
if a.sessionLifespanConf != nil {
session, err = a.sessionLifespanConf.CreateSessionLifespan(payload)
if err != nil {
return nil, errorchain.New(heimdall.ErrInternal).WithErrorContext(a).CausedBy(err)
}
if session != nil {
if err = session.Assert(); err != nil {
return nil, errorchain.New(heimdall.ErrAuthentication).WithErrorContext(a).CausedBy(err)
}
}
}
if cacheTTL := a.getCacheTTL(session); cacheTTL > 0 {
if err = cch.Set(ctx.AppContext(), cacheKey, payload, cacheTTL); err != nil {
logger.Warn().Err(err).Msg("Failed to cache subject information")
}
}
return payload, nil
}
func (a *genericAuthenticator) fetchSubjectInformation(ctx heimdall.Context, authData string) ([]byte, error) {
req, err := a.createRequest(ctx, authData)
if err != nil {
return nil, err
}
resp, err := a.e.CreateClient(req.URL.Hostname()).Do(req)
if err != nil {
var clientErr *url.Error
if errors.As(err, &clientErr) && clientErr.Timeout() {
return nil, errorchain.
NewWithMessage(heimdall.ErrCommunicationTimeout,
"request to the endpoint to get information about the user timed out").
WithErrorContext(a).
CausedBy(err)
}
return nil, errorchain.
NewWithMessage(heimdall.ErrCommunication,
"request to the endpoint to get information about the user failed").
WithErrorContext(a).
CausedBy(err)
}
defer resp.Body.Close()
return a.readResponse(resp)
}
func (a *genericAuthenticator) createRequest(ctx heimdall.Context, authData string) (*http.Request, error) {
logger := zerolog.Ctx(ctx.AppContext())
var body io.Reader
templateData := map[string]any{
"AuthenticationData": authData,
}
if a.payload != nil {
value, err := a.payload.Render(templateData)
if err != nil {
return nil, errorchain.NewWithMessage(heimdall.ErrInternal,
"failed to render payload for the authenticator endpoint").
WithErrorContext(a).CausedBy(err)
}
body = strings.NewReader(value)
}
req, err := a.e.CreateRequest(ctx.AppContext(), body,
endpoint.RenderFunc(func(value string) (string, error) {
tpl, err := template.New(value)
if err != nil {
return "", errorchain.NewWithMessage(heimdall.ErrInternal, "failed to create template").
WithErrorContext(a).
CausedBy(err)
}
return tpl.Render(templateData)
}))
if err != nil {
return nil, errorchain.
NewWithMessage(heimdall.ErrInternal, "failed creating request").
WithErrorContext(a).
CausedBy(err)
}
for _, headerName := range a.fwdHeaders {
headerValue := ctx.Request().Header(headerName)
if len(headerValue) == 0 {
logger.Warn().Str("_header", headerName).
Msg("Header not present in the request but configured to be forwarded")
} else {
req.Header.Add(headerName, headerValue)
}
}
for _, cookieName := range a.fwdCookies {
cookieValue := ctx.Request().Cookie(cookieName)
if len(cookieValue) == 0 {
logger.Warn().Str("_cookie", cookieName).
Msg("Cookie not present in the request but configured to be forwarded")
} else {
req.AddCookie(&http.Cookie{Name: cookieName, Value: cookieValue})
}
}
return req, nil
}
func (a *genericAuthenticator) readResponse(resp *http.Response) ([]byte, error) {
if !(resp.StatusCode >= http.StatusOK && resp.StatusCode < http.StatusMultipleChoices) {
return nil, errorchain.NewWithMessagef(heimdall.ErrCommunication,
"unexpected response code: %v", resp.StatusCode).WithErrorContext(a)
}
rawData, err := io.ReadAll(resp.Body)
if err != nil {
return nil, errorchain.NewWithMessage(heimdall.ErrInternal, "failed to read response").
WithErrorContext(a).
CausedBy(err)
}
return rawData, nil
}
func (a *genericAuthenticator) getCacheTTL(sessionLifespan *SessionLifespan) time.Duration {
// timeLeeway defines the default time deviation to ensure the session is still valid
// when used from cache
const timeLeeway = 10
if a.ttl <= 0 {
return 0
}
// we cache using the settings in the configured ttl.
// It is however ensured, that this ttl does not exceed the ttl of the session itself
// (if this information is available)
if sessionLifespan != nil && !sessionLifespan.exp.Equal(time.Time{}) {
expiresIn := sessionLifespan.exp.Unix() - time.Now().Unix() - timeLeeway
expirationTTL := x.IfThenElse(expiresIn > 0, time.Duration(expiresIn)*time.Second, 0)
return min(a.ttl, expirationTTL)
}
return a.ttl
}
func (a *genericAuthenticator) calculateCacheKey(reference string) string {
digest := sha256.New()
digest.Write(a.e.Hash())
digest.Write(stringx.ToBytes(reference))
return hex.EncodeToString(digest.Sum(nil))
}