aws-s3-multi-region 0.6.3

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,222 @@
1
+ module AWS
2
+ module S3
3
+ # All authentication is taken care of for you by the AWS::S3 library. None the less, some details of the two types
4
+ # of authentication and when they are used may be of interest to some.
5
+ #
6
+ # === Header based authentication
7
+ #
8
+ # Header based authentication is achieved by setting a special <tt>Authorization</tt> header whose value
9
+ # is formatted like so:
10
+ #
11
+ # "AWS #{access_key_id}:#{encoded_canonical}"
12
+ #
13
+ # The <tt>access_key_id</tt> is the public key that is assigned by Amazon for a given account which you use when
14
+ # establishing your initial connection. The <tt>encoded_canonical</tt> is computed according to rules layed out
15
+ # by Amazon which we will describe presently.
16
+ #
17
+ # ==== Generating the encoded canonical string
18
+ #
19
+ # The "canonical string", generated by the CanonicalString class, is computed by collecting the current request method,
20
+ # a set of significant headers of the current request, and the current request path into a string.
21
+ # That canonical string is then encrypted with the <tt>secret_access_key</tt> assigned by Amazon. The resulting encrypted canonical
22
+ # string is then base 64 encoded.
23
+ #
24
+ # === Query string based authentication
25
+ #
26
+ # When accessing a restricted object from the browser, you can authenticate via the query string, by setting the following parameters:
27
+ #
28
+ # "AWSAccessKeyId=#{access_key_id}&Expires=#{expires}&Signature=#{encoded_canonical}"
29
+ #
30
+ # The QueryString class is responsible for generating the appropriate parameters for authentication via the
31
+ # query string.
32
+ #
33
+ # The <tt>access_key_id</tt> and <tt>encoded_canonical</tt> are the same as described in the Header based authentication section.
34
+ # The <tt>expires</tt> value dictates for how long the current url is valid (by default, it will expire in 5 minutes). Expiration can be specified
35
+ # either by an absolute time (expressed in seconds since the epoch), or in relative time (in number of seconds from now).
36
+ # Details of how to customize the expiration of the url are provided in the documentation for the QueryString class.
37
+ #
38
+ # All requests made by this library use header authentication. When a query string authenticated url is needed,
39
+ # the S3Object#url method will include the appropriate query string parameters.
40
+ #
41
+ # === Full authentication specification
42
+ #
43
+ # The full specification of the authentication protocol can be found at
44
+ # http://docs.amazonwebservices.com/AmazonS3/2006-03-01/RESTAuthentication.html
45
+ class Authentication
46
+ constant :AMAZON_HEADER_PREFIX, 'x-amz-'
47
+
48
+ # Signature is the abstract super class for the Header and QueryString authentication methods. It does the job
49
+ # of computing the canonical_string using the CanonicalString class as well as encoding the canonical string. The subclasses
50
+ # parameterize these computations and arrange them in a string form appropriate to how they are used, in one case a http request
51
+ # header value, and in the other case key/value query string parameter pairs.
52
+ class Signature < String #:nodoc:
53
+ attr_reader :request, :access_key_id, :secret_access_key, :current_host, :options
54
+
55
+ def initialize(request, access_key_id, secret_access_key, current_host, options = {})
56
+ super()
57
+ @request, @access_key_id, @secret_access_key, @current_host = request, access_key_id, secret_access_key, current_host
58
+ @options = options
59
+ end
60
+
61
+ private
62
+
63
+ def canonical_string
64
+ options = {}
65
+ options[:expires] = expires if expires?
66
+ CanonicalString.new(request, current_host, options)
67
+ end
68
+ memoized :canonical_string
69
+
70
+ def encoded_canonical
71
+ digest = OpenSSL::Digest::Digest.new('sha1')
72
+ b64_hmac = [OpenSSL::HMAC.digest(digest, secret_access_key, canonical_string)].pack("m").strip
73
+ url_encode? ? CGI.escape(b64_hmac) : b64_hmac
74
+ end
75
+
76
+ def url_encode?
77
+ !@options[:url_encode].nil?
78
+ end
79
+
80
+ def expires?
81
+ is_a? QueryString
82
+ end
83
+
84
+ def date
85
+ request['date'].to_s.strip.empty? ? Time.now : Time.parse(request['date'])
86
+ end
87
+ end
88
+
89
+ # Provides header authentication by computing the value of the Authorization header. More details about the
90
+ # various authentication schemes can be found in the docs for its containing module, Authentication.
91
+ class Header < Signature #:nodoc:
92
+ def initialize(*args)
93
+ super
94
+ self << "AWS #{access_key_id}:#{encoded_canonical}"
95
+ end
96
+ end
97
+
98
+ # Provides query string authentication by computing the three authorization parameters: AWSAccessKeyId, Expires and Signature.
99
+ # More details about the various authentication schemes can be found in the docs for its containing module, Authentication.
100
+ class QueryString < Signature #:nodoc:
101
+ constant :DEFAULT_EXPIRY, 300 # 5 minutes
102
+ def initialize(*args)
103
+ super
104
+ options[:url_encode] = true
105
+ self << build
106
+ end
107
+
108
+ private
109
+
110
+ # Will return one of three values, in the following order of precedence:
111
+ #
112
+ # 1) Seconds since the epoch explicitly passed in the +:expires+ option
113
+ # 2) The current time in seconds since the epoch plus the number of seconds passed in
114
+ # the +:expires_in+ option
115
+ # 3) The current time in seconds since the epoch plus the default number of seconds (60 seconds)
116
+ def expires
117
+ return options[:expires] if options[:expires]
118
+ date.to_i + expires_in
119
+ end
120
+
121
+ def expires_in
122
+ options.has_key?(:expires_in) ? Integer(options[:expires_in]) : DEFAULT_EXPIRY
123
+ end
124
+
125
+ # Keep in alphabetical order
126
+ def build
127
+ "AWSAccessKeyId=#{access_key_id}&Expires=#{expires}&Signature=#{encoded_canonical}"
128
+ end
129
+ end
130
+
131
+ # The CanonicalString is used to generate an encrypted signature, signed with your secrect access key. It is composed of
132
+ # data related to the given request for which it provides authentication. This data includes the request method, request headers,
133
+ # and the request path. Both Header and QueryString use it to generate their signature.
134
+ class CanonicalString < String #:nodoc:
135
+ class << self
136
+ def default_headers
137
+ %w(content-type content-md5)
138
+ end
139
+
140
+ def interesting_headers
141
+ ['content-md5', 'content-type', 'date', 'Host', amazon_header_prefix]
142
+ end
143
+
144
+ def amazon_header_prefix
145
+ /^#{AMAZON_HEADER_PREFIX}/io
146
+ end
147
+ end
148
+
149
+ attr_reader :request, :headers, :current_host
150
+
151
+ def initialize(request, current_host, options = {})
152
+ super()
153
+ @request = request
154
+ @current_host = current_host
155
+ @headers = {}
156
+ @options = options
157
+ # "For non-authenticated or anonymous requests. A NotImplemented error result code will be returned if
158
+ # an authenticated (signed) request specifies a Host: header other than 's3.amazonaws.com'"
159
+ # (from http://docs.amazonwebservices.com/AmazonS3/2006-03-01/VirtualHosting.html)
160
+ request['Host'] ||= DEFAULT_HOST
161
+ build
162
+ end
163
+
164
+ private
165
+ def build
166
+ self << "#{request.method}\n"
167
+ ensure_date_is_valid
168
+
169
+ initialize_headers
170
+ set_expiry!
171
+
172
+ headers.sort_by {|k, _| k}.each do |key, value|
173
+ value = value.to_s.strip
174
+ self << (key =~ self.class.amazon_header_prefix ? "#{key}:#{value}" : value)
175
+ self << "\n"
176
+ end
177
+ self << path
178
+ end
179
+
180
+ def initialize_headers
181
+ identify_interesting_headers
182
+ set_default_headers
183
+ end
184
+
185
+ def set_expiry!
186
+ self.headers['date'] = @options[:expires] if @options[:expires]
187
+ end
188
+
189
+ def ensure_date_is_valid
190
+ request['Date'] ||= Time.now.httpdate
191
+ end
192
+
193
+ def identify_interesting_headers
194
+ request.each do |key, value|
195
+ key = key.downcase # Can't modify frozen string so no bang
196
+ if self.class.interesting_headers.any? {|header| header === key}
197
+ self.headers[key] = value.to_s.strip
198
+ end
199
+ end
200
+ end
201
+
202
+ def set_default_headers
203
+ self.class.default_headers.each do |header|
204
+ self.headers[header] ||= ''
205
+ end
206
+ end
207
+
208
+ def path
209
+ [only_path, extract_significant_parameter].compact.join('?')
210
+ end
211
+
212
+ def extract_significant_parameter
213
+ request.path[/[&?](acl|torrent|logging)(?:&|=|$)/, 1]
214
+ end
215
+
216
+ def only_path
217
+ (current_host.nil? ? '' : "/#{current_host}") << request.path[/^[^?]*/]
218
+ end
219
+ end
220
+ end
221
+ end
222
+ end
@@ -0,0 +1,269 @@
1
+ module AWS #:nodoc:
2
+ # AWS::S3 is a Ruby library for Amazon's Simple Storage Service's REST API (http://aws.amazon.com/s3).
3
+ # Full documentation of the currently supported API can be found at http://docs.amazonwebservices.com/AmazonS3/2006-03-01.
4
+ #
5
+ # == Getting started
6
+ #
7
+ # To get started you need to require 'aws/s3':
8
+ #
9
+ # % irb -rubygems
10
+ # irb(main):001:0> require 'aws/s3'
11
+ # # => true
12
+ #
13
+ # The AWS::S3 library ships with an interactive shell called <tt>s3sh</tt>. From within it, you have access to all the operations the library exposes from the command line.
14
+ #
15
+ # % s3sh
16
+ # >> Version
17
+ #
18
+ # Before you can do anything, you must establish a connection using Base.establish_connection!. A basic connection would look something like this:
19
+ #
20
+ # AWS::S3::Base.establish_connection!(
21
+ # :access_key_id => 'abc',
22
+ # :secret_access_key => '123'
23
+ # )
24
+ #
25
+ # The minimum connection options that you must specify are your access key id and your secret access key.
26
+ #
27
+ # (If you don't already have your access keys, all you need to sign up for the S3 service is an account at Amazon. You can sign up for S3 and get access keys by visiting http://aws.amazon.com/s3.)
28
+ #
29
+ # For convenience, if you set two special environment variables with the value of your access keys, the console will automatically create a default connection for you. For example:
30
+ #
31
+ # % cat .amazon_keys
32
+ # export AMAZON_ACCESS_KEY_ID='abcdefghijklmnop'
33
+ # export AMAZON_SECRET_ACCESS_KEY='1234567891012345'
34
+ #
35
+ # Then load it in your shell's rc file.
36
+ #
37
+ # % cat .zshrc
38
+ # if [[ -f "$HOME/.amazon_keys" ]]; then
39
+ # source "$HOME/.amazon_keys";
40
+ # fi
41
+ #
42
+ # See more connection details at AWS::S3::Connection::Management::ClassMethods.
43
+ module S3
44
+ constant :DEFAULT_HOST, 's3.amazonaws.com'
45
+
46
+ # AWS::S3::Base is the abstract super class of all classes who make requests against S3, such as the built in
47
+ # Service, Bucket and S3Object classes. It provides methods for making requests, inferring or setting response classes,
48
+ # processing request options, and accessing attributes from S3's response data.
49
+ #
50
+ # Establishing a connection with the Base class is the entry point to using the library:
51
+ #
52
+ # AWS::S3::Base.establish_connection!(:access_key_id => '...', :secret_access_key => '...')
53
+ #
54
+ # The <tt>:access_key_id</tt> and <tt>:secret_access_key</tt> are the two required connection options. More
55
+ # details can be found in the docs for Connection::Management::ClassMethods.
56
+ #
57
+ # Extensive examples can be found in the README[link:files/README.html].
58
+ class Base
59
+ cattr_reader :current_host
60
+
61
+ class << self
62
+ # Wraps the current connection's request method and picks the appropriate response class to wrap the response in.
63
+ # If the response is an error, it will raise that error as an exception. All such exceptions can be caught by rescuing
64
+ # their superclass, the ResponseError exception class.
65
+ #
66
+ # It is unlikely that you would call this method directly. Subclasses of Base have convenience methods for each http request verb
67
+ # that wrap calls to request.
68
+ def request(verb, path, options = {}, body = nil, attempts = 0, &block)
69
+ Service.response = nil
70
+ process_options!(options, verb)
71
+ response = response_class.new(connection.request(verb, path, options, body, attempts, current_host, &block))
72
+ Service.response = response
73
+
74
+ Error::Response.new(response.response).error.raise if response.error?
75
+ if attempts > 0 and !current_host.match(".#{DEFAULT_HOST}")
76
+ establish_connection!(:server => DEFAULT_HOST)
77
+ end
78
+ response
79
+ # Once in a while, a request to S3 returns an internal error. A glitch in the matrix I presume. Since these
80
+ # errors are few and far between the request method will rescue InternalErrors the first three times they encouter them
81
+ # and will retry the request again. Most of the time the second attempt will work.
82
+ rescue InternalError, RequestTimeout
83
+ if attempts == 3
84
+ raise
85
+ else
86
+ attempts += 1
87
+ retry
88
+ end
89
+ rescue
90
+ raise unless response
91
+ if response.redirect?
92
+ new_host = response.parsed["endpoint"]
93
+ establish_connection!(:server => new_host)
94
+ end
95
+ attempts == 3 || !response.redirect? ? raise : (attempts += 1; retry)
96
+ end
97
+
98
+ [:get, :post, :put, :delete, :head].each do |verb|
99
+ class_eval(<<-EVAL, __FILE__, __LINE__)
100
+ def #{verb}(path, headers = {}, body = nil, &block)
101
+ request(:#{verb}, path, headers, body, &block)
102
+ end
103
+ EVAL
104
+ end
105
+
106
+ # Called when a method which requires a bucket name is called without that bucket name specified. It will try to
107
+ # infer the current bucket by looking for it as the subdomain of the current connection's address. If no subdomain
108
+ # is found, CurrentBucketNotSpecified will be raised.
109
+ #
110
+ # MusicBucket.establish_connection! :server => 'jukeboxzero.s3.amazonaws.com'
111
+ # MusicBucket.connection.server
112
+ # => 'jukeboxzero.s3.amazonaws.com'
113
+ # MusicBucket.current_bucket
114
+ # => 'jukeboxzero'
115
+ #
116
+ # Rather than infering the current bucket from the subdomain, the current class' bucket can be explicitly set with
117
+ # set_current_bucket_to.
118
+ def current_bucket
119
+ connection.subdomain or raise CurrentBucketNotSpecified.new(connection.http.address)
120
+ end
121
+
122
+ def current_host
123
+ @@current_host
124
+ end
125
+
126
+ def current_host=(host)
127
+ @@current_host = host
128
+ end
129
+
130
+ # If you plan on always using a specific bucket for certain files, you can skip always having to specify the bucket by creating
131
+ # a subclass of Bucket or S3Object and telling it what bucket to use:
132
+ #
133
+ # class JukeBoxSong < AWS::S3::S3Object
134
+ # set_current_bucket_to 'jukebox'
135
+ # end
136
+ #
137
+ # For all methods that take a bucket name as an argument, the current bucket will be used if the bucket name argument is omitted.
138
+ #
139
+ # other_song = 'baby-please-come-home.mp3'
140
+ # JukeBoxSong.store(other_song, open(other_song))
141
+ #
142
+ # This time we didn't have to explicitly pass in the bucket name, as the JukeBoxSong class knows that it will
143
+ # always use the 'jukebox' bucket.
144
+ #
145
+ # "Astute readers", as they say, may have noticed that we used the third parameter to pass in the content type,
146
+ # rather than the fourth parameter as we had the last time we created an object. If the bucket can be inferred, or
147
+ # is explicitly set, as we've done in the JukeBoxSong class, then the third argument can be used to pass in
148
+ # options.
149
+ #
150
+ # Now all operations that would have required a bucket name no longer do.
151
+ #
152
+ # other_song = JukeBoxSong.find('baby-please-come-home.mp3')
153
+ def set_current_bucket_to(name)
154
+ raise ArgumentError, "`#{__method__}' must be called on a subclass of #{self.name}" if self == AWS::S3::Base
155
+ instance_eval(<<-EVAL)
156
+ def current_bucket
157
+ '#{name}'
158
+ end
159
+ EVAL
160
+ end
161
+ alias_method :current_bucket=, :set_current_bucket_to
162
+
163
+ private
164
+
165
+ def response_class
166
+ FindResponseClass.for(self)
167
+ end
168
+
169
+ def process_options!(options, verb)
170
+ options.replace(RequestOptions.process(options, verb))
171
+ end
172
+
173
+ # Using the conventions layed out in the <tt>response_class</tt> works for more than 80% of the time.
174
+ # There are a few edge cases though where we want a given class to wrap its responses in different
175
+ # response classes depending on which method is being called.
176
+ def respond_with(klass)
177
+ eval(<<-EVAL, binding, __FILE__, __LINE__)
178
+ def new_response_class
179
+ #{klass}
180
+ end
181
+
182
+ class << self
183
+ alias_method :old_response_class, :response_class
184
+ alias_method :response_class, :new_response_class
185
+ end
186
+ EVAL
187
+
188
+ yield
189
+ ensure
190
+ # Restore the original version
191
+ eval(<<-EVAL, binding, __FILE__, __LINE__)
192
+ class << self
193
+ alias_method :response_class, :old_response_class
194
+ end
195
+ EVAL
196
+ end
197
+
198
+ def bucket_name(name)
199
+ name || current_bucket
200
+ end
201
+
202
+ class RequestOptions < Hash #:nodoc:
203
+ attr_reader :options, :verb
204
+
205
+ class << self
206
+ def process(*args, &block)
207
+ new(*args, &block).process!
208
+ end
209
+ end
210
+
211
+ def initialize(options, verb = :get)
212
+ @options = options.to_normalized_options
213
+ @verb = verb
214
+ super()
215
+ end
216
+
217
+ def process!
218
+ set_access_controls! if verb == :put
219
+ replace(options)
220
+ end
221
+
222
+ private
223
+ def set_access_controls!
224
+ ACL::OptionProcessor.process!(options)
225
+ end
226
+ end
227
+ end
228
+
229
+ def initialize(attributes = {}) #:nodoc:
230
+ @attributes = attributes
231
+ end
232
+
233
+ private
234
+ attr_reader :attributes
235
+
236
+ def current_host
237
+ self.class.current_host
238
+ end
239
+
240
+ def current_host=(host)
241
+ self.class.current_host = host
242
+ end
243
+
244
+ def connection
245
+ self.class.connection
246
+ end
247
+
248
+ def http
249
+ connection.http
250
+ end
251
+
252
+ def request(*args, &block)
253
+ self.class.request(*args, &block)
254
+ end
255
+
256
+ def method_missing(method, *args, &block)
257
+ case
258
+ when attributes.has_key?(method.to_s)
259
+ attributes[method.to_s]
260
+ when attributes.has_key?(method)
261
+ attributes[method]
262
+ else
263
+ super
264
+ end
265
+ end
266
+
267
+ end
268
+ end
269
+ end