-
Notifications
You must be signed in to change notification settings - Fork 13
/
remote_authorizer.go
396 lines (328 loc) · 11.3 KB
/
remote_authorizer.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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
// 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 authorizers
import (
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"errors"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/goccy/go-json"
"github.com/google/cel-go/cel"
"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/cellib"
"github.com/dadrus/heimdall/internal/rules/mechanisms/contenttype"
"github.com/dadrus/heimdall/internal/rules/mechanisms/subject"
"github.com/dadrus/heimdall/internal/rules/mechanisms/template"
"github.com/dadrus/heimdall/internal/rules/mechanisms/values"
"github.com/dadrus/heimdall/internal/x"
"github.com/dadrus/heimdall/internal/x/errorchain"
"github.com/dadrus/heimdall/internal/x/stringx"
)
var errNoContent = errors.New("no payload received")
// by intention. Used only during application bootstrap
//
//nolint:gochecknoinits
func init() {
registerTypeFactory(
func(id string, typ string, conf map[string]any) (bool, Authorizer, error) {
if typ != AuthorizerRemote {
return false, nil, nil
}
auth, err := newRemoteAuthorizer(id, conf)
return true, auth, err
})
}
type remoteAuthorizer struct {
id string
e endpoint.Endpoint
payload template.Template
expressions compiledExpressions
headersForUpstream []string
ttl time.Duration
celEnv *cel.Env
v values.Values
}
type authorizationInformation struct {
Headers http.Header `json:"headers"`
Payload any `json:"payload"`
}
func (ai *authorizationInformation) addHeadersTo(headerNames []string, ctx heimdall.Context) {
for _, headerName := range headerNames {
headerValue := ai.Headers.Get(headerName)
if len(headerValue) != 0 {
ctx.AddHeaderForUpstream(headerName, headerValue)
}
}
}
func (ai *authorizationInformation) addAttributesTo(key string, sub *subject.Subject) {
if ai.Payload != nil {
sub.Attributes[key] = ai.Payload
}
}
func newRemoteAuthorizer(id string, rawConfig map[string]any) (*remoteAuthorizer, error) {
type Config struct {
Endpoint endpoint.Endpoint `mapstructure:"endpoint" validate:"required"` //nolint:lll
Expressions []Expression `mapstructure:"expressions" validate:"dive"`
Payload template.Template `mapstructure:"payload" validate:"required_without=Endpoint.Headers"` //nolint:lll
ResponseHeadersToForward []string `mapstructure:"forward_response_headers_to_upstream"`
CacheTTL time.Duration `mapstructure:"cache_ttl"`
Values values.Values `mapstructure:"values"`
}
var conf Config
if err := decodeConfig(AuthorizerRemote, rawConfig, &conf); err != nil {
return nil, err
}
env, err := cel.NewEnv(cellib.Library())
if err != nil {
return nil, errorchain.NewWithMessage(heimdall.ErrInternal, "failed creating CEL environment").
CausedBy(err)
}
expressions, err := compileExpressions(conf.Expressions, env)
if err != nil {
return nil, err
}
return &remoteAuthorizer{
id: id,
e: conf.Endpoint,
payload: conf.Payload,
expressions: expressions,
headersForUpstream: conf.ResponseHeadersToForward,
ttl: conf.CacheTTL,
celEnv: env,
v: conf.Values,
}, nil
}
func (a *remoteAuthorizer) Execute(ctx heimdall.Context, sub *subject.Subject) error {
logger := zerolog.Ctx(ctx.AppContext())
logger.Debug().Str("_id", a.id).Msg("Authorizing using remote authorizer")
if sub == nil {
return errorchain.NewWithMessage(heimdall.ErrInternal,
"failed to execute remote authorizer due to 'nil' subject").
WithErrorContext(a)
}
cch := cache.Ctx(ctx.AppContext())
var (
cacheKey string
authInfo *authorizationInformation
)
vals, payload, err := a.renderTemplates(ctx, sub)
if err != nil {
return err
}
if a.ttl > 0 {
cacheKey = a.calculateCacheKey(sub, vals, payload)
if entry, err := cch.Get(ctx.AppContext(), cacheKey); err == nil {
var ai authorizationInformation
if err = json.Unmarshal(entry, &ai); err == nil {
logger.Debug().Msg("Reusing authorization information from cache")
authInfo = &ai
}
}
}
if authInfo == nil {
authInfo, err = a.doAuthorize(ctx, sub, vals, payload)
if err != nil {
return err
}
if a.ttl > 0 && len(cacheKey) != 0 {
data, _ := json.Marshal(authInfo)
if err = cch.Set(ctx.AppContext(), cacheKey, data, a.ttl); err != nil {
logger.Warn().Err(err).Msg("Failed to cache authorization information")
}
}
}
authInfo.addHeadersTo(a.headersForUpstream, ctx)
authInfo.addAttributesTo(a.id, sub)
return nil
}
func (a *remoteAuthorizer) WithConfig(rawConfig map[string]any) (Authorizer, error) {
if len(rawConfig) == 0 {
return a, nil
}
type Config struct {
Payload template.Template `mapstructure:"payload"`
Expressions []Expression `mapstructure:"expressions" validate:"dive"`
ResponseHeadersToForward []string `mapstructure:"forward_response_headers_to_upstream"`
CacheTTL time.Duration `mapstructure:"cache_ttl"`
Values values.Values `mapstructure:"values"`
}
var conf Config
if err := decodeConfig(AuthorizerRemote, rawConfig, &conf); err != nil {
return nil, err
}
expressions, err := compileExpressions(conf.Expressions, a.celEnv)
if err != nil {
return nil, err
}
return &remoteAuthorizer{
id: a.id,
e: a.e,
payload: x.IfThenElse(conf.Payload != nil, conf.Payload, a.payload),
celEnv: a.celEnv,
expressions: x.IfThenElse(len(expressions) != 0, expressions, a.expressions),
headersForUpstream: x.IfThenElse(len(conf.ResponseHeadersToForward) != 0,
conf.ResponseHeadersToForward, a.headersForUpstream),
ttl: x.IfThenElse(conf.CacheTTL > 0, conf.CacheTTL, a.ttl),
v: a.v.Merge(conf.Values),
}, nil
}
func (a *remoteAuthorizer) ID() string { return a.id }
func (a *remoteAuthorizer) ContinueOnError() bool { return false }
func (a *remoteAuthorizer) doAuthorize(
ctx heimdall.Context,
sub *subject.Subject,
values map[string]string,
payload string,
) (*authorizationInformation, error) {
logger := zerolog.Ctx(ctx.AppContext())
logger.Debug().Msg("Calling remote authorization endpoint")
endpointRenderer := endpoint.RenderFunc(func(tplString string) (string, error) {
tpl, err := template.New(tplString)
if err != nil {
return "", errorchain.NewWithMessage(heimdall.ErrInternal, "failed to create template").
WithErrorContext(a).
CausedBy(err)
}
return tpl.Render(map[string]any{
"Subject": sub,
"Values": values,
})
})
req, err := a.e.CreateRequest(ctx.AppContext(), strings.NewReader(payload), endpointRenderer)
if err != nil {
return nil, errorchain.NewWithMessage(heimdall.ErrInternal, "failed creating request").
WithErrorContext(a).
CausedBy(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 authorization endpoint timed out").
WithErrorContext(a).
CausedBy(err)
}
return nil, errorchain.NewWithMessage(heimdall.ErrCommunication,
"request to the authorization endpoint failed").
WithErrorContext(a).
CausedBy(err)
}
defer resp.Body.Close()
data, err := a.readResponse(ctx, resp)
if err != nil && !errors.Is(err, errNoContent) {
return nil, err
}
err = a.verify(ctx, data)
if err != nil {
return nil, err
}
return &authorizationInformation{Headers: resp.Header, Payload: data}, nil
}
func (a *remoteAuthorizer) readResponse(ctx heimdall.Context, resp *http.Response) (any, error) {
logger := zerolog.Ctx(ctx.AppContext())
if !(resp.StatusCode >= http.StatusOK && resp.StatusCode < http.StatusMultipleChoices) {
return nil, errorchain.NewWithMessagef(heimdall.ErrAuthorization,
"authorization failed based on received response code: %v", resp.StatusCode).
WithErrorContext(a)
}
if resp.ContentLength == 0 {
logger.Debug().Msg("No content received")
return nil, errNoContent
}
rawData, err := io.ReadAll(resp.Body)
if err != nil {
return nil, errorchain.NewWithMessage(heimdall.ErrInternal, "failed to read response").
WithErrorContext(a).
CausedBy(err)
}
contentType := resp.Header.Get("Content-Type")
decoder, err := contenttype.NewDecoder(contentType)
if err != nil {
logger.Warn().Str("_content_type", contentType).
Msg("Content type is not supported. Treating it as string")
return stringx.ToString(rawData), nil // nolint: nilerr
}
result, err := decoder.Decode(rawData)
if err != nil {
return nil, errorchain.NewWithMessage(heimdall.ErrInternal, "failed to unmarshal response").
WithErrorContext(a).
CausedBy(err)
}
return result, nil
}
func (a *remoteAuthorizer) calculateCacheKey(sub *subject.Subject, values map[string]string, payload string) string {
const int64BytesCount = 8
ttlBytes := make([]byte, int64BytesCount)
binary.LittleEndian.PutUint64(ttlBytes, uint64(a.ttl))
hash := sha256.New()
hash.Write(a.e.Hash())
hash.Write(stringx.ToBytes(a.id))
hash.Write(stringx.ToBytes(strings.Join(a.headersForUpstream, ",")))
hash.Write(stringx.ToBytes(payload))
hash.Write(ttlBytes)
hash.Write(sub.Hash())
for k, v := range values {
hash.Write(stringx.ToBytes(k))
hash.Write(stringx.ToBytes(v))
}
return hex.EncodeToString(hash.Sum(nil))
}
func (a *remoteAuthorizer) verify(ctx heimdall.Context, result any) error {
logger := zerolog.Ctx(ctx.AppContext())
logger.Debug().Msg("Verifying authorization response")
return a.expressions.eval(map[string]any{"Payload": result}, a)
}
func (a *remoteAuthorizer) renderTemplates(
ctx heimdall.Context,
sub *subject.Subject,
) (map[string]string, string, error) {
var (
values map[string]string
payload string
err error
)
if values, err = a.v.Render(map[string]any{
"Request": ctx.Request(),
"Subject": sub,
}); err != nil {
return nil, "", errorchain.NewWithMessage(heimdall.ErrInternal,
"failed to render values for the authorization endpoint").
WithErrorContext(a).
CausedBy(err)
}
if a.payload != nil {
if payload, err = a.payload.Render(map[string]any{
"Request": ctx.Request(),
"Subject": sub,
"Values": values,
}); err != nil {
return nil, "", errorchain.NewWithMessage(heimdall.ErrInternal,
"failed to render payload for the authorization endpoint").
WithErrorContext(a).
CausedBy(err)
}
}
return values, payload, nil
}