-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth_handler_test.go
218 lines (193 loc) · 7.48 KB
/
auth_handler_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
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
package aggregadantur_test
import (
"github.com/gorilla/sessions"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/orange-cloudfoundry/aggregadantur/contexes"
"github.com/orange-cloudfoundry/aggregadantur/models"
"github.com/orange-cloudfoundry/aggregadantur/testhelper"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"time"
"github.com/orange-cloudfoundry/aggregadantur"
)
var _ = Describe("AuthHandler", func() {
var aggrRoute *models.AggregateRoute
var upstreamHandler *TestHandler
var packAuth *ServerPack
var respRecorder *httptest.ResponseRecorder
var authHandler *aggregadantur.AuthHandler
var jwtToken string
var store sessions.Store
BeforeEach(func() {
store = sessions.NewCookieStore([]byte("secret"))
var err error
respRecorder = httptest.NewRecorder()
upstreamHandler = NewTestHandlerWithInterface(
models.AggregateEndpoint{
Url: "http://localhost",
Identifier: "test",
},
)
packAuth = NewPack()
scopes := []string{"openid", "admin"}
jwtToken = GenerateJWTToken("user", scopes)
accessResp := aggregadantur.AccessTokenResponse{
AccessToken: jwtToken,
TokenType: "bearer",
ExpiresIn: time.Now().Add(5 * time.Minute).Second(),
Scope: strings.Join(scopes, " "),
}
packAuth.handler.SetInterface(accessResp)
aggrRoute, err = models.NewAggregateRoute(
"test",
"test",
models.NewUpstreamFromHandler(upstreamHandler),
models.AggregateEndpoints{
{
Url: "http://localhost",
Identifier: "test",
},
},
models.Auth{
Includes: models.PathMatchers{models.NewPathMatcher("/**")},
Excludes: models.PathMatchers{models.NewPathMatcher("/metrics")},
Oauth2Auth: models.NewOauth2Auth(
packAuth.HttpServer().URL,
"cf",
"",
[]string{"admin"},
),
JWTCheck: models.JWTChecks{
models.JWTCheck{
Alg: "RS256",
Secret: publicKeyJwt,
Issuer: "http://uaa.localhost",
NotVerifyIssuedAt: false,
},
},
LoginPageTemplate: "",
LoginPageTemplatePath: "",
},
models.PathMatchers{models.NewPathMatcher("/**")},
models.PathMatchers{models.NewPathMatcher("/metrics")},
)
Expect(err).NotTo(HaveOccurred())
authHandler = aggregadantur.NewAuthHandler(upstreamHandler, aggrRoute, http.DefaultClient, store)
})
AfterEach(func() {
packAuth.HttpServer().Close()
})
Context("ServeHTTP", func() {
When("have a options request", func() {
It("should pass as it is to next handler by default", func() {
req := testhelper.NewRequest(http.MethodOptions, "http://localhost", nil)
authHandler.ServeHTTP(respRecorder, req)
res := RespRecordToAggrEndpoint(respRecorder)
Expect(res.Url).To(Equal("http://localhost"))
Expect(res.Identifier).To(Equal("test"))
})
})
When("not match auth", func() {
It("should pass as it is to next handler by default", func() {
req := testhelper.NewRequest(http.MethodGet, "http://localhost/metrics", nil)
authHandler.ServeHTTP(respRecorder, req)
res := RespRecordToAggrEndpoint(respRecorder)
Expect(res.Url).To(Equal("http://localhost"))
Expect(res.Identifier).To(Equal("test"))
})
})
Context("No jwt given", func() {
It("should give the login page on get request", func() {
req := testhelper.NewRequest(http.MethodGet, "http://localhost", nil)
auth := aggrRoute.Auth
auth.LoginPageTemplate = "%s: %s"
aggrRoute.Auth = auth
authHandler.ServeHTTP(respRecorder, req)
Expect(respRecorder.Code).To(Equal(http.StatusUnauthorized))
Expect(respRecorder.Body.String()).To(Equal("Test: /"))
})
When("Post username and password from login page", func() {
It("should set session and redirect if user is correct", func() {
form := url.Values{}
form.Add("username", "user")
form.Add("password", "password")
req := testhelper.NewRequest(http.MethodPost, "http://localhost", strings.NewReader(form.Encode()))
req.Form = form
req.PostForm = form
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
authHandler.ServeHTTP(respRecorder, req)
sess, err := store.Get(req, "auth-test")
Expect(err).ToNot(HaveOccurred())
Expect(sess.Values).To(HaveLen(1))
Expect(sess.Values["jwt_token"]).To(Equal(jwtToken))
Expect(respRecorder.Code).To(Equal(http.StatusTemporaryRedirect))
Expect(respRecorder.Header().Get("Location")).To(Equal("/"))
})
It("should be unauthorized if user is incorrect", func() {
form := url.Values{}
form.Add("username", "user")
form.Add("password", "password")
req := testhelper.NewRequest(http.MethodPost, "http://localhost", strings.NewReader(form.Encode()))
req.Form = form
req.PostForm = form
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
packAuth.handler.SetFn(func(w http.ResponseWriter, req *http.Request) bool {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("user doesn't exists"))
return true
})
authHandler.ServeHTTP(respRecorder, req)
sess, err := store.Get(req, "auth-test")
Expect(err).ToNot(HaveOccurred())
Expect(sess.Values).To(HaveLen(0))
Expect(respRecorder.Code).To(Equal(http.StatusUnauthorized))
})
})
})
Context("Token jwt is given", func() {
It("should pass request and apply headers and contexts in request if token is correct", func() {
req := testhelper.NewRequest(http.MethodGet, "http://localhost", nil)
req.Header.Set("Authorization", "Bearer "+jwtToken)
authHandler.ServeHTTP(respRecorder, req)
res := RespRecordToAggrEndpoint(respRecorder)
Expect(res.Url).To(Equal("http://localhost"))
Expect(res.Identifier).To(Equal("test"))
Expect(req.Header.Get(aggregadantur.XAggregatorUsernameHeader)).To(Equal("user"))
Expect(req.Header.Get(aggregadantur.XAggregatorScopesHeader)).To(Equal("openid,admin"))
Expect(contexes.Username(req)).To(Equal("user"))
Expect(contexes.Scopes(req)).To(ConsistOf("openid", "admin"))
Expect(contexes.JwtClaim(req).Username).To(Equal("user"))
Expect(contexes.JwtClaim(req).Scope).To(ConsistOf("openid", "admin"))
})
It("should unauthorized if token is incorrect", func() {
req := testhelper.NewRequest(http.MethodGet, "http://localhost", nil)
req.Header.Set("Authorization", "Bearer "+jwtToken+"incorrect")
authHandler.ServeHTTP(respRecorder, req)
Expect(respRecorder.Code).To(Equal(http.StatusUnauthorized))
})
When("token is in session", func() {
It("should pass request and apply headers and contexts in request if token is correct", func() {
req := testhelper.NewRequest(http.MethodGet, "http://localhost", nil)
sess, err := store.Get(req, "auth-test")
Expect(err).ToNot(HaveOccurred())
sess.Values["jwt_token"] = jwtToken
err = sess.Save(req, httptest.NewRecorder())
Expect(err).ToNot(HaveOccurred())
authHandler.ServeHTTP(respRecorder, req)
res := RespRecordToAggrEndpoint(respRecorder)
Expect(res.Url).To(Equal("http://localhost"))
Expect(res.Identifier).To(Equal("test"))
Expect(req.Header.Get(aggregadantur.XAggregatorUsernameHeader)).To(Equal("user"))
Expect(req.Header.Get(aggregadantur.XAggregatorScopesHeader)).To(Equal("openid,admin"))
Expect(contexes.Username(req)).To(Equal("user"))
Expect(contexes.Scopes(req)).To(ConsistOf("openid", "admin"))
Expect(contexes.JwtClaim(req).Username).To(Equal("user"))
Expect(contexes.JwtClaim(req).Scope).To(ConsistOf("openid", "admin"))
})
})
})
})
})