Skip to content

Commit 37d94e5

Browse files
author
Prithvi Kanherkar
committed
Getting all tests to pass
1 parent 5c4c5cb commit 37d94e5

10 files changed

+200
-156
lines changed

lib/msal-core/src/ServerRequestParameters.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ export class ServerRequestParameters {
137137
* @param request
138138
*/
139139
private validatePromptParameter (prompt: string) {
140-
if (!([PromptState.LOGIN, PromptState.SELECT_ACCOUNT, PromptState.CONSENT, PromptState.NONE].indexOf(prompt) >= 0)) {
140+
if ([PromptState.LOGIN, PromptState.SELECT_ACCOUNT, PromptState.CONSENT, PromptState.NONE].indexOf(prompt) < 0) {
141141
throw ClientConfigurationError.createInvalidPromptError(prompt);
142142
}
143143
}

lib/msal-core/src/UserAgentApplication.ts

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -238,11 +238,7 @@ export class UserAgentApplication {
238238
this.acquireTokenInProgress = false;
239239

240240
// cache keys msal - typescript throws an error if any value other than "localStorage" or "sessionStorage" is passed
241-
try {
242-
this.cacheStorage = new AuthCache(this.clientId, this.config.cache.cacheLocation, this.inCookie);
243-
} catch (e) {
244-
throw ClientConfigurationError.createInvalidCacheLocationConfigError(this.config.cache.cacheLocation);
245-
}
241+
this.cacheStorage = new AuthCache(this.clientId, this.config.cache.cacheLocation, this.inCookie);
246242

247243
// Initialize window handling code
248244
window.openedWindows = [];

lib/msal-core/src/cache/AuthCache.ts

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,12 @@ export class AuthCache extends BrowserStorage {// Singleton
5050
JSON.parse(key);
5151
return key;
5252
} catch (e) {
53-
return `${CacheKeys.PREFIX}.${this.clientId}.${key}`;
53+
if (key.startsWith(`${CacheKeys.PREFIX}.${this.clientId}`)) {
54+
return key;
55+
} else {
56+
return `${CacheKeys.PREFIX}.${this.clientId}.${key}`;
57+
}
58+
5459
}
5560
}
5661

@@ -109,23 +114,21 @@ export class AuthCache extends BrowserStorage {// Singleton
109114

110115
removeAcquireTokenEntries(state?: string): void {
111116
const storage = window[this.cacheLocation];
112-
if (storage) {
113-
let key: string;
114-
for (key in storage) {
115-
if (storage.hasOwnProperty(key)) {
116-
if ((key.indexOf(CacheKeys.AUTHORITY) !== -1 || key.indexOf(CacheKeys.ACQUIRE_TOKEN_ACCOUNT) !== 1) && (!state || key.indexOf(state) !== -1)) {
117-
const splitKey = key.split(Constants.resourceDelimiter);
118-
let state;
119-
if (splitKey.length > 1) {
120-
state = splitKey[1];
121-
}
122-
if (state && !this.tokenRenewalInProgress(state)) {
123-
this.removeItem(key);
124-
this.removeItem(CacheKeys.RENEW_STATUS + state);
125-
this.removeItem(CacheKeys.STATE_LOGIN);
126-
this.removeItem(CacheKeys.STATE_ACQ_TOKEN);
127-
this.setItemCookie(key, "", -1);
128-
}
117+
let key: string;
118+
for (key in storage) {
119+
if (storage.hasOwnProperty(key)) {
120+
if ((key.indexOf(CacheKeys.AUTHORITY) !== -1 || key.indexOf(CacheKeys.ACQUIRE_TOKEN_ACCOUNT) !== 1) && (!state || key.indexOf(state) !== -1)) {
121+
const resourceDelimSplitKey = key.split(Constants.resourceDelimiter);
122+
let keyState;
123+
if (resourceDelimSplitKey.length > 1) {
124+
keyState = resourceDelimSplitKey[resourceDelimSplitKey.length-1];
125+
}
126+
if (keyState && !this.tokenRenewalInProgress(keyState)) {
127+
this.removeItem(key);
128+
this.removeItem(CacheKeys.RENEW_STATUS + state);
129+
this.removeItem(CacheKeys.STATE_LOGIN);
130+
this.removeItem(CacheKeys.STATE_ACQ_TOKEN);
131+
this.setItemCookie(key, "", -1);
129132
}
130133
}
131134
}

lib/msal-core/src/cache/BrowserStorage.ts

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
* Licensed under the MIT License.
44
*/
55

6-
import { Constants, CacheKeys } from "../utils/Constants";
6+
import { CacheKeys } from "../utils/Constants";
77
import { CacheLocation } from "../Configuration";
88
import { ClientConfigurationError } from "../error/ClientConfigurationError";
99
import { AuthError } from "../error/AuthError";
@@ -13,22 +13,18 @@ import { AuthError } from "../error/AuthError";
1313
*/
1414
export class BrowserStorage {// Singleton
1515

16-
private localStorageSupported: boolean;
17-
private sessionStorageSupported: boolean;
1816
protected cacheLocation: CacheLocation;
1917

2018
constructor(cacheLocation: CacheLocation) {
2119
if (!window) {
2220
throw AuthError.createNoWindowObjectError("Browser storage class could not find window object");
2321
}
2422

25-
this.cacheLocation = cacheLocation;
26-
this.localStorageSupported = typeof window[this.cacheLocation] !== "undefined" && window[this.cacheLocation] != null;
27-
this.sessionStorageSupported = typeof window[cacheLocation] !== "undefined" && window[cacheLocation] != null;
28-
29-
if (!this.localStorageSupported && !this.sessionStorageSupported) {
30-
throw ClientConfigurationError.createNoStorageSupportedError();
23+
const storageSupported = typeof window[cacheLocation] !== "undefined" && window[cacheLocation] != null;
24+
if (!storageSupported) {
25+
throw ClientConfigurationError.createStorageNotSupportedError(cacheLocation);
3126
}
27+
this.cacheLocation = cacheLocation;
3228
}
3329

3430
// add value to storage

lib/msal-core/src/error/ClientConfigurationError.ts

Lines changed: 6 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,9 @@ export const ClientConfigurationErrorMessage = {
1212
code: "no_config_set",
1313
desc: "Configuration has not been set. Please call the UserAgentApplication constructor with a valid Configuration object."
1414
},
15-
invalidCacheLocation: {
16-
code: "invalid_cache_location",
17-
desc: "The cache location provided is not valid."
18-
},
19-
noStorageSupported: {
20-
code: "browser_storage_not_supported",
21-
desc: "localStorage and sessionStorage are not supported."
15+
storageNotSupported: {
16+
code: "storage_not_supported",
17+
desc: "The value for the cacheLocation is not supported."
2218
},
2319
noRedirectCallbacksSet: {
2420
code: "no_redirect_callbacks",
@@ -100,14 +96,9 @@ export class ClientConfigurationError extends ClientAuthError {
10096
`${ClientConfigurationErrorMessage.configurationNotSet.desc}`);
10197
}
10298

103-
static createInvalidCacheLocationConfigError(givenCacheLocation: string): ClientConfigurationError {
104-
return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidCacheLocation.code,
105-
`${ClientConfigurationErrorMessage.invalidCacheLocation.desc} Provided value: ${givenCacheLocation}. Possible values are: ${Constants.cacheLocationLocal}, ${Constants.cacheLocationSession}.`);
106-
}
107-
108-
static createNoStorageSupportedError() : ClientConfigurationError {
109-
return new ClientConfigurationError(ClientConfigurationErrorMessage.noStorageSupported.code,
110-
ClientConfigurationErrorMessage.noStorageSupported.desc);
99+
static createStorageNotSupportedError(givenCacheLocation: string) : ClientConfigurationError {
100+
return new ClientConfigurationError(ClientConfigurationErrorMessage.storageNotSupported.code,
101+
`${ClientConfigurationErrorMessage.storageNotSupported.desc} Given location: ${givenCacheLocation}`);
111102
}
112103

113104
static createRedirectCallbacksNotSetError(): ClientConfigurationError {

lib/msal-core/src/utils/Constants.ts

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -51,9 +51,6 @@ export class Constants {
5151
static get openidScope(): string { return "openid"; }
5252
static get profileScope(): string { return "profile"; }
5353

54-
static get cacheLocationLocal(): CacheLocation { return "localStorage"; }
55-
static get cacheLocationSession(): CacheLocation { return "sessionStorage"; }
56-
5754
static get interactionTypeRedirect(): InteractionType { return "redirectInteraction"; }
5855
static get interactionTypePopup(): InteractionType { return "popupInteraction"; }
5956
}
@@ -140,11 +137,11 @@ export type InteractionType = "redirectInteraction" | "popupInteraction";
140137
* internal partners too, hence the choice of generic "string" type instead of the "enum"
141138
* @hidden
142139
*/
143-
export enum PromptState {
144-
LOGIN = "login",
145-
SELECT_ACCOUNT = "select_account",
146-
CONSENT = "consent",
147-
NONE = "none",
140+
export const PromptState = {
141+
LOGIN: "login",
142+
SELECT_ACCOUNT: "select_account",
143+
CONSENT: "consent",
144+
NONE: "none",
148145
};
149146

150147
/**

lib/msal-core/test/Storage.localStorage.spec.ts

Lines changed: 65 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,21 @@ import { expect } from "chai";
22
import sinon from "sinon";
33
import { BrowserStorage } from "../src/cache/BrowserStorage";
44
import { AuthCache } from "../src/cache/AuthCache";
5-
import { Constants } from "../src";
5+
import { Constants, AuthError } from "../src";
66
import { CacheKeys } from "../src/utils/Constants";
77
import { AccessTokenKey } from "../src/cache/AccessTokenKey";
88
import { AccessTokenValue } from "../src/cache/AccessTokenValue";
99
import { Account } from "../src/Account";
10+
import { AuthErrorMessage } from "../src/error/AuthError";
11+
import { ClientConfigurationErrorMessage, ClientConfigurationError } from "../src/error/ClientConfigurationError";
1012

1113
describe("CacheStorage.ts Class - Local Storage", function () {
12-
let TEST_KEY = "test_key";
13-
let TEST_VALUE = "test value";
14-
let TEST_ACCOUNT_ID = "1234";
15-
let TEST_STATE = "state5678";
16-
let TEST_STATE2 = "state9012";
14+
const TEST_KEY = "test_key";
15+
const TEST_VALUE = "test value";
16+
const TEST_ACCOUNT_ID = "1234";
17+
const TEST_STATE = "state5678";
18+
const TEST_STATE2 = "state9012";
19+
const LOCAL_STORAGE = "localStorage";
1720
let cacheStorage : BrowserStorage;
1821
let ACCESS_TOKEN_KEY : AccessTokenKey;
1922
let ACCESS_TOKEN_VALUE : AccessTokenValue;
@@ -59,29 +62,58 @@ describe("CacheStorage.ts Class - Local Storage", function () {
5962
});
6063

6164
it("parses the cache location correctly", function () {
62-
cacheStorage = new BrowserStorage("localStorage");
65+
cacheStorage = new BrowserStorage(LOCAL_STORAGE);
6366
cacheStorage.setItem(TEST_KEY, TEST_VALUE);
6467
expect(window.localStorage.getItem(TEST_KEY)).to.be.eq(TEST_VALUE);
6568
});
6669

6770
it("throws error if cache location is not supported", function () {
68-
// Cannot test with current tooling - will need to take a look
69-
// Possibly wrapple as an option here? https://github.com/mroderick/wrapple
70-
});
71-
72-
it("uses previous storage instance if one already exists", function () {
73-
let oldCacheStorage = new BrowserStorage(Constants.cacheLocationLocal);
74-
cacheStorage = new BrowserStorage(Constants.cacheLocationSession);
75-
expect(cacheStorage).to.deep.eq(oldCacheStorage);
71+
sinon.stub(window, LOCAL_STORAGE).value(null);
72+
console.log(window.localStorage);
73+
let authErr;
74+
try {
75+
cacheStorage = new BrowserStorage(LOCAL_STORAGE);
76+
} catch (e) {
77+
authErr = e;
78+
}
79+
expect(authErr instanceof ClientConfigurationError).to.be.true;
80+
expect(authErr instanceof Error).to.be.true;
81+
expect(authErr.errorCode).to.equal(ClientConfigurationErrorMessage.storageNotSupported.code);
82+
expect(authErr.errorMessage).to.include(ClientConfigurationErrorMessage.storageNotSupported.desc);
83+
expect(authErr.message).to.include(ClientConfigurationErrorMessage.storageNotSupported.desc);
84+
expect(authErr.errorMessage).to.include(LOCAL_STORAGE);
85+
expect(authErr.message).to.include(LOCAL_STORAGE);
86+
expect(authErr.name).to.equal("ClientConfigurationError");
87+
expect(authErr.stack).to.include("Storage.localStorage.spec.ts");
88+
sinon.restore();
7689
});
7790

91+
it("throws error if window object does not exist", function () {
92+
let authErr;
93+
const oldWindow = window;
94+
window = null;
95+
try {
96+
cacheStorage = new BrowserStorage(LOCAL_STORAGE);
97+
} catch (e) {
98+
authErr = e;
99+
}
100+
expect(authErr instanceof AuthError).to.be.true;
101+
expect(authErr instanceof Error).to.be.true;
102+
expect(authErr.errorCode).to.equal(AuthErrorMessage.noWindowObjectError.code);
103+
expect(authErr.errorMessage).to.include(AuthErrorMessage.noWindowObjectError.desc);
104+
expect(authErr.message).to.include(AuthErrorMessage.noWindowObjectError.desc);
105+
expect(authErr.name).to.equal("AuthError");
106+
expect(authErr.stack).to.include("Storage.localStorage.spec.ts");
107+
window = oldWindow;
108+
})
78109
});
79110

80111
describe("localStorage access functions", function () {
81112

82113
beforeEach(function () {
83-
cacheStorage = new BrowserStorage("localStorage");
114+
cacheStorage = new BrowserStorage(LOCAL_STORAGE);
84115
setTestCacheItems();
116+
document.cookie = "";
85117
});
86118

87119
afterEach(function () {
@@ -118,13 +150,15 @@ describe("CacheStorage.ts Class - Local Storage", function () {
118150
cacheStorage.setItemCookie(CacheKeys.NONCE_IDTOKEN, idTokenNonceString);
119151
expect(document.cookie).to.include(CacheKeys.NONCE_IDTOKEN);
120152
expect(document.cookie).to.include(idTokenNonceString);
153+
cacheStorage.clearItemCookie(CacheKeys.NONCE_IDTOKEN);
121154
});
122155

123156
it("tests getItemCookie ", function () {
124157
let idTokenNonceString = "idTokenNonce";
125158
cacheStorage.setItemCookie(CacheKeys.NONCE_IDTOKEN, idTokenNonceString);
126159
let retrievedItem = cacheStorage.getItemCookie(CacheKeys.NONCE_IDTOKEN);
127160
expect(retrievedItem).to.include(idTokenNonceString);
161+
cacheStorage.clearItemCookie(CacheKeys.NONCE_IDTOKEN);
128162
});
129163

130164
it("tests getCookieExpirationTime", function () {
@@ -173,8 +207,9 @@ describe("CacheStorage.ts Class - Local Storage", function () {
173207
let msalCacheStorage: AuthCache;
174208

175209
beforeEach(function () {
176-
msalCacheStorage = new AuthCache(MSAL_CLIENT_ID,"localStorage", true);
210+
msalCacheStorage = new AuthCache(MSAL_CLIENT_ID,LOCAL_STORAGE, true);
177211
setTestCacheItems();
212+
document.cookie = "";
178213
});
179214

180215
afterEach(function () {
@@ -217,8 +252,9 @@ describe("CacheStorage.ts Class - Local Storage", function () {
217252
it("removeAcquireTokenEntries removes any acquireToken or authorityKey entries in the cache", function () {
218253
let acquireTokenAccountKey = AuthCache.generateAcquireTokenAccountKey(TEST_ACCOUNT_ID, TEST_STATE);
219254
let authorityKey = AuthCache.generateAuthorityKey(TEST_STATE);
220-
window.localStorage.setItem(acquireTokenAccountKey, JSON.stringify(ACCOUNT));
221-
window.localStorage.setItem(authorityKey, validAuthority);
255+
256+
window.localStorage.setItem(`${CacheKeys.PREFIX}.${MSAL_CLIENT_ID}.${acquireTokenAccountKey}`, JSON.stringify(ACCOUNT));
257+
window.localStorage.setItem(`${CacheKeys.PREFIX}.${MSAL_CLIENT_ID}.${authorityKey}`, validAuthority);
222258

223259
expect(msalCacheStorage.getItem(acquireTokenAccountKey)).to.be.eq(JSON.stringify(ACCOUNT));
224260
expect(msalCacheStorage.getItem(authorityKey)).to.be.eq(validAuthority);
@@ -235,10 +271,10 @@ describe("CacheStorage.ts Class - Local Storage", function () {
235271

236272
let acquireTokenAccountKey2 = AuthCache.generateAcquireTokenAccountKey(TEST_ACCOUNT_ID, TEST_STATE2);
237273
let authorityKey2 = AuthCache.generateAuthorityKey(TEST_STATE2);
238-
window.localStorage.setItem(acquireTokenAccountKey, JSON.stringify(ACCOUNT));
239-
window.localStorage.setItem(authorityKey, validAuthority);
240-
window.localStorage.setItem(acquireTokenAccountKey2, JSON.stringify(ACCOUNT));
241-
window.localStorage.setItem(authorityKey2, validAuthority);
274+
window.localStorage.setItem(`${CacheKeys.PREFIX}.${MSAL_CLIENT_ID}.${acquireTokenAccountKey}`, JSON.stringify(ACCOUNT));
275+
window.localStorage.setItem(`${CacheKeys.PREFIX}.${MSAL_CLIENT_ID}.${authorityKey}`, validAuthority);
276+
window.localStorage.setItem(`${CacheKeys.PREFIX}.${MSAL_CLIENT_ID}.${acquireTokenAccountKey2}`, JSON.stringify(ACCOUNT));
277+
window.localStorage.setItem(`${CacheKeys.PREFIX}.${MSAL_CLIENT_ID}.${authorityKey2}`, validAuthority);
242278

243279
expect(msalCacheStorage.getItem(acquireTokenAccountKey)).to.be.eq(JSON.stringify(ACCOUNT));
244280
expect(msalCacheStorage.getItem(authorityKey)).to.be.eq(validAuthority);
@@ -263,11 +299,17 @@ describe("CacheStorage.ts Class - Local Storage", function () {
263299
let stateLoginString = "stateLogin";
264300
let loginRequestString = "loginRequest";
265301
let stateAcquireTokenString = "stateAcquireToken";
302+
console.log(document.cookie);
266303
msalCacheStorage.setItemCookie(CacheKeys.NONCE_IDTOKEN, idTokenNonceString);
304+
console.log(document.cookie);
267305
msalCacheStorage.setItemCookie(CacheKeys.STATE_LOGIN, stateLoginString);
306+
console.log(document.cookie);
268307
msalCacheStorage.setItemCookie(CacheKeys.LOGIN_REQUEST, loginRequestString);
308+
console.log(document.cookie);
269309
msalCacheStorage.setItemCookie(CacheKeys.STATE_ACQ_TOKEN, stateAcquireTokenString);
310+
console.log(document.cookie);
270311
msalCacheStorage.clearMsalCookie();
312+
console.log(document.cookie);
271313
expect(document.cookie).to.be.empty;
272314
});
273315

0 commit comments

Comments
 (0)