├── test ├── test_helper.exs ├── aws_utils_test.exs └── aws_auth_test.exs ├── .gitignore ├── CHANGELOG.md ├── mix.exs ├── config └── config.exs ├── lib ├── aws_auth │ ├── authorization_header.ex │ ├── query_parameters.ex │ └── utils.ex └── aws_auth.ex ├── mix.lock ├── README.md └── LICENSE /test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.start() 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /_build 2 | /deps 3 | erl_crash.dump 4 | *.ez 5 | /doc 6 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [0.6.1] 2 | 3 | ### Fixed 4 | - Correctly handle NaiveDateTimes with ms precision (thanks to [@radar](https://github.com/radar)) 5 | 6 | ## [0.6.0] 7 | 8 | ### Changed 9 | - Requires Elixir 1.3 or higher 10 | 11 | ### Fixed 12 | - Removed timex dependency and using Elixir's built in datetime functions (thanks to [@radar](https://github.com/radar)) 13 | 14 | ## [0.5.1] 15 | 16 | ### Fixed 17 | - Use Timex.DateTime.now, rather than Timex.DateTime.today (thanks to [@radar](https://github.com/radar)) 18 | 19 | ## [0.5.0] 20 | 21 | ### Fixed 22 | - `x-amz-date` using Date instead of DateTime (thanks to [@radar](https://github.com/radar)) 23 | 24 | ### Changed 25 | - Dependency updates (thanks to [@radar](https://github.com/radar)) 26 | 27 | ## [0.4.0] 28 | 29 | ### Fixed 30 | - Signing works for more than just S3 from @kenta-aktsk 31 | 32 | ### Changed 33 | - headers params for `sign_url` and `sign_authorization_header` now expects a map instead of a Dict 34 | -------------------------------------------------------------------------------- /mix.exs: -------------------------------------------------------------------------------- 1 | defmodule AWSAuth.Mixfile do 2 | use Mix.Project 3 | 4 | def project do 5 | [app: :aws_auth, 6 | version: "0.7.2", 7 | elixir: "~> 1.3", 8 | description: description(), 9 | package: package(), 10 | deps: deps(), 11 | test_coverage: [tool: ExCoveralls], 12 | preferred_cli_env: [coveralls: :test] 13 | ] 14 | end 15 | 16 | def application do 17 | [applications: [:logger]] 18 | end 19 | 20 | defp deps do 21 | [ 22 | {:earmark, "~> 1.2.3", only: :dev }, 23 | {:ex_doc, "~> 0.16", only: :dev }, 24 | {:excoveralls, "~> 0.4", only: :test}, 25 | {:credo, "~> 0.8.6", only: [:dev, :test]} 26 | ] 27 | end 28 | 29 | defp description do 30 | """ 31 | AWS Signature Version 4 Signing Library 32 | """ 33 | end 34 | 35 | defp package do 36 | [ 37 | files: ["lib", "mix.exs", "README*"], 38 | maintainers: ["Bryan Joseph"], 39 | licenses: ["Apache 2.0"], 40 | links: %{"GitHub" => "https://github.com/bryanjos/aws_auth"} 41 | ] 42 | end 43 | end 44 | -------------------------------------------------------------------------------- /config/config.exs: -------------------------------------------------------------------------------- 1 | # This file is responsible for configuring your application 2 | # and its dependencies with the aid of the Mix.Config module. 3 | use Mix.Config 4 | 5 | # This configuration is loaded before any dependency and is restricted 6 | # to this project. If another project depends on this project, this 7 | # file won't be loaded nor affect the parent project. For this reason, 8 | # if you want to provide default values for your application for third- 9 | # party users, it should be done in your mix.exs file. 10 | 11 | # Sample configuration: 12 | # 13 | # config :logger, :console, 14 | # level: :info, 15 | # format: "$date $time [$level] $metadata$message\n", 16 | # metadata: [:user_id] 17 | 18 | # It is also possible to import configuration files, relative to this 19 | # directory. For example, you can emulate configuration per environment 20 | # by uncommenting the line below and defining dev.exs, test.exs and such. 21 | # Configuration from the imported file will override the ones defined 22 | # here (which is why it is important to import them last). 23 | # 24 | # import_config "#{Mix.env}.exs" 25 | -------------------------------------------------------------------------------- /test/aws_utils_test.exs: -------------------------------------------------------------------------------- 1 | defmodule AWSAuth.UtilsTest do 2 | use ExUnit.Case 3 | 4 | test "build_canonical_request/5 builds correct AWS request representation" do 5 | canonical_request = AWSAuth.Utils.build_canonical_request("GET", "path/subpath", %{ "a" => 1, "b" => "2", "c" => 1.0}, 6 | %{ "a" => "1", "b" => "2" }, "hashed_payload") 7 | assert canonical_request == "GET\npath/subpath\na=1&b=2&c=1.0\na:1\nb:2\n\na;b\nhashed_payload" 8 | end 9 | 10 | test "build_canonical_request/5 builds correct AWS request representation with unsigned hash_payload" do 11 | canonical_request = AWSAuth.Utils.build_canonical_request("GET", "path/subpath", %{ "a" => 1, "b" => "2", "c" => 1.0}, 12 | %{ "a" => "1", "b" => "2" }, :unsigned) 13 | assert canonical_request == "GET\npath/subpath\na=1&b=2&c=1.0\na:1\nb:2\n\na;b\nUNSIGNED-PAYLOAD" 14 | end 15 | 16 | test "build_canonical_request/5 builds correct AWS request representation correctly escaped" do 17 | canonical_request = AWSAuth.Utils.build_canonical_request("GET", "path/subpath/!@#$%^&*()-_=+?,.<>;:'\"[]{}|\\~`", %{}, %{}, "") 18 | assert canonical_request == "GET\npath/subpath/%21%40%23%24%25%5E%26%2A%28%29-_%3D%2B%3F%2C.%3C%3E%3B%3A%27%22%5B%5D%7B%7D%7C%5C~%60\n\n\n\n\n" 19 | end 20 | 21 | test "format_time/1 formats a time correctly" do 22 | time = AWSAuth.Utils.format_time(~N[2016-10-20 10:32:45.12345]) 23 | assert time == "20161020T103245Z" 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /lib/aws_auth/authorization_header.ex: -------------------------------------------------------------------------------- 1 | defmodule AWSAuth.AuthorizationHeader do 2 | @moduledoc false 3 | 4 | #http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-auth-using-authorization-header.html 5 | def sign(access_key, secret_key, http_method, url, region, service, payload, headers, request_time) do 6 | uri = URI.parse(url) 7 | 8 | params = case uri.query do 9 | nil -> 10 | Map.new 11 | _ -> 12 | URI.decode_query(uri.query) 13 | end 14 | 15 | http_method = String.upcase(http_method) 16 | region = String.downcase(region) 17 | service = String.downcase(service) 18 | 19 | headers = Map.put_new(headers, "host", uri.host) 20 | 21 | payload = AWSAuth.Utils.hash_sha256(payload) 22 | 23 | headers = Map.put_new(headers, "x-amz-content-sha256", payload) 24 | 25 | amz_date = request_time |> AWSAuth.Utils.format_time 26 | date = request_time |> AWSAuth.Utils.format_date 27 | 28 | headers = Map.put_new(headers, "x-amz-date", amz_date) 29 | 30 | scope = "#{date}/#{region}/#{service}/aws4_request" 31 | 32 | string_to_sign = AWSAuth.Utils.build_canonical_request(http_method, uri.path || "/", params, headers, payload) 33 | |> AWSAuth.Utils.build_string_to_sign(amz_date, scope) 34 | 35 | signature = AWSAuth.Utils.build_signing_key(secret_key, date, region, service) 36 | |> AWSAuth.Utils.build_signature(string_to_sign) 37 | 38 | signed_headers = Enum.map(headers, fn({key, _}) -> String.downcase(key) end) 39 | |> Enum.sort(&(&1 < &2)) 40 | |> Enum.join(";") 41 | 42 | auth_header = "AWS4-HMAC-SHA256 Credential=#{access_key}/#{scope},SignedHeaders=#{signed_headers},Signature=#{signature}" 43 | 44 | headers 45 | |> Map.put("authorization", auth_header) 46 | |> Map.to_list 47 | end 48 | end 49 | -------------------------------------------------------------------------------- /lib/aws_auth/query_parameters.ex: -------------------------------------------------------------------------------- 1 | defmodule AWSAuth.QueryParameters do 2 | @moduledoc false 3 | 4 | #http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html 5 | def sign(access_key, secret_key, http_method, url, region, service, headers, request_time, payload) do 6 | uri = URI.parse(url) 7 | 8 | http_method = String.upcase(http_method) 9 | region = String.downcase(region) 10 | service = String.downcase(service) 11 | 12 | headers = Map.put_new(headers, "host", uri.host) 13 | 14 | amz_date = request_time |> AWSAuth.Utils.format_time 15 | date = request_time |> AWSAuth.Utils.format_date 16 | 17 | scope = "#{date}/#{region}/#{service}/aws4_request" 18 | 19 | params = case uri.query do 20 | nil -> 21 | Map.new 22 | _ -> 23 | URI.decode_query(uri.query) 24 | end 25 | 26 | params = params 27 | |> Map.put("X-Amz-Algorithm", "AWS4-HMAC-SHA256") 28 | |> Map.put("X-Amz-Credential", "#{access_key}/#{scope}") 29 | |> Map.put("X-Amz-Date", amz_date) 30 | |> Map.put("X-Amz-Expires", "86400") 31 | |> Map.put("X-Amz-SignedHeaders", "#{Map.keys(headers) |> Enum.join(";")}") 32 | 33 | hashed_payload = if service == "s3", 34 | do: :unsigned, 35 | else: AWSAuth.Utils.hash_sha256(payload) 36 | 37 | string_to_sign = AWSAuth.Utils.build_canonical_request(http_method, uri.path, params, headers, hashed_payload) 38 | |> AWSAuth.Utils.build_string_to_sign(amz_date, scope) 39 | 40 | signature = AWSAuth.Utils.build_signing_key(secret_key, date, region, service) 41 | |> AWSAuth.Utils.build_signature(string_to_sign) 42 | 43 | params = params |> Map.put("X-Amz-Signature", signature) 44 | query_string = URI.encode_query(params) |> String.replace("+", "%20") 45 | 46 | "#{uri.scheme}://#{uri.authority}#{uri.path || "/"}?#{query_string}" 47 | end 48 | end 49 | -------------------------------------------------------------------------------- /lib/aws_auth/utils.ex: -------------------------------------------------------------------------------- 1 | defmodule AWSAuth.Utils do 2 | @moduledoc false 3 | 4 | def build_canonical_request(http_method, path, params, headers, hashed_payload) do 5 | 6 | query_params = URI.encode_query(params) |> String.replace("+", "%20") 7 | 8 | header_params = Enum.map(headers, fn({key, value}) -> "#{String.downcase(key)}:#{String.trim(value)}" end) 9 | |> Enum.sort(&(&1 < &2)) 10 | |> Enum.join("\n") 11 | 12 | signed_header_params = Enum.map(headers, fn({key, _}) -> String.downcase(key) end) 13 | |> Enum.sort(&(&1 < &2)) 14 | |> Enum.join(";") 15 | 16 | hashed_payload = if hashed_payload == :unsigned, 17 | do: "UNSIGNED-PAYLOAD", 18 | else: hashed_payload 19 | 20 | encoded_path = 21 | path 22 | |> String.split("/") 23 | |> Enum.map(fn (segment) -> URI.encode_www_form(segment) end) 24 | |> Enum.join("/") 25 | 26 | "#{http_method}\n#{encoded_path}\n#{query_params}\n#{header_params}\n\n#{signed_header_params}\n#{hashed_payload}" 27 | end 28 | 29 | def build_string_to_sign(canonical_request, timestamp, scope) do 30 | hashed_canonical_request = hash_sha256(canonical_request) 31 | "AWS4-HMAC-SHA256\n#{timestamp}\n#{scope}\n#{hashed_canonical_request}" 32 | end 33 | 34 | def build_signing_key(secret_key, date, region, service) do 35 | hmac_sha256("AWS4#{secret_key}", date) 36 | |> hmac_sha256(region) 37 | |> hmac_sha256(service) 38 | |> hmac_sha256("aws4_request") 39 | end 40 | 41 | def build_signature(signing_key, string_to_sign) do 42 | hmac_sha256(signing_key, string_to_sign) 43 | |> bytes_to_string 44 | end 45 | 46 | def hash_sha256(data) do 47 | :crypto.hash(:sha256, data) 48 | |> bytes_to_string 49 | end 50 | 51 | def hmac_sha256(key, data) do 52 | :crypto.hmac(:sha256, key, data) 53 | end 54 | 55 | def bytes_to_string(bytes) do 56 | Base.encode16(bytes, case: :lower) 57 | end 58 | 59 | def format_time(time) do 60 | formatted_time = time 61 | |> NaiveDateTime.to_iso8601 62 | |> String.split(".") 63 | |> List.first 64 | |> String.replace("-", "") 65 | |> String.replace(":", "") 66 | formatted_time <> "Z" 67 | end 68 | 69 | def format_date(date) do 70 | date 71 | |> NaiveDateTime.to_date 72 | |> Date.to_iso8601 73 | |> String.replace("-", "") 74 | end 75 | end 76 | -------------------------------------------------------------------------------- /mix.lock: -------------------------------------------------------------------------------- 1 | %{"bunt": {:hex, :bunt, "0.2.0", "951c6e801e8b1d2cbe58ebbd3e616a869061ddadcc4863d0a2182541acae9a38", [:mix], [], "hexpm"}, 2 | "certifi": {:hex, :certifi, "0.7.0", "861a57f3808f7eb0c2d1802afeaae0fa5de813b0df0979153cbafcd853ababaf", [:rebar3], []}, 3 | "combine": {:hex, :combine, "0.9.2", "cd3c8721f378ebe032487d8a4fa2ced3181a456a3c21b16464da8c46904bb552", [:mix], []}, 4 | "credo": {:hex, :credo, "0.8.6", "335f723772d35da499b5ebfdaf6b426bfb73590b6fcbc8908d476b75f8cbca3f", [:mix], [{:bunt, "~> 0.2.0", [hex: :bunt, repo: "hexpm", optional: false]}], "hexpm"}, 5 | "earmark": {:hex, :earmark, "1.2.3", "206eb2e2ac1a794aa5256f3982de7a76bf4579ff91cb28d0e17ea2c9491e46a4", [:mix], [], "hexpm"}, 6 | "ex_doc": {:hex, :ex_doc, "0.16.4", "4bf6b82d4f0a643b500366ed7134896e8cccdbab4d1a7a35524951b25b1ec9f0", [:mix], [{:earmark, "~> 1.1", [hex: :earmark, repo: "hexpm", optional: false]}], "hexpm"}, 7 | "excoveralls": {:hex, :excoveralls, "0.6.0", "bd8565173ad1b97c29329dcbabb9effb56a5fcd1a698fd2097108dfe84b4c4ef", [:mix], [{:exjsx, "~> 3.0", [hex: :exjsx, optional: false]}, {:hackney, ">= 0.12.0", [hex: :hackney, optional: false]}]}, 8 | "exjsx": {:hex, :exjsx, "3.2.1", "1bc5bf1e4fd249104178f0885030bcd75a4526f4d2a1e976f4b428d347614f0f", [], [{:jsx, "~> 2.8.0", [hex: :jsx, optional: false]}]}, 9 | "gettext": {:hex, :gettext, "0.11.0", "80c1dd42d270482418fa158ec5ba073d2980e3718bacad86f3d4ad71d5667679", [:mix], []}, 10 | "hackney": {:hex, :hackney, "1.6.5", "8c025ee397ac94a184b0743c73b33b96465e85f90a02e210e86df6cbafaa5065", [:rebar3], [{:certifi, "0.7.0", [hex: :certifi, optional: false]}, {:idna, "1.2.0", [hex: :idna, optional: false]}, {:metrics, "1.0.1", [hex: :metrics, optional: false]}, {:mimerl, "1.0.2", [hex: :mimerl, optional: false]}, {:ssl_verify_fun, "1.1.1", [hex: :ssl_verify_fun, optional: false]}]}, 11 | "idna": {:hex, :idna, "1.2.0", "ac62ee99da068f43c50dc69acf700e03a62a348360126260e87f2b54eced86b2", [], []}, 12 | "jsx": {:hex, :jsx, "2.8.1", "1453b4eb3615acb3e2cd0a105d27e6761e2ed2e501ac0b390f5bbec497669846", [:mix, :rebar3], []}, 13 | "metrics": {:hex, :metrics, "1.0.1", "25f094dea2cda98213cecc3aeff09e940299d950904393b2a29d191c346a8486", [], []}, 14 | "mimerl": {:hex, :mimerl, "1.0.2", "993f9b0e084083405ed8252b99460c4f0563e41729ab42d9074fd5e52439be88", [], []}, 15 | "ssl_verify_fun": {:hex, :ssl_verify_fun, "1.1.1", "28a4d65b7f59893bc2c7de786dec1e1555bd742d336043fe644ae956c3497fbe", [:make, :rebar], []}, 16 | "ssl_verify_hostname": {:hex, :ssl_verify_hostname, "1.0.5"}, 17 | "timex": {:hex, :timex, "2.2.1", "0d69012a7fd69f4cbdaa00cc5f2a5f30f1bed56072fb362ed4bddf60db343022", [:mix], [{:combine, "~> 0.7", [hex: :combine, optional: false]}, {:gettext, "~> 0.10", [hex: :gettext, optional: false]}, {:tzdata, "~> 0.1.8 or ~> 0.5", [hex: :tzdata, optional: false]}]}, 18 | "tzdata": {:hex, :tzdata, "0.5.9", "575be217b039057a47e133b72838cbe104fb5329b19906ea4e66857001c37edb", [:mix], [{:hackney, "~> 1.0", [hex: :hackney, optional: false]}]}} 19 | -------------------------------------------------------------------------------- /test/aws_auth_test.exs: -------------------------------------------------------------------------------- 1 | defmodule AWSAuthTest do 2 | use ExUnit.Case 3 | 4 | @time ~N[2013-05-24 01:23:45] 5 | 6 | test "url signing" do 7 | signed_request = AWSAuth.sign_url("AKIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", 8 | "GET", 9 | "https://examplebucket.s3.amazonaws.com/test.txt", 10 | "us-east-1", 11 | "s3", 12 | Map.new, 13 | @time) |> URI.parse 14 | 15 | assert signed_request.host == "examplebucket.s3.amazonaws.com" 16 | assert signed_request.scheme == "https" 17 | assert signed_request.path == "/test.txt" 18 | 19 | expected_query_parts = [ 20 | {"X-Amz-Algorithm", "AWS4-HMAC-SHA256"}, 21 | {"X-Amz-Credential", "AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request"}, 22 | {"X-Amz-Date", "20130524T012345Z"}, 23 | {"X-Amz-Expires", "86400"}, 24 | {"X-Amz-Signature", "e78f6cd3458a7e2b49a5db198a304414581bc823a3d8160d6b1178bfd93c7026"}, 25 | {"X-Amz-SignedHeaders", "host"} 26 | ] 27 | 28 | query_parts = URI.query_decoder(signed_request.query) |> Enum.to_list 29 | assert query_parts == expected_query_parts 30 | end 31 | 32 | test "sign_authorization_header PUT" do 33 | headers = Map.new 34 | |> Map.put("Date", "Fri, 24 May 2013 00:00:00 GMT") 35 | |> Map.put("x-amz-storage-class", "REDUCED_REDUNDANCY") 36 | |> Map.put("x-amz-date", "20130524T000000Z") 37 | 38 | signed_request = AWSAuth.sign_authorization_header("AKIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", 39 | "PUT", 40 | "https://examplebucket.s3.amazonaws.com/test$file.text", 41 | "us-east-1", 42 | "s3", 43 | headers, 44 | "Welcome to Amazon S3.", 45 | @time) 46 | 47 | {"authorization", "AWS4-HMAC-SHA256 " <> request_parts} = signed_request |> List.keyfind("authorization", 0) 48 | 49 | request_parts = String.split(request_parts, ",") |> Enum.map(&(String.split(&1, "="))) 50 | assert request_parts == [ 51 | ["Credential", "AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request"], 52 | ["SignedHeaders", "date;host;x-amz-content-sha256;x-amz-date;x-amz-storage-class"], 53 | ["Signature", "cb26a806062d11d1ba2debc79cfebbe2bae32c39f039cbb4f7df09e9450c9caa"] 54 | ] 55 | end 56 | 57 | test "sign_query_parameters_request_with_multiple_headers" do 58 | headers = Map.new 59 | |> Map.put("x-amz-acl", "public-read") 60 | 61 | signed_request = AWSAuth.sign_url("AKIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", 62 | "PUT", 63 | "https://examplebucket.s3.amazonaws.com/test.txt", 64 | "us-east-1", 65 | "s3", 66 | headers, 67 | @time) |> URI.parse 68 | 69 | assert signed_request.host == "examplebucket.s3.amazonaws.com" 70 | assert signed_request.scheme == "https" 71 | assert signed_request.path == "/test.txt" 72 | 73 | expected_query_parts = [ 74 | {"X-Amz-Algorithm", "AWS4-HMAC-SHA256"}, 75 | {"X-Amz-Credential", "AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request"}, 76 | {"X-Amz-Date", "20130524T012345Z"}, 77 | {"X-Amz-Expires", "86400"}, 78 | {"X-Amz-Signature", "486cf3cae7cf411a757b859139da22000288900fa78c18377fd57f243bbc7d01"}, 79 | {"X-Amz-SignedHeaders", "host;x-amz-acl"} 80 | ] 81 | 82 | query_parts = URI.query_decoder(signed_request.query) |> Enum.to_list 83 | assert query_parts == expected_query_parts 84 | end 85 | end 86 | -------------------------------------------------------------------------------- /lib/aws_auth.ex: -------------------------------------------------------------------------------- 1 | defmodule AWSAuth do 2 | 3 | @moduledoc """ 4 | Signs urls or authentication headers for use with AWS requests 5 | """ 6 | 7 | @doc """ 8 | `AWSAuth.sign_url(access_key, secret_key, http_method, url, region, service, headers)` 9 | 10 | `access_key`: Your AWS Access key 11 | 12 | `secret_key`: Your AWS secret key 13 | 14 | `http_method`: "GET","POST","PUT","DELETE", etc 15 | 16 | `url`: The AWS url you want to sign 17 | 18 | `region`: The AWS name for the region you want to access (i.e. us-east-1). Check [here](http://docs.aws.amazon.com/general/latest/gr/rande.html) for the region names 19 | 20 | `service`: The AWS service you are trying to access (i.e. s3). Check the url above for names as well. 21 | 22 | `headers` (optional. defaults to `Map.new`): The headers that will be used in the request. Used for signing the request. 23 | For signing, host is the only one required unless using any other x-amx-* headers. 24 | If host is present here, it will override using the host in the url to attempt signing. 25 | If only the host is needed, then you don't have to supply it and the host from the url will be used. 26 | """ 27 | def sign_url(access_key, secret_key, http_method, url, region, service) do 28 | sign_url(access_key, secret_key, http_method, url, region, service, Map.new) 29 | end 30 | 31 | def sign_url(access_key, secret_key, http_method, url, region, service, headers) do 32 | sign_url(access_key, secret_key, http_method, url, region, service, headers, current_time()) 33 | end 34 | 35 | def sign_url(access_key, secret_key, http_method, url, region, service, headers, request_time) do 36 | sign_url(access_key, secret_key, http_method, url, region, service, headers, request_time, "") 37 | end 38 | 39 | def sign_url(access_key, secret_key, http_method, url, region, service, headers, request_time, payload) do 40 | AWSAuth.QueryParameters.sign(access_key, secret_key, http_method, url, region, service, headers, request_time, payload) 41 | end 42 | 43 | @doc """ 44 | `AWSAuth.sign_authorization_header(access_key, secret_key, http_method, url, region, service, headers, payload)` 45 | 46 | `access_key`: Your AWS Access key 47 | 48 | `secret_key`: Your AWS secret key 49 | 50 | `http_method`: "GET","POST","PUT","DELETE", etc 51 | 52 | `url`: The AWS url you want to sign 53 | 54 | `region`: The AWS name for the region you want to access (i.e. us-east-1). Check [here](http://docs.aws.amazon.com/general/latest/gr/rande.html) for the region names 55 | 56 | `service`: The AWS service you are trying to access (i.e. s3). Check the url above for names as well. 57 | 58 | `headers` (optional. defaults to `Map.new`): The headers that will be used in the request. Used for signing the request. 59 | For signing, host is the only one required unless using any other x-amx-* headers. 60 | If host is present here, it will override using the host in the url to attempt signing. 61 | Same goes for the x-amz-content-sha256 headers 62 | If only the host and x-amz-content-sha256 headers are needed, then you don't have to supply it and the host from the url will be used and 63 | the payload will be hashed to get the x-amz-content-sha256 header. 64 | 65 | `payload` (optional. defaults to `""`): The contents of the payload if there is one. 66 | """ 67 | def sign_authorization_header(access_key, secret_key, http_method, url, region, service) do 68 | sign_authorization_header(access_key, secret_key, http_method, url, region, service, Map.new) 69 | end 70 | 71 | def sign_authorization_header(access_key, secret_key, http_method, url, region, service, headers) do 72 | sign_authorization_header(access_key, secret_key, http_method, url, region, service, headers, "") 73 | end 74 | 75 | def sign_authorization_header(access_key, secret_key, http_method, url, region, service, headers, payload) do 76 | sign_authorization_header(access_key, secret_key, http_method, url, region, service, headers, payload, current_time()) 77 | end 78 | 79 | def sign_authorization_header(access_key, secret_key, http_method, url, region, service, headers, payload, request_time) do 80 | AWSAuth.AuthorizationHeader.sign(access_key, secret_key, http_method, url, region, service, payload, headers, request_time) 81 | end 82 | 83 | defp current_time do 84 | DateTime.utc_now |> DateTime.to_naive 85 | end 86 | end 87 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | AWSAuth 2 | ======= 3 | 4 | A small library used to sign AWS request urls using AWS Signature Version 4. 5 | 6 | Takes some inspiration from the [Simplex](https://github.com/adamkittelson/simplex) Library. 7 | 8 | Does both URL and Authorization Header signing. 9 | 10 | `AWSAuth.sign_url(access_key, secret_key, http_method, url, region, service, headers \\ Map.new)` 11 | 12 | `access_key`: Your AWS Access key 13 | 14 | `secret_key`: Your AWS secret key 15 | 16 | `http_method`: "GET","POST","PUT","DELETE", etc 17 | 18 | `url`: The AWS url you want to sign 19 | 20 | `region`: The AWS name for the region you want to access (i.e. us-east-1). Check [here](http://docs.aws.amazon.com/general/latest/gr/rande.html) for the region names 21 | 22 | `service`: The AWS service you are trying to access (i.e. s3). Check the url above for names as well. 23 | 24 | `headers` (optional): The headers that will be used in the request. Used for signing the request. For signing, host is the only one required unless using any other x-amx-* headers. If host is present here, it will override using the host in the url to attempt signing. If only the host is needed, then you don't have to supply it and the host from the url will be used. 25 | 26 | In most cases, you would probably call it like this (examples using the example access key and secret from AWS): 27 | 28 | ```elixir 29 | signed_request = AWSAuth.sign_url("AKIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", 30 | "GET", 31 | "https://examplebucket.s3.amazonaws.com/test.txt", 32 | "us-east-1", 33 | "s3") 34 | "https://examplebucket.s3.amazonaws.com/test.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20141219%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20141219T153739Z&X-Amz-Expires=86400&X-Amz-Signature=89d9f702dc8fb4fad2fd75bf07fc8468d60634f13234dd17e63835ed1fc324cd&X-Amz-SignedHeaders=host" 35 | ``` 36 | 37 | Or if you need to supply headers for signing, like this: 38 | 39 | ```elixir 40 | signed_request = AWSAuth.sign_url("AKIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", 41 | "GET", 42 | "https://examplebucket.s3.amazonaws.com/test.txt", 43 | "us-east-1", 44 | "s3", 45 | Map.new |> Map.put("x-amz-header","value")) 46 | "https://examplebucket.s3.amazonaws.com/test.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20141219%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20141219T153646Z&X-Amz-Expires=86400&X-Amz-Signature=b05688cc482398bf2d6ff4068560b85b310a6bb24c5d21711b7099ab5e3df510&X-Amz-SignedHeaders=host,x-amx-header" 47 | ``` 48 | 49 | 50 | Using the example from AWS (http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html) 51 | 52 | ```elixir 53 | signed_request = AWSAuth.sign_url("AKIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", 54 | "GET", 55 | "https://examplebucket.s3.amazonaws.com/test.txt", 56 | "us-east-1", 57 | "s3", 58 | Map.new, 59 | ~N[2013-05-24 00:00:00]) 60 | "https://examplebucket.s3.amazonaws.com/test.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20130524%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20130524T000000Z&X-Amz-Expires=86400&X-Amz-Signature=aeeed9bbccd4d02ee5c0109b86d86835f995330da4c265957d157751f604d404&X-Amz-SignedHeaders=host" 61 | ``` 62 | 63 | 64 | `AWSAuth.sign_authorization_header(access_key, secret_key, http_method, url, region, service, headers \\ Map.new, payload \\ "")` 65 | 66 | `access_key`: Your AWS Access key 67 | 68 | `secret_key`: Your AWS secret key 69 | 70 | `http_method`: "GET","POST","PUT","DELETE", etc 71 | 72 | `url`: The AWS url you want to sign 73 | 74 | `region`: The AWS name for the region you want to access (i.e. us-east-1). Check [here](http://docs.aws.amazon.com/general/latest/gr/rande.html) for the region names 75 | 76 | `service`: The AWS service you are trying to access (i.e. s3). Check the url above for names as well. 77 | 78 | `headers` (optional. defaults to `Map.new`): The headers that will be used in the request. Used for signing the request. 79 | For signing, host is the only one required unless using any other x-amx-* headers. 80 | If host is present here, it will override using the host in the url to attempt signing. 81 | Same goes for the x-amz-content-sha256 headers 82 | If only the host and x-amz-content-sha256 headers are needed, then you don't have to supply it and the host from the url will be used and 83 | the payload will be hashed to get the x-amz-content-sha256 header. 84 | 85 | `payload` (optional. defaults to `""`): The contents of the payload if there is one. 86 | 87 | 88 | ```elixir 89 | headers = Map.new 90 | |> Map.put("Date", "Fri, 24 May 2013 00:00:00 GMT") 91 | |> Map.put("x-amz-storage-class", "REDUCED_REDUNDANCY") 92 | |> Map.put("x-amz-date", "20130524T000000Z") 93 | 94 | signed_request = AWSAuth.sign_authorization_header("AKIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", 95 | "PUT", 96 | "https://examplebucket.s3.amazonaws.com/test$file.text", 97 | "us-east-1", 98 | "s3", 99 | headers, 100 | "Welcome to Amazon S3.") 101 | "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20141220/us-east-1/s3/aws4_request,SignedHeaders=date;host;x-amz-content-sha256;x-amz-date;x-amz-storage-class,Signature=dddba55b1ae5cd9233e9dc8e43a0daf6e2e120bec86294b1d80d802cab8af258" 102 | ``` 103 | 104 | Using the example from AWS (http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html) 105 | 106 | ```elixir 107 | headers = Map.new 108 | |> Map.put("Date", "Fri, 24 May 2013 00:00:00 GMT") 109 | |> Map.put("x-amz-storage-class", "REDUCED_REDUNDANCY") 110 | |> Map.put("x-amz-date", "20130524T000000Z") 111 | 112 | signed_request = AWSAuth.sign_authorization_header("AKIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", 113 | "PUT", 114 | "https://examplebucket.s3.amazonaws.com/test$file.text", 115 | "us-east-1", 116 | "s3", 117 | headers, 118 | "Welcome to Amazon S3.", 119 | ~N[2013-05-24 00:00:00]) 120 | "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request,SignedHeaders=date;host;x-amz-content-sha256;x-amz-date;x-amz-storage-class,Signature=98ad721746da40c64f1a55b78f14c238d841ea1380cd77a1b5971af0ece108bd" 121 | ``` 122 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2017 Bryan Joseph 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------