-
Notifications
You must be signed in to change notification settings - Fork 361
/
Copy pathremote_json_test.go
441 lines (427 loc) · 14.3 KB
/
remote_json_test.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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package authz_test
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/tidwall/sjson"
"github.com/ory/x/configx"
"github.com/ory/x/logrusx"
"github.com/ory/oathkeeper/driver/configuration"
"github.com/ory/oathkeeper/pipeline/authn"
. "github.com/ory/oathkeeper/pipeline/authz"
"github.com/ory/oathkeeper/rule"
"github.com/ory/x/otelx"
)
type authorizeTestStruct struct {
name string
setup func(t *testing.T) *httptest.Server
session *authn.AuthenticationSession
sessionHeaderMatch *http.Header
config json.RawMessage
wantErr bool
}
func matchJsonFieldTest(name string, response string, config string, wantErr bool) authorizeTestStruct {
return authorizeTestStruct{
name: name,
setup: func(t *testing.T) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, err := io.ReadAll(r.Body)
require.NoError(t, err)
w.WriteHeader(http.StatusOK)
w.Write([]byte(response))
}))
},
session: &authn.AuthenticationSession{},
config: json.RawMessage(config),
wantErr: wantErr,
}
}
func TestAuthorizerRemoteJSONAuthorize(t *testing.T) {
t.Parallel()
tests := []authorizeTestStruct{
{
name: "invalid configuration",
session: &authn.AuthenticationSession{},
config: json.RawMessage(`{}`),
wantErr: true,
},
{
name: "unresolvable host",
session: &authn.AuthenticationSession{},
config: json.RawMessage(`{"remote":"http://unresolvable-host/path","payload":"{}"}`),
wantErr: true,
},
{
name: "invalid template",
session: &authn.AuthenticationSession{},
config: json.RawMessage(`{"remote":"http://host/path","payload":"{{"}`),
wantErr: true,
},
{
name: "unknown field",
session: &authn.AuthenticationSession{},
config: json.RawMessage(`{"remote":"http://host/path","payload":"{{ .foo }}"}`),
wantErr: true,
},
{
name: "invalid json",
session: &authn.AuthenticationSession{},
config: json.RawMessage(`{"remote":"http://host/path","payload":"{"}`),
wantErr: true,
},
{
name: "invalid headers type",
session: &authn.AuthenticationSession{},
config: json.RawMessage(`{"remote":"http://host/path","payload":"{\"match\":\"baz\"}","headers":"string"}`),
wantErr: true,
},
{
name: "invalid headers template",
session: &authn.AuthenticationSession{},
config: json.RawMessage(`{"remote":"http://host/path","payload":"{\"match\":\"baz\"}","headers":{"Subject":"{{ Invalid Template }}"}}`),
wantErr: true,
},
{
name: "headers template with unknown field",
session: &authn.AuthenticationSession{},
config: json.RawMessage(`{"remote":"http://host/path","payload":"{\"match\":\"baz\"}","headers":{"Subject":"{{ .UnknownField }}"}}`),
wantErr: true,
},
{
name: "forbidden",
setup: func(t *testing.T) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusForbidden)
}))
},
session: &authn.AuthenticationSession{},
config: json.RawMessage(`{"payload":"{}"}`),
wantErr: true,
},
{
name: "unexpected status code",
setup: func(t *testing.T) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusBadRequest)
}))
},
session: &authn.AuthenticationSession{},
config: json.RawMessage(`{"payload":"{}"}`),
wantErr: true,
},
matchJsonFieldTest("match_json_field denied empty body",
"",
`{"payload":"{}","match_json_field": {"field":"result", "str_val": "allowed"}}`,
true),
matchJsonFieldTest("match_json_field denied bool",
`{"allowed": false}`,
`{"payload":"{}","match_json_field": {"field":"allowed", "bool_val": true}}`,
true),
matchJsonFieldTest("match_json_field denied bool false",
`{"denied": true}`,
`{"payload":"{}","match_json_field": {"field":"denied", "bool_val": false}}`,
true),
matchJsonFieldTest("match_json_field denied str",
`{"result": "denied"}`,
`{"payload":"{}","match_json_field": {"field":"result", "str_val": "allowed"}}`,
true),
matchJsonFieldTest("match_json_field denied wrong type",
`{"result": "denied"}`,
`{"payload":"{}","match_json_field": {"field":"result", "bool_val": true}}`,
true),
matchJsonFieldTest("match_json_field denied true as string",
`{"allowed": "true"}`,
`{"payload":"{}","match_json_field": {"field":"allowed", "bool_val": true}}`,
true),
{
name: "ok",
setup: func(t *testing.T) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Contains(t, r.Header, "Content-Type")
assert.Contains(t, r.Header["Content-Type"], "application/json")
assert.Contains(t, r.Header, "Authorization")
assert.Contains(t, r.Header["Authorization"], "Bearer token")
body, err := io.ReadAll(r.Body)
require.NoError(t, err)
assert.Equal(t, string(body), "{}")
w.WriteHeader(http.StatusOK)
}))
},
session: &authn.AuthenticationSession{},
config: json.RawMessage(`{"payload":"{}"}`),
},
{
name: "ok with allowed response headers",
setup: func(t *testing.T) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("X-Foo", "bar")
w.WriteHeader(http.StatusOK)
}))
},
session: new(authn.AuthenticationSession),
sessionHeaderMatch: &http.Header{"X-Foo": []string{"bar"}},
config: json.RawMessage(`{"payload":"{}","forward_response_headers_to_upstream":["X-Foo"]}`),
},
{
name: "ok with not allowed response headers",
setup: func(t *testing.T) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("X-Bar", "foo")
w.WriteHeader(http.StatusOK)
}))
},
session: new(authn.AuthenticationSession),
sessionHeaderMatch: &http.Header{"X-Foo": []string{""}},
config: json.RawMessage(`{"payload":"{}","forward_response_headers_to_upstream":["X-Foo"]}`),
},
{
name: "authentication session",
setup: func(t *testing.T) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
require.NoError(t, err)
assert.Equal(t, string(body), `{"subject":"alice","extra":"bar","match":"baz"}`)
w.WriteHeader(http.StatusOK)
}))
},
session: &authn.AuthenticationSession{
Subject: "alice",
Extra: map[string]interface{}{"foo": "bar"},
MatchContext: authn.MatchContext{
RegexpCaptureGroups: []string{"baz"},
},
},
config: json.RawMessage(`{"payload":"{\"subject\":\"{{ .Subject }}\",\"extra\":\"{{ .Extra.foo }}\",\"match\":\"{{ index .MatchContext.RegexpCaptureGroups 0 }}\"}"}`),
},
{
name: "authentication session with extra request headers",
setup: func(t *testing.T) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
require.NoError(t, err)
assert.Equal(t, string(body), `{"match":"baz"}`)
assert.Equal(t, r.Header.Get("Subject"), "alice")
w.WriteHeader(http.StatusOK)
}))
},
session: &authn.AuthenticationSession{
Subject: "alice",
},
config: json.RawMessage(`{"payload":"{\"match\":\"baz\"}","headers":{"Subject":"{{ .Subject }}","Empty-Header":""}}`),
},
{
name: "json array",
setup: func(t *testing.T) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
require.NoError(t, err)
assert.Equal(t, string(body), `["foo","bar"]`)
w.WriteHeader(http.StatusOK)
}))
},
session: &authn.AuthenticationSession{},
config: json.RawMessage(`{"payload":"[\"foo\",\"bar\"]"}`),
},
matchJsonFieldTest("match_json_field bool field",
`{"allowed": true}`,
`{"payload":"{}","match_json_field": {"field":"allowed", "bool_val": true}}`,
false),
matchJsonFieldTest("match_json_field str field",
`{"result": "allowed"}`,
`{"payload":"{}","match_json_field": {"field":"result", "str_val": "allowed"}}`,
false),
matchJsonFieldTest("match_json_field nested",
`{"deeply": {"nested": {"result": "allowed"}}}`,
`{"payload":"{}","match_json_field": {"field":"deeply.nested.result", "str_val": "allowed"}}`,
false),
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
if tt.setup != nil {
server := tt.setup(t)
defer server.Close()
tt.config, _ = sjson.SetBytes(tt.config, "remote", server.URL)
}
l := logrusx.New("", "")
p, err := configuration.NewKoanfProvider(context.Background(), nil, l)
if err != nil {
l.WithError(err).Fatal("Failed to initialize configuration")
}
a := NewAuthorizerRemoteJSON(p, otelx.NewNoop(l, p.TracingConfig()))
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
r, err := http.NewRequestWithContext(ctx, "", "", nil)
require.NoError(t, err)
r.Header = map[string][]string{"Authorization": {"Bearer token"}}
if err := a.Authorize(r, tt.session, tt.config, &rule.Rule{}); (err != nil) != tt.wantErr {
t.Errorf("Authorize() error = %v, wantErr %v", err, tt.wantErr)
}
if tt.sessionHeaderMatch != nil {
assert.Equal(t, tt.sessionHeaderMatch, &tt.session.Header)
}
})
}
}
func TestAuthorizerRemoteJSONValidate(t *testing.T) {
t.Parallel()
tests := []struct {
name string
enabled bool
config json.RawMessage
wantErr bool
}{
{
name: "disabled",
config: json.RawMessage(`{}`),
wantErr: true,
},
{
name: "empty configuration",
enabled: true,
config: json.RawMessage(`{}`),
wantErr: true,
},
{
name: "missing payload",
enabled: true,
config: json.RawMessage(`{"remote":"http://host/path"}`),
wantErr: true,
},
{
name: "missing remote",
enabled: true,
config: json.RawMessage(`{"payload":"{}"}`),
wantErr: true,
},
{
name: "invalid url",
enabled: true,
config: json.RawMessage(`{"remote":"invalid-url","payload":"{}"}`),
wantErr: true,
},
{
name: "match response empty",
enabled: true,
config: json.RawMessage(`{"remote":"http://host/path", "payload":"{}", "match_json_field":{}}`),
wantErr: true,
},
{
name: "match response no value",
enabled: true,
config: json.RawMessage(`{"remote":"http://host/path", "payload":"{}", "match_json_field":{"field":"foo"}}`),
wantErr: true,
},
{
name: "valid configuration",
enabled: true,
config: json.RawMessage(`{"remote":"http://host/path","payload":"{}"}`),
},
{
name: "valid configuration with headers",
enabled: true,
config: json.RawMessage(`{"remote":"http://host/path","payload":"{}","headers":{"Authorization":"Bearer token"}}`),
},
{
name: "valid configuration with partial retry 1",
enabled: true,
config: json.RawMessage(`{"remote":"http://host/path","payload":"{}","retry":{"max_delay":"100ms"}}`),
},
{
name: "valid configuration with partial retry 2",
enabled: true,
config: json.RawMessage(`{"remote":"http://host/path","payload":"{}","retry":{"give_up_after":"3s"}}`),
},
{
name: "valid configuration with retry",
enabled: true,
config: json.RawMessage(`{"remote":"http://host/path","payload":"{}","retry":{"give_up_after":"3s", "max_delay":"100ms"}}`),
},
{
name: "valid configuration with match bool field",
enabled: true,
config: json.RawMessage(`{"remote":"http://host/path","payload":"{}","match_json_field":{"field":"foo","bool_val":true}}`),
},
{
name: "valid configuration with match str field",
enabled: true,
config: json.RawMessage(`{"remote":"http://host/path","payload":"{}","match_json_field":{"field":"foo","str_val":"bar"}}`),
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
p, err := configuration.NewKoanfProvider(
context.Background(), nil, logrusx.New("", ""),
configx.SkipValidation(),
)
require.NoError(t, err)
l := logrusx.New("", "")
a := NewAuthorizerRemoteJSON(p, otelx.NewNoop(l, p.TracingConfig()))
p.SetForTest(t, configuration.AuthorizerRemoteJSONIsEnabled, tt.enabled)
if err := a.Validate(tt.config); (err != nil) != tt.wantErr {
t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func TestAuthorizerRemoteJSONConfig(t *testing.T) {
t.Parallel()
tests := []struct {
name string
raw json.RawMessage
expected *AuthorizerRemoteJSONConfiguration
}{
{
name: "valid configuration with forward_response_headers_to_upstream",
raw: json.RawMessage(`{"remote":"http://host/path","payload":"{}","forward_response_headers_to_upstream":["X-Foo"]}`),
expected: &AuthorizerRemoteJSONConfiguration{
Remote: "http://host/path",
Payload: "{}",
ForwardResponseHeadersToUpstream: []string{"X-Foo"},
Retry: &AuthorizerRemoteJSONRetryConfiguration{
Timeout: "100ms", // default timeout from schema
MaxWait: "1s",
},
},
},
{
name: "valid configuration without forward_response_headers_to_upstream",
raw: json.RawMessage(`{"remote":"http://host/path","payload":"{}"}`),
expected: &AuthorizerRemoteJSONConfiguration{
Remote: "http://host/path",
Payload: "{}",
ForwardResponseHeadersToUpstream: []string{},
Retry: &AuthorizerRemoteJSONRetryConfiguration{
Timeout: "100ms", // default timeout from schema
MaxWait: "1s",
},
},
},
}
for _, tt := range tests {
tt := tt
t.Run("case="+tt.name, func(t *testing.T) {
t.Parallel()
p, err := configuration.NewKoanfProvider(
context.Background(), nil, logrusx.New("", ""),
)
require.NoError(t, err)
l := logrusx.New("", "")
a := NewAuthorizerRemoteJSON(p, otelx.NewNoop(l, p.TracingConfig()))
actual, err := a.Config(tt.raw)
assert.NoError(t, err)
assert.Equal(t, tt.expected, actual)
})
}
}