Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BC-5522-Implementation of an API for deleting data #4533

Merged
merged 125 commits into from
Nov 30, 2023
Merged
Show file tree
Hide file tree
Changes from 59 commits
Commits
Show all changes
125 commits
Select commit Hold shift + click to select a range
cce8684
endpoints preparation
sszafGCA Nov 8, 2023
aa32e24
Merge remote-tracking branch 'origin' into BC-5522-impl-of-deletion-api
sszafGCA Nov 8, 2023
5308f8f
Merge branch 'main' into BC-5522-impl-of-deletion-api
sszafGCA Nov 9, 2023
d6e0922
Merge branch 'main' into BC-5522-impl-of-deletion-api
sszafGCA Nov 9, 2023
175e495
auth startegy impl
sszafGCA Nov 9, 2023
fd2b9b8
api impl
sszafGCA Nov 10, 2023
7d3b626
some changes
WojciechGrancow Nov 10, 2023
a954f6b
some fixes need in KNL module
WojciechGrancow Nov 11, 2023
a07bd74
Merge branch 'main' into BC-5522-impl-of-deletion-api
WojciechGrancow Nov 11, 2023
60aa0ac
changes in uc and register entities
WojciechGrancow Nov 12, 2023
c65367b
Pr fixes and minor changes
sszafGCA Nov 12, 2023
bf27fd8
rename file
sszafGCA Nov 12, 2023
d477ba7
some fixes
WojciechGrancow Nov 13, 2023
762a9ee
Merge branch 'main' into BC-5522-impl-of-deletion-api
WojciechGrancow Nov 13, 2023
80430f5
add exposing admin API port from the api-svc
bn-pass Nov 13, 2023
24b823c
add server test module + delete FileEntity from allEntities
sszafGCA Nov 13, 2023
f4e10ff
change module
sszafGCA Nov 13, 2023
f2f2a5d
admin api server module test impl
sszafGCA Nov 13, 2023
9c4be9e
add some tests
WojciechGrancow Nov 14, 2023
4ab94f8
Merge branch 'BC-5522-impl-of-deletion-api' of https://github.com/hpi…
WojciechGrancow Nov 14, 2023
9a790fd
Merge branch 'main' into BC-5522-impl-of-deletion-api
WojciechGrancow Nov 14, 2023
b5e2a01
add some test for API
WojciechGrancow Nov 14, 2023
495e953
Merge branch 'main' into BC-5522-impl-of-deletion-api
WojciechGrancow Nov 14, 2023
bd430e9
add some test
WojciechGrancow Nov 14, 2023
fb3012f
Merge branch 'main' into BC-5522-impl-of-deletion-api
WojciechGrancow Nov 14, 2023
caf07ab
x-api-key.strategy tests
sszafGCA Nov 14, 2023
b040876
x-api-key-strategy-tests impl
sszafGCA Nov 14, 2023
0d3074e
remove test for api-setup-helper, remove unused imports
sszafGCA Nov 14, 2023
d935d13
remove test file
sszafGCA Nov 14, 2023
01340fb
add info for the Admin API port
bn-pass Nov 15, 2023
c866efe
add test for controller
WojciechGrancow Nov 15, 2023
bf68c68
Merge branch 'BC-5522-impl-of-deletion-api' of https://github.com/hpi…
WojciechGrancow Nov 15, 2023
adb77c9
add test for deletionRequestResponse
WojciechGrancow Nov 15, 2023
3f046f5
remove not needed parameter from constructor
sszafGCA Nov 15, 2023
9a04a4a
add test for deletionRequestLogResponse
WojciechGrancow Nov 15, 2023
9ea749f
Merge branch 'BC-5522-impl-of-deletion-api' of https://github.com/hpi…
WojciechGrancow Nov 15, 2023
46c98b2
add test for executionParams and requestbodyParams
WojciechGrancow Nov 15, 2023
539c173
replace hard-coded Admin API server port value with the one taken fro…
bn-pass Nov 15, 2023
c1f1f35
change creation of API method location
sszafGCA Nov 15, 2023
9ad4206
change default json
sszafGCA Nov 15, 2023
f422a7b
fix import in server module
sszafGCA Nov 15, 2023
8c46093
Merge branch 'main' into BC-5522-impl-of-deletion-api
sszafGCA Nov 15, 2023
3b58d13
fixes soma issues
WojciechGrancow Nov 15, 2023
01bdd63
Merge branch 'BC-5522-impl-of-deletion-api' of https://github.com/hpi…
WojciechGrancow Nov 15, 2023
4fc4c70
fixes after review
WojciechGrancow Nov 15, 2023
aba6e1a
add admin api object
sszafGCA Nov 15, 2023
6764f95
default json chnages
sszafGCA Nov 15, 2023
15ed045
Revert "default json chnages"
sszafGCA Nov 15, 2023
2a15fe3
Revert "add admin api object"
sszafGCA Nov 15, 2023
2e80ece
Revert "fixes after review"
sszafGCA Nov 15, 2023
c57995f
Revert "fixes soma issues"
sszafGCA Nov 15, 2023
011b0f7
fixes after review
WojciechGrancow Nov 16, 2023
ccf0aef
small fixes
WojciechGrancow Nov 16, 2023
30ab3f4
Revert "small fixes"
sszafGCA Nov 16, 2023
6feb0a8
Revert "Revert "small fixes""
sszafGCA Nov 16, 2023
8b6243e
default ADMIN_API_KEY
WojciechGrancow Nov 16, 2023
2ffb06a
fix some imports
WojciechGrancow Nov 16, 2023
4bbf149
small change in x-api-key.strategy
WojciechGrancow Nov 16, 2023
a6f0b6a
Merge branch 'main' into BC-5522-impl-of-deletion-api
sszafGCA Nov 16, 2023
0188096
Update apps/server/src/modules/deletion/uc/builder/deletion-log-stati…
WojciechGrancow Nov 16, 2023
2e07dc3
change default.schema.json
sszafGCA Nov 16, 2023
3826319
new changes to default.schema.json
sszafGCA Nov 16, 2023
a0046bc
fix after review
WojciechGrancow Nov 16, 2023
8373501
add logger for error in deeltionRequestUC
WojciechGrancow Nov 17, 2023
2695b3d
fix problem with fileentity
WojciechGrancow Nov 17, 2023
92dba86
fix imports
WojciechGrancow Nov 17, 2023
3155b71
add logger to test in uc of deletionModule
WojciechGrancow Nov 17, 2023
2196f1e
change module config
sszafGCA Nov 17, 2023
c0ae9d7
hard-coded Admin API server port after the discussion with Paul
bn-pass Nov 17, 2023
b0c730b
fixes bug during deletion uders data from lessons
WojciechGrancow Nov 17, 2023
3a8f8d4
Merge branch 'main' into BC-5522-impl-of-deletion-api
WojciechGrancow Nov 17, 2023
684cd52
Merge branch 'BC-5522-impl-of-deletion-api' of https://github.com/hpi…
WojciechGrancow Nov 17, 2023
7a97f28
merge with main
WojciechGrancow Nov 21, 2023
9d40aea
fix pipeline
sszafGCA Nov 21, 2023
87cdfd2
fix pipeline #2
sszafGCA Nov 21, 2023
048875d
fix pipeline
sszafGCA Nov 21, 2023
8ccf2d6
fix lint
sszafGCA Nov 21, 2023
d2fc5dc
Merge branch 'main' into BC-5522-impl-of-deletion-api
sszafGCA Nov 23, 2023
2848964
Merge branch 'main' into BC-5522-impl-of-deletion-api
sszafGCA Nov 23, 2023
1e0bb2d
fix modules imports
sszafGCA Nov 23, 2023
994262f
fix providers in exports in deletion module
sszafGCA Nov 23, 2023
72e7f31
split deletion module and deletion-api.module
sszafGCA Nov 23, 2023
86b176d
move setup sessions to server config
sszafGCA Nov 23, 2023
e336196
try to fix test coverage
sszafGCA Nov 23, 2023
235a83c
Revert "try to fix test coverage"
sszafGCA Nov 23, 2023
e4b133d
Revert "move setup sessions to server config"
sszafGCA Nov 23, 2023
0cd52ca
remove api key from default.json
sszafGCA Nov 23, 2023
d86d1e5
changes to server module
sszafGCA Nov 24, 2023
41fcd0c
use timers in tests
sszafGCA Nov 24, 2023
a254858
revert last commit
sszafGCA Nov 24, 2023
4892112
Merge branch 'main' into BC-5522-impl-of-deletion-api
sszafGCA Nov 24, 2023
fe26bb0
add testXApiKeyClient
WojciechGrancow Nov 27, 2023
fce93f5
merge with main
WojciechGrancow Nov 27, 2023
bb48803
deployment impl
sszafGCA Nov 27, 2023
ee6c312
add newlines
sszafGCA Nov 27, 2023
7c229e2
add test
WojciechGrancow Nov 27, 2023
49f82f5
Merge branch 'main' into BC-5522-impl-of-deletion-api
WojciechGrancow Nov 27, 2023
2c37383
change character length
sszafGCA Nov 27, 2023
d98d11c
fix imports
WojciechGrancow Nov 27, 2023
fc41e5f
fix deployment in PR
WojciechGrancow Nov 27, 2023
eea9009
PR fixes part 1
sszafGCA Nov 28, 2023
ed55cdb
fix build and push
sszafGCA Nov 28, 2023
53905bb
fix prettier
sszafGCA Nov 28, 2023
2496a8b
default schema changes
sszafGCA Nov 28, 2023
787ab34
small fixes
WojciechGrancow Nov 28, 2023
c0567ff
Merge remote-tracking branch 'origin' into BC-5522-impl-of-deletion-api
WojciechGrancow Nov 28, 2023
1d53580
fix lint
sszafGCA Nov 28, 2023
084e46e
Merge branch 'main' into BC-5522-impl-of-deletion-api
sszafGCA Nov 28, 2023
228ab7a
add registration pins module
sszafGCA Nov 28, 2023
6590fc0
change sorting of code lines
CeEv Nov 29, 2023
9d98975
small fixes after review
WojciechGrancow Nov 29, 2023
02e37c8
add enabled in admiApiServer
WojciechGrancow Nov 29, 2023
df06ed7
add process.exit
WojciechGrancow Nov 29, 2023
b2fa12f
test revert enabled (testing purposes)
sszafGCA Nov 29, 2023
bc3faa1
Revert "test revert enabled (testing purposes)"
sszafGCA Nov 29, 2023
d589435
add default for testers
sszafGCA Nov 29, 2023
9d6e7c8
Revert "add default for testers"
sszafGCA Nov 29, 2023
a13fc2d
fix with elsson entity
WojciechGrancow Nov 29, 2023
760190d
Merge branch 'main' into BC-5522-impl-of-deletion-api
WojciechGrancow Nov 29, 2023
25b15c6
Merge branch 'BC-5522-impl-of-deletion-api' of https://github.com/hpi…
WojciechGrancow Nov 29, 2023
499d22b
fix lint
sszafGCA Nov 30, 2023
fcacb61
Merge branch 'main' into BC-5522-impl-of-deletion-api
sszafGCA Nov 30, 2023
7e75f2b
changes in main.yml
sszafGCA Nov 30, 2023
e482fd6
Merge branch 'main' into BC-5522-impl-of-deletion-api
sszafGCA Nov 30, 2023
1d41b33
fix enabled
WojciechGrancow Nov 30, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ spec:
- containerPort: 3030
name: api
protocol: TCP
- containerPort: 4030
name: api-admin
protocol: TCP
WojciechGrancow marked this conversation as resolved.
Show resolved Hide resolved
- containerPort: 9090
name: api-metrics
protocol: TCP
Expand Down
4 changes: 4 additions & 0 deletions ansible/roles/schulcloud-server-core/templates/svc.yml.j2
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ spec:
targetPort: 3030
protocol: TCP
name: api
- port: {{ PORT_ADMIN_SERVER }}
targetPort: 4030
protocol: TCP
name: api-admin
- port: {{ PORT_METRICS_SERVER }}
targetPort: 9090
protocol: TCP
Expand Down
28 changes: 28 additions & 0 deletions apps/server/src/apps/server.app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
import { Mail, MailService } from '@infra/mail';
import { LegacyLogger, Logger } from '@src/core/logger';
import { AccountService } from '@modules/account';
import { TeamService } from '@modules/teams/service/team.service';

Check warning on line 11 in apps/server/src/apps/server.app.ts

View workflow job for this annotation

GitHub Actions / nest_lint

'@modules/teams/service/team.service' import is restricted from being used by a pattern. Do not deep import from a module
import { AccountValidationService } from '@modules/account/services/account.validation.service';

Check warning on line 12 in apps/server/src/apps/server.app.ts

View workflow job for this annotation

GitHub Actions / nest_lint

'@modules/account/services/account.validation.service' import is restricted from being used by a pattern. Do not deep import from a module
import { AccountUc } from '@modules/account/uc/account.uc';

Check warning on line 13 in apps/server/src/apps/server.app.ts

View workflow job for this annotation

GitHub Actions / nest_lint

'@modules/account/uc/account.uc' import is restricted from being used by a pattern. Do not deep import from a module
import { CollaborativeStorageUc } from '@modules/collaborative-storage/uc/collaborative-storage.uc';

Check warning on line 14 in apps/server/src/apps/server.app.ts

View workflow job for this annotation

GitHub Actions / nest_lint

'@modules/collaborative-storage/uc/collaborative-storage.uc' import is restricted from being used by a pattern. Do not deep import from a module
import { GroupService } from '@modules/group';
import { RocketChatService } from '@modules/rocketchat';
import { ServerModule } from '@modules/server';
Expand All @@ -21,6 +21,8 @@
// register source-map-support for debugging
import { install as sourceMapInstall } from 'source-map-support';
import { FeathersRosterService } from '@modules/pseudonym';
import { Configuration } from '@hpi-schul-cloud/commons/lib';
import { AdminApiServerModule } from '@src/modules/server/admin-api.server.module';
import legacyAppPromise = require('../../../../src/app');

import { AppStartLoggable } from './helpers/app-start-loggable';
Expand All @@ -29,6 +31,28 @@
createAndStartPrometheusMetricsAppIfEnabled,
} from './helpers/prometheus-metrics';

const createAndStartAdminApiServer = async (logger: Logger) => {
const nestAdminServerExpress = express();
WojciechGrancow marked this conversation as resolved.
Show resolved Hide resolved
nestAdminServerExpress.disable('x-powered-by');
const nestAdminServerExpressAdapter = new ExpressAdapter(nestAdminServerExpress);
const nestAdminServerApp = await NestFactory.create(AdminApiServerModule, nestAdminServerExpressAdapter);

nestAdminServerApp.setGlobalPrefix('/admin/api/v1');
await nestAdminServerApp.init();

const adminApiServerPort = Configuration.get('ADMIN_API__PORT') as number;

nestAdminServerExpress.listen(adminApiServerPort, () => {
logger.info(
new AppStartLoggable({
appName: 'Admin API server app',
port: adminApiServerPort,
mountsDescription: `/admin/api/v1 --> Admin API Server`,
})
);
});
};

async function bootstrap() {
sourceMapInstall();

Expand Down Expand Up @@ -127,6 +151,10 @@
createAndStartPrometheusMetricsAppIfEnabled(logger);
});

if (Configuration.get('ADMIN_API__ENABLED') === true) {
await createAndStartAdminApiServer(logger);
}

console.log('#################################');
console.log(`### Start Server ###`);
console.log(`### Port: ${port} ###`);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { JwtStrategy } from './strategy/jwt.strategy';
import { LdapStrategy } from './strategy/ldap.strategy';
import { LocalStrategy } from './strategy/local.strategy';
import { Oauth2Strategy } from './strategy/oauth2.strategy';
import { XApiKeyStrategy } from './strategy/x-api-key.strategy';

// values copied from Algorithm definition. Type does not exist at runtime and can't be checked anymore otherwise
const algorithms = [
Expand Down Expand Up @@ -76,6 +77,7 @@ const jwtModuleOptions: JwtModuleOptions = {
LdapService,
LdapStrategy,
Oauth2Strategy,
XApiKeyStrategy,
],
exports: [AuthenticationService],
})
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export interface IXApiKeyConfig {
ADMIN_API__ALLOWED_API_KEYS: string[];
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { UnauthorizedException } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { ConfigService } from '@nestjs/config';
import { createMock } from '@golevelup/ts-jest';
import { XApiKeyStrategy } from './x-api-key.strategy';
import { IXApiKeyConfig } from '../config/x-api-key.config';

describe('XApiKeyStrategy', () => {
let module: TestingModule;
let strategy: XApiKeyStrategy;
let configService: ConfigService<IXApiKeyConfig, true>;

beforeAll(async () => {
module = await Test.createTestingModule({
imports: [],
providers: [
XApiKeyStrategy,
{
provide: ConfigService,
useValue: createMock<ConfigService<IXApiKeyConfig, true>>({ get: () => ['1ab2c3d4e5f61ab2c3d4e5f6'] }),
},
],
}).compile();

strategy = module.get(XApiKeyStrategy);
configService = module.get(ConfigService<IXApiKeyConfig, true>);
});

afterAll(async () => {
await module.close();
});

beforeEach(() => {
jest.resetAllMocks();
});

describe('validate', () => {
const setup = () => {
WojciechGrancow marked this conversation as resolved.
Show resolved Hide resolved
const CORRECT_API_KEY = '1ab2c3d4e5f61ab2c3d4e5f6';
const INVALID_API_KEY = '1ab2c3d4e5f61ab2c3d4e5f6778173';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const done = jest.fn((error: Error | null, data: boolean | null) => {});

return { CORRECT_API_KEY, INVALID_API_KEY, done };
};
describe('when a valid api key is provided', () => {
it('should do nothing', () => {
const { CORRECT_API_KEY, done } = setup();
strategy.validate(CORRECT_API_KEY, done);
expect(done).toBeCalledWith(null, true);
});
});

describe('when a invalid api key is provided', () => {
it('should throw error', () => {
const { INVALID_API_KEY, done } = setup();
strategy.validate(INVALID_API_KEY, done);
expect(done).toBeCalledWith(new UnauthorizedException(), null);
});
});
});

describe('constructor', () => {
it('should create strategy', () => {
const ApiKeyStrategy = new XApiKeyStrategy(configService);
expect(ApiKeyStrategy).toBeDefined();
expect(ApiKeyStrategy).toBeInstanceOf(XApiKeyStrategy);
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ConfigService } from '@nestjs/config';
import Strategy from 'passport-headerapikey';
import { IXApiKeyConfig } from '../config/x-api-key.config';

@Injectable()
export class XApiKeyStrategy extends PassportStrategy(Strategy, 'api-key') {
private readonly allowedApiKeys: string[];

constructor(private readonly configService: ConfigService<IXApiKeyConfig, true>) {
super({ header: 'X-API-KEY' }, false);
this.allowedApiKeys = this.configService.get<string[]>('ADMIN_API__ALLOWED_API_KEYS');
}

public validate = (apiKey: string, done: (error: Error | null, data: boolean | null) => void) => {
CeEv marked this conversation as resolved.
Show resolved Hide resolved
if (this.allowedApiKeys.includes(apiKey)) {
done(null, true);
}
done(new UnauthorizedException(), null);
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { ExecutionContext, INestApplication } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { ApiValidationError } from '@shared/common';
import { Request } from 'express';
import request from 'supertest';
import { AuthGuard } from '@nestjs/passport';
import { AdminApiServerTestModule } from '../../../server/admin-api.server.module';
WojciechGrancow marked this conversation as resolved.
Show resolved Hide resolved
import { DeletionExecutionParams } from '../dto';

const baseRouteName = '/deletionExecutions';

class API {
app: INestApplication;

constructor(app: INestApplication) {
this.app = app;
}

async post(query?: DeletionExecutionParams) {
const response = await request(this.app.getHttpServer())
.post(`${baseRouteName}`)
.set('Accept', 'application/json')
.query(query || {});

return {
error: response.body as ApiValidationError,
status: response.status,
};
}
}

describe(`deletionExecution (api)`, () => {
let app: INestApplication;
let api: API;
const API_KEY = '1ab2c3d4e5f61ab2c3d4e5f6';

beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [AdminApiServerTestModule],
})
.overrideGuard(AuthGuard('api-key'))
.useValue({
canActivate(context: ExecutionContext) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not in this ticket/PR, but as follow up ticket. We use the TestApiClient for setup authorised request. Please improve this helper and use it for create real requests in each api.spec file that use a x-api-key.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So taking into account all the comments regarding TestAPIClient/TestXapiKeyClient and overriding authguards I see two alternative sollution

  1. Accept current code and make diffrent ticket for helper or TestXapiClient and make it there
  2. Make all changes in this PR

@CeEv what should we choose?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use option 1 but link this PR, or note my different hints about the helper.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

const req: Request = context.switchToHttp().getRequest();
req.headers['X-API-KEY'] = API_KEY;
return true;
},
})
.compile();

app = module.createNestApplication();
await app.init();
api = new API(app);
});

afterAll(async () => {
await app.close();
});

WojciechGrancow marked this conversation as resolved.
Show resolved Hide resolved
describe('when execute deletionRequests with default limit', () => {
it('should return status 204', async () => {
const response = await api.post();

expect(response.status).toEqual(204);
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import { ExecutionContext, INestApplication } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { ApiValidationError } from '@shared/common';
import { Request } from 'express';
import request from 'supertest';
import { AuthGuard } from '@nestjs/passport';
import { EntityManager } from '@mikro-orm/mongodb';
import { AdminApiServerTestModule } from '../../../server/admin-api.server.module';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@modules/..

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

import { DeletionRequestBodyProps, DeletionRequestResponse } from '../dto';
import { DeletionDomainModel } from '../../domain/types';
import { DeletionRequestEntity } from '../../entity';

const baseRouteName = '/deletionRequests';

class API {
app: INestApplication;

constructor(app: INestApplication) {
this.app = app;
}

async post(requestBody: object) {
const response = await request(this.app.getHttpServer())
.post(`${baseRouteName}`)
.set('Accept', 'application/json')
.send(requestBody);

return {
result: response.body as DeletionRequestResponse,
error: response.body as ApiValidationError,
status: response.status,
};
}
}

describe(`deletionRequest create (api)`, () => {
let app: INestApplication;
let em: EntityManager;
let api: API;
const API_KEY = '1ab2c3d4e5f61ab2c3d4e5f6';

beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [AdminApiServerTestModule],
})
.overrideGuard(AuthGuard('api-key'))
.useValue({
canActivate(context: ExecutionContext) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the legacy hack to do api test. Please check examples with { TestApiClient } from '@shared/testing';

Copy link
Contributor

@WojciechGrancow WojciechGrancow Nov 24, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Check my comment to TestApiClient if und which api key exists in a request, must be handled by the TestXApiKeyClient the override should be removed.

const req: Request = context.switchToHttp().getRequest();
req.headers['X-API-KEY'] = API_KEY;
return true;
},
})
.compile();

app = module.createNestApplication();
await app.init();
em = module.get(EntityManager);
api = new API(app);
});

afterAll(async () => {
await app.close();
});

const setup = () => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please move it into the when senario description.
If you change the TestApiClient/TestXApiKeyClient than you must also add more when senarios for example api key is missed, or is invalid. It should run into different error results.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

waiting for answer on comment #4533 (comment)

const deletionRequestToCreate: DeletionRequestBodyProps = {
targetRef: {
domain: DeletionDomainModel.USER,
id: '653e4833cc39e5907a1e18d2',
},
};

const deletionRequestToImmediateRemoval: DeletionRequestBodyProps = {
targetRef: {
domain: DeletionDomainModel.USER,
id: '653e4833cc39e5907a1e18d2',
},
deleteInMinutes: 0,
};

return { deletionRequestToCreate, deletionRequestToImmediateRemoval };
};

WojciechGrancow marked this conversation as resolved.
Show resolved Hide resolved
describe('when create deletionRequest', () => {
it('should return status 202', async () => {
const { deletionRequestToCreate } = setup();

const response = await api.post(deletionRequestToCreate);

expect(response.status).toEqual(202);
});

it('should return the created deletionRequest', async () => {
const { deletionRequestToCreate } = setup();

const { result } = await api.post(deletionRequestToCreate);

expect(result.requestId).toBeDefined();
});

it('should create deletionRequest with default deletion time (add 43200 minutes to current time) ', async () => {
const { deletionRequestToCreate } = setup();

const { result } = await api.post(deletionRequestToCreate);

const createdDeletionRequestId = result.requestId;

const createdItem = await em.findOneOrFail(DeletionRequestEntity, createdDeletionRequestId);

const deletionPlannedAt = createdItem.createdAt;
deletionPlannedAt.setMinutes(deletionPlannedAt.getMinutes() + 43200);

expect(createdItem.deleteAfter).toEqual(deletionPlannedAt);
});

it('should create deletionRequest with deletion time (0 minutes to current time) ', async () => {
const { deletionRequestToImmediateRemoval } = setup();

const { result } = await api.post(deletionRequestToImmediateRemoval);

const createdDeletionRequestId = result.requestId;

const createdItem = await em.findOneOrFail(DeletionRequestEntity, createdDeletionRequestId);

expect(createdItem.createdAt).toEqual(createdItem.deleteAfter);
});
});
});
Loading
Loading