Files
wekan/models/avatars.js
T
Lauri Ojansivu 0afb1336db SVG is uploaded and shown as an image: an attachment, a cover, a board background, an avatar.
Since JVN#74210258 (stored XSS) an SVG upload was refused and any stored
SVG was served as a download, so an SVG could not be a card's picture.
Every uploaded SVG is already sanitized on the server before it is
stored - no script, event handler, javascript: URI, foreignObject or
DOCTYPE/ENTITY XML loop (models/lib/sanitizeUploadedFile.js) - so the
refusal goes, for attachments and avatars.

Serving it inline is made safe in one place, server/lib/svgResponse.js,
used by every route that sends file bytes (universalFileServer.js for
attachments, avatars and legacy files, avatarServer.js,
legacyAttachments.js and httpStream.js): the WHOLE file is sanitized
again before it is sent, whatever is stored, and sent as image/svg+xml
under a Content-Security-Policy with default-src 'none' and sandbox, no
script, X-Frame-Options DENY and nosniff, so even opened directly as a
page it runs nothing. A download is sanitized too; a range request gets
the whole file; an SVG over 8 MB stays a sandboxed download. A file whose
active markup is removed on the way out is logged to Admin Panel /
Problems like the stream sanitizer's, and one removed at upload trips
the existing sanitize.dangerous-content canary.

tests/svgServing.test.cjs runs the real sanitizer on a crafted SVG
(script, onload, javascript:, DOCTYPE/ENTITY, foreignObject/iframe) and
checks the body and headers, the download, the oversized case, and that
no file-serving route in server/routes or httpStream.js sends bytes
without the SVG path, and that nothing else sends image/svg+xml;
tests/playwright/specs/svg-attachment.e2e.js uploads one, checks what is
served, that it shows in the card without running anything, and makes
it the cover and the board background.

Thanks to xet7 !
2026-10-25 06:32:25 +02:00

153 lines
5.6 KiB
JavaScript

import { Meteor } from 'meteor/meteor';
import { FilesCollection } from 'meteor/ostrio:files';
import { Random } from 'meteor/random';
const { safeUploadFileId } = require('/models/lib/uploadFileId');
const { isFilesRoot } = require('/models/lib/filesRoot');
import { generateUniversalAvatarUrl } from '/models/lib/universalUrlGenerator';
const { cleanFileName } = require('/imports/lib/fileNameDisplay');
const { filesize } = require('filesize');
const getTAPi18n = () => require('/imports/i18n').TAPi18n;
let avatarsUploadSize = 72000;
// Compute storage path:
// - Docker (WRITABLE_PATH=/data): /data/files/avatars
// - Snap (WRITABLE_PATH=$SNAP_COMMON/files): $SNAP_COMMON/files/avatars
const computeAvatarStoragePath = () => {
const basePath = process.env.WRITABLE_PATH || process.cwd();
const endsWithFiles = isFilesRoot(basePath);
if (endsWithFiles) {
// Snap: WRITABLE_PATH already includes /files
return basePath + '/avatars';
} else {
// Docker & Dev: append /files/avatars
return basePath + '/files/avatars';
}
};
const storagePath = Meteor.isServer ? computeAvatarStoragePath() : 'assets/app/uploads/avatars';
const Avatars = new FilesCollection({
debug: false, // Change to `true` for debugging
collectionName: 'avatars',
// 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,
// WeKan serves current and legacy avatars through its guarded canonical
// /cdn/storage/avatars route. Meteor-Files' broad middleware must not
// intercept that URL first and reject an authenticated legacy file.
downloadRoute: '/meteor-files-internal',
allowClientCode: true,
storagePath: storagePath,
namingFunction(opts) {
let filenameWithoutExtension = ""
let fileId = "";
if (opts?.name) {
// Client
filenameWithoutExtension = opts.name.replace(/(.+)\..+/, "$1");
fileId = opts.meta.fileId;
delete opts.meta.fileId;
} else if (opts?.file?.name) {
// Server
if (opts.file.extension) {
// A literal suffix, never a RegExp built from the uploaded name.
const name = opts.file.name;
const suffix = opts.file.extensionWithDot;
filenameWithoutExtension = name.endsWith(suffix) ? name.slice(0, -suffix.length) : name;
} else {
// file has no extension, so don't replace anything, otherwise the last character is removed (because extensionWithDot = '.')
filenameWithoutExtension = opts.file.name;
}
fileId = opts.fileId;
}
else {
// should never reach here
filenameWithoutExtension = Math.random().toString(36).slice(2);
fileId = Math.random().toString(36).slice(2);
}
// UploadPathBleed, avatar sibling (2026-10-02): the id is client-supplied
// and starts the on-disk name, so "../../x" wrote outside the store.
fileId = safeUploadFileId(fileId, { source: 'Avatars.namingFunction', fresh: () => Random.id(), isServer: Meteor.isServer });
// Strip shell metacharacters and path-traversal sequences from the
// user-supplied portion of the filename. The result is used as part of
// the on-disk path passed to external commands, so only safe characters
// (alphanumerics, hyphens, underscores, and dots) are kept.
const safeName = filenameWithoutExtension.replace(/[^a-zA-Z0-9_.\-]/g, '_');
const ret = fileId + "-original-" + safeName;
return ret;
},
sanitize(str, max, replacement) {
// Strip characters that are dangerous in shell contexts and filesystem paths.
return str.replace(/[^a-zA-Z0-9_.\-]/g, '_');
},
onBeforeUpload(file) {
// An avatar belongs to a signed-in user; nobody else uploads one.
if (!this.userId) return 'Please sign in to upload an avatar.';
file.name = cleanFileName(file && file.name) || 'image';
// 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.
if (file.size <= avatarsUploadSize && file.type.startsWith('image/')) {
return true;
}
return getTAPi18n().__('avatar-too-big', {size: filesize(avatarsUploadSize)});
},
});
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 Avatars.find({ _id: filesInput }).fetch();
}
if (filesInput && typeof filesInput === 'object') {
if (filesInput._id && (filesInput.versions || filesInput.userId)) {
return [filesInput];
}
return Avatars.find(filesInput).fetch();
}
return [];
}
// Export normalizeRemovedFiles and avatarsUploadSize setter for use in server file
export { normalizeRemovedFiles };
export function setAvatarsUploadSize(size) {
avatarsUploadSize = size;
}
// Override the link method to use universal URLs
if (Meteor.isClient) {
// Add custom link method to avatar documents
Avatars.collection.helpers({
link(version = 'original') {
// Use universal URL generator for consistent, URL-agnostic URLs
return generateUniversalAvatarUrl(this._id, version);
}
});
}
export default Avatars;