Skip to content

Commit

Permalink
Merge pull request #64 from hypersign-protocol/HSSTUD-145
Browse files Browse the repository at this point in the history
Hsstud 145
  • Loading branch information
varsha766 authored Feb 20, 2023
2 parents 5ed42a2 + 656e0bc commit 94407b1
Show file tree
Hide file tree
Showing 10 changed files with 65 additions and 17 deletions.
4 changes: 2 additions & 2 deletions src/app-auth/app-auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { AppAuthSecretService } from './services/app-auth-passord.service';
import { JwtModule } from '@nestjs/jwt';
import { JwtStrategy, JwtStrategyApp } from './strategy/jwt.strategy';
import { AppAuthApiKeyService } from './services/app-auth-apikey.service';
import { WhitelistCorsMiddleware } from './middlewares/cors.middleware';
import { WhitelistAppCorsMiddleware } from './middlewares/cors.middleware';
import { TrimMiddleware } from 'src/utils/middleware/trim.middleware';
@Module({
imports: [
Expand All @@ -49,7 +49,7 @@ import { TrimMiddleware } from 'src/utils/middleware/trim.middleware';
export class AppAuthModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(WhitelistCorsMiddleware)
.apply(WhitelistAppCorsMiddleware)
.forRoutes(AppAuthController, AppOAuthController);
consumer
.apply(TrimMiddleware)
Expand Down
3 changes: 3 additions & 0 deletions src/app-auth/controllers/app-auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import { PaginationDto } from 'src/utils/pagination.dto';
import { AppSecretHeader } from '../decorator/app-sercret.decorator';
import { TransformResponseInterceptor } from '../interceptors/transformResponse.interseptor';
import { JwtGuard } from '../guard/jwt.guard';
import { SanitizeUrl } from 'src/utils/customDecorator/urlSanitiser.decorator';

@UseFilters(AllExceptionsFilter)
@Controller('app')
Expand Down Expand Up @@ -124,6 +125,7 @@ export class AppAuthController {
}

@Post()
@SanitizeUrl()
@UseInterceptors(
MongooseClassSerializerInterceptor(createAppResponse, {
excludePrefixes: ['apiKeyPrefix', '_', '__'],
Expand Down Expand Up @@ -153,6 +155,7 @@ export class AppAuthController {
}),
)
@Put(':appId')
@SanitizeUrl()
@ApiResponse({
status: 200,
description: 'App updated',
Expand Down
24 changes: 20 additions & 4 deletions src/app-auth/middlewares/cors.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,36 @@ import {
NestMiddleware,
UnauthorizedException,
} from '@nestjs/common';

import { NextFunction, Request, Response } from 'express';
import { AppRepository } from 'src/app-auth/repositories/app.repository';
@Injectable()
export class WhitelistCorsMiddleware implements NestMiddleware {
export class WhitelistAppCorsMiddleware implements NestMiddleware {
constructor(private readonly appRepositiory: AppRepository) {}
async use(req: Request, res: Response, next: NextFunction) {
const whitelistedOrigins = process.env.WHITELISTED_CORS;
const apiSecretKey = req.headers['x-api-secret-key'] as string;
const origin = req.header('Origin');
if (!whitelistedOrigins.includes(origin)) {
if (whitelistedOrigins.includes(origin)) {
return next();
} else if (apiSecretKey !== '' && apiSecretKey != undefined) {
const apikeyIndex = apiSecretKey?.split('.')[0];
const appDetail = await this.appRepositiory.findOne({
apiKeyPrefix: apikeyIndex,
});
if (!appDetail) {
throw new UnauthorizedException(['access_denied']);
}
if (appDetail.whitelistedCors.includes('*')) {
return next();
}
if (!appDetail.whitelistedCors.includes(origin)) {
throw new UnauthorizedException(['Origin mismatch']);
}
return next();
} else {
throw new UnauthorizedException([
'This is CORS-enabled for a whitelisted domain.',
]);
}
next();
}
}
4 changes: 2 additions & 2 deletions src/credential/credential.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { HidWalletService } from 'src/hid-wallet/services/hid-wallet.service';
import { CredentialRepository } from './repository/credential.repository';
import { DidModule } from 'src/did/did.module';
import { AppAuthModule } from 'src/app-auth/app-auth.module';
import { WhitelistMiddleware } from 'src/utils/middleware/cors.middleware';
import { WhitelistSSICorsMiddleware } from 'src/utils/middleware/cors.middleware';
import { TrimMiddleware } from 'src/utils/middleware/trim.middleware';
@Module({
imports: [
Expand All @@ -42,7 +42,7 @@ import { TrimMiddleware } from 'src/utils/middleware/trim.middleware';
})
export class CredentialModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(WhitelistMiddleware).forRoutes(CredentialController);
consumer.apply(WhitelistSSICorsMiddleware).forRoutes(CredentialController);
consumer
.apply(TrimMiddleware)
.exclude(
Expand Down
5 changes: 5 additions & 0 deletions src/did/controllers/did.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,11 @@ export class DidController {
description: 'Error occured at the time of creating did',
type: DidError,
})
@ApiHeader({
name: 'Authorization',
description: 'Bearer <access_token>',
required: false,
})
@Post('/register')
@UsePipes(ValidationPipe)
register(@Body() registerDidDto: RegisterDidDto, @Req() req: any) {
Expand Down
4 changes: 2 additions & 2 deletions src/did/did.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import {
import { HidWalletModule } from 'src/hid-wallet/hid-wallet.module';
import { HidWalletService } from 'src/hid-wallet/services/hid-wallet.service';
import { AppAuthModule } from 'src/app-auth/app-auth.module';
import { WhitelistMiddleware } from 'src/utils/middleware/cors.middleware';
import { WhitelistSSICorsMiddleware } from 'src/utils/middleware/cors.middleware';
import { TrimMiddleware } from 'src/utils/middleware/trim.middleware';
@Module({
imports: [
Expand Down Expand Up @@ -52,7 +52,7 @@ import { TrimMiddleware } from 'src/utils/middleware/trim.middleware';
})
export class DidModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(WhitelistMiddleware).forRoutes(DidController);
consumer.apply(WhitelistSSICorsMiddleware).forRoutes(DidController);
consumer
.apply(TrimMiddleware)
.exclude(
Expand Down
4 changes: 2 additions & 2 deletions src/presentation/presentation.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { HidWalletService } from 'src/hid-wallet/services/hid-wallet.service';
import { EdvService } from 'src/edv/services/edv.service';
import { DidModule } from 'src/did/did.module';
import { AppAuthModule } from 'src/app-auth/app-auth.module';
import { WhitelistMiddleware } from 'src/utils/middleware/cors.middleware';
import { WhitelistSSICorsMiddleware } from 'src/utils/middleware/cors.middleware';
import { TrimMiddleware } from 'src/utils/middleware/trim.middleware';
import { AppAuthApiKeyService } from 'src/app-auth/services/app-auth-apikey.service';
@Module({
Expand All @@ -49,7 +49,7 @@ import { AppAuthApiKeyService } from 'src/app-auth/services/app-auth-apikey.serv
export class PresentationModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(WhitelistMiddleware)
.apply(WhitelistSSICorsMiddleware)
.forRoutes(PresentationTempleteController, PresentationController);
consumer
.apply(TrimMiddleware)
Expand Down
4 changes: 2 additions & 2 deletions src/schema/schema.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { DidModule } from 'src/did/did.module';
import { SchemaRepository } from './repository/schema.repository';
import { MongooseModule } from '@nestjs/mongoose';
import { Schemas, SchemasSchema } from './schemas/schemas.schema';
import { WhitelistMiddleware } from 'src/utils/middleware/cors.middleware';
import { WhitelistSSICorsMiddleware } from 'src/utils/middleware/cors.middleware';
import { AppAuthModule } from 'src/app-auth/app-auth.module';
import { TrimMiddleware } from 'src/utils/middleware/trim.middleware';
@Module({
Expand All @@ -37,7 +37,7 @@ import { TrimMiddleware } from 'src/utils/middleware/trim.middleware';
export class SchemaModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
//// Appy middleware on all routes
consumer.apply(WhitelistMiddleware).forRoutes(SchemaController);
consumer.apply(WhitelistSSICorsMiddleware).forRoutes(SchemaController);
//apply middleware on all routes except mentioned in exclude()
consumer
.apply(TrimMiddleware)
Expand Down
11 changes: 11 additions & 0 deletions src/utils/customDecorator/urlSanitiser.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export const SanitizeUrl = () => (target, key, descriptor) => {
const originalMethod = descriptor.value;
descriptor.value = function (...args) {
const urls = args[0].body.whitelistedCors;
const cleanedUrls = urls.map((url) => url.replace(/\/$/, ''));
const uniqueUrls = Array.from(new Set(cleanedUrls));
args[0].body.whitelistedCors = uniqueUrls;
return originalMethod.apply(this, args);
};
return descriptor;
};
19 changes: 16 additions & 3 deletions src/utils/middleware/cors.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,20 @@ import * as jwt from 'jsonwebtoken';
import { NextFunction, Request, Response } from 'express';
import { AppRepository } from 'src/app-auth/repositories/app.repository';
@Injectable()
export class WhitelistMiddleware implements NestMiddleware {
export class WhitelistSSICorsMiddleware implements NestMiddleware {
constructor(private readonly appRepositiory: AppRepository) {}
async use(req: Request, res: Response, next: NextFunction) {
const origin = req.header('Origin');
if (req.header('authorization') == undefined) {
const origin = req.header('Origin') || req.header('Referer');
let matchOrigin;
if (origin) {
// regex to check if url consists of some path or not
const originRegx = /^https?:\/\/[^\/]+/i;
matchOrigin = origin.match(originRegx);
}
if (
req.header('authorization') == undefined ||
req.header('authorization') == ''
) {
throw new UnauthorizedException([
'Unauthorized',
'Please pass access token',
Expand All @@ -25,6 +34,10 @@ export class WhitelistMiddleware implements NestMiddleware {
} catch (e) {
throw new UnauthorizedException([e]);
}
const whitelistedOrigins = process.env.WHITELISTED_CORS;
if (matchOrigin && whitelistedOrigins.includes(matchOrigin[0])) {
return next();
}
const appInfo = await this.appRepositiory.findOne({
appId: decoded['appId'],
userId: decoded['userId'],
Expand Down

0 comments on commit 94407b1

Please sign in to comment.