cache-driver.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. /*
  2. * @copyright
  3. * Copyright © Microsoft Open Technologies, Inc.
  4. *
  5. * All Rights Reserved
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http: *www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
  14. * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
  15. * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
  16. * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
  17. *
  18. * See the Apache License, Version 2.0 for the specific language
  19. * governing permissions and limitations under the License.
  20. */
  21. 'use strict';
  22. var _ = require('underscore');
  23. var crypto = require('crypto');
  24. require('date-utils'); // Adds a number of convenience methods to the builtin Date object.
  25. var Logger = require('./log').Logger;
  26. var constants = require('./constants');
  27. var cacheConstants = constants.Cache;
  28. var TokenResponseFields = constants.TokenResponseFields;
  29. // TODO: remove this.
  30. // There is a PM requirement that developers be able to look in to the cache and manipulate the cache based on
  31. // the parameters (authority, resource, clientId, userId), in any combination. They must be able find, add, and remove
  32. // tokens based on those parameters. Any default cache that the API supplies must allow for this query pattern.
  33. // This has the following implications:
  34. // The developer must not be required to calculate any special fields, such as hashes or unique keys.
  35. //
  36. // The default cache implementation can not include optimizations that break the previous requirement.
  37. // This means that we can only do complete scans of the data and equality can only be calculated based on
  38. // equality of all of the individual fields.
  39. //
  40. // The cache interface can not make any assumption about the query efficency of the cache nor can
  41. // it help in optimizing those queries.
  42. //
  43. // There is no simple sorting optimization, rather a series of indexes, and index intersection would
  44. // be necessary.
  45. //
  46. // If for some reason the developer tries to update the cache with a new entry that may be a refresh
  47. // token, they will not know that they need to update all of the refresh tokens or they may get strange
  48. // behavior.
  49. //
  50. // Related to the above, there is no definition of a coherent cache. And if there was there would be
  51. // no way for our API to enforce it. What about duplicates?
  52. //
  53. // there be a single cache entry per (authority, resource, clientId)
  54. // tuple, with no special tokens (i.e. MRRT tokens)
  55. // Required cache operations
  56. //
  57. // Constants
  58. var METADATA_CLIENTID = '_clientId';
  59. var METADATA_AUTHORITY = '_authority';
  60. function nop(placeHolder, callback) {
  61. callback();
  62. }
  63. /*
  64. * This is a place holder cache that does nothing.
  65. */
  66. var nopCache = {
  67. add : nop,
  68. addMany : nop,
  69. remove : nop,
  70. removeMany : nop,
  71. find : nop
  72. };
  73. function createTokenHash(token) {
  74. var hashAlg = crypto.createHash(cacheConstants.HASH_ALGORITHM);
  75. hashAlg.update(token, 'utf8');
  76. return hashAlg.digest('base64');
  77. }
  78. function createTokenIdMessage(entry) {
  79. var accessTokenHash = createTokenHash(entry[TokenResponseFields.ACCESS_TOKEN]);
  80. var message = 'AccessTokenId: ' + accessTokenHash;
  81. if (entry[TokenResponseFields.REFRESH_TOKEN]) {
  82. var refreshTokenHash = createTokenHash(entry[TokenResponseFields.REFRESH_TOKEN]);
  83. message += ', RefreshTokenId: ' + refreshTokenHash;
  84. }
  85. return message;
  86. }
  87. /**
  88. * This is the callback that is passed to all acquireToken variants below.
  89. * @callback RefreshEntryFunction
  90. * @memberOf CacheDriver
  91. * @param {object} tokenResponse A token response to refresh.
  92. * @param {string} [resource] The resource for which to obtain the token if it is different from the original token.
  93. * @param {AcquireTokenCallback} callback Called on completion with an error or a new entry to add to the cache.
  94. */
  95. /**
  96. * Constructs a new CacheDriver object.
  97. * @constructor
  98. * @private
  99. * @param {object} callContext Contains any context information that applies to the request.
  100. * @param {string} authority
  101. * @param {TokenCache} [cache] A token cache to use. If none is passed then the CacheDriver instance
  102. * will not cache.
  103. * @param {RefreshEntryFunction} refreshFunction
  104. */
  105. function CacheDriver(callContext, authority, resource, clientId, cache, refreshFunction) {
  106. this._callContext = callContext;
  107. this._log = new Logger('CacheDriver', callContext._logContext);
  108. this._authority = authority;
  109. this._resource = resource;
  110. this._clientId = clientId;
  111. this._cache = cache || nopCache;
  112. this._refreshFunction = refreshFunction;
  113. }
  114. /**
  115. * This is the callback that is passed to all acquireToken variants below.
  116. * @callback QueryCallback
  117. * @memberOf CacheDriver
  118. * @param {Error} [error] If the request fails this parameter will contain an Error object.
  119. * @param {Array} [response] On a succesful request returns an array of matched entries.
  120. */
  121. /**
  122. * The cache driver query function. Ensures that all queries are authority specific.
  123. * @param {object} query A query object. Can contain a clientId or userId or both.
  124. * @param {QueryCallback} callback
  125. */
  126. CacheDriver.prototype._find = function(query, callback) {
  127. this._cache.find(query, callback);
  128. };
  129. /**
  130. * Queries for all entries that might satisfy a request for a cached token.
  131. * @param {object} query A query object. Can contain a clientId or userId or both.
  132. * @param {QueryCallback} callback
  133. */
  134. CacheDriver.prototype._getPotentialEntries = function(query, callback) {
  135. var self = this;
  136. var potentialEntriesQuery = {};
  137. if (query.clientId) {
  138. potentialEntriesQuery[METADATA_CLIENTID] = query.clientId;
  139. }
  140. if (query.userId) {
  141. potentialEntriesQuery[TokenResponseFields.USER_ID] = query.userId;
  142. }
  143. this._log.verbose('Looking for potential cache entries:');
  144. this._log.verbose(JSON.stringify(potentialEntriesQuery), true);
  145. this._find(potentialEntriesQuery, function(err, entries) {
  146. self._log.verbose('Found ' + entries.length + ' potential entries.');
  147. callback(err, entries);
  148. return;
  149. });
  150. };
  151. /**
  152. * Finds all multi resource refresh tokens in the cache.
  153. * Refresh token is bound to userId, clientId.
  154. * @param {QueryCallback} callback
  155. */
  156. CacheDriver.prototype._findMRRTTokensForUser = function(user, callback) {
  157. this._find({ isMRRT : true, userId : user, _clientId : this._clientId}, callback);
  158. };
  159. /**
  160. * This is the callback that is passed to all acquireToken variants below.
  161. * @callback SingleEntryCallback
  162. * @memberOf CacheDriver
  163. * @param {Error} [error] If the request fails this parameter will contain an Error object.
  164. * @param {object} [response] On a succesful request returns a single cache entry.
  165. */
  166. /**
  167. * Finds a single entry that matches the query. If multiple entries are found that satisfy the query
  168. * then an error will be returned.
  169. * @param {object} query A query object.
  170. * @param {SingleEntryCallback} callback
  171. */
  172. CacheDriver.prototype._loadSingleEntryFromCache = function(query, callback) {
  173. var self = this;
  174. this._getPotentialEntries(query, function(err, potentialEntries) {
  175. if (err) {
  176. callback(err);
  177. return;
  178. }
  179. var returnVal;
  180. var isResourceTenantSpecific;
  181. if (potentialEntries && 0 < potentialEntries.length) {
  182. var resourceTenantSpecificEntries = _.where(potentialEntries, { resource : self._resource, _authority : self._authority });
  183. if (!resourceTenantSpecificEntries || 0 === resourceTenantSpecificEntries.length) {
  184. self._log.verbose('No resource specific cache entries found.');
  185. // There are no resource specific entries. Find an MRRT token.
  186. var mrrtTokens = _.where(potentialEntries, { isMRRT : true });
  187. if (mrrtTokens && mrrtTokens.length > 0) {
  188. self._log.verbose('Found an MRRT token.');
  189. returnVal = mrrtTokens[0];
  190. } else {
  191. self._log.verbose('No MRRT tokens found.');
  192. }
  193. } else if (resourceTenantSpecificEntries.length === 1) {
  194. self._log.verbose('Resource specific token found.');
  195. returnVal = resourceTenantSpecificEntries[0];
  196. isResourceTenantSpecific = true;
  197. }else {
  198. callback(self._log.createError('More than one token matches the criteria. The result is ambiguous.'));
  199. return;
  200. }
  201. }
  202. if (returnVal) {
  203. self._log.verbose('Returning token from cache lookup');
  204. self._log.verbose('Returning token from cache lookup, ' + createTokenIdMessage(returnVal), true);
  205. }
  206. callback(null, returnVal, isResourceTenantSpecific);
  207. });
  208. };
  209. /**
  210. * The response from a token refresh request never contains an id_token and therefore no
  211. * userInfo can be created from the response. This function creates a new cache entry
  212. * combining the id_token based info and cache metadata from the cache entry that was refreshed with the
  213. * new tokens in the refresh response.
  214. * @param {object} entry A cache entry corresponding to the resfreshResponse.
  215. * @param {object} refreshResponse The response from a token refresh request for the entry parameter.
  216. * @return {object} A new cache entry.
  217. */
  218. CacheDriver.prototype._createEntryFromRefresh = function(entry, refreshResponse) {
  219. var newEntry = _.clone(entry);
  220. newEntry = _.extend(newEntry, refreshResponse);
  221. if (entry.isMRRT && this._authority !== entry[METADATA_AUTHORITY]) {
  222. newEntry[METADATA_AUTHORITY] = this._authority;
  223. }
  224. this._log.verbose('Created new cache entry from refresh response.');
  225. return newEntry;
  226. };
  227. CacheDriver.prototype._replaceEntry = function(entryToReplace, newEntry, callback) {
  228. var self = this;
  229. this.remove(entryToReplace, function(err) {
  230. if (err) {
  231. callback(err);
  232. return;
  233. }
  234. self.add(newEntry, callback);
  235. });
  236. };
  237. /**
  238. * Given an expired cache entry refreshes it and updates the cache.
  239. * @param {object} entry A cache entry with an MRRT to refresh for another resource.
  240. * @param {SingleEntryCallback} callback
  241. */
  242. CacheDriver.prototype._refreshExpiredEntry = function(entry, callback) {
  243. var self = this;
  244. this._refreshFunction(entry, null, function(err, tokenResponse) {
  245. if (err) {
  246. callback(err);
  247. return;
  248. }
  249. var newEntry = self._createEntryFromRefresh(entry, tokenResponse);
  250. self._replaceEntry(entry, newEntry, function(err) {
  251. if (err) {
  252. self._log.error('error refreshing expired token', err, true);
  253. } else {
  254. self._log.info('Returning token refreshed after expiry.');
  255. }
  256. callback(err, newEntry);
  257. });
  258. });
  259. };
  260. /**
  261. * Given a cache entry with an MRRT will acquire a new token for a new resource via the MRRT, and cache it.
  262. * @param {object} entry A cache entry with an MRRT to refresh for another resource.
  263. * @param {SingleEntryCallback} callback
  264. */
  265. CacheDriver.prototype._acquireNewTokenFromMrrt = function(entry, callback) {
  266. var self = this;
  267. this._refreshFunction(entry, this._resource, function(err, tokenResponse) {
  268. if (err) {
  269. callback(err);
  270. return;
  271. }
  272. var newEntry = self._createEntryFromRefresh(entry, tokenResponse);
  273. self.add(newEntry, function(err) {
  274. if (err) {
  275. self._log.error('error refreshing mrrt', err, true);
  276. } else {
  277. self._log.info('Returning token derived from mrrt refresh.');
  278. }
  279. callback(err, newEntry);
  280. });
  281. });
  282. };
  283. /**
  284. * Given a token this function will refresh it if it is either expired, or an MRRT.
  285. * @param {object} entry A cache entry to refresh if necessary.
  286. * @param {Boolean} isResourceSpecific Indicates whether this token is appropriate for the resource for which
  287. * it was requested or whether it is possibly an MRRT token for which
  288. * a resource specific access token should be acquired.
  289. * @param {SingleEntryCallback} callback
  290. */
  291. CacheDriver.prototype._refreshEntryIfNecessary = function(entry, isResourceSpecific, callback) {
  292. var expiryDate = entry[TokenResponseFields.EXPIRES_ON];
  293. // Add some buffer in to the time comparison to account for clock skew or latency.
  294. var nowPlusBuffer = (new Date()).addMinutes(constants.Misc.CLOCK_BUFFER);
  295. if (isResourceSpecific && nowPlusBuffer.isAfter(expiryDate)) {
  296. this._log.info('Cached token is expired. Refreshing: ' + expiryDate);
  297. this._refreshExpiredEntry(entry, callback);
  298. return;
  299. } else if (!isResourceSpecific && entry.isMRRT) {
  300. this._log.info('Acquiring new access token from MRRT token.');
  301. this._acquireNewTokenFromMrrt(entry, callback);
  302. return;
  303. } else {
  304. callback(null, entry);
  305. }
  306. };
  307. /**
  308. * Finds a single entry in the cache that matches the query or fails if more than one match is found.
  309. * @param {object} query A query object
  310. * @param {SingleEntryCallback} callback
  311. */
  312. CacheDriver.prototype.find = function(query, callback) {
  313. var self = this;
  314. query = query || {};
  315. this._log.verbose('finding using query');
  316. this._log.verbose('finding with query:' + JSON.stringify(query), true);
  317. this._loadSingleEntryFromCache(query, function(err, entry, isResourceTenantSpecific) {
  318. if (err) {
  319. callback(err);
  320. return;
  321. }
  322. if (!entry) {
  323. callback();
  324. return;
  325. }
  326. self._refreshEntryIfNecessary(entry, isResourceTenantSpecific, function(err, newEntry) {
  327. callback(err, newEntry);
  328. return;
  329. });
  330. });
  331. };
  332. /**
  333. * Removes a single entry from the cache.
  334. * @param {object} entry The entry to remove.
  335. * @param {Function} callback Called on completion. The first parameter may contain an error.
  336. */
  337. CacheDriver.prototype.remove = function(entry, callback) {
  338. this._log.verbose('Removing entry.');
  339. return this._cache.remove([entry], function(err) {
  340. callback(err);
  341. return;
  342. });
  343. };
  344. /**
  345. * Removes a collection of entries from the cache in a single batch operation.
  346. * @param {Array} entries An array of cache entries to remove.
  347. * @param {Function} callback This function is called when the operation is complete. Any error is provided as the
  348. * first parameter.
  349. */
  350. CacheDriver.prototype._removeMany = function(entries, callback) {
  351. this._log.verbose('Remove many: ' + entries.length);
  352. this._cache.remove(entries, function(err) {
  353. callback(err);
  354. return;
  355. });
  356. };
  357. /**
  358. * Adds a collection of entries to the cache in a single batch operation.
  359. * @param {Array} entries An array of entries to add to the cache.
  360. * @param {Function} callback This function is called when the operation is complete. Any error is provided as the
  361. * first parameter.
  362. */
  363. CacheDriver.prototype._addMany = function(entries, callback) {
  364. this._log.verbose('Add many: ' + entries.length);
  365. this._cache.add(entries, function(err) {
  366. callback(err);
  367. return;
  368. });
  369. };
  370. /*
  371. * Tests whether the passed entry is a multi resource refresh token.
  372. * Somewhat mysteriously the presense of a resource field in a returned
  373. * token response indicates that the response is an MRRT.
  374. * @param {object} entry
  375. * @return {Boolean} true if the entry is an MRRT.
  376. */
  377. function isMRRT(entry) {
  378. return entry.resource ? true : false;
  379. }
  380. /**
  381. * Given an cache entry this function finds all of the MRRT tokens already in the cache
  382. * and updates them with the refresh_token of the passed in entry.
  383. * @param {object} entry The entry from which to get an updated refresh_token
  384. * @param {Function} callback Called back on completion. The first parameter may contain an error.
  385. */
  386. CacheDriver.prototype._updateRefreshTokens = function(entry, callback) {
  387. var self = this;
  388. if (isMRRT(entry)) {
  389. this._findMRRTTokensForUser(entry.userId, function(err, mrrtTokens) {
  390. if (err) {
  391. callback(err);
  392. return;
  393. }
  394. if (!mrrtTokens || 0 === mrrtTokens.length) {
  395. callback();
  396. return;
  397. }
  398. self._log.verbose('Updating ' + mrrtTokens.length + ' cached refresh tokens.');
  399. self._removeMany(mrrtTokens, function(err) {
  400. if (err) {
  401. callback(err);
  402. return;
  403. }
  404. for (var i = 0; i < mrrtTokens.length; i++) {
  405. mrrtTokens[i][TokenResponseFields.REFRESH_TOKEN] = entry[TokenResponseFields.REFRESH_TOKEN];
  406. }
  407. self._addMany(mrrtTokens, function(err) {
  408. callback(err);
  409. return;
  410. });
  411. });
  412. });
  413. } else {
  414. callback();
  415. return;
  416. }
  417. };
  418. /**
  419. * Checks to see if the entry has cache metadata already. If it does
  420. * then it probably came from a refresh operation and the metadata
  421. * was copied from the originating entry.
  422. * @param {object} entry The entry to check
  423. * @return {bool} Returns true if the entry has already been augmented
  424. * with cache metadata.
  425. */
  426. CacheDriver.prototype._entryHasMetadata = function(entry) {
  427. return (_.has(entry, METADATA_CLIENTID) && _.has(entry, METADATA_AUTHORITY));
  428. };
  429. CacheDriver.prototype._augmentEntryWithCacheMetadata = function(entry) {
  430. if (this._entryHasMetadata(entry)) {
  431. return;
  432. }
  433. if (isMRRT(entry)) {
  434. this._log.verbose('Added entry is MRRT');
  435. entry.isMRRT = true;
  436. } else {
  437. entry.resource = this._resource;
  438. }
  439. entry[METADATA_CLIENTID] = this._clientId;
  440. entry[METADATA_AUTHORITY] = this._authority;
  441. };
  442. /**
  443. * Adds a single entry to the cache.
  444. * @param {object} entry The entry to add.
  445. * @param {string} clientId The id of this client app.
  446. * @param {string} resource The id of the resource for which the cached token was obtained.
  447. * @param {Function} callback Called back on completion. The first parameter may contain an error.
  448. */
  449. CacheDriver.prototype.add = function(entry, callback) {
  450. var self = this;
  451. this._log.verbose('Adding entry');
  452. this._log.verbose('Adding entry, ' + createTokenIdMessage(entry));
  453. this._augmentEntryWithCacheMetadata(entry);
  454. this._updateRefreshTokens(entry, function(err) {
  455. if (err) {
  456. callback(err);
  457. return;
  458. }
  459. self._cache.add([entry], function(err) {
  460. callback(err);
  461. return;
  462. });
  463. });
  464. };
  465. module.exports = CacheDriver;