-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathapi_key_signer.rb
More file actions
67 lines (58 loc) · 2.13 KB
/
api_key_signer.rb
File metadata and controls
67 lines (58 loc) · 2.13 KB
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
# frozen_string_literal: true
module Smithy
module Client
# Signs requests with the ApiKey identity.
class ApiKeySigner
# @param [Hash] options
# @option options [String] :name
# The name of the header or query parameter to which the API key value will be assigned.
# @option options [String] :in
# Where to place the API key value. Valid values are "header" and "query".
# @option options [String] :scheme
# An optional scheme to be prepended to the API key value when signing in a header.
def initialize(options = {})
@name = options[:name]
@in = options[:in]
@scheme = options[:scheme]
end
def sign_request(context)
case @in
when 'header' then sign_in_header(context.http_request, context.config.api_key_provider)
when 'query' then sign_in_query_param(context.http_request, context.config.api_key_provider)
end
end
def presign_url(_context)
raise NotImplementedError
end
private
def sign_in_header(http_request, provider)
http_request.headers.delete(@name)
value = "#{@scheme} #{provider.identity.key}".strip
http_request.headers[@name] = value
end
def sign_in_query_param(http_request, provider)
remove_query_param(http_request)
append_query_param(http_request, provider)
end
def append_query_param(http_request, provider)
value = provider.identity.key
if http_request.endpoint.query
http_request.endpoint.query += "&#{@name}=#{value}"
else
http_request.endpoint.query = "#{@name}=#{value}"
end
end
def remove_query_param(http_request)
return unless http_request.endpoint.query
parsed = CGI.parse(http_request.endpoint.query)
parsed.delete(@name)
# encode_www_form ignores query params without values
# (CGI parses these as empty lists)
parsed.each do |key, values|
parsed[key] = values.empty? ? nil : values
end
http_request.endpoint.query = URI.encode_www_form(parsed)
end
end
end
end