forked from stripe/stripe-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebhook.java
More file actions
263 lines (238 loc) · 9.93 KB
/
Webhook.java
File metadata and controls
263 lines (238 loc) · 9.93 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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
package com.stripe.net;
import com.stripe.exception.SignatureVerificationException;
import com.stripe.model.Event;
import com.stripe.model.StripeObject;
import com.stripe.util.StringUtils;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public final class Webhook {
public static final long DEFAULT_TOLERANCE = 300;
/**
* Returns an Event instance using the provided JSON payload. Throws a JsonSyntaxException if the
* payload is not valid JSON, and a SignatureVerificationException if the signature verification
* fails for any reason.
*
* @param payload the payload sent by Stripe.
* @param sigHeader the contents of the signature header sent by Stripe.
* @param secret secret used to generate the signature.
* @return the Event instance
* @throws SignatureVerificationException if the verification fails.
*/
public static Event constructEvent(String payload, String sigHeader, String secret)
throws SignatureVerificationException {
return constructEvent(payload, sigHeader, secret, DEFAULT_TOLERANCE);
}
/**
* Returns an Event instance using the provided JSON payload. Throws a JsonSyntaxException if the
* payload is not valid JSON, and a SignatureVerificationException if the signature verification
* fails for any reason.
*
* @param payload the payload sent by Stripe.
* @param sigHeader the contents of the signature header sent by Stripe.
* @param secret secret used to generate the signature.
* @param tolerance maximum difference in seconds allowed between the header's timestamp and the
* current time
* @return the Event instance
* @throws SignatureVerificationException if the verification fails.
*/
public static Event constructEvent(
String payload, String sigHeader, String secret, long tolerance)
throws SignatureVerificationException {
return constructEvent(payload, sigHeader, secret, tolerance, null);
}
/**
* Returns an Event instance using the provided JSON payload. Throws a JsonSyntaxException if the
* payload is not valid JSON, a SignatureVerificationException if the signature verification fails
* for any reason, and an IllegalArgumentException if you pass the wrong type of input.
*
* @param payload the payload sent by Stripe.
* @param sigHeader the contents of the signature header sent by Stripe.
* @param secret secret used to generate the signature.
* @param tolerance maximum difference in seconds allowed between the header's timestamp and the
* current time
* @param clock instance of clock if you want to use custom time instance
* @return the Event instance
* @throws SignatureVerificationException if the verification fails.
*/
public static Event constructEvent(
String payload, String sigHeader, String secret, long tolerance, Clock clock)
throws SignatureVerificationException {
Event event =
StripeObject.deserializeStripeObject(
payload, Event.class, ApiResource.getGlobalResponseGetter());
if ("v2.core.event".equals(event.getObject())) {
throw new IllegalArgumentException(
"You passed an event notification to Webhook.constructEvent, which expects a webhook payload."
+ " Use StripeClient.parseEventNotification instead.");
}
Signature.verifyHeader(payload, sigHeader, secret, tolerance, clock);
// StripeObjects source their raw JSON object from their last response, but constructed webhooks
// don't have that
// in order to make the raw object available on parsed events, we fake the response.
if (event.getLastResponse() == null) {
event.setLastResponse(
new StripeResponse(200, HttpHeaders.of(Collections.emptyMap()), payload));
}
return event;
}
public static final class Signature {
public static final String EXPECTED_SCHEME = "v1";
/**
* Verifies the signature header sent by Stripe. Throws a SignatureVerificationException if the
* verification fails for any reason.
*
* @param payload the payload sent by Stripe.
* @param sigHeader the contents of the signature header sent by Stripe.
* @param secret secret used to generate the signature.
* @param tolerance maximum difference allowed between the header's timestamp and the current
* time
* @throws SignatureVerificationException if the verification fails.
*/
public static boolean verifyHeader(
String payload, String sigHeader, String secret, long tolerance)
throws SignatureVerificationException {
return verifyHeader(payload, sigHeader, secret, tolerance, null);
}
/**
* Verifies the signature header sent by Stripe. Throws a SignatureVerificationException if the
* verification fails for any reason.
*
* @param payload the payload sent by Stripe.
* @param sigHeader the contents of the signature header sent by Stripe.
* @param secret secret used to generate the signature.
* @param tolerance maximum difference allowed between the header's timestamp and the current
* time
* @param clock instance of clock if you want to use custom time instance
* @throws SignatureVerificationException if the verification fails.
*/
public static boolean verifyHeader(
String payload, String sigHeader, String secret, long tolerance, Clock clock)
throws SignatureVerificationException {
// Get timestamp and signatures from header
long timestamp = getTimestamp(sigHeader);
List<String> signatures = getSignatures(sigHeader, EXPECTED_SCHEME);
if (timestamp <= 0) {
throw new SignatureVerificationException(
"Unable to extract timestamp and signatures from header", sigHeader);
}
if (signatures.size() == 0) {
throw new SignatureVerificationException(
"No signatures found with expected scheme", sigHeader);
}
// Compute expected signature
String signedPayload = String.format("%d.%s", timestamp, payload);
String expectedSignature;
try {
expectedSignature = computeSignature(signedPayload, secret);
} catch (Exception e) {
throw new SignatureVerificationException(
"Unable to compute signature for payload", sigHeader);
}
// Check if expected signature is found in list of header's signatures
boolean signatureFound = false;
for (String signature : signatures) {
if (StringUtils.secureCompare(expectedSignature, signature)) {
signatureFound = true;
break;
}
}
if (!signatureFound) {
throw new SignatureVerificationException(
"No signatures found matching the expected signature for payload", sigHeader);
}
long currentTime = clock == null ? Util.getTimeNow() : clock.millis() / 1000;
// Check tolerance
if ((tolerance > 0) && (timestamp < (currentTime - tolerance))) {
throw new SignatureVerificationException("Timestamp outside the tolerance zone", sigHeader);
}
return true;
}
/**
* Extracts the timestamp in a signature header.
*
* @param sigHeader the signature header
* @return the timestamp contained in the header.
*/
private static long getTimestamp(String sigHeader) {
String[] items = sigHeader.split(",", -1);
for (String item : items) {
String[] itemParts = item.split("=", 2);
if (itemParts[0].equals("t")) {
try {
return Long.parseLong(itemParts[1]);
} catch (NumberFormatException e) {
return -1;
}
}
}
return -1;
}
/**
* Extracts the signatures matching a given scheme in a signature header.
*
* @param sigHeader the signature header
* @param scheme the signature scheme to look for.
* @return the list of signatures matching the provided scheme.
*/
private static List<String> getSignatures(String sigHeader, String scheme) {
List<String> signatures = new ArrayList<String>();
String[] items = sigHeader.split(",", -1);
for (String item : items) {
String[] itemParts = item.split("=", 2);
if (itemParts[0].equals(scheme)) {
signatures.add(itemParts[1]);
}
}
return signatures;
}
/**
* Computes the signature for a given payload and secret.
*
* <p>The current scheme used by Stripe ("v1") is HMAC/SHA-256.
*
* @param payload the payload to sign.
* @param secret the secret used to generate the signature.
* @return the signature as a string.
*/
private static String computeSignature(String payload, String secret)
throws NoSuchAlgorithmException, InvalidKeyException {
return Util.computeHmacSha256(secret, payload);
}
}
public static final class Util {
/**
* Computes the HMAC/SHA-256 code for a given key and message.
*
* @param key the key used to generate the code.
* @param message the message.
* @return the code as a string.
*/
public static String computeHmacSha256(String key, String message)
throws NoSuchAlgorithmException, InvalidKeyException {
Mac hasher = Mac.getInstance("HmacSHA256");
hasher.init(new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] hash = hasher.doFinal(message.getBytes(StandardCharsets.UTF_8));
String result = "";
for (byte b : hash) {
result += Integer.toString((b & 0xff) + 0x100, 16).substring(1);
}
return result;
}
/**
* Returns the current UTC timestamp in seconds.
*
* @return the timestamp as a long.
*/
public static long getTimeNow() {
long time = System.currentTimeMillis() / 1000L;
return time;
}
}
}