diff --git a/ShopifyNet.Tests/ShopifyWebhookHmacTests.cs b/ShopifyNet.Tests/ShopifyWebhookHmacTests.cs new file mode 100644 index 0000000..06ddfa6 --- /dev/null +++ b/ShopifyNet.Tests/ShopifyWebhookHmacTests.cs @@ -0,0 +1,138 @@ +using System.Security.Cryptography; +using System.Text; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ShopifyNet.Tests; + +[TestClass] +public class ShopifyWebhookHmacTests +{ + private const string Secret = "client-secret"; + private const string Body = "{\"id\":820982911946154508,\"email\":\"jon@example.com\"}"; + // Computed independently: printf '%s' "$Body" | openssl dgst -sha256 -hmac 'client-secret' -binary | base64 + private const string BodyHmac = "Bl2MneNADkze0Byhd9z+bUTwNwuqta2avGGaZwoNh/s="; + // Computed independently: printf '' | openssl dgst -sha256 -hmac 'client-secret' -binary | base64 + private const string EmptyBodyHmac = "A8Bv4pNVz2gNhZFyYII6Wg0LPn0GT36FVD7hRp+Em20="; + + private static string Sign(byte[] body, string secret = Secret) => + Convert.ToBase64String(HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret), body)); + + [TestMethod] + public void AcceptsValidHmacForStringBody() + { + Assert.IsTrue(ShopifyOAuthClient.IsValidWebhookHmac(BodyHmac, Body, Secret)); + } + + [TestMethod] + public void AcceptsValidHmacForByteBody() + { + Assert.IsTrue(ShopifyOAuthClient.IsValidWebhookHmac(BodyHmac, Encoding.UTF8.GetBytes(Body), Secret)); + } + + [TestMethod] + public void AcceptsValidHmacForEmptyBody() + { + Assert.IsTrue(ShopifyOAuthClient.IsValidWebhookHmac(EmptyBodyHmac, "", Secret)); + Assert.IsTrue(ShopifyOAuthClient.IsValidWebhookHmac(EmptyBodyHmac, ReadOnlySpan.Empty, Secret)); + } + + [TestMethod] + public void EncodesStringBodyAndSecretAsUtf8() + { + const string body = "{\"title\":\"Café ☕ 日本\"}"; + const string secret = "sécret-🔑"; + var hmac = Sign(Encoding.UTF8.GetBytes(body), secret); + Assert.IsTrue(ShopifyOAuthClient.IsValidWebhookHmac(hmac, body, secret)); + Assert.IsFalse(ShopifyOAuthClient.IsValidWebhookHmac(hmac, Encoding.Latin1.GetBytes(body), secret)); + } + + [TestMethod] + public void ValidatesRawBytesThatAreNotValidUtf8() + { + var body = new byte[] { 0x7B, 0xFF, 0xFE, 0x00, 0x7D }; + Assert.IsTrue(ShopifyOAuthClient.IsValidWebhookHmac(Sign(body), body, Secret)); + } + + [DataTestMethod] + [DataRow("{\"id\":820982911946154508,\"email\":\"jon@example.org\"}")] + [DataRow("{\"id\":820982911946154508,\"email\":\"jon@example.com\"}\n")] + [DataRow(" {\"id\":820982911946154508,\"email\":\"jon@example.com\"}")] + [DataRow("{\"email\":\"jon@example.com\",\"id\":820982911946154508}")] + [DataRow("{ \"id\": 820982911946154508, \"email\": \"jon@example.com\" }")] + [DataRow("")] + public void RejectsTamperedOrReserializedBody(string body) + { + Assert.IsFalse(ShopifyOAuthClient.IsValidWebhookHmac(BodyHmac, body, Secret)); + Assert.IsFalse(ShopifyOAuthClient.IsValidWebhookHmac(BodyHmac, Encoding.UTF8.GetBytes(body), Secret)); + } + + [DataTestMethod] + [DataRow("wrong-secret")] + [DataRow("")] + [DataRow("Client-Secret")] + public void RejectsWrongSecret(string secret) + { + Assert.IsFalse(ShopifyOAuthClient.IsValidWebhookHmac(BodyHmac, Body, secret)); + } + + [TestMethod] + public void RejectsHmacWithSingleFlippedBit() + { + var hash = Convert.FromBase64String(BodyHmac); + for (var i = 0; i < hash.Length; i++) + { + var tampered = (byte[])hash.Clone(); + tampered[i] ^= 0x01; + Assert.IsFalse(ShopifyOAuthClient.IsValidWebhookHmac(Convert.ToBase64String(tampered), Body, Secret), $"byte {i}"); + } + } + + [DataTestMethod] + [DataRow(null)] + [DataRow("")] + [DataRow(" ")] + [DataRow("not base64!")] + [DataRow("Bl2MneNADkze0Byhd9z+bUTwNwuqta2avGGaZwoNh/s")] // missing padding + [DataRow("Bl2MneNADkze0Byhd9z-bUTwNwuqta2avGGaZwoNh_s=")] // base64url alphabet + [DataRow("065d8c9de3400e4cded01ca177dcfe6d44f0370baab5ad9abc619a670a0d87fb")] // hex encoding of the right hash + [DataRow("Bl2MneNADkze0Byhd9z+bUTwNwuqta2avGGaZwoN")] // truncated to 30 bytes + [DataRow("Bl2MneNADkze0Byhd9z+bUTwNwuqta2avGGaZwoNh/sA")] // 33 bytes + [DataRow("Bl2MneNADkze0Byhd9z+bUTwNwuqta2avGGaZwoNh/s=,Bl2MneNADkze0Byhd9z+bUTwNwuqta2avGGaZwoNh/s=")] // multiple header values + [DataRow("Bl2MneNADkze0Byhd9z+bUTwNwuqta2avGGaZwoNh/s=Bl2MneNADkze0Byhd9z+bUTwNwuqta2avGGaZwoNh/s=")] // concatenated + public void RejectsMalformedHmacHeader(string hmacHeader) + { + Assert.IsFalse(ShopifyOAuthClient.IsValidWebhookHmac(hmacHeader, Body, Secret)); + Assert.IsFalse(ShopifyOAuthClient.IsValidWebhookHmac(hmacHeader, Encoding.UTF8.GetBytes(Body), Secret)); + } + + [TestMethod] + public void RejectsHmacOfDifferentLengthEvenWhenPrefixMatches() + { + var hash = Convert.FromBase64String(BodyHmac); + var longer = hash.Concat(new byte[] { 0 }).ToArray(); + Assert.IsFalse(ShopifyOAuthClient.IsValidWebhookHmac(Convert.ToBase64String(longer), Body, Secret)); + Assert.IsFalse(ShopifyOAuthClient.IsValidWebhookHmac(Convert.ToBase64String(hash[..^1]), Body, Secret)); + } + + [TestMethod] + public void RejectsNullStringBody() + { + Assert.IsFalse(ShopifyOAuthClient.IsValidWebhookHmac(BodyHmac, (string)null, Secret)); + } + + [TestMethod] + public void ThrowsOnNullSecret() + { + Assert.ThrowsException(() => ShopifyOAuthClient.IsValidWebhookHmac(BodyHmac, Body, null)); + Assert.ThrowsException(() => ShopifyOAuthClient.IsValidWebhookHmac(BodyHmac, Encoding.UTF8.GetBytes(Body), null)); + // The secret is checked before the header and body, so misconfiguration is never masked as an invalid request. + Assert.ThrowsException(() => ShopifyOAuthClient.IsValidWebhookHmac(null, (string)null, null)); + Assert.ThrowsException(() => ShopifyOAuthClient.IsValidWebhookHmac(null, ReadOnlySpan.Empty, null)); + } + + [TestMethod] + public void ExposesShopifyHmacHeaderName() + { + Assert.AreEqual("X-Shopify-Hmac-SHA256", ShopifyOAuthClient.WEBHOOK_HMAC_HEADER); + } +} diff --git a/ShopifyNet/OAuth/ShopifyOAuthClient.cs b/ShopifyNet/OAuth/ShopifyOAuthClient.cs index 73e085d..6061079 100644 --- a/ShopifyNet/OAuth/ShopifyOAuthClient.cs +++ b/ShopifyNet/OAuth/ShopifyOAuthClient.cs @@ -30,7 +30,6 @@ public class ShopifyOAuthClient private const string GRANT_OPTIONS_KEY = "grant_options[]"; private const string CLIENT_ASSERTION_KEY = "client_assertion"; private const string CLIENT_ASSERTION_TYPE_KEY = "client_assertion_type"; - private const string EXPIRING_VALUE = "1"; private const string REFRESH_TOKEN_GRANT_TYPE = "refresh_token"; private const string TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange"; @@ -39,6 +38,8 @@ public class ShopifyOAuthClient private const string ONLINE_ACCESS_TOKEN_TYPE = "urn:shopify:params:oauth:token-type:online-access-token"; private const string CLIENT_CREDENTIALS_GRANT_TYPE = "client_credentials"; private const string JWT_BEARER_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"; + public const string WEBHOOK_HMAC_HEADER = "X-Shopify-Hmac-SHA256"; + private static readonly HttpClient _defaultHttpClient = new(new SocketsHttpHandler { @@ -160,6 +161,39 @@ public static bool IsValidHmac(IEnumerable> queryPa return CryptographicOperations.FixedTimeEquals(expectedHash, suppliedHash); } + /// + /// Verifies a webhook's base64 HMAC-SHA256 (the X-Shopify-Hmac-SHA256 header) over the raw request body using the client secret. + /// Supply the body exactly as received; a re-serialized body will not validate. + /// Missing, malformed or incorrect HMACs return false. A header with several values, joined with commas, is malformed. + /// This checks authenticity only: deduplicate with X-Shopify-Event-Id and apply any freshness policy separately. + /// See https://shopify.dev/docs/apps/build/webhooks/subscribe/https#step-2-validate-the-origin-of-your-webhook-to-ensure-its-coming-from-shopify + /// + public static bool IsValidWebhookHmac(string hmacHeader, ReadOnlySpan requestBody, string clientSecret) + { + ArgumentNullException.ThrowIfNull(clientSecret); + + if (hmacHeader == null) + return false; + + Span suppliedHash = stackalloc byte[HMACSHA256.HashSizeInBytes]; + if (!Convert.TryFromBase64String(hmacHeader, suppliedHash, out var bytesWritten) || bytesWritten != HMACSHA256.HashSizeInBytes) + return false; + + Span expectedHash = stackalloc byte[HMACSHA256.HashSizeInBytes]; + HMACSHA256.HashData(Encoding.UTF8.GetBytes(clientSecret), requestBody, expectedHash); + return CryptographicOperations.FixedTimeEquals(expectedHash, suppliedHash); + } + + public static bool IsValidWebhookHmac(string hmacHeader, string requestBody, string clientSecret) + { + ArgumentNullException.ThrowIfNull(clientSecret); + + if (requestBody == null) + return false; + + return IsValidWebhookHmac(hmacHeader, Encoding.UTF8.GetBytes(requestBody), clientSecret); + } + private static string EncodeHmacQueryComponent(string value, bool isKey = false) { // This method encodes query components for HMAC verification according to Shopify's requirements. diff --git a/ShopifyNet/ShopifyNet.csproj b/ShopifyNet/ShopifyNet.csproj index ec9f89b..11edc68 100644 --- a/ShopifyNet/ShopifyNet.csproj +++ b/ShopifyNet/ShopifyNet.csproj @@ -5,7 +5,7 @@ https://github.com/Wish-Org/ShopifyNet https://github.com/Wish-Org/ShopifyNet .NET utilities for Shopify GraphQL - 3.1.0 + 3.2.0 shopify graphql types classes schema generator strongly typed