-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
TokenRefreshInterceptorTest.java
206 lines (181 loc) · 9.36 KB
/
TokenRefreshInterceptorTest.java
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
/**
* Copyright (C) 2015 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.fabric8.kubernetes.client.utils;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.ConfigBuilder;
import io.fabric8.kubernetes.client.http.HttpClient;
import io.fabric8.kubernetes.client.http.HttpRequest;
import io.fabric8.kubernetes.client.http.StandardHttpRequest;
import io.fabric8.kubernetes.client.http.TestHttpResponse;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Objects;
import static io.fabric8.kubernetes.client.Config.KUBERNETES_AUTH_SERVICEACCOUNT_TOKEN_FILE_SYSTEM_PROPERTY;
import static io.fabric8.kubernetes.client.Config.KUBERNETES_AUTH_TRYKUBECONFIG_SYSTEM_PROPERTY;
import static io.fabric8.kubernetes.client.Config.KUBERNETES_KUBECONFIG_FILE;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
/**
* Ignoring for now - the token refresh should be based upon the java 11 client or the provided client library and not okhttp
*/
class TokenRefreshInterceptorTest {
@Test
void shouldAutoconfigureAfter401() throws Exception {
try {
// Prepare kubeconfig for autoconfiguration
File tempFile = Files.createTempFile("test", "kubeconfig").toFile();
Files.copy(Objects.requireNonNull(getClass().getResourceAsStream("/token-refresh-interceptor/kubeconfig")),
Paths.get(tempFile.getPath()), StandardCopyOption.REPLACE_EXISTING);
System.setProperty(KUBERNETES_KUBECONFIG_FILE, tempFile.getAbsolutePath());
HttpRequest.Builder builder = Mockito.mock(HttpRequest.Builder.class, Mockito.RETURNS_SELF);
// Call
boolean reissue = new TokenRefreshInterceptor(Config.autoConfigure(null), null, Instant.now())
.afterFailure(builder, new TestHttpResponse<>().withCode(401)).get();
Mockito.verify(builder).setHeader("Authorization", "Bearer token");
assertTrue(reissue);
} finally {
// Remove any side effect
System.clearProperty(KUBERNETES_KUBECONFIG_FILE);
}
}
@Test
void shouldAutoconfigureAfter1Minute() throws Exception {
try {
// Prepare kubeconfig for autoconfiguration
File tempFile = Files.createTempFile("test", "kubeconfig").toFile();
Files.copy(Objects.requireNonNull(getClass().getResourceAsStream("/token-refresh-interceptor/kubeconfig")),
Paths.get(tempFile.getPath()), StandardCopyOption.REPLACE_EXISTING);
System.setProperty(KUBERNETES_KUBECONFIG_FILE, tempFile.getAbsolutePath());
HttpRequest.Builder builder = Mockito.mock(HttpRequest.Builder.class, Mockito.RETURNS_SELF);
// Call
TokenRefreshInterceptor tokenRefreshInterceptor = new TokenRefreshInterceptor(Config.autoConfigure(null),
null,
Instant.now().minus(61, ChronoUnit.SECONDS));
// Replace kubeconfig file
Files.copy(Objects.requireNonNull(getClass().getResourceAsStream("/token-refresh-interceptor/kubeconfig.new")),
Paths.get(tempFile.getPath()), StandardCopyOption.REPLACE_EXISTING);
tokenRefreshInterceptor.before(builder, null);
Mockito.verify(builder).setHeader("Authorization", "Bearer new token");
} finally {
// Remove any side effect
System.clearProperty(KUBERNETES_KUBECONFIG_FILE);
}
}
@Test
@DisplayName("#4442 token auto refresh should not overwrite existing token when not applicable")
void refreshShouldNotOverwriteExistingToken() throws Exception {
// Given
final Config originalConfig = spy(new ConfigBuilder(Config.empty())
.withOauthToken("existing-token")
.build());
final Config autoConfig = new ConfigBuilder(Config.empty())
.withOauthToken("") // empty token
.build();
when(originalConfig.refresh()).thenReturn(autoConfig);
final TokenRefreshInterceptor tokenRefreshInterceptor = new TokenRefreshInterceptor(
originalConfig, null, Instant.now().minusSeconds(61));
// When
final boolean result = tokenRefreshInterceptor
.afterFailure(new StandardHttpRequest.Builder(), new TestHttpResponse<>().withCode(401)).get();
// Then
assertThat(result).isFalse();
assertThat(originalConfig).hasFieldOrPropertyWithValue("oauthToken", "existing-token");
}
@Test
@DisplayName("#4442 token auto refresh should overwrite existing token when applicable")
void refreshShouldOverwriteExistingToken() throws Exception {
// Given
final Config originalConfig = spy(new ConfigBuilder(Config.empty())
.withOauthToken("existing-token")
.build());
final Config autoConfig = new ConfigBuilder(Config.empty())
.withOauthToken("new-token")
.build();
when(originalConfig.refresh()).thenReturn(autoConfig);
final TokenRefreshInterceptor tokenRefreshInterceptor = new TokenRefreshInterceptor(
originalConfig, null, Instant.now().minusSeconds(61));
// When
final boolean result = tokenRefreshInterceptor
.afterFailure(new StandardHttpRequest.Builder(), new TestHttpResponse<>().withCode(401)).get();
// Then
assertThat(result).isTrue();
assertThat(originalConfig).hasFieldOrPropertyWithValue("oauthToken", "new-token");
}
@Test
void shouldReloadInClusterServiceAccount() throws Exception {
try {
// Write service account token file with value "expired" in it,
// Set properties for it to be used instead of kubeconfig.
File tokenFile = Files.createTempFile("test", "token").toFile();
Files.write(tokenFile.toPath(), "expired".getBytes());
System.setProperty(KUBERNETES_AUTH_SERVICEACCOUNT_TOKEN_FILE_SYSTEM_PROPERTY, tokenFile.getAbsolutePath());
System.setProperty(KUBERNETES_AUTH_TRYKUBECONFIG_SYSTEM_PROPERTY, "false");
HttpRequest.Builder builder = Mockito.mock(HttpRequest.Builder.class, Mockito.RETURNS_SELF);
// The expired token will be read at auto configure.
TokenRefreshInterceptor interceptor = new TokenRefreshInterceptor(Config.autoConfigure(null), null, Instant.now());
// Write new value to token file to simulate renewal.
Files.write(tokenFile.toPath(), "renewed".getBytes());
boolean reissue = interceptor.afterFailure(builder, new TestHttpResponse<>().withCode(401)).get();
// Make the call and check that renewed token was read at 401 Unauthorized.
Mockito.verify(builder).setHeader("Authorization", "Bearer renewed");
assertTrue(reissue);
} finally {
// Remove any side effect
System.clearProperty(KUBERNETES_AUTH_SERVICEACCOUNT_TOKEN_FILE_SYSTEM_PROPERTY);
System.clearProperty(KUBERNETES_AUTH_TRYKUBECONFIG_SYSTEM_PROPERTY);
}
}
@Test
void shouldRefreshOIDCToken() throws Exception {
try {
// Prepare kubeconfig for autoconfiguration
File tempFile = Files.createTempFile("test", "kubeconfig").toFile();
Files.copy(Objects.requireNonNull(getClass().getResourceAsStream("/token-refresh-interceptor/kubeconfig-oidc")),
Paths.get(tempFile.getPath()), StandardCopyOption.REPLACE_EXISTING);
System.setProperty(KUBERNETES_KUBECONFIG_FILE, tempFile.getAbsolutePath());
// Prepare HTTP call that will fail with 401 Unauthorized to trigger OIDC token renewal.
HttpRequest.Builder builder = Mockito.mock(HttpRequest.Builder.class, Mockito.RETURNS_SELF);
// Loads the initial kubeconfig, including initial token value.
Config config = Config.autoConfigure(null);
// Copy over new config with following auth provider configuration:
// - refresh-token is set to null to avoid real network connection towards
// OIDC provider. This makes it unnecessary to mock the OIDC HTTP client.
// - id-token to set to "renewed". Since the original id-token at autoconfigure
// had different value, we can be used the new value to assert/observe that
// 401 Unauthorized triggers renewal when OIDC auth provider is used.
Files.copy(Objects.requireNonNull(getClass().getResourceAsStream("/token-refresh-interceptor/kubeconfig-oidc")),
Paths.get(tempFile.getPath()), StandardCopyOption.REPLACE_EXISTING);
TokenRefreshInterceptor interceptor = new TokenRefreshInterceptor(config, Mockito.mock(HttpClient.Factory.class),
Instant.now());
boolean reissue = interceptor.afterFailure(builder, new TestHttpResponse<>().withCode(401)).get();
// Make the call and check that renewed token was read at 401 Unauthorized.
Mockito.verify(builder).setHeader("Authorization", "Bearer renewed");
assertTrue(reissue);
} finally {
// Remove any side effect.
System.clearProperty(KUBERNETES_KUBECONFIG_FILE);
}
}
}