diff --git a/server/mixins/__tests__/socketio.spec.ts b/server/mixins/__tests__/socketio.spec.ts
index c5fc25a647a..f3c65ef3037 100644
--- a/server/mixins/__tests__/socketio.spec.ts
+++ b/server/mixins/__tests__/socketio.spec.ts
@@ -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',
+ });
+ }
+ });
});
diff --git a/server/mixins/socketio.mixin.ts b/server/mixins/socketio.mixin.ts
index 4cd1a6e0ab8..ffc6549d650 100644
--- a/server/mixins/socketio.mixin.ts
+++ b/server/mixins/socketio.mixin.ts
@@ -23,6 +23,7 @@ import { getRequestIp } from '../lib/requestIp';
const blacklist: (string | RegExp)[] = [
'gateway.*',
+ 'file.*',
/^\$/, // moleculer internal services like "$node", which expose broker options
];
diff --git a/server/packages/sdk/src/services/lib/moleculer-web/index.ts b/server/packages/sdk/src/services/lib/moleculer-web/index.ts
index d05bf83cb8b..5a15f5cf652 100644
--- a/server/packages/sdk/src/services/lib/moleculer-web/index.ts
+++ b/server/packages/sdk/src/services/lib/moleculer-web/index.ts
@@ -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 },
diff --git a/server/services/core/file.service.ts b/server/services/core/file.service.ts
index 726f7d32f35..6d4670bdedf 100644
--- a/server/services/core/file.service.ts
+++ b/server/services/core/file.service.ts
@@ -5,6 +5,7 @@ import {
buildUploadUrl,
config,
TcDbService,
+ EntityError,
NoPermissionError,
TcMinioService,
} from 'tailchat-server-sdk';
@@ -47,7 +48,9 @@ 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: {
@@ -55,12 +58,14 @@ class FileService extends TcService {
},
});
this.registerAction('get', this.get, {
+ visibility: 'public',
params: {
objectName: 'string',
},
disableSocket: true,
});
this.registerAction('stat', this.stat, {
+ visibility: 'public',
params: {
objectName: 'string',
},
@@ -120,20 +125,27 @@ 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) => {
// 这里是文件传输错误处理
// 比如文件过大
@@ -141,22 +153,16 @@ class FileService extends TcService {
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
+ );
});
}
diff --git a/server/services/core/gateway.service.ts b/server/services/core/gateway.service.ts
index f7835e8f5cc..2ad5e8b2e6d 100644
--- a/server/services/core/gateway.service.ts
+++ b/server/services/core/gateway.service.ts
@@ -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: [],
diff --git a/server/services/core/group/group.service.ts b/server/services/core/group/group.service.ts
index a0ea66c99f8..db5005ce42a 100644
--- a/server/services/core/group/group.service.ts
+++ b/server/services/core/group/group.service.ts
@@ -184,6 +184,7 @@ class GroupService extends TcService {
'getGroupLobbyConverseId',
this.getGroupLobbyConverseId,
{
+ visibility: 'public',
params: {
groupId: 'string',
},
diff --git a/server/services/openapi/app.service.ts b/server/services/openapi/app.service.ts
index 3084d022d7f..1f06acc9366 100644
--- a/server/services/openapi/app.service.ts
+++ b/server/services/openapi/app.service.ts
@@ -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',
diff --git a/server/test/integration/file/file.spec.ts b/server/test/integration/file/file.spec.ts
index bc65ffe9585..cd92fb5d449 100644
--- a/server/test/integration/file/file.spec.ts
+++ b/server/test/integration/file/file.spec.ts
@@ -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');
diff --git a/server/test/integration/gateway/gateway.spec.ts b/server/test/integration/gateway/gateway.spec.ts
index 61c12788c80..b7dda60f637 100644
--- a/server/test/integration/gateway/gateway.spec.ts
+++ b/server/test/integration/gateway/gateway.spec.ts
@@ -52,6 +52,7 @@ describe('Test "gateway" service', () => {
name: 'file',
actions: {
get: () => Readable.from(['']),
+ save: () => 'ok',
},
});
const headers = { 'x-token': 'any' };
@@ -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);
diff --git a/server/test/integration/gateway/gatewayAccessControl.spec.ts b/server/test/integration/gateway/gatewayAccessControl.spec.ts
new file mode 100644
index 00000000000..6913ae3f1e0
--- /dev/null
+++ b/server/test/integration/gateway/gatewayAccessControl.spec.ts
@@ -0,0 +1,541 @@
+import http from 'http';
+import { Readable } from 'stream';
+import type { AddressInfo } from 'net';
+import jwt from 'jsonwebtoken';
+import {
+ ApiGatewayMixin,
+ config,
+ TcBroker,
+ TcMinioService,
+} from 'tailchat-server-sdk';
+import { TcHealth } from '../../../mixins/health.mixin';
+import { TcSocketIOService } from '../../../mixins/socketio.mixin';
+import ApiService from '../../../services/core/gateway.service';
+import UserService from '../../../services/core/user/user.service';
+import FileService from '../../../services/core/file.service';
+import ConfigService from '../../../services/core/config.service';
+import GroupService from '../../../services/core/group/group.service';
+import MailService from '../../../services/core/user/mail.service';
+import OpenAppService from '../../../services/openapi/app.service';
+import OpenBotService from '../../../services/openapi/bot.service';
+import UserModel from '../../../models/user/user';
+
+const regularUser = new UserModel({
+ _id: '507f1f77bcf86cd799439011',
+ email: 'regular@example.invalid',
+ nickname: 'RegularUser',
+ discriminator: '0001',
+ password: 'hashed-password',
+});
+
+const minioClientMock = {
+ listBuckets: jest.fn(async () => [{ name: 'tailchat' }]),
+ fGetObject: jest.fn(),
+ fPutObject: jest.fn(),
+ getObject: jest.fn(async () => Readable.from([''])),
+ statObject: jest.fn(async () => ({ size: 12, metaData: {} })),
+ removeObject: jest.fn(async () => undefined),
+ putObject: jest.fn(async (_bucket, _name, stream: Readable) => {
+ for await (const _chunk of stream) {
+ // drain
+ }
+ return { etag: 'mock-etag' };
+ }),
+ copyObject: jest.fn(async () => ({ etag: 'mock-etag' })),
+};
+
+const fileSaveStreamSpy = jest.fn(async (ctx, filename, stream: Readable) => {
+ for await (const _chunk of stream) {
+ // drain upload stream
+ }
+ return {
+ etag: 'mock-etag',
+ objectName: `files/${ctx.meta.userId}/mock-etag.txt`,
+ url: `/static/files/${ctx.meta.userId}/mock-etag.txt`,
+ };
+});
+
+const userUpdateOneSpy = jest.fn(async () => ({ modifiedCount: 1 }));
+const configSetClientSpy = jest.fn(async () => ({}));
+const mailSendSpy = jest.fn(async () => ({}));
+
+class TestUserService extends UserService {
+ onInit() {
+ this.registerLocalDb = () => {
+ this.adapter = {
+ model: {
+ findById: async (id: string) =>
+ String(id) === String(regularUser._id) ? regularUser : null,
+ updateOne: userUpdateOneSpy,
+ },
+ findById: async (id: string) =>
+ String(id) === String(regularUser._id) ? regularUser : null,
+ } as any;
+ this.transformDocuments = (async (_ctx, _params, doc) => {
+ if (!doc) {
+ return doc;
+ }
+ const json = doc.toJSON ? doc.toJSON() : { ...doc };
+ if (json._id !== undefined) {
+ json._id = String(json._id);
+ }
+ return json;
+ }) as any;
+ };
+ super.onInit();
+ }
+}
+
+class TestFileService extends FileService {
+ onInit() {
+ this.registerLocalDb = () => {
+ this.adapter = {
+ model: {
+ updateOne: jest.fn(async () => ({})),
+ deleteMany: jest.fn(async () => ({})),
+ },
+ } as any;
+ };
+ const origRegisterMixin = this.registerMixin.bind(this);
+ this.registerMixin = (mixin) => {
+ if (mixin === TcMinioService) {
+ origRegisterMixin({
+ ...TcMinioService,
+ methods: {
+ ...TcMinioService.methods,
+ createMinioClient() {
+ return minioClientMock;
+ },
+ ping() {
+ return Promise.resolve(true);
+ },
+ },
+ });
+ } else {
+ origRegisterMixin(mixin);
+ }
+ };
+ super.onInit();
+ this.registerSetting('minioHealthCheckInterval', 0);
+ }
+
+ async onInited() {
+ // Skip bucket bootstrap in unit test
+ }
+
+ saveFileStream = fileSaveStreamSpy as any;
+}
+
+class TestConfigService extends ConfigService {
+ onInit() {
+ this.registerLocalDb = () => {
+ this.adapter = {
+ model: {
+ getAllClientPersistConfig: jest.fn(async () => ({})),
+ setClientPersistConfig: configSetClientSpy,
+ },
+ } as any;
+ };
+ this.cleanActionCache = jest.fn(async () => undefined);
+ super.onInit();
+ }
+}
+
+class TestGroupService extends GroupService {
+ onInit() {
+ this.registerLocalDb = () => {
+ this.adapter = { model: {} } as any;
+ };
+ super.onInit();
+ }
+}
+
+class TestMailService extends MailService {
+ onInit() {
+ this.registerLocalDb = () => {
+ this.adapter = {
+ model: {
+ verifyMailService: jest.fn(async () => false),
+ sendMail: mailSendSpy,
+ },
+ } as any;
+ };
+ super.onInit();
+ }
+
+ onInited() {
+ // Skip SMTP check
+ }
+}
+
+class TestOpenAppService extends OpenAppService {
+ onInit() {
+ this.registerLocalDb = () => {
+ this.adapter = { model: {} } as any;
+ };
+ super.onInit();
+ }
+}
+
+class TestGatewayService extends ApiService {
+ onInit() {
+ const socketSchema = TcSocketIOService({
+ userAuth: async () => null,
+ });
+ this.registerMixin(ApiGatewayMixin);
+ this.registerMixin({
+ actions: socketSchema.actions,
+ });
+ this.registerMixin(TcHealth());
+ this.registerSetting('port', 0);
+ this.registerSetting('ip', '127.0.0.1');
+ this.registerSetting('routes', this.getRoutes());
+ this.registerSetting('log4XXResponses', false);
+ this.registerSetting('logRequestParams', null);
+ this.registerSetting('logResponseData', null);
+ this.registerMethod('authorize', this.authorize);
+ }
+}
+
+describe('Gateway access control against real service action schemas', () => {
+ const broker = new TcBroker({ logger: false, cacher: 'Memory' });
+ let gateway: TestGatewayService;
+ let fileService: TestFileService;
+ const originalStorage = { ...config.storage };
+ try {
+ config.storage.minioUrl = '127.0.0.1:9000';
+ config.storage.user = 'test';
+ config.storage.pass = 'test';
+
+ gateway = broker.createService(TestGatewayService) as TestGatewayService;
+ fileService = broker.createService(TestFileService) as TestFileService;
+ broker.createService(TestUserService);
+ broker.createService(TestConfigService);
+ broker.createService(TestGroupService);
+ broker.createService(TestMailService);
+ broker.createService(TestOpenAppService);
+ broker.createService(OpenBotService);
+ } finally {
+ config.storage.minioUrl = originalStorage.minioUrl;
+ config.storage.user = originalStorage.user;
+ config.storage.pass = originalStorage.pass;
+ }
+
+ const userToken = jwt.sign({ _id: String(regularUser._id) }, config.secret);
+
+ function httpRequest(options: {
+ method: string;
+ path: string;
+ headers?: Record;
+ body?: string;
+ }): Promise<{
+ status: number;
+ headers: http.IncomingHttpHeaders;
+ rawBody: string;
+ json: any;
+ }> {
+ const { port } = gateway.server.address() as AddressInfo;
+ return new Promise((resolve, reject) => {
+ const req = http.request(
+ {
+ hostname: '127.0.0.1',
+ port,
+ method: options.method,
+ path: options.path,
+ headers: options.headers,
+ },
+ (res) => {
+ let rawBody = '';
+ res.on('data', (chunk) => {
+ rawBody += chunk;
+ });
+ res.on('end', () => {
+ let json: any = null;
+ try {
+ json = JSON.parse(rawBody);
+ } catch {
+ // non-json response (e.g. /static)
+ }
+ resolve({
+ status: res.statusCode ?? 0,
+ headers: res.headers,
+ rawBody,
+ json,
+ });
+ });
+ }
+ );
+ req.on('error', reject);
+ if (options.body !== undefined) {
+ req.write(options.body);
+ }
+ req.end();
+ });
+ }
+
+ beforeAll(() => broker.start());
+ beforeEach(() => jest.clearAllMocks());
+ afterAll(() => broker.stop());
+
+ test.each([
+ // MinIO raw actions (visibility: 'private') + file service actions (excluded from /api)
+ [
+ 'POST',
+ '/api/file/fPutObject',
+ { bucketName: 'tailchat', objectName: 'x', filePath: '/etc/passwd' },
+ ],
+ [
+ 'POST',
+ '/api/file/fGetObject',
+ { bucketName: 'tailchat', objectName: 'x', filePath: '/tmp/pwn' },
+ ],
+ ['POST', '/api/file/listBuckets', {}],
+ [
+ 'POST',
+ '/api/file/removeObject',
+ { bucketName: 'tailchat', objectName: 'files/victim/a.png' },
+ ],
+ ['POST', '/api/file/delete', { objectName: 'files/victim/a.png' }],
+ [
+ 'POST',
+ '/api/file/saveFileWithUrl',
+ { fileUrl: 'https://example.com/a.png' },
+ ],
+ ['POST', '/api/file/get', { objectName: 'files/victim/a.html' }],
+ ['POST', '/api/file/stat', { objectName: 'files/victim/a.png' }],
+ ['POST', '/api/file/save', {}],
+ ['POST', '/api/file.save', {}],
+ ['GET', '/api/file/save', undefined],
+ // User internal actions (visibility: 'public')
+ [
+ 'POST',
+ '/api/user/generateUserToken',
+ { userId: 'target', nickname: 'admin', email: 'a@b.c', avatar: '' },
+ ],
+ ['POST', '/api/user/signUserToken', { userId: String(regularUser._id) }],
+ ['POST', '/api/user.signUserToken', { userId: String(regularUser._id) }],
+ ['GET', `/api/user/signUserToken?userId=${regularUser._id}`, undefined],
+ ['POST', '/api/user/banUser', { userId: String(regularUser._id) }],
+ ['POST', '/api/user/unbanUser', { userId: String(regularUser._id) }],
+ ['POST', '/api/user/ensurePluginBot', { botId: 'x', nickname: 'x' }],
+ ['POST', '/api/user/ensureOpenapiBot', { botId: 'x', nickname: 'x' }],
+ ['POST', '/api/user/findOpenapiBotId', { email: 'x@openapi.msgbyte.com' }],
+ [
+ 'POST',
+ '/api/user/getUserInfoInternal',
+ { userId: String(regularUser._id) },
+ ],
+ ['POST', '/api/user/findUserByEmail', { email: regularUser.email }],
+ ['POST', '/api/user/findUserByUsername', { username: 'admin' }],
+ // Config internal actions (visibility: 'public')
+ ['POST', '/api/config/set', { key: 'evil', value: true }],
+ [
+ 'POST',
+ '/api/config/addToSet',
+ { key: '$gatewayAfterHooks.user.login', value: 'evil.action' },
+ ],
+ [
+ 'POST',
+ '/api/config/setClientConfig',
+ { key: 'serverName', value: 'pwned' },
+ ],
+ ['POST', '/api/config/all', {}],
+ ['POST', '/api/config/get', { key: 'panelFeature' }],
+ // Gateway internal actions (visibility: 'public')
+ ['GET', '/api/gateway/list-aliases?withActionSchema=true', undefined],
+ ['POST', '/api/gateway/listAliases', { withActionSchema: true }],
+ ['POST', '/api/gateway/addRoute', { route: { path: '/pwn' } }],
+ ['POST', '/api/gateway/removeRoute', { path: '/api' }],
+ [
+ 'POST',
+ '/api/gateway/joinRoom',
+ { roomIds: ['secret-room'], userId: String(regularUser._id) },
+ ],
+ [
+ 'POST',
+ '/api/gateway/leaveRoom',
+ { roomIds: ['secret-room'], userId: String(regularUser._id) },
+ ],
+ [
+ 'POST',
+ '/api/gateway/fetchUserSocketIds',
+ { userId: String(regularUser._id) },
+ ],
+ [
+ 'POST',
+ '/api/gateway/getUserSocketToken',
+ { userId: String(regularUser._id) },
+ ],
+ ['POST', '/api/gateway/tickUser', { userId: String(regularUser._id) }],
+ [
+ 'POST',
+ '/api/gateway/notify',
+ { type: 'broadcast', eventName: 'x', eventData: {} },
+ ],
+ // Group, mail & openapi internal actions (visibility: 'public')
+ [
+ 'POST',
+ '/api/group/getGroupInfo',
+ { groupId: '507f1f77bcf86cd799439022' },
+ ],
+ [
+ 'POST',
+ '/api/group/addMember',
+ { groupId: '507f1f77bcf86cd799439022', userId: String(regularUser._id) },
+ ],
+ ['POST', '/api/group/joinGroup', { groupId: '507f1f77bcf86cd799439022' }],
+ [
+ 'POST',
+ '/api/group/getUserAllPermissions',
+ { groupId: '507f1f77bcf86cd799439022', userId: String(regularUser._id) },
+ ],
+ [
+ 'POST',
+ '/api/group/getGroupLobbyConverseId',
+ { groupId: '507f1f77bcf86cd799439022' },
+ ],
+ [
+ 'POST',
+ '/api/mail/sendMail',
+ { to: 'victim@example.com', subject: 'hi', html: 'hi' },
+ ],
+ ['POST', '/api/openapi/app/authToken', { appId: 'tc_1', token: 'abc' }],
+ ['POST', '/api/openapi/bot/getOrCreateBotAccount', { appId: 'tc_1' }],
+ ])(
+ 'rejects %s %s for an authenticated normal user with 404 ServiceNotFoundError',
+ async (method, path, payload) => {
+ const res = await httpRequest({
+ method,
+ path,
+ headers: {
+ 'x-token': userToken,
+ ...(payload !== undefined
+ ? { 'content-type': 'application/json' }
+ : {}),
+ },
+ body: payload !== undefined ? JSON.stringify(payload) : undefined,
+ });
+
+ expect(res.status).toBe(404);
+ expect(res.json?.name).toBe('ServiceNotFoundError');
+ expect(minioClientMock.fPutObject).not.toHaveBeenCalled();
+ expect(minioClientMock.fGetObject).not.toHaveBeenCalled();
+ expect(minioClientMock.removeObject).not.toHaveBeenCalled();
+ expect(minioClientMock.getObject).not.toHaveBeenCalled();
+ expect(minioClientMock.statObject).not.toHaveBeenCalled();
+ expect(fileSaveStreamSpy).not.toHaveBeenCalled();
+ expect(userUpdateOneSpy).not.toHaveBeenCalled();
+ expect(configSetClientSpy).not.toHaveBeenCalled();
+ expect(mailSendSpy).not.toHaveBeenCalled();
+ }
+ );
+
+ test('rejects unauthenticated requests to /upload', async () => {
+ const postNoToken = await httpRequest({
+ method: 'POST',
+ path: '/upload',
+ body: 'hello',
+ });
+ expect(postNoToken.status).toBe(401);
+ expect(postNoToken.json?.type).toBe('NO_TOKEN');
+
+ const putNoToken = await httpRequest({
+ method: 'PUT',
+ path: '/upload',
+ body: 'hello',
+ });
+ expect(putNoToken.status).toBe(401);
+ expect(putNoToken.json?.type).toBe('NO_TOKEN');
+
+ const putInvalidToken = await httpRequest({
+ method: 'PUT',
+ path: '/upload',
+ headers: { 'x-token': 'invalid-token' },
+ body: 'hello',
+ });
+ expect(putInvalidToken.status).toBe(401);
+ expect(putInvalidToken.json?.type).toBe('INVALID_TOKEN');
+ expect(fileSaveStreamSpy).not.toHaveBeenCalled();
+ });
+
+ test('allows authenticated normal user on published endpoints', async () => {
+ const res = await httpRequest({
+ method: 'POST',
+ path: '/api/user/whoami',
+ headers: {
+ 'x-token': userToken,
+ 'content-type': 'application/json',
+ },
+ body: '{}',
+ });
+
+ expect(res.status).toBe(200);
+ expect(res.json?.data?.userId).toBe(String(regularUser._id));
+ });
+
+ test('allows authenticated uploads to /upload via PUT stream and POST multipart', async () => {
+ const putRes = await httpRequest({
+ method: 'PUT',
+ path: '/upload',
+ headers: { 'x-token': userToken },
+ body: 'hello tailchat',
+ });
+
+ expect(putRes.status).toBe(200);
+ expect(fileSaveStreamSpy).toHaveBeenCalledTimes(1);
+ expect(fileSaveStreamSpy.mock.calls[0][0].meta.userId).toBe(
+ String(regularUser._id)
+ );
+
+ const boundary = '----TailchatTestBoundary';
+ const multipartBody = [
+ `--${boundary}`,
+ 'Content-Disposition: form-data; name="file"; filename="hello.txt"',
+ 'Content-Type: text/plain',
+ '',
+ 'hello multipart',
+ `--${boundary}--`,
+ '',
+ ].join('\r\n');
+ const postRes = await httpRequest({
+ method: 'POST',
+ path: '/upload',
+ headers: {
+ 'x-token': userToken,
+ 'content-type': `multipart/form-data; boundary=${boundary}`,
+ },
+ body: multipartBody,
+ });
+
+ expect(postRes.status).toBe(200);
+ expect(fileSaveStreamSpy).toHaveBeenCalledTimes(2);
+ expect(fileSaveStreamSpy.mock.calls[1][0].meta.userId).toBe(
+ String(regularUser._id)
+ );
+ });
+
+ test('keeps /static working via internal file.get while enforcing attachment headers', async () => {
+ const htmlRes = await httpRequest({
+ method: 'GET',
+ path: '/static/files/u/xss.html',
+ });
+ expect(htmlRes.status).toBe(200);
+ expect(htmlRes.headers['content-disposition']).toBe('attachment');
+ expect(htmlRes.headers['x-content-type-options']).toBe('nosniff');
+ expect(minioClientMock.getObject).toHaveBeenCalledWith(
+ fileService.bucketName,
+ 'files/u/xss.html'
+ );
+ });
+
+ test('marks file.save as disableSocket and omits internal file actions from published action list', () => {
+ expect((fileService.schema.actions.save as any)?.disableSocket).toBe(true);
+ const publishedFileActions = fileService.getActionList().map((a) => a.name);
+ expect(publishedFileActions).not.toContain('get');
+ expect(publishedFileActions).not.toContain('stat');
+ expect(publishedFileActions).not.toContain('delete');
+ expect(publishedFileActions).not.toContain('saveFileWithUrl');
+ expect(publishedFileActions).not.toContain('fPutObject');
+ expect(publishedFileActions).not.toContain('fGetObject');
+ });
+});