-
Notifications
You must be signed in to change notification settings - Fork 214
/
DittoPublicKeyProviderTest.java
210 lines (175 loc) · 10.2 KB
/
DittoPublicKeyProviderTest.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
207
208
209
210
/*
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.ditto.gateway.service.security.authentication.jwt;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import java.time.Duration;
import java.util.Collections;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.eclipse.ditto.gateway.api.GatewayAuthenticationProviderUnavailableException;
import org.eclipse.ditto.gateway.service.util.config.security.OAuthConfig;
import org.eclipse.ditto.internal.utils.cache.config.CacheConfig;
import org.eclipse.ditto.internal.utils.http.HttpClientFacade;
import org.eclipse.ditto.json.JsonArray;
import org.eclipse.ditto.json.JsonObject;
import org.eclipse.ditto.jwt.model.JsonWebKey;
import org.eclipse.ditto.policies.model.SubjectIssuer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import akka.actor.ActorSystem;
import akka.http.javadsl.model.HttpRequest;
import akka.http.javadsl.model.HttpResponse;
import akka.http.javadsl.model.StatusCodes;
@RunWith(MockitoJUnitRunner.class)
public final class DittoPublicKeyProviderTest {
private static final Long LATCH_TIMEOUT = 20L;
private static final HttpRequest DISCOVERY_ENDPOINT_REQUEST =
HttpRequest.GET("https://google.com/.well-known/openid-configuration");
private static final String JWKS_URI = "https://the.uri.com";
private static final HttpRequest PUBLIC_KEYS_REQUEST = HttpRequest.GET(JWKS_URI);
private static final String KEY_ID = "cc34c0a0-bd5a-4a3c-a50d-a2a7db7643df";
private ActorSystem actorSystem;
private PublicKeyProvider underTest;
@Mock
public HttpClientFacade httpClientMock;
@Mock
public CacheConfig cacheConfigMock;
@Mock
public OAuthConfig oauthConfigMock;
@Before
public void setup() {
actorSystem = ActorSystem.create(getClass().getSimpleName());
when(httpClientMock.getActorSystem()).thenReturn(actorSystem);
final JwtSubjectIssuersConfig subjectIssuersConfig = JwtSubjectIssuersConfig.fromJwtSubjectIssuerConfigs(
Collections.singleton(new JwtSubjectIssuerConfig(SubjectIssuer.GOOGLE, "google.com")));
when(cacheConfigMock.getMaximumSize()).thenReturn(100L);
when(cacheConfigMock.getExpireAfterWrite()).thenReturn(Duration.ofMinutes(3));
when(oauthConfigMock.getAllowedClockSkew()).thenReturn(Duration.ofSeconds(1));
underTest = DittoPublicKeyProvider.of(subjectIssuersConfig, httpClientMock, cacheConfigMock,
getClass().getSimpleName(), oauthConfigMock);
}
@After
public void tearDown() {
if (actorSystem != null) {
actorSystem.terminate();
actorSystem = null;
}
}
@Test
public void verifyThatKeyIsCached() throws InterruptedException, TimeoutException, ExecutionException {
mockSuccessfulDiscoveryEndpointRequest();
mockSuccessfulPublicKeysRequest();
final Optional<PublicKeyWithParser> publicKeyFromEndpoint =
underTest.getPublicKeyWithParser("google.com", KEY_ID).get(LATCH_TIMEOUT, TimeUnit.SECONDS);
assertThat(publicKeyFromEndpoint).isNotEmpty();
verify(httpClientMock).createSingleHttpRequest(DISCOVERY_ENDPOINT_REQUEST);
verify(httpClientMock).createSingleHttpRequest(PUBLIC_KEYS_REQUEST);
Mockito.clearInvocations(httpClientMock);
final Optional<PublicKeyWithParser> publicKeyFromCache =
underTest.getPublicKeyWithParser("google.com", KEY_ID).get(LATCH_TIMEOUT, TimeUnit.SECONDS);
assertThat(publicKeyFromCache).contains(publicKeyFromEndpoint.get());
assertThat(publicKeyFromCache).isNotEmpty();
verifyNoMoreInteractions(httpClientMock);
}
@Test
public void verifyThatKeyIsNotCachedOnErrorResponseFromDiscoveryEndpoint() {
mockErrorDiscoveryEndpointRequest();
assertThatExceptionOfType(ExecutionException.class)
.isThrownBy(() -> underTest.getPublicKeyWithParser("google.com", KEY_ID).get(LATCH_TIMEOUT, TimeUnit.SECONDS))
.withCauseExactlyInstanceOf(GatewayAuthenticationProviderUnavailableException.class);
verify(httpClientMock).createSingleHttpRequest(DISCOVERY_ENDPOINT_REQUEST);
verify(httpClientMock, never()).createSingleHttpRequest(PUBLIC_KEYS_REQUEST);
Mockito.clearInvocations(httpClientMock);
assertThatExceptionOfType(ExecutionException.class)
.isThrownBy(() -> underTest.getPublicKeyWithParser("google.com", KEY_ID).get(LATCH_TIMEOUT, TimeUnit.SECONDS))
.withCauseExactlyInstanceOf(GatewayAuthenticationProviderUnavailableException.class);
verify(httpClientMock).createSingleHttpRequest(DISCOVERY_ENDPOINT_REQUEST);
verify(httpClientMock, never()).createSingleHttpRequest(PUBLIC_KEYS_REQUEST);
}
@Test
public void verifyThatKeyIsNotCachedIfResponseDoesNotContainKeyId()
throws InterruptedException, ExecutionException, TimeoutException {
mockSuccessfulDiscoveryEndpointRequest();
mockSuccessfulPublicKeysRequestWithoutMatchingKeyId();
assertThat(underTest.getPublicKeyWithParser("google.com", KEY_ID).get(LATCH_TIMEOUT, TimeUnit.SECONDS)).isEmpty();
verify(httpClientMock).createSingleHttpRequest(DISCOVERY_ENDPOINT_REQUEST);
verify(httpClientMock).createSingleHttpRequest(PUBLIC_KEYS_REQUEST);
Mockito.clearInvocations(httpClientMock);
assertThat(underTest.getPublicKeyWithParser("google.com", KEY_ID).get(LATCH_TIMEOUT, TimeUnit.SECONDS)).isEmpty();
verify(httpClientMock).createSingleHttpRequest(DISCOVERY_ENDPOINT_REQUEST);
verify(httpClientMock).createSingleHttpRequest(PUBLIC_KEYS_REQUEST);
}
private void mockSuccessfulDiscoveryEndpointRequest() {
final JsonObject jwksUriResponse = JsonObject.newBuilder().set("jwks_uri", JWKS_URI).build();
final HttpResponse discoveryEndpointResponse = HttpResponse.create().withStatus(StatusCodes.OK)
.withEntity(jwksUriResponse.toString());
when(httpClientMock.createSingleHttpRequest(DISCOVERY_ENDPOINT_REQUEST))
.thenReturn(CompletableFuture.completedFuture(discoveryEndpointResponse));
}
private void mockErrorDiscoveryEndpointRequest() {
final JsonObject errorBody = JsonObject.newBuilder().set("message", "Something went wrong.").build();
final HttpResponse discoveryEndpointResponse =
HttpResponse.create().withStatus(StatusCodes.SERVICE_UNAVAILABLE).withEntity(errorBody.toString());
when(httpClientMock.createSingleHttpRequest(DISCOVERY_ENDPOINT_REQUEST))
.thenReturn(CompletableFuture.completedFuture(discoveryEndpointResponse));
}
private void mockSuccessfulPublicKeysRequest() {
final JsonObject jsonWebKey = JsonObject.newBuilder()
.set(JsonWebKey.JsonFields.KEY_TYPE, "RSA")
.set(JsonWebKey.JsonFields.KEY_ALGORITHM, "HS256")
.set(JsonWebKey.JsonFields.KEY_USAGE, "sig")
.set(JsonWebKey.JsonFields.KEY_ID, KEY_ID)
.set(JsonWebKey.JsonFields.KEY_MODULUS,
"pjdss8ZaDfEH6K6U7GeW2nxDqR4IP049fk1fK0lndimbMMVBdPv_hSpm8T8EtBDxrUdi1OHZfMhUixGaut-3nQ4GG9nM249oxhCtxqqNvEXrmQRGqczyLxuh-fKn9Fg--hS9UpazHpfVAFnB5aCfXoNhPuI8oByyFKMKaOVgHNqP5NBEqabiLftZD3W_lsFCPGuzr4Vp0YS7zS2hDYScC2oOMu4rGU1LcMZf39p3153Cq7bS2Xh6Y-vw5pwzFYZdjQxDn8x8BG3fJ6j8TGLXQsbKH1218_HcUJRvMwdpbUQG5nvA2GXVqLqdwp054Lzk9_B_f1lVrmOKuHjTNHq48w")
.set(JsonWebKey.JsonFields.KEY_EXPONENT, "AQAB")
.build();
final JsonArray keysArray = JsonArray.newBuilder().add(jsonWebKey).build();
final JsonObject keysJson = JsonObject.newBuilder().set("keys", keysArray).build();
final HttpResponse publicKeysResponse = HttpResponse.create()
.withStatus(StatusCodes.OK)
.withEntity(keysJson.toString());
when(httpClientMock.createSingleHttpRequest(PUBLIC_KEYS_REQUEST))
.thenReturn(CompletableFuture.completedFuture(publicKeysResponse));
}
private void mockSuccessfulPublicKeysRequestWithoutMatchingKeyId() {
final JsonObject jsonWebKey = JsonObject.newBuilder()
.set(JsonWebKey.JsonFields.KEY_TYPE, "RSA")
.set(JsonWebKey.JsonFields.KEY_ALGORITHM, "HS256")
.set(JsonWebKey.JsonFields.KEY_USAGE, "sig")
.set(JsonWebKey.JsonFields.KEY_ID, "anotherId")
.set(JsonWebKey.JsonFields.KEY_MODULUS,
"pjdss8ZaDfEH6K6U7GeW2nxDqR4IP049fk1fK0lndimbMMVBdPv_hSpm8T8EtBDxrUdi1OHZfMhUixGaut-3nQ4GG9nM249oxhCtxqqNvEXrmQRGqczyLxuh-fKn9Fg--hS9UpazHpfVAFnB5aCfXoNhPuI8oByyFKMKaOVgHNqP5NBEqabiLftZD3W_lsFCPGuzr4Vp0YS7zS2hDYScC2oOMu4rGU1LcMZf39p3153Cq7bS2Xh6Y-vw5pwzFYZdjQxDn8x8BG3fJ6j8TGLXQsbKH1218_HcUJRvMwdpbUQG5nvA2GXVqLqdwp054Lzk9_B_f1lVrmOKuHjTNHq48w")
.set(JsonWebKey.JsonFields.KEY_EXPONENT, "AQAB")
.build();
final JsonArray keysArray = JsonArray.newBuilder().add(jsonWebKey).build();
final JsonObject keysJson = JsonObject.newBuilder().set("keys", keysArray).build();
final HttpResponse publicKeysResponse = HttpResponse.create()
.withStatus(StatusCodes.OK)
.withEntity(keysJson.toString());
when(httpClientMock.createSingleHttpRequest(PUBLIC_KEYS_REQUEST))
.thenReturn(CompletableFuture.completedFuture(publicKeysResponse));
}
}