auth: Add token limit of 200

This is a very high ceiling unlikely to hinder legitimate usage, but should prevent possible attack vectors

Signed-off-by: Philip Molares <philip.molares@udo.edu>
This commit is contained in:
Philip Molares 2021-01-25 12:05:25 +01:00 committed by David Mehren
parent 39d9fb5dec
commit af993407b3
No known key found for this signature in database
GPG key ID: 185982BA4C42B7C3
2 changed files with 17 additions and 2 deletions

View file

@ -11,7 +11,11 @@ import { AuthToken } from './auth-token.entity';
import { AuthTokenDto } from './auth-token.dto'; import { AuthTokenDto } from './auth-token.dto';
import { AuthTokenWithSecretDto } from './auth-token-with-secret.dto'; import { AuthTokenWithSecretDto } from './auth-token-with-secret.dto';
import { compare, hash } from 'bcrypt'; import { compare, hash } from 'bcrypt';
import { NotInDBError, TokenNotValidError } from '../errors/errors'; import {
NotInDBError,
TokenNotValidError,
TooManyTokensError,
} from '../errors/errors';
import { randomBytes } from 'crypto'; import { randomBytes } from 'crypto';
import { InjectRepository } from '@nestjs/typeorm'; import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm'; import { Repository } from 'typeorm';
@ -76,7 +80,14 @@ export class AuthService {
identifier: string, identifier: string,
validUntil: TimestampMillis, validUntil: TimestampMillis,
): Promise<AuthTokenWithSecretDto> { ): Promise<AuthTokenWithSecretDto> {
const user = await this.usersService.getUserByUsername(userName); 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(
`User '${user.displayName}' has already 200 tokens and can't have anymore`,
);
}
const secret = await this.randomString(64); const secret = await this.randomString(64);
const keyId = this.BufferToBase64Url(await this.randomString(8)); const keyId = this.BufferToBase64Url(await this.randomString(8));
const accessTokenString = await this.hashPassword(secret.toString()); const accessTokenString = await this.hashPassword(secret.toString());

View file

@ -19,3 +19,7 @@ export class PermissionError extends Error {
export class TokenNotValidError extends Error { export class TokenNotValidError extends Error {
name = 'TokenNotValidError'; name = 'TokenNotValidError';
} }
export class TooManyTokensError extends Error {
name = 'TooManyTokensError';
}