Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
11 changes: 11 additions & 0 deletions server/mixins/__tests__/socketio.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,4 +115,15 @@ describe('Testing "socketio.mixin"', () => {
message: 'Not allowed request',
});
});

test('socketio should not call file service actions', async () => {
for (const action of ['file.save', 'file.get', 'file.fPutObject']) {
const res = await createAndEmitMessage(action);

expect(res).toEqual({
result: false,
message: 'Not allowed request',
});
}
});
});
1 change: 1 addition & 0 deletions server/mixins/socketio.mixin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { getRequestIp } from '../lib/requestIp';

const blacklist: (string | RegExp)[] = [
'gateway.*',
'file.*',
/^\$/, // moleculer internal services like "$node", which expose broker options
];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,7 @@ export const ApiGatewayMixin: ServiceSchema = {

listAliases: {
rest: 'GET /list-aliases',
visibility: 'public',
params: {
grouping: { type: 'boolean', optional: true, convert: true },
withActionSchema: { type: 'boolean', optional: true, convert: true },
Expand Down
54 changes: 30 additions & 24 deletions server/services/core/file.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
buildUploadUrl,
config,
TcDbService,
EntityError,
NoPermissionError,
TcMinioService,
} from 'tailchat-server-sdk';
Expand Down Expand Up @@ -47,20 +48,24 @@ class FileService extends TcService {
this.registerSetting('secretKey', config.storage.pass);
this.registerSetting('pathStyle', config.storage.pathStyle);

this.registerAction('save', this.save);
this.registerAction('save', this.save, {
disableSocket: true,
});
this.registerAction('saveFileWithUrl', this.saveFileWithUrl, {
visibility: 'public',
params: {
fileUrl: 'string',
},
});
this.registerAction('get', this.get, {
visibility: 'public',
params: {
objectName: 'string',
},
disableSocket: true,
});
this.registerAction('stat', this.stat, {
visibility: 'public',
params: {
objectName: 'string',
},
Expand Down Expand Up @@ -120,43 +125,44 @@ class FileService extends TcService {
>
) {
const t = ctx.meta.t;
const userId = ctx.meta.userId;
this.logger.info('Received upload $params:', ctx.meta.$params);
this.logger.info('Received upload meta:', _.omit(ctx.meta, ['token', 't']));

return new Promise(async (resolve, reject) => {
const userId = ctx.meta.userId;
this.logger.info('Received upload meta:', ctx.meta);
if (!isValidStr(userId)) {
throw new NoPermissionError(t('用户无上传权限'));
}

if (!isValidStr(userId)) {
throw new NoPermissionError(t('用户无上传权限'));
}
const stream = ctx.params as NodeJS.ReadableStream;
if (
!stream ||
typeof (stream as any).on !== 'function' ||
typeof (stream as any).pipe !== 'function'
) {
throw new EntityError(t('上传数据流无效'));
}

return new Promise((resolve, reject) => {
const originFilename = String(ctx.meta.filename);
const usage = _.get(ctx, 'meta.$multipart.usage', 'unknown');

const stream = ctx.params as NodeJS.ReadableStream;
(stream as any).on('error', (err) => {
// 这里是文件传输错误处理
// 比如文件过大
this.logger.error('File error received', err.message);
reject(err);
});

try {
const { etag, objectName, url } = await this.saveFileStream(
ctx,
originFilename,
stream,
usage
);

resolve({
etag,
path: `${this.bucketName}/${objectName}`,
url,
});
} catch (e) {
reject(e);
}
this.saveFileStream(ctx, originFilename, stream, usage).then(
({ etag, objectName, url }) => {
resolve({
etag,
path: `${this.bucketName}/${objectName}`,
url,
});
},
reject
);
});
}

Expand Down
3 changes: 2 additions & 1 deletion server/services/core/gateway.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,8 @@ export default class ApiService extends TcService {
whitelist: [
// Access to any actions in all services under "/api" URL,
// except moleculer internal services like "$node" which expose broker options
/^[^$]/,
// and "file.*" actions which are only exposed via dedicated /upload and /static routes
/^(?!\$|file\.)/,
],
// Route-level Express middlewares. More info: https://moleculer.services/docs/0.14/moleculer-web.html#Middlewares
use: [],
Expand Down
1 change: 1 addition & 0 deletions server/services/core/group/group.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ class GroupService extends TcService {
'getGroupLobbyConverseId',
this.getGroupLobbyConverseId,
{
visibility: 'public',
params: {
groupId: 'string',
},
Expand Down
1 change: 1 addition & 0 deletions server/services/openapi/app.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ class OpenAppService extends TcService {
this.registerLocalDb(require('../../models/openapi/app').default);

this.registerAction('authToken', this.authToken, {
visibility: 'public',
params: {
appId: 'string',
token: 'string',
Expand Down
40 changes: 40 additions & 0 deletions server/test/integration/file/file.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,48 @@
import http from 'http';
import type { AddressInfo } from 'net';
import FileService from '../../../services/core/file.service';
import { EntityError, NoPermissionError } from 'tailchat-server-sdk';

describe('Test "file" service', () => {
describe('Test "file.save"', () => {
const service = {
bucketName: 'test',
logger: { info: jest.fn(), error: jest.fn() },
saveFileStream: jest.fn(),
};

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

test('rejects calls without an authenticated userId', async () => {
await expect(
FileService.prototype.save.call(service, {
params: {},
meta: { t: (key: string) => key },
})
).rejects.toThrow(NoPermissionError);
expect(service.saveFileStream).not.toHaveBeenCalled();
});

test('rejects non-stream payloads cleanly and omits JWT from logs', async () => {
await expect(
FileService.prototype.save.call(service, {
params: { on: jest.fn() },
meta: {
userId: '507f1f77bcf86cd799439011',
token: 'secret-jwt-token',
t: (key: string) => key,
},
})
).rejects.toThrow(EntityError);
expect(service.saveFileStream).not.toHaveBeenCalled();
expect(JSON.stringify(service.logger.info.mock.calls)).not.toContain(
'secret-jwt-token'
);
});
});

describe('Test "file.saveFileWithUrl"', () => {
const handler = jest.fn((req, res) => {
res.end('internal secret');
Expand Down
15 changes: 15 additions & 0 deletions server/test/integration/gateway/gateway.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ describe('Test "gateway" service', () => {
name: 'file',
actions: {
get: () => Readable.from(['<script>alert(1)</script>']),
save: () => 'ok',
},
});
const headers = { 'x-token': 'any' };
Expand All @@ -73,6 +74,20 @@ describe('Test "gateway" service', () => {
}
});

test('should not expose gateway listAliases or file actions under /api', async () => {
for (const path of [
'/api/gateway/list-aliases',
'/api/gateway/listAliases',
'/api/file/get?objectName=files/u/a.html',
'/api/file/save',
]) {
const res = await request(path, headers);

expect(res.status).toBe(404);
expect(res.body.name).toBe('ServiceNotFoundError');
}
});

test('should still expose published service actions', async () => {
const res = await request('/api/gateway/health', headers);

Expand Down
Loading
Loading