Doc improvements
[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     #
24
25     module PKCS12
26       
27       ##
28       # Loads a key from PKCS12 file, assuming a single private key
29       # is present.
30       #
31       # @param [String] keyfile
32       #    Path of the PKCS12 file to load. If not a path to an actual file,
33       #    assumes the string is the content of the file itself. 
34       # @param [String] passphrase
35       #   Passphrase for unlocking the private key
36       #
37       # @return [OpenSSL::PKey] The private key for signing assertions.
38       def self.load_key(keyfile, passphrase)
39         begin
40           if File.exists?(keyfile)
41             content = File.read(keyfile)
42           else
43             content = keyfile
44           end  
45           pkcs12 = OpenSSL::PKCS12.new(content, passphrase)
46           return pkcs12.key
47         rescue OpenSSL::PKCS12::PKCS12Error
48           raise ArgumentError.new("Invalid keyfile or passphrase")
49         end
50       end
51     end
52
53     ##
54     # Generates access tokens using the JWT assertion profile. Requires a
55     # service account & access to the private key.
56     #
57     # @example
58     #
59     #    client = Google::APIClient.new
60     #    key = Google::APIClient::PKCS12.load_key('client.p12', 'notasecret')
61     #    service_account = Google::APIClient::JWTAsserter(
62     #        '123456-abcdef@developer.gserviceaccount.com',
63     #        'https://www.googleapis.com/auth/prediction',
64     #        key)
65     #    client.authorization = service_account.authorize
66     #    client.execute(...)
67     #
68     # @see https://developers.google.com/accounts/docs/OAuth2ServiceAccount
69     class JWTAsserter
70       # @return [String] ID/email of the issuing party
71       attr_accessor :issuer
72       # @return [Fixnum] How long, in seconds, the assertion is valid for
73       attr_accessor :expiry
74       # @return [Fixnum] Seconds to expand the issued at/expiry window to account for clock skew
75       attr_accessor :skew
76       # @return [String] Scopes to authorize
77       attr_reader :scope
78       # @return [OpenSSL::PKey] key for signing assertions
79       attr_writer :key
80
81       ##
82       # Initializes the asserter for a service account.
83       #
84       # @param [String] issuer
85       #    Name/ID of the client issuing the assertion
86       # @param [String, Array] scope
87       #   Scopes to authorize. May be a space delimited string or array of strings
88       # @param [OpenSSL::PKey] key
89       #   RSA private key for signing assertions
90       def initialize(issuer, scope, key)
91         self.issuer = issuer
92         self.scope = scope
93         self.expiry = 60 # 1 min default 
94         self.skew = 60      
95         self.key = key
96       end
97
98       ##
99       # Set the scopes to authorize
100       #
101       # @param [String, Array] new_scope
102       #   Scopes to authorize. May be a space delimited string or array of strings
103       def scope=(new_scope)
104         case new_scope
105         when Array
106           @scope = new_scope.join(' ')
107         when String
108           @scope = new_scope
109         when nil
110           @scope = ''
111         else
112           raise TypeError, "Expected Array or String, got #{new_scope.class}"
113         end
114       end
115       
116       ##
117       # Builds & signs the assertion.
118       # 
119       # @param [String] person
120       #   Email address of a user, if requesting a token to act on their behalf
121       # @return [String] Encoded JWT
122       def to_jwt(person=nil)
123         now = Time.new        
124         assertion = {
125           "iss" => @issuer,
126           "scope" => self.scope,
127           "aud" => "https://accounts.google.com/o/oauth2/token",
128           "exp" => (now + expiry).to_i,
129           "iat" => (now - skew).to_i
130         }
131         assertion['prn'] = person unless person.nil?
132         return JWT.encode(assertion, @key, "RS256")
133       end
134
135       ##
136       # Request a new access token.
137       # 
138       # @param [String] person
139       #   Email address of a user, if requesting a token to act on their behalf
140       # @param [Hash] options
141       #   Pass through to Signet::OAuth2::Client.fetch_access_token
142       # @return [Signet::OAuth2::Client] Access token 
143       #
144       # @see Signet::OAuth2::Client.fetch_access_token
145       def authorize(person = nil, options={})
146         assertion = self.to_jwt(person)
147         authorization = Signet::OAuth2::Client.new(
148           :token_credential_uri => 'https://accounts.google.com/o/oauth2/token'
149         )
150         authorization.grant_type = 'urn:ietf:params:oauth:grant-type:jwt-bearer'
151         authorization.extension_parameters = { :assertion => assertion }
152         authorization.fetch_access_token!(options)
153         return authorization
154       end
155     end
156   end
157 end