3 # In order to get a Blob from Keep, you have to prove either
4 # [a] you have recently written it to Keep yourself, or
5 # [b] apiserver has recently decided that you should be able to read it
7 # To ensure that the requestor of a blob is authorized to read it,
8 # Keep requires clients to timestamp the blob locator with an expiry
9 # time, and to sign the timestamped locator with their API token.
11 # A signed blob locator has the form:
12 # locator_hash +A blob_signature @ timestamp
13 # where the timestamp is a Unix time expressed as a hexadecimal value,
14 # and the blob_signature is the signed locator_hash + API token + timestamp.
16 class InvalidSignatureError < StandardError
19 # Blob.sign_locator: return a signed and timestamped blob locator.
21 # The 'opts' argument should include:
22 # [required] :key - the Arvados server-side blobstore key
23 # [required] :api_token - user's API token
24 # [optional] :ttl - number of seconds before signature should expire
25 # [optional] :expire - unix timestamp when signature should expire
27 def self.sign_locator blob_locator, opts
28 # We only use the hash portion for signatures.
29 blob_hash = blob_locator.split('+').first
31 # Generate an expiry timestamp (seconds after epoch, base 16)
34 raise "Cannot specify both :ttl and :expire options"
36 timestamp = opts[:expire]
38 timestamp = Time.now.to_i + (opts[:ttl] || 600)
40 timestamp_hex = timestamp.to_s(16)
43 # Generate a signature.
45 generate_signature opts[:key], blob_hash, opts[:api_token], timestamp_hex
47 blob_locator + '+A' + signature + '@' + timestamp_hex
50 # Blob.verify_signature
51 # Safely verify the signature on a blob locator.
52 # Return value: true if the locator has a valid signature, false otherwise
53 # Arguments: signed_blob_locator, opts
55 def self.verify_signature *args
57 self.verify_signature! *args
59 rescue Blob::InvalidSignatureError
64 # Blob.verify_signature!
65 # Verify the signature on a blob locator.
66 # Return value: true if the locator has a valid signature
67 # Arguments: signed_blob_locator, opts
69 # Blob::InvalidSignatureError if the blob locator does not include a
72 def self.verify_signature! signed_blob_locator, opts
73 blob_hash = signed_blob_locator.split('+').first
74 given_signature, timestamp = signed_blob_locator.
80 raise Blob::InvalidSignatureError.new 'No signature provided.'
82 if !timestamp.match /^[\da-f]+$/
83 raise Blob::InvalidSignatureError.new 'Timestamp is not a base16 number.'
85 if timestamp.to_i(16) < Time.now.to_i
86 raise Blob::InvalidSignatureError.new 'Signature expiry time has passed.'
90 generate_signature opts[:key], blob_hash, opts[:api_token], timestamp
92 if my_signature != given_signature
93 raise Blob::InvalidSignatureError.new 'Signature is invalid.'
99 def self.generate_signature key, blob_hash, api_token, timestamp
100 OpenSSL::HMAC.hexdigest('sha1', key,
103 timestamp].join('@'))