attachments.js 11 KB

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