Skip to content

Commit

Permalink
implement a client helper class
Browse files Browse the repository at this point in the history
  • Loading branch information
GrantBirki committed Oct 15, 2024
1 parent 13f7ff0 commit 3b8fd10
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 2 deletions.
3 changes: 3 additions & 0 deletions spec/kemal-hmac/kemal-hmac_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ describe "Kemal::Hmac" do
timestamp = Time::Format::ISO_8601_DATE_TIME.format(Time.utc)
hmac_token = Kemal::Hmac::Token.new(client, "/api", timestamp).hexdigest("octo-secret-green")

hmac_client = Kemal::Hmac::Client.new(client, "octo-secret-green", "SHA256")
headers = hmac_client.generate_headers("/api")

request = HTTP::Request.new(
"GET",
"/api",
Expand Down
2 changes: 2 additions & 0 deletions src/kemal-hmac.cr
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ require "./kemal-hmac/**"

module Kemal
module Hmac
class InvalidSecretError < Exception; end

KEY_VALIDATION_REGEX = /^[A-Z0-9][A-Z0-9_-]+[A-Z0-9]$/
ALGORITHM = algorithm(ENV.fetch("HMAC_ALGORITHM", "SHA256").upcase)
end
Expand Down
27 changes: 27 additions & 0 deletions src/kemal-hmac/client.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
require "./token"

module Kemal::Hmac
class Client
def initialize(client : String, secret : String, algorithm : String? = "SHA256")
@client = client.upcase
@secret = secret
algo = (algorithm || ENV.fetch("HMAC_ALGORITHM", "SHA256")).upcase
@algorithm = Kemal::Hmac.algorithm(algo)

unless KEY_VALIDATION_REGEX.match(@client)
raise InvalidSecretError.new("client name must only contain letters, numbers, -, or _")
end
end

def generate_headers(path : String)
timestamp = Time::Format::ISO_8601_DATE_TIME.format(Time.utc)
hmac_token = Kemal::Hmac::Token.new(@client, path, timestamp).hexdigest(@secret)

return {
"hmac-client" => @client,
"hmac-timestamp" => timestamp,
"hmac-token" => hmac_token,
}
end
end
end
2 changes: 0 additions & 2 deletions src/kemal-hmac/handler.cr
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@ module Kemal::Hmac
HMAC_KEY_SUFFIX_LIST = ENV.fetch("HMAC_KEY_SUFFIX_LIST", "HMAC_SECRET_BLUE,HMAC_SECRET_GREEN").split(",").map(&.strip)
HMAC_KEY_DELIMITER = ENV.fetch("HMAC_KEY_DELIMITER", "_")

class InvalidSecretError < Exception; end

# initialize the Kemal::Hmac::Handler
# note: "BLUE" and "GREEN" in this context are two different secrets for the same client. This is a common pattern to allow for key rotation without downtime.
# examples:
Expand Down

0 comments on commit 3b8fd10

Please sign in to comment.