-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathauthenticator_test.go
107 lines (86 loc) · 2.55 KB
/
authenticator_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
package main_test
import (
"context"
"net/http"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"go.uber.org/mock/gomock"
"k8s.io/apiserver/pkg/authentication/authenticator"
namespacelister "github.com/konflux-ci/namespace-lister"
"github.com/konflux-ci/namespace-lister/mocks"
)
var _ = Describe("Authenticator", func() {
var (
ctrl *gomock.Controller
auth authenticator.Request
c *mocks.MockFakeInterface
)
userHeaderKey := "X-User-Header"
userHeaderValue := "my-user"
BeforeEach(func(ctx context.Context) {
ctrl = gomock.NewController(GinkgoT())
})
When("Header authentication is enabled", func() {
BeforeEach(func() {
// given
c = mocks.NewMockFakeInterface(ctrl)
a, err := namespacelister.NewAuthenticator(namespacelister.AuthenticatorOptions{
Client: c,
Header: userHeaderKey,
})
Expect(err).NotTo(HaveOccurred())
auth = a
})
It("returns user info from header", func(ctx context.Context) {
// given
r, err := http.NewRequestWithContext(ctx, http.MethodGet, "/", nil)
Expect(err).NotTo(HaveOccurred())
r.Header.Add(userHeaderKey, userHeaderValue)
// when
rs, ok, err := auth.AuthenticateRequest(r)
// then
Expect(err).NotTo(HaveOccurred())
Expect(ok).To(BeTrue())
Expect(rs).NotTo(BeNil())
Expect(rs.User).NotTo(BeNil())
Expect(rs.User.GetName()).To(BeEquivalentTo(userHeaderValue))
})
})
When("Header authentication is disabled", func() {
BeforeEach(func() {
// given
c = mocks.NewMockFakeInterface(ctrl)
a, err := namespacelister.NewAuthenticator(namespacelister.AuthenticatorOptions{
Client: c,
})
Expect(err).NotTo(HaveOccurred())
auth = a
})
It("ignores user info from header", func(ctx context.Context) {
// given
r, err := http.NewRequestWithContext(ctx, http.MethodGet, "/", nil)
Expect(err).NotTo(HaveOccurred())
r.Header.Add(userHeaderKey, userHeaderValue)
// when
rs, ok, err := auth.AuthenticateRequest(r)
// then
Expect(err).NotTo(HaveOccurred())
Expect(ok).To(BeFalse())
Expect(rs).To(BeNil())
})
It("tries to validate the bearer token", func(ctx context.Context) {
// we expect the TokenReview API to be used to validate the token
c.EXPECT().Post().Times(1)
// given
r, err := http.NewRequestWithContext(ctx, http.MethodGet, "/", nil)
Expect(err).NotTo(HaveOccurred())
r.Header.Add("Authorization", "Bearer invalid")
// when
rs, ok, err := auth.AuthenticateRequest(r)
// then
Expect(err).To(HaveOccurred())
Expect(ok).To(BeFalse())
Expect(rs).To(BeNil())
})
})
})