-
Notifications
You must be signed in to change notification settings - Fork 160
/
AuthenticationTests.ts
295 lines (253 loc) · 11 KB
/
AuthenticationTests.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
const {describe, it, beforeEach, afterEach} = intern.getPlugin('interface.bdd');
const {expect} = intern.getPlugin('chai');
const {fetchMock} = intern.getPlugin('fetchMock');
const {sinon} = intern.getPlugin('sinon');
import { ConnectClient, InvalidSessionMiddleware, login, logout } from "../../main/frontend";
// `connectClient.call` adds the host and context to the endpoint request.
// we need to add this origin when configuring fetch-mock
const base = window.location.origin;
const $wnd = window as any;
/* global btoa localStorage setTimeout URLSearchParams Request Response */
describe('Authentication', () => {
const csrf = 'spring-csrf-token';
const headerName = 'X-CSRF-TOKEN';
const headers: Record<string, string> = {};
const vaadinCsrfToken = '6a60700e-852b-420f-a126-a1c61b73d1ba';
const happyCaseResponseText = '<head><meta name="_csrf" content="spring-csrf-token"></meta><meta name="_csrf_header" content="X-CSRF-TOKEN"></meta></head><script>window.Vaadin = {TypeScript: {"csrfToken":"'+vaadinCsrfToken+'"}};</script>';
function clearSpringCsrfMetaTags() {
Array.from(document.head.querySelectorAll('meta[name="_csrf"], meta[name="_csrf_header"]'))
.forEach(el => el.remove());
}
function setupSpringCsrfMetaTags(csrfToken = csrf) {
let csrfMetaTag = document.head.querySelector('meta[name="_csrf"]') as HTMLMetaElement | null;
let csrfHeaderNameMetaTag = document.head.querySelector('meta[name="_csrf_header"]') as HTMLMetaElement | null;
if (!csrfMetaTag) {
csrfMetaTag = document.createElement('meta');
csrfMetaTag.name = '_csrf';
document.head.appendChild(csrfMetaTag);
}
csrfMetaTag.content = csrfToken;
if (!csrfHeaderNameMetaTag) {
csrfHeaderNameMetaTag = document.createElement('meta');
csrfHeaderNameMetaTag.name = '_csrf_header';
document.head.appendChild(csrfHeaderNameMetaTag);
}
csrfHeaderNameMetaTag.content = headerName;
}
beforeEach( ()=> {
setupSpringCsrfMetaTags();
headers[headerName]=csrf;
});
afterEach(() => {
// @ts-ignore
delete window.Vaadin.TypeScript;
clearSpringCsrfMetaTags();
});
describe('login', () => {
afterEach(() => {
fetchMock.restore();
});
it('should return an error on invalid credentials', async () => {
fetchMock.post('/login', { redirectUrl: '/login?error' }, { headers });
const result = await login('invalid-username', 'invalid-password');
const expectedResult = {
error: true,
errorTitle: 'Incorrect username or password.',
errorMessage: 'Check that you have entered the correct username and password and try again.'
};
expect(fetchMock.calls()).to.have.lengthOf(1);
expect(result).to.deep.equal(expectedResult);
})
it('should return a CSRF token on valid credentials', async () => {
fetchMock.post('/login', {
body: happyCaseResponseText,
redirectUrl: '//localhost:8080/'
}, { headers });
const result = await login('valid-username', 'valid-password');
const expectedResult = {
error: false,
token: vaadinCsrfToken,
redirectUrl: '//localhost:8080/'
};
expect(fetchMock.calls()).to.have.lengthOf(1);
expect(result).to.deep.equal(expectedResult);
})
it('should return an error on other unexpected responses', async () => {
const body = 'Unexpected error';
const errorResponse = new Response(
body,
{
status: 500,
statusText: 'Internal Server Error'
}
);
fetchMock.post('/login', errorResponse, { headers });
const result = await login('valid-username', 'valid-password');
const expectedResult = {
error: true,
errorTitle: 'Error',
errorMessage: 'Something went wrong when trying to login.'
};
expect(fetchMock.calls()).to.have.lengthOf(1);
expect(result).to.deep.equal(expectedResult);
})
it('should return an error when response is missing CSRF token', async () => {
fetchMock.post('/login', 'I am mock response without CSRF token', { headers });
const result = await login('valid-username', 'valid-password');
const expectedResult = {
error: true,
errorTitle: 'Error',
errorMessage: 'Something went wrong when trying to login.'
};
expect(fetchMock.calls()).to.have.lengthOf(1);
expect(result).to.deep.equal(expectedResult);
})
it('should redirect based on request cache after login', async () => {
// An unthenticated request attempt would be captured by the default
// request cache, so after login, it should redirect the user to that
// request
fetchMock.post('/login', {
body: happyCaseResponseText,
// mock the unthenticated attempt, which would be
// saved by the default request cache
redirectUrl: '//localhost:8080/protected-view'
}, { headers });
const result = await login('valid-username', 'valid-password');
const expectedResult = {
error: false,
token: vaadinCsrfToken,
redirectUrl: '//localhost:8080/protected-view'
};
expect(fetchMock.calls()).to.have.lengthOf(1);
expect(result).to.deep.equal(expectedResult);
})
});
describe("logout", () => {
beforeEach(() => {
$wnd.Vaadin.TypeScript = {};
$wnd.Vaadin.TypeScript.csrfToken = vaadinCsrfToken;
});
afterEach(() => fetchMock.restore());
function verifySpringCsrfTokenIsCleared() {
expect(document.head.querySelector('meta[name="_csrf"]')).to.be.null;
expect(document.head.querySelector('meta[name="_csrf_header"]')).to.be.null;
}
it('should set the csrf token on logout', async () => {
fetchMock.post('/logout', {
body: happyCaseResponseText,
redirectUrl: '/logout?login'
}, { headers });
await logout();
expect(fetchMock.calls()).to.have.lengthOf(1);
expect($wnd.Vaadin.TypeScript.csrfToken).to.equal(vaadinCsrfToken);
});
it('should clear the csrf tokens on failed server logout', async () => {
const fakeError = new Error('unable to connect');
fetchMock.post('/logout', () => {
throw fakeError;
}, { headers });
fetchMock.get('?nocache', {
body: happyCaseResponseText
});
try {
await logout();
} catch (err) {
expect(err).to.equal(fakeError);
}
expect(fetchMock.calls()).to.have.lengthOf(3);
expect($wnd.Vaadin.TypeScript.csrfToken).to.be.undefined
verifySpringCsrfTokenIsCleared();
});
// when started the app offline, the spring csrf meta tags are not available
it('should retry when no spring csrf metas in the doc', async () => {
clearSpringCsrfMetaTags();
verifySpringCsrfTokenIsCleared();
fetchMock.post('/logout', 403, {repeat: 1});
fetchMock.get('?nocache', {
body: happyCaseResponseText
});
fetchMock.post('/logout', {
body: happyCaseResponseText,
redirectUrl: '/logout?login'
}, { headers, overwriteRoutes: false, repeat: 1});
await logout();
expect(fetchMock.calls()).to.have.lengthOf(3);
expect($wnd.Vaadin.TypeScript.csrfToken).to.equal(vaadinCsrfToken);
expect(document.head.querySelector('meta[name="_csrf"]')?.getAttribute('content')).to.equal(csrf);
expect(document.head.querySelector('meta[name="_csrf_header"]')?.getAttribute('content')).to.equal(headerName);
});
// when started the app offline, the spring csrf meta tags are not available
it('should retry when no spring csrf metas in the doc and clear the csrf token on failed server logout with the retry', async () => {
clearSpringCsrfMetaTags();
expect(document.head.querySelector('meta[name="_csrf"]')).to.be.null;
expect(document.head.querySelector('meta[name="_csrf_header"]')).to.be.null;
fetchMock.post('/logout', 403, {repeat: 1});
fetchMock.get('?nocache', {
body: happyCaseResponseText,
});
const fakeError = new Error('server error');
fetchMock.post('/logout', () => {
throw fakeError;
}, { headers, overwriteRoutes: false, repeat: 1});
try {
await logout();
} catch (err) {
expect(err).to.equal(fakeError);
}
expect(fetchMock.calls()).to.have.lengthOf(3);
expect($wnd.Vaadin.TypeScript.csrfToken).to.be.undefined;
setupSpringCsrfMetaTags();
});
// when the page has been opend too long the session has expired
it('should retry when expired spring csrf metas in the doc', async () => {
const expiredSpringCsrfToken = 'expired-'+csrf;
setupSpringCsrfMetaTags(expiredSpringCsrfToken);
const headersWithExpiredSpringCsrfToken: Record<string, string> = {};
headersWithExpiredSpringCsrfToken[headerName] = expiredSpringCsrfToken;
fetchMock.post('/logout', 403, {headers: headersWithExpiredSpringCsrfToken, repeat: 1});
fetchMock.get('?nocache', {
body: happyCaseResponseText,
});
fetchMock.post('/logout', {
body: happyCaseResponseText,
redirectUrl: '/logout?login'
}, { headers, overwriteRoutes: false, repeat: 1});
await logout();
expect(fetchMock.calls()).to.have.lengthOf(3);
expect($wnd.Vaadin.TypeScript.csrfToken).to.equal(vaadinCsrfToken);
expect(document.head.querySelector('meta[name="_csrf"]')?.getAttribute('content')).to.equal(csrf);
expect(document.head.querySelector('meta[name="_csrf_header"]')?.getAttribute('content')).to.equal(headerName);
});
});
describe("InvalidSessionMiddleWare", ()=>{
afterEach(() => fetchMock.restore());
it("should invoke the onInvalidSession callback on 401 response", async ()=>{
fetchMock.post(base + '/connect/FooEndpoint/fooMethod', 401)
const invalidSessionCallback = sinon.spy(()=>{
// mock to pass authentication
fetchMock.restore();
fetchMock.post(base + '/connect/FooEndpoint/fooMethod', {fooData: 'foo'})
return {
error: false,
token: "csrf-token"
}
});
const middleware = new InvalidSessionMiddleware(invalidSessionCallback);
const client = new ConnectClient({middlewares:[middleware]});
await client.call('FooEndpoint','fooMethod');
expect(invalidSessionCallback.calledOnce).to.be.true;
const headers = fetchMock.lastOptions().headers;
expect(headers).to.deep.include({
'x-csrf-token': 'csrf-token'
});
})
it("should not invoke the onInvalidSession callback on 200 response", async ()=>{
fetchMock.post(base + '/connect/FooEndpoint/fooMethod', {fooData: 'foo'})
const invalidSessionCallback = sinon.spy();
const middleware = new InvalidSessionMiddleware(invalidSessionCallback);
const client = new ConnectClient({middlewares:[middleware]});
await client.call('FooEndpoint', 'fooMethod');
expect(invalidSessionCallback.called).to.be.false;
})
});
});