-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathV2PayloadHandler.java
More file actions
232 lines (190 loc) · 9.04 KB
/
V2PayloadHandler.java
File metadata and controls
232 lines (190 loc) · 9.04 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
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package com.uid2.operator.vertx;
import com.uid2.operator.model.IdentityScope;
import com.uid2.operator.model.KeyManager;
import com.uid2.operator.monitoring.TokenResponseStatsCollector;
import com.uid2.operator.service.EncodingUtils;
import com.uid2.operator.service.ResponseUtil;
import com.uid2.operator.service.V2RequestUtil;
import com.uid2.shared.InstantClock;
import com.uid2.shared.Utils;
import com.uid2.shared.auth.ClientKey;
import com.uid2.shared.encryption.AesGcm;
import com.uid2.shared.middleware.AuthMiddleware;
import com.uid2.shared.store.ISiteStore;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import org.slf4j.LoggerFactory;
import java.nio.charset.StandardCharsets;
import java.util.function.Function;
import static com.uid2.operator.service.ResponseUtil.SendClientErrorResponseAndRecordStats;
public class V2PayloadHandler {
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(V2PayloadHandler.class);
private KeyManager keyManager;
private Boolean enableEncryption;
private IdentityScope identityScope;
private ISiteStore siteProvider;
public V2PayloadHandler(KeyManager keyManager, Boolean enableEncryption, IdentityScope identityScope, ISiteStore siteProvider) {
this.keyManager = keyManager;
this.enableEncryption = enableEncryption;
this.identityScope = identityScope;
this.siteProvider = siteProvider;
}
public void handle(RoutingContext rc, Handler<RoutingContext> apiHandler) {
if (!enableEncryption) {
passThrough(rc, apiHandler);
return;
}
V2RequestUtil.V2Request request = V2RequestUtil.parseRequest(rc.body().asString(), AuthMiddleware.getAuthClient(ClientKey.class, rc), new InstantClock());
if (!request.isValid()) {
ResponseUtil.LogInfoAndSend400Response(rc, request.errorMessage);
return;
}
rc.data().put("request", request.payload);
apiHandler.handle(rc);
handleResponse(rc, request);
}
public void handleNonBlocking(Vertx vertx, RoutingContext rc, Handler<RoutingContext> apiHandler) {
vertx.executeBlocking(
blockingPromise -> {
V2RequestUtil.V2Request request = V2RequestUtil.parseRequest(rc.body().asString(), AuthMiddleware.getAuthClient(ClientKey.class, rc), new InstantClock());
if (!request.isValid()) {
ResponseUtil.LogInfoAndSend400Response(rc, request.errorMessage);
blockingPromise.complete();
return;
}
rc.data().put("request", request.payload);
apiHandler.handle(rc);
handleResponse(rc, request);
blockingPromise.complete(request);
},
false,
blockingResult -> {
if (blockingResult.failed()) {
ResponseUtil.LogErrorAndSendResponse(ResponseUtil.ResponseStatus.GenericError, 500, rc, "");
}
});
}
public void handleAsync(RoutingContext rc, Function<RoutingContext, Future> apiHandler) {
if (!enableEncryption) {
apiHandler.apply(rc);
return;
}
V2RequestUtil.V2Request request = V2RequestUtil.parseRequest(rc.body().asString(), AuthMiddleware.getAuthClient(ClientKey.class, rc), new InstantClock());
if (!request.isValid()) {
ResponseUtil.LogInfoAndSend400Response(rc, request.errorMessage);
return;
}
rc.data().put("request", request.payload);
apiHandler.apply(rc).onComplete(ar -> {
handleResponse(rc, request);
});
}
public void handleTokenGenerate(RoutingContext rc, Handler<RoutingContext> apiHandler) {
if (!enableEncryption) {
passThrough(rc, apiHandler);
return;
}
V2RequestUtil.V2Request request = V2RequestUtil.parseRequest(rc.body().asString(), AuthMiddleware.getAuthClient(ClientKey.class, rc), new InstantClock());
if (!request.isValid()) {
SendClientErrorResponseAndRecordStats(ResponseUtil.ResponseStatus.ClientError, 400, rc, request.errorMessage, null, TokenResponseStatsCollector.Endpoint.GenerateV2, TokenResponseStatsCollector.ResponseStatus.BadPayload, siteProvider, TokenResponseStatsCollector.PlatformType.Other);
return;
}
rc.data().put("request", request.payload);
apiHandler.handle(rc);
if (rc.response().getStatusCode() != 200) {
return;
}
try {
JsonObject respJson = (JsonObject) rc.data().get("response");
// DevNote: 200 does not guarantee a token.
if (respJson.getString("status").equals(ResponseUtil.ResponseStatus.Success) && respJson.containsKey("body")) {
V2RequestUtil.handleRefreshTokenInResponseBody(respJson.getJsonObject("body"), this.keyManager, this.identityScope);
}
writeResponse(rc, request.nonce, respJson, request.encryptionKey);
}
catch (Exception ex){
LOGGER.error("Failed to generate token", ex);
ResponseUtil.LogErrorAndSendResponse(ResponseUtil.ResponseStatus.GenericError, 500, rc, "");
}
}
public void handleTokenRefresh(RoutingContext rc, Handler<RoutingContext> apiHandler) {
if (!enableEncryption) {
passThrough(rc, apiHandler);
return;
}
String bodyString = rc.body().asString();
V2RequestUtil.V2Request request = null;
if (bodyString != null && bodyString.length() == V2RequestUtil.V2_REFRESH_PAYLOAD_LENGTH) {
request = V2RequestUtil.parseRefreshRequest(bodyString, this.keyManager);
if (!request.isValid()) {
SendClientErrorResponseAndRecordStats(ResponseUtil.ResponseStatus.ClientError, 400, rc, request.errorMessage, null, TokenResponseStatsCollector.Endpoint.RefreshV2, TokenResponseStatsCollector.ResponseStatus.BadPayload, siteProvider, TokenResponseStatsCollector.PlatformType.Other);
return;
}
rc.data().put("request", request.payload);
}
else {
rc.data().put("request", bodyString);
}
apiHandler.handle(rc);
if (rc.response().getStatusCode() != 200) {
return;
}
try {
JsonObject respJson = (JsonObject) rc.data().get("response");
JsonObject bodyJson = respJson.getJsonObject("body");
if (bodyJson != null)
V2RequestUtil.handleRefreshTokenInResponseBody(bodyJson, this.keyManager, this.identityScope);
if (request != null) {
rc.response().putHeader(HttpHeaders.CONTENT_TYPE, "text/plain");
// Encrypt whole payload using key shared with client.
byte[] encryptedResp = AesGcm.encrypt(
respJson.encode().getBytes(StandardCharsets.UTF_8),
request.encryptionKey);
rc.response().end(Utils.toBase64String(encryptedResp));
}
else {
rc.response().putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.end(respJson.encode());
}
}
catch (Exception ex){
LOGGER.error("Failed to refresh token", ex);
ResponseUtil.LogErrorAndSendResponse(ResponseUtil.ResponseStatus.GenericError, 500, rc, "");
}
}
private void passThrough(RoutingContext rc, Handler<RoutingContext> apiHandler) {
rc.data().put("request", rc.body().asJsonObject());
apiHandler.handle(rc);
if (rc.response().getStatusCode() != 200) {
return;
}
JsonObject respJson = (JsonObject) rc.data().get("response");
rc.response().putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.end(respJson.encode());
}
private void writeResponse(RoutingContext rc, byte[] nonce, JsonObject resp, byte[] keyBytes) {
Buffer buffer = Buffer.buffer();
buffer.appendLong(EncodingUtils.NowUTCMillis().toEpochMilli());
buffer.appendBytes(nonce);
buffer.appendBytes(resp.encode().getBytes(StandardCharsets.UTF_8));
rc.response().putHeader(HttpHeaders.CONTENT_TYPE, "text/plain");
rc.response().end(Utils.toBase64String(AesGcm.encrypt(buffer.getBytes(), keyBytes)));
}
private void handleResponse(RoutingContext rc, V2RequestUtil.V2Request request) {
if (rc.response().getStatusCode() != 200) {
return;
}
try {
JsonObject respJson = (JsonObject) rc.data().get("response");
writeResponse(rc, request.nonce, respJson, request.encryptionKey);
} catch (Exception ex) {
LOGGER.error("Failed to generate response", ex);
ResponseUtil.LogErrorAndSendResponse(ResponseUtil.ResponseStatus.GenericError, 500, rc, "");
}
}
}