Skip to content

Commit

Permalink
test fix, remove most logs
Browse files Browse the repository at this point in the history
  • Loading branch information
SebastianW committed Dec 2, 2024
1 parent a6e5426 commit 9b226a6
Show file tree
Hide file tree
Showing 9 changed files with 121 additions and 65 deletions.
10 changes: 2 additions & 8 deletions libs/logger/src/logger.module.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { DynamicModule, Module } from '@nestjs/common';
import { Module } from '@nestjs/common';
import { OMSLogger } from './oms/oms.logger.service';

@Module({
Expand All @@ -7,10 +7,4 @@ import { OMSLogger } from './oms/oms.logger.service';
],
exports: [OMSLogger],
})
export class LoggerModule {
static register(): DynamicModule {
return {
module: LoggerModule
};
}
}
export class LoggerModule { }
10 changes: 5 additions & 5 deletions libs/oidc/src/controllers/login-callback.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Test, TestingModule } from '@nestjs/testing';
import { LoginCallbackController } from './login-callback.controller';
import { createResponse, createRequest } from 'node-mocks-http';
import { MockOidcService, MOCK_REQUEST } from '../mocks';
import { createRequest, createResponse } from 'node-mocks-http';
import { MOCK_REQUEST, MockOidcService } from '../mocks';
import { OidcService } from '../services';
import { LoginCallbackController } from './login-callback.controller';

describe('LoginCallbackController', () => {
let controller: LoginCallbackController;
Expand Down Expand Up @@ -33,8 +33,8 @@ describe('LoginCallbackController', () => {
});

describe('loginCallback', () => {
it('should call oidcService login', async () => {
const spy = jest.spyOn(oidcService, 'login').mockReturnThis();
it('should call oidcService login callback', async () => {
const spy = jest.spyOn(oidcService, 'loginCallback').mockReturnThis();
await controller.loginCallback(MOCK_REQ, MOCK_RES, MOCK_NEXT, MOCK_PARAMS);
expect(spy).toHaveBeenCalledWith(MOCK_REQ, MOCK_RES, MOCK_NEXT, MOCK_PARAMS);
});
Expand Down
22 changes: 12 additions & 10 deletions libs/oidc/src/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,19 +42,21 @@ export const MOCK_OIDC_MODULE_OPTIONS: OidcModuleOptions = {
export const MockOidcService = {
options: {},

login: (req, res, next, params) => {},
login: (req, res, next, params) => { },

logout: (req, res, params) => {},
loginCallback: (req, res, next, params) => { },

checkToken: (req, res) => {},
logout: (req, res, params) => { },

refreshTokens: (req, res) => {},
checkToken: (req, res) => { },

loggedOut: (res, params) => {},
refreshTokens: (req, res) => { },

tenantSwitchWarn: (res, params) => {},
loggedOut: (res, params) => { },

isExpired: () => {},
tenantSwitchWarn: (res, params) => { },

isExpired: () => { },

createStrategy: () => {
return Promise.resolve({});
Expand All @@ -64,11 +66,11 @@ export const MockOidcService = {
return 'tenant.b2c';
},

updateSessionDuration: req => {},
updateSessionDuration: req => { },

updateUserAuthToken: (data, req) => {},
updateUserAuthToken: (data, req) => { },

requestTokenRefresh: authTokens => {},
requestTokenRefresh: authTokens => { },
};

export const MOCK_REQUEST = {
Expand Down
8 changes: 7 additions & 1 deletion libs/oidc/src/oidc.module.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createMock } from '@golevelup/nestjs-testing';
import { MiddlewareConsumer } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { Test, TestingModule } from '@nestjs/testing';
import { Issuer } from 'openid-client';
import { MOCK_ISSUER_INSTANCE, MOCK_OIDC_MODULE_OPTIONS } from './mocks';
Expand All @@ -14,7 +15,12 @@ describe(OidcModule.name, () => {
IssuerMock.keystore = jest.fn();
jest.spyOn(Issuer, 'discover').mockImplementation(() => Promise.resolve(IssuerMock));
module = await Test.createTestingModule({
imports: [OidcModule.forRoot(MOCK_OIDC_MODULE_OPTIONS)],
imports: [
OidcModule.forRoot(MOCK_OIDC_MODULE_OPTIONS),
ConfigModule.forRoot({
load: [() => { return { APIM_BASE_URL: 'https://localhost' } }]
}),
],
}).compile();
});

Expand Down
38 changes: 35 additions & 3 deletions libs/oidc/src/services/oidc.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ConfigService } from '@nestjs/config';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { Test, TestingModule } from '@nestjs/testing';
import axios from 'axios';
import * as handlebars from 'handlebars';
import { JWKS } from 'jose';
Expand All @@ -12,10 +13,35 @@ import { SSRPagesService } from './ssr-pages.service';
import passport = require('passport');

describe('OidcService', () => {
let service = new OidcService(MOCK_OIDC_MODULE_OPTIONS, new ConfigService(), new SSRPagesService());
let service/* = new OidcService(MOCK_OIDC_MODULE_OPTIONS, new ConfigService(), new SSRPagesService()) */;
let options: OidcModuleOptions = MOCK_OIDC_MODULE_OPTIONS;
const idpKey = 'idpKey';

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [
ConfigModule.forRoot({
load: [
() => {
return {
APIM_BASE_URL: 'https://localhost',
SERVER_INSTANCE_ID: 'id123'
}
}
]
}),
],
providers: [
{
provide: OidcService,
useValue: new OidcService(options, new ConfigService(), new SSRPagesService())
}
]
}).compile();

service = module.get<OidcService>(OidcService);
});

describe('createStrategy', () => {
beforeEach(async () => {
const IssuerMock = MOCK_ISSUER_INSTANCE;
Expand Down Expand Up @@ -211,7 +237,7 @@ describe('OidcService', () => {
};

const spy = jest.spyOn(passport, 'authenticate').mockImplementation((strategy, options, cb) => {
cb();
cb('error');
return (req, res, next) => { };
});

Expand Down Expand Up @@ -274,6 +300,8 @@ describe('OidcService', () => {
cb();
});
req.query = { request_url: null };
req.host = 'localhost';
req.headers.host = 'localhost';

const spy = jest.spyOn(passport, 'authenticate').mockImplementation((strategy, options, cb) => {
req.query = {
Expand Down Expand Up @@ -327,6 +355,8 @@ describe('OidcService', () => {
maxAge: 0,
},
};
req.host = 'localhost';
req.headers.host = 'localhost';

const spy = jest.spyOn(passport, 'authenticate').mockImplementation((strategy, options, cb) => {
req.query = {
Expand Down Expand Up @@ -359,6 +389,8 @@ describe('OidcService', () => {
maxAge: 0,
},
};
req.host = 'localhost';
req.headers.host = 'localhost';

const spy = jest.spyOn(passport, 'authenticate').mockImplementation((strategy, options, cb) => {
req.query = {
Expand Down
17 changes: 4 additions & 13 deletions libs/oidc/src/services/oidc.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,6 @@ export class OidcService implements OnModuleInit {
req.session['tenant'] = tenantId;
req.session['channel'] = channel;
redirect_url = Buffer.from(JSON.stringify({ redirect_url: `${prefix}${redirect_url}`, loginpopup: loginpopup }), 'utf-8',).toString('base64');
this.logger.log(this.#sessionLog({ name: 'PRE_AUTHENTICATE', req }));

passport.authenticate(
Object.create(strategy),
Expand All @@ -179,7 +178,6 @@ export class OidcService implements OnModuleInit {
this.logger.error(this.#sessionLog({ name: 'AUTHENTICATE ERROR', req }));
return next(err || info);
}
this.logger.log(this.#sessionLog({ name: 'PRE_LOGIN_REQ', req }));
req.logIn(user, err => {
if (err) {
this.logger.error(this.#sessionLog({ name: 'LOGIN_REQ ERROR', req }));
Expand All @@ -192,19 +190,16 @@ export class OidcService implements OnModuleInit {
let url: string = state['redirect_url'];
url = !url.startsWith('/') ? `/${url}` : url;
const loginpopup = state['loginpopup'];
this.logger.log(this.#sessionLog({ name: 'PRE_REDIRECT', req }));
if (loginpopup) {
return res.send(`
<script type="text/javascript">
window.close();
</script >
`);
} else {
this.logger.log(this.#sessionLog({ name: 'AUTHENTICATION SUCCESS', req }));
if (req.get('host').includes(this.#region) === true || req.headers.host.includes(this.#region) === true) {
this.logger.log(this.#sessionLog({ name: 'AUTHENTICATION SUCCESS URL WITH REGION', req }));
const redirect_url = this.#oidc_redirect_uri.replace(`-${this.#region}`, '').replace(`/${_loginCallbackPath}`, '');
this.logger.log(`redirect_uri: ${redirect_url}`);
this.logger.log(this.#sessionLog({ name: 'AUTHENTICATION SUCCESS URL WITH REGION', req, redirectUri: redirect_url }));
return res.redirect(redirect_url);
}
return res.redirect(url);
Expand All @@ -220,11 +215,9 @@ export class OidcService implements OnModuleInit {
}

async loginCallback(@Req() req: Request, @Res() res: Response, @Next() next: Function, @Param() params) {
this.logger.log(this.#sessionLog({ name: 'LOGIN CALLBACK', req }));
const session = req.session[this.#sessionKey];

if (Object.keys(session || {}).length === 0) {
// TODO: check if same region is always responding (redirect_uri.includes(this.region))
this.logger.log(this.#sessionLog({ name: 'LOGIN CALLBACK SESSION EMPTY', req }));
}
return this.login(req, res, next, params);
Expand Down Expand Up @@ -267,7 +260,6 @@ export class OidcService implements OnModuleInit {
this.logger.log(`REFRESH TOKEN user: ${user}`);

if (!req.isAuthenticated()) {
this.logger.log(`REFRESH TOKEN isAuthenticated: ${req.isAuthenticated()}`);
res.sendStatus(401);
return;
}
Expand Down Expand Up @@ -380,10 +372,9 @@ export class OidcService implements OnModuleInit {
return [tenantPrefix, channelPrefix].filter(Boolean).join('/');
}

#sessionLog({ name, req, instanceID = this.#instanceID, region = this.#region, sessionKey = this.#sessionKey, redirectUri = this.#oidc_redirect_uri }: LogParams = {} as LogParams): string {
const session = JSON.stringify(req.session[sessionKey] ?? {});
return `${name.toLocaleUpperCase()} url: ${req.url}, method: ${req.method}, instanceID: ${instanceID}, region: ${region}, redirect_uri: ${redirectUri}, session: ${session}`;
#sessionLog({ name, req, instanceID = this.#instanceID, region = this.#region, redirectUri = this.#oidc_redirect_uri }: LogParams = {} as LogParams): string {
return `${name.toLocaleUpperCase()} url: ${req.url}, instanceID: ${instanceID}, region: ${region}, redirect_uri: ${redirectUri}`;
}
}

interface LogParams { name: string, req: Request, instanceID?: string, region?: string, sessionKey?: string, redirectUri?: string };
interface LogParams { name: string, req: Request, instanceID?: string, region?: string, redirectUri?: string };
28 changes: 25 additions & 3 deletions libs/oidc/src/strategies/oidc.strategy.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createMock } from '@golevelup/nestjs-testing';
import { ConfigService } from '@nestjs/config';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { Test, TestingModule } from '@nestjs/testing';
import { JWKS } from 'jose';
import { TokenSet } from 'openid-client';
import { MOCK_CLIENT_INSTANCE, MOCK_OIDC_MODULE_OPTIONS, MOCK_TRUST_ISSUER } from '../mocks';
Expand All @@ -12,8 +13,29 @@ describe('OidcStrategy', () => {
let strategy: OidcStrategy;
let mockTokenset: TokenSet;

beforeEach(() => {
const mockOidcService = new OidcService(MOCK_OIDC_MODULE_OPTIONS, new ConfigService(), new SSRPagesService());
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [
ConfigModule.forRoot({
load: [
() => {
return {
APIM_BASE_URL: 'https://localhost',
SERVER_INSTANCE_ID: 'id123'
}
}
]
}),
],
providers: [
{
provide: OidcService,
useValue: new OidcService(MOCK_OIDC_MODULE_OPTIONS, new ConfigService(), new SSRPagesService())
}
]
}).compile();

const mockOidcService = module.get<OidcService>(OidcService);
const idpKey = 'idpKey';
mockOidcService.idpInfos[idpKey] = {
client: MOCK_CLIENT_INSTANCE,
Expand Down
28 changes: 25 additions & 3 deletions libs/oidc/src/utils/user-info.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ConfigService } from '@nestjs/config';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { Test, TestingModule } from '@nestjs/testing';
import { JWKS } from 'jose';
import { UserInfoMethod } from '../interfaces';
import { MOCK_CLIENT_INSTANCE, MOCK_OIDC_MODULE_OPTIONS, MOCK_TRUST_ISSUER } from '../mocks';
Expand All @@ -15,8 +16,29 @@ describe('OidcStrategy', () => {
const idpKey = 'idpKey';
let service;

beforeEach(() => {
service = new OidcService(MOCK_OIDC_MODULE_OPTIONS, new ConfigService(), new SSRPagesService());
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [
ConfigModule.forRoot({
load: [
() => {
return {
APIM_BASE_URL: 'https://localhost',
SERVER_INSTANCE_ID: 'id123'
}
}
]
}),
],
providers: [
{
provide: OidcService,
useValue: new OidcService(MOCK_OIDC_MODULE_OPTIONS, new ConfigService(), new SSRPagesService())
}
]
}).compile();
// service = new OidcService(MOCK_OIDC_MODULE_OPTIONS, new ConfigService(), new SSRPagesService());
service = module.get<OidcService>(OidcService);
service.idpInfos[idpKey] = {
client: MOCK_CLIENT_INSTANCE,
tokenStore: new JWKS.KeyStore([]),
Expand Down
Loading

0 comments on commit 9b226a6

Please sign in to comment.