attachments.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. import { ReactiveCache } from '/imports/reactiveCache';
  2. import { Meteor } from 'meteor/meteor';
  3. import { FilesCollection } from 'meteor/ostrio:files';
  4. import { isFileValid } from './fileValidation';
  5. import { createBucket } from './lib/grid/createBucket';
  6. import fs from 'fs';
  7. import path from 'path';
  8. import { AttachmentStoreStrategyFilesystem, AttachmentStoreStrategyGridFs, AttachmentStoreStrategyS3 } from '/models/lib/attachmentStoreStrategy';
  9. import FileStoreStrategyFactory, {moveToStorage, rename, STORAGE_NAME_FILESYSTEM, STORAGE_NAME_GRIDFS, STORAGE_NAME_S3} from '/models/lib/fileStoreStrategy';
  10. import { getAttachmentWithBackwardCompatibility, getAttachmentsWithBackwardCompatibility } from './lib/attachmentBackwardCompatibility';
  11. import AttachmentStorageSettings from './attachmentStorageSettings';
  12. let attachmentUploadExternalProgram;
  13. let attachmentUploadMimeTypes = [];
  14. let attachmentUploadSize = 0;
  15. let attachmentBucket;
  16. let storagePath;
  17. if (Meteor.isServer) {
  18. attachmentBucket = createBucket('attachments');
  19. if (process.env.ATTACHMENTS_UPLOAD_MIME_TYPES) {
  20. attachmentUploadMimeTypes = process.env.ATTACHMENTS_UPLOAD_MIME_TYPES.split(',');
  21. attachmentUploadMimeTypes = attachmentUploadMimeTypes.map(value => value.trim());
  22. }
  23. if (process.env.ATTACHMENTS_UPLOAD_MAX_SIZE) {
  24. attachmentUploadSize = parseInt(process.env.ATTACHMENTS_UPLOAD_MAX_SIZE);
  25. if (isNaN(attachmentUploadSize)) {
  26. attachmentUploadSize = 0
  27. }
  28. }
  29. if (process.env.ATTACHMENTS_UPLOAD_EXTERNAL_PROGRAM) {
  30. attachmentUploadExternalProgram = process.env.ATTACHMENTS_UPLOAD_EXTERNAL_PROGRAM;
  31. if (!attachmentUploadExternalProgram.includes("{file}")) {
  32. attachmentUploadExternalProgram = undefined;
  33. }
  34. }
  35. storagePath = path.join(process.env.WRITABLE_PATH, 'attachments');
  36. }
  37. export const fileStoreStrategyFactory = new FileStoreStrategyFactory(AttachmentStoreStrategyFilesystem, storagePath, AttachmentStoreStrategyGridFs, attachmentBucket);
  38. // XXX Enforce a schema for the Attachments FilesCollection
  39. // see: https://github.com/VeliovGroup/Meteor-Files/wiki/Schema
  40. Attachments = new FilesCollection({
  41. debug: false, // Change to `true` for debugging
  42. collectionName: 'attachments',
  43. allowClientCode: true,
  44. namingFunction(opts) {
  45. let filenameWithoutExtension = ""
  46. let fileId = "";
  47. if (opts?.name) {
  48. // Client
  49. filenameWithoutExtension = opts.name.replace(/(.+)\..+/, "$1");
  50. fileId = opts.meta.fileId;
  51. delete opts.meta.fileId;
  52. } else if (opts?.file?.name) {
  53. // Server
  54. if (opts.file.extension) {
  55. filenameWithoutExtension = opts.file.name.replace(new RegExp(opts.file.extensionWithDot + "$"), "")
  56. } else {
  57. // file has no extension, so don't replace anything, otherwise the last character is removed (because extensionWithDot = '.')
  58. filenameWithoutExtension = opts.file.name;
  59. }
  60. fileId = opts.fileId;
  61. }
  62. else {
  63. // should never reach here
  64. filenameWithoutExtension = Math.random().toString(36).slice(2);
  65. fileId = Math.random().toString(36).slice(2);
  66. }
  67. // OLD:
  68. //const ret = fileId + "-original-" + filenameWithoutExtension;
  69. // NEW: Save file only with filename of ObjectID, not including filename.
  70. // Fixes https://github.com/wekan/wekan/issues/4416#issuecomment-1510517168
  71. const ret = fileId;
  72. // remove fileId from meta, it was only stored there to have this information here in the namingFunction function
  73. return ret;
  74. },
  75. sanitize(str, max, replacement) {
  76. // keep the original filename
  77. return str;
  78. },
  79. storagePath() {
  80. const ret = fileStoreStrategyFactory.storagePath;
  81. return ret;
  82. },
  83. onBeforeUpload(file) {
  84. // Block SVG files for attachments to prevent XSS attacks
  85. if (file.name && file.name.toLowerCase().endsWith('.svg')) {
  86. if (process.env.DEBUG === 'true') {
  87. console.warn('Blocked SVG file upload for attachment:', file.name);
  88. }
  89. return 'SVG files are not allowed for attachments due to security reasons. Please use PNG, JPG, GIF, or other safe formats.';
  90. }
  91. if (file.type === 'image/svg+xml') {
  92. if (process.env.DEBUG === 'true') {
  93. console.warn('Blocked SVG MIME type upload for attachment:', file.type);
  94. }
  95. return 'SVG files are not allowed for attachments due to security reasons. Please use PNG, JPG, GIF, or other safe formats.';
  96. }
  97. return true;
  98. },
  99. onAfterUpload(fileObj) {
  100. // Get default storage backend from settings
  101. let defaultStorage = STORAGE_NAME_FILESYSTEM;
  102. try {
  103. const settings = AttachmentStorageSettings.findOne({});
  104. if (settings) {
  105. defaultStorage = settings.getDefaultStorage();
  106. }
  107. } catch (error) {
  108. console.warn('Could not get attachment storage settings, using default:', error);
  109. }
  110. // Set initial storage to filesystem (temporary)
  111. Object.keys(fileObj.versions).forEach(versionName => {
  112. fileObj.versions[versionName].storage = STORAGE_NAME_FILESYSTEM;
  113. });
  114. this._now = new Date();
  115. Attachments.update({ _id: fileObj._id }, { $set: { "versions" : fileObj.versions } });
  116. Attachments.update({ _id: fileObj.uploadedAtOstrio }, { $set: { "uploadedAtOstrio" : this._now } });
  117. // Use selected storage backend or copy storage if specified
  118. let storageDestination = fileObj.meta.copyStorage || defaultStorage;
  119. // Only migrate if the destination is different from filesystem
  120. if (storageDestination !== STORAGE_NAME_FILESYSTEM) {
  121. Meteor.defer(() => Meteor.call('validateAttachmentAndMoveToStorage', fileObj._id, storageDestination));
  122. }
  123. },
  124. interceptDownload(http, fileObj, versionName) {
  125. const ret = fileStoreStrategyFactory.getFileStrategy(fileObj, versionName).interceptDownload(http, this.cacheControl);
  126. return ret;
  127. },
  128. onAfterRemove(files) {
  129. files.forEach(fileObj => {
  130. Object.keys(fileObj.versions).forEach(versionName => {
  131. fileStoreStrategyFactory.getFileStrategy(fileObj, versionName).onAfterRemove();
  132. });
  133. });
  134. },
  135. // We authorize the attachment download either:
  136. // - if the board is public, everyone (even unconnected) can download it
  137. // - if the board is private, only board members can download it
  138. protected(fileObj) {
  139. // file may have been deleted already again after upload validation failed
  140. if (!fileObj) {
  141. return false;
  142. }
  143. const board = ReactiveCache.getBoard(fileObj.meta.boardId);
  144. if (board.isPublic()) {
  145. return true;
  146. }
  147. return board.hasMember(this.userId);
  148. },
  149. });
  150. if (Meteor.isServer) {
  151. Attachments.allow({
  152. insert(userId, fileObj) {
  153. return allowIsBoardMember(userId, ReactiveCache.getBoard(fileObj.boardId));
  154. },
  155. update(userId, fileObj, fields) {
  156. // Only allow updates to specific fields that don't affect security
  157. const allowedFields = ['name', 'size', 'type', 'extension', 'extensionWithDot', 'meta', 'versions'];
  158. const isAllowedField = fields.every(field => allowedFields.includes(field));
  159. if (!isAllowedField) {
  160. if (process.env.DEBUG === 'true') {
  161. console.warn('Blocked attempt to update restricted attachment fields:', fields);
  162. }
  163. return false;
  164. }
  165. return allowIsBoardMember(userId, ReactiveCache.getBoard(fileObj.boardId));
  166. },
  167. remove(userId, fileObj) {
  168. // Additional security check: ensure the file belongs to the board the user has access to
  169. if (!fileObj || !fileObj.boardId) {
  170. if (process.env.DEBUG === 'true') {
  171. console.warn('Blocked attachment removal: file has no boardId');
  172. }
  173. return false;
  174. }
  175. const board = ReactiveCache.getBoard(fileObj.boardId);
  176. if (!board) {
  177. if (process.env.DEBUG === 'true') {
  178. console.warn('Blocked attachment removal: board not found');
  179. }
  180. return false;
  181. }
  182. return allowIsBoardMember(userId, board);
  183. },
  184. fetch: ['meta', 'boardId'],
  185. });
  186. Meteor.methods({
  187. // Validate image URL to prevent SVG-based DoS attacks
  188. validateImageUrl(imageUrl) {
  189. check(imageUrl, String);
  190. if (!imageUrl) {
  191. return { valid: false, reason: 'Empty URL' };
  192. }
  193. // Block SVG files and data URIs
  194. if (imageUrl.endsWith('.svg') || imageUrl.startsWith('data:image/svg')) {
  195. if (process.env.DEBUG === 'true') {
  196. console.warn('Blocked potentially malicious SVG image URL:', imageUrl);
  197. }
  198. return { valid: false, reason: 'SVG images are blocked for security reasons' };
  199. }
  200. // Block data URIs that could contain malicious content
  201. if (imageUrl.startsWith('data:')) {
  202. if (process.env.DEBUG === 'true') {
  203. console.warn('Blocked data URI image URL:', imageUrl);
  204. }
  205. return { valid: false, reason: 'Data URIs are blocked for security reasons' };
  206. }
  207. // Validate URL format
  208. try {
  209. const url = new URL(imageUrl);
  210. // Only allow http and https protocols
  211. if (!['http:', 'https:'].includes(url.protocol)) {
  212. return { valid: false, reason: 'Only HTTP and HTTPS protocols are allowed' };
  213. }
  214. } catch (e) {
  215. return { valid: false, reason: 'Invalid URL format' };
  216. }
  217. return { valid: true };
  218. },
  219. moveAttachmentToStorage(fileObjId, storageDestination) {
  220. check(fileObjId, String);
  221. check(storageDestination, String);
  222. const fileObj = ReactiveCache.getAttachment(fileObjId);
  223. moveToStorage(fileObj, storageDestination, fileStoreStrategyFactory);
  224. },
  225. renameAttachment(fileObjId, newName) {
  226. check(fileObjId, String);
  227. check(newName, String);
  228. const currentUserId = Meteor.userId();
  229. if (!currentUserId) {
  230. throw new Meteor.Error('not-authorized', 'User must be logged in');
  231. }
  232. const fileObj = ReactiveCache.getAttachment(fileObjId);
  233. if (!fileObj) {
  234. throw new Meteor.Error('file-not-found', 'Attachment not found');
  235. }
  236. // Verify the user has permission to modify this attachment
  237. const board = ReactiveCache.getBoard(fileObj.boardId);
  238. if (!board) {
  239. throw new Meteor.Error('board-not-found', 'Board not found');
  240. }
  241. if (!allowIsBoardMember(currentUserId, board)) {
  242. if (process.env.DEBUG === 'true') {
  243. console.warn(`Blocked unauthorized attachment rename attempt: user ${currentUserId} tried to rename attachment ${fileObjId} in board ${fileObj.boardId}`);
  244. }
  245. throw new Meteor.Error('not-authorized', 'You do not have permission to modify this attachment');
  246. }
  247. rename(fileObj, newName, fileStoreStrategyFactory);
  248. },
  249. validateAttachment(fileObjId) {
  250. check(fileObjId, String);
  251. const fileObj = ReactiveCache.getAttachment(fileObjId);
  252. const isValid = Promise.await(isFileValid(fileObj, attachmentUploadMimeTypes, attachmentUploadSize, attachmentUploadExternalProgram));
  253. if (!isValid) {
  254. Attachments.remove(fileObjId);
  255. }
  256. },
  257. validateAttachmentAndMoveToStorage(fileObjId, storageDestination) {
  258. check(fileObjId, String);
  259. check(storageDestination, String);
  260. Meteor.call('validateAttachment', fileObjId);
  261. const fileObj = ReactiveCache.getAttachment(fileObjId);
  262. if (fileObj) {
  263. Meteor.defer(() => Meteor.call('moveAttachmentToStorage', fileObjId, storageDestination));
  264. }
  265. },
  266. });
  267. Meteor.startup(() => {
  268. Attachments.collection.createIndex({ 'meta.cardId': 1 });
  269. const storagePath = fileStoreStrategyFactory.storagePath;
  270. if (!fs.existsSync(storagePath)) {
  271. console.log("create storagePath because it doesn't exist: " + storagePath);
  272. fs.mkdirSync(storagePath, { recursive: true });
  273. }
  274. });
  275. // Add backward compatibility methods
  276. Attachments.getAttachmentWithBackwardCompatibility = getAttachmentWithBackwardCompatibility;
  277. Attachments.getAttachmentsWithBackwardCompatibility = getAttachmentsWithBackwardCompatibility;
  278. }
  279. export default Attachments;