aboutsummaryrefslogtreecommitdiffstats
path: root/core/src/tests/OC/requesttoken.spec.ts
blob: 8f92dbed153836c54a10986a7d4276d7e2c4efaf (plain)
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
/**
 * SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

import { setupServer } from 'msw/node'
import { http, HttpResponse } from 'msw'
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { fetchRequestToken, getRequestToken, setRequestToken } from '../../OC/requesttoken.ts'

const eventbus = vi.hoisted(() => ({ emit: vi.fn() }))
vi.mock('@nextcloud/event-bus', () => eventbus)

const server = setupServer()

describe('getRequestToken', () => {
	it('can read the token from DOM', () => {
		mockToken('tokenmock-123')
		expect(getRequestToken()).toBe('tokenmock-123')
	})

	it('can handle missing token', () => {
		mockToken(undefined)
		expect(getRequestToken()).toBeUndefined()
	})
})

describe('setRequestToken', () => {
	beforeEach(() => {
		vi.resetAllMocks()
	})

	it('does emit an event on change', () => {
		setRequestToken('new-token')
		expect(eventbus.emit).toBeCalledTimes(1)
		expect(eventbus.emit).toBeCalledWith('csrf-token-update', { token: 'new-token' })
	})

	it('does set the new token to the DOM', () => {
		setRequestToken('new-token')
		expect(document.head.dataset.requesttoken).toBe('new-token')
	})

	it('does remember the new token', () => {
		mockToken('old-token')
		setRequestToken('new-token')
		expect(getRequestToken()).toBe('new-token')
	})

	it('throws if the token is not a string', () => {
		// @ts-expect-error mocking
		expect(() => setRequestToken(123)).toThrowError('Invalid CSRF token given')
	})

	it('throws if the token is not valid', () => {
		expect(() => setRequestToken('')).toThrowError('Invalid CSRF token given')
	})

	it('does not emit an event if the token is not valid', () => {
		expect(() => setRequestToken('')).toThrowError('Invalid CSRF token given')
		expect(eventbus.emit).not.toBeCalled()
	})
})

describe('fetchRequestToken', () => {
	const successfullCsrf = http.get('/index.php/csrftoken', () => {
		return HttpResponse.json({ token: 'new-token' })
	})
	const forbiddenCsrf = http.get('/index.php/csrftoken', () => {
		return HttpResponse.json([], { status: 403 })
	})
	const serverErrorCsrf = http.get('/index.php/csrftoken', () => {
		return HttpResponse.json([], { status: 500 })
	})
	const networkErrorCsrf = http.get('/index.php/csrftoken', () => {
		return new HttpResponse(null, { type: 'error' })
	})

	beforeAll(() => {
		server.listen()
	})

	beforeEach(() => {
		vi.resetAllMocks()
	})

	it('correctly parses response', async () => {
		server.use(successfullCsrf)

		mockToken('oldToken')
		const token = await fetchRequestToken()
		expect(token).toBe('new-token')
	})

	it('sets the token', async () => {
		server.use(successfullCsrf)

		mockToken('oldToken')
		await fetchRequestToken()
		expect(getRequestToken()).toBe('new-token')
	})

	it('does emit an event', async () => {
		server.use(successfullCsrf)

		await fetchRequestToken()
		expect(eventbus.emit).toHaveBeenCalledOnce()
		expect(eventbus.emit).toBeCalledWith('csrf-token-update', { token: 'new-token' })
	})

	it('handles 403 error due to invalid cookies', async () => {
		server.use(forbiddenCsrf)

		mockToken('oldToken')
		await expect(() => fetchRequestToken()).rejects.toThrowError('Could not fetch CSRF token from API')
		expect(getRequestToken()).toBe('oldToken')
	})

	it('handles server error', async () => {
		server.use(serverErrorCsrf)

		mockToken('oldToken')
		await expect(() => fetchRequestToken()).rejects.toThrowError('Could not fetch CSRF token from API')
		expect(getRequestToken()).toBe('oldToken')
	})

	it('handles network error', async () => {
		server.use(networkErrorCsrf)

		mockToken('oldToken')
		await expect(() => fetchRequestToken()).rejects.toThrow()
		expect(getRequestToken()).toBe('oldToken')
	})
})

/**
 * Mock the request token directly so we can test reading it.
 *
 * @param token - The CSRF token to mock
 */
function mockToken(token?: string) {
	if (token === undefined) {
		delete document.head.dataset.requesttoken
	} else {
		document.head.dataset.requesttoken = token
	}
}