aws-sigv4-1.8.0/0000755000004100000410000000000014536021166013400 5ustar www-datawww-dataaws-sigv4-1.8.0/CHANGELOG.md0000644000004100000410000000526014536021166015214 0ustar www-datawww-dataUnreleased Changes ------------------ 1.8.0 (2023-11-28) ------------------ * Feature - Support `sigv4-s3express` signing algorithm. 1.7.0 (2023-11-22) ------------------ * Feature - AWS SDK for Ruby no longer supports Ruby runtime versions 2.3 and 2.4. 1.6.1 (2023-10-25) ------------------ * Issue - (Static Stability) use provided `expires_in` in presigned url when credentials are expired. 1.6.0 (2023-06-28) ------------------ * Feature - Select the minimum expiration time for presigned urls between the expiration time option and the credential expiration time. 1.5.2 (2022-09-30) ------------------ * Issue - Fix an issue where quoted strings with multiple spaces are not trimmed. (#2758) 1.5.1 (2022-07-19) ------------------ * Issue - Fix performance regression when checking if `aws-crt` is available. (#2729) 1.5.0 (2022-04-20) ------------------ * Feature - Use CRT based signers if `aws-crt` is available - provides support for `sigv4a`. 1.4.0 (2021-09-02) ------------------ * Feature - add `signing_algorithm` option with `sigv4` default. 1.3.0 (2021-09-01) ------------------ * Feature - AWS SDK for Ruby no longer supports Ruby runtime versions 1.9, 2.0, 2.1, and 2.2. 1.2.4 (2021-07-08) ------------------ * Issue - Fix usage of `:uri_escape_path` and `:apply_checksum_header` in `Signer`. 1.2.3 (2021-03-04) ------------------ * Issue - Include LICENSE, CHANGELOG, and VERSION files with this gem. 1.2.2 (2020-08-13) ------------------ * Issue - Sort query params with same names by value when signing. (#2376) 1.2.1 (2020-06-24) ------------------ * Issue - Don't overwrite `host` header in sigv4 signer if given. 1.2.0 (2020-06-17) ------------------ * Feature - Bump `aws-eventstream` dependency to `~> 1`. 1.1.4 (2020-05-28) ------------------ * Issue - Don't use `expect` header to compute Signature. 1.1.3 (2020-04-27) ------------------ * Issue - Don't rely on the set? method of credentials. 1.1.2 (2020-04-17) ------------------ * Issue - Raise errors when credentials are not set (nil or empty) 1.1.1 (2020-02-26) ------------------ * Issue - Handle signing for unknown protocols and default ports. 1.1.0 (2019-03-13) ------------------ * Feature - Support signature V4 signing per event. 1.0.3 (2018-06-28) ------------------ * Issue - Reduce memory allocation when generating signatures. 1.0.2 (2018-02-21) ------------------ * Issue - Fix Ruby warning: shadowed local variable "headers". 1.0.2 (2017-08-31) ------------------ * Issue - Update `aws-sigv4` gemspec metadata. 1.0.1 (2017-07-12) ------------------ * Issue - Make UTF-8 encoding explicit in spec test. 1.0.0 (2016-11-08) ------------------ * Feature - Initial release of the `aws-sigv4` gem. aws-sigv4-1.8.0/aws-sigv4.gemspec0000644000004100000410000000331614536021166016574 0ustar www-datawww-data######################################################### # This file has been automatically generated by gem2tgz # ######################################################### # -*- encoding: utf-8 -*- # stub: aws-sigv4 1.8.0 ruby lib Gem::Specification.new do |s| s.name = "aws-sigv4".freeze s.version = "1.8.0" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.metadata = { "changelog_uri" => "https://github.com/aws/aws-sdk-ruby/tree/version-3/gems/aws-sigv4/CHANGELOG.md", "source_code_uri" => "https://github.com/aws/aws-sdk-ruby/tree/version-3/gems/aws-sigv4" } if s.respond_to? :metadata= s.require_paths = ["lib".freeze] s.authors = ["Amazon Web Services".freeze] s.date = "2023-11-28" s.description = "Amazon Web Services Signature Version 4 signing library. Generates sigv4 signature for HTTP requests.".freeze s.files = ["CHANGELOG.md".freeze, "LICENSE.txt".freeze, "VERSION".freeze, "lib/aws-sigv4.rb".freeze, "lib/aws-sigv4/credentials.rb".freeze, "lib/aws-sigv4/errors.rb".freeze, "lib/aws-sigv4/request.rb".freeze, "lib/aws-sigv4/signature.rb".freeze, "lib/aws-sigv4/signer.rb".freeze] s.homepage = "https://github.com/aws/aws-sdk-ruby".freeze s.licenses = ["Apache-2.0".freeze] s.required_ruby_version = Gem::Requirement.new(">= 2.5".freeze) s.rubygems_version = "3.3.15".freeze s.summary = "AWS Signature Version 4 library.".freeze if s.respond_to? :specification_version then s.specification_version = 4 end if s.respond_to? :add_runtime_dependency then s.add_runtime_dependency(%q.freeze, ["~> 1", ">= 1.0.2"]) else s.add_dependency(%q.freeze, ["~> 1", ">= 1.0.2"]) end end aws-sigv4-1.8.0/lib/0000755000004100000410000000000014536021166014146 5ustar www-datawww-dataaws-sigv4-1.8.0/lib/aws-sigv4.rb0000644000004100000410000000044214536021166016317 0ustar www-datawww-data# frozen_string_literal: true require_relative 'aws-sigv4/credentials' require_relative 'aws-sigv4/errors' require_relative 'aws-sigv4/signature' require_relative 'aws-sigv4/signer' module Aws module Sigv4 VERSION = File.read(File.expand_path('../VERSION', __dir__)).strip end endaws-sigv4-1.8.0/lib/aws-sigv4/0000755000004100000410000000000014536021166015772 5ustar www-datawww-dataaws-sigv4-1.8.0/lib/aws-sigv4/credentials.rb0000644000004100000410000000374714536021166020627 0ustar www-datawww-data# frozen_string_literal: true module Aws module Sigv4 # Users that wish to configure static credentials can use the # `:access_key_id` and `:secret_access_key` constructor options. # @api private class Credentials # @option options [required, String] :access_key_id # @option options [required, String] :secret_access_key # @option options [String, nil] :session_token (nil) def initialize(options = {}) if options[:access_key_id] && options[:secret_access_key] @access_key_id = options[:access_key_id] @secret_access_key = options[:secret_access_key] @session_token = options[:session_token] else msg = "expected both :access_key_id and :secret_access_key options" raise ArgumentError, msg end end # @return [String] attr_reader :access_key_id # @return [String] attr_reader :secret_access_key # @return [String, nil] attr_reader :session_token # @return [Boolean] Returns `true` if the access key id and secret # access key are both set. def set? !access_key_id.nil? && !access_key_id.empty? && !secret_access_key.nil? && !secret_access_key.empty? end end # Users that wish to configure static credentials can use the # `:access_key_id` and `:secret_access_key` constructor options. # @api private class StaticCredentialsProvider # @option options [Credentials] :credentials # @option options [String] :access_key_id # @option options [String] :secret_access_key # @option options [String] :session_token (nil) def initialize(options = {}) @credentials = options[:credentials] ? options[:credentials] : Credentials.new(options) end # @return [Credentials] attr_reader :credentials # @return [Boolean] def set? !!credentials && credentials.set? end end end end aws-sigv4-1.8.0/lib/aws-sigv4/errors.rb0000644000004100000410000000106714536021166017637 0ustar www-datawww-data# frozen_string_literal: true module Aws module Sigv4 module Errors class MissingCredentialsError < ArgumentError def initialize(msg = nil) super(msg || <<-MSG.strip) missing credentials, provide credentials with one of the following options: - :access_key_id and :secret_access_key - :credentials - :credentials_provider MSG end end class MissingRegionError < ArgumentError def initialize(*args) super("missing required option :region") end end end end end aws-sigv4-1.8.0/lib/aws-sigv4/request.rb0000644000004100000410000000270314536021166020011 0ustar www-datawww-data# frozen_string_literal: true require 'uri' module Aws module Sigv4 class Request # @option options [required, String] :http_method # @option options [required, HTTP::URI, HTTPS::URI, String] :endpoint # @option options [Hash] :headers ({}) # @option options [String, IO] :body ('') def initialize(options = {}) @http_method = nil @endpoint = nil @headers = {} @body = '' options.each_pair do |attr_name, attr_value| send("#{attr_name}=", attr_value) end end # @param [String] http_method One of 'GET', 'PUT', 'POST', 'DELETE', 'HEAD', or 'PATCH' def http_method=(http_method) @http_method = http_method end # @return [String] One of 'GET', 'PUT', 'POST', 'DELETE', 'HEAD', or 'PATCH' def http_method @http_method end # @param [String, HTTP::URI, HTTPS::URI] endpoint def endpoint=(endpoint) @endpoint = URI.parse(endpoint.to_s) end # @return [HTTP::URI, HTTPS::URI] def endpoint @endpoint end # @param [Hash] headers def headers=(headers) @headers = headers end # @return [Hash] def headers @headers end # @param [String, IO] body def body=(body) @body = body end # @return [String, IO] def body @body end end end end aws-sigv4-1.8.0/lib/aws-sigv4/signature.rb0000644000004100000410000000173714536021166020330 0ustar www-datawww-data# frozen_string_literal: true module Aws module Sigv4 class Signature # @api private def initialize(options) options.each_pair do |attr_name, attr_value| send("#{attr_name}=", attr_value) end end # @return [Hash] A hash of headers that should # be applied to the HTTP request. Header keys are lower # cased strings and may include the following: # # * 'host' # * 'x-amz-date' # * 'x-amz-security-token' # * 'x-amz-content-sha256' # * 'authorization' # attr_accessor :headers # @return [String] For debugging purposes. attr_accessor :canonical_request # @return [String] For debugging purposes. attr_accessor :string_to_sign # @return [String] For debugging purposes. attr_accessor :content_sha256 # @return [Hash] Internal data for debugging purposes. attr_accessor :extra end end end aws-sigv4-1.8.0/lib/aws-sigv4/signer.rb0000644000004100000410000010026514536021166017612 0ustar www-datawww-data# frozen_string_literal: true require 'openssl' require 'tempfile' require 'time' require 'uri' require 'set' require 'cgi' require 'aws-eventstream' module Aws module Sigv4 # Utility class for creating AWS signature version 4 signature. This class # provides two methods for generating signatures: # # * {#sign_request} - Computes a signature of the given request, returning # the hash of headers that should be applied to the request. # # * {#presign_url} - Computes a presigned request with an expiration. # By default, the body of this request is not signed and the request # expires in 15 minutes. # # ## Configuration # # To use the signer, you need to specify the service, region, and credentials. # The service name is normally the endpoint prefix to an AWS service. For # example: # # ec2.us-west-1.amazonaws.com => ec2 # # The region is normally the second portion of the endpoint, following # the service name. # # ec2.us-west-1.amazonaws.com => us-west-1 # # It is important to have the correct service and region name, or the # signature will be invalid. # # ## Credentials # # The signer requires credentials. You can configure the signer # with static credentials: # # signer = Aws::Sigv4::Signer.new( # service: 's3', # region: 'us-east-1', # # static credentials # access_key_id: 'akid', # secret_access_key: 'secret' # ) # # You can also provide refreshing credentials via the `:credentials_provider`. # If you are using the AWS SDK for Ruby, you can use any of the credential # classes: # # signer = Aws::Sigv4::Signer.new( # service: 's3', # region: 'us-east-1', # credentials_provider: Aws::InstanceProfileCredentials.new # ) # # Other AWS SDK for Ruby classes that can be provided via `:credentials_provider`: # # * `Aws::Credentials` # * `Aws::SharedCredentials` # * `Aws::InstanceProfileCredentials` # * `Aws::AssumeRoleCredentials` # * `Aws::ECSCredentials` # # A credential provider is any object that responds to `#credentials` # returning another object that responds to `#access_key_id`, `#secret_access_key`, # and `#session_token`. # class Signer @@use_crt = begin require 'aws-crt' true rescue LoadError false end # @overload initialize(service:, region:, access_key_id:, secret_access_key:, session_token:nil, **options) # @param [String] :service The service signing name, e.g. 's3'. # @param [String] :region The region name, e.g. 'us-east-1'. # @param [String] :access_key_id # @param [String] :secret_access_key # @param [String] :session_token (nil) # # @overload initialize(service:, region:, credentials:, **options) # @param [String] :service The service signing name, e.g. 's3'. # @param [String] :region The region name, e.g. 'us-east-1'. # @param [Credentials] :credentials Any object that responds to the following # methods: # # * `#access_key_id` => String # * `#secret_access_key` => String # * `#session_token` => String, nil # * `#set?` => Boolean # # @overload initialize(service:, region:, credentials_provider:, **options) # @param [String] :service The service signing name, e.g. 's3'. # @param [String] :region The region name, e.g. 'us-east-1'. # @param [#credentials] :credentials_provider An object that responds # to `#credentials`, returning an object that responds to the following # methods: # # * `#access_key_id` => String # * `#secret_access_key` => String # * `#session_token` => String, nil # * `#set?` => Boolean # # @option options [Array] :unsigned_headers ([]) A list of # headers that should not be signed. This is useful when a proxy # modifies headers, such as 'User-Agent', invalidating a signature. # # @option options [Boolean] :uri_escape_path (true) When `true`, # the request URI path is uri-escaped as part of computing the canonical # request string. This is required for every service, except Amazon S3, # as of late 2016. # # @option options [Boolean] :apply_checksum_header (true) When `true`, # the computed content checksum is returned in the hash of signature # headers. This is required for AWS Glacier, and optional for # every other AWS service as of late 2016. # # @option options [Symbol] :signing_algorithm (:sigv4) The # algorithm to use for signing. :sigv4a is only supported when # `aws-crt` is available. # # @option options [Boolean] :omit_session_token (false) # (Supported only when `aws-crt` is available) If `true`, # then security token is added to the final signing result, # but is treated as "unsigned" and does not contribute # to the authorization signature. # # @option options [Boolean] :normalize_path (true) (Supported only when `aws-crt` is available) # When `true`, the uri paths will be normalized when building the canonical request def initialize(options = {}) @service = extract_service(options) @region = extract_region(options) @credentials_provider = extract_credentials_provider(options) @unsigned_headers = Set.new((options.fetch(:unsigned_headers, [])).map(&:downcase)) @unsigned_headers << 'authorization' @unsigned_headers << 'x-amzn-trace-id' @unsigned_headers << 'expect' @uri_escape_path = options.fetch(:uri_escape_path, true) @apply_checksum_header = options.fetch(:apply_checksum_header, true) @signing_algorithm = options.fetch(:signing_algorithm, :sigv4) @normalize_path = options.fetch(:normalize_path, true) @omit_session_token = options.fetch(:omit_session_token, false) if @signing_algorithm == :sigv4a && !Signer.use_crt? raise ArgumentError, 'You are attempting to sign a' \ ' request with sigv4a which requires the `aws-crt` gem.'\ ' Please install the gem or add it to your gemfile.' end if @signing_algorithm == 'sigv4-s3express'.to_sym && Signer.use_crt? && Aws::Crt::GEM_VERSION <= '0.1.9' raise ArgumentError, 'This version of aws-crt does not support S3 Express. Please update this gem to at least version 0.2.0.' end end # @return [String] attr_reader :service # @return [String] attr_reader :region # @return [#credentials] Returns an object that responds to # `#credentials`, returning an object that responds to the following # methods: # # * `#access_key_id` => String # * `#secret_access_key` => String # * `#session_token` => String, nil # * `#set?` => Boolean # attr_reader :credentials_provider # @return [Set] Returns a set of header names that should not be signed. # All header names have been downcased. attr_reader :unsigned_headers # @return [Boolean] When `true` the `x-amz-content-sha256` header will be signed and # returned in the signature headers. attr_reader :apply_checksum_header # Computes a version 4 signature signature. Returns the resultant # signature as a hash of headers to apply to your HTTP request. The given # request is not modified. # # signature = signer.sign_request( # http_method: 'PUT', # url: 'https://domain.com', # headers: { # 'Abc' => 'xyz', # }, # body: 'body' # String or IO object # ) # # # Apply the following hash of headers to your HTTP request # signature.headers['host'] # signature.headers['x-amz-date'] # signature.headers['x-amz-security-token'] # signature.headers['x-amz-content-sha256'] # signature.headers['authorization'] # # In addition to computing the signature headers, the canonicalized # request, string to sign and content sha256 checksum are also available. # These values are useful for debugging signature errors returned by AWS. # # signature.canonical_request #=> "..." # signature.string_to_sign #=> "..." # signature.content_sha256 #=> "..." # # @param [Hash] request # # @option request [required, String] :http_method One of # 'GET', 'HEAD', 'PUT', 'POST', 'PATCH', or 'DELETE' # # @option request [required, String, URI::HTTPS, URI::HTTP] :url # The request URI. Must be a valid HTTP or HTTPS URI. # # @option request [optional, Hash] :headers ({}) A hash of headers # to sign. If the 'X-Amz-Content-Sha256' header is set, the `:body` # is optional and will not be read. # # @option request [optional, String, IO] :body ('') The HTTP request body. # A sha256 checksum is computed of the body unless the # 'X-Amz-Content-Sha256' header is set. # # @return [Signature] Return an instance of {Signature} that has # a `#headers` method. The headers must be applied to your request. # def sign_request(request) return crt_sign_request(request) if Signer.use_crt? creds, _ = fetch_credentials http_method = extract_http_method(request) url = extract_url(request) headers = downcase_headers(request[:headers]) datetime = headers['x-amz-date'] datetime ||= Time.now.utc.strftime("%Y%m%dT%H%M%SZ") date = datetime[0,8] content_sha256 = headers['x-amz-content-sha256'] content_sha256 ||= sha256_hexdigest(request[:body] || '') sigv4_headers = {} sigv4_headers['host'] = headers['host'] || host(url) sigv4_headers['x-amz-date'] = datetime if creds.session_token if @signing_algorithm == 'sigv4-s3express'.to_sym sigv4_headers['x-amz-s3session-token'] = creds.session_token else sigv4_headers['x-amz-security-token'] = creds.session_token end end sigv4_headers['x-amz-content-sha256'] ||= content_sha256 if @apply_checksum_header headers = headers.merge(sigv4_headers) # merge so we do not modify given headers hash # compute signature parts creq = canonical_request(http_method, url, headers, content_sha256) sts = string_to_sign(datetime, creq) sig = signature(creds.secret_access_key, date, sts) # apply signature sigv4_headers['authorization'] = [ "AWS4-HMAC-SHA256 Credential=#{credential(creds, date)}", "SignedHeaders=#{signed_headers(headers)}", "Signature=#{sig}", ].join(', ') # Returning the signature components. Signature.new( headers: sigv4_headers, string_to_sign: sts, canonical_request: creq, content_sha256: content_sha256 ) end # Signs a event and returns signature headers and prior signature # used for next event signing. # # Headers of a sigv4 signed event message only contains 2 headers # * ':chunk-signature' # * computed signature of the event, binary string, 'bytes' type # * ':date' # * millisecond since epoch, 'timestamp' type # # Payload of the sigv4 signed event message contains eventstream encoded message # which is serialized based on input and protocol # # To sign events # # headers_0, signature_0 = signer.sign_event( # prior_signature, # hex-encoded string # payload_0, # binary string (eventstream encoded event 0) # encoder, # Aws::EventStreamEncoder # ) # # headers_1, signature_1 = signer.sign_event( # signature_0, # payload_1, # binary string (eventstream encoded event 1) # encoder # ) # # The initial prior_signature should be using the signature computed at initial request # # Note: # # Since ':chunk-signature' header value has bytes type, the signature value provided # needs to be a binary string instead of a hex-encoded string (like original signature # V4 algorithm). Thus, when returning signature value used for next event siging, the # signature value (a binary string) used at ':chunk-signature' needs to converted to # hex-encoded string using #unpack def sign_event(prior_signature, payload, encoder) # Note: CRT does not currently provide event stream signing, so we always use the ruby implementation. creds, _ = fetch_credentials time = Time.now headers = {} datetime = time.utc.strftime("%Y%m%dT%H%M%SZ") date = datetime[0,8] headers[':date'] = Aws::EventStream::HeaderValue.new(value: time.to_i * 1000, type: 'timestamp') sts = event_string_to_sign(datetime, headers, payload, prior_signature, encoder) sig = event_signature(creds.secret_access_key, date, sts) headers[':chunk-signature'] = Aws::EventStream::HeaderValue.new(value: sig, type: 'bytes') # Returning signed headers and signature value in hex-encoded string [headers, sig.unpack('H*').first] end # Signs a URL with query authentication. Using query parameters # to authenticate requests is useful when you want to express a # request entirely in a URL. This method is also referred as # presigning a URL. # # See [Authenticating Requests: Using Query Parameters (AWS Signature Version 4)](http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html) for more information. # # To generate a presigned URL, you must provide a HTTP URI and # the http method. # # url = signer.presign_url( # http_method: 'GET', # url: 'https://my-bucket.s3-us-east-1.amazonaws.com/key', # expires_in: 60 # ) # # By default, signatures are valid for 15 minutes. You can specify # the number of seconds for the URL to expire in. # # url = signer.presign_url( # http_method: 'GET', # url: 'https://my-bucket.s3-us-east-1.amazonaws.com/key', # expires_in: 3600 # one hour # ) # # You can provide a hash of headers that you plan to send with the # request. Every 'X-Amz-*' header you plan to send with the request # **must** be provided, or the signature is invalid. Other headers # are optional, but should be provided for security reasons. # # url = signer.presign_url( # http_method: 'PUT', # url: 'https://my-bucket.s3-us-east-1.amazonaws.com/key', # headers: { # 'X-Amz-Meta-Custom' => 'metadata' # } # ) # # @option options [required, String] :http_method The HTTP request method, # e.g. 'GET', 'HEAD', 'PUT', 'POST', 'PATCH', or 'DELETE'. # # @option options [required, String, HTTPS::URI, HTTP::URI] :url # The URI to sign. # # @option options [Hash] :headers ({}) Headers that should # be signed and sent along with the request. All x-amz-* # headers must be present during signing. Other # headers are optional. # # @option options [Integer] :expires_in (900) # How long the presigned URL should be valid for. Defaults # to 15 minutes (900 seconds). # # @option options [optional, String, IO] :body # If the `:body` is set, then a SHA256 hexdigest will be computed of the body. # If `:body_digest` is set, this option is ignored. If neither are set, then # the `:body_digest` will be computed of the empty string. # # @option options [optional, String] :body_digest # The SHA256 hexdigest of the request body. If you wish to send the presigned # request without signing the body, you can pass 'UNSIGNED-PAYLOAD' as the # `:body_digest` in place of passing `:body`. # # @option options [Time] :time (Time.now) Time of the signature. # You should only set this value for testing. # # @return [HTTPS::URI, HTTP::URI] # def presign_url(options) return crt_presign_url(options) if Signer.use_crt? creds, expiration = fetch_credentials http_method = extract_http_method(options) url = extract_url(options) headers = downcase_headers(options[:headers]) headers['host'] ||= host(url) datetime = headers['x-amz-date'] datetime ||= (options[:time] || Time.now).utc.strftime("%Y%m%dT%H%M%SZ") date = datetime[0,8] content_sha256 = headers['x-amz-content-sha256'] content_sha256 ||= options[:body_digest] content_sha256 ||= sha256_hexdigest(options[:body] || '') params = {} params['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256' params['X-Amz-Credential'] = credential(creds, date) params['X-Amz-Date'] = datetime params['X-Amz-Expires'] = presigned_url_expiration(options, expiration, Time.strptime(datetime, "%Y%m%dT%H%M%S%Z")).to_s if creds.session_token if @signing_algorithm == 'sigv4-s3express'.to_sym params['X-Amz-S3session-Token'] = creds.session_token else params['X-Amz-Security-Token'] = creds.session_token end end params['X-Amz-SignedHeaders'] = signed_headers(headers) params = params.map do |key, value| "#{uri_escape(key)}=#{uri_escape(value)}" end.join('&') if url.query url.query += '&' + params else url.query = params end creq = canonical_request(http_method, url, headers, content_sha256) sts = string_to_sign(datetime, creq) url.query += '&X-Amz-Signature=' + signature(creds.secret_access_key, date, sts) url end private def canonical_request(http_method, url, headers, content_sha256) [ http_method, path(url), normalized_querystring(url.query || ''), canonical_headers(headers) + "\n", signed_headers(headers), content_sha256, ].join("\n") end def string_to_sign(datetime, canonical_request) [ 'AWS4-HMAC-SHA256', datetime, credential_scope(datetime[0,8]), sha256_hexdigest(canonical_request), ].join("\n") end # Compared to original #string_to_sign at signature v4 algorithm # there is no canonical_request concept for an eventstream event, # instead, an event contains headers and payload two parts, and # they will be used for computing digest in #event_string_to_sign # # Note: # While headers need to be encoded under eventstream format, # payload used is already eventstream encoded (event without signature), # thus no extra encoding is needed. def event_string_to_sign(datetime, headers, payload, prior_signature, encoder) encoded_headers = encoder.encode_headers( Aws::EventStream::Message.new(headers: headers, payload: payload) ) [ "AWS4-HMAC-SHA256-PAYLOAD", datetime, credential_scope(datetime[0,8]), prior_signature, sha256_hexdigest(encoded_headers), sha256_hexdigest(payload) ].join("\n") end def credential_scope(date) [ date, @region, @service, 'aws4_request', ].join('/') end def credential(credentials, date) "#{credentials.access_key_id}/#{credential_scope(date)}" end def signature(secret_access_key, date, string_to_sign) k_date = hmac("AWS4" + secret_access_key, date) k_region = hmac(k_date, @region) k_service = hmac(k_region, @service) k_credentials = hmac(k_service, 'aws4_request') hexhmac(k_credentials, string_to_sign) end # Comparing to original signature v4 algorithm, # returned signature is a binary string instread of # hex-encoded string. (Since ':chunk-signature' requires # 'bytes' type) # # Note: # converting signature from binary string to hex-encoded # string is handled at #sign_event instead. (Will be used # as next prior signature for event signing) def event_signature(secret_access_key, date, string_to_sign) k_date = hmac("AWS4" + secret_access_key, date) k_region = hmac(k_date, @region) k_service = hmac(k_region, @service) k_credentials = hmac(k_service, 'aws4_request') hmac(k_credentials, string_to_sign) end def path(url) path = url.path path = '/' if path == '' if @uri_escape_path uri_escape_path(path) else path end end def normalized_querystring(querystring) params = querystring.split('&') params = params.map { |p| p.match(/=/) ? p : p + '=' } # From: https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html # Sort the parameter names by character code point in ascending order. # Parameters with duplicate names should be sorted by value. # # Default sort <=> in JRuby will swap members # occasionally when <=> is 0 (considered still sorted), but this # causes our normalized query string to not match the sent querystring. # When names match, we then sort by their values. When values also # match then we sort by their original order params.each.with_index.sort do |a, b| a, a_offset = a b, b_offset = b a_name, a_value = a.split('=') b_name, b_value = b.split('=') if a_name == b_name if a_value == b_value a_offset <=> b_offset else a_value <=> b_value end else a_name <=> b_name end end.map(&:first).join('&') end def signed_headers(headers) headers.inject([]) do |signed_headers, (header, _)| if @unsigned_headers.include?(header) signed_headers else signed_headers << header end end.sort.join(';') end def canonical_headers(headers) headers = headers.inject([]) do |hdrs, (k,v)| if @unsigned_headers.include?(k) hdrs else hdrs << [k,v] end end headers = headers.sort_by(&:first) headers.map{|k,v| "#{k}:#{canonical_header_value(v.to_s)}" }.join("\n") end def canonical_header_value(value) value.gsub(/\s+/, ' ').strip end def host(uri) # Handles known and unknown URI schemes; default_port nil when unknown. if uri.default_port == uri.port uri.host else "#{uri.host}:#{uri.port}" end end # @param [File, Tempfile, IO#read, String] value # @return [String] def sha256_hexdigest(value) if (File === value || Tempfile === value) && !value.path.nil? && File.exist?(value.path) OpenSSL::Digest::SHA256.file(value).hexdigest elsif value.respond_to?(:read) sha256 = OpenSSL::Digest::SHA256.new loop do chunk = value.read(1024 * 1024) # 1MB break unless chunk sha256.update(chunk) end value.rewind sha256.hexdigest else OpenSSL::Digest::SHA256.hexdigest(value) end end def hmac(key, value) OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha256'), key, value) end def hexhmac(key, value) OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), key, value) end def extract_service(options) if options[:service] options[:service] else msg = "missing required option :service" raise ArgumentError, msg end end def extract_region(options) if options[:region] options[:region] else raise Errors::MissingRegionError end end def extract_credentials_provider(options) if options[:credentials_provider] options[:credentials_provider] elsif options.key?(:credentials) || options.key?(:access_key_id) StaticCredentialsProvider.new(options) else raise Errors::MissingCredentialsError end end def extract_http_method(request) if request[:http_method] request[:http_method].upcase else msg = "missing required option :http_method" raise ArgumentError, msg end end def extract_url(request) if request[:url] URI.parse(request[:url].to_s) else msg = "missing required option :url" raise ArgumentError, msg end end def downcase_headers(headers) (headers || {}).to_hash.inject({}) do |hash, (key, value)| hash[key.downcase] = value hash end end def extract_expires_in(options) case options[:expires_in] when nil then 900 when Integer then options[:expires_in] else msg = "expected :expires_in to be a number of seconds" raise ArgumentError, msg end end def uri_escape(string) self.class.uri_escape(string) end def uri_escape_path(string) self.class.uri_escape_path(string) end def fetch_credentials credentials = @credentials_provider.credentials if credentials_set?(credentials) expiration = nil if @credentials_provider.respond_to?(:expiration) expiration = @credentials_provider.expiration end [credentials, expiration] else raise Errors::MissingCredentialsError, 'unable to sign request without credentials set' end end # Returns true if credentials are set (not nil or empty) # Credentials may not implement the Credentials interface # and may just be credential like Client response objects # (eg those returned by sts#assume_role) def credentials_set?(credentials) !credentials.access_key_id.nil? && !credentials.access_key_id.empty? && !credentials.secret_access_key.nil? && !credentials.secret_access_key.empty? end def presigned_url_expiration(options, expiration, datetime) expires_in = extract_expires_in(options) return expires_in unless expiration expiration_seconds = (expiration - datetime).to_i # In the static stability case, credentials may expire in the past # but still be valid. For those cases, use the user configured # expires_in and ingore expiration. if expiration_seconds <= 0 expires_in else [expires_in, expiration_seconds].min end end ### CRT Code # the credentials used by CRT must be a # CRT StaticCredentialsProvider object def crt_fetch_credentials creds, expiration = fetch_credentials crt_creds = Aws::Crt::Auth::StaticCredentialsProvider.new( creds.access_key_id, creds.secret_access_key, creds.session_token ) [crt_creds, expiration] end def crt_sign_request(request) creds, _ = crt_fetch_credentials http_method = extract_http_method(request) url = extract_url(request) headers = downcase_headers(request[:headers]) datetime = if headers.include? 'x-amz-date' Time.parse(headers.delete('x-amz-date')) end content_sha256 = headers.delete('x-amz-content-sha256') content_sha256 ||= sha256_hexdigest(request[:body] || '') sigv4_headers = {} sigv4_headers['host'] = headers['host'] || host(url) # Modify the user-agent to add usage of crt-signer # This should be temporary during developer preview only if headers.include? 'user-agent' headers['user-agent'] = "#{headers['user-agent']} crt-signer/#{@signing_algorithm}/#{Aws::Sigv4::VERSION}" sigv4_headers['user-agent'] = headers['user-agent'] end headers = headers.merge(sigv4_headers) # merge so we do not modify given headers hash config = Aws::Crt::Auth::SigningConfig.new( algorithm: @signing_algorithm, signature_type: :http_request_headers, region: @region, service: @service, date: datetime, signed_body_value: content_sha256, signed_body_header_type: @apply_checksum_header ? :sbht_content_sha256 : :sbht_none, credentials: creds, unsigned_headers: @unsigned_headers, use_double_uri_encode: @uri_escape_path, should_normalize_uri_path: @normalize_path, omit_session_token: @omit_session_token ) http_request = Aws::Crt::Http::Message.new( http_method, url.to_s, headers ) signable = Aws::Crt::Auth::Signable.new(http_request) signing_result = Aws::Crt::Auth::Signer.sign_request(config, signable) Signature.new( headers: sigv4_headers.merge( downcase_headers(signing_result[:headers]) ), string_to_sign: 'CRT_INTERNAL', canonical_request: 'CRT_INTERNAL', content_sha256: content_sha256, extra: {config: config, signable: signable} ) end def crt_presign_url(options) creds, expiration = crt_fetch_credentials http_method = extract_http_method(options) url = extract_url(options) headers = downcase_headers(options[:headers]) headers['host'] ||= host(url) datetime = Time.strptime(headers.delete('x-amz-date'), "%Y%m%dT%H%M%S%Z") if headers['x-amz-date'] datetime ||= (options[:time] || Time.now) content_sha256 = headers.delete('x-amz-content-sha256') content_sha256 ||= options[:body_digest] content_sha256 ||= sha256_hexdigest(options[:body] || '') config = Aws::Crt::Auth::SigningConfig.new( algorithm: @signing_algorithm, signature_type: :http_request_query_params, region: @region, service: @service, date: datetime, signed_body_value: content_sha256, signed_body_header_type: @apply_checksum_header ? :sbht_content_sha256 : :sbht_none, credentials: creds, unsigned_headers: @unsigned_headers, use_double_uri_encode: @uri_escape_path, should_normalize_uri_path: @normalize_path, omit_session_token: @omit_session_token, expiration_in_seconds: presigned_url_expiration(options, expiration, datetime) ) http_request = Aws::Crt::Http::Message.new( http_method, url.to_s, headers ) signable = Aws::Crt::Auth::Signable.new(http_request) signing_result = Aws::Crt::Auth::Signer.sign_request(config, signable, http_method, url.to_s) url = URI.parse(signing_result[:path]) if options[:extra] && options[:extra].is_a?(Hash) options[:extra][:config] = config options[:extra][:signable] = signable end url end class << self def use_crt? @@use_crt end # @api private def uri_escape_path(path) path.gsub(/[^\/]+/) { |part| uri_escape(part) } end # @api private def uri_escape(string) if string.nil? nil else CGI.escape(string.encode('UTF-8')).gsub('+', '%20').gsub('%7E', '~') end end end end end end aws-sigv4-1.8.0/LICENSE.txt0000644000004100000410000002613614536021166015233 0ustar www-datawww-data Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. aws-sigv4-1.8.0/VERSION0000644000004100000410000000000614536021166014444 0ustar www-datawww-data1.8.0