Created
July 9, 2013 03:18
-
-
Save hectcastro/5954428 to your computer and use it in GitHub Desktop.
Ruby implementation of query string authentication for a local Riak CS instance.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# encoding: utf-8 | |
require "cgi" | |
require "base64" | |
require "openssl" | |
require "net/http" | |
ACCESS_KEY = ENV["AWS_ACCESS_KEY_ID"] | |
SECRET_KEY = ENV["AWS_SECRET_ACCESS_KEY"] | |
def http_get(resource_url) | |
uri = URI(resource_url) | |
Net::HTTP.start(uri.host, uri.port) do |http| | |
request = Net::HTTP::Get.new(uri.request_uri, { "Host" => "s3.amazonaws.com" }) | |
response = http.request(request) | |
response.body | |
end | |
end | |
def sign(secret_key, string_to_sign, digest_method="sha1") | |
Base64.encode64(hmac(secret_key, string_to_sign, digest_method)).strip | |
end | |
def hmac(secret_key, string_to_sign, digest="sha1") | |
OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new(digest), secret_key, string_to_sign) | |
end | |
def canonicalized_resource(bucket, path) | |
parts = [ ] | |
parts << "/%s" % [ bucket ] | |
parts << path | |
parts.join | |
end | |
def get_signature(bucket, path, expires, secret_key) | |
parts = [ ] | |
parts << "GET" | |
parts << "" # MD5 | |
parts << "" # Content type | |
parts << expires | |
parts << canonicalized_resource(bucket, path) | |
string_to_sign = parts.join("\n") | |
sign(secret_key, string_to_sign) | |
end | |
def presigned_get(root_url, bucket, path, expires, access_id, secret_key) | |
expires = (Time.now.to_i + expires).to_s | |
signature = CGI.escape(get_signature(bucket, path, expires, secret_key)) | |
presigned_url = "%s/%s%s?AWSAccessKeyId=%s&Expires=%s&Signature=%s" % [ | |
root_url, bucket, path, access_id, expires, signature ] | |
http_get(presigned_url) | |
end | |
# --- | |
p presigned_get("http://127.0.0.1:8080", "test", "/introduction-to-riak-and-riak-cs.key", 1000, ACCESS_KEY, SECRET_KEY) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment