Files
n8n/packages/cli/test/integration/execution-limits.controller.test.ts

259 lines
8.0 KiB
TypeScript

import { ExecutionLimitsService } from '@n8n/backend-module-execution-limits';
import { testDb } from '@n8n/backend-test-utils';
import { LICENSE_FEATURES } from '@n8n/constants';
import type { User } from '@n8n/db';
import { Container } from '@n8n/di';
import { DataSource } from '@n8n/typeorm';
import { cleanupRolesAndScopes, createCustomRoleWithScopeSlugs } from '@test-integration/db/roles';
import { createAdmin, createMember, createOwner, createUser } from '@test-integration/db/users';
import * as utils from '@test-integration/utils';
const testServer = utils.setupTestServer({
endpointGroups: ['execution-limits'],
modules: ['execution-limits'],
enabledFeatures: [LICENSE_FEATURES.EXECUTION_LIMITS],
});
const INSTANCE_PATH = '/execution-limits/instance';
const USAGE_PATH = '/execution-limits/instance/usage';
const instanceUsageTable = () =>
Container.get(DataSource).getRepository<{
day: string;
entityType: string;
startedCount: number;
blockedCount: number;
}>('ExecutionLimitInstanceUsage');
/** Counts runs on the current UTC day, which is in the current period of each period unit. */
const countToday = async (startedCount: number, blockedCount = 0) => {
await instanceUsageTable().insert({
day: new Date().toISOString().slice(0, 10),
entityType: 'workflow',
startedCount,
blockedCount,
});
};
let owner: User;
let admin: User;
let member: User;
let readOnlyUser: User;
beforeAll(async () => {
owner = await createOwner();
admin = await createAdmin();
member = await createMember();
const readOnlyRole = await createCustomRoleWithScopeSlugs(['executionLimit:read'], {
roleType: 'global',
});
readOnlyUser = await createUser({ role: readOnlyRole });
});
afterEach(async () => {
await testDb.truncate(['Settings', 'ExecutionLimitAudit']);
await instanceUsageTable().clear();
});
afterAll(async () => {
await testDb.truncate(['User']);
await cleanupRolesAndScopes();
});
describe('Internal API /rest/execution-limits/instance', () => {
test('reads default settings on a fresh instance', async () => {
const response = await testServer.authAgentFor(owner).get(INSTANCE_PATH);
expect(response.statusCode).toBe(200);
expect(response.body.data).toEqual({
periodUnit: 'month',
maxExecutions: null,
defaultProjectMaxExecutions: null,
});
});
test('allows an admin to read and write', async () => {
const write = await testServer.authAgentFor(admin).put(INSTANCE_PATH).send({
periodUnit: 'week',
maxExecutions: 100_000,
defaultProjectMaxExecutions: 10_000,
});
expect(write.statusCode).toBe(200);
expect(write.body.data).toEqual({
periodUnit: 'week',
maxExecutions: 100_000,
defaultProjectMaxExecutions: 10_000,
});
const read = await testServer.authAgentFor(admin).get(INSTANCE_PATH);
expect(read.statusCode).toBe(200);
expect(read.body.data).toEqual(write.body.data);
// A GET body round-trips as a valid PUT body.
const roundTrip = await testServer.authAgentFor(admin).put(INSTANCE_PATH).send(read.body.data);
expect(roundTrip.statusCode).toBe(200);
expect(roundTrip.body.data).toEqual(read.body.data);
});
test.each([
['missing periodUnit', { maxExecutions: 100, defaultProjectMaxExecutions: null }],
['missing maxExecutions', { periodUnit: 'month', defaultProjectMaxExecutions: null }],
['missing defaultProjectMaxExecutions', { periodUnit: 'month', maxExecutions: 100 }],
[
'extra unknown field',
{
periodUnit: 'month',
maxExecutions: 100,
defaultProjectMaxExecutions: null,
unknownField: true,
},
],
])('rejects %s with 400', async (_, body) => {
const response = await testServer.authAgentFor(owner).put(INSTANCE_PATH).send(body);
expect(response.statusCode).toBe(400);
});
test('rejects defaultProjectMaxExecutions above maxExecutions with 400 and changes nothing', async () => {
const response = await testServer.authAgentFor(owner).put(INSTANCE_PATH).send({
periodUnit: 'month',
maxExecutions: 100,
defaultProjectMaxExecutions: 101,
});
expect(response.statusCode).toBe(400);
const current = await testServer.authAgentFor(owner).get(INSTANCE_PATH);
expect(current.body.data).toEqual({
periodUnit: 'month',
maxExecutions: null,
defaultProjectMaxExecutions: null,
});
});
test('rejects unauthenticated requests with 401', async () => {
expect((await testServer.authlessAgent.get(INSTANCE_PATH)).statusCode).toBe(401);
expect(
(
await testServer.authlessAgent.put(INSTANCE_PATH).send({
periodUnit: 'month',
maxExecutions: null,
defaultProjectMaxExecutions: null,
})
).statusCode,
).toBe(401);
});
test('rejects callers missing the required scope with 403', async () => {
expect((await testServer.authAgentFor(member).get(INSTANCE_PATH)).statusCode).toBe(403);
expect(
(
await testServer.authAgentFor(member).put(INSTANCE_PATH).send({
periodUnit: 'month',
maxExecutions: 100,
defaultProjectMaxExecutions: null,
})
).statusCode,
).toBe(403);
// A caller with only executionLimit:read can GET but not PUT.
expect((await testServer.authAgentFor(readOnlyUser).get(INSTANCE_PATH)).statusCode).toBe(200);
expect(
(
await testServer.authAgentFor(readOnlyUser).put(INSTANCE_PATH).send({
periodUnit: 'month',
maxExecutions: 100,
defaultProjectMaxExecutions: null,
})
).statusCode,
).toBe(403);
});
test('rejects requests with 403 when the license feature is disabled', async () => {
testServer.license.disable(LICENSE_FEATURES.EXECUTION_LIMITS);
expect((await testServer.authAgentFor(owner).get(INSTANCE_PATH)).statusCode).toBe(403);
expect(
(
await testServer.authAgentFor(owner).put(INSTANCE_PATH).send({
periodUnit: 'month',
maxExecutions: 100,
defaultProjectMaxExecutions: null,
})
).statusCode,
).toBe(403);
});
});
describe('Internal API /rest/execution-limits/instance/usage', () => {
// A frozen clock keeps the inserted day and the queried period in the same period.
beforeEach(() => {
vi.useFakeTimers({ toFake: ['Date'] });
});
afterEach(() => {
vi.useRealTimers();
});
test('reads the usage when the instance has no limit', async () => {
await countToday(7);
const response = await testServer.authAgentFor(owner).get(USAGE_PATH);
expect(response.statusCode).toBe(200);
expect(response.body.data).toEqual({
periodUnit: 'month',
periodStart: expect.stringMatching(/^\d{4}-\d{2}-\d{2}$/),
resetsAt: expect.stringMatching(/^\d{4}-\d{2}-\d{2}T00:00:00\.000Z$/),
maxExecutions: null,
workflowExecutions: 7,
remaining: null,
});
});
test('reads the usage against the instance limit', async () => {
await Container.get(ExecutionLimitsService).updateSettings(
{ instanceMaxExecutions: 100 },
owner.id,
);
await countToday(45, 5);
const response = await testServer.authAgentFor(admin).get(USAGE_PATH);
expect(response.statusCode).toBe(200);
expect(response.body.data).toMatchObject({
maxExecutions: 100,
workflowExecutions: 40,
remaining: 60,
});
});
test('uses the period unit of the instance settings', async () => {
await Container.get(ExecutionLimitsService).updateSettings({ periodUnit: 'day' }, owner.id);
const today = new Date().toISOString().slice(0, 10);
const response = await testServer.authAgentFor(owner).get(USAGE_PATH);
expect(response.statusCode).toBe(200);
expect(response.body.data).toMatchObject({ periodUnit: 'day', periodStart: today });
});
test('rejects unauthenticated requests with 401', async () => {
expect((await testServer.authlessAgent.get(USAGE_PATH)).statusCode).toBe(401);
});
test('allows callers with the read scope and rejects others with 403', async () => {
expect((await testServer.authAgentFor(member).get(USAGE_PATH)).statusCode).toBe(403);
expect((await testServer.authAgentFor(readOnlyUser).get(USAGE_PATH)).statusCode).toBe(200);
});
test('rejects requests with 403 when the license feature is disabled', async () => {
testServer.license.disable(LICENSE_FEATURES.EXECUTION_LIMITS);
expect((await testServer.authAgentFor(owner).get(USAGE_PATH)).statusCode).toBe(403);
});
});