Backwards compatibility for MultiJson.
[arvados.git] / lib / google / api_client / service_account.rb
1 # Copyright 2010 Google Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #      http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 require 'jwt'
16 require 'signet/oauth_2/client'
17
18 module Google
19   class APIClient
20     ##
21     # Helper for loading keys from the PKCS12 files downloaded when
22     # setting up service accounts at the APIs Console.
23     module PKCS12
24       
25       ##
26       # Loads a key from PKCS12 file, assuming a single private key
27       # is present.
28       #
29       # @param [String] keyfile
30       #    Path of the PKCS12 file to load. If not a path to an actual file,
31       #    assumes the string is the content of the file itself. 
32       # @param [String] passphrase
33       #   Passphrase for unlocking the private key
34       #
35       # @return [OpenSSL::PKey] The private key for signing assertions.
36       def self.load_key(keyfile, passphrase)
37         begin
38           if File.exists?(keyfile)
39             content = File.read(keyfile)
40           else
41             content = keyfile
42           end  
43           pkcs12 = OpenSSL::PKCS12.new(content, passphrase)
44           return pkcs12.key
45         rescue OpenSSL::PKCS12::PKCS12Error
46           raise ArgumentError.new("Invalid keyfile or passphrase")
47         end
48       end
49     end
50
51     ##
52     # Generates access tokens using the JWT assertion profile. Requires a
53     # service account & access to the private key.
54     class JWTAsserter
55       attr_accessor :issuer, :expiry
56       attr_reader :scope
57       attr_writer :key
58
59       ##
60       # Initializes the asserter for a service account.
61       #
62       # @param [String] issuer
63       #    Name/ID of the client issuing the assertion
64       # @param [String or Array] scope
65       #   Scopes to authorize. May be a space delimited string or array of strings
66       # @param [OpenSSL::PKey]
67       #   RSA private key for signing assertions
68       def initialize(issuer, scope, key)
69         self.issuer = issuer
70         self.scope = scope
71         self.expiry = 60 # 1 min default        
72         self.key = key
73       end
74
75       ##
76       # Set the scopes to authorize
77       #
78       # @param [String or Array] scope
79       #   Scopes to authorize. May be a space delimited string or array of strings
80       def scope=(new_scope)
81         case new_scope
82         when Array
83           @scope = new_scope.join(' ')
84         when String
85           @scope = new_scope
86         when nil
87           @scope = ''
88         else
89           raise TypeError, "Expected Array or String, got #{new_scope.class}"
90         end
91       end
92       
93       ##
94       # Builds & signs the assertion.
95       # 
96       # @param [String] person
97       #   Email address of a user, if requesting a token to act on their behalf
98       # @return [String] Encoded JWT
99       def to_jwt(person=nil)
100         now = Time.new        
101         assertion = {
102           "iss" => @issuer,
103           "scope" => self.scope,
104           "aud" => "https://accounts.google.com/o/oauth2/token",
105           "exp" => (now + expiry).to_i,
106           "iat" => now.to_i
107         }
108         assertion['prn'] = person unless person.nil?
109         return JWT.encode(assertion, @key, "RS256")
110       end
111
112       ##
113       # Request a new access token.
114       # 
115       # @param [String] person
116       #   Email address of a user, if requesting a token to act on their behalf
117       # @param [Hash] options
118       #   Pass through to Signet::OAuth2::Client.fetch_access_token
119       # @return [Signet::OAuth2::Client] Access token 
120       #
121       # @see Signet::OAuth2::Client.fetch_access_token
122       def authorize(person = nil, options={})
123         assertion = self.to_jwt(person)
124         authorization = Signet::OAuth2::Client.new(
125           :token_credential_uri => 'https://accounts.google.com/o/oauth2/token'
126         )
127         authorization.grant_type = 'urn:ietf:params:oauth:grant-type:jwt-bearer'
128         authorization.extension_parameters = { :assertion => assertion }
129         authorization.fetch_access_token!(options)
130         return authorization
131       end
132     end
133   end
134 end