Skip to content

Node.js based forum software built for the modern web

35.4 KB
Raw Blame
'use strict';


const assert = require('assert');
const url = require('url');
const nconf = require('nconf');

const db = require('./mocks/databasemock');
const request = require('../src/request');
const user = require('../src/user');
const utils = require('../src/utils');
const meta = require('../src/meta');
const plugins = require('../src/plugins');
const privileges = require('../src/privileges');
const api = require('../src/api');
const controllerHelpers = require('../src/controllers/helpers');
const helpers = require('./helpers');

describe('authentication', () => {
	const jar = request.jar();
	let regularUid;
	const dummyEmailerHook = async (data) => {};

	before(async () => {
		// Attach an emailer hook so related requests do not error
		plugins.hooks.register('authentication-test', {
			hook: 'static:email.send',
			method: dummyEmailerHook,
		});

		regularUid = await user.create({
			username: 'regular', password: 'regularpwd', email: '[email protected]',
		}, {
			emailVerification: 'verify',
		});
		assert.strictEqual(regularUid, 1);
	});

	after(() => {
		plugins.hooks.unregister('authentication-test', 'static:email.send');
	});

	describe('x-return-to', () => {
		it('should normalize URLs safely on a root installation', () => {
			const configuredUrl = nconf.get('url');
			const relativePath = nconf.get('relative_path');
			try {
				nconf.set('url', nconf.get('base_url'));
				nconf.set('relative_path', '');
				assert.strictEqual(controllerHelpers.normalizeReturnToPath('/topic/1?sort=newest#post-2'), '/topic/1?sort=newest#post-2');
				assert.strictEqual(controllerHelpers.normalizeReturnToPath(`${nconf.get('base_url')}/topic/1`), '/topic/1');
				assert.strictEqual(controllerHelpers.normalizeReturnToPath(`${nconf.get('base_url')}//attacker.example`), '');
				assert.strictEqual(controllerHelpers.normalizeReturnToPath('//attacker.example'), '');
				assert.strictEqual(controllerHelpers.normalizeReturnToPath('/api/v3/users'), '/api/v3/users');
				assert.strictEqual(controllerHelpers.normalizeReturnToPath('/api/v3/users', { allowApi: false }), '');
			} finally {
				nconf.set('url', configuredUrl);
				nconf.set('relative_path', relativePath);
			}
		});

		async function getLoginDestination(page, returnTo) {
			const requestJar = request.jar();
			const { response: pageResponse } = await request.get(`${nconf.get('url')}/api/${page}`, {
				jar: requestJar,
				headers: {
					'x-return-to': returnTo,
				},
			});
			assert.strictEqual(pageResponse.statusCode, 200);

			const csrf_token = await helpers.getCsrfToken(requestJar);
			const { response, body } = await request.post(`${nconf.get('url')}/login`, {
				jar: requestJar,
				body: {
					username: 'regular',
					password: 'regularpwd',
				},
				headers: {
					'x-csrf-token': csrf_token,
				},
			});
			assert.strictEqual(response.statusCode, 200);
			return body.next;
		}

		const relativePath = nconf.get('relative_path');
		const home = `${relativePath}/`;
		const invalidTargets = [
			{ name: 'an external absolute URL', value: 'https://attacker.example/topic/1' },
			{ name: 'a scheme-relative URL', value: '//attacker.example/topic/1' },
			{ name: 'an encoded scheme-relative URL', value: '%2F%2Fattacker.example/topic/1' },
			{ name: 'an encoded external absolute URL', value: 'https%3A%2F%2Fattacker.example%2Ftopic%2F1' },
			{ name: 'a backslash authority URL', value: '/\\attacker.example/topic/1' },
			{ name: 'an encoded backslash authority URL', value: '/%5Cattacker.example/topic/1' },
			{ name: 'an encoded control character', value: '/topic/1%0D%0AX-Test%3Avalue' },
			{ name: 'a malformed encoded URL', value: '/topic/%' },
			{ name: 'a same-origin URL that becomes scheme-relative after subfolder stripping', value: `${nconf.get('url')}//attacker.example/topic/1` },
			{ name: 'an encoded path that becomes scheme-relative after subfolder stripping', value: `${relativePath}/%2F%2Fattacker.example/topic/1` },
		];
		const mountBoundaryTargets = [
			{ name: 'a same-origin URL at the origin root', value: `${nconf.get('base_url')}/outside` },
			{ name: 'a same-origin URL resolving to the origin root', value: `${nconf.get('url')}/../outside` },
		];

		['login', 'register'].forEach((page) => {
			invalidTargets.forEach((target) => {
				it(`should reject ${target.name} from the ${page} page`, async () => {
					assert.strictEqual(await getLoginDestination(page, target.value), home);
				});
			});
			mountBoundaryTargets.forEach((target) => {
				const expected = relativePath ? home : '/outside';
				const behavior = relativePath ? 'reject' : 'preserve';
				it(`should ${behavior} ${target.name} from the ${page} page`, async () => {
					assert.strictEqual(await getLoginDestination(page, target.value), expected);
				});
			});

			it(`should preserve an internal URL with query and hash from the ${page} page`, async () => {
				const target = '/topic/1?next=%2Fcategory%2F1#post-2';
				assert.strictEqual(
					await getLoginDestination(page, target),
					`${nconf.get('relative_path')}${target}`
				);
			});

			it(`should strip the configured subfolder from a same-origin URL on the ${page} page`, async () => {
				const path = '/topic/1?sort=newest#post-2';
				assert.strictEqual(await getLoginDestination(page, `${nconf.get('url')}${path}`), `${nconf.get('relative_path')}${path}`);
			});

			if (relativePath) {
				it(`should not confuse a subfolder-prefix lookalike on the ${page} page`, async () => {
					assert.strictEqual(
						await getLoginDestination(page, `${relativePath}ish/topic/1`),
						`${relativePath}${relativePath}ish/topic/1`
					);
				});
			} else {
				it(`should reject a path without a leading slash from the ${page} page`, async () => {
					assert.strictEqual(await getLoginDestination(page, 'ish/topic/1'), home);
				});
			}
		});

		async function getApiReauthDestination(returnTo, expectedSessionReturnTo) {
			const { jar: reauthJar } = await helpers.loginUser('regular', 'regularpwd');
			let hookReturnTo;
			const hookName = `x-return-to-reauth-${utils.generateUUID()}`;
			plugins.hooks.register(hookName, {
				hook: 'response:auth.relogin',
				method: async ({ req }) => {
					hookReturnTo = req.session.returnTo;
				},
			});

			try {
				const { response } = await helpers.request('post', '/api/v3/users/reauth/verify', {
					jar: reauthJar,
					body: {},
					headers: {
						'x-return-to': returnTo,
					},
				});
				assert.strictEqual(response.statusCode, 401);
				assert.strictEqual(hookReturnTo, expectedSessionReturnTo);
			} finally {
				plugins.hooks.unregister(hookName, 'response:auth.relogin');
			}

			const csrf_token = await helpers.getCsrfToken(reauthJar);
			const { body } = await request.post(`${nconf.get('url')}/login`, {
				jar: reauthJar,
				body: {
					username: 'regular',
					password: 'regularpwd',
				},
				headers: {
					'x-csrf-token': csrf_token,
				},
			});
			return body.next;
		}

		it('should normalize the return path before firing the API reauthentication hook', async () => {
			const target = '/topic/1?sort=newest#post-2';
			assert.strictEqual(
				await getApiReauthDestination(`${nconf.get('url')}${target}`, target),
				`${nconf.get('relative_path')}${target}`
			);
		});

		it('should reject an external API reauthentication return URL', async () => {
			assert.strictEqual(
				await getApiReauthDestination('https://attacker.example/topic/1', '/'),
				home
			);
		});

		it('should not redirect a browser login back to an API route', async () => {
			assert.strictEqual(
				await getApiReauthDestination('/api/v3/admin/tokens', '/'),
				home
			);
		});

		it('should reject case and encoded variants of the API route', async () => {
			assert.strictEqual(
				await getApiReauthDestination('/API/v3/admin/tokens', '/'),
				home
			);
			assert.strictEqual(
				await getApiReauthDestination('/a%70i/v3/admin/tokens', '/'),
				home
			);
		});

		it('should let the registration-complete hook override a normalized internal target', async () => {
			const requestJar = request.jar();
			const target = '/topic/1?sort=newest#post-2';
			const pluginTarget = 'https://plugin.example/return';
			let hookNext;
			const hookName = `x-return-to-register-${utils.generateUUID()}`;
			plugins.hooks.register(hookName, {
				hook: 'filter:register.complete',
				method: async (data) => {
					hookNext = data.next;
					data.next = pluginTarget;
					return data;
				},
			});

			try {
				await request.get(`${nconf.get('url')}/api/register`, {
					jar: requestJar,
					headers: {
						'x-return-to': `${nconf.get('url')}${target}`,
					},
				});
				const csrf_token = await helpers.getCsrfToken(requestJar);
				const username = `returnto${utils.generateUUID().slice(0, 8)}`;
				const { response, body } = await request.post(`${nconf.get('url')}/register`, {
					jar: requestJar,
					body: {
						username,
						email: `${username}@example.org`,
						password: 'register-password',
						'password-confirm': 'register-password',
						gdpr_consent: true,
					},
					headers: {
						'x-csrf-token': csrf_token,
					},
				});
				assert.strictEqual(response.statusCode, 200);
				assert.strictEqual(hookNext, target);
				assert.strictEqual(body.next, pluginTarget);
			} finally {
				plugins.hooks.unregister(hookName, 'filter:register.complete');
			}
		});
	});

	it('should allow login with email for uid 1', async () => {
		const oldValue = meta.config.allowLoginWith;
		meta.config.allowLoginWith = 'username-email';
		const { response } = await helpers.loginUser('[email protected]', 'regularpwd');
		assert.strictEqual(response.statusCode, 200);
		meta.config.allowLoginWith = oldValue;
	});

	it('second user should fail to login with email since email is not confirmed', async () => {
		const oldValue = meta.config.allowLoginWith;
		meta.config.allowLoginWith = 'username-email';
		const uid = await user.create({ username: '2nduser', password: '2ndpassword', email: '[email protected]' });
		const { response, body } = await helpers.loginUser('[email protected]', '2ndpassword');
		// Unconfirmed emails are not in the email:uid index, so they fall through the
		// same non-existent-user path as any other bad credential (403, not 400).
		assert.strictEqual(response.statusCode, 403);
		assert.strictEqual(body, '[[error:invalid-login-credentials]]');
		meta.config.allowLoginWith = oldValue;
	});

	it('should not leak whether an email is registered (email enumeration)', async () => {
		const oldValue = meta.config.allowLoginWith;
		meta.config.allowLoginWith = 'username-email';
		try {
			// Unregistered email
			const { response: emailRes, body: emailBody } = await helpers.loginUser('[email protected]', 'SomePassword123');
			// Non-existent username
			const { response: userRes, body: userBody } = await helpers.loginUser('unregistered-enum-user', 'SomePassword123');
			// Registered email with a wrong password
			const { response: regRes, body: regBody } = await helpers.loginUser('[email protected]', 'WrongPassword123');

			// All three must be indistinguishable: same status, same message
			assert.strictEqual(emailRes.statusCode, 403);
			assert.strictEqual(emailBody, '[[error:invalid-login-credentials]]');
			assert.strictEqual(userRes.statusCode, 403);
			assert.strictEqual(userBody, '[[error:invalid-login-credentials]]');
			assert.strictEqual(regRes.statusCode, 403);
			assert.strictEqual(regBody, '[[error:invalid-login-credentials]]');
		} finally {
			meta.config.allowLoginWith = oldValue;
		}
	});

	it('should fail to create user if username is too short', async () => {
		const { response, body } = await helpers.registerUser({
			username: 'a',
			password: '123456',
		});
		assert.equal(response.statusCode, 400);
		assert.equal(body, '[[error:username-too-short]]');
	});

	it('should fail to create user if userslug is too short', async () => {
		const { response, body } = await helpers.registerUser({
			username: '----a-----',
			password: '123456',
		});
		assert.equal(response.statusCode, 400);
		assert.equal(body, '[[error:username-too-short]]');
	});

	it('should fail to create user if userslug is too short', async () => {
		const { response, body } = await helpers.registerUser({
			username: '     a',
			password: '123456',
		});
		assert.equal(response.statusCode, 400);
		assert.equal(body, '[[error:username-too-short]]');
	});

	it('should fail to create user if userslug is too short', async () => {
		const { response, body } = await helpers.registerUser({
			username: 'a      ',
			password: '123456',
		});
		assert.equal(response.statusCode, 400);
		assert.equal(body, '[[error:username-too-short]]');
	});

	it('should register and login a user', async () => {
		const jar = request.jar();
		const csrf_token = await helpers.getCsrfToken(jar);

		const { body } = await request.post(`${nconf.get('url')}/register`, {
			jar,
			body: {
				email: '[email protected]',
				username: 'admin',
				password: 'adminpwd',
				'password-confirm': 'adminpwd',
				userLang: 'it',
				gdpr_consent: true,
			},
			headers: {
				'x-csrf-token': csrf_token,
			},
		});

		const validationPending = await user.email.isValidationPending(body.uid, '[email protected]');
		assert.strictEqual(validationPending, true);

		assert(body);
		assert(body.hasOwnProperty('uid') && body.uid > 0);
		const newUid = body.uid;
		const { body: self } = await request.get(`${nconf.get('url')}/api/self`, {
			jar,
		});
		assert(self);
		assert.equal(self.username, 'admin');
		assert.equal(self.uid, newUid);
		const settings = await user.getSettings(body.uid);
		assert.equal(settings.userLang, 'it');
	});

	it('should logout a user', async () => {
		await helpers.logoutUser(jar);

		const { response, body } = await request.get(`${nconf.get('url')}/api/me`, {
			jar: jar,
		});
		assert.equal(response.statusCode, 401);
		assert.strictEqual(body.status.code, 'not-authorised');
	});

	it('should regenerate the session identifier on successful login', async () => {
		const matchRegexp = /express\.sid=s%3A(.+?);/;
		const { hostname, pathname } = new URL(nconf.get('url'));
		const sid = String(jar.store.idx[hostname][pathname]['express.sid']).match(matchRegexp)[1];
		await helpers.logoutUser(jar);
		const newJar = (await helpers.loginUser('regular', 'regularpwd')).jar;
		const newSid = String(newJar.store.idx[hostname][pathname]['express.sid']).match(matchRegexp)[1];

		assert.notStrictEqual(newSid, sid);
	});


	it('should revoke all sessions', async () => {
		const socketAdmin = require('../src/socket.io/admin');
		let sessionCount = await db.sortedSetCard(`uid:${regularUid}:sessions`);
		assert(sessionCount);
		await socketAdmin.deleteAllSessions({ uid: 1 }, {});
		sessionCount = await db.sortedSetCard(`uid:${regularUid}:sessions`);
		assert(!sessionCount);
	});

	describe('login', () => {
		let username;
		let password;
		let uid;

		function getCookieExpiry(response) {
			const { headers } = response;
			assert(headers['set-cookie']);
			assert.strictEqual(headers['set-cookie'].includes('Expires'), true);

			const values = headers['set-cookie'].split(';');
			return values.reduce((memo, cur) => {
				if (!memo) {
					const [name, value] = cur.split('=');
					if (name === ' Expires') {
						memo = new Date(value);
					}
				}

				return memo;
			}, undefined);
		}

		beforeEach(async () => {
			([username, password] = [utils.generateUUID().slice(0, 10), utils.generateUUID()]);
			uid = await user.create({ username, password });
		});

		it('should login a user', async () => {
			const { jar, body: loginBody } = await helpers.loginUser(username, password);
			assert(loginBody);
			const { body } = await request.get(`${nconf.get('url')}/api/self`, {
				jar,
			});
			assert(body);
			assert.equal(body.username, username);
			const sessions = await db.getSortedSetRange(`uid:${uid}:sessions`, 0, -1);
			assert(sessions);
			assert(Object.keys(sessions).length > 0);
		});

		it('should track the new session when a logged-in user signs in as another user', async () => {
			const firstUsername = utils.generateUUID().slice(0, 10);
			const firstPassword = utils.generateUUID();
			await user.create({ username: firstUsername, password: firstPassword });
			const { jar, response: firstLoginResponse } = await helpers.loginUser(firstUsername, firstPassword);
			assert.strictEqual(firstLoginResponse.statusCode, 200);
			assert.strictEqual(await db.sortedSetCard(`uid:${uid}:sessions`), 0);

			try {
				const { response } = await helpers.request('post', '/login', {
					jar,
					body: { username, password },
				});
				assert.strictEqual(response.statusCode, 200);

				const { body: self } = await request.get(`${nconf.get('url')}/api/self`, { jar });
				assert.strictEqual(self.uid, uid);
				assert.strictEqual((await user.auth.getSessions(uid)).length, 1);
			} finally {
				await helpers.logoutUser(jar);
			}
		});

		it('should set a cookie that only lasts for the life of the browser session', async () => {
			const { response } = await helpers.loginUser(username, password);

			assert(response.headers);
			assert(response.headers['set-cookie']);
			assert.strictEqual(response.headers['set-cookie'].includes('Expires'), false);
		});

		it('should set a different expiry if sessionDuration is set', async () => {
			const _sessionDuration = meta.config.sessionDuration;
			const days = 1;
			meta.config.sessionDuration = days * 24 * 60 * 60;

			const { response } = await helpers.loginUser(username, password);

			const expiry = getCookieExpiry(response);
			const expected = new Date();
			expected.setUTCDate(expected.getUTCDate() + days);

			assert.strictEqual(expiry.getUTCDate(), expected.getUTCDate());

			meta.config.sessionDuration = _sessionDuration;
		});

		it('should set a cookie that lasts for x days where x is loginDays setting, if asked to remember', async () => {
			const { response } = await helpers.loginUser(username, password, { remember: 'on' });

			const expiry = getCookieExpiry(response);
			const expected = new Date();
			expected.setUTCDate(expected.getUTCDate() + meta.config.loginDays);

			assert.strictEqual(expiry.getUTCDate(), expected.getUTCDate());
		});

		it('should set the cookie expiry properly if loginDays setting is changed', async () => {
			const _loginDays = meta.config.loginDays;
			meta.config.loginDays = 5;

			const { response } = await helpers.loginUser(username, password, { remember: 'on' });

			const expiry = getCookieExpiry(response);
			const expected = new Date();
			expected.setUTCDate(expected.getUTCDate() + meta.config.loginDays);

			assert.strictEqual(expiry.getUTCDate(), expected.getUTCDate());

			meta.config.loginDays = _loginDays;
		});

		it('should ignore loginDays if loginSeconds is truthy', async () => {
			const _loginSeconds = meta.config.loginSeconds;
			meta.config.loginSeconds = 60;

			const { response } = await helpers.loginUser(username, password, { remember: 'on' });

			const expiry = getCookieExpiry(response);
			const expected = new Date();
			expected.setUTCSeconds(expected.getUTCSeconds() + meta.config.loginSeconds);

			assert.strictEqual(expiry.getUTCDate(), expected.getUTCDate());
			assert.strictEqual(expiry.getUTCMinutes(), expected.getUTCMinutes());

			meta.config.loginSeconds = _loginSeconds;
		});
	});

	it('should fail to login if ip address is invalid', async () => {
		const jar = request.jar();
		const csrf_token = await helpers.getCsrfToken(jar);

		const { response } = await request.post(`${nconf.get('url')}/login`, {
			body: {
				username: 'regular',
				password: 'regularpwd',
			},
			jar: jar,
			headers: {
				'x-csrf-token': csrf_token,
				'x-forwarded-for': '<script>alert("xss")</script>',
			},
		});
		assert.equal(response.status, 500);
	});

	it('should fail to login if body is missing', async () => {
		const jar = request.jar();
		const csrf_token = await helpers.getCsrfToken(jar);

		const { response, body } = await request.post(`${nconf.get('url')}/login`, {
			body: null,
			jar: jar,
			headers: {
				'x-csrf-token': csrf_token,
			},
		});
		assert.equal(response.status, 403);
		assert.strictEqual(body, '[[error:invalid-username-or-password]]');
	});

	it('should fail to login if user does not exist', async () => {
		const { response, body } = await helpers.loginUser('doesnotexist', 'nopassword');
		assert.equal(response.statusCode, 403);
		assert.equal(body, '[[error:invalid-login-credentials]]');
	});

	it('should fail to login if username is empty', async () => {
		const { response, body } = await helpers.loginUser('', 'some password');
		assert.equal(response.statusCode, 403);
		assert.equal(body, '[[error:invalid-username-or-password]]');
	});

	it('should fail to login if password is empty', async () => {
		const { response, body } = await helpers.loginUser('someuser', '');
		assert.equal(response.statusCode, 403);
		assert.equal(body, '[[error:invalid-username-or-password]]');
	});

	it('should fail to login if username and password are empty', async () => {
		const { response, body } = await helpers.loginUser('', '');
		assert.equal(response.statusCode, 403);
		assert.equal(body, '[[error:invalid-username-or-password]]');
	});

	it('should fail to login if user does not have password field in db', async () => {
		await user.create({ username: 'hasnopassword', email: '[email protected]' });
		const { response, body } = await helpers.loginUser('hasnopassword', 'doesntmatter');
		assert.equal(response.statusCode, 403);
		assert.equal(body, '[[error:invalid-login-credentials]]');
	});

	it('should fail to login if password is longer than 4096', async () => {
		let longPassword = '';
		for (let i = 0; i < 5000; i++) {
			longPassword += 'a';
		}
		const { response, body } = await helpers.loginUser('someuser', longPassword);
		assert.equal(response.statusCode, 403);
		assert.equal(body, '[[error:password-too-long]]');
	});

	it('should fail to login if local login is disabled', async () => {
		await privileges.global.rescind(['groups:local:login'], 'registered-users');
		const { response, body } = await helpers.loginUser('regular', 'regularpwd');
		assert.equal(response.statusCode, 403);
		assert.equal(body, '[[error:local-login-disabled]]');
		await privileges.global.give(['groups:local:login'], 'registered-users');
	});

	it('should fail to register if registraton is disabled', async () => {
		meta.config.registrationType = 'disabled';
		const { response, body } = await helpers.registerUser({
			username: 'someuser',
			password: 'somepassword',
		});
		assert.equal(response.statusCode, 403);
		assert.equal(body, 'Forbidden');
	});

	it('should return error if invitation is not valid', async () => {
		meta.config.registrationType = 'invite-only';
		const { response, body } = await helpers.registerUser({
			username: 'someuser',
			password: 'somepassword',
		});
		meta.config.registrationType = 'normal';
		assert.equal(response.statusCode, 400);
		assert.equal(body, '[[register:invite.error-invite-only]]');
	});

	describe('pending registrations', () => {
		let previousConfig;

		before(() => {
			previousConfig = {
				registrationType: meta.config.registrationType,
				registrationApprovalType: meta.config.registrationApprovalType,
				gdpr_enabled: meta.config.gdpr_enabled,
				sendValidationEmail: meta.config.sendValidationEmail,
			};
		});

		beforeEach(() => {
			meta.config.registrationType = 'normal';
			meta.config.registrationApprovalType = 'normal';
			meta.config.gdpr_enabled = 1;
			meta.config.sendValidationEmail = 0;
		});

		after(() => {
			Object.assign(meta.config, previousConfig);
		});

		function registrationBody(username) {
			return {
				username,
				email: `${username}@example.org`,
				password: 'pending-registration-password',
				'password-confirm': 'pending-registration-password',
			};
		}

		async function parkRegistration(username) {
			const jar = request.jar();
			const { response, body } = await helpers.request('post', '/register', {
				jar,
				body: registrationBody(username),
			});
			assert.strictEqual(response.status, 200);
			assert.strictEqual(body.next, `${nconf.get('relative_path')}/register/complete`);
			assert.strictEqual(await user.getUidByUsername(username), null);
			return jar;
		}

		async function completeRegistration(jar) {
			const formData = new FormData();
			formData.append('gdpr_agree_data', 'on');
			formData.append('gdpr_agree_email', 'on');
			return await helpers.request('post', '/register/complete', {
				jar,
				body: formData,
				redirect: 'manual',
			});
		}

		it('should complete if the registration policy still allows it', async () => {
			const username = `policy${utils.generateUUID().slice(0, 8)}`;
			const jar = await parkRegistration(username);
			const { response } = await completeRegistration(jar);

			assert.strictEqual(response.status, 302);
			assert(await user.getUidByUsername(username));
		});

		it('should reject a pending registration after registrations are disabled', async () => {
			const username = `policy${utils.generateUUID().slice(0, 8)}`;
			const jar = await parkRegistration(username);
			meta.config.registrationType = 'disabled';

			const { response } = await completeRegistration(jar);

			assert.strictEqual(response.status, 403);
			assert.strictEqual(await user.getUidByUsername(username), null);
		});

		it('should reject an uninvited pending registration after invite-only mode is enabled', async () => {
			const username = `policy${utils.generateUUID().slice(0, 8)}`;
			const jar = await parkRegistration(username);
			meta.config.registrationType = 'invite-only';

			const { response } = await completeRegistration(jar);

			assert.strictEqual(response.status, 302);
			const redirect = new URL(response.headers.location, nconf.get('url'));
			assert.strictEqual(redirect.searchParams.get('register'), '[[register:invite.error-invite-only]]');
			assert.strictEqual(await user.getUidByUsername(username), null);
		});

		it('should ignore a client-supplied uid in the registration body', async () => {
			meta.config.requireEmailAddress = 0;

			// Victim: an account with a confirmed email and no password (e.g. SSO-created)
			const suffix = utils.generateUUID().slice(0, 8);
			const victimUid = await user.create({
				username: `victim${suffix}`,
				email: `victim${suffix}@example.org`,
			}, { emailVerification: 'verify' });

			const username = `mallory${suffix}`;
			const jar = request.jar();
			const { response, body } = await helpers.request('post', '/register', {
				jar,
				body: {
					username,
					password: 'pending-registration-password',
					'password-confirm': 'pending-registration-password',
					uid: victimUid,
				},
			});
			assert.strictEqual(response.status, 200);
			assert.strictEqual(body.next, `${nconf.get('relative_path')}/register/complete`);

			const formData = new FormData();
			formData.append('email', '');
			formData.append('gdpr_agree_data', 'on');
			formData.append('gdpr_agree_email', 'on');
			const { response: res2 } = await helpers.request('post', '/register/complete', {
				jar,
				body: formData,
				redirect: 'manual',
			});
			assert.strictEqual(res2.status, 302);

			const victimData = await user.getUserFields(victimUid, ['email', 'email:confirmed']);
			assert.strictEqual(victimData.email, `victim${suffix}@example.org`);
			assert.strictEqual(victimData['email:confirmed'], 1);

			meta.config.requireEmailAddress = 1;
		});
	});

	it('should fail to register if username is falsy or too short', async () => {
		const userData = [
			{ username: '', password: 'somepassword' },
			{ username: 'a', password: 'somepassword' },
		];
		for (const user of userData) {
			// eslint-disable-next-line no-await-in-loop
			const { response, body } = await helpers.registerUser(user);
			assert.equal(response.statusCode, 400);
			assert.equal(body, '[[error:username-too-short]]');
		}
	});

	it('should fail to register if username is too long', async () => {
		const { response, body } = await helpers.registerUser({
			username: 'thisisareallylongusername',
			password: '123456',
		});

		assert.equal(response.statusCode, 400);
		assert.equal(body, '[[error:username-too-long]]');
	});

	it('should queue user if ip is used before', async () => {
		meta.config.registrationApprovalType = 'admin-approval-ip';
		const { response, body } = await helpers.registerUser({
			email: '[email protected]',
			username: 'anotheruser',
			password: 'anotherpwd',
			gdpr_consent: 1,
		});
		meta.config.registrationApprovalType = 'normal';
		assert.equal(response.statusCode, 200);
		assert.equal(body.message, '[[register:registration-added-to-queue]]');
	});


	it('should be able to login with email', async () => {
		const email = '[email protected]';
		const uid = await user.create({ username: 'ginger', password: '123456', email }, {
			emailVerification: 'verify',
		});
		const { response } = await helpers.loginUser('[email protected]', '123456');
		assert.equal(response.statusCode, 200);
	});

	it('should fail to login if login type is username and an email is sent', async () => {
		meta.config.allowLoginWith = 'username';
		const { response, body } = await helpers.loginUser('[email protected]', '123456');
		meta.config.allowLoginWith = 'username-email';
		assert.equal(response.statusCode, 400);
		assert.equal(body, '[[error:wrong-login-type-username]]');
	});

	it('should send 200 if not logged in', async () => {
		const jar = request.jar();
		const csrf_token = await helpers.getCsrfToken(jar);

		const { response, body } = await request.post(`${nconf.get('url')}/logout`, {
			data: {},
			jar: jar,
			headers: {
				'x-csrf-token': csrf_token,
			},
		});

		assert.equal(response.statusCode, 200);
		assert.equal(body, 'not-logged-in');
	});

	describe('banned user authentication', () => {
		const bannedUser = {
			username: 'banme',
			pw: '123456',
			uid: null,
		};

		before(async () => {
			bannedUser.uid = await user.create({ username: 'banme', password: '123456', email: '[email protected]' });
		});

		it('should prevent banned user from logging in', async () => {
			await user.bans.ban(bannedUser.uid, 0, 'spammer');
			const { response: res1, body: body1 } = await helpers.loginUser(bannedUser.username, bannedUser.pw);
			assert.equal(res1.statusCode, 403);
			delete body1.timestamp;
			assert.deepStrictEqual(body1, {
				banned_until: 0,
				banned_until_readable: '',
				expiry: 0,
				expiry_readable: '',
				reason: 'spammer',
				uid: bannedUser.uid,
			});
			await user.bans.unban(bannedUser.uid);
			const expiry = Date.now() + 10000;
			await user.bans.ban(bannedUser.uid, expiry, '');
			const { response: res2, body: body2 } = await helpers.loginUser(bannedUser.username, bannedUser.pw);
			assert.equal(res2.statusCode, 403);
			assert(body2.banned_until);
			assert(body2.reason, '[[user:info.banned-no-reason]]');
		});

		it('should allow banned user to log in if the "banned-users" group has "local-login" privilege', async () => {
			await privileges.global.give(['groups:local:login'], 'banned-users');
			const { response } = await helpers.loginUser(bannedUser.username, bannedUser.pw);
			assert.strictEqual(response.statusCode, 200);
		});

		it('should allow banned user to log in if the user herself has "local-login" privilege', async () => {
			await privileges.global.rescind(['groups:local:login'], 'banned-users');
			await privileges.categories.give(['local:login'], 0, bannedUser.uid);
			const { response } = await helpers.loginUser(bannedUser.username, bannedUser.pw);
			assert.strictEqual(response.statusCode, 200);
		});
	});

	it('should lockout account on 3 failed login attempts', async () => {
		meta.config.loginAttempts = 3;
		const uid = await user.create({ username: 'lockme', password: '123456' });
		await helpers.loginUser('lockme', 'abcdef');
		await helpers.loginUser('lockme', 'abcdef');
		await helpers.loginUser('lockme', 'abcdef');
		let data = await helpers.loginUser('lockme', 'abcdef');

		meta.config.loginAttempts = 5;
		assert.equal(data.response.statusCode, 403);
		assert.equal(data.body, '[[error:account-locked]]');
		data = await helpers.loginUser('lockme', 'abcdef');
		assert.equal(data.response.statusCode, 403);
		assert.equal(data.body, '[[error:account-locked]]');
		const locked = await db.exists(`lockout:${uid}`);
		assert(locked);
	});

	it('should lockout IP after 5 failed login attempts', async () => {
		const ip = '1.2.3.4';
		const jar = request.jar();
		const oldIpLoginAttempts = meta.config.ipLoginAttempts;
		meta.config.ipLoginAttempts = 5;
		const oldLoginAttempts = meta.config.loginAttempts;
		meta.config.loginAttempts = 1000;
		const csrf_token = await helpers.getCsrfToken(jar);
		const payload = { username: 'nonexistent', password: 'wrongpassword' };
		const headers = {
			'x-forwarded-for': ip,
			'x-csrf-token': csrf_token,
		};

		// 5 attempts should not lock out yet
		for (let i = 0; i < 5; i++) {
			// eslint-disable-next-line no-await-in-loop
			const { response, body } = await request.post(`${nconf.get('url')}/login`, {
				jar,
				body: payload,
				headers,
			});
			assert.strictEqual(response.statusCode, 403);
			assert.strictEqual(body, '[[error:invalid-login-credentials]]');
		}

		// 6th attempt should lock out
		const { response: res21, body: body21 } = await request.post(`${nconf.get('url')}/login`, {
			jar,
			body: payload,
			headers,
		});
		assert.strictEqual(res21.statusCode, 403);
		assert.strictEqual(body21, '[[error:ip-locked]]');

		// verify lockout key exists
		const locked = await db.exists(`lockout:ip:${ip}`);
		assert(locked);

		meta.config.loginAttempts = oldLoginAttempts;
		meta.config.ipLoginAttempts = oldIpLoginAttempts;
	});


	it('should clear all reset tokens upon successful login', async () => {
		const code = await user.reset.generate(regularUid);
		await helpers.loginUser('regular', 'regularpwd');
		const valid = await user.reset.validate(code);
		assert.strictEqual(valid, false);
	});

	describe('api tokens', () => {
		let newUid;
		let userToken;
		let masterToken;
		before(async () => {
			newUid = await user.create({ username: 'apiUserTarget' });
			userToken = await api.utils.tokens.generate({
				uid: newUid,
				description: `api token for uid ${newUid}`,
			});
			masterToken = await api.utils.tokens.generate({
				uid: 0,
				description: 'api master token',
			});
		});

		it('should fail with invalid token', async () => {
			const { response, body } = await helpers.request('get', `/api/self?_uid${newUid}`, {
				jar: jar,
				headers: {
					Authorization: `Bearer sdfhaskfdja-jahfdaksdf`,
				},
			});
			assert.strictEqual(response.statusCode, 401);
			assert.strictEqual(body, 'not-authorized');
		});

		it('should use a token tied to an uid', async () => {
			const { response, body } = await helpers.request('get', `/api/self`, {
				headers: {
					Authorization: `Bearer ${userToken}`,
				},
			});

			assert.strictEqual(response.statusCode, 200);
			assert.strictEqual(body.username, 'apiUserTarget');
		});

		it('should fail if _uid is not passed in with master token', async () => {
			const { response, body } = await helpers.request('get', `/api/self`, {
				headers: {
					Authorization: `Bearer ${masterToken}`,
				},
			});

			assert.strictEqual(response.statusCode, 500);
			assert.strictEqual(body.error, '[[error:api.master-token-no-uid]]');
		});

		it('should use master api token and _uid', async () => {
			const { response, body } = await helpers.request('get', `/api/self?_uid=${newUid}`, {
				headers: {
					Authorization: `Bearer ${masterToken}`,
				},
			});

			assert.strictEqual(response.statusCode, 200);
			assert.strictEqual(body.username, 'apiUserTarget');
		});

		it('should return an error if master api token _uid points to a banned user', async () => {
			await user.bans.ban(newUid);
			const { response, body } = await helpers.request('get', `/api/categories?_uid=${newUid}`, {
				headers: {
					Authorization: `Bearer ${masterToken}`,
				},
			});

			assert.strictEqual(response.statusCode, 403);
			assert.strictEqual(body.error, '[[error:user-banned]]');
			await user.bans.unban(newUid);
		});
	});
});