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
|
package client
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/golang-jwt/jwt/v4"
"github.com/stretchr/testify/require"
"gitlab.com/gitlab-org/gitaly/v15/internal/testhelper"
)
const secret = "it's a secret"
func TestJWTAuthenticationHeader(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, err := fmt.Fprint(w, r.Header.Get(apiSecretHeaderName))
require.NoError(t, err)
}))
defer server.Close()
tests := []struct {
secret string
method string
}{
{
secret: secret,
method: http.MethodGet,
},
{
secret: secret,
method: http.MethodPost,
},
{
secret: "\n\t " + secret + "\t \n",
method: http.MethodGet,
},
{
secret: "\n \t" + secret + "\n\t ",
method: http.MethodPost,
},
}
for _, tc := range tests {
t.Run(tc.method+" with "+tc.secret, func(t *testing.T) {
gitlabnet := &GitlabNetClient{
httpClient: &HTTPClient{Client: server.Client(), Host: server.URL},
secret: tc.secret,
}
response, err := gitlabnet.DoRequest(testhelper.Context(t), tc.method, "/jwt_auth", nil)
require.NoError(t, err)
require.NotNil(t, response)
defer response.Body.Close()
responseBody, err := io.ReadAll(response.Body)
require.NoError(t, err)
claims := &jwt.RegisteredClaims{}
token, err := jwt.ParseWithClaims(string(responseBody), claims, func(token *jwt.Token) (interface{}, error) {
return []byte(secret), nil
})
require.NoError(t, err)
require.True(t, token.Valid)
require.Equal(t, "gitlab-shell", claims.Issuer)
require.WithinDuration(t, time.Now().Truncate(time.Second), claims.IssuedAt.Time, time.Second)
require.WithinDuration(t, time.Now().Truncate(time.Second).Add(time.Minute), claims.ExpiresAt.Time, time.Second)
})
}
}
|