8 !!@locator.match(/^d41d8cd98f00b204e9800998ecf8427e(\+.*)?$/)
11 # In order to get a Blob from Keep, you have to prove either
12 # [a] you have recently written it to Keep yourself, or
13 # [b] apiserver has recently decided that you should be able to read it
15 # To ensure that the requestor of a blob is authorized to read it,
16 # Keep requires clients to timestamp the blob locator with an expiry
17 # time, and to sign the timestamped locator with their API token.
19 # A signed blob locator has the form:
20 # locator_hash +A blob_signature @ timestamp
21 # where the timestamp is a Unix time expressed as a hexadecimal value,
22 # and the blob_signature is the signed locator_hash + API token + timestamp.
24 class InvalidSignatureError < StandardError
27 # Blob.sign_locator: return a signed and timestamped blob locator.
29 # The 'opts' argument should include:
30 # [required] :key - the Arvados server-side blobstore key
31 # [required] :api_token - user's API token
32 # [optional] :ttl - number of seconds before signature should expire
33 # [optional] :expire - unix timestamp when signature should expire
35 def self.sign_locator blob_locator, opts
36 # We only use the hash portion for signatures.
37 blob_hash = blob_locator.split('+').first
39 # Generate an expiry timestamp (seconds after epoch, base 16)
42 raise "Cannot specify both :ttl and :expire options"
44 timestamp = opts[:expire]
46 timestamp = Time.now.to_i + (opts[:ttl] || 1209600)
48 timestamp_hex = timestamp.to_s(16)
51 # Generate a signature.
53 generate_signature opts[:key], blob_hash, opts[:api_token], timestamp_hex
55 blob_locator + '+A' + signature + '@' + timestamp_hex
58 # Blob.verify_signature
59 # Safely verify the signature on a blob locator.
60 # Return value: true if the locator has a valid signature, false otherwise
61 # Arguments: signed_blob_locator, opts
63 def self.verify_signature *args
65 self.verify_signature! *args
67 rescue Blob::InvalidSignatureError
72 # Blob.verify_signature!
73 # Verify the signature on a blob locator.
74 # Return value: true if the locator has a valid signature
75 # Arguments: signed_blob_locator, opts
77 # Blob::InvalidSignatureError if the blob locator does not include a
80 def self.verify_signature! signed_blob_locator, opts
81 blob_hash = signed_blob_locator.split('+').first
82 given_signature, timestamp = signed_blob_locator.
88 raise Blob::InvalidSignatureError.new 'No signature provided.'
90 if !timestamp.match /^[\da-f]+$/
91 raise Blob::InvalidSignatureError.new 'Timestamp is not a base16 number.'
93 if timestamp.to_i(16) < Time.now.to_i
94 raise Blob::InvalidSignatureError.new 'Signature expiry time has passed.'
98 generate_signature opts[:key], blob_hash, opts[:api_token], timestamp
100 if my_signature != given_signature
101 raise Blob::InvalidSignatureError.new 'Signature is invalid.'
107 def self.generate_signature key, blob_hash, api_token, timestamp
108 OpenSSL::HMAC.hexdigest('sha1', key,
111 timestamp].join('@'))