Re-org service account support
[arvados.git] / lib / google / api_client / auth / jwt_asserter.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     # Generates access tokens using the JWT assertion profile. Requires a
22     # service account & access to the private key.
23     #
24     # @example
25     #
26     #    client = Google::APIClient.new
27     #    key = Google::APIClient::PKCS12.load_key('client.p12', 'notasecret')
28     #    service_account = Google::APIClient::JWTAsserter(
29     #        '123456-abcdef@developer.gserviceaccount.com',
30     #        'https://www.googleapis.com/auth/prediction',
31     #        key)
32     #    client.authorization = service_account.authorize
33     #    client.execute(...)
34     #
35     # @see https://developers.google.com/accounts/docs/OAuth2ServiceAccount
36     class JWTAsserter
37       # @return [String] ID/email of the issuing party
38       attr_accessor :issuer
39       # @return [Fixnum] How long, in seconds, the assertion is valid for
40       attr_accessor :expiry
41       # @return [Fixnum] Seconds to expand the issued at/expiry window to account for clock skew
42       attr_accessor :skew
43       # @return [String] Scopes to authorize
44       attr_reader :scope
45       # @return [OpenSSL::PKey] key for signing assertions
46       attr_writer :key
47
48       ##
49       # Initializes the asserter for a service account.
50       #
51       # @param [String] issuer
52       #    Name/ID of the client issuing the assertion
53       # @param [String, Array] scope
54       #   Scopes to authorize. May be a space delimited string or array of strings
55       # @param [OpenSSL::PKey] key
56       #   RSA private key for signing assertions
57       def initialize(issuer, scope, key)
58         self.issuer = issuer
59         self.scope = scope
60         self.expiry = 60 # 1 min default 
61         self.skew = 60      
62         self.key = key
63       end
64
65       ##
66       # Set the scopes to authorize
67       #
68       # @param [String, Array] new_scope
69       #   Scopes to authorize. May be a space delimited string or array of strings
70       def scope=(new_scope)
71         case new_scope
72         when Array
73           @scope = new_scope.join(' ')
74         when String
75           @scope = new_scope
76         when nil
77           @scope = ''
78         else
79           raise TypeError, "Expected Array or String, got #{new_scope.class}"
80         end
81       end
82       
83       ##
84       # Builds & signs the assertion.
85       # 
86       # @param [String] person
87       #   Email address of a user, if requesting a token to act on their behalf
88       # @return [String] Encoded JWT
89       def to_jwt(person=nil)
90         now = Time.new        
91         assertion = {
92           "iss" => @issuer,
93           "scope" => self.scope,
94           "aud" => "https://accounts.google.com/o/oauth2/token",
95           "exp" => (now + expiry).to_i,
96           "iat" => (now - skew).to_i
97         }
98         assertion['prn'] = person unless person.nil?
99         return JWT.encode(assertion, @key, "RS256")
100       end
101
102       ##
103       # Request a new access token.
104       # 
105       # @param [String] person
106       #   Email address of a user, if requesting a token to act on their behalf
107       # @param [Hash] options
108       #   Pass through to Signet::OAuth2::Client.fetch_access_token
109       # @return [Signet::OAuth2::Client] Access token 
110       #
111       # @see Signet::OAuth2::Client.fetch_access_token
112       def authorize(person = nil, options={})
113         assertion = self.to_jwt(person)
114         authorization = Signet::OAuth2::Client.new(
115           :token_credential_uri => 'https://accounts.google.com/o/oauth2/token'
116         )
117         authorization.grant_type = 'urn:ietf:params:oauth:grant-type:jwt-bearer'
118         authorization.extension_parameters = { :assertion => assertion }
119         authorization.fetch_access_token!(options)
120         return authorization
121       end
122     end
123   end
124 end