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