blob: e3e3f6dba6db68e1a2f26a1eef4d06e7cca88b18 [file] [log] [blame]
Joe Gregorio9da2ad82011-09-11 14:04:44 -04001# Copyright 2011 Google Inc. All Rights Reserved.
2
3"""Multi-credential file store with lock support.
4
5This module implements a JSON credential store where multiple
6credentials can be stored in one file. That file supports locking
7both in a single process and across processes.
8
9The credential themselves are keyed off of:
10* client_id
11* user_agent
12* scope
13
14The format of the stored data is like so:
15{
16 'file_version': 1,
17 'data': [
18 {
19 'key': {
20 'clientId': '<client id>',
21 'userAgent': '<user agent>',
22 'scope': '<scope>'
23 },
Joe Gregorio562b7312011-09-15 09:06:38 -040024 'credential': {
25 # JSON serialized Credentials.
26 }
Joe Gregorio9da2ad82011-09-11 14:04:44 -040027 }
28 ]
29}
30"""
31
32__author__ = 'jbeda@google.com (Joe Beda)'
33
34import base64
35import fcntl
36import logging
37import os
38import pickle
39import threading
40
41try: # pragma: no cover
42 import simplejson
43except ImportError: # pragma: no cover
44 try:
45 # Try to import from django, should work on App Engine
46 from django.utils import simplejson
47 except ImportError:
48 # Should work for Python2.6 and higher.
49 import json as simplejson
50
51from client import Storage as BaseStorage
Joe Gregorio562b7312011-09-15 09:06:38 -040052from client import Credentials
Joe Gregorio9da2ad82011-09-11 14:04:44 -040053
54logger = logging.getLogger(__name__)
55
56# A dict from 'filename'->_MultiStore instances
57_multistores = {}
58_multistores_lock = threading.Lock()
59
60
61class Error(Exception):
62 """Base error for this module."""
63 pass
64
65
66class NewerCredentialStoreError(Error):
67 """The credential store is a newer version that supported."""
68 pass
69
70
71def get_credential_storage(filename, client_id, user_agent, scope,
72 warn_on_readonly=True):
73 """Get a Storage instance for a credential.
74
75 Args:
76 filename: The JSON file storing a set of credentials
77 client_id: The client_id for the credential
78 user_agent: The user agent for the credential
79 scope: A string for the scope being requested
80 warn_on_readonly: if True, log a warning if the store is readonly
81
82 Returns:
83 An object derived from client.Storage for getting/setting the
84 credential.
85 """
86 filename = os.path.realpath(os.path.expanduser(filename))
87 _multistores_lock.acquire()
88 try:
89 multistore = _multistores.setdefault(
90 filename, _MultiStore(filename, warn_on_readonly))
91 finally:
92 _multistores_lock.release()
93 return multistore._get_storage(client_id, user_agent, scope)
94
95
96class _MultiStore(object):
97 """A file backed store for multiple credentials."""
98
99 def __init__(self, filename, warn_on_readonly=True):
100 """Initialize the class.
101
102 This will create the file if necessary.
103 """
104 self._filename = filename
105 self._thread_lock = threading.Lock()
106 self._file_handle = None
107 self._read_only = False
108 self._warn_on_readonly = warn_on_readonly
109
110 self._create_file_if_needed()
111
112 # Cache of deserialized store. This is only valid after the
113 # _MultiStore is locked or _refresh_data_cache is called. This is
114 # of the form of:
115 #
116 # (client_id, user_agent, scope) -> OAuth2Credential
117 #
118 # If this is None, then the store hasn't been read yet.
119 self._data = None
120
121 class _Storage(BaseStorage):
122 """A Storage object that knows how to read/write a single credential."""
123
124 def __init__(self, multistore, client_id, user_agent, scope):
125 self._multistore = multistore
126 self._client_id = client_id
127 self._user_agent = user_agent
128 self._scope = scope
129
130 def acquire_lock(self):
131 """Acquires any lock necessary to access this Storage.
132
133 This lock is not reentrant.
134 """
135 self._multistore._lock()
136
137 def release_lock(self):
138 """Release the Storage lock.
139
140 Trying to release a lock that isn't held will result in a
141 RuntimeError.
142 """
143 self._multistore._unlock()
144
145 def locked_get(self):
146 """Retrieve credential.
147
148 The Storage lock must be held when this is called.
149
150 Returns:
151 oauth2client.client.Credentials
152 """
153 credential = self._multistore._get_credential(
154 self._client_id, self._user_agent, self._scope)
155 if credential:
156 credential.set_store(self)
157 return credential
158
159 def locked_put(self, credentials):
160 """Write a credential.
161
162 The Storage lock must be held when this is called.
163
164 Args:
165 credentials: Credentials, the credentials to store.
166 """
167 self._multistore._update_credential(credentials, self._scope)
168
169 def _create_file_if_needed(self):
170 """Create an empty file if necessary.
171
172 This method will not initialize the file. Instead it implements a
173 simple version of "touch" to ensure the file has been created.
174 """
175 if not os.path.exists(self._filename):
176 old_umask = os.umask(0177)
177 try:
178 open(self._filename, 'a+').close()
179 finally:
180 os.umask(old_umask)
181
182 def _lock(self):
183 """Lock the entire multistore."""
184 self._thread_lock.acquire()
185 # Check to see if the file is writeable.
186 if os.access(self._filename, os.W_OK):
187 self._file_handle = open(self._filename, 'r+')
188 fcntl.lockf(self._file_handle.fileno(), fcntl.LOCK_EX)
189 else:
190 # Cannot open in read/write mode. Open only in read mode.
191 self._file_handle = open(self._filename, 'r')
192 self._read_only = True
193 if self._warn_on_readonly:
194 logger.warn('The credentials file (%s) is not writable. Opening in '
195 'read-only mode. Any refreshed credentials will only be '
196 'valid for this run.' % self._filename)
197 if os.path.getsize(self._filename) == 0:
198 logger.debug('Initializing empty multistore file')
199 # The multistore is empty so write out an empty file.
200 self._data = {}
201 self._write()
202 elif not self._read_only or self._data is None:
203 # Only refresh the data if we are read/write or we haven't
204 # cached the data yet. If we are readonly, we assume is isn't
205 # changing out from under us and that we only have to read it
206 # once. This prevents us from whacking any new access keys that
207 # we have cached in memory but were unable to write out.
208 self._refresh_data_cache()
209
210 def _unlock(self):
211 """Release the lock on the multistore."""
212 if not self._read_only:
213 fcntl.lockf(self._file_handle.fileno(), fcntl.LOCK_UN)
214 self._file_handle.close()
215 self._thread_lock.release()
216
217 def _locked_json_read(self):
218 """Get the raw content of the multistore file.
219
220 The multistore must be locked when this is called.
221
222 Returns:
223 The contents of the multistore decoded as JSON.
224 """
225 assert self._thread_lock.locked()
226 self._file_handle.seek(0)
227 return simplejson.load(self._file_handle)
228
229 def _locked_json_write(self, data):
230 """Write a JSON serializable data structure to the multistore.
231
232 The multistore must be locked when this is called.
233
234 Args:
235 data: The data to be serialized and written.
236 """
237 assert self._thread_lock.locked()
238 if self._read_only:
239 return
240 self._file_handle.seek(0)
241 simplejson.dump(data, self._file_handle, sort_keys=True, indent=2)
242 self._file_handle.truncate()
243
244 def _refresh_data_cache(self):
245 """Refresh the contents of the multistore.
246
247 The multistore must be locked when this is called.
248
249 Raises:
250 NewerCredentialStoreError: Raised when a newer client has written the
251 store.
252 """
253 self._data = {}
254 try:
255 raw_data = self._locked_json_read()
256 except Exception:
257 logger.warn('Credential data store could not be loaded. '
258 'Will ignore and overwrite.')
259 return
260
261 version = 0
262 try:
263 version = raw_data['file_version']
264 except Exception:
265 logger.warn('Missing version for credential data store. It may be '
266 'corrupt or an old version. Overwriting.')
267 if version > 1:
268 raise NewerCredentialStoreError(
269 'Credential file has file_version of %d. '
270 'Only file_version of 1 is supported.' % version)
271
272 credentials = []
273 try:
274 credentials = raw_data['data']
275 except (TypeError, KeyError):
276 pass
277
278 for cred_entry in credentials:
279 try:
280 (key, credential) = self._decode_credential_from_json(cred_entry)
281 self._data[key] = credential
282 except:
283 # If something goes wrong loading a credential, just ignore it
284 logger.info('Error decoding credential, skipping', exc_info=True)
285
286 def _decode_credential_from_json(self, cred_entry):
287 """Load a credential from our JSON serialization.
288
289 Args:
290 cred_entry: A dict entry from the data member of our format
291
292 Returns:
293 (key, cred) where the key is the key tuple and the cred is the
294 OAuth2Credential object.
295 """
296 raw_key = cred_entry['key']
297 client_id = raw_key['clientId']
298 user_agent = raw_key['userAgent']
299 scope = raw_key['scope']
300 key = (client_id, user_agent, scope)
Joe Gregorio562b7312011-09-15 09:06:38 -0400301 credential = None
302 credential = Credentials.new_from_json(simplejson.dumps(cred_entry['credential']))
Joe Gregorio9da2ad82011-09-11 14:04:44 -0400303 return (key, credential)
304
305 def _write(self):
306 """Write the cached data back out.
307
308 The multistore must be locked.
309 """
310 raw_data = {'file_version': 1}
311 raw_creds = []
312 raw_data['data'] = raw_creds
313 for (cred_key, cred) in self._data.items():
314 raw_key = {
315 'clientId': cred_key[0],
316 'userAgent': cred_key[1],
317 'scope': cred_key[2]
318 }
Joe Gregorio562b7312011-09-15 09:06:38 -0400319 raw_cred = simplejson.loads(cred.to_json())
Joe Gregorio9da2ad82011-09-11 14:04:44 -0400320 raw_creds.append({'key': raw_key, 'credential': raw_cred})
321 self._locked_json_write(raw_data)
322
323 def _get_credential(self, client_id, user_agent, scope):
324 """Get a credential from the multistore.
325
326 The multistore must be locked.
327
328 Args:
329 client_id: The client_id for the credential
330 user_agent: The user agent for the credential
331 scope: A string for the scope being requested
332
333 Returns:
334 The credential specified or None if not present
335 """
336 key = (client_id, user_agent, scope)
Joe Gregorio562b7312011-09-15 09:06:38 -0400337
Joe Gregorio9da2ad82011-09-11 14:04:44 -0400338 return self._data.get(key, None)
339
340 def _update_credential(self, cred, scope):
341 """Update a credential and write the multistore.
342
343 This must be called when the multistore is locked.
344
345 Args:
346 cred: The OAuth2Credential to update/set
347 scope: The scope that this credential covers
348 """
349 key = (cred.client_id, cred.user_agent, scope)
350 self._data[key] = cred
351 self._write()
352
353 def _get_storage(self, client_id, user_agent, scope):
354 """Get a Storage object to get/set a credential.
355
356 This Storage is a 'view' into the multistore.
357
358 Args:
359 client_id: The client_id for the credential
360 user_agent: The user agent for the credential
361 scope: A string for the scope being requested
362
363 Returns:
364 A Storage object that can be used to get/set this cred
365 """
366 return self._Storage(self, client_id, user_agent, scope)