-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauth_client_test.go
More file actions
177 lines (154 loc) · 4.99 KB
/
auth_client_test.go
File metadata and controls
177 lines (154 loc) · 4.99 KB
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
// SPDX-FileCopyrightText: 2025 Greenbone AG <https://greenbone.net>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
package auth
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestKeycloakClient_GetToken(t *testing.T) {
tests := map[string]struct {
credentials Credentials
responseBody string
responseCode int
wantUrlValues url.Values
wantErr bool
wantToken string
}{
"successful token retrieval (client credentials)": {
credentials: ClientCredentials{ClientID: "test-client-id", ClientSecret: "test-client-secret"},
responseBody: `{"access_token": "test-token", "expires_in": 3600}`,
responseCode: http.StatusOK,
wantUrlValues: url.Values{
"grant_type": {"client_credentials"},
"client_id": {"test-client-id"},
"client_secret": {"test-client-secret"},
},
wantErr: false,
wantToken: "test-token",
},
"successful token retrieval (resource owner credentials)": {
credentials: ResourceOwnerCredentials{ClientID: "test-client-id", Username: "test-user", Password: "test-password"},
responseBody: `{"access_token": "test-token", "expires_in": 3600}`,
responseCode: http.StatusOK,
wantUrlValues: url.Values{
"grant_type": {"password"},
"client_id": {"test-client-id"},
"username": {"test-user"},
"password": {"test-password"},
},
wantErr: false,
wantToken: "test-token",
},
"failed authentication": {
credentials: ClientCredentials{ClientID: "invalid-client-id", ClientSecret: "invalid-client-secret"},
responseBody: `{}`,
responseCode: http.StatusUnauthorized,
wantUrlValues: url.Values{
"grant_type": {"client_credentials"},
"client_id": {"invalid-client-id"},
"client_secret": {"invalid-client-secret"},
},
wantErr: true,
},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
var serverCallCount atomic.Int32
mockServer := httptest.NewServer(http.HandlerFunc(func(
w http.ResponseWriter, r *http.Request,
) {
serverCallCount.Add(1)
// Verify required URL parameters are present
err := r.ParseForm()
require.NoError(t, err)
require.Equal(t, tt.wantUrlValues, r.Form)
w.WriteHeader(tt.responseCode)
_, err = w.Write([]byte(tt.responseBody))
require.NoError(t, err)
}))
defer mockServer.Close()
client := NewKeycloakClient(http.DefaultClient, KeycloakConfig{
AuthURL: mockServer.URL,
// the other fields are also required in real scenario, but omit here for brevity
}, tt.credentials)
gotToken, err := client.GetToken(context.Background())
assert.Greater(t, serverCallCount.Load(), int32(0), "server was not called")
if tt.wantErr {
require.Error(t, err)
} else {
require.NoError(t, err)
assert.Equal(t, tt.wantToken, gotToken)
}
})
}
}
type fakeClock struct {
currentTime time.Time
}
func (fc *fakeClock) Now() time.Time {
return fc.currentTime
}
func (fc *fakeClock) Advance(d time.Duration) {
fc.currentTime = fc.currentTime.Add(d)
}
func NewFakeClock(startTime time.Time) *fakeClock {
return &fakeClock{currentTime: startTime}
}
func TestKeycloakClient_GetToken_Refresh(t *testing.T) {
tokenValidity := 60 * time.Second
kcMockResponse := []byte(fmt.Sprintf(`{"access_token": "test-token", "expires_in": %d}`, int(tokenValidity.Seconds())))
tests := map[string]struct {
responseBody string
responseCode int
requestAfter time.Duration
wantServerCalled int
wantToken string
}{
"token is cached": {
requestAfter: tokenValidity - tokenRefreshMargin - time.Nanosecond,
wantServerCalled: 1, // should be called only once due to caching
wantToken: "test-token",
},
"token expiry handling": {
requestAfter: tokenValidity - tokenRefreshMargin + time.Nanosecond,
wantServerCalled: 2, // should be called twice due to expiry
wantToken: "test-token",
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
fakeClock := NewFakeClock(time.Now())
var serverCallCount atomic.Int32
mockServer := httptest.NewServer(http.HandlerFunc(func(
w http.ResponseWriter, r *http.Request,
) {
serverCallCount.Add(1)
w.WriteHeader(200)
_, err := w.Write(kcMockResponse)
require.NoError(t, err)
}))
defer mockServer.Close()
client := NewKeycloakClient(http.DefaultClient, KeycloakConfig{
AuthURL: mockServer.URL,
// the other fields are also required in real scenario, but omit here for brevity
}, ClientCredentials{})
client.clock = fakeClock
_, err := client.GetToken(context.Background())
require.NoError(t, err)
fakeClock.Advance(tc.requestAfter)
gotToken, err := client.GetToken(context.Background()) // second call to test caching/refresh
require.NoError(t, err)
assert.Equal(t, tc.wantServerCalled, int(serverCallCount.Load()), "unexpected number of server calls")
assert.Equal(t, tc.wantToken, gotToken)
})
}
}