/
EventUtility.cs
205 lines (186 loc) · 9.16 KB
/
EventUtility.cs
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
namespace Stripe
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Stripe.Infrastructure;
/// <summary>
/// This class contains utility methods to process event objects in Stripe's webhooks.
/// </summary>
public static class EventUtility
{
internal static readonly UTF8Encoding SafeUTF8
= new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
private const int DefaultTimeTolerance = 300;
/// <summary>
/// Parses a JSON string from a Stripe webhook into a <see cref="Event"/> object.
/// </summary>
/// <param name="json">The JSON string to parse.</param>
/// <param name="throwOnApiVersionMismatch">
/// If <c>true</c> (default), the method will throw a <see cref="StripeException"/> if the
/// API version of the event doesn't match Stripe.net's default API version (see
/// <see cref="StripeConfiguration.ApiVersion"/>).
/// </param>
/// <returns>The deserialized <see cref="Event"/>.</returns>
/// <exception cref="StripeException">
/// Thrown if the API version of the event doesn't match Stripe.net's default API version.
/// </exception>
/// <remarks>
/// This method doesn't verify <a href="https://stripe.com/docs/webhooks/signatures">webhook
/// signatures</a>. It's recommended that you use
/// <see cref="ConstructEvent(string, string, string, long, bool)"/> instead.
/// </remarks>
public static Event ParseEvent(string json, bool throwOnApiVersionMismatch = true)
{
var stripeEvent = JsonUtils.DeserializeObject<Event>(
json,
StripeConfiguration.SerializerSettings);
if (throwOnApiVersionMismatch &&
stripeEvent.ApiVersion != StripeConfiguration.ApiVersion)
{
throw new StripeException(
$"Received event with API version {stripeEvent.ApiVersion}, but Stripe.net "
+ $"{StripeConfiguration.StripeNetVersion} expects API version "
+ $"{StripeConfiguration.ApiVersion}. We recommend that you create a "
+ "WebhookEndpoint with this API version. Otherwise, you can disable this "
+ "exception by passing `throwOnApiVersionMismatch: false` to "
+ "`Stripe.EventUtility.ParseEvent` or `Stripe.EventUtility.ConstructEvent`, "
+ "but be wary that objects may be incorrectly deserialized.");
}
return stripeEvent;
}
/// <summary>
/// Parses a JSON string from a Stripe webhook into a <see cref="Event"/> object, while
/// verifying the <a href="https://stripe.com/docs/webhooks/signatures">webhook's
/// signature</a>.
/// </summary>
/// <param name="json">The JSON string to parse.</param>
/// <param name="stripeSignatureHeader">
/// The value of the <c>Stripe-Signature</c> header from the webhook request.
/// </param>
/// <param name="secret">The webhook endpoint's signing secret.</param>
/// <param name="tolerance">The time tolerance, in seconds (default 300).</param>
/// <param name="throwOnApiVersionMismatch">
/// If <c>true</c> (default), the method will throw a <see cref="StripeException"/> if the
/// API version of the event doesn't match Stripe.net's default API version (see
/// <see cref="StripeConfiguration.ApiVersion"/>).
/// </param>
/// <returns>The deserialized <see cref="Event"/>.</returns>
/// <exception cref="StripeException">
/// Thrown if the signature verification fails for any reason, of if the API version of the
/// event doesn't match Stripe.net's default API version.
/// </exception>
public static Event ConstructEvent(
string json,
string stripeSignatureHeader,
string secret,
long tolerance = DefaultTimeTolerance,
bool throwOnApiVersionMismatch = true)
{
return ConstructEvent(
json,
stripeSignatureHeader,
secret,
tolerance,
DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
throwOnApiVersionMismatch);
}
/// <summary>
/// Parses a JSON string from a Stripe webhook into a <see cref="Event"/> object, while
/// verifying the <a href="https://stripe.com/docs/webhooks/signatures">webhook's
/// signature</a>.
/// </summary>
/// <param name="json">The JSON string to parse.</param>
/// <param name="stripeSignatureHeader">
/// The value of the <c>Stripe-Signature</c> header from the webhook request.
/// </param>
/// <param name="secret">The webhook endpoint's signing secret.</param>
/// <param name="tolerance">The time tolerance, in seconds.</param>
/// <param name="utcNow">The timestamp to use for the current time.</param>
/// <param name="throwOnApiVersionMismatch">
/// If <c>true</c> (default), the method will throw a <see cref="StripeException"/> if the
/// API version of the event doesn't match Stripe.net's default API version (see
/// <see cref="StripeConfiguration.ApiVersion"/>).
/// </param>
/// <returns>The deserialized <see cref="Event"/>.</returns>
/// <exception cref="StripeException">
/// Thrown if the signature verification fails for any reason, of if the API version of the
/// event doesn't match Stripe.net's default API version.
/// </exception>
public static Event ConstructEvent(
string json,
string stripeSignatureHeader,
string secret,
long tolerance,
long utcNow,
bool throwOnApiVersionMismatch = true)
{
ValidateSignature(json, stripeSignatureHeader, secret, tolerance, utcNow);
return ParseEvent(json, throwOnApiVersionMismatch);
}
public static void ValidateSignature(string json, string stripeSignatureHeader, string secret, long tolerance = DefaultTimeTolerance)
{
ValidateSignature(json, stripeSignatureHeader, secret, tolerance, DateTimeOffset.UtcNow.ToUnixTimeSeconds());
}
public static void ValidateSignature(string json, string stripeSignatureHeader, string secret, long tolerance, long utcNow)
{
var signatureItems = ParseStripeSignature(stripeSignatureHeader);
var signature = string.Empty;
try
{
signature = ComputeSignature(secret, signatureItems["t"].FirstOrDefault(), json);
}
catch (EncoderFallbackException ex)
{
throw new StripeException(
"The webhook cannot be processed because the signature cannot be safely calculated.",
ex);
}
if (!IsSignaturePresent(signature, signatureItems["v1"]))
{
throw new StripeException(
"The expected signature was not found in the Stripe-Signature header. " +
"Make sure you're using the correct webhook secret (whsec_) and confirm the incoming request came from Stripe.");
}
var webhookUtc = Convert.ToInt32(signatureItems["t"].FirstOrDefault());
if (Math.Abs(utcNow - webhookUtc) > tolerance)
{
throw new StripeException(
"The webhook cannot be processed because the current timestamp is outside of the allowed tolerance.");
}
}
private static ILookup<string, string> ParseStripeSignature(string stripeSignatureHeader)
{
(string Key, string Value) ParseItem(string item)
{
string[] parts = item.Trim().Split(new[] { '=' }, 2);
if (parts.Length != 2)
{
throw new StripeException(
"The signature header format is unexpected.");
}
return (parts[0], parts[1]);
}
return stripeSignatureHeader.Trim()
.Split(',')
.Select(item => ParseItem(item))
.ToLookup(item => item.Key, item => item.Value);
}
private static bool IsSignaturePresent(string signature, IEnumerable<string> signatures)
{
return signatures.Any(key => StringUtils.SecureEquals(key, signature));
}
private static string ComputeSignature(string secret, string timestamp, string payload)
{
var secretBytes = SafeUTF8.GetBytes(secret);
var payloadBytes = SafeUTF8.GetBytes($"{timestamp}.{payload}");
using (var cryptographer = new HMACSHA256(secretBytes))
{
var hash = cryptographer.ComputeHash(payloadBytes);
return BitConverter.ToString(hash).Replace("-", string.Empty).ToLowerInvariant();
}
}
}
}