This repository has been archived by the owner on Nov 14, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
elixir_test.go
242 lines (204 loc) · 7.42 KB
/
elixir_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
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"os"
"testing"
"time"
"github.com/golang-jwt/jwt/v4"
"github.com/oauth2-proxy/mockoidc"
log "github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
"golang.org/x/oauth2"
)
type ElixirTests struct {
suite.Suite
TempDir string
ECKeyFile *os.File
RSAKeyFile *os.File
mockServer *mockoidc.MockOIDC
ElixirConfig ElixirConfig
}
func TestElixirTestSuite(t *testing.T) {
suite.Run(t, new(ElixirTests))
}
func (suite *ElixirTests) SetupTest() {
var err error
suite.mockServer, err = mockoidc.Run()
if err != nil {
log.Error(err)
}
// Create a temporary directory for our config file
suite.TempDir, err = os.MkdirTemp(os.TempDir(), "sda-auth-test-")
if err != nil {
log.Fatal("Couldn't create temporary test directory", err)
}
// Create RSA private key file
suite.RSAKeyFile, err = os.CreateTemp(suite.TempDir, "rsakey-")
if err != nil {
log.Fatal("Cannot create temporary rsa key file", err)
}
RSAPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
log.Error("Failed to generate RSA key")
}
var privateKeyBytes = x509.MarshalPKCS1PrivateKey(RSAPrivateKey)
privateKeyBlock := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: privateKeyBytes,
}
err = pem.Encode(suite.RSAKeyFile, privateKeyBlock)
if err != nil {
log.Error("Error writing RSA private key")
}
// Create EC private key file
suite.ECKeyFile, err = os.CreateTemp(suite.TempDir, "eckey-")
if err != nil {
log.Fatal("Cannot create temporary ec key file", err)
}
ECPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
log.Error("Failed to generate EC key")
}
privateKeyBytes, err = x509.MarshalECPrivateKey(ECPrivateKey)
if err != nil {
log.Error("Failed to marshal EC key")
}
privateKeyBlock = &pem.Block{
Type: "EC PRIVATE KEY",
Bytes: privateKeyBytes,
}
err = pem.Encode(suite.ECKeyFile, privateKeyBlock)
if err != nil {
log.Error("Error writing EC private key")
}
// create an elixir config that has the needed endpoints set
suite.ElixirConfig = ElixirConfig{
ID: suite.mockServer.ClientID,
Provider: suite.mockServer.Issuer(),
RedirectURL: "http://redirect",
Secret: suite.mockServer.ClientSecret,
}
}
func (suite *ElixirTests) TearDownTest() {
err := suite.mockServer.Shutdown()
if err != nil {
log.Errorf("Couldn't shut down mock OIDC server: %v", err)
}
}
func (suite *ElixirTests) TestGetOidcClient() {
expectedEndpoint := oauth2.Endpoint{
AuthURL: suite.mockServer.AuthorizationEndpoint(),
TokenURL: suite.mockServer.TokenEndpoint(),
AuthStyle: 0}
oauth2Config, provider := getOidcClient(suite.ElixirConfig)
assert.Equal(suite.T(), suite.mockServer.ClientID, oauth2Config.ClientID, "ClientID was modified when creating the oauth2Config")
assert.Equal(suite.T(), suite.mockServer.ClientSecret, oauth2Config.ClientSecret, "ClientSecret was modified when creating the oauth2Config")
assert.Equal(suite.T(), suite.ElixirConfig.RedirectURL, oauth2Config.RedirectURL, "RedirectURL was modified when creating the oauth2Config")
assert.Equal(suite.T(), expectedEndpoint, oauth2Config.Endpoint, "Issuer was modified when creating the oauth2Config")
assert.Equal(suite.T(), expectedEndpoint, provider.Endpoint(), "provider has the wrong endpoint")
assert.Equal(suite.T(), []string{"openid", "ga4gh_passport_v1 profile email"}, oauth2Config.Scopes, "oauth2Config has the wrong scopes")
}
func (suite *ElixirTests) TestAuthenticateWithOidc() {
// Create a code to authenticate
session, err := suite.mockServer.SessionStore.NewSession(
"openid email profile", "nonce", mockoidc.DefaultUser(), "", "")
if err != nil {
log.Error(err)
}
code := session.SessionID
jwkURL := suite.mockServer.JWKSEndpoint()
oauth2Config, provider := getOidcClient(suite.ElixirConfig)
elixirIdentity, err := authenticateWithOidc(oauth2Config, provider, code, jwkURL)
assert.Nil(suite.T(), err, "Failed to authenticate with OIDC")
assert.NotEqual(suite.T(), "", elixirIdentity.Token, "Empty token returned from OIDC authentication")
}
func (suite *ElixirTests) TestValidateJwt() {
session, err := suite.mockServer.SessionStore.NewSession("openid email profile", "nonce", mockoidc.DefaultUser(), "", "")
if err != nil {
log.Error(err)
}
oauth2Config, provider := getOidcClient(suite.ElixirConfig)
jwkURL := suite.mockServer.JWKSEndpoint()
elixirIdentity, _ := authenticateWithOidc(oauth2Config, provider, session.SessionID, jwkURL)
elixirJWT := elixirIdentity.Token
// Create HS256 test token
mySigningKey := []byte("AllYourBase")
claims := &jwt.RegisteredClaims{
Issuer: "test",
ExpiresAt: jwt.NewNumericDate(time.Now().UTC().Add(time.Hour)),
}
tokenHS256 := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
testTokenHS256, err := tokenHS256.SignedString(mySigningKey)
if err != nil {
log.Error(err)
}
// Create RSA test token
rsaKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
log.Error(err)
}
tokenRSA := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
testTokenRSA, err := tokenRSA.SignedString(rsaKey)
if err != nil {
log.Error(err)
}
// Create ECDSA test token
ecKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
log.Error(err)
}
tokenEC := jwt.NewWithClaims(jwt.SigningMethodES256, claims)
testTokenEC, err := tokenEC.SignedString(ecKey)
if err != nil {
log.Error(err)
}
// Create expired RSA test token
claims.ExpiresAt = jwt.NewNumericDate(time.Now().UTC().Add(-time.Hour))
expiredTokenRSA := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
testExpiredTokenRSA, err := expiredTokenRSA.SignedString(rsaKey)
if err != nil {
log.Error(err)
}
// sanity check
token, expDate, err := validateToken(elixirJWT, suite.mockServer.JWKSEndpoint())
if assert.Nil(suite.T(), err) {
assert.True(suite.T(), token.Valid, "Validation failed but without returning errors")
assert.Equal(suite.T(), expDate, elixirIdentity.ExpDate, "Returned wrong exp date but without returning errors")
}
// wrong jwk url
_, _, err = validateToken(elixirJWT, "http://some/jwk/endpoint")
assert.ErrorContains(suite.T(), err, "failed to fetch remote JWK")
// wrong signing method
_, _, err = validateToken(testTokenHS256, suite.mockServer.JWKSEndpoint())
if assert.Error(suite.T(), err) {
assert.Equal(suite.T(), "unexpected signing method", err.Error())
}
// wrong private key, RSA
_, _, err = validateToken(testTokenRSA, suite.mockServer.JWKSEndpoint())
if assert.Error(suite.T(), err) {
assert.Equal(suite.T(), "signature not valid: crypto/rsa: verification error", err.Error())
}
// wrong private key, ECDSA
_, _, err = validateToken(testTokenEC, suite.mockServer.JWKSEndpoint())
if assert.Error(suite.T(), err) {
assert.Equal(suite.T(), "signature not valid: key is of invalid type", err.Error())
}
// expired token
_, _, err = validateToken(testExpiredTokenRSA, suite.mockServer.JWKSEndpoint())
assert.Equal(suite.T(), "Token is expired", err.Error())
// check that we handle the case where token has no expiration date
claims.ExpiresAt = nil
expiredTokenRSA = jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
testExpiredTokenRSA, err = expiredTokenRSA.SignedString(rsaKey)
if err != nil {
log.Error(err)
}
_, _, err = validateToken(testExpiredTokenRSA, suite.mockServer.JWKSEndpoint())
assert.ErrorContains(suite.T(), err, "signature not valid")
}