mirror of
https://github.com/wekan/wekan.git
synced 2026-11-24 18:10:06 -05:00
Every attachment gets its SHA-256 (contentHash: value, size, time) and its plain search text (with the time it was made) when it is added, and - for one added before this - the first time it is read whole. Text, Markdown, CSV, code, JSON, HTML and e-mail are read as text, PDF and Office through the document extractor, Outlook .msg and OpenDocument from their slideshow rows. A new attachment's "Added" card history row carries its hash, and so do the soft delete and restore rows. Each whole read hashes the bytes on their way out, with no second read: no stored hash - it is stored; the same - nothing; another hash that the card history knows - an earlier version an undo or restore brought back - a new hash and search text are made; anything else - a warning in Admin Panel / Problems (integrity), keeping the stored hash. A range is no evidence. Filter's text field, the board's Search and Search All Boards find a card by its attachments' text; each index row is checked against its live attachment on that card, and the text is never sent to the browser. tests/attachmentContent.test.cjs pins the decisions and the wiring; tests/playwright/specs/attachment-content-search.e2e.js adds a file, finds it three ways, changes it on disk (warned), reads a range (nothing) and brings back a known version (accepted, indexed again). Thanks to xet7 !
606 lines
26 KiB
JavaScript
606 lines
26 KiB
JavaScript
import { requireBoardMutation } from '/models/lib/boardMutationGuard';
|
|
import { forgetIntegrityBaselinesOfFiles } from '/server/lib/fileIntegrityForget';
|
|
import { ReactiveCache } from '/imports/reactiveCache';
|
|
import { Meteor } from 'meteor/meteor';
|
|
import { MongoInternals } from 'meteor/mongo';
|
|
import { check } from 'meteor/check';
|
|
import { isFileValid } from './fileValidation';
|
|
import { createBucket } from './lib/grid/createBucket';
|
|
import fs from 'fs';
|
|
import path from 'path';
|
|
import { AttachmentStoreStrategyFilesystem, AttachmentStoreStrategyGridFs, AttachmentStoreStrategyCloud } from '/models/lib/attachmentStoreStrategy';
|
|
import FileStoreStrategyFactory, { moveToStorage, rename, STORAGE_NAME_FILESYSTEM, STORAGE_NAME_GRIDFS } from '/models/lib/fileStoreStrategy';
|
|
import { refreshCloudStorageFromSettings } from '/models/lib/cloudStorage';
|
|
import { getAttachmentWithBackwardCompatibility, getAttachmentsWithBackwardCompatibility } from './lib/attachmentBackwardCompatibility';
|
|
import AttachmentStorageSettings from './attachmentStorageSettings';
|
|
import Attachments, { normalizeRemovedFiles } from './attachments';
|
|
import Boards from '/models/boards';
|
|
import { allowIsBoardMember } from '/server/lib/utils';
|
|
import { ensureIndex } from '/server/lib/mongoStartup';
|
|
const { isFilesRoot } = require('/models/lib/filesRoot');
|
|
const { readableWithoutMembership } = require('/models/lib/boardPermission');
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Server-only configuration
|
|
// ---------------------------------------------------------------------------
|
|
|
|
let attachmentUploadExternalProgram;
|
|
let attachmentUploadMimeTypes = [];
|
|
let attachmentUploadSize = 0;
|
|
|
|
function parseNonNegativeInt(value, fallback = 0) {
|
|
const parsed = Number.parseInt(value, 10);
|
|
if (!Number.isFinite(parsed) || parsed < 0) {
|
|
return fallback;
|
|
}
|
|
return parsed;
|
|
}
|
|
|
|
export async function getAttachmentUploadMaxBytes() {
|
|
try {
|
|
const settings = await AttachmentStorageSettings.findOneAsync({});
|
|
const configuredLimit = settings?.limitSettings?.attachmentsUploadMaxBytes;
|
|
if (Number.isFinite(configuredLimit) && configuredLimit >= 0) {
|
|
return configuredLimit;
|
|
}
|
|
|
|
// Backward compatibility: respect existing uploadSettings.maxFileSize if present.
|
|
const legacySettingLimit = settings?.uploadSettings?.maxFileSize;
|
|
if (Number.isFinite(legacySettingLimit) && legacySettingLimit >= 0) {
|
|
return legacySettingLimit;
|
|
}
|
|
} catch (error) {
|
|
if (process.env.DEBUG === 'true') {
|
|
console.warn('Could not load attachment upload limit from settings:', error);
|
|
}
|
|
}
|
|
|
|
return attachmentUploadSize;
|
|
}
|
|
|
|
const attachmentBucket = createBucket('attachments');
|
|
|
|
// Compute storage path:
|
|
// - Docker (WRITABLE_PATH=/data): /data/files/attachments
|
|
// - Snap (WRITABLE_PATH=$SNAP_COMMON/files): $SNAP_COMMON/files/attachments
|
|
const basePath = process.env.WRITABLE_PATH || process.cwd();
|
|
const endsWithFiles = isFilesRoot(basePath);
|
|
const storagePath = endsWithFiles
|
|
? path.join(basePath, 'attachments')
|
|
: path.join(basePath, 'files', 'attachments');
|
|
|
|
if (process.env.ATTACHMENTS_UPLOAD_MIME_TYPES) {
|
|
attachmentUploadMimeTypes = process.env.ATTACHMENTS_UPLOAD_MIME_TYPES.split(',');
|
|
attachmentUploadMimeTypes = attachmentUploadMimeTypes.map(value => value.trim());
|
|
}
|
|
|
|
if (process.env.ATTACHMENTS_UPLOAD_MAX_SIZE) {
|
|
attachmentUploadSize = parseNonNegativeInt(process.env.ATTACHMENTS_UPLOAD_MAX_SIZE, 0);
|
|
}
|
|
|
|
if (process.env.ATTACHMENTS_UPLOAD_EXTERNAL_PROGRAM) {
|
|
attachmentUploadExternalProgram = process.env.ATTACHMENTS_UPLOAD_EXTERNAL_PROGRAM;
|
|
|
|
if (!attachmentUploadExternalProgram.includes("{file}")) {
|
|
attachmentUploadExternalProgram = undefined;
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// File store strategy factory
|
|
// ---------------------------------------------------------------------------
|
|
|
|
export const fileStoreStrategyFactory = new FileStoreStrategyFactory(
|
|
AttachmentStoreStrategyFilesystem, storagePath,
|
|
AttachmentStoreStrategyGridFs, attachmentBucket,
|
|
AttachmentStoreStrategyCloud,
|
|
Attachments,
|
|
);
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Assign server-only FilesCollection callbacks
|
|
// ---------------------------------------------------------------------------
|
|
|
|
Attachments.storagePath = function () {
|
|
return fileStoreStrategyFactory.storagePath;
|
|
};
|
|
|
|
// UploadBleed: the upload pipeline inserts server-side, past the allow rules,
|
|
// so this is where an upload is authorized - on every chunk, after the shared
|
|
// file-name sanitizing (models/attachments.js). The decision is
|
|
// models/lib/attachmentUploadAuth.js; a card attachment's board, list and
|
|
// swimlane are its card's, whatever the client sent (StampBleed).
|
|
const sharedOnBeforeUpload = Attachments.onBeforeUpload;
|
|
Attachments.onBeforeUpload = async function (file) {
|
|
const shared = sharedOnBeforeUpload ? sharedOnBeforeUpload.call(this, file) : true;
|
|
if (shared !== true) return shared;
|
|
const { uploadDecision } = require('/models/lib/attachmentUploadAuth');
|
|
const { canEditCardOrLinkedCard } = require('/server/lib/linkedCardPermission');
|
|
const { allowIsBoardMemberWithWriteAccess } = require('/server/lib/utils');
|
|
const Cards = require('/models/cards').default;
|
|
const meta = (file && file.meta && typeof file.meta === 'object') ? file.meta : {};
|
|
let uploadsBlocked = false;
|
|
try {
|
|
const settings = await AttachmentStorageSettings.findOneAsync({});
|
|
uploadsBlocked = settings?.limitSettings?.attachmentsUploadBlocked === true;
|
|
} catch (e) { /* unreadable setting: uploads stay as they were */ }
|
|
const card = this.userId && typeof meta.cardId === 'string' && meta.cardId
|
|
? await Cards.findOneAsync(meta.cardId) : null;
|
|
const board = this.userId && !meta.cardId && typeof meta.boardId === 'string' && meta.boardId
|
|
? await Boards.findOneAsync(meta.boardId) : null;
|
|
const decision = uploadDecision({
|
|
userId: this.userId,
|
|
meta,
|
|
card,
|
|
// Recorded below once per upload, not by the helper on every chunk.
|
|
mayEditCard: Boolean(card) && await canEditCardOrLinkedCard(this.userId, card, undefined, { recordDenial: false }),
|
|
board,
|
|
mayWriteBoard: Boolean(board) && allowIsBoardMemberWithWriteAccess(this.userId, board),
|
|
uploadsBlocked,
|
|
});
|
|
if (!decision.allow) {
|
|
// Recorded once per upload, at its start (chunk -1), not per chunk.
|
|
if (decision.key && this.chunkId === -1) {
|
|
try {
|
|
require('/server/lib/securityLog').record({
|
|
key: decision.key, action: 'blocked', source: 'upload:attachments',
|
|
userId: this.userId || undefined,
|
|
detail: `Upload refused: ${decision.reason}`,
|
|
});
|
|
} catch (e) { /* logging must never break the guard */ }
|
|
}
|
|
return decision.reason;
|
|
}
|
|
if (decision.stamp) {
|
|
file.meta = { ...meta, ...decision.stamp };
|
|
}
|
|
return true;
|
|
};
|
|
|
|
Attachments.onAfterUpload = async function (fileObj) {
|
|
// Detect and sanitize known exploits from the uploaded file IN PLACE, while it
|
|
// is still on the local filesystem staging area and BEFORE it is validated or
|
|
// moved to any final storage backend (filesystem final location, S3, GridFS...).
|
|
// Today this strips scripts, event handlers, javascript: URIs and XML
|
|
// DOCTYPE/ENTITY (XML loop / billion-laughs) constructs from SVG uploads, so SVG
|
|
// images upload safely instead of being rejected. General for every upload,
|
|
// regardless of the configured storage backend.
|
|
const { sanitizeUploadedFileExploits } = require('./lib/sanitizeUploadedFile');
|
|
if (await sanitizeUploadedFileExploits(fileObj)) {
|
|
try {
|
|
await Attachments.updateAsync(
|
|
{ _id: fileObj._id },
|
|
{ $set: { versions: fileObj.versions } },
|
|
);
|
|
} catch (error) {
|
|
console.error('[onAfterUpload] Failed to persist sanitized versions:', error);
|
|
}
|
|
// Log to Admin Panel / Problems: who uploaded, what was removed, when, where.
|
|
try {
|
|
await require('/server/lib/filenameSanitizeLog').logContentSanitized({
|
|
fileObj, source: 'attachmentUpload',
|
|
});
|
|
} catch (e) { /* best effort */ }
|
|
}
|
|
|
|
// Filename hardening for EVERY upload, on all storage backends:
|
|
// 1. Reject a filename that itself looks like an exploit (HTML/JS/XML/etc.).
|
|
// 2. Normalize + correct the stored name: URL-decode, fold confusable
|
|
// homoglyphs, remove invisible characters, strip exploit markup, and fix
|
|
// the EXTENSION to match the real detected file type — so double-clicking
|
|
// the downloaded file opens the right application — capped to a portable
|
|
// length. Uses the general, storage-agnostic detector (streams only a
|
|
// small header to WRITABLE_PATH/files/temp, then deletes it).
|
|
try {
|
|
const { filenameLooksLikeExploit, sanitizeUploadFileName } = require('./lib/uploadFileName');
|
|
if (filenameLooksLikeExploit(fileObj.name)) {
|
|
console.log('[onAfterUpload] rejected exploit-looking filename:', fileObj._id);
|
|
await Attachments.removeAsync(fileObj._id);
|
|
return;
|
|
}
|
|
const { detectStoredFileMime } = require('./lib/fileTypeCorrection');
|
|
const detectedMime = await detectStoredFileMime(fileObj, fileStoreStrategyFactory);
|
|
const originalName = fileObj.name;
|
|
const correctedName = sanitizeUploadFileName(originalName, detectedMime || fileObj.type);
|
|
if (correctedName && correctedName !== originalName) {
|
|
await rename(fileObj, correctedName, fileStoreStrategyFactory);
|
|
fileObj.name = correctedName;
|
|
// Log to Admin Panel / Problems: who uploaded, why, when, where.
|
|
try {
|
|
const { sanitizationReasons } = require('./lib/uploadFileName');
|
|
await require('/server/lib/filenameSanitizeLog').logFilenameSanitized({
|
|
fileObj, source: 'attachmentUpload',
|
|
reasons: sanitizationReasons(originalName, detectedMime || fileObj.type, correctedName),
|
|
from: originalName, to: correctedName,
|
|
});
|
|
} catch (e) { /* best effort */ }
|
|
}
|
|
} catch (error) {
|
|
console.error('[onAfterUpload] filename hardening failed:', error);
|
|
}
|
|
|
|
// Get default storage backend from settings
|
|
let defaultStorage = STORAGE_NAME_FILESYSTEM;
|
|
try {
|
|
const settings = await AttachmentStorageSettings.findOneAsync({});
|
|
if (settings) {
|
|
defaultStorage = settings.getDefaultStorage();
|
|
}
|
|
} catch (error) {
|
|
console.warn('Could not get attachment storage settings, using default:', error);
|
|
}
|
|
|
|
// Set initial storage to filesystem (temporary)
|
|
Object.keys(fileObj.versions).forEach(versionName => {
|
|
fileObj.versions[versionName].storage = STORAGE_NAME_FILESYSTEM;
|
|
});
|
|
|
|
this._now = new Date();
|
|
await Attachments.updateAsync({ _id: fileObj._id }, { $set: { "versions": fileObj.versions, "uploadedAtOstrio": this._now } });
|
|
|
|
// Use selected storage backend or copy storage if specified
|
|
let storageDestination = fileObj.meta.copyStorage || defaultStorage;
|
|
|
|
// Validate EVERY upload while its bytes are on the local staging filesystem.
|
|
// The filesystem destination used to skip this block entirely, while only
|
|
// GridFS/cloud migrations were checked.
|
|
const fileObjId = fileObj._id;
|
|
// Do not hold Meteor-Files' completion hook open while scanning. Its client
|
|
// waits for this hook before completing the upload UI, and the stored record
|
|
// is reliably queryable once this deferred task starts.
|
|
Meteor.defer(async () => {
|
|
try {
|
|
const currentFileObj = await ReactiveCache.getAttachment(fileObjId);
|
|
if (!currentFileObj) return;
|
|
const effectiveUploadMaxBytes = await getAttachmentUploadMaxBytes();
|
|
const isValid = await isFileValid(
|
|
currentFileObj,
|
|
attachmentUploadMimeTypes,
|
|
effectiveUploadMaxBytes,
|
|
attachmentUploadExternalProgram,
|
|
);
|
|
if (!isValid) {
|
|
await Attachments.removeAsync(fileObjId);
|
|
return;
|
|
}
|
|
|
|
// Only migrate if the destination is different from filesystem.
|
|
if (storageDestination !== STORAGE_NAME_FILESYSTEM) {
|
|
const fileObjAfterValidation = await ReactiveCache.getAttachment(fileObjId);
|
|
if (fileObjAfterValidation) {
|
|
moveToStorage(fileObjAfterValidation, storageDestination, fileStoreStrategyFactory);
|
|
}
|
|
}
|
|
} catch (error) {
|
|
console.error('[onAfterUpload] Error during validation and storage migration:', error);
|
|
}
|
|
});
|
|
|
|
// Every new attachment gets its SHA-256 and its plain search text, in the
|
|
// background, and an "added" row in the card history carrying that hash
|
|
// (server/lib/attachmentContentIndex.js). This only builds the search index
|
|
// and the check - it does not change how the attachment is displayed.
|
|
Meteor.defer(async () => {
|
|
try {
|
|
const { indexNewAttachment } = require('/server/lib/attachmentContentIndex');
|
|
await indexNewAttachment(fileObjId);
|
|
} catch (error) {
|
|
// Search indexing must never break the upload.
|
|
console.error('[onAfterUpload] Attachment content indexing failed:', error);
|
|
}
|
|
});
|
|
};
|
|
|
|
Attachments.interceptDownload = function (http, fileObj, versionName) {
|
|
const ret = fileStoreStrategyFactory.getFileStrategy(fileObj, versionName).interceptDownload(http, this.cacheControl);
|
|
return ret;
|
|
};
|
|
|
|
Attachments.onAfterRemove = function (filesInput) {
|
|
const files = normalizeRemovedFiles(filesInput);
|
|
// #6898: Meteor-Files unlinks the version paths itself after this hook
|
|
// (it returns nothing, so the default unlink runs), so this is where a
|
|
// removed file's integrity baseline is forgotten.
|
|
forgetIntegrityBaselinesOfFiles(files);
|
|
|
|
files.forEach(fileObj => {
|
|
if (!fileObj || !fileObj.versions) {
|
|
return;
|
|
}
|
|
|
|
Object.keys(fileObj.versions).forEach(versionName => {
|
|
fileStoreStrategyFactory.getFileStrategy(fileObj, versionName).onAfterRemove();
|
|
});
|
|
});
|
|
};
|
|
|
|
// We authorize the attachment download either:
|
|
// - if the board is public, everyone (even unconnected) can download it
|
|
// - if the board is private, only board members can download it, and an
|
|
// assigned-only member only the files of cards assigned to them
|
|
// (AssignedBleed, GHSA-3cgr-47wm-9cc9)
|
|
// Note: ostrio:files v3.x uses `await this.protected.call(...)` in _checkAccess,
|
|
// so this function can be async and use findOneAsync for Meteor 3.x compatibility.
|
|
Attachments.protected = async function (fileObj) {
|
|
// file may have been deleted already again after upload validation failed
|
|
if (!fileObj) {
|
|
return false;
|
|
}
|
|
const board = await Boards.findOneAsync(fileObj.meta.boardId);
|
|
if (!board) {
|
|
return false;
|
|
}
|
|
// #3249: an 'instance' board is readable by any signed-in user.
|
|
if (readableWithoutMembership(board.permission, !!this.userId)) {
|
|
return true;
|
|
}
|
|
if (!board.hasMember(this.userId)) return false;
|
|
return require('/server/lib/assignedOnlyAttachments')
|
|
.mayReadBoardAttachment(board, this.userId, fileObj, 'attachments:protected');
|
|
};
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Backward compatibility methods (override client stubs)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
Attachments.getAttachmentWithBackwardCompatibility = getAttachmentWithBackwardCompatibility;
|
|
Attachments.getAttachmentsWithBackwardCompatibility = getAttachmentsWithBackwardCompatibility;
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Meteor methods
|
|
// ---------------------------------------------------------------------------
|
|
|
|
Meteor.methods({
|
|
// Validate image URL to prevent SVG-based DoS attacks
|
|
validateImageUrl(imageUrl) {
|
|
check(imageUrl, String);
|
|
|
|
if (!imageUrl) {
|
|
return { valid: false, reason: 'Empty URL' };
|
|
}
|
|
|
|
// Block SVG files and data URIs
|
|
if (imageUrl.endsWith('.svg') || imageUrl.startsWith('data:image/svg')) {
|
|
if (process.env.DEBUG === 'true') {
|
|
console.warn('Blocked potentially malicious SVG image URL:', imageUrl);
|
|
}
|
|
return { valid: false, reason: 'SVG images are blocked for security reasons' };
|
|
}
|
|
|
|
// Block data URIs that could contain malicious content
|
|
if (imageUrl.startsWith('data:')) {
|
|
if (process.env.DEBUG === 'true') {
|
|
console.warn('Blocked data URI image URL:', imageUrl);
|
|
}
|
|
return { valid: false, reason: 'Data URIs are blocked for security reasons' };
|
|
}
|
|
|
|
// Validate URL format
|
|
try {
|
|
const url = new URL(imageUrl);
|
|
// Only allow http and https protocols
|
|
if (!['http:', 'https:'].includes(url.protocol)) {
|
|
return { valid: false, reason: 'Only HTTP and HTTPS protocols are allowed' };
|
|
}
|
|
} catch (e) {
|
|
return { valid: false, reason: 'Invalid URL format' };
|
|
}
|
|
|
|
return { valid: true };
|
|
},
|
|
async moveAttachmentToStorage(fileObjId, storageDestination) {
|
|
check(fileObjId, String);
|
|
check(storageDestination, String);
|
|
|
|
if (!this.userId) {
|
|
throw new Meteor.Error('not-authorized', 'You must be logged in.');
|
|
}
|
|
|
|
const user = await ReactiveCache.getUser(this.userId);
|
|
if (!user || !user.isAdmin) {
|
|
throw new Meteor.Error('not-authorized', 'Admin access required.');
|
|
}
|
|
|
|
const fileObj = await ReactiveCache.getAttachment(fileObjId);
|
|
if (!fileObj) {
|
|
throw new Meteor.Error('attachment-not-found', 'Attachment not found');
|
|
}
|
|
|
|
const board = await ReactiveCache.getBoard(fileObj.meta?.boardId);
|
|
if (!board || !board.isVisibleBy({ _id: this.userId })) {
|
|
throw new Meteor.Error('not-authorized', 'You do not have access to this board.');
|
|
}
|
|
|
|
// Allowlist storage destinations
|
|
const allowedDestinations = ['fs', 'gridfs', 's3', 'azure', 'gcs', 'webdav'];
|
|
if (!allowedDestinations.includes(storageDestination)) {
|
|
throw new Meteor.Error('invalid-storage-destination', 'Invalid storage destination');
|
|
}
|
|
|
|
moveToStorage(fileObj, storageDestination, fileStoreStrategyFactory);
|
|
},
|
|
async renameAttachment(fileObjId, newName) {
|
|
check(fileObjId, String);
|
|
check(newName, String);
|
|
|
|
const currentUserId = this.userId;
|
|
if (!currentUserId) {
|
|
throw new Meteor.Error('not-authorized', 'User must be logged in');
|
|
}
|
|
|
|
const fileObj = await ReactiveCache.getAttachment(fileObjId);
|
|
if (!fileObj) {
|
|
throw new Meteor.Error('file-not-found', 'Attachment not found');
|
|
}
|
|
|
|
// Verify the user has permission to modify this attachment
|
|
const board = await ReactiveCache.getBoard(fileObj.meta?.boardId);
|
|
if (!board) {
|
|
throw new Meteor.Error('board-not-found', 'Board not found');
|
|
}
|
|
|
|
requireBoardMutation(currentUserId, board, 'renameAttachment', Meteor);
|
|
// ListLockBulkBleed (ListLockAttachBleed's sibling): a rename is a write on
|
|
// the card, so the card's list may refuse it (#4527). The card's own board
|
|
// decides. The card's screen offers a rename, so a refusal is not recorded.
|
|
const card = fileObj.meta?.cardId ? await ReactiveCache.getCard(fileObj.meta.cardId) : null;
|
|
if (card) {
|
|
await require('/server/lib/listPermissionGate').assertListsWritable(currentUserId,
|
|
await ReactiveCache.getBoard(card.boardId), [card.listId]);
|
|
}
|
|
|
|
// FileNameBleed, regressed (2023-02-21 to 2026-10-02): the server check
|
|
// added by the original fix was deleted in "Try to fix build errors", and
|
|
// only the client refused markup in a new name - so a direct method call
|
|
// stored it. Display paths escape it today; the name is refused here
|
|
// anyway, and every other name is stored cleaned, as an upload's is.
|
|
const { filenameLooksLikeExploit } = require('./lib/uploadFileName');
|
|
if (filenameLooksLikeExploit(newName)) {
|
|
try {
|
|
require('/server/lib/securityLog').record({
|
|
key: 'file.name', action: 'blocked', source: 'renameAttachment', userId: currentUserId,
|
|
detail: 'An attachment rename carried markup or a path.',
|
|
});
|
|
} catch (e) { /* logging must never break the guard */ }
|
|
throw new Meteor.Error('invalid-filename', 'This file name is not allowed.');
|
|
}
|
|
const { cleanFileName } = require('/imports/lib/fileNameDisplay');
|
|
const cleanName = cleanFileName(newName);
|
|
if (!cleanName) throw new Meteor.Error('invalid-filename', 'This file name is not allowed.');
|
|
|
|
await rename(fileObj, cleanName, fileStoreStrategyFactory);
|
|
},
|
|
async validateAttachment(fileObjId) {
|
|
check(fileObjId, String);
|
|
|
|
if (!this.userId) {
|
|
throw new Meteor.Error('not-authorized', 'You must be logged in.');
|
|
}
|
|
|
|
const fileObj = await ReactiveCache.getAttachment(fileObjId);
|
|
if (!fileObj) {
|
|
throw new Meteor.Error('attachment-not-found', 'Attachment not found');
|
|
}
|
|
|
|
const board = await ReactiveCache.getBoard(fileObj.meta?.boardId);
|
|
if (!board || !board.isVisibleBy({ _id: this.userId })) {
|
|
throw new Meteor.Error('not-authorized', 'You do not have access to this board.');
|
|
}
|
|
|
|
// MoveStorageBleed sibling (2026-10-27 regression audit): seeing the board
|
|
// was enough, and a file that fails the CURRENT upload rules - a type or a
|
|
// size an admin has since disallowed - is removed for good. So anybody who
|
|
// could see a board, a public one included, could delete its attachments.
|
|
// Only who may change the attachment's card (or write its board, for a
|
|
// board's own image), or a site admin, validates now. No WeKan client calls
|
|
// this method - validateAttachmentAndMoveToStorage does, for an admin - so
|
|
// a refusal is an attempt and is recorded.
|
|
const user = await ReactiveCache.getUser(this.userId);
|
|
if (!(user && user.isAdmin)) {
|
|
const { canEditCardOrLinkedCard } = require('/server/lib/linkedCardPermission');
|
|
const { allowIsBoardMemberWithWriteAccess } = require('/server/lib/utils');
|
|
const card = fileObj.meta?.cardId ? await ReactiveCache.getCard(fileObj.meta.cardId) : null;
|
|
const mayChange = card
|
|
? await canEditCardOrLinkedCard(this.userId, card, undefined, { recordDenial: false })
|
|
: allowIsBoardMemberWithWriteAccess(this.userId, board);
|
|
if (!mayChange) {
|
|
try {
|
|
require('/server/lib/securityLog').record({
|
|
key: 'authz.attachment-validate', action: 'blocked', source: 'ddp:validateAttachment',
|
|
userId: this.userId,
|
|
detail: 'Asked to validate - and so possibly delete - an attachment the caller cannot change.',
|
|
});
|
|
} catch (e) { /* logging must never break the guard */ }
|
|
throw new Meteor.Error('not-authorized', 'You cannot change this attachment.');
|
|
}
|
|
}
|
|
|
|
const effectiveUploadMaxBytes = await getAttachmentUploadMaxBytes();
|
|
const isValid = await isFileValid(fileObj, attachmentUploadMimeTypes, effectiveUploadMaxBytes, attachmentUploadExternalProgram);
|
|
|
|
if (!isValid) {
|
|
await Attachments.removeAsync(fileObjId);
|
|
}
|
|
},
|
|
async validateAttachmentAndMoveToStorage(fileObjId, storageDestination) {
|
|
check(fileObjId, String);
|
|
check(storageDestination, String);
|
|
|
|
if (!this.userId) {
|
|
throw new Meteor.Error('not-authorized', 'You must be logged in.');
|
|
}
|
|
|
|
const user = await ReactiveCache.getUser(this.userId);
|
|
if (!user || !user.isAdmin) {
|
|
throw new Meteor.Error('not-authorized', 'Admin access required.');
|
|
}
|
|
|
|
const fileObj = await ReactiveCache.getAttachment(fileObjId);
|
|
if (!fileObj) {
|
|
throw new Meteor.Error('attachment-not-found', 'Attachment not found');
|
|
}
|
|
|
|
const board = await ReactiveCache.getBoard(fileObj.meta?.boardId);
|
|
if (!board || !board.isVisibleBy({ _id: this.userId })) {
|
|
throw new Meteor.Error('not-authorized', 'You do not have access to this board.');
|
|
}
|
|
|
|
// Allowlist storage destinations
|
|
const allowedDestinations = ['fs', 'gridfs', 's3', 'azure', 'gcs', 'webdav'];
|
|
if (!allowedDestinations.includes(storageDestination)) {
|
|
throw new Meteor.Error('invalid-storage-destination', 'Invalid storage destination');
|
|
}
|
|
|
|
await Meteor.callAsync('validateAttachment', fileObjId);
|
|
|
|
const fileObjAfter = await ReactiveCache.getAttachment(fileObjId);
|
|
|
|
// The move runs after the method returns. It used to re-enter
|
|
// moveAttachmentToStorage from Meteor.defer, where there is no method
|
|
// invocation and so no userId: that method's login check refused it every
|
|
// time, and the file never moved. Every check it makes - admin, the board
|
|
// visible, the destination allowlisted - was made above, so the deferred
|
|
// step moves the file itself, as the upload path does.
|
|
if (fileObjAfter) {
|
|
Meteor.defer(() => Promise.resolve(moveToStorage(fileObjAfter, storageDestination, fileStoreStrategyFactory))
|
|
.catch(error => console.error('[validateAttachmentAndMoveToStorage] move failed:', error)));
|
|
}
|
|
},
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Startup
|
|
// ---------------------------------------------------------------------------
|
|
|
|
Meteor.startup(async () => {
|
|
await ensureIndex(Attachments, { 'meta.cardId': 1 });
|
|
// The board publication now publishes all of a board's attachments with one cursor
|
|
// on the denormalized meta.boardId (replacing a per-card N+1, #6480); index it so
|
|
// that board-level query is not a full collection scan.
|
|
await ensureIndex(Attachments, { 'meta.boardId': 1 });
|
|
// The Files report pages every attachment by name (server/publications/attachments.js),
|
|
// so that sort - and the count beside it - is an index scan, not a scan of the
|
|
// whole collection plus an in-memory sort.
|
|
await ensureIndex(Attachments, { name: 1 });
|
|
|
|
// Ensure standard GridFS index on attachments.chunks for efficient chunk lookups.
|
|
// Without this, queries like find({files_id: ObjectId}) do full collection scans.
|
|
const db = MongoInternals.defaultRemoteCollectionDriver().mongo.db;
|
|
const chunksCollection = db.collection('attachments.chunks');
|
|
try {
|
|
await chunksCollection.createIndex({ files_id: 1, n: 1 }, { unique: true });
|
|
} catch (e) {
|
|
// Index already exists, which is fine — skip the error.
|
|
if (e.code !== 86) throw e;
|
|
}
|
|
|
|
const sp = fileStoreStrategyFactory.storagePath;
|
|
if (!fs.existsSync(sp)) {
|
|
console.log("create storagePath because it doesn't exist: " + sp);
|
|
fs.mkdirSync(sp, { recursive: true });
|
|
}
|
|
|
|
// Build the configured cloud storage adapters (S3/Azure/GCS) from settings.
|
|
await refreshCloudStorageFromSettings();
|
|
});
|