Files
wekan/models/attachments.js
T
Lauri Ojansivu b335c5df07 Attachments: a SHA-256 and plain search text for each, checked on every read, and searched by Filter, Search and Search All Boards.
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 !
2026-11-22 17:37:15 +02:00

232 lines
9.6 KiB
JavaScript

import { Meteor } from 'meteor/meteor';
import { Random } from 'meteor/random';
import { FilesCollection } from 'meteor/ostrio:files';
import { generateUniversalAttachmentUrl } from '/models/lib/universalUrlGenerator';
const { isFilesRoot } = require('/models/lib/filesRoot');
const { cleanFileName } = require('/imports/lib/fileNameDisplay');
// Pure helper: build the activity document for a newly added attachment.
// Kept side-effect free so it can be unit tested without a database.
// Mirrors the shape used for the 'deleteAttachment' activity, so card
// history rendering and member/subscriber notifications behave identically.
// see #5905
export function buildAttachmentAddedActivity(fileObj) {
const meta = (fileObj && fileObj.meta) || {};
return {
userId: fileObj && fileObj.userId,
type: 'card',
activityType: 'addAttachment',
attachmentId: fileObj && fileObj._id,
// preserve the name so notifications stay meaningful even after removal
attachmentName: fileObj && fileObj.name,
boardId: meta.boardId,
cardId: meta.cardId,
listId: meta.listId,
swimlaneId: meta.swimlaneId,
};
}
// XXX Enforce a schema for the Attachments FilesCollection
// see: https://github.com/VeliovGroup/Meteor-Files/wiki/Schema
// Compute storage path:
// - Docker (WRITABLE_PATH=/data): /data/files/attachments
// - Snap (WRITABLE_PATH=$SNAP_COMMON/files): $SNAP_COMMON/files/attachments
const computeAttachmentStoragePath = () => {
const basePath = process.env.WRITABLE_PATH || process.cwd();
const endsWithFiles = isFilesRoot(basePath);
if (endsWithFiles) {
// Snap: WRITABLE_PATH already includes /files
return basePath + '/attachments';
} else {
// Docker & Dev: append /files/attachments
return basePath + '/files/attachments';
}
};
const storagePath = Meteor.isServer ? computeAttachmentStoragePath() : 'assets/app/uploads/attachments';
const Attachments = new FilesCollection({
debug: false,
collectionName: 'attachments',
// CacheBleed (GHSA-w3qg-pf27-g68r): Meteor-Files' default is a public, one-year
// cache; this file is served only after an access check.
cacheControl: require('/models/lib/fileCacheHeaders').PRIVATE_FILE_CACHE_CONTROL,
allowClientCode: true,
storagePath: storagePath,
namingFunction(opts) {
let { fileId } = require('/models/lib/uploadFileId').uploadNameParts(opts);
// OLD:
//const ret = fileId + "-original-" + filenameWithoutExtension;
// NEW: Save file only with filename of ObjectID, not including filename.
// Fixes https://github.com/wekan/wekan/issues/4416#issuecomment-1510517168
//
// SECURITY (path traversal / arbitrary file write): fileId is
// client-supplied (opts.fileId on the server branch, opts.meta.fileId on
// the client one) and is used VERBATIM as the on-disk file name below -
// this.sanitize() just above in the upload pipeline already strips
// path-traversal/shell characters (see the comment on sanitize() below),
// but require the result to also look like the ObjectId WeKan itself
// generates, so a malformed or unexpected value can never reach the
// filesystem at all rather than merely losing its dangerous characters.
fileId = require('/models/lib/uploadFileId').safeUploadFileId(fileId, {
source: 'Attachments.namingFunction', fresh: () => Random.id(), isServer: Meteor.isServer });
const ret = fileId;
// remove fileId from meta, it was only stored there to have this information here in the namingFunction function
return ret;
},
sanitize(str, max, replacement) {
// SECURITY (path traversal / arbitrary file write): this used to be an
// identity function ("keep the original filename"), but ostrio:files
// never calls this.sanitize() on the human-readable file name - only on
// fileId/FSName, the tokens it uses to build the ON-DISK PATH before any
// containment check (server.js's DDP _Start/_Write methods and the HTTP
// __upload route all call `this.sanitize(opts.fileId, 20, 'a')` first).
// An identity sanitize let a client-supplied fileId like
// "../../../../tmp/pwn" flow straight through to the physical path.
// Restored to the same whitelist models/avatars.js already uses for the
// same tokens - file DISPLAY names are untouched, they are sanitized
// separately in onBeforeUpload below.
return (str || '').replace(/[^a-zA-Z0-9_.\-]/g, replacement || '_');
},
onBeforeUpload(file) {
// SECURITY: Sanitize filename to prevent path traversal attacks
if (file.name && typeof file.name === 'string') {
// Strip directory components (client-safe alternative to path.basename)
let safeName = file.name.split(/[\\/]/).pop();
// Remove null bytes
safeName = safeName.replace(/\0/g, '');
// Remove path traversal sequences (repeat until stable to avoid incomplete multi-character sanitization)
let previousSafeName;
do {
previousSafeName = safeName;
safeName = safeName.replace(/\.\.[\\/]/g, '');
} while (safeName !== previousSafeName);
safeName = safeName.replace(/^\.\.$/g, '');
safeName = safeName.trim();
// If sanitization changed the name, update it
if (safeName && safeName !== '.' && safeName !== '..' && safeName !== file.name) {
file.name = safeName;
} else if (!safeName || safeName === '.' || safeName === '..') {
file.name = 'unnamed';
}
// Apply the same plain-text and classic Amiga FFS 30-character policy
// before bytes leave the client. Content-derived extension correction is
// repeated authoritatively on the server after its bounded header sniff.
file.name = cleanFileName(file.name) || 'unnamed';
}
// SVG is allowed (#6802, maintainer decision 2026-10-25): every uploaded SVG
// is sanitized on the server before it is stored - no script, event handler,
// javascript: URI, foreignObject or DOCTYPE/ENTITY XML loop
// (models/lib/sanitizeUploadedFile.js) - and sanitized again whenever it is
// served, inline under a script-free sandbox (server/lib/svgResponse.js).
// It used to be refused here after JVN#74210258.
return true;
},
});
function normalizeRemovedFiles(filesInput) {
if (!filesInput) {
return [];
}
if (Array.isArray(filesInput)) {
return filesInput;
}
if (typeof filesInput.fetch === 'function') {
return filesInput.fetch();
}
if (Array.isArray(filesInput.files)) {
return filesInput.files;
}
if (typeof filesInput === 'string') {
return Attachments.find({ _id: filesInput }).fetch();
}
if (filesInput && typeof filesInput === 'object') {
if (filesInput._id && (filesInput.versions || filesInput.meta)) {
return [filesInput];
}
return Attachments.find(filesInput).fetch();
}
return [];
}
// Export normalizeRemovedFiles for use in server file
export { normalizeRemovedFiles };
// Backward compatibility stubs (overridden in attachments.server.js with real implementations)
Attachments.getAttachmentWithBackwardCompatibility = async () => null;
Attachments.getAttachmentsWithBackwardCompatibility = async () => [];
// Override Attachments.link to use universal short URLs and to bypass
// the `check(fileRef, Object)` inside the original which fails when fileRef is
// a collection-helpers class instance (not a plain object).
// Uses short URL format handled by universalFileServer.js.
if (Meteor.isClient) {
Attachments.link = function () {
let fileRef;
if (this && this._id) {
// Called as instance method: doc.link(version)
fileRef = this;
} else if (arguments[0] && arguments[0]._id) {
// Called as static from FileCursor: Attachments.link(fileRef, version)
fileRef = arguments[0];
} else {
return '';
}
return generateUniversalAttachmentUrl(fileRef._id);
};
}
// #5905: Notify card members/subscribers and record card history when a new
// attachment is uploaded. The 'deleteAttachment' activity is already created
// (via the store strategy's onAfterRemove during file removal), but the matching
// 'addAttachment' activity was never created during the upload flow. Create it
// here with a server-side collection insert hook, mirroring the original
// behaviour. The generic Activities after.insert hook (server/models/activities.js)
// then notifies card members + watchers, deduplicated, exactly as it does for
// every other card activity.
if (Meteor.isServer) {
Attachments.collection.after.insert((userId, doc) => {
// Skip attachments created during a board/card import: those are not
// user-driven uploads and should not generate notifications.
if (doc.meta && doc.meta.source === 'import') {
return;
}
// Lazy import to keep this out of the client bundle.
const Activities = require('/models/activities').default;
Activities.insertAsync(buildAttachmentAddedActivity(doc)).catch(error => {
console.error('Failed to insert addAttachment activity:', error);
});
});
}
// The slideshow's converted previews (server/lib/attachmentPreviewStore.js) are
// a cache of the file: they go with it.
if (Meteor.isServer) {
Attachments.collection.after.remove((userId, doc) => {
try {
require('/server/lib/attachmentPreviewStore').removePreviews(doc && doc._id);
} catch (error) {
console.error('Failed to remove attachment previews:', error);
}
// Its search text goes with it: a removed file is found by no search.
if (doc && doc._id) {
require('/server/lib/documentGif').DocumentPreviews.rawCollection().deleteMany({ attachmentId: doc._id })
.catch(error => console.error('Failed to remove attachment search text:', error));
}
});
}
export default Attachments;