-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth_test.go
76 lines (61 loc) · 2.2 KB
/
auth_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
package main_test
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/coreos/go-oidc/v3/oidc"
guard "github.com/equinor/radix-oauth-guard"
"github.com/stretchr/testify/assert"
)
type FakeVerifier func(ctx context.Context, rawIDToken string) (*oidc.IDToken, error)
func (f FakeVerifier) Verify(ctx context.Context, rawIDToken string) (*oidc.IDToken, error) {
return f(ctx, rawIDToken)
}
func TestAuthHandler(t *testing.T) {
handler := guard.AuthHandler([]string{"radix1", "radix2"}, FakeVerifier(func(_ context.Context, _ string) (*oidc.IDToken, error) {
return &oidc.IDToken{
Subject: "radix1",
}, nil
}))
writer := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/auth", nil)
req.Header.Set("Authorization", "Bearer abcd.abcd.abcd")
handler.ServeHTTP(writer, req)
assert.Equal(t, http.StatusOK, writer.Code)
assert.Equal(t, `OK`, writer.Body.String())
}
func TestMissingAuthHeaderFails(t *testing.T) {
handler := guard.AuthHandler([]string{"radix1", "radix2"}, FakeVerifier(func(_ context.Context, _ string) (*oidc.IDToken, error) {
return &oidc.IDToken{
Subject: "radix-fake",
}, nil
}))
writer := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/auth", nil)
handler.ServeHTTP(writer, req)
assert.Equal(t, http.StatusUnauthorized, writer.Code)
}
func TestAuthFailureFails(t *testing.T) {
handler := guard.AuthHandler([]string{"radix1", "radix2"}, FakeVerifier(func(_ context.Context, _ string) (*oidc.IDToken, error) {
return nil, errors.New("some error")
}))
writer := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/auth", nil)
req.Header.Set("Authorization", "Bearer abcdabcd")
handler.ServeHTTP(writer, req)
assert.Equal(t, http.StatusUnauthorized, writer.Code)
}
func TestInvalidJWTFails(t *testing.T) {
handler := guard.AuthHandler([]string{"radix1", "radix2"}, FakeVerifier(func(_ context.Context, _ string) (*oidc.IDToken, error) {
return &oidc.IDToken{
Subject: "radix-fail",
}, nil
}))
writer := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/auth", nil)
req.Header.Set("Authorization", "Bearer abcd.abcd.abcd")
handler.ServeHTTP(writer, req)
assert.Equal(t, http.StatusForbidden, writer.Code)
}