2021-01-22 09:29:10 -05:00
|
|
|
/*
|
|
|
|
* SPDX-FileCopyrightText: 2021 The HedgeDoc developers (see AUTHORS file)
|
|
|
|
*
|
|
|
|
* SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
*/
|
|
|
|
|
2021-01-29 16:00:47 -05:00
|
|
|
import { Injectable } from '@nestjs/common';
|
2021-01-15 12:53:09 -05:00
|
|
|
import { UsersService } from '../users/users.service';
|
|
|
|
import { User } from '../users/user.entity';
|
2021-01-22 09:29:10 -05:00
|
|
|
import { AuthToken } from './auth-token.entity';
|
|
|
|
import { AuthTokenDto } from './auth-token.dto';
|
|
|
|
import { AuthTokenWithSecretDto } from './auth-token-with-secret.dto';
|
|
|
|
import { compare, hash } from 'bcrypt';
|
2021-01-25 06:05:25 -05:00
|
|
|
import {
|
|
|
|
NotInDBError,
|
|
|
|
TokenNotValidError,
|
|
|
|
TooManyTokensError,
|
|
|
|
} from '../errors/errors';
|
2021-01-22 09:29:10 -05:00
|
|
|
import { randomBytes } from 'crypto';
|
|
|
|
import { InjectRepository } from '@nestjs/typeorm';
|
|
|
|
import { Repository } from 'typeorm';
|
|
|
|
import { ConsoleLoggerService } from '../logger/console-logger.service';
|
2021-01-23 15:24:11 -05:00
|
|
|
import { TimestampMillis } from '../utils/timestamp';
|
2021-01-25 10:29:09 -05:00
|
|
|
import { Cron, Timeout } from '@nestjs/schedule';
|
2021-01-15 12:53:09 -05:00
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class AuthService {
|
2021-01-22 09:29:10 -05:00
|
|
|
constructor(
|
|
|
|
private readonly logger: ConsoleLoggerService,
|
|
|
|
private usersService: UsersService,
|
|
|
|
@InjectRepository(AuthToken)
|
|
|
|
private authTokenRepository: Repository<AuthToken>,
|
|
|
|
) {
|
|
|
|
this.logger.setContext(AuthService.name);
|
|
|
|
}
|
2021-01-15 12:53:09 -05:00
|
|
|
|
|
|
|
async validateToken(token: string): Promise<User> {
|
2021-01-29 16:00:47 -05:00
|
|
|
const [keyId, secret] = token.split('.');
|
2021-01-29 16:24:19 -05:00
|
|
|
if (!secret) {
|
|
|
|
throw new TokenNotValidError('Invalid AuthToken format');
|
|
|
|
}
|
2021-01-29 16:00:47 -05:00
|
|
|
if (secret.length > 72) {
|
|
|
|
// Only the first 72 characters of the tokens are considered by bcrypt
|
|
|
|
// This should prevent strange corner cases
|
|
|
|
// At the very least it won't hurt us
|
|
|
|
throw new TokenNotValidError(
|
|
|
|
`AuthToken '${secret}' is too long the be a proper token`,
|
|
|
|
);
|
2021-01-15 12:53:09 -05:00
|
|
|
}
|
2021-01-29 16:00:47 -05:00
|
|
|
const accessToken = await this.getAuthTokenAndValidate(keyId, secret);
|
|
|
|
await this.setLastUsedToken(keyId);
|
2021-02-20 14:14:36 -05:00
|
|
|
return await this.usersService.getUserByUsername(accessToken.user.userName);
|
2021-01-15 12:53:09 -05:00
|
|
|
}
|
2021-01-22 09:29:10 -05:00
|
|
|
|
|
|
|
async hashPassword(cleartext: string): Promise<string> {
|
2021-01-23 13:04:00 -05:00
|
|
|
// hash the password with bcrypt and 2^12 iterations
|
2021-01-23 15:24:11 -05:00
|
|
|
// this was decided on the basis of https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#bcrypt
|
2021-02-20 14:14:36 -05:00
|
|
|
return await hash(cleartext, 12);
|
2021-01-22 09:29:10 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
async checkPassword(cleartext: string, password: string): Promise<boolean> {
|
2021-02-20 14:14:36 -05:00
|
|
|
return await compare(cleartext, password);
|
2021-01-22 09:29:10 -05:00
|
|
|
}
|
|
|
|
|
2021-02-23 16:16:27 -05:00
|
|
|
randomString(length: number): Buffer {
|
2021-01-23 13:04:00 -05:00
|
|
|
if (length <= 0) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
return randomBytes(length);
|
|
|
|
}
|
|
|
|
|
2021-02-20 15:15:45 -05:00
|
|
|
bufferToBase64Url(text: Buffer): string {
|
2021-01-25 10:29:09 -05:00
|
|
|
// This is necessary as the is no base64url encoding in the toString method
|
|
|
|
// but as can be seen on https://tools.ietf.org/html/rfc4648#page-7
|
|
|
|
// base64url is quite easy buildable from base64
|
2021-01-23 13:04:00 -05:00
|
|
|
return text
|
2021-01-22 09:29:10 -05:00
|
|
|
.toString('base64')
|
2021-01-26 04:19:12 -05:00
|
|
|
.replace(/\+/g, '-')
|
|
|
|
.replace(/\//g, '_')
|
|
|
|
.replace(/=+$/, '');
|
2021-01-22 09:29:10 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
async createTokenForUser(
|
|
|
|
userName: string,
|
|
|
|
identifier: string,
|
2021-01-23 15:24:11 -05:00
|
|
|
validUntil: TimestampMillis,
|
2021-01-22 09:29:10 -05:00
|
|
|
): Promise<AuthTokenWithSecretDto> {
|
2021-01-25 06:05:25 -05:00
|
|
|
const user = await this.usersService.getUserByUsername(userName, true);
|
|
|
|
if (user.authTokens.length >= 200) {
|
|
|
|
// This is a very high ceiling unlikely to hinder legitimate usage,
|
|
|
|
// but should prevent possible attack vectors
|
|
|
|
throw new TooManyTokensError(
|
2021-01-25 12:16:08 -05:00
|
|
|
`User '${user.userName}' has already 200 tokens and can't have anymore`,
|
2021-01-25 06:05:25 -05:00
|
|
|
);
|
|
|
|
}
|
2021-02-23 16:16:27 -05:00
|
|
|
const secret = this.bufferToBase64Url(this.randomString(54));
|
|
|
|
const keyId = this.bufferToBase64Url(this.randomString(8));
|
2021-01-26 04:19:12 -05:00
|
|
|
const accessToken = await this.hashPassword(secret);
|
2021-01-22 09:29:10 -05:00
|
|
|
let token;
|
2021-01-25 06:14:26 -05:00
|
|
|
// Tokens can only be valid for a maximum of 2 years
|
|
|
|
const maximumTokenValidity =
|
|
|
|
new Date().getTime() + 2 * 365 * 24 * 60 * 60 * 1000;
|
|
|
|
if (validUntil === 0 || validUntil > maximumTokenValidity) {
|
|
|
|
token = AuthToken.create(
|
|
|
|
user,
|
|
|
|
identifier,
|
|
|
|
keyId,
|
|
|
|
accessToken,
|
|
|
|
new Date(maximumTokenValidity),
|
|
|
|
);
|
2021-01-22 09:29:10 -05:00
|
|
|
} else {
|
2021-01-23 15:24:11 -05:00
|
|
|
token = AuthToken.create(
|
|
|
|
user,
|
|
|
|
identifier,
|
|
|
|
keyId,
|
|
|
|
accessToken,
|
|
|
|
new Date(validUntil),
|
|
|
|
);
|
2021-01-22 09:29:10 -05:00
|
|
|
}
|
2021-02-24 16:35:06 -05:00
|
|
|
const createdToken = (await this.authTokenRepository.save(
|
|
|
|
token,
|
|
|
|
)) as AuthToken;
|
2021-01-22 09:29:10 -05:00
|
|
|
return this.toAuthTokenWithSecretDto(createdToken, `${keyId}.${secret}`);
|
|
|
|
}
|
|
|
|
|
2021-02-27 11:41:32 -05:00
|
|
|
async setLastUsedToken(keyId: string): Promise<void> {
|
2021-01-22 09:29:10 -05:00
|
|
|
const accessToken = await this.authTokenRepository.findOne({
|
|
|
|
where: { keyId: keyId },
|
|
|
|
});
|
2021-01-23 15:24:11 -05:00
|
|
|
accessToken.lastUsed = new Date();
|
2021-01-22 09:29:10 -05:00
|
|
|
await this.authTokenRepository.save(accessToken);
|
|
|
|
}
|
|
|
|
|
2021-01-23 13:04:00 -05:00
|
|
|
async getAuthTokenAndValidate(
|
|
|
|
keyId: string,
|
|
|
|
token: string,
|
|
|
|
): Promise<AuthToken> {
|
2021-01-22 09:29:10 -05:00
|
|
|
const accessToken = await this.authTokenRepository.findOne({
|
|
|
|
where: { keyId: keyId },
|
|
|
|
relations: ['user'],
|
|
|
|
});
|
|
|
|
if (accessToken === undefined) {
|
|
|
|
throw new NotInDBError(`AuthToken '${token}' not found`);
|
|
|
|
}
|
|
|
|
if (!(await this.checkPassword(token, accessToken.accessTokenHash))) {
|
|
|
|
// hashes are not the same
|
|
|
|
throw new TokenNotValidError(`AuthToken '${token}' is not valid.`);
|
|
|
|
}
|
|
|
|
if (
|
|
|
|
accessToken.validUntil &&
|
2021-01-23 15:24:11 -05:00
|
|
|
accessToken.validUntil.getTime() < new Date().getTime()
|
2021-01-22 09:29:10 -05:00
|
|
|
) {
|
|
|
|
// tokens validUntil Date lies in the past
|
|
|
|
throw new TokenNotValidError(
|
2021-02-24 16:35:06 -05:00
|
|
|
`AuthToken '${token}' is not valid since ${accessToken.validUntil.toISOString()}.`,
|
2021-01-22 09:29:10 -05:00
|
|
|
);
|
|
|
|
}
|
|
|
|
return accessToken;
|
|
|
|
}
|
|
|
|
|
|
|
|
async getTokensByUsername(userName: string): Promise<AuthToken[]> {
|
|
|
|
const user = await this.usersService.getUserByUsername(userName, true);
|
|
|
|
if (user.authTokens === undefined) {
|
|
|
|
return [];
|
|
|
|
}
|
|
|
|
return user.authTokens;
|
|
|
|
}
|
|
|
|
|
2021-02-27 11:41:32 -05:00
|
|
|
async removeToken(keyId: string): Promise<void> {
|
2021-01-22 09:29:10 -05:00
|
|
|
const token = await this.authTokenRepository.findOne({
|
2021-01-23 16:24:59 -05:00
|
|
|
where: { keyId: keyId },
|
2021-01-22 09:29:10 -05:00
|
|
|
});
|
|
|
|
await this.authTokenRepository.remove(token);
|
|
|
|
}
|
|
|
|
|
2021-01-23 15:24:11 -05:00
|
|
|
toAuthTokenDto(authToken: AuthToken): AuthTokenDto | null {
|
2021-01-22 09:29:10 -05:00
|
|
|
if (!authToken) {
|
2021-02-24 16:35:06 -05:00
|
|
|
this.logger.warn(
|
|
|
|
`Recieved ${String(authToken)} argument!`,
|
|
|
|
'toAuthTokenDto',
|
|
|
|
);
|
2021-01-22 09:29:10 -05:00
|
|
|
return null;
|
|
|
|
}
|
2021-01-23 15:24:11 -05:00
|
|
|
const tokenDto: AuthTokenDto = {
|
|
|
|
lastUsed: null,
|
|
|
|
validUntil: null,
|
2021-01-24 14:37:04 -05:00
|
|
|
label: authToken.label,
|
2021-01-22 09:29:10 -05:00
|
|
|
keyId: authToken.keyId,
|
2021-01-23 15:24:11 -05:00
|
|
|
createdAt: authToken.createdAt,
|
2021-01-22 09:29:10 -05:00
|
|
|
};
|
2021-01-23 15:24:11 -05:00
|
|
|
|
|
|
|
if (authToken.validUntil) {
|
|
|
|
tokenDto.validUntil = new Date(authToken.validUntil);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (authToken.lastUsed) {
|
|
|
|
tokenDto.lastUsed = new Date(authToken.lastUsed);
|
|
|
|
}
|
|
|
|
|
|
|
|
return tokenDto;
|
2021-01-22 09:29:10 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
toAuthTokenWithSecretDto(
|
|
|
|
authToken: AuthToken | null | undefined,
|
|
|
|
secret: string,
|
|
|
|
): AuthTokenWithSecretDto | null {
|
2021-01-23 13:04:00 -05:00
|
|
|
const tokenDto = this.toAuthTokenDto(authToken);
|
2021-01-22 09:29:10 -05:00
|
|
|
return {
|
2021-01-23 13:04:00 -05:00
|
|
|
...tokenDto,
|
2021-01-22 09:29:10 -05:00
|
|
|
secret: secret,
|
|
|
|
};
|
|
|
|
}
|
2021-01-24 14:37:04 -05:00
|
|
|
|
|
|
|
// Delete all non valid tokens every sunday on 3:00 AM
|
|
|
|
@Cron('0 0 3 * * 0')
|
2021-02-27 11:41:32 -05:00
|
|
|
async handleCron(): Promise<void> {
|
2021-02-20 14:14:36 -05:00
|
|
|
return await this.removeInvalidTokens();
|
2021-01-25 10:29:09 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Delete all non valid tokens 5 sec after startup
|
|
|
|
@Timeout(5000)
|
2021-02-27 11:41:32 -05:00
|
|
|
async handleTimeout(): Promise<void> {
|
2021-02-20 14:14:36 -05:00
|
|
|
return await this.removeInvalidTokens();
|
2021-01-25 10:29:09 -05:00
|
|
|
}
|
|
|
|
|
2021-02-27 11:41:32 -05:00
|
|
|
async removeInvalidTokens(): Promise<void> {
|
2021-01-24 14:37:04 -05:00
|
|
|
const currentTime = new Date().getTime();
|
|
|
|
const tokens: AuthToken[] = await this.authTokenRepository.find();
|
2021-01-25 10:29:09 -05:00
|
|
|
let removedTokens = 0;
|
2021-01-24 14:37:04 -05:00
|
|
|
for (const token of tokens) {
|
|
|
|
if (token.validUntil && token.validUntil.getTime() <= currentTime) {
|
2021-02-05 16:30:22 -05:00
|
|
|
this.logger.debug(
|
|
|
|
`AuthToken '${token.keyId}' was removed`,
|
|
|
|
'removeInvalidTokens',
|
|
|
|
);
|
2021-01-24 14:37:04 -05:00
|
|
|
await this.authTokenRepository.remove(token);
|
2021-01-25 10:29:09 -05:00
|
|
|
removedTokens++;
|
2021-01-24 14:37:04 -05:00
|
|
|
}
|
|
|
|
}
|
2021-01-25 10:29:09 -05:00
|
|
|
this.logger.log(
|
|
|
|
`${removedTokens} invalid AuthTokens were purged from the DB.`,
|
2021-02-05 16:30:22 -05:00
|
|
|
'removeInvalidTokens',
|
2021-01-25 10:29:09 -05:00
|
|
|
);
|
2021-01-24 14:37:04 -05:00
|
|
|
}
|
2021-01-15 12:53:09 -05:00
|
|
|
}
|