diff --git a/models/importZip.js b/models/importZip.js index 8efb89c5d8..a15b82837c 100644 --- a/models/importZip.js +++ b/models/importZip.js @@ -198,11 +198,16 @@ runOnServer(function () { const creator = new WekanCreator({ membersMode: req.query && req.query.membersMode, importFields: fields }); creator.attachmentStream = attachmentStream; const { DDP } = require('meteor/ddp'); - const tracked = require('/server/importRuns').trackImport({ userId: user._id, source: 'wekan-zip', creator, - execute: () => creator.create(doc, null) }); + // The import STARTS inside the importer's method context, not merely is + // awaited in it: trackImport runs execute() at once, and everything it + // reaches - the people the file names becoming the importer + // (membersMode=me), the author of a row with none - asks Meteor.userId(), + // which outside a context threw, so every .zip that became a new board + // answered 500 (tests/importZipUserContext.test.cjs). const newBoardId = await DDP._CurrentMethodInvocation.withValue( { userId: user._id, isSimulation: false, connection: null }, - () => tracked.promise, + () => require('/server/importRuns').trackImport({ userId: user._id, source: 'wekan-zip', creator, + execute: () => creator.create(doc, null) }).promise, ); answer(200, { ok: true, boardId: newBoardId }); return; diff --git a/server/trelloApiImport.js b/server/trelloApiImport.js index 99b410ab95..3c6b3effcf 100644 --- a/server/trelloApiImport.js +++ b/server/trelloApiImport.js @@ -856,8 +856,16 @@ async function runJob(jobId) { }); const creator = new TrelloCreator({ membersMapping }); creator.attachmentStream = trelloAttachmentStreamer(creds.key, creds.token); - const newBoardId = await trackImport({ userId: job.userId, source: 'trello-api', creator, - execute: () => creator.create(sanitized, null) }).promise; + // As the user who asked for the import: TrelloCreator asks + // Meteor.userId() for the board's owner and for every Trello member + // nobody is mapped to, and a job has no method context of its own - the + // import threw before writing anything (tests/importZipUserContext.test.cjs). + const { DDP } = require('meteor/ddp'); + const newBoardId = await DDP._CurrentMethodInvocation.withValue( + { userId: job.userId, isSimulation: false, connection: null }, + () => trackImport({ userId: job.userId, source: 'trello-api', creator, + execute: () => creator.create(sanitized, null) }).promise, + ); // The sanitized copy, like the creator above: the organization name is // stored as a workspace title, so it is imported text too. diff --git a/tests/importZipUserContext.test.cjs b/tests/importZipUserContext.test.cjs new file mode 100644 index 0000000000..85af449923 --- /dev/null +++ b/tests/importZipUserContext.test.cjs @@ -0,0 +1,68 @@ +'use strict'; +// An import STARTED outside a method context: every .zip that became a new board +// (POST /api/import/zip?newBoard=1 - All Boards / Import, and "Import many +// boards") answered 500, "Meteor.userId can only be invoked inside a method, +// publication, or WebApp endpoint". trackImport() runs execute() at once, so +// wrapping only the AWAIT of its promise in DDP._CurrentMethodInvocation.withValue +// came too late: the creator had already asked Meteor.userId() for the people +// the file names (membersMode=me) and for every row with no author. The Trello +// API import job had the same shape with no context at all. +// +// The fix starts trackImport INSIDE the context. This pins it for every caller: +// a trackImport() outside a Meteor method (models/import.js) has to be called +// from within a withValue / runAsUser callback. +// tests/playwright/specs/gitea-backup-wekan-import.e2e.js imports a .zip as a new +// board through the route itself. +// Run: node tests/importZipUserContext.test.cjs +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); + +const root = path.resolve(__dirname, '..'); +const SKIP = new Set(['node_modules', '_build', '.build', '.tools', '.meteor', 'tests', 'packages']); + +function files(dir, out = []) { + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP.has(entry.name) || entry.name.startsWith('_build')) continue; + const full = path.join(dir, entry.name); + if (entry.isDirectory()) files(full, out); + else if (entry.name.endsWith('.js')) out.push(full); + } + return out; +} + +// Inside a method: Meteor gives the context, nothing to wrap. +const IN_METHODS = new Set(['models/import.js']); +// The definition, which hands the call on to its library: not a caller. +const DEFINITION = new Set(['server/importRuns.js']); + +const callers = []; +for (const file of [...files(path.join(root, 'server')), ...files(path.join(root, 'models'))]) { + const rel = path.relative(root, file); + const text = fs.readFileSync(file, 'utf8'); + const re = /\btrackImport\(\{/g; + let m; + while ((m = re.exec(text))) { + if (/function\s+trackImport\s*\($/.test(text.slice(Math.max(0, m.index - 20), m.index + 12))) continue; + if (DEFINITION.has(rel)) continue; + callers.push(rel); + if (IN_METHODS.has(rel)) continue; + // The statement the call is part of: back to the previous `;` or `{` line end. + const before = text.slice(Math.max(0, m.index - 400), m.index); + const statement = before.slice(Math.max(before.lastIndexOf(';\n'), before.lastIndexOf('{\n')) + 1); + assert.ok(/(?:withValue|runAsUser)\([\s\S]*=>\s*(?:require\([^)]*\)\.)?$/.test(statement.trim()), + `${rel}: trackImport() is started outside a user context - wrap the CALL (not its promise) in ` + + `DDP._CurrentMethodInvocation.withValue or runAsUser:\n${statement.trim()}`); + } +} +assert.ok(callers.includes('models/importZip.js'), 'the .zip import is one of the callers'); +assert.ok(callers.includes('server/trelloApiImport.js'), 'the Trello API import is one of the callers'); + +// Negative: the old shape - a tracked import made first, its promise awaited in +// the context afterwards - is nowhere. +for (const file of [...files(path.join(root, 'server')), ...files(path.join(root, 'models'))]) { + const text = fs.readFileSync(file, 'utf8'); + assert.ok(!/withValue\([\s\S]{0,200}?=>\s*tracked\.promise/.test(text), + `${path.relative(root, file)}: awaits an import's promise in a context it was not started in`); +} +console.log(`importZipUserContext: ${callers.length} trackImport callers, each started in a user context`); diff --git a/tests/playwright/specs/gitea-backup-wekan-import.e2e.js b/tests/playwright/specs/gitea-backup-wekan-import.e2e.js new file mode 100644 index 0000000000..b32f01f9c1 --- /dev/null +++ b/tests/playwright/specs/gitea-backup-wekan-import.e2e.js @@ -0,0 +1,74 @@ +'use strict'; +// A Gitea backup restored into WeKan (gitea-patches mirror/common/gitea_backup.py, +// "Restore a backup into WeKan"): its WeKan .zip - wekan.json and +// attachments/- - becomes a new board through POST +// /api/import/zip?newBoard=1, with a card for each issue and pull request in +// Open, Closed or Merged, the comment, the label, and the issue's file. +// +// The .zip is made by gitea-patches' tests/lib/sample_backup.py, so the test +// checks what that script really writes; without the gitea-patches checkout +// under .tools/w the test is skipped. +const { test, expect } = require('../fixtures'); +const fs = require('node:fs'); +const path = require('node:path'); +const { execFileSync } = require('node:child_process'); +const db = require('../helpers/db'); + +const repo = path.resolve(__dirname, '../../..'); +const sample = path.join(repo, '.tools/w/gitea-patches/tests/lib/sample_backup.py'); + +test('a Gitea backup imports as a WeKan board, with its comments, labels and files', async ({ loggedInPage: page, user }) => { + test.skip(!fs.existsSync(sample), 'the gitea-patches checkout is not under .tools/w'); + test.setTimeout(120000); + const parent = process.env.TMPDIR || path.join(repo, '.tools/tmp'); + fs.mkdirSync(parent, { recursive: true }); + const work = fs.mkdtempSync(path.join(parent, 'gitea-backup-wekan-')); + let boardId; + try { + const zip = execFileSync('python3', ['-I', sample, work], { encoding: 'utf8' }).trim(); + const bytes = fs.readFileSync(zip); + const answer = await page.evaluate(async ({ base64, token }) => { + const body = Uint8Array.from(atob(base64), value => value.charCodeAt(0)); + const response = await fetch(`/api/import/zip?newBoard=1&membersMode=me&authToken=${encodeURIComponent(token)}`, { + method: 'POST', headers: { 'Content-Type': 'application/zip' }, body, + }); + return { status: response.status, body: await response.json() }; + }, { base64: bytes.toString('base64'), token: user.token }); + expect(answer.status).toBe(200); + boardId = answer.body.boardId; + expect(boardId).toBeTruthy(); + + const board = db.findOne('boards', { _id: boardId }); + expect(board.title).toBe('sample/proj'); + const lists = Object.fromEntries(db.find('lists', { boardId }).map(l => [l._id, l.title])); + const cards = db.find('cards', { boardId }); + expect(Object.fromEntries(cards.map(c => [c.title, lists[c.listId]]))).toEqual({ + '#1 Sample open issue': 'Open', '#2 Sample merged PR': 'Merged', '#3 Sample closed issue': 'Closed', + }); + const open = cards.find(c => c.title === '#1 Sample open issue'); + expect(open.description).toContain('Body of the issue'); + const bug = board.labels.find(l => l.name === 'bug'); + expect(bug && bug.color).toBe('red'); + expect(open.labelIds).toContain(bug._id); + const comments = db.find('card_comments', { cardId: open._id }); + expect(comments.map(c => c.text).join('\n')).toContain('Sample comment text'); + expect(comments[0].text).toContain('@bob'); + await expect.poll(() => db.find('attachments', { 'meta.cardId': open._id }).map(a => a.name)).toEqual(['notes.txt']); + + // Negative: the same file without its wekan.json is not a WeKan import. + const JSZip = require('jszip'); + const broken = new JSZip(); + broken.file('attachments/x-notes.txt', 'x'); + const refused = await page.evaluate(async ({ base64, token }) => { + const body = Uint8Array.from(atob(base64), value => value.charCodeAt(0)); + const response = await fetch(`/api/import/zip?newBoard=1&authToken=${encodeURIComponent(token)}`, { + method: 'POST', headers: { 'Content-Type': 'application/zip' }, body, + }); + return response.status; + }, { base64: (await broken.generateAsync({ type: 'nodebuffer' })).toString('base64'), token: user.token }); + expect(refused).toBe(400); + } finally { + if (boardId) db.cleanup({ boardIds: [boardId] }); + fs.rmSync(work, { recursive: true, force: true }); + } +});