Files
wekan/server/migrations/fixAllFileUrls.js
T
Lauri Ojansivu ebcd02be6f Hall of Fame regression audit: every fixed vulnerability still fixed, siblings of six of them closed.
Every Hall of Fame vulnerability without a test naming it (24 names, 30
advisories) was checked against the current source. No fix had been
reverted. Looking for the same mistake elsewhere found siblings:

- FloppyBleed: the fs-path-heal upgrade step joined an attachment's
  stored name into candidate paths as-is; a record a client inserted
  named ../../../etc/passwd made the next upgrade copy that file into
  storage - an arbitrary file read. Only the name's last component is
  used now; the bulk move limits a legacy name's extension the same way.
- FilePathBleed (GHSA-g6vm-7757-pr88): the insert guard looked only
  inside versions; with versions left out ostrio:files falls back to a
  top-level path, which removing the record deletes and validation
  reads. A client's top-level path is refused for attachments and
  avatars, recorded by the existing canaries.
- MoveStorageBleed: validateAttachment, which deletes a file failing the
  current upload rules, was open to anybody who could see the board, a
  public one included. Only who may change the file, or a site admin,
  validates now; a refusal is recorded (authz.attachment-validate).
- HookUrlBleed / IntegrationBleed: the REST reads of a board's
  integrations gave the webhook URL - whose path is its secret - to
  every member reading the board; non-admins get what the publication
  gives them.
- AttachmentMigrationBleed: four migration methods answered any
  logged-in user about any board, deleteDuplicateEmptyLists.getStatus
  with a private board's list titles; they require a visible board and
  record refusals (authz.migration-board).
- LegacyAttachBleed (GHSA-xcxp-hx9w-q5q9) and MimeStorageBleed
  (GHSA-rv5g-5p4g-3v89): the legacy route judged a name dangerous only
  for .svg, the response policy missed x-javascript, ecmascript, xsl and
  +xml types, and the sniffers missed <tag/onx= handlers.

OIDCBleed refusals are now recorded in Admin Panel / Problems too. New
suites name the vulnerabilities they guard, existing ones name the
advisories they already covered, and tests/securityRegressionCoverage
counts 128 of 137 published vulnerabilities with a named test (was 125).

Thanks to xet7 !
2026-10-27 16:28:12 +02:00

313 lines
9.4 KiB
JavaScript

/**
* Fix All File URLs Migration
* Ensures all attachment and avatar URLs are universal and work regardless of ROOT_URL and PORT settings
*/
import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';
import { ReactiveCache } from '/imports/reactiveCache';
import { assertMigrationBoardVisible } from '/server/lib/migrationBoardAccess';
import Boards from '/models/boards';
import Users from '/models/users';
import Attachments from '/models/attachments';
import Avatars from '/models/avatars';
import Cards from '/models/cards';
import { generateUniversalAttachmentUrl, generateUniversalAvatarUrl, cleanFileUrl, extractFileIdFromUrl, isUniversalFileUrl } from '/models/lib/universalUrlGenerator';
class FixAllFileUrlsMigration {
constructor() {
this.name = 'fixAllFileUrls';
this.version = 1;
}
/**
* Check if migration is needed for a board
*/
async needsMigration(boardId) {
// Get all users who are members of this board
const board = await ReactiveCache.getBoard(boardId);
if (!board || !board.members) {
return false;
}
const memberIds = board.members.map(m => m.userId);
// Check for problematic avatar URLs for board members
const users = await ReactiveCache.getUsers({ _id: { $in: memberIds } });
for (const user of users) {
if (user.profile && user.profile.avatarUrl) {
const avatarUrl = user.profile.avatarUrl;
if (this.hasProblematicUrl(avatarUrl)) {
return true;
}
}
}
// Check for problematic attachment URLs on this board
const cards = await ReactiveCache.getCards({ boardId });
const cardIds = cards.map(c => c._id);
const attachments = await ReactiveCache.getAttachments({ cardId: { $in: cardIds } });
for (const attachment of attachments) {
if (attachment.url && this.hasProblematicUrl(attachment.url)) {
return true;
}
}
return false;
}
/**
* Check if a URL has problematic patterns
*/
hasProblematicUrl(url) {
if (!url) return false;
// Check for auth parameters
if (url.includes('auth=false') || url.includes('brokenIsFine=true')) {
return true;
}
// Check for absolute URLs with domains
if (url.startsWith('http://') || url.startsWith('https://')) {
return true;
}
// Check for ROOT_URL dependencies
if (Meteor.isServer && process.env.ROOT_URL) {
try {
const rootUrl = new URL(process.env.ROOT_URL);
if (rootUrl.pathname && rootUrl.pathname !== '/' && url.includes(rootUrl.pathname)) {
return true;
}
} catch (e) {
// Ignore URL parsing errors
}
}
// Check for non-universal file URLs
if (url.includes('/cfs/files/') && !isUniversalFileUrl(url, 'attachment') && !isUniversalFileUrl(url, 'avatar')) {
return true;
}
return false;
}
/**
* Execute the migration for a board
*/
async execute(boardId) {
let filesFixed = 0;
let errors = [];
console.log(`Starting universal file URL migration for board ${boardId}...`);
try {
// Fix avatar URLs for board members
const avatarFixed = await this.fixAvatarUrls(boardId);
filesFixed += avatarFixed;
// Fix attachment URLs for board cards
const attachmentFixed = await this.fixAttachmentUrls(boardId);
filesFixed += attachmentFixed;
// Fix card attachment references
const cardFixed = await this.fixCardAttachmentUrls(boardId);
filesFixed += cardFixed;
} catch (error) {
console.error('Error during file URL migration for board', boardId, ':', error);
errors.push(error.message);
}
console.log(`Universal file URL migration completed for board ${boardId}. Fixed ${filesFixed} file URLs.`);
return {
success: errors.length === 0,
filesFixed,
errors,
changes: [`Fixed ${filesFixed} file URLs for this board`]
};
}
/**
* Fix avatar URLs in user profiles for board members
*/
async fixAvatarUrls(boardId) {
const board = await ReactiveCache.getBoard(boardId);
if (!board || !board.members) {
return 0;
}
const memberIds = board.members.map(m => m.userId);
const users = await ReactiveCache.getUsers({ _id: { $in: memberIds } });
let avatarsFixed = 0;
for (const user of users) {
if (user.profile && user.profile.avatarUrl) {
const avatarUrl = user.profile.avatarUrl;
if (this.hasProblematicUrl(avatarUrl)) {
try {
// Extract file ID from URL
const fileId = extractFileIdFromUrl(avatarUrl, 'avatar');
let cleanUrl;
if (fileId) {
// Generate universal URL
cleanUrl = generateUniversalAvatarUrl(fileId);
} else {
// Clean existing URL
cleanUrl = cleanFileUrl(avatarUrl, 'avatar');
}
if (cleanUrl && cleanUrl !== avatarUrl) {
// Update user's avatar URL
await Users.updateAsync(user._id, {
$set: {
'profile.avatarUrl': cleanUrl,
modifiedAt: new Date()
}
});
avatarsFixed++;
if (process.env.DEBUG === 'true') {
console.log(`Fixed avatar URL for user ${user.username}: ${avatarUrl} -> ${cleanUrl}`);
}
}
} catch (error) {
console.error(`Error fixing avatar URL for user ${user.username}:`, error);
}
}
}
}
return avatarsFixed;
}
/**
* Fix attachment URLs in attachment records for this board
*/
async fixAttachmentUrls(boardId) {
const cards = await ReactiveCache.getCards({ boardId });
const cardIds = cards.map(c => c._id);
const attachments = await ReactiveCache.getAttachments({ cardId: { $in: cardIds } });
let attachmentsFixed = 0;
for (const attachment of attachments) {
// Check if attachment has URL field that needs fixing
if (attachment.url && this.hasProblematicUrl(attachment.url)) {
try {
const fileId = attachment._id;
const cleanUrl = generateUniversalAttachmentUrl(fileId);
if (cleanUrl && cleanUrl !== attachment.url) {
// Update attachment URL
await Attachments.updateAsync(attachment._id, {
$set: {
url: cleanUrl,
modifiedAt: new Date()
}
});
attachmentsFixed++;
if (process.env.DEBUG === 'true') {
console.log(`Fixed attachment URL: ${attachment.url} -> ${cleanUrl}`);
}
}
} catch (error) {
console.error(`Error fixing attachment URL for ${attachment._id}:`, error);
}
}
}
return attachmentsFixed;
}
/**
* Fix attachment URLs in the Attachments collection for this board
*/
async fixCardAttachmentUrls(boardId) {
const cards = await ReactiveCache.getCards({ boardId });
const cardIds = cards.map(c => c._id);
const attachments = await ReactiveCache.getAttachments({ cardId: { $in: cardIds } });
let attachmentsFixed = 0;
for (const attachment of attachments) {
if (attachment.url && this.hasProblematicUrl(attachment.url)) {
try {
const fileId = attachment._id || extractFileIdFromUrl(attachment.url, 'attachment');
const cleanUrl = fileId ? generateUniversalAttachmentUrl(fileId) : cleanFileUrl(attachment.url, 'attachment');
if (cleanUrl && cleanUrl !== attachment.url) {
// Update attachment with fixed URL
await Attachments.updateAsync(attachment._id, {
$set: {
url: cleanUrl,
modifiedAt: new Date()
}
});
attachmentsFixed++;
if (process.env.DEBUG === 'true') {
console.log(`Fixed attachment URL ${attachment._id}`);
}
}
} catch (error) {
console.error(`Error fixing attachment URL:`, error);
}
}
}
return attachmentsFixed;
}
}
// Export singleton instance
export const fixAllFileUrlsMigration = new FixAllFileUrlsMigration();
// Meteor methods
Meteor.methods({
async 'fixAllFileUrls.execute'(boardId) {
check(boardId, String);
if (!this.userId) {
throw new Meteor.Error('not-authorized', 'You must be logged in');
}
// Check if user is board admin
const board = await ReactiveCache.getBoard(boardId);
if (!board) {
throw new Meteor.Error('board-not-found', 'Board not found');
}
const user = await ReactiveCache.getUser(this.userId);
if (!user) {
throw new Meteor.Error('user-not-found', 'User not found');
}
// Only board admins can run migrations
const isBoardAdmin = board.members && board.members.some(
member => member.userId === this.userId && member.isAdmin
);
if (!isBoardAdmin && !user.isAdmin) {
throw new Meteor.Error('not-authorized', 'Only board administrators can run migrations');
}
return await fixAllFileUrlsMigration.execute(boardId);
},
async 'fixAllFileUrls.needsMigration'(boardId) {
check(boardId, String);
// AttachmentMigrationBleed: a board the caller can see, not any board.
await assertMigrationBoardVisible(this.userId, boardId, 'ddp:fixAllFileUrls.needsMigration');
return await fixAllFileUrlsMigration.needsMigration(boardId);
}
});