Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 44 additions & 3 deletions src/main/java/com/stripe/StripeClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.stripe.exception.SignatureVerificationException;
import com.stripe.exception.StripeException;
import com.stripe.model.Event;
import com.stripe.model.StripeObject;
import com.stripe.model.v2.core.EventNotification;
import com.stripe.net.*;
Expand Down Expand Up @@ -58,9 +59,10 @@ public EventNotification parseEventNotification(String payload, String sigHeader
}

/**
* Returns an StripeEvent 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.
* Constructs a <a href="https://docs.stripe.com/event-destinations#thin-payload">thin event
* notification</a> from an incoming webhook after verifying its authenticity. To work with a
* webhook that has already been verified (i.e. one from a cloud provider, an asynchronous queue,
* or during testing), see {@code parseEventNotificationWithoutVerification}.
*
* @param payload the payload sent by Stripe.
* @param sigHeader the contents of the signature header sent by Stripe.
Expand Down Expand Up @@ -117,6 +119,45 @@ public com.stripe.model.Event constructEvent(
return event;
}

/**
* Constructs a <a href="https://docs.stripe.com/event-destinations#snapshot-payload">snapshot
* event</a> from an incoming webhook without first verifying its authenticity. Should be used
* after calling {@code Webhook.Signature.verifyHeader(...)} or with input from a trusted source
* (such as <a href="https://docs.stripe.com/event-destinations/eventbridge">AWS EventBridge</a>,
* or <a href="https://docs.stripe.com/event-destinations/eventgrid">Azure Event Grid</a>
* payload). Or, to verify &amp; construct in a single call, use {@code constructEvent(...)}
* instead.
*
* @param payload the JSON payload: a raw Stripe Event or an AWS EventBridge/Azure Event Grid
* envelope.
* @return the Event instance.
* @throws IllegalArgumentException if the payload is a thin event notification, or if the format
* is not recognized.
*/
public com.stripe.model.Event constructEventWithoutVerification(String payload) {
Event event = Webhook.constructEventWithoutVerification(payload);
event.setResponseGetter(this.getResponseGetter());
return event;
}

/**
* Constructs a <a href="https://docs.stripe.com/event-destinations#thin-payload">thin event
* notification</a> from an incoming webhook without first verifying its authenticity. Should be
* used after calling {@code Webhook.Signature.verifyHeader(...)} or with input from a trusted
* source (such as <a href="https://docs.stripe.com/event-destinations/eventbridge">AWS
* EventBridge</a>, or <a href="https://docs.stripe.com/event-destinations/eventgrid">Azure Event
* Grid</a> payload). Or, to verify &amp; parse in a single call, use {@code
* parseEventNotification(...)} instead.
*
* @param payload the JSON payload: a raw Stripe Event, or an AWS EventBridge/Azure Event Grid
* envelope.
* @return the EventNotification instance.
* @throws IllegalArgumentException if the payload format is not recognized.
*/
public EventNotification parseEventNotificationWithoutVerification(String payload) {
return EventNotification.fromJson(Webhook.maybeExtractFromCloudProviderEnvelope(payload), this);
}

// The beginning of the section generated from our OpenAPI spec
public com.stripe.service.V1Services v1() {
return new com.stripe.service.V1Services(this.getResponseGetter());
Expand Down
33 changes: 25 additions & 8 deletions src/main/java/com/stripe/model/v2/core/EventNotification.java
Original file line number Diff line number Diff line change
Expand Up @@ -86,17 +86,34 @@ public static class Reason {
/**
* Helper for constructing an Event Notification. Doesn't perform signature validation, so you
* should use {@link com.stripe.StripeClient#parseEventNotification} instead for initial handling.
* This is useful in unit tests and working with EventNotifications that you've already validated
* the authenticity of.
* This is useful in unit tests and working with EventNotifications whose authenticity you've
* already validated.
*/
public static EventNotification fromJson(String payload, StripeClient client) {
// don't love the double json parse here, but I don't think we can avoid it?
JsonObject jsonObject = ApiResource.GSON.fromJson(payload, JsonObject.class).getAsJsonObject();
return EventNotification.fromJson(
ApiResource.GSON.fromJson(payload, JsonObject.class).getAsJsonObject(), client);
}

if (jsonObject.has("object") && "event".equals(jsonObject.get("object").getAsString())) {
throw new IllegalArgumentException(
"You passed a webhook payload to StripeClient.parseEventNotification, which expects an event notification."
+ " Use StripeClient.constructEvent instead.");
/**
* Helper for constructing an Event Notification. Doesn't perform signature validation, so you
* should use {@link com.stripe.StripeClient#parseEventNotification} instead for initial handling.
* This is useful in unit tests and working with EventNotifications whose authenticity you've
* already validated.
*/
public static EventNotification fromJson(JsonObject jsonObject, StripeClient client) {
if (jsonObject.has("object")) {
String object = jsonObject.get("object").getAsString();
if ("event".equals(object)) {
throw new IllegalArgumentException(
"You passed a webhook payload to a method that expects an event notification. Use the corresponding constructEvent method instead.");
}
if (!"v2.core.event".equals(object)) {
throw new IllegalArgumentException(
"Unexpected object type '"
+ object
+ "'. Expected 'v2.core.event' for an event notification.");
}
}

Class<? extends EventNotification> cls =
Expand All @@ -105,7 +122,7 @@ public static EventNotification fromJson(String payload, StripeClient client) {
cls = UnknownEventNotification.class;
}

EventNotification e = ApiResource.GSON.fromJson(payload, cls);
EventNotification e = ApiResource.GSON.fromJson(jsonObject, cls);
e.client = client;

return e;
Expand Down
121 changes: 108 additions & 13 deletions src/main/java/com/stripe/net/Webhook.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.stripe.net;

import com.google.gson.JsonObject;
import com.stripe.exception.SignatureVerificationException;
import com.stripe.model.Event;
import com.stripe.model.StripeObject;
Expand Down Expand Up @@ -53,9 +54,10 @@ public static Event constructEvent(
}

/**
* 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.
* Constructs a <a href="https://docs.stripe.com/event-destinations#snapshot-payload">snapshot
* event</a> from an incoming webhook after verifying its authenticity. To work with a webhook
* that has already been verified (i.e. one from a cloud provider, an asynchronous queue, or
* during testing), see {@code constructEventWithoutVerification}.
*
* @param payload the payload sent by Stripe.
* @param sigHeader the contents of the signature header sent by Stripe.
Expand All @@ -69,28 +71,90 @@ public static Event constructEvent(
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());
Signature.verifyHeader(payload, sigHeader, secret, tolerance, clock);

return buildV1Event(payload);
}

/**
* Constructs a <a href="https://docs.stripe.com/event-destinations#snapshot-payload">snapshot
* event</a> from an incoming webhook without first verifying its authenticity. Should be used
* after calling {@code Webhook.Signature.verifyHeader(...)} or with input from a trusted source
* (such as <a href="https://docs.stripe.com/event-destinations/eventbridge">AWS EventBridge</a>,
* or <a href="https://docs.stripe.com/event-destinations/eventgrid">Azure Event Grid</a>
* payload). Or, to verify &amp; construct in a single call, use {@code
* Webhook.constructEvent(...)} instead.
*
* @param payload the payload sent by Stripe, or a cloud provider envelope wrapping it.
* @return the Event instance
* @throws IllegalArgumentException if the payload is a v2 thin event notification.
*/
public static Event constructEventWithoutVerification(String payload) {
return buildV1Event(maybeExtractFromCloudProviderEnvelope(payload));
}

if ("v2.core.event".equals(event.getObject())) {
private static Event buildV1Event(String payload) {
return buildV1Event(ApiResource.GSON.fromJson(payload, JsonObject.class));
}

private static Event buildV1Event(JsonObject jsonObject) {
if (jsonObject.has("object")
&& "v2.core.event".equals(jsonObject.get("object").getAsString())) {
throw new IllegalArgumentException(
"You passed an event notification to Webhook.constructEvent, which expects a webhook payload."
+ " Use StripeClient.parseEventNotification instead.");
"You passed an event notification to Webhook method, which expects a webhook payload. Use the corresponding parseEventNotification method instead.");
}

Signature.verifyHeader(payload, sigHeader, secret, tolerance, clock);
Event event =
StripeObject.deserializeStripeObject(
jsonObject, Event.class, ApiResource.getGlobalResponseGetter());

// 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));
new StripeResponse(200, HttpHeaders.of(Collections.emptyMap()), jsonObject.toString()));
}

return event;
}

/**
* Parses a JSON payload (or cloud provider envelope) and returns the inner Stripe event JSON
* object. If the payload is already a raw Stripe event (object is "event" or "v2.core.event"), it
* is returned as-is. If it is an AWS EventBridge or Azure Event Grid envelope, the inner event is
* extracted. Throws {@link IllegalArgumentException} for unrecognized formats.
*
* @param payload the raw JSON string.
* @return the inner event as a {@link JsonObject}.
*/
public static JsonObject maybeExtractFromCloudProviderEnvelope(String payload) {
JsonObject root = ApiResource.GSON.fromJson(payload, JsonObject.class);

// AWS
// https://docs.stripe.com/event-destinations/eventbridge#event-structure
if (root.has("detail")) {
return root.get("detail").getAsJsonObject();
}

// Azure
// https://docs.stripe.com/event-destinations/eventgrid#event-structure
if (root.has("specversion") && root.has("data")) {
return root.get("data").getAsJsonObject();
Comment thread
xavdid marked this conversation as resolved.
Resolved
}

// Raw Stripe event passed directly: pass through as-is
if (root.has("object") && root.get("object").isJsonPrimitive()) {
String object = root.get("object").getAsString();
if ("event".equals(object) || "v2.core.event".equals(object)) {
return root;
}
}

throw new IllegalArgumentException(
"Unrecognized event format. The payload must be an AWS EventBridge/Azure Event Grid event envelope or a Stripe webhook (thin event notification or snapshot).");
}

public static final class Signature {
public static final String EXPECTED_SCHEME = "v1";

Expand All @@ -112,8 +176,10 @@ public static boolean verifyHeader(
}

/**
* Verifies the signature header sent by Stripe. Throws a SignatureVerificationException if the
* verification fails for any reason.
* Verifies the authenticity (and recency) of a webhook, throwing a {@code
* SignatureVerificationException} if there's a mismatch. Useful for quickly validating incoming
* webhooks before storing them for later processing (at which time you can use the {@code
* *WithoutVerification} methods for parsing).
*
* @param payload the payload sent by Stripe.
* @param sigHeader the contents of the signature header sent by Stripe.
Expand Down Expand Up @@ -171,6 +237,35 @@ public static boolean verifyHeader(
return true;
}

/**
* Generates a {@code Stripe-Signature} header for the given payload and secret using the
* current timestamp.
*
* @param payload the payload to sign.
* @param secret the webhook secret.
* @return the generated signature header string.
*/
public static String generateSignatureHeader(String payload, String secret)
throws NoSuchAlgorithmException, InvalidKeyException {
return generateSignatureHeader(payload, secret, Util.getTimeNow());
}

/**
* Compute the {@code Stripe-Signature} header for a given webhook body &amp; secret. Useful for
* signing payloads in unit tests.
*
* @param payload the payload to sign.
* @param secret the webhook secret.
* @param timestamp the timestamp to use (seconds since epoch).
* @return the generated signature header string.
*/
public static String generateSignatureHeader(String payload, String secret, long timestamp)
throws NoSuchAlgorithmException, InvalidKeyException {
String payloadToSign = String.format("%d.%s", timestamp, payload);
String signature = computeSignature(payloadToSign, secret);
return String.format("t=%d,%s=%s", timestamp, EXPECTED_SCHEME, signature);
}

/**
* Extracts the timestamp in a signature header.
*
Expand Down
Loading
Loading