Webhook HMAC verification works locally but fails on testing environment

New Member
3 0 0

I have a Rails app. 

 

We have validation code similar to the example code here:
https://github.com/Shopify/example-ruby-app/blob/master/02%20Charging%20For%20Your%20App/app.rb#L148

(though updated since that's 2016)

 

 

api_secret = Rails.application.config.shopify[:api_secret]
request.body.rewind
@body = request.body.read
calculated_hmac = Base64.strict_encode64(OpenSSL::HMAC.digest('sha256', api_secret, @body))
hmac_header = request.headers["HTTP_X_SHOPIFY_HMAC_SHA256"]
Rails.logger.info "hmac_header: #{hmac_header} comparing against calculated_hmac #{calculated_hmac}"
Rails.logger.info "body: #{@body}"
Rails.logger.info "api_secret: #{api_secret}"
unless ActiveSupport::SecurityUtils.secure_compare(calculated_hmac, hmac_header)
  Rails.logger.error "hmac_header: #{hmac_header} failed to compare against calculated_hmac #{calculated_hmac}"
  Rails.logger.error "body: #{@body}"
  render json_error_403
  return
end

 

When a product is updated through Shopify, the product/update webhook is called. This part works fine locally (via ngrok) and on testing.


However, when it gets to the verification code, it works locally and the calculated HMAC is equal to the HMAC header, but on the testing environment it does not. 

 

I've tried running locally in prod mode and it still works.

 

I'm at a loss for why it would fail in one and not the other. Ideas?

 

0 Likes
Community Manager
Community Manager
451 17 45

Hi @parkerhobbydb,

 

Are you switching the secret used to calculate the hmac when you are switching environments? Presumably your testing and prod apps are different apps in Shopify, each with their own secret. It's an oopsie I've seen far too often.

 

Let me know if that's not the case and we can go back to the drawing board.

 

Cheers,

0 Likes
New Member
3 0 0

Yes, we have different apps, and different tokens + secrets. All of that is ok. 
I'm wondering if there's something weird with Unicorn (server) vs Webrick (server local) and the Ruby implementation.

0 Likes
Highlighted
Community Manager
Community Manager
451 17 45

What exactly is the error you are seeing? I don't see how the server would cause issues calculating an hmac, assuming the parameters used to sign were correct, but a better idea of the error occurring might help.

 

 

0 Likes
New Member
3 0 0

That's the odd thing!

 

The error is that the request header (HMAC) sent in from Shopify is different from the calculated HMAC header.

When running and calculating the header via the console it calculates the same when I put in all the data via local, but when I put in the same data (with different tokens/secrets changed), it's different.

This is super weird, sorry.

0 Likes