-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth_test.go
More file actions
649 lines (548 loc) · 17.2 KB
/
auth_test.go
File metadata and controls
649 lines (548 loc) · 17.2 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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
package grpckit
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
func TestExtractToken(t *testing.T) {
tests := []struct {
name string
header string
expected string
}{
{
name: "Bearer token",
header: "Bearer abc123",
expected: "abc123",
},
{
name: "bearer lowercase",
header: "bearer xyz789",
expected: "xyz789",
},
{
name: "BEARER uppercase",
header: "BEARER TOKEN123",
expected: "TOKEN123",
},
{
name: "no prefix",
header: "rawtoken",
expected: "rawtoken",
},
{
name: "empty string",
header: "",
expected: "",
},
{
name: "Bearer with spaces",
header: "Bearer token with spaces",
expected: " token with spaces",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := extractToken(tt.header)
if result != tt.expected {
t.Errorf("extractToken(%q) = %q, want %q", tt.header, result, tt.expected)
}
})
}
}
func TestMatchPattern(t *testing.T) {
tests := []struct {
name string
pattern string
path string
expected bool
}{
{
name: "exact match",
pattern: "/api/v1/users",
path: "/api/v1/users",
expected: true,
},
{
name: "exact no match",
pattern: "/api/v1/users",
path: "/api/v1/items",
expected: false,
},
{
name: "double star suffix",
pattern: "/api/v1/**",
path: "/api/v1/users/123",
expected: true,
},
{
name: "double star no match",
pattern: "/api/v1/**",
path: "/api/v2/users",
expected: false,
},
{
name: "single star",
pattern: "/api/v1/*",
path: "/api/v1/users",
expected: true,
},
{
name: "single star no match nested",
pattern: "/api/v1/*",
path: "/api/v1/users/123",
expected: false,
},
{
name: "grpc method pattern",
pattern: "/myservice.v1.MyService/*",
path: "/myservice.v1.MyService/GetUser",
expected: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := matchPattern(tt.pattern, tt.path)
if result != tt.expected {
t.Errorf("matchPattern(%q, %q) = %v, want %v", tt.pattern, tt.path, result, tt.expected)
}
})
}
}
func TestMatchesAnyPattern(t *testing.T) {
patterns := []string{"/healthz", "/readyz", "/api/public/**"}
tests := []struct {
path string
expected bool
}{
{"/healthz", true},
{"/readyz", true},
{"/api/public/data", true},
{"/api/private/data", false},
{"/metrics", false},
}
for _, tt := range tests {
t.Run(tt.path, func(t *testing.T) {
result := matchesAnyPattern(tt.path, patterns)
if result != tt.expected {
t.Errorf("matchesAnyPattern(%q, patterns) = %v, want %v", tt.path, result, tt.expected)
}
})
}
}
func TestRequiresAuth(t *testing.T) {
tests := []struct {
name string
path string
authFunc AuthFunc
protectedEndpoints []string
publicEndpoints []string
expected bool
}{
{
name: "no auth func",
path: "/api/v1/users",
authFunc: nil,
expected: false,
},
{
name: "protected endpoints - match",
path: "/api/v1/users",
authFunc: func(ctx context.Context, token string) (context.Context, error) { return ctx, nil },
protectedEndpoints: []string{"/api/v1/**"},
expected: true,
},
{
name: "protected endpoints - no match",
path: "/healthz",
authFunc: func(ctx context.Context, token string) (context.Context, error) { return ctx, nil },
protectedEndpoints: []string{"/api/v1/**"},
expected: false,
},
{
name: "public endpoints - match",
path: "/healthz",
authFunc: func(ctx context.Context, token string) (context.Context, error) { return ctx, nil },
publicEndpoints: []string{"/healthz", "/readyz"},
expected: false,
},
{
name: "public endpoints - no match requires auth",
path: "/api/v1/users",
authFunc: func(ctx context.Context, token string) (context.Context, error) { return ctx, nil },
publicEndpoints: []string{"/healthz", "/readyz"},
expected: true,
},
{
name: "auth func set, no patterns - protect everything",
path: "/anything",
authFunc: func(ctx context.Context, token string) (context.Context, error) { return ctx, nil },
expected: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg := &serverConfig{
authFunc: tt.authFunc,
protectedEndpoints: tt.protectedEndpoints,
publicEndpoints: tt.publicEndpoints,
}
result := requiresAuth(tt.path, cfg)
if result != tt.expected {
t.Errorf("requiresAuth(%q) = %v, want %v", tt.path, result, tt.expected)
}
})
}
}
func TestAuthMiddleware_NoAuthFunc(t *testing.T) {
cfg := &serverConfig{authFunc: nil}
nextCalled := false
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
nextCalled = true
w.WriteHeader(http.StatusOK)
})
handler := authMiddleware(cfg, next)
req := httptest.NewRequest(http.MethodGet, "/api/v1/users", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if !nextCalled {
t.Error("expected next handler to be called when no auth func")
}
}
func TestAuthMiddleware_PublicEndpoint(t *testing.T) {
cfg := &serverConfig{
authFunc: func(ctx context.Context, token string) (context.Context, error) { return nil, errors.New("auth error") },
publicEndpoints: []string{"/healthz"},
}
nextCalled := false
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
nextCalled = true
w.WriteHeader(http.StatusOK)
})
handler := authMiddleware(cfg, next)
req := httptest.NewRequest(http.MethodGet, "/healthz", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if !nextCalled {
t.Error("expected next handler to be called for public endpoint")
}
}
func TestAuthMiddleware_AuthSuccess(t *testing.T) {
var capturedCtx context.Context
cfg := &serverConfig{
authFunc: func(ctx context.Context, token string) (context.Context, error) {
if token != "valid-token" {
return nil, ErrUnauthorized
}
return context.WithValue(ctx, UserIDKey, "user123"), nil
},
}
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
capturedCtx = r.Context()
w.WriteHeader(http.StatusOK)
})
handler := authMiddleware(cfg, next)
req := httptest.NewRequest(http.MethodGet, "/api/v1/users", nil)
req.Header.Set("Authorization", "Bearer valid-token")
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", rec.Code)
}
if capturedCtx.Value(UserIDKey) != "user123" {
t.Error("expected enriched context with user_id")
}
}
func TestAuthMiddleware_AuthFailure(t *testing.T) {
cfg := &serverConfig{
authFunc: func(ctx context.Context, token string) (context.Context, error) {
return nil, ErrUnauthorized
},
}
nextCalled := false
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
nextCalled = true
})
handler := authMiddleware(cfg, next)
req := httptest.NewRequest(http.MethodGet, "/api/v1/users", nil)
req.Header.Set("Authorization", "Bearer invalid-token")
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Errorf("expected status 401, got %d", rec.Code)
}
if nextCalled {
t.Error("next handler should not be called on auth failure")
}
}
func TestGRPCAuthInterceptor_NoAuthFunc(t *testing.T) {
cfg := &serverConfig{authFunc: nil}
interceptor := grpcAuthInterceptor(cfg)
handlerCalled := false
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
handlerCalled = true
return "response", nil
}
resp, err := interceptor(context.Background(), "request", &grpc.UnaryServerInfo{FullMethod: "/test/Method"}, handler)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if !handlerCalled {
t.Error("handler should be called when no auth func")
}
if resp != "response" {
t.Errorf("unexpected response: %v", resp)
}
}
func TestGRPCAuthInterceptor_PublicEndpoint(t *testing.T) {
cfg := &serverConfig{
authFunc: func(ctx context.Context, token string) (context.Context, error) { return nil, errors.New("should not be called") },
publicEndpoints: []string{"/test.Service/*"},
}
interceptor := grpcAuthInterceptor(cfg)
handlerCalled := false
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
handlerCalled = true
return "response", nil
}
_, err := interceptor(context.Background(), "request", &grpc.UnaryServerInfo{FullMethod: "/test.Service/Method"}, handler)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if !handlerCalled {
t.Error("handler should be called for public endpoint")
}
}
func TestGRPCAuthInterceptor_MissingMetadata(t *testing.T) {
cfg := &serverConfig{
authFunc: func(ctx context.Context, token string) (context.Context, error) {
return ctx, nil
},
}
interceptor := grpcAuthInterceptor(cfg)
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return "response", nil
}
// Context without metadata
_, err := interceptor(context.Background(), "request", &grpc.UnaryServerInfo{FullMethod: "/test/Method"}, handler)
if err == nil {
t.Error("expected error for missing metadata")
}
st, ok := status.FromError(err)
if !ok || st.Code() != codes.Unauthenticated {
t.Errorf("expected Unauthenticated error, got %v", err)
}
}
func TestGRPCAuthInterceptor_AuthSuccess(t *testing.T) {
cfg := &serverConfig{
authFunc: func(ctx context.Context, token string) (context.Context, error) {
if token != "valid-token" {
return nil, ErrUnauthorized
}
return context.WithValue(ctx, UserIDKey, "user123"), nil
},
}
interceptor := grpcAuthInterceptor(cfg)
var capturedCtx context.Context
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
capturedCtx = ctx
return "response", nil
}
md := metadata.New(map[string]string{"authorization": "Bearer valid-token"})
ctx := metadata.NewIncomingContext(context.Background(), md)
_, err := interceptor(ctx, "request", &grpc.UnaryServerInfo{FullMethod: "/test/Method"}, handler)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if capturedCtx.Value(UserIDKey) != "user123" {
t.Error("expected enriched context with user_id")
}
}
func TestGRPCAuthInterceptor_AuthFailure(t *testing.T) {
cfg := &serverConfig{
authFunc: func(ctx context.Context, token string) (context.Context, error) {
return nil, ErrUnauthorized
},
}
interceptor := grpcAuthInterceptor(cfg)
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
t.Error("handler should not be called")
return nil, nil
}
md := metadata.New(map[string]string{"authorization": "Bearer invalid-token"})
ctx := metadata.NewIncomingContext(context.Background(), md)
_, err := interceptor(ctx, "request", &grpc.UnaryServerInfo{FullMethod: "/test/Method"}, handler)
if err == nil {
t.Error("expected authentication error")
}
st, ok := status.FromError(err)
if !ok || st.Code() != codes.Unauthenticated {
t.Errorf("expected Unauthenticated error, got %v", err)
}
}
// mockServerStream is a minimal mock for grpc.ServerStream used in tests.
type mockServerStream struct {
grpc.ServerStream
ctx context.Context
}
func (m *mockServerStream) Context() context.Context {
return m.ctx
}
func TestGRPCStreamAuthInterceptor_NoAuthFunc(t *testing.T) {
cfg := &serverConfig{authFunc: nil}
interceptor := grpcStreamAuthInterceptor(cfg)
handlerCalled := false
handler := func(srv interface{}, stream grpc.ServerStream) error {
handlerCalled = true
return nil
}
md := metadata.New(map[string]string{})
ctx := metadata.NewIncomingContext(context.Background(), md)
stream := &mockServerStream{ctx: ctx}
err := interceptor(nil, stream, &grpc.StreamServerInfo{FullMethod: "/test/Method"}, handler)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if !handlerCalled {
t.Error("handler should be called when no auth func")
}
}
func TestGRPCStreamAuthInterceptor_PublicEndpoint(t *testing.T) {
cfg := &serverConfig{
authFunc: func(ctx context.Context, token string) (context.Context, error) { return nil, errors.New("should not be called") },
publicEndpoints: []string{"/test.Service/*"},
}
interceptor := grpcStreamAuthInterceptor(cfg)
handlerCalled := false
handler := func(srv interface{}, stream grpc.ServerStream) error {
handlerCalled = true
return nil
}
md := metadata.New(map[string]string{})
ctx := metadata.NewIncomingContext(context.Background(), md)
stream := &mockServerStream{ctx: ctx}
err := interceptor(nil, stream, &grpc.StreamServerInfo{FullMethod: "/test.Service/WatchSomething"}, handler)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if !handlerCalled {
t.Error("handler should be called for public endpoint")
}
}
func TestGRPCStreamAuthInterceptor_MissingMetadata(t *testing.T) {
cfg := &serverConfig{
authFunc: func(ctx context.Context, token string) (context.Context, error) {
return ctx, nil
},
}
interceptor := grpcStreamAuthInterceptor(cfg)
handler := func(srv interface{}, stream grpc.ServerStream) error {
return nil
}
// Context without metadata
stream := &mockServerStream{ctx: context.Background()}
err := interceptor(nil, stream, &grpc.StreamServerInfo{FullMethod: "/test/Method"}, handler)
if err == nil {
t.Error("expected error for missing metadata")
}
st, ok := status.FromError(err)
if !ok || st.Code() != codes.Unauthenticated {
t.Errorf("expected Unauthenticated error, got %v", err)
}
}
func TestGRPCStreamAuthInterceptor_AuthSuccess(t *testing.T) {
cfg := &serverConfig{
authFunc: func(ctx context.Context, token string) (context.Context, error) {
if token != "valid-token" {
return nil, ErrUnauthorized
}
return context.WithValue(ctx, UserIDKey, "user123"), nil
},
}
interceptor := grpcStreamAuthInterceptor(cfg)
var capturedCtx context.Context
handler := func(srv interface{}, stream grpc.ServerStream) error {
capturedCtx = stream.Context()
return nil
}
md := metadata.New(map[string]string{"authorization": "Bearer valid-token"})
ctx := metadata.NewIncomingContext(context.Background(), md)
stream := &mockServerStream{ctx: ctx}
err := interceptor(nil, stream, &grpc.StreamServerInfo{FullMethod: "/test/Method"}, handler)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if capturedCtx.Value(UserIDKey) != "user123" {
t.Error("expected enriched context with user_id to be propagated to stream handler")
}
}
func TestGRPCStreamAuthInterceptor_PropagatesContext(t *testing.T) {
// This test specifically verifies that the enriched context from authFunc
// is available in the stream handler, which is critical for grant type validation.
type claimsKey struct{}
cfg := &serverConfig{
authFunc: func(ctx context.Context, token string) (context.Context, error) {
// Simulate OIDC auth that adds claims to context
claims := map[string]string{
"grant_type": "client_credentials",
"client_id": "test-client",
}
return context.WithValue(ctx, claimsKey{}, claims), nil
},
}
interceptor := grpcStreamAuthInterceptor(cfg)
var capturedClaims map[string]string
handler := func(srv interface{}, stream grpc.ServerStream) error {
// This simulates what GrantTypeStreamInterceptor does - extract claims from context
claims, ok := stream.Context().Value(claimsKey{}).(map[string]string)
if ok {
capturedClaims = claims
}
return nil
}
md := metadata.New(map[string]string{"authorization": "Bearer some-token"})
ctx := metadata.NewIncomingContext(context.Background(), md)
stream := &mockServerStream{ctx: ctx}
err := interceptor(nil, stream, &grpc.StreamServerInfo{FullMethod: "/test/WatchMethod"}, handler)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if capturedClaims == nil {
t.Fatal("claims should be available in stream context - this is the bug that was fixed!")
}
if capturedClaims["grant_type"] != "client_credentials" {
t.Errorf("expected grant_type=client_credentials, got %v", capturedClaims["grant_type"])
}
if capturedClaims["client_id"] != "test-client" {
t.Errorf("expected client_id=test-client, got %v", capturedClaims["client_id"])
}
}
func TestGRPCStreamAuthInterceptor_AuthFailure(t *testing.T) {
cfg := &serverConfig{
authFunc: func(ctx context.Context, token string) (context.Context, error) {
return nil, ErrUnauthorized
},
}
interceptor := grpcStreamAuthInterceptor(cfg)
handler := func(srv interface{}, stream grpc.ServerStream) error {
t.Error("handler should not be called")
return nil
}
md := metadata.New(map[string]string{"authorization": "Bearer invalid-token"})
ctx := metadata.NewIncomingContext(context.Background(), md)
stream := &mockServerStream{ctx: ctx}
err := interceptor(nil, stream, &grpc.StreamServerInfo{FullMethod: "/test/Method"}, handler)
if err == nil {
t.Error("expected authentication error")
}
st, ok := status.FromError(err)
if !ok || st.Code() != codes.Unauthenticated {
t.Errorf("expected Unauthenticated error, got %v", err)
}
}