-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathhandler_test.go
More file actions
592 lines (514 loc) · 19 KB
/
handler_test.go
File metadata and controls
592 lines (514 loc) · 19 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
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
package centralproxy
import (
"bytes"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/stackrox/rox/pkg/centralsensor"
pkghttputil "github.com/stackrox/rox/pkg/httputil"
"github.com/stackrox/rox/sensor/common"
"github.com/stackrox/rox/sensor/common/centralcaps"
"github.com/stackrox/rox/sensor/common/centralproxy/allowedpaths"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
authenticationv1 "k8s.io/api/authentication/v1"
authv1 "k8s.io/api/authorization/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes/fake"
k8sTesting "k8s.io/client-go/testing"
)
func TestValidateRequest(t *testing.T) {
tests := []struct {
name string
method string
centralReachable bool
wantStatusCode int
wantError string
}{
{
name: "GET is allowed",
method: http.MethodGet,
centralReachable: true,
wantStatusCode: 0, // validateRequest returns nil on success
},
{
name: "POST is allowed",
method: http.MethodPost,
centralReachable: true,
wantStatusCode: 0,
},
{
name: "OPTIONS is allowed (for CORS preflight)",
method: http.MethodOptions,
centralReachable: true,
wantStatusCode: 0,
},
{
name: "HEAD is allowed",
method: http.MethodHead,
centralReachable: true,
wantStatusCode: 0,
},
{
name: "PUT returns 405",
method: http.MethodPut,
centralReachable: true,
wantStatusCode: http.StatusMethodNotAllowed,
wantError: "method PUT not allowed",
},
{
name: "DELETE returns 405",
method: http.MethodDelete,
centralReachable: true,
wantStatusCode: http.StatusMethodNotAllowed,
wantError: "method DELETE not allowed",
},
{
name: "central not reachable returns 503",
method: http.MethodGet,
centralReachable: false,
wantStatusCode: http.StatusServiceUnavailable,
wantError: "central not reachable",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
h := &Handler{
clusterIDGetter: &testClusterIDGetter{clusterID: "test-cluster-id"},
}
h.centralReachable.Store(tt.centralReachable)
req := httptest.NewRequest(tt.method, "/v1/alerts", nil)
err := h.validateRequest(req)
if tt.wantStatusCode == 0 {
assert.NoError(t, err)
} else {
require.Error(t, err)
httpErr, ok := err.(pkghttputil.HTTPError)
require.True(t, ok, "error should be an HTTPError")
assert.Equal(t, tt.wantStatusCode, httpErr.HTTPStatusCode())
assert.Contains(t, err.Error(), tt.wantError)
}
})
}
}
func TestServeHTTP(t *testing.T) {
t.Run("validation fails, proxy not called", func(t *testing.T) {
setupCentralCapsForTest(t)
baseURL, err := url.Parse("https://central:443")
require.NoError(t, err)
h := newTestHandler(t, baseURL, nil, nil, "test-token")
h.centralReachable.Store(false) // Will fail validation
req := httptest.NewRequest(http.MethodGet, "/v1/alerts", nil)
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
assert.Equal(t, http.StatusServiceUnavailable, w.Code)
assert.Contains(t, w.Body.String(), "central not reachable")
})
t.Run("validation passes, request proxied", func(t *testing.T) {
f := newProxyTestFixture(t, newAllowingAuthorizer(t))
w := f.serveHTTP(t, http.MethodGet, "/v1/alerts", map[string]string{
"Authorization": "Bearer test-token",
})
assert.True(t, f.proxyCalled, "proxy should be called")
assert.Equal(t, http.StatusOK, w.Code)
})
t.Run("proxy error handled by ErrorHandler", func(t *testing.T) {
setupCentralCapsForTest(t)
baseURL, err := url.Parse("https://central:443")
require.NoError(t, err)
h := newTestHandlerWithTransportError(t, baseURL, newAllowingAuthorizer(t), errTransportError)
h.centralReachable.Store(true)
req := httptest.NewRequest(http.MethodGet, "/v1/alerts", nil)
req.Header.Set("Authorization", "Bearer test-token")
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
assert.Equal(t, http.StatusInternalServerError, w.Code)
assert.Contains(t, w.Body.String(), "failed to contact central")
})
t.Run("request rejected when Central lacks internal token API capability", func(t *testing.T) {
// Explicitly clear central caps to simulate an older Central without the capability.
// Use cleanup to restore state and avoid cross-test interference.
centralcaps.Set(nil)
t.Cleanup(func() {
centralcaps.Set(nil)
})
var proxyCalled bool
mockTransport := pkghttputil.RoundTripperFunc(func(req *http.Request) (*http.Response, error) {
proxyCalled = true
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(strings.NewReader(`{"ok":true}`)),
Header: http.Header{"Content-Type": []string{"application/json"}},
}, nil
})
baseURL, err := url.Parse("https://central:443")
require.NoError(t, err)
h := &Handler{
proxy: newReverseProxyForTest(baseURL, mockTransport),
authorizer: newAllowingAuthorizer(t),
}
h.centralReachable.Store(true)
req := httptest.NewRequest(http.MethodGet, "/v1/alerts", nil)
req.Header.Set("Authorization", "Bearer test-token")
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
assert.False(t, proxyCalled, "proxy should not be called when capability is missing")
assert.Equal(t, http.StatusNotImplemented, w.Code)
assert.Contains(t, w.Body.String(), "proxy to Central is not available")
assert.Contains(t, w.Body.String(), "internal token API")
})
}
func TestServeHTTP_ConstructsAbsoluteURLs(t *testing.T) {
tests := []struct {
name string
baseURL string
requestPath string
requestQuery string
expectedURL string
}{
{
name: "simple path without query",
baseURL: "https://central.stackrox.svc:443",
requestPath: "/v1/alerts",
expectedURL: "https://central.stackrox.svc:443/v1/alerts",
},
{
name: "path with query parameters",
baseURL: "https://central.stackrox.svc:443",
requestPath: "/v1/alerts",
requestQuery: "limit=10&offset=20",
expectedURL: "https://central.stackrox.svc:443/v1/alerts?limit=10&offset=20",
},
{
name: "graphql endpoint",
baseURL: "https://central.stackrox.svc:443",
requestPath: "/api/graphql",
expectedURL: "https://central.stackrox.svc:443/api/graphql",
},
{
name: "endpoint without port",
baseURL: "https://central.stackrox.svc",
requestPath: "/v1/deployments",
expectedURL: "https://central.stackrox.svc/v1/deployments",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
setupCentralCapsForTest(t)
baseURL, err := url.Parse(tt.baseURL)
assert.NoError(t, err)
var capturedURL string
mockTransport := pkghttputil.RoundTripperFunc(func(req *http.Request) (*http.Response, error) {
// Capture the URL that was used for the request
capturedURL = req.URL.String()
// Verify it's an absolute URL with scheme and host
assert.NotEmpty(t, req.URL.Scheme, "URL scheme should not be empty")
assert.NotEmpty(t, req.URL.Host, "URL host should not be empty")
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString("{}")),
Header: http.Header{"Content-Type": []string{"application/json"}},
}, nil
})
h := newTestHandler(t, baseURL, mockTransport, newAllowingAuthorizer(t), "test-token")
h.centralReachable.Store(true)
req := httptest.NewRequest(http.MethodGet, tt.requestPath, nil)
req.Header.Set("Authorization", "Bearer test-token")
if tt.requestQuery != "" {
req.URL.RawQuery = tt.requestQuery
}
writer := httptest.NewRecorder()
h.ServeHTTP(writer, req)
assert.Equal(t, tt.expectedURL, capturedURL)
})
}
}
func TestNotify(t *testing.T) {
h := &Handler{}
t.Run("CentralReachable sets centralReachable to true", func(t *testing.T) {
h.centralReachable.Store(false)
h.Notify(common.SensorComponentEventCentralReachable)
assert.True(t, h.centralReachable.Load())
})
t.Run("OfflineMode sets centralReachable to false", func(t *testing.T) {
h.centralReachable.Store(true)
h.Notify(common.SensorComponentEventOfflineMode)
assert.False(t, h.centralReachable.Load())
})
}
func TestExtractBearerToken(t *testing.T) {
tests := []struct {
name string
authHeader string
wantToken string
wantErr bool
errContains string
}{
{
name: "valid bearer token",
authHeader: "Bearer my-secret-token-123",
wantToken: "my-secret-token-123",
wantErr: false,
},
{
name: "bearer token with spaces",
authHeader: "Bearer token-with-spaces ",
wantToken: "token-with-spaces ",
wantErr: false,
},
{
name: "missing authorization header",
authHeader: "",
wantErr: true,
errContains: "missing or invalid bearer token",
},
{
name: "invalid format - no Bearer prefix",
authHeader: "Basic dXNlcjpwYXNz",
wantErr: true,
errContains: "missing or invalid bearer token",
},
{
name: "case-insensitive bearer prefix (lowercase)",
authHeader: "bearer my-token-123",
wantToken: "my-token-123",
wantErr: false,
},
{
name: "case-insensitive bearer prefix (mixed case)",
authHeader: "BeArEr my-token-123",
wantToken: "my-token-123",
wantErr: false,
},
{
name: "empty token after Bearer",
authHeader: "Bearer ",
wantErr: true,
errContains: "missing or invalid bearer token",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/test", nil)
if tt.authHeader != "" {
req.Header.Set("Authorization", tt.authHeader)
}
token, err := extractBearerToken(req)
if tt.wantErr {
assert.Error(t, err)
assert.Contains(t, err.Error(), tt.errContains)
} else {
assert.NoError(t, err)
assert.Equal(t, tt.wantToken, token)
}
})
}
}
func TestServeHTTP_AuthorizationIntegration(t *testing.T) {
t.Run("authorization failure prevents proxy call", func(t *testing.T) {
f := newProxyTestFixture(t, newDenyingAuthorizer(t))
// Set namespace scope header to trigger SAR check.
w := f.serveHTTP(t, http.MethodGet, "/v1/alerts", map[string]string{
"Authorization": "Bearer test-token",
stackroxNamespaceHeader: "my-namespace",
})
assert.False(t, f.proxyCalled, "proxy should not be called when authorization fails")
assert.Equal(t, http.StatusForbidden, w.Code)
assert.Contains(t, w.Body.String(), "lacks")
})
t.Run("no authorizer returns server error", func(t *testing.T) {
f := newProxyTestFixture(t, nil)
w := f.serveHTTP(t, http.MethodGet, "/v1/alerts", nil)
assert.False(t, f.proxyCalled, "proxy should not be called when authorizer is not configured")
assert.Equal(t, http.StatusInternalServerError, w.Code)
assert.Contains(t, w.Body.String(), "authorizer not configured")
})
t.Run("authorization success allows proxy call", func(t *testing.T) {
f := newProxyTestFixture(t, newAllowingAuthorizer(t))
w := f.serveHTTP(t, http.MethodGet, "/v1/alerts", map[string]string{
"Authorization": "Bearer test-token",
})
assert.True(t, f.proxyCalled, "proxy should be called when authorization succeeds")
assert.Equal(t, http.StatusOK, w.Code)
})
}
func TestServeHTTP_NamespaceScopeBasedAuthorization(t *testing.T) {
t.Run("empty namespace scope skips SAR check", func(t *testing.T) {
// Create authorizer that denies SAR but allows TokenReview.
f := newProxyTestFixture(t, newDenyingAuthorizer(t))
// No namespace scope header - should skip SAR.
w := f.serveHTTP(t, http.MethodGet, "/v1/metadata", map[string]string{
"Authorization": "Bearer test-token",
})
assert.True(t, f.proxyCalled, "proxy should be called when namespace scope is empty (no SAR)")
assert.Equal(t, http.StatusOK, w.Code)
})
t.Run("specific namespace scope triggers SAR check", func(t *testing.T) {
f := newProxyTestFixture(t, newDenyingAuthorizer(t))
w := f.serveHTTP(t, http.MethodGet, "/v1/alerts", map[string]string{
"Authorization": "Bearer test-token",
stackroxNamespaceHeader: "my-namespace",
})
assert.False(t, f.proxyCalled, "proxy should not be called when SAR fails for namespace scope")
assert.Equal(t, http.StatusForbidden, w.Code)
})
t.Run("cluster-wide scope (*) triggers SAR check", func(t *testing.T) {
f := newProxyTestFixture(t, newDenyingAuthorizer(t))
w := f.serveHTTP(t, http.MethodGet, "/v1/alerts", map[string]string{
"Authorization": "Bearer test-token",
stackroxNamespaceHeader: FullClusterAccessScope,
})
assert.False(t, f.proxyCalled, "proxy should not be called when SAR fails for cluster-wide scope")
assert.Equal(t, http.StatusForbidden, w.Code)
})
t.Run("namespace scope with valid permissions succeeds", func(t *testing.T) {
setupCentralCapsForTest(t)
var proxyCalled bool
mockTransport := pkghttputil.RoundTripperFunc(func(req *http.Request) (*http.Response, error) {
proxyCalled = true
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(strings.NewReader(`{"ok":true}`)),
Header: http.Header{"Content-Type": []string{"application/json"}},
}, nil
})
baseURL, err := url.Parse("https://central:443")
require.NoError(t, err)
fakeClient := fake.NewClientset()
// Mock TokenReview to return authenticated
fakeClient.PrependReactor("create", "tokenreviews", func(action k8sTesting.Action) (bool, runtime.Object, error) {
return true, &authenticationv1.TokenReview{
Status: authenticationv1.TokenReviewStatus{
Authenticated: true,
User: authenticationv1.UserInfo{
Username: "test-user",
},
},
}, nil
})
// Mock SAR to allow
fakeClient.PrependReactor("create", "subjectaccessreviews", func(action k8sTesting.Action) (bool, runtime.Object, error) {
return true, &authv1.SubjectAccessReview{
Status: authv1.SubjectAccessReviewStatus{
Allowed: true,
},
}, nil
})
h := newTestHandler(t, baseURL, mockTransport, newK8sAuthorizer(fakeClient), "test-token")
h.centralReachable.Store(true)
req := httptest.NewRequest(http.MethodGet, "/v1/alerts", nil)
req.Header.Set("Authorization", "Bearer test-token")
req.Header.Set(stackroxNamespaceHeader, "my-namespace")
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
assert.True(t, proxyCalled, "proxy should be called with valid permissions")
assert.Equal(t, http.StatusOK, w.Code)
})
}
func TestServeHTTP_TransportFailure(t *testing.T) {
t.Run("transport failure returns 500", func(t *testing.T) {
setupCentralCapsForTest(t)
baseURL, err := url.Parse("https://central:443")
require.NoError(t, err)
h := newTestHandlerWithTransportError(t, baseURL, newAllowingAuthorizer(t), errTransportError)
h.centralReachable.Store(true)
req := httptest.NewRequest(http.MethodGet, "/v1/alerts", nil)
req.Header.Set("Authorization", "Bearer test-token")
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
assert.Equal(t, http.StatusInternalServerError, w.Code)
assert.Contains(t, w.Body.String(), "failed to contact central")
})
t.Run("initialization error returns 503", func(t *testing.T) {
setupCentralCapsForTest(t)
baseURL, err := url.Parse("https://central:443")
require.NoError(t, err)
// Use errServiceUnavailable to simulate initialization failure
h := newTestHandlerWithTransportError(t, baseURL, newAllowingAuthorizer(t), errServiceUnavailable)
h.centralReachable.Store(true)
req := httptest.NewRequest(http.MethodGet, "/v1/alerts", nil)
req.Header.Set("Authorization", "Bearer test-token")
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
assert.Equal(t, http.StatusServiceUnavailable, w.Code)
assert.Contains(t, w.Body.String(), "proxy temporarily unavailable")
})
}
func TestServeHTTP_TokenInjection(t *testing.T) {
t.Run("token is injected into proxied request", func(t *testing.T) {
setupCentralCapsForTest(t)
expectedToken := "dynamic-central-token-123"
var capturedAuthHeader string
mockTransport := pkghttputil.RoundTripperFunc(func(req *http.Request) (*http.Response, error) {
capturedAuthHeader = req.Header.Get("Authorization")
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(strings.NewReader(`{"ok":true}`)),
Header: http.Header{"Content-Type": []string{"application/json"}},
}, nil
})
baseURL, err := url.Parse("https://central:443")
require.NoError(t, err)
h := newTestHandler(t, baseURL, mockTransport, newAllowingAuthorizer(t), expectedToken)
h.centralReachable.Store(true)
req := httptest.NewRequest(http.MethodGet, "/v1/alerts", nil)
req.Header.Set("Authorization", "Bearer user-token") // User's incoming token
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "Bearer "+expectedToken, capturedAuthHeader, "proxied request should have Central token, not user token")
})
}
func TestServeHTTP_RequiresAuthentication(t *testing.T) {
t.Run("missing token returns 401", func(t *testing.T) {
f := newProxyTestFixture(t, newAllowingAuthorizer(t))
// No Authorization header set.
w := f.serveHTTP(t, http.MethodGet, "/v1/alerts", nil)
assert.False(t, f.proxyCalled, "proxy should not be called without authorization header")
assert.Equal(t, http.StatusUnauthorized, w.Code)
assert.Contains(t, w.Body.String(), "bearer token")
})
t.Run("invalid token returns 401", func(t *testing.T) {
f := newProxyTestFixture(t, newUnauthenticatedAuthorizer(t))
w := f.serveHTTP(t, http.MethodGet, "/v1/alerts", map[string]string{
"Authorization": "Bearer invalid-token",
})
assert.False(t, f.proxyCalled, "proxy should not be called with unauthenticated token")
assert.Equal(t, http.StatusUnauthorized, w.Code)
})
}
func TestServeHTTP_PathFiltering(t *testing.T) {
t.Run("disallowed path returns 403", func(t *testing.T) {
f := newProxyTestFixture(t, newAllowingAuthorizer(t))
w := f.serveHTTP(t, http.MethodGet, "/admin/secret", map[string]string{
"Authorization": "Bearer test-token",
})
assert.False(t, f.proxyCalled, "proxy should not be called for disallowed path")
assert.Equal(t, http.StatusForbidden, w.Code)
assert.Contains(t, w.Body.String(), "not allowed by the proxy allow-list")
})
t.Run("allowed path proceeds normally", func(t *testing.T) {
f := newProxyTestFixture(t, newAllowingAuthorizer(t))
w := f.serveHTTP(t, http.MethodGet, "/v1/alerts", map[string]string{
"Authorization": "Bearer test-token",
})
assert.True(t, f.proxyCalled, "proxy should be called for allowed path")
assert.Equal(t, http.StatusOK, w.Code)
})
t.Run("no allow-list configured allows all paths", func(t *testing.T) {
f := newProxyTestFixture(t, newAllowingAuthorizer(t))
// Override: remove path filtering capability and clear allowed paths.
centralcaps.Set([]centralsensor.CentralCapability{
centralsensor.InternalTokenAPISupported,
})
allowedpaths.Reset()
w := f.serveHTTP(t, http.MethodGet, "/admin/anything", map[string]string{
"Authorization": "Bearer test-token",
})
assert.True(t, f.proxyCalled, "proxy should be called when no allow-list is configured")
assert.Equal(t, http.StatusOK, w.Code)
})
}