~bigbes/lethe

ref: 1af5bcbe871cc5f262c5c9a1a310d657b4a158d9 lethe/internal/server/auth/middleware_test.go -rw-r--r-- 17.5 KiB
1af5bcbe — Eugene Blikh docs(lethe-web-ui-foundation): import design handoff, add task file a month ago
                                                                                
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
package auth_test

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"github.com/go-chi/chi/v5"

	"sourcecraft.dev/bigbes/lethe/internal/config"
	"sourcecraft.dev/bigbes/lethe/internal/platform/observability"
	"sourcecraft.dev/bigbes/lethe/internal/server/auth"
)

// problem mirrors the apierror.Problem extension fields the tests assert on.
// Decoded into a local type to avoid importing the unexported render plumbing.
type problem struct {
	Status int    `json:"status"`
	Code   string `json:"code"`
	Detail string `json:"detail"`
}

// captureHandler records the Identity it sees on the request context. It
// always responds 200 so a non-200 in the test means the auth chain rejected
// the request before reaching here.
type captureHandler struct {
	called   bool
	identity auth.Identity
	hadID    bool
}

func (c *captureHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	c.called = true
	c.identity, c.hadID = auth.IdentityFrom(r.Context())
	w.WriteHeader(http.StatusOK)
}

// newAuthenticator builds an Authenticator with a working logger and the
// supplied config + verifier, calls Init, and fails the test on Init error.
func newAuthenticator(t *testing.T, cfg config.AuthConfig, v *auth.OIDCVerifier) *auth.Authenticator {
	t.Helper()
	logger := &observability.Logger{Cfg: config.LoggingConfig{Level: "info", Format: "json"}}
	if err := logger.Init(context.Background()); err != nil {
		t.Fatalf("logger.Init: %v", err)
	}
	a := &auth.Authenticator{Cfg: cfg, Log: logger, Verifier: v}
	if err := a.Init(context.Background()); err != nil {
		t.Fatalf("Authenticator.Init: %v", err)
	}
	return a
}

// mountAndServe wires the authenticator under a chi router on /api/v1, then
// dispatches r against it. Returns the recorder and the capture handler so
// the test can assert on both response and resolved identity.
func mountAndServe(a *auth.Authenticator, r *http.Request) (*httptest.ResponseRecorder, *captureHandler) {
	cap := &captureHandler{}
	router := chi.NewRouter()
	router.Route("/api/v1", func(r chi.Router) {
		r.Use(a.Middleware)
		r.Handle("/*", cap)
	})
	rec := httptest.NewRecorder()
	router.ServeHTTP(rec, r)
	return rec, cap
}

// --- Forward-auth path -----------------------------------------------------

func TestForwardAuth_MissingHeader(t *testing.T) {
	a := newAuthenticator(t, config.AuthConfig{
		AllowedUsers: []string{"alice"},
		ForwardAuth:  config.ForwardAuthConfig{Enabled: true, UserHeader: "Remote-User"},
	}, nil)

	rec, cap := mountAndServe(a, httptest.NewRequest(http.MethodGet, "/api/v1/x", nil))
	if rec.Code != http.StatusUnauthorized {
		t.Fatalf("status = %d; want 401", rec.Code)
	}
	if cap.called {
		t.Errorf("handler should not have been called")
	}
}

func TestForwardAuth_HeaderNotInAllowlist(t *testing.T) {
	a := newAuthenticator(t, config.AuthConfig{
		AllowedUsers: []string{"alice"},
		ForwardAuth:  config.ForwardAuthConfig{Enabled: true, UserHeader: "Remote-User"},
	}, nil)

	req := httptest.NewRequest(http.MethodGet, "/api/v1/x", nil)
	req.Header.Set("Remote-User", "mallory")

	rec, cap := mountAndServe(a, req)
	if rec.Code != http.StatusForbidden {
		t.Fatalf("status = %d; want 403", rec.Code)
	}
	if cap.called {
		t.Errorf("handler should not have been called")
	}
}

func TestForwardAuth_HeaderAllowed(t *testing.T) {
	a := newAuthenticator(t, config.AuthConfig{
		AllowedUsers: []string{"alice"},
		ForwardAuth:  config.ForwardAuthConfig{Enabled: true, UserHeader: "Remote-User"},
	}, nil)

	req := httptest.NewRequest(http.MethodGet, "/api/v1/x", nil)
	req.Header.Set("Remote-User", "alice")

	rec, cap := mountAndServe(a, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d; want 200", rec.Code)
	}
	if !cap.called || !cap.hadID {
		t.Fatalf("expected handler called with identity; called=%v hadID=%v", cap.called, cap.hadID)
	}
	if cap.identity.User != "alice" {
		t.Errorf("identity.User = %q; want alice", cap.identity.User)
	}
}

func TestForwardAuth_AllowlistCaseInsensitive(t *testing.T) {
	a := newAuthenticator(t, config.AuthConfig{
		AllowedUsers: []string{"Alice"},
		ForwardAuth:  config.ForwardAuthConfig{Enabled: true, UserHeader: "Remote-User"},
	}, nil)

	req := httptest.NewRequest(http.MethodGet, "/api/v1/x", nil)
	req.Header.Set("Remote-User", "ALICE")

	rec, cap := mountAndServe(a, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d; want 200", rec.Code)
	}
	if cap.identity.User != "alice" {
		t.Errorf("identity.User = %q; want alice (lowercased)", cap.identity.User)
	}
}

func TestForwardAuth_CustomHeaderName(t *testing.T) {
	a := newAuthenticator(t, config.AuthConfig{
		AllowedUsers: []string{"alice"},
		ForwardAuth:  config.ForwardAuthConfig{Enabled: true, UserHeader: "X-Forwarded-User"},
	}, nil)

	req := httptest.NewRequest(http.MethodGet, "/api/v1/x", nil)
	req.Header.Set("X-Forwarded-User", "alice")

	rec, _ := mountAndServe(a, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d; want 200", rec.Code)
	}

	// Default header name should NOT work when a custom one is configured.
	req2 := httptest.NewRequest(http.MethodGet, "/api/v1/x", nil)
	req2.Header.Set("Remote-User", "alice")
	rec2, _ := mountAndServe(a, req2)
	if rec2.Code != http.StatusUnauthorized {
		t.Fatalf("Remote-User leak: status = %d; want 401", rec2.Code)
	}
}

// --- OIDC path -------------------------------------------------------------

func TestOIDC_MissingAuthorization(t *testing.T) {
	o := newOIDCTestServer(t)
	v := o.newVerifier(t, "lethe")
	a := newAuthenticator(t, config.AuthConfig{
		AllowedUsers: []string{"alice"},
		OIDC:         config.OIDCConfig{Enabled: true, Issuer: o.issuer, Audience: "lethe", UsernameClaim: "preferred_username"},
	}, v)

	rec, _ := mountAndServe(a, httptest.NewRequest(http.MethodGet, "/api/v1/x", nil))
	if rec.Code != http.StatusUnauthorized {
		t.Fatalf("status = %d; want 401", rec.Code)
	}
}

func TestOIDC_MalformedBearer(t *testing.T) {
	o := newOIDCTestServer(t)
	v := o.newVerifier(t, "lethe")
	a := newAuthenticator(t, config.AuthConfig{
		AllowedUsers: []string{"alice"},
		OIDC:         config.OIDCConfig{Enabled: true, Issuer: o.issuer, Audience: "lethe", UsernameClaim: "preferred_username"},
	}, v)

	req := httptest.NewRequest(http.MethodGet, "/api/v1/x", nil)
	req.Header.Set("Authorization", "Bearer not-a-jwt")

	rec, _ := mountAndServe(a, req)
	if rec.Code != http.StatusUnauthorized {
		t.Fatalf("status = %d; want 401", rec.Code)
	}
}

func TestOIDC_ValidAndAllowed(t *testing.T) {
	o := newOIDCTestServer(t)
	v := o.newVerifier(t, "lethe")
	a := newAuthenticator(t, config.AuthConfig{
		AllowedUsers: []string{"alice"},
		OIDC:         config.OIDCConfig{Enabled: true, Issuer: o.issuer, Audience: "lethe", UsernameClaim: "preferred_username"},
	}, v)

	tok := o.signToken(t, map[string]any{
		"aud":                "lethe",
		"sub":                "alice-uuid",
		"preferred_username": "alice",
	})
	req := httptest.NewRequest(http.MethodGet, "/api/v1/x", nil)
	req.Header.Set("Authorization", "Bearer "+tok)

	rec, cap := mountAndServe(a, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d; want 200; body=%s", rec.Code, rec.Body.String())
	}
	if cap.identity.User != "alice" {
		t.Errorf("identity.User = %q; want alice", cap.identity.User)
	}
}

func TestOIDC_ValidNotAllowed(t *testing.T) {
	o := newOIDCTestServer(t)
	v := o.newVerifier(t, "lethe")
	a := newAuthenticator(t, config.AuthConfig{
		AllowedUsers: []string{"alice"},
		OIDC:         config.OIDCConfig{Enabled: true, Issuer: o.issuer, Audience: "lethe", UsernameClaim: "preferred_username"},
	}, v)

	tok := o.signToken(t, map[string]any{
		"aud":                "lethe",
		"sub":                "mallory-uuid",
		"preferred_username": "mallory",
	})
	req := httptest.NewRequest(http.MethodGet, "/api/v1/x", nil)
	req.Header.Set("Authorization", "Bearer "+tok)

	rec, _ := mountAndServe(a, req)
	if rec.Code != http.StatusForbidden {
		t.Fatalf("status = %d; want 403", rec.Code)
	}
}

func TestOIDC_Expired(t *testing.T) {
	o := newOIDCTestServer(t)
	v := o.newVerifier(t, "lethe")
	a := newAuthenticator(t, config.AuthConfig{
		AllowedUsers: []string{"alice"},
		OIDC:         config.OIDCConfig{Enabled: true, Issuer: o.issuer, Audience: "lethe", UsernameClaim: "preferred_username"},
	}, v)

	// Expired well past go-oidc's default skew.
	tok := o.signToken(t, map[string]any{
		"aud":                "lethe",
		"sub":                "alice",
		"preferred_username": "alice",
		"iat":                time.Now().Add(-2 * time.Hour).Unix(),
		"exp":                time.Now().Add(-1 * time.Hour).Unix(),
	})
	req := httptest.NewRequest(http.MethodGet, "/api/v1/x", nil)
	req.Header.Set("Authorization", "Bearer "+tok)

	rec, _ := mountAndServe(a, req)
	if rec.Code != http.StatusUnauthorized {
		t.Fatalf("status = %d; want 401", rec.Code)
	}
}

func TestOIDC_WrongAudience(t *testing.T) {
	o := newOIDCTestServer(t)
	v := o.newVerifier(t, "lethe")
	a := newAuthenticator(t, config.AuthConfig{
		AllowedUsers: []string{"alice"},
		OIDC:         config.OIDCConfig{Enabled: true, Issuer: o.issuer, Audience: "lethe", UsernameClaim: "preferred_username"},
	}, v)

	tok := o.signToken(t, map[string]any{
		"aud":                "someone-else",
		"sub":                "alice",
		"preferred_username": "alice",
	})
	req := httptest.NewRequest(http.MethodGet, "/api/v1/x", nil)
	req.Header.Set("Authorization", "Bearer "+tok)

	rec, _ := mountAndServe(a, req)
	if rec.Code != http.StatusUnauthorized {
		t.Fatalf("status = %d; want 401", rec.Code)
	}
}

func TestOIDC_PreferredUsernameClaimUsed(t *testing.T) {
	o := newOIDCTestServer(t)
	v := o.newVerifier(t, "lethe")
	a := newAuthenticator(t, config.AuthConfig{
		AllowedUsers: []string{"alice"},
		OIDC:         config.OIDCConfig{Enabled: true, Issuer: o.issuer, Audience: "lethe", UsernameClaim: "preferred_username"},
	}, v)

	tok := o.signToken(t, map[string]any{
		"aud":                "lethe",
		"sub":                "u-9999",
		"preferred_username": "alice",
	})
	req := httptest.NewRequest(http.MethodGet, "/api/v1/x", nil)
	req.Header.Set("Authorization", "Bearer "+tok)

	rec, cap := mountAndServe(a, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d; want 200", rec.Code)
	}
	if cap.identity.User != "alice" {
		t.Errorf("identity.User = %q; want alice (from preferred_username)", cap.identity.User)
	}
}

func TestOIDC_FallsBackToSubWhenPreferredUsernameAbsent(t *testing.T) {
	o := newOIDCTestServer(t)
	v := o.newVerifier(t, "lethe")
	a := newAuthenticator(t, config.AuthConfig{
		AllowedUsers: []string{"u-9999"},
		OIDC:         config.OIDCConfig{Enabled: true, Issuer: o.issuer, Audience: "lethe", UsernameClaim: "preferred_username"},
	}, v)

	tok := o.signToken(t, map[string]any{
		"aud": "lethe",
		"sub": "u-9999",
		// no preferred_username
	})
	req := httptest.NewRequest(http.MethodGet, "/api/v1/x", nil)
	req.Header.Set("Authorization", "Bearer "+tok)

	rec, cap := mountAndServe(a, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d; want 200; body=%s", rec.Code, rec.Body.String())
	}
	if cap.identity.User != "u-9999" {
		t.Errorf("identity.User = %q; want u-9999 (from sub fallback)", cap.identity.User)
	}
}

// --- Both enabled ---------------------------------------------------------

func TestBoth_BearerWinsOverHeader(t *testing.T) {
	o := newOIDCTestServer(t)
	v := o.newVerifier(t, "lethe")
	a := newAuthenticator(t, config.AuthConfig{
		AllowedUsers: []string{"alice", "bob"},
		ForwardAuth:  config.ForwardAuthConfig{Enabled: true, UserHeader: "Remote-User"},
		OIDC:         config.OIDCConfig{Enabled: true, Issuer: o.issuer, Audience: "lethe", UsernameClaim: "preferred_username"},
	}, v)

	tok := o.signToken(t, map[string]any{
		"aud":                "lethe",
		"sub":                "alice",
		"preferred_username": "alice",
	})
	req := httptest.NewRequest(http.MethodGet, "/api/v1/x", nil)
	req.Header.Set("Authorization", "Bearer "+tok)
	req.Header.Set("Remote-User", "bob")

	rec, cap := mountAndServe(a, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d; want 200", rec.Code)
	}
	if cap.identity.User != "alice" {
		t.Errorf("identity.User = %q; want alice (from JWT, not header)", cap.identity.User)
	}
}

func TestBoth_BearerInvalidWithHeader_FailsClosed(t *testing.T) {
	o := newOIDCTestServer(t)
	v := o.newVerifier(t, "lethe")
	a := newAuthenticator(t, config.AuthConfig{
		AllowedUsers: []string{"alice"},
		ForwardAuth:  config.ForwardAuthConfig{Enabled: true, UserHeader: "Remote-User"},
		OIDC:         config.OIDCConfig{Enabled: true, Issuer: o.issuer, Audience: "lethe", UsernameClaim: "preferred_username"},
	}, v)

	req := httptest.NewRequest(http.MethodGet, "/api/v1/x", nil)
	req.Header.Set("Authorization", "Bearer not-a-jwt")
	req.Header.Set("Remote-User", "alice")

	rec, cap := mountAndServe(a, req)
	if rec.Code != http.StatusUnauthorized {
		t.Fatalf("status = %d; want 401 (no fallback to header)", rec.Code)
	}
	if cap.called {
		t.Errorf("handler should not have been called when bearer was invalid")
	}
}

func TestBoth_AbsentBearerAndHeader(t *testing.T) {
	o := newOIDCTestServer(t)
	v := o.newVerifier(t, "lethe")
	a := newAuthenticator(t, config.AuthConfig{
		AllowedUsers: []string{"alice"},
		ForwardAuth:  config.ForwardAuthConfig{Enabled: true, UserHeader: "Remote-User"},
		OIDC:         config.OIDCConfig{Enabled: true, Issuer: o.issuer, Audience: "lethe", UsernameClaim: "preferred_username"},
	}, v)

	rec, _ := mountAndServe(a, httptest.NewRequest(http.MethodGet, "/api/v1/x", nil))
	if rec.Code != http.StatusUnauthorized {
		t.Fatalf("status = %d; want 401", rec.Code)
	}
}

// --- Admin flag -----------------------------------------------------------

func TestAdmin_AdminUserHasIsAdminTrue(t *testing.T) {
	a := newAuthenticator(t, config.AuthConfig{
		AllowedUsers: []string{"alice", "bob"},
		Admins:       []string{"alice"},
		ForwardAuth:  config.ForwardAuthConfig{Enabled: true, UserHeader: "Remote-User"},
	}, nil)

	req := httptest.NewRequest(http.MethodGet, "/api/v1/x", nil)
	req.Header.Set("Remote-User", "alice")

	_, cap := mountAndServe(a, req)
	if !cap.identity.IsAdmin {
		t.Errorf("IsAdmin = false; want true for alice")
	}
}

func TestAdmin_NonAdminHasIsAdminFalse(t *testing.T) {
	a := newAuthenticator(t, config.AuthConfig{
		AllowedUsers: []string{"alice", "bob"},
		Admins:       []string{"alice"},
		ForwardAuth:  config.ForwardAuthConfig{Enabled: true, UserHeader: "Remote-User"},
	}, nil)

	req := httptest.NewRequest(http.MethodGet, "/api/v1/x", nil)
	req.Header.Set("Remote-User", "bob")

	_, cap := mountAndServe(a, req)
	if cap.identity.IsAdmin {
		t.Errorf("IsAdmin = true; want false for bob")
	}
}

// --- Problem JSON shape ---------------------------------------------------

func TestProblemShape_401(t *testing.T) {
	a := newAuthenticator(t, config.AuthConfig{
		AllowedUsers: []string{"alice"},
		ForwardAuth:  config.ForwardAuthConfig{Enabled: true, UserHeader: "Remote-User"},
	}, nil)

	rec, _ := mountAndServe(a, httptest.NewRequest(http.MethodGet, "/api/v1/x", nil))
	if rec.Code != http.StatusUnauthorized {
		t.Fatalf("status = %d; want 401", rec.Code)
	}
	if got := rec.Header().Get("Content-Type"); got != "application/problem+json" {
		t.Errorf("Content-Type = %q; want application/problem+json", got)
	}
	var p problem
	if err := json.Unmarshal(rec.Body.Bytes(), &p); err != nil {
		t.Fatalf("decode body: %v; body=%s", err, rec.Body.String())
	}
	if p.Status != http.StatusUnauthorized {
		t.Errorf("body.status = %d; want 401", p.Status)
	}
	if p.Code != "UNAUTHORIZED" {
		t.Errorf("body.code = %q; want UNAUTHORIZED", p.Code)
	}
}

func TestProblemShape_403(t *testing.T) {
	a := newAuthenticator(t, config.AuthConfig{
		AllowedUsers: []string{"alice"},
		ForwardAuth:  config.ForwardAuthConfig{Enabled: true, UserHeader: "Remote-User"},
	}, nil)

	req := httptest.NewRequest(http.MethodGet, "/api/v1/x", nil)
	req.Header.Set("Remote-User", "mallory")

	rec, _ := mountAndServe(a, req)
	if rec.Code != http.StatusForbidden {
		t.Fatalf("status = %d; want 403", rec.Code)
	}
	if got := rec.Header().Get("Content-Type"); got != "application/problem+json" {
		t.Errorf("Content-Type = %q; want application/problem+json", got)
	}
	var p problem
	if err := json.Unmarshal(rec.Body.Bytes(), &p); err != nil {
		t.Fatalf("decode body: %v; body=%s", err, rec.Body.String())
	}
	if p.Status != http.StatusForbidden {
		t.Errorf("body.status = %d; want 403", p.Status)
	}
	if p.Code != "FORBIDDEN" {
		t.Errorf("body.code = %q; want FORBIDDEN", p.Code)
	}
}

// --- Init invariants ------------------------------------------------------

func TestInit_OIDCEnabledWithoutVerifier(t *testing.T) {
	logger := &observability.Logger{Cfg: config.LoggingConfig{Level: "info", Format: "json"}}
	if err := logger.Init(context.Background()); err != nil {
		t.Fatalf("logger.Init: %v", err)
	}
	a := &auth.Authenticator{
		Cfg: config.AuthConfig{
			AllowedUsers: []string{"alice"},
			OIDC:         config.OIDCConfig{Enabled: true, Issuer: "https://example.invalid", Audience: "lethe", UsernameClaim: "preferred_username"},
		},
		Log:      logger,
		Verifier: nil,
	}
	err := a.Init(context.Background())
	if err == nil {
		t.Fatalf("Init: expected error when OIDC enabled without verifier")
	}
}

func TestInit_ForwardAuthEnabledWithoutHeader(t *testing.T) {
	logger := &observability.Logger{Cfg: config.LoggingConfig{Level: "info", Format: "json"}}
	if err := logger.Init(context.Background()); err != nil {
		t.Fatalf("logger.Init: %v", err)
	}
	a := &auth.Authenticator{
		Cfg: config.AuthConfig{
			AllowedUsers: []string{"alice"},
			ForwardAuth:  config.ForwardAuthConfig{Enabled: true, UserHeader: ""},
		},
		Log: logger,
	}
	err := a.Init(context.Background())
	if err == nil {
		t.Fatalf("Init: expected error when forward-auth enabled without user_header")
	}
}