-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathoidc_test.go
316 lines (260 loc) · 8.61 KB
/
oidc_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
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
package main
import (
"context"
"crypto/rand"
"crypto/rsa"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"strings"
"testing"
"time"
oidc "github.com/coreos/go-oidc"
"github.com/stretchr/testify/assert"
"golang.org/x/oauth2"
jose "gopkg.in/square/go-jose.v2"
"github.com/uninett/goidc-proxy/conf"
)
var dummyConfig = oauth2.Config{
ClientID: "our-id",
ClientSecret: "some-secret",
Endpoint: oauth2.Endpoint{
AuthURL: "http://oauth.example.com/auth",
TokenURL: "http://oauth.example.com/token",
},
RedirectURL: "http://localhost/oauth2/callback",
Scopes: []string{},
}
var dummyCookie = &http.Cookie{
Name: "test-cookie0",
Value: "dummy-token",
MaxAge: 3600,
Path: "/",
}
var testStateID = "0000-1234-1337-9001"
var stateCookie = &http.Cookie{
Name: "state." + testStateID,
Value: "1234-1234-1234-1234",
MaxAge: 3600,
Path: "/",
}
func testAuthHandler(t *testing.T) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.True(t, true, "Nested handler called")
})
}
func TestAuthHandlerRedirect(t *testing.T) {
auth := &Authenticator{
cookieName: "test-cookie",
signer: NewSigner("test"),
clientConfig: dummyConfig,
}
assert := assert.New(t)
r := httptest.NewRequest("GET", "http://localhost/some_endpoint", nil)
w := httptest.NewRecorder()
ah := auth.authHandler(testAuthHandler(t))
ah.ServeHTTP(w, r)
assert.Equal(http.StatusForbidden, w.Code, "authHandler should return 403 Forbidden")
locBytes, err := ioutil.ReadAll(w.Body)
assert.Nil(err)
loc := string(locBytes[:len(locBytes)])
assert.True(strings.Contains(loc, dummyConfig.Endpoint.AuthURL+"?client_id="+dummyConfig.ClientID), "Redirect to correct URL")
}
type testVerifier struct {
jwk jose.JSONWebKey
}
func (t *testVerifier) VerifySignature(ctx context.Context, jwt string) ([]byte, error) {
jws, err := jose.ParseSigned(jwt)
if err != nil {
return nil, fmt.Errorf("oidc: malformed jwt: %v", err)
}
return jws.Verify(&t.jwk)
}
type signingKey struct {
keyID string // optional
priv interface{}
pub interface{}
alg jose.SignatureAlgorithm
}
// sign creates a JWS using the private key from the provided payload.
func (s *signingKey) sign(t *testing.T, payload []byte) string {
privKey := &jose.JSONWebKey{Key: s.priv, Algorithm: string(s.alg), KeyID: s.keyID}
signer, err := jose.NewSigner(jose.SigningKey{Algorithm: s.alg, Key: privKey}, nil)
if err != nil {
t.Fatal(err)
}
jws, err := signer.Sign(payload)
if err != nil {
t.Fatal(err)
}
data, err := jws.CompactSerialize()
if err != nil {
t.Fatal(err)
}
return data
}
// jwk returns the public part of the signing key.
func (s *signingKey) jwk() jose.JSONWebKey {
return jose.JSONWebKey{Key: s.pub, Use: "sig", Algorithm: string(s.alg), KeyID: s.keyID}
}
func newRSAKey(t *testing.T) *signingKey {
priv, err := rsa.GenerateKey(rand.Reader, 1028)
if err != nil {
t.Fatal(err)
}
return &signingKey{"", priv, priv.Public(), jose.RS256}
}
func createMockIssuer(t *testing.T, issuer string) (*signingKey, *oidc.IDTokenVerifier) {
signKey := newRSAKey(t)
ks := &testVerifier{signKey.jwk()}
return signKey, oidc.NewVerifier(issuer, ks, &oidc.Config{
SkipClientIDCheck: true,
SkipExpiryCheck: true,
})
}
func createMockGroupServer(rawURL string) (error, *httptest.Server) {
parsedURL, err := url.Parse(rawURL)
if err != nil {
return err, nil
}
groupsHost := parsedURL.Host
groupJSON, err := json.Marshal([]Group{Group{"0000-" + rawURL}})
if err != nil {
return fmt.Errorf("Failed to marshal JSON, got error: %s", err), nil
}
l, err := net.Listen("tcp", groupsHost)
if err != nil {
return fmt.Errorf("Failed to listen to: %s! Got error: %s", groupsHost, err), nil
}
groupsServer := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write(groupJSON)
}))
groupsServer.Listener = l
return nil, groupsServer
}
func TestCallbackHandler(t *testing.T) {
err := conf.ReadConfig("goidc_test.json")
if err != nil {
t.Fatalf("Failed to read config file: %s", err)
}
// Create a issuer capable of signing our ID token.
signKey, verifier := createMockIssuer(t, "https://foo")
auth := &Authenticator{
cookieName: "state",
signer: NewSigner("test"),
ctx: context.Background(),
verifier: verifier,
clientConfig: dummyConfig,
}
idToken := `{"iss":"https://foo"}`
idTokenSigned := signKey.sign(t, []byte(idToken))
mockTokenServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(fmt.Sprintf(`{"access_token": "9000000000000000011111111111111111test", "scope": "user", "token_type": "bearer", "expires_in": 86400, "id_token": "%s" }`, idTokenSigned)))
}))
defer mockTokenServer.Close()
auth.clientConfig.Endpoint.TokenURL = mockTokenServer.URL
err, mockGroupsServer := createMockGroupServer(strings.Split(conf.GetStringValue("engine.groups_endpoint"), ",")[0])
if err != nil {
t.Fatal(err)
}
mockGroupsServer.Start()
defer mockGroupsServer.Close()
r := httptest.NewRequest("GET", "http://localhost/oauth2/callback?state="+testStateID+"", nil)
r.AddCookie(stateCookie)
w := httptest.NewRecorder()
ah := auth.callbackHandler()
ah.ServeHTTP(w, r)
assert.Equal(t, http.StatusFound, w.Code, "authHandler should return 302 Found")
}
func TestGroupsGetter(t *testing.T) {
groupURLs := []string{"http://localhost:28765"}
mgroupURLs := []string{"http://localhost:28765", "http://should-not-work.test"}
err, mockGroupsServer := createMockGroupServer(groupURLs[0])
if err != nil {
t.Fatal(err)
}
mockGroupsServer.Start()
defer mockGroupsServer.Close()
mockToken := &oauth2.Token{AccessToken: "test-token"}
groups := getUserGroups(mockToken, groupURLs)
assert.True(t, len(groups) == 1, "wrong number of groups returned")
for _, g := range groups {
assert.True(t, strings.HasPrefix(g, "0000-"), "groups returned incorrectly")
}
groups = getUserGroups(mockToken, mgroupURLs)
assert.True(t, len(groups) == 1, "wrong number of groups returned")
for _, g := range groups {
assert.True(t, strings.HasPrefix(g, "0000-"), "groups returned incorrectly")
}
}
func TestAuthHandlerUnsignedCookieRedirect(t *testing.T) {
auth := &Authenticator{
cookieName: "test-cookie",
signer: NewSigner("test"),
clientConfig: dummyConfig,
}
assert := assert.New(t)
r := httptest.NewRequest("GET", "http://localhost/some_endpoint", nil)
dummyCookie.Value = "dummy-token" + SEP + strconv.FormatInt(time.Now().Unix()+3600, 10)
r.AddCookie(dummyCookie)
w := httptest.NewRecorder()
ah := auth.authHandler(testAuthHandler(t))
ah.ServeHTTP(w, r)
assert.Equal(http.StatusForbidden, w.Code, "authHandler should return 403 Forbidden")
}
func TestAuthHandlerExpiredCookieRedirect(t *testing.T) {
auth := &Authenticator{
cookieName: "test-cookie",
signer: NewSigner("test"),
clientConfig: dummyConfig,
}
assert := assert.New(t)
r := httptest.NewRequest("GET", "http://localhost/some_endpoint", nil)
dummyCookie.Value = auth.signer.getSignedData(
"dummy-token" + SEP + strconv.FormatInt(time.Now().Unix()-3600, 10))
r.AddCookie(dummyCookie)
w := httptest.NewRecorder()
ah := auth.authHandler(testAuthHandler(t))
ah.ServeHTTP(w, r)
assert.Equal(http.StatusForbidden, w.Code, "authHandler should return 403 Forbidden")
}
func TestAuthHandlerBadSignatureCookieRedirect(t *testing.T) {
auth := &Authenticator{
cookieName: "test-cookie",
signer: NewSigner("test"),
clientConfig: dummyConfig,
}
assert := assert.New(t)
r := httptest.NewRequest("GET", "http://localhost/some_endpoint", nil)
dummyCookie.Value = auth.signer.getSignedData(
"dummy-token" + SEP + strconv.FormatInt(time.Now().Unix()+3600, 10))
dummyCookie.Value = dummyCookie.Value + "badsig"
r.AddCookie(dummyCookie)
w := httptest.NewRecorder()
ah := auth.authHandler(testAuthHandler(t))
ah.ServeHTTP(w, r)
assert.Equal(http.StatusForbidden, w.Code, "authHandler should return 403 Forbidden")
}
func TestAuthHandlerCookie(t *testing.T) {
auth := &Authenticator{
cookieName: "test-cookie",
signer: NewSigner("test"),
clientConfig: dummyConfig,
}
assert := assert.New(t)
r := httptest.NewRequest("GET", "http://localhost/some_endpoint", nil)
dummyCookie.Value = auth.signer.getSignedData(
"dummy-token" + SEP + strconv.FormatInt(time.Now().Unix()+3600, 10))
r.AddCookie(dummyCookie)
w := httptest.NewRecorder()
ah := auth.authHandler(testAuthHandler(t))
ah.ServeHTTP(w, r)
assert.Equal(http.StatusOK, w.Code, "authHandler should return 200 OK")
}