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

chore(audit-logs): migrate audit logs to v5 #20251

Merged
merged 17 commits into from
May 27, 2024
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
"test:front:update:ce": "yarn test:front:ce -u",
"test:front:watch": "cross-env IS_EE=true run test:front --watch",
"test:front:watch:ce": "cross-env IS_EE=false run test:front --watch",
"test:generate-app": "yarn build:ts && node test/scripts/generate-test-app.js",
"test:generate-app": "yarn build:ts && node tests/scripts/generate-test-app.js",
"test:generate-app:no-build": "node tests/scripts/generate-test-app.js",
"test:ts": "yarn test:ts:packages && yarn test:ts:front && yarn test:ts:back",
"test:ts:back": "nx run-many --target=test:ts:back --nx-ignore-cycles",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
export const auditLog = {
schema: {
kind: 'collectionType',
collectionName: 'strapi_audit_logs',
info: {
singularName: 'audit-log',
pluralName: 'audit-logs',
displayName: 'Audit Log',
},
options: {
timestamps: false,
},
pluginOptions: {
'content-manager': {
visible: false,
},
'content-type-builder': {
visible: false,
},
},
attributes: {
action: {
type: 'string',
required: true,
},
date: {
type: 'datetime',
required: true,
},
user: {
type: 'relation',
relation: 'oneToOne',
target: 'admin::user',
},
payload: {
type: 'json',
},
},
},
};
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { enableFeatureMiddleware } from './utils';
import { enableFeatureMiddleware } from '../../routes/utils';

export default {
type: 'admin',
routes: [
{
method: 'GET',
path: '/audit-logs',
handler: 'auditLogs.findMany',
handler: 'audit-logs.findMany',
config: {
middlewares: [enableFeatureMiddleware('audit-logs')],
policies: [
Expand All @@ -23,7 +23,7 @@ export default {
{
method: 'GET',
path: '/audit-logs/:id',
handler: 'auditLogs.findOne',
handler: 'audit-logs.findOne',
config: {
middlewares: [enableFeatureMiddleware('audit-logs')],
policies: [
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { createAuditLogsLifecycle } from '../lifecycles';
import createEventHub from '../../../../../../../core/dist/services/event-hub';
import { scheduleJob } from 'node-schedule';

import '@strapi/types';

jest.mock('node-schedule', () => ({
scheduleJob: jest.fn(),
}));

describe('Audit logs service', () => {
const mockSubscribe = jest.fn();

const strapi = {
requestContext: {
get() {
return {
state: {
user: {
id: 1,
},
route: {
info: {
type: 'admin',
},
},
},
};
},
},
ee: {
features: {
isEnabled: jest.fn().mockReturnValue(false),
get: jest.fn(),
},
},
add: jest.fn(),
get: jest.fn(() => ({
deleteExpiredEvents: jest.fn(),
})),
config: {
get(key: any) {
switch (key) {
case 'admin.auditLogs.enabled':
return true;
case 'admin.auditLogs.retentionDays':
return undefined;
default:
return null;
}
},
},
eventHub: {
...createEventHub(),
subscribe: mockSubscribe,
},
hook: () => ({
register: jest.fn(),
}),
} as any;

afterEach(() => {
jest.resetModules();
});

afterAll(() => {
jest.useRealTimers();
});

it('should not subscribe to events when the license does not allow it', async () => {
// Should not subscribe to events at first
const lifecycle = createAuditLogsLifecycle(strapi);
await lifecycle.register();
expect(mockSubscribe).not.toHaveBeenCalled();

// Should subscribe to events when license gets enabled
jest.mocked(strapi.ee.features.isEnabled).mockImplementationOnce(() => true);
await strapi.eventHub.emit('ee.enable');
expect(mockSubscribe).toHaveBeenCalled();

// Should unsubscribe to events when license gets disabled
mockSubscribe.mockClear();
jest.mocked(strapi.ee.features.isEnabled).mockImplementationOnce(() => false);
await strapi.eventHub.emit('ee.disable');
expect(mockSubscribe).not.toHaveBeenCalled();

// Should recreate the service when license updates
const destroySpy = jest.spyOn(lifecycle, 'destroy');
const registerSpy = jest.spyOn(lifecycle, 'register');
await strapi.eventHub.emit('ee.update');
expect(destroySpy).toHaveBeenCalled();
expect(registerSpy).toHaveBeenCalled();
});

it('should create a cron job that executed one time a day', async () => {
// @ts-expect-error scheduleJob
const mockScheduleJob = scheduleJob.mockImplementationOnce(
jest.fn((rule, callback) => callback())
);

const lifecycle = createAuditLogsLifecycle(strapi);
await lifecycle.register();

expect(mockScheduleJob).toHaveBeenCalledTimes(1);
expect(mockScheduleJob).toHaveBeenCalledWith('0 0 * * *', expect.any(Function));
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import type { Core } from '@strapi/types';

interface Event {
action: string;
date: Date;
userId: string | number;
payload: Record<string, unknown>;
}

interface Log extends Omit<Event, 'userId'> {
user: string | number;
}

const getSanitizedUser = (user: any) => {
let displayName = user.email;

if (user.username) {
displayName = user.username;
} else if (user.firstname && user.lastname) {
displayName = `${user.firstname} ${user.lastname}`;
}

return {
id: user.id,
email: user.email,
displayName,
};
};

/**
* @description
* Manages audit logs interaction with the database. Accessible via strapi.get('audit-logs')
*/
const createAuditLogsService = (strapi: Core.Strapi) => {
return {
async saveEvent(event: Event) {
const { userId, ...rest } = event;

const auditLog: Log = { ...rest, user: userId };

// Save to database
await strapi.db?.query('admin::audit-log').create({ data: auditLog });

return this;
},

async findMany(query: unknown) {
const { results, pagination } = await strapi.db?.query('admin::audit-log').findPage({
populate: ['user'],
select: ['action', 'date', 'payload'],
...strapi.get('query-params').transform('admin::audit-log', query),
});

const sanitizedResults = results.map((result: any) => {
const { user, ...rest } = result;
return {
...rest,
user: user ? getSanitizedUser(user) : null,
};
});

return {
results: sanitizedResults,
pagination,
};
},

async findOne(id: unknown) {
const result: any = await strapi.db?.query('admin::audit-log').findOne({
where: { id },
populate: ['user'],
select: ['action', 'date', 'payload'],
});

if (!result) {
return null;
}

const { user, ...rest } = result;
return {
...rest,
user: user ? getSanitizedUser(user) : null,
};
},

deleteExpiredEvents(expirationDate: Date) {
return strapi.db?.query('admin::audit-log').deleteMany({
where: {
date: {
$lt: expirationDate.toISOString(),
},
},
});
},
};
};

export { createAuditLogsService };
Loading
Loading