-
Notifications
You must be signed in to change notification settings - Fork 214
/
ClientCredentialsFlowTest.java
205 lines (172 loc) · 8.61 KB
/
ClientCredentialsFlowTest.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
/*
* Copyright (c) 2021 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.connectivity.service.messaging.httppush;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import org.assertj.core.api.Condition;
import org.eclipse.ditto.connectivity.service.messaging.monitoring.ConnectionMonitor;
import org.eclipse.ditto.connectivity.service.messaging.monitoring.logs.InfoProviderFactory;
import org.eclipse.ditto.internal.utils.cache.Cache;
import org.eclipse.ditto.internal.utils.cache.CacheFactory;
import org.eclipse.ditto.internal.utils.cache.config.DefaultCacheConfig;
import org.eclipse.ditto.jwt.model.JsonWebToken;
import org.eclipse.ditto.jwt.model.JwtInvalidException;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
import com.github.benmanes.caffeine.cache.AsyncCacheLoader;
import com.typesafe.config.ConfigFactory;
import org.apache.pekko.NotUsed;
import org.apache.pekko.actor.ActorSystem;
import org.apache.pekko.http.javadsl.model.HttpHeader;
import org.apache.pekko.http.javadsl.model.HttpMethods;
import org.apache.pekko.http.javadsl.model.HttpRequest;
import org.apache.pekko.http.javadsl.model.HttpResponse;
import org.apache.pekko.japi.Pair;
import org.apache.pekko.stream.javadsl.Flow;
import org.apache.pekko.stream.javadsl.Sink;
import org.apache.pekko.stream.javadsl.Source;
import org.apache.pekko.testkit.javadsl.TestKit;
import scala.util.Try;
/**
* Tests {@link ClientCredentialsFlow}.
*/
public final class ClientCredentialsFlowTest {
private static final Duration DEFAULT_TOKEN_TTL = Duration.ofSeconds(10);
private static final DefaultCacheConfig CACHE_CONFIG = DefaultCacheConfig.of(ConfigFactory.parseMap(Map.of(
"cache.maximum-size", "1")), "cache");
private static final HttpPushContext PUSH_CONTEXT = new TestHttpPushContext();
private static final HttpRequest HTTP_REQUEST = HttpRequest.create().withMethod(HttpMethods.GET);
private static ActorSystem actorSystem;
private Flow<Pair<HttpRequest, HttpPushContext>, Pair<HttpRequest, HttpPushContext>, NotUsed> credentialsFlow;
private AtomicLong asyncLoadCounter;
@BeforeClass
public static void setUp() {
actorSystem = ActorSystem.create("AkkaTestSystem");
}
@Before
public void init() throws Exception {
asyncLoadCounter = new AtomicLong();
final ClientCredentialsFlow underTest = initClientCredentialsFlow(DEFAULT_TOKEN_TTL, Duration.ZERO);
credentialsFlow = underTest.getFlow();
}
private ClientCredentialsFlow initClientCredentialsFlow(final Duration tokenTtl, final Duration maxClockSkew) {
final Flow<HttpRequest, Try<HttpResponse>, NotUsed> flow =
TokenFlowFactory.getFlow(tokenTtl).wireTap(t -> asyncLoadCounter.incrementAndGet());
final AsyncCacheLoader<String, JsonWebToken>
asyncJwtLoader = new AsyncJwtLoader(actorSystem, flow, TokenFlowFactory.CREDENTIALS);
final ClientCredentialsFlowVisitor.JsonWebTokenExpiry jsonWebTokenExpiry =
ClientCredentialsFlowVisitor.JsonWebTokenExpiry.of(maxClockSkew);
final Cache<String, JsonWebToken> cache =
CacheFactory.createCache(asyncJwtLoader, jsonWebTokenExpiry, CACHE_CONFIG, "token-cache",
actorSystem.getDispatcher());
return ClientCredentialsFlow.of(cache);
}
@AfterClass
public static void tearDown() {
if (actorSystem != null) {
TestKit.shutdownActorSystem(actorSystem);
}
}
@Test
public void sendRequest() {
final CompletionStage<Pair<HttpRequest, HttpPushContext>> resultFuture =
Source.single(Pair.create(HTTP_REQUEST, PUSH_CONTEXT))
.via(credentialsFlow)
.runWith(Sink.head(), actorSystem);
final Pair<HttpRequest, HttpPushContext> result = resultFuture.toCompletableFuture().join();
assertThat(result.first().getHeaders()).haveExactly(1,
new Condition<>(h -> "Authorization".equals(h.name()) && h.value().startsWith("Bearer"),
"contains bearer token"));
}
@Test
public void reuseToken() {
// no token requested before first request is processed
assertThat(asyncLoadCounter).hasValue(0);
final CompletionStage<List<Pair<HttpRequest, HttpPushContext>>> resultFuture =
Source.repeat(Pair.create(HTTP_REQUEST, PUSH_CONTEXT))
.take(5)
.via(credentialsFlow)
.runWith(Sink.seq(), actorSystem);
final List<Pair<HttpRequest, HttpPushContext>> result = resultFuture.toCompletableFuture().join();
assertThat(result).hasSize(5);
final HttpHeader expectedHeader =
result.get(0).first().getHeader("Authorization").orElseThrow();
assertThat(result).allSatisfy(
pair -> assertThat(pair.first().getHeader("Authorization")).contains(expectedHeader));
// 1 token was requested for multiple requests within expiration time
assertThat(asyncLoadCounter).hasValue(1);
}
@Test
public void testTokenExpiry() {
final Duration tokenTtl = Duration.ofSeconds(2);
final ClientCredentialsFlow clientCredentialsFlow = initClientCredentialsFlow(tokenTtl, Duration.ZERO);
// make 10 requests with delay of 300 milliseconds
final int tokens = 10;
final CompletionStage<List<Pair<HttpRequest, HttpPushContext>>> resultFuture =
Source.repeat(Pair.create(HTTP_REQUEST, PUSH_CONTEXT))
.take(tokens)
.via(clientCredentialsFlow.getFlow())
.throttle(1, Duration.ofMillis(300))
.runWith(Sink.seq(), actorSystem);
final List<Pair<HttpRequest, HttpPushContext>> result = resultFuture.toCompletableFuture().join();
assertThat(result).hasSize(tokens);
final Map<String, List<Pair<HttpRequest, HttpPushContext>>> requestsGroupedByToken = result.stream()
.collect(Collectors.groupingBy(
p -> p.first().getHeader("Authorization").map(HttpHeader::value).orElseThrow()));
// verification is fuzzy because of timing issues
// expect max. 3 requested tokens within 3 seconds (max. 2 reloads within 3 seconds with exp. time of 2
// seconds + 1 requested for the initial load)
assertThat(asyncLoadCounter).hasValueBetween(2, 3);
assertThat(requestsGroupedByToken).hasSizeBetween(2, 3);
}
@Test
public void testCacheReturnsEmptyOptional() {
final Cache<String, JsonWebToken> emptyCache = Mockito.mock(Cache.class);
when(emptyCache.get(any())).thenReturn(CompletableFuture.completedFuture(Optional.empty()));
final Flow<Pair<HttpRequest, HttpPushContext>, Pair<HttpRequest, HttpPushContext>, NotUsed>
emptyCredentialsFlow =
ClientCredentialsFlow.of(emptyCache).getFlow();
final CompletionStage<Pair<HttpRequest, HttpPushContext>> resultFuture =
Source.repeat(Pair.create(HTTP_REQUEST, PUSH_CONTEXT))
.take(5)
.via(emptyCredentialsFlow)
.runWith(Sink.head(), actorSystem);
assertThatExceptionOfType(CompletionException.class)
.isThrownBy(resultFuture.toCompletableFuture()::join)
.withCauseInstanceOf(JwtInvalidException.class);
}
private static class TestHttpPushContext implements HttpPushContext {
@Override
public ConnectionMonitor.InfoProvider getInfoProvider() {
return InfoProviderFactory.empty();
}
@Override
public void onResponse(final Try<HttpResponse> response) {
// no-op
}
}
}