feat: 時限ロール (#10145)
* feat: 時限ロール * クライアントから期限を確認できるように * リファクタとか * fix test * fix test * fix test * clean up
This commit is contained in:
parent
7c3a390763
commit
1c5291f818
16 changed files with 296 additions and 391 deletions
|
@ -3,16 +3,18 @@ process.env.NODE_ENV = 'test';
|
|||
import { jest } from '@jest/globals';
|
||||
import { ModuleMocker } from 'jest-mock';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { DataSource } from 'typeorm';
|
||||
import * as lolex from '@sinonjs/fake-timers';
|
||||
import rndstr from 'rndstr';
|
||||
import { GlobalModule } from '@/GlobalModule.js';
|
||||
import { RoleService } from '@/core/RoleService.js';
|
||||
import type { Role, RolesRepository, RoleAssignmentsRepository, UsersRepository, User } from '@/models/index.js';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import { CoreModule } from '@/core/CoreModule.js';
|
||||
import { MetaService } from '@/core/MetaService.js';
|
||||
import { genAid } from '@/misc/id/aid.js';
|
||||
import { UserCacheService } from '@/core/UserCacheService.js';
|
||||
import { IdService } from '@/core/IdService.js';
|
||||
import { GlobalEventService } from '@/core/GlobalEventService.js';
|
||||
import { sleep } from '../utils.js';
|
||||
import type { TestingModule } from '@nestjs/testing';
|
||||
import type { MockFunctionMetadata } from 'jest-mock';
|
||||
|
||||
|
@ -25,6 +27,7 @@ describe('RoleService', () => {
|
|||
let rolesRepository: RolesRepository;
|
||||
let roleAssignmentsRepository: RoleAssignmentsRepository;
|
||||
let metaService: jest.Mocked<MetaService>;
|
||||
let clock: lolex.InstalledClock;
|
||||
|
||||
function createUser(data: Partial<User> = {}) {
|
||||
const un = rndstr('a-z0-9', 16);
|
||||
|
@ -50,16 +53,12 @@ describe('RoleService', () => {
|
|||
.then(x => rolesRepository.findOneByOrFail(x.identifiers[0]));
|
||||
}
|
||||
|
||||
async function assign(roleId: Role['id'], userId: User['id']) {
|
||||
await roleAssignmentsRepository.insert({
|
||||
id: genAid(new Date()),
|
||||
createdAt: new Date(),
|
||||
roleId,
|
||||
userId,
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
clock = lolex.install({
|
||||
now: new Date(),
|
||||
shouldClearNativeTimers: true,
|
||||
});
|
||||
|
||||
app = await Test.createTestingModule({
|
||||
imports: [
|
||||
GlobalModule,
|
||||
|
@ -67,6 +66,8 @@ describe('RoleService', () => {
|
|||
providers: [
|
||||
RoleService,
|
||||
UserCacheService,
|
||||
IdService,
|
||||
GlobalEventService,
|
||||
],
|
||||
})
|
||||
.useMocker((token) => {
|
||||
|
@ -92,12 +93,15 @@ describe('RoleService', () => {
|
|||
});
|
||||
|
||||
afterEach(async () => {
|
||||
clock.uninstall();
|
||||
|
||||
await Promise.all([
|
||||
app.get(DI.metasRepository).delete({}),
|
||||
usersRepository.delete({}),
|
||||
rolesRepository.delete({}),
|
||||
roleAssignmentsRepository.delete({}),
|
||||
]);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
|
@ -115,7 +119,7 @@ describe('RoleService', () => {
|
|||
expect(result.canManageCustomEmojis).toBe(false);
|
||||
});
|
||||
|
||||
test('instance default policies 2', async () => {
|
||||
test('instance default policies 2', async () => {
|
||||
const user = await createUser();
|
||||
metaService.fetch.mockResolvedValue({
|
||||
policies: {
|
||||
|
@ -128,7 +132,7 @@ describe('RoleService', () => {
|
|||
expect(result.canManageCustomEmojis).toBe(true);
|
||||
});
|
||||
|
||||
test('with role', async () => {
|
||||
test('with role', async () => {
|
||||
const user = await createUser();
|
||||
const role = await createRole({
|
||||
name: 'a',
|
||||
|
@ -140,7 +144,7 @@ describe('RoleService', () => {
|
|||
},
|
||||
},
|
||||
});
|
||||
await assign(role.id, user.id);
|
||||
await roleService.assign(user.id, role.id);
|
||||
metaService.fetch.mockResolvedValue({
|
||||
policies: {
|
||||
canManageCustomEmojis: false,
|
||||
|
@ -152,7 +156,7 @@ describe('RoleService', () => {
|
|||
expect(result.canManageCustomEmojis).toBe(true);
|
||||
});
|
||||
|
||||
test('priority', async () => {
|
||||
test('priority', async () => {
|
||||
const user = await createUser();
|
||||
const role1 = await createRole({
|
||||
name: 'role1',
|
||||
|
@ -174,8 +178,8 @@ describe('RoleService', () => {
|
|||
},
|
||||
},
|
||||
});
|
||||
await assign(role1.id, user.id);
|
||||
await assign(role2.id, user.id);
|
||||
await roleService.assign(user.id, role1.id);
|
||||
await roleService.assign(user.id, role2.id);
|
||||
metaService.fetch.mockResolvedValue({
|
||||
policies: {
|
||||
driveCapacityMb: 50,
|
||||
|
@ -187,7 +191,7 @@ describe('RoleService', () => {
|
|||
expect(result.driveCapacityMb).toBe(100);
|
||||
});
|
||||
|
||||
test('conditional role', async () => {
|
||||
test('conditional role', async () => {
|
||||
const user1 = await createUser({
|
||||
createdAt: new Date(Date.now() - (1000 * 60 * 60 * 24 * 365)),
|
||||
});
|
||||
|
@ -228,5 +232,42 @@ describe('RoleService', () => {
|
|||
expect(user1Policies.canManageCustomEmojis).toBe(false);
|
||||
expect(user2Policies.canManageCustomEmojis).toBe(true);
|
||||
});
|
||||
|
||||
test('expired role', async () => {
|
||||
const user = await createUser();
|
||||
const role = await createRole({
|
||||
name: 'a',
|
||||
policies: {
|
||||
canManageCustomEmojis: {
|
||||
useDefault: false,
|
||||
priority: 0,
|
||||
value: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
await roleService.assign(user.id, role.id, new Date(Date.now() + (1000 * 60 * 60 * 24)));
|
||||
metaService.fetch.mockResolvedValue({
|
||||
policies: {
|
||||
canManageCustomEmojis: false,
|
||||
},
|
||||
} as any);
|
||||
|
||||
const result = await roleService.getUserPolicies(user.id);
|
||||
expect(result.canManageCustomEmojis).toBe(true);
|
||||
|
||||
clock.tick('25:00:00');
|
||||
|
||||
const resultAfter25h = await roleService.getUserPolicies(user.id);
|
||||
expect(resultAfter25h.canManageCustomEmojis).toBe(false);
|
||||
|
||||
await roleService.assign(user.id, role.id);
|
||||
|
||||
// ストリーミング経由で反映されるまでちょっと待つ
|
||||
clock.uninstall();
|
||||
await sleep(100);
|
||||
|
||||
const resultAfter25hAgain = await roleService.getUserPolicies(user.id);
|
||||
expect(resultAfter25hAgain.canManageCustomEmojis).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
@ -1,320 +1,3 @@
|
|||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { dirname } from 'node:path';
|
||||
import * as childProcess from 'child_process';
|
||||
import * as http from 'node:http';
|
||||
import { SIGKILL } from 'constants';
|
||||
import WebSocket from 'ws';
|
||||
import fetch from 'node-fetch';
|
||||
import FormData from 'form-data';
|
||||
import { DataSource } from 'typeorm';
|
||||
import got, { RequestError } from 'got';
|
||||
import loadConfig from '../src/config/load.js';
|
||||
import { entities } from '@/postgres.js';
|
||||
import type * as misskey from 'misskey-js';
|
||||
|
||||
const _filename = fileURLToPath(import.meta.url);
|
||||
const _dirname = dirname(_filename);
|
||||
|
||||
const config = loadConfig();
|
||||
export const port = config.port;
|
||||
|
||||
export const api = async (endpoint: string, params: any, me?: any) => {
|
||||
endpoint = endpoint.replace(/^\//, '');
|
||||
|
||||
const auth = me ? {
|
||||
i: me.token,
|
||||
} : {};
|
||||
|
||||
try {
|
||||
const res = await got<string>(`http://localhost:${port}/api/${endpoint}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(Object.assign(auth, params)),
|
||||
retry: {
|
||||
limit: 0,
|
||||
},
|
||||
});
|
||||
|
||||
const status = res.statusCode;
|
||||
const body = res.statusCode !== 204 ? await JSON.parse(res.body) : null;
|
||||
|
||||
return {
|
||||
status,
|
||||
body,
|
||||
};
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof RequestError && err.response) {
|
||||
const status = err.response.statusCode;
|
||||
const body = await JSON.parse(err.response.body as string);
|
||||
|
||||
return {
|
||||
status,
|
||||
body,
|
||||
};
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const request = async (path: string, params: any, me?: any): Promise<{ body: any, status: number }> => {
|
||||
const auth = me ? {
|
||||
i: me.token,
|
||||
} : {};
|
||||
|
||||
const res = await fetch(`http://localhost:${port}/${path}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(Object.assign(auth, params)),
|
||||
});
|
||||
|
||||
const status = res.status;
|
||||
const body = res.status === 200 ? await res.json().catch() : null;
|
||||
|
||||
return {
|
||||
body, status,
|
||||
};
|
||||
};
|
||||
|
||||
export const signup = async (params?: any): Promise<any> => {
|
||||
const q = Object.assign({
|
||||
username: 'test',
|
||||
password: 'test',
|
||||
}, params);
|
||||
|
||||
const res = await api('signup', q);
|
||||
|
||||
return res.body;
|
||||
};
|
||||
|
||||
export const post = async (user: any, params?: misskey.Endpoints['notes/create']['req']): Promise<misskey.entities.Note> => {
|
||||
const q = Object.assign({
|
||||
text: 'test',
|
||||
}, params);
|
||||
|
||||
const res = await api('notes/create', q, user);
|
||||
|
||||
return res.body ? res.body.createdNote : null;
|
||||
};
|
||||
|
||||
export const react = async (user: any, note: any, reaction: string): Promise<any> => {
|
||||
await api('notes/reactions/create', {
|
||||
noteId: note.id,
|
||||
reaction: reaction,
|
||||
}, user);
|
||||
};
|
||||
|
||||
/**
|
||||
* Upload file
|
||||
* @param user User
|
||||
* @param _path Optional, absolute path or relative from ./resources/
|
||||
*/
|
||||
export const uploadFile = async (user: any, _path?: string): Promise<any> => {
|
||||
const absPath = _path == null ? `${_dirname}/resources/Lenna.jpg` : path.isAbsolute(_path) ? _path : `${_dirname}/resources/${_path}`;
|
||||
|
||||
const formData = new FormData() as any;
|
||||
formData.append('i', user.token);
|
||||
formData.append('file', fs.createReadStream(absPath));
|
||||
formData.append('force', 'true');
|
||||
|
||||
const res = await got<string>(`http://localhost:${port}/api/drive/files/create`, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
retry: {
|
||||
limit: 0,
|
||||
},
|
||||
});
|
||||
|
||||
const body = res.statusCode !== 204 ? await JSON.parse(res.body) : null;
|
||||
|
||||
return body;
|
||||
};
|
||||
|
||||
export const uploadUrl = async (user: any, url: string) => {
|
||||
let file: any;
|
||||
const marker = Math.random().toString();
|
||||
|
||||
const ws = await connectStream(user, 'main', (msg) => {
|
||||
if (msg.type === 'urlUploadFinished' && msg.body.marker === marker) {
|
||||
file = msg.body.file;
|
||||
}
|
||||
});
|
||||
|
||||
await api('drive/files/upload-from-url', {
|
||||
url,
|
||||
marker,
|
||||
force: true,
|
||||
}, user);
|
||||
|
||||
await sleep(7000);
|
||||
ws.close();
|
||||
|
||||
return file;
|
||||
};
|
||||
|
||||
export function connectStream(user: any, channel: string, listener: (message: Record<string, any>) => any, params?: any): Promise<WebSocket> {
|
||||
return new Promise((res, rej) => {
|
||||
const ws = new WebSocket(`ws://localhost:${port}/streaming?i=${user.token}`);
|
||||
|
||||
ws.on('open', () => {
|
||||
ws.on('message', data => {
|
||||
const msg = JSON.parse(data.toString());
|
||||
if (msg.type === 'channel' && msg.body.id === 'a') {
|
||||
listener(msg.body);
|
||||
} else if (msg.type === 'connected' && msg.body.id === 'a') {
|
||||
res(ws);
|
||||
}
|
||||
});
|
||||
|
||||
ws.send(JSON.stringify({
|
||||
type: 'connect',
|
||||
body: {
|
||||
channel: channel,
|
||||
id: 'a',
|
||||
pong: true,
|
||||
params: params,
|
||||
},
|
||||
}));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export const waitFire = async (user: any, channel: string, trgr: () => any, cond: (msg: Record<string, any>) => boolean, params?: any) => {
|
||||
return new Promise<boolean>(async (res, rej) => {
|
||||
let timer: NodeJS.Timeout;
|
||||
|
||||
let ws: WebSocket;
|
||||
try {
|
||||
ws = await connectStream(user, channel, msg => {
|
||||
if (cond(msg)) {
|
||||
ws.close();
|
||||
if (timer) clearTimeout(timer);
|
||||
res(true);
|
||||
}
|
||||
}, params);
|
||||
} catch (e) {
|
||||
rej(e);
|
||||
}
|
||||
|
||||
if (!ws!) return;
|
||||
|
||||
timer = setTimeout(() => {
|
||||
ws.close();
|
||||
res(false);
|
||||
}, 3000);
|
||||
|
||||
try {
|
||||
await trgr();
|
||||
} catch (e) {
|
||||
ws.close();
|
||||
if (timer) clearTimeout(timer);
|
||||
rej(e);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export const simpleGet = async (path: string, accept = '*/*'): Promise<{ status?: number, type?: string, location?: string }> => {
|
||||
// node-fetchだと3xxを取れない
|
||||
return await new Promise((resolve, reject) => {
|
||||
const req = http.request(`http://localhost:${port}${path}`, {
|
||||
headers: {
|
||||
Accept: accept,
|
||||
},
|
||||
}, res => {
|
||||
if (res.statusCode! >= 400) {
|
||||
reject(res);
|
||||
} else {
|
||||
resolve({
|
||||
status: res.statusCode,
|
||||
type: res.headers['content-type'],
|
||||
location: res.headers.location,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
req.end();
|
||||
});
|
||||
};
|
||||
|
||||
export function launchServer(callbackSpawnedProcess: (p: childProcess.ChildProcess) => void, moreProcess: () => Promise<void> = async () => {}) {
|
||||
return (done: (err?: Error) => any) => {
|
||||
const p = childProcess.spawn('node', [_dirname + '/../index.js'], {
|
||||
stdio: ['inherit', 'inherit', 'inherit', 'ipc'],
|
||||
env: { NODE_ENV: 'test', PATH: process.env.PATH },
|
||||
});
|
||||
callbackSpawnedProcess(p);
|
||||
p.on('message', message => {
|
||||
if (message === 'ok') moreProcess().then(() => done()).catch(e => done(e));
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
export async function initTestDb(justBorrow = false, initEntities?: any[]) {
|
||||
if (process.env.NODE_ENV !== 'test') throw 'NODE_ENV is not a test';
|
||||
|
||||
const db = new DataSource({
|
||||
type: 'postgres',
|
||||
host: config.db.host,
|
||||
port: config.db.port,
|
||||
username: config.db.user,
|
||||
password: config.db.pass,
|
||||
database: config.db.db,
|
||||
synchronize: true && !justBorrow,
|
||||
dropSchema: true && !justBorrow,
|
||||
entities: initEntities ?? entities,
|
||||
});
|
||||
|
||||
await db.initialize();
|
||||
|
||||
return db;
|
||||
}
|
||||
|
||||
export function startServer(timeout = 60 * 1000): Promise<childProcess.ChildProcess> {
|
||||
return new Promise((res, rej) => {
|
||||
const t = setTimeout(() => {
|
||||
p.kill(SIGKILL);
|
||||
rej('timeout to start');
|
||||
}, timeout);
|
||||
|
||||
const p = childProcess.spawn('node', [_dirname + '/../built/index.js'], {
|
||||
stdio: ['inherit', 'inherit', 'inherit', 'ipc'],
|
||||
env: { NODE_ENV: 'test', PATH: process.env.PATH },
|
||||
});
|
||||
|
||||
p.on('error', e => rej(e));
|
||||
|
||||
p.on('message', message => {
|
||||
if (message === 'ok') {
|
||||
clearTimeout(t);
|
||||
res(p);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function shutdownServer(p: childProcess.ChildProcess | undefined, timeout = 20 * 1000) {
|
||||
if (p == null) return Promise.resolve('nop');
|
||||
return new Promise((res, rej) => {
|
||||
const t = setTimeout(() => {
|
||||
p.kill(SIGKILL);
|
||||
res('force exit');
|
||||
}, timeout);
|
||||
|
||||
p.once('exit', () => {
|
||||
clearTimeout(t);
|
||||
res('exited');
|
||||
});
|
||||
|
||||
p.kill();
|
||||
});
|
||||
}
|
||||
|
||||
export function sleep(msec: number) {
|
||||
return new Promise<void>(res => {
|
||||
setTimeout(() => {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue