Require current revisions on board, list and swimlane REST edits

Require If-Match for board titles and view settings, label deletion and list and swimlane updates. Send the revision on reads and use it in the Python CLI on the affected commands.

Thanks to rmb82 and xet7 !
This commit is contained in:
Lauri Ojansivu committed 2026-12-02 16:00:55 +02:00
1 parent 95cf88110c
commit d140a37813
11 files changed
+260 -47

No files matched your search

+14 -3
View File
@@ -154,6 +154,17 @@ If *nix: chmod +x api.py => ./api.py users
python3 api.py editallteamfeature FIELD true|false # Set one team feature on ALL teams
"""
def put_with_revision(url, resource_url, headers, **options):
current = requests.get(resource_url, headers=headers)
current.raise_for_status()
revision = current.headers.get('ETag')
if not revision:
raise RuntimeError('The resource response did not include a revision (ETag)')
response = requests.put(url, headers={**headers, 'If-Match': revision}, **options)
response.raise_for_status()
return response
if arguments == 0:
print(syntax)
sys.exit()
@@ -449,7 +460,7 @@ if arguments >= 4:
print(edlist)
headers = {'Accept': 'application/json', 'Authorization': 'Bearer {}'.format(apikey)}
put_data = {'title': '{}'.format(newlisttitle)}
requests.put(edlist, data=put_data, headers=headers)
put_with_revision(edlist, edlist, headers, data=put_data)
print("=== EDIT LIST ===\n")
body = requests.get(edlist, headers=headers)
data2 = body.text.replace('}', "}\n")
@@ -475,7 +486,7 @@ if arguments >= 4:
print(edlist)
headers = {'Accept': 'application/json', 'Authorization': 'Bearer {}'.format(apikey)}
put_data = {'color': '{}'.format(newcolor)}
requests.put(edlist, data=put_data, headers=headers)
put_with_revision(edlist, edlist, headers, data=put_data)
print("=== EDIT LIST COLOR ===\n")
body = requests.get(edlist, headers=headers)
data2 = body.text.replace('}', "}\n")
@@ -606,7 +617,7 @@ if arguments == 3:
post_data = {'title': boardtitle}
body = requests.put(edboardtitle, json=post_data, headers=headers)
body = put_with_revision(edboardtitle, wekanurl + apiboards + boardid, headers, json=post_data)
print("=== EDIT BOARD TITLE ===\n")
#body = requests.get(edboardtitle, headers=headers)
data2 = body.text.replace('}',"}\n")
+1
View File
@@ -137,6 +137,7 @@ function effectiveListWidth(list) {
fixedEnabled,
fixedWidth,
sharedWidth: list.width,
defaultWidth: ReactiveCache.getBoard(list.boardId)?.defaultListWidth,
personalMode,
personalWidth,
});
+21 -3
View File
@@ -397,6 +397,22 @@ view), the two defaults resolved (missing or unknown reads as
dropped, missing views appended in default order). `keys` lists the known
view keys.
## Revisions for REST writes
A board, list, swimlane, or Board View settings response includes a
`revision` string and an `ETag` header. Copy the full header value,
including its quotes, into `If-Match` on these writes:
- `PUT /api/boards/:boardId/title` and
`DELETE /api/boards/:boardId/labels/:labelId` use the board's revision.
- `PUT /api/boards/:boardId/boardViewSettings` uses the settings response.
- `PUT /api/boards/:boardId/lists/:listId` and
`PUT /api/boards/:boardId/swimlanes/:swimlaneId` use the item read.
A missing header returns `428 revision-required`. An invalid header returns
`400 invalid-revision`. A stale revision returns `412 revision-conflict`.
Read the resource again and reconcile any intervening changes before resending.
## Get the Board View settings
| URL | Requires Auth (board access) | HTTP Method |
| :--- | :--- | :--- |
@@ -430,8 +446,9 @@ Result (shortened):
| `/api/boards/:boardId/boardViewSettings` | `yes` | `PUT` |
The body is any subset of `boardViewSettings`, `defaultPublicBoardView`,
`defaultPrivateBoardView` and `boardViewOrder`; keys not sent are left as
they are. The rules are the popup's:
`defaultPrivateBoardView`, `boardViewOrder`, `autoWidth` and
`defaultListWidth`. Omitted fields keep their current values.
`defaultListWidth` is a whole number of pixels with a minimum of 200.
- a default is always shown on its side: setting a default also ticks its
*Show* box, and hiding a side's current default is refused with `400` -
@@ -443,11 +460,12 @@ they are. The rules are the popup's:
- `boardViewOrder` is normalised so the menu lists every view exactly once:
the keys sent come first in the order given, the rest follow in default
order;
- a body with none of the four keys is a `400`.
- a body with none of the supported keys is a `400`.
```bash
curl -H "Authorization: Bearer t7iYB86mXoLfP_XsMegxF41oKT7iiA9lDYiKVtXcctl" \
-H "Content-type:application/json" \
-H "If-Match: $ETAG" \
-X PUT \
http://localhost:3000/api/boards/BOARDID/boardViewSettings \
-d '{
+1
View File
@@ -1505,6 +1505,7 @@ Boards.attachSchema(
type: Boolean,
defaultValue: false,
},
defaultListWidth: { type: Number, optional: true, min: 200 },
autoWidth: {
/**
* Shared (per-board) auto-width for all lists (#6409). When true, lists
+13
View File
@@ -434,6 +434,8 @@ function defaultBoardViewModifier(board, view, visibility) {
// through defaultBoardView() so an unknown or missing default reads as
// Swimlanes, and the order made whole - the same decisions the UI renders
// with, so the API never reports a state the menu would not show.
const { normalizeListWidth, parseListWidthInput } = require('./listWidth');
function boardViewSettingsSnapshot(board) {
const boardViewSettings = {};
VIEW_KEYS.forEach(view => {
@@ -444,6 +446,8 @@ function boardViewSettingsSnapshot(board) {
});
return {
boardViewSettings,
autoWidth: board?.autoWidth === true,
defaultListWidth: normalizeListWidth(board?.defaultListWidth),
defaultPublicBoardView: defaultBoardView(board, 'public'),
defaultPrivateBoardView: defaultBoardView(board, 'private'),
boardViewOrder: normalizeBoardViewOrder(board && board.boardViewOrder),
@@ -542,6 +546,15 @@ function boardViewSettingsRequest(board, input) {
merge({ boardViewOrder: normalizeBoardViewOrder(order) });
}
if (Object.hasOwn(input, 'autoWidth')) {
if (![true, false, 'true', 'false'].includes(input.autoWidth)) return { error: 'autoWidth must be a boolean' };
$set.autoWidth = input.autoWidth === true || input.autoWidth === 'true';
}
if (Object.hasOwn(input, 'defaultListWidth')) {
const width = parseListWidthInput(String(input.defaultListWidth));
if (width === null) return { error: 'defaultListWidth must be a whole number of pixels, at least 200' };
$set.defaultListWidth = width;
}
return { $set };
}
+3 -1
View File
@@ -76,13 +76,15 @@ function resolveListWidth(options) {
fixedEnabled = false,
fixedWidth = null,
sharedWidth = null,
defaultWidth = DEFAULT_LIST_WIDTH,
personalMode = false,
personalWidth = null,
} = options || {};
if (fixedEnabled) {
return normalizeListWidth(fixedWidth);
}
const shared = normalizeListWidth(sharedWidth);
const fallback = normalizeListWidth(defaultWidth);
const shared = sharedWidth === DEFAULT_LIST_WIDTH ? fallback : normalizeListWidth(sharedWidth, fallback);
if (!personalMode) {
return shared;
}
+62
View File
@@ -0,0 +1,62 @@
import { createHash } from 'node:crypto';
import { EJSON } from 'meteor/ejson';
import { sendJsonResult } from '/server/apiMiddleware';
function revisionOf(document) {
const serialized = EJSON.stringify(document, { canonical: true });
const digest = createHash('sha256').update(serialized).digest('hex');
return BigInt('0x' + digest).toString();
}
export function sendRevision(res, document, data = document) {
const revision = revisionOf(document);
res.setHeader('ETag', '"' + revision + '"');
sendJsonResult(res, { code: 200, data: { ...data, revision } });
}
export function checkRevision(req, res, document) {
const value = req.headers['if-match'];
if (value === undefined) {
sendJsonResult(res, { code: 428, data: { error: 'Revision required', code: 'revision-required' } });
return false;
}
const match = typeof value === 'string' && /^"([1-9]\d{0,77})"$/.exec(value);
if (!match) {
sendJsonResult(res, { code: 400, data: { error: 'If-Match must contain a quoted revision', code: 'invalid-revision' } });
return false;
}
if (match[1] !== revisionOf(document)) {
sendRevisionConflict(res);
return false;
}
return true;
}
export function sendRevisionConflict(res) {
sendJsonResult(res, { code: 412, data: { error: 'Revision no longer matches', code: 'revision-conflict' } });
}
// Include known but previously absent fields. An editor adding a field between
// the read and the write changes the revision just as replacing a value does.
export function revisionSelector(collection, scope, document) {
const keys = new Set([
...Object.keys(document),
...Object.keys(collection.simpleSchema()?.schema() || {}).map(key => key.split('.')[0]),
]);
const conditions = [scope];
for (const key of keys) {
if (key === '_id' || key.startsWith('$') || key.includes('.')) continue;
if (Object.hasOwn(document, key)) {
conditions.push({ [key]: { $eq: document[key], ...(document[key] === null ? { $exists: true } : {}) } });
} else {
conditions.push({ [key]: { $exists: false } });
}
}
return { $and: conditions };
}
export async function writeRevision(res, collection, scope, document, modifier, options) {
const matched = await collection.direct.updateAsync(revisionSelector(collection, scope, document), modifier, options);
if (!matched) sendRevisionConflict(res);
return Boolean(matched);
}
+49 -12
View File
@@ -1,3 +1,4 @@
import { sendRevision, checkRevision, writeRevision, revisionSelector, sendRevisionConflict } from '/server/lib/restRevision';
import { Meteor } from 'meteor/meteor';
import { WebApp } from 'meteor/webapp';
import { DDP } from 'meteor/ddp';
@@ -1077,11 +1078,9 @@ WebApp.handlers.get('/api/boards/:boardId', async function(req, res) {
const paramBoardId = req.params.boardId;
await Authentication.checkBoardAccess(req.userId, paramBoardId);
const board = await ReactiveCache.getBoard(paramBoardId);
sendJsonResult(res, {
code: 200,
data: board,
});
const board = await Boards.findOneAsync(paramBoardId, { transform: null });
Authentication.checkBoardExists(board);
sendRevision(res, board);
} catch (error) {
sendJsonResult(res, publicErrorData(error));
}
@@ -1302,7 +1301,11 @@ WebApp.handlers.put('/api/boards/:boardId/title', async function(req, res) {
await Authentication.checkBoardAdmin(req.userId, boardId);
const title = req.body.title;
await Boards.direct.updateAsync({ _id: boardId }, { $set: { title } });
const scope = { _id: boardId };
const board = await Boards.findOneAsync(scope, { transform: null });
Authentication.checkBoardExists(board);
if (!checkRevision(req, res, board)) return;
if (!await writeRevision(res, Boards, scope, board, { $set: { title } })) return;
sendJsonResult(res, {
code: 200,
@@ -1376,6 +1379,39 @@ WebApp.handlers.put('/api/boards/:boardId/labels', async function(req, res) {
}
});
/**
* @operation delete_board_label
* @tag Boards
* @summary Remove a label from the board and its cards
* @param {string} boardId the board ID
* @param {string} labelId the label ID
* @response 200 {_id: string} Label removed
* @response 404 Label not found on this board
* @response 412 Board revision no longer matches
* @response 428 Board revision required
*/
WebApp.handlers.delete('/api/boards/:boardId/labels/:labelId', async function(req, res) {
try {
const { boardId, labelId } = req.params;
await Authentication.checkBoardAdmin(req.userId, boardId);
const scope = { _id: boardId };
const board = await Boards.findOneAsync(scope, { transform: null });
Authentication.checkBoardExists(board);
if (!checkRevision(req, res, board)) return;
if (!board.labels?.some(label => label._id === labelId)) {
sendJsonResult(res, { code: 404, data: { error: 'Label not found on this board' } });
return;
}
// Use the ordinary update hook also used by Board.removeLabel.
const matched = await Boards.updateAsync(revisionSelector(Boards, scope, board), { $pull: { labels: { _id: labelId } } });
if (!matched) return sendRevisionConflict(res);
sendJsonResult(res, { code: 200, data: { _id: labelId } });
} catch (error) {
sendJsonResult(res, publicErrorData(error));
}
});
// Issue #3062: read/update the board-level "Card Settings" (the allows* toggles
// shown under Board Settings that control which fields/badges appear on cards and
// minicards). Board-level only — per-user presentation settings are out of scope.
@@ -2004,13 +2040,13 @@ WebApp.handlers.get('/api/boards/:boardId/boardViewSettings', async function(req
try {
const paramBoardId = req.params.boardId;
await Authentication.checkBoardAccess(req.userId, paramBoardId);
const board = await ReactiveCache.getBoard(paramBoardId);
const board = await Boards.findOneAsync(paramBoardId, { transform: null });
if (!board) {
sendJsonResult(res, { code: 404, data: { error: 'Board not found' } });
return;
}
const { boardViewSettingsSnapshot } = require('/models/lib/boardViewSettings');
sendJsonResult(res, { code: 200, data: boardViewSettingsSnapshot(board) });
sendRevision(res, board, boardViewSettingsSnapshot(board));
} catch (error) {
sendJsonResult(res, publicErrorData(error));
}
@@ -2044,11 +2080,12 @@ WebApp.handlers.put('/api/boards/:boardId/boardViewSettings', async function(req
try {
const paramBoardId = req.params.boardId;
await Authentication.checkBoardAdmin(req.userId, paramBoardId);
const board = await ReactiveCache.getBoard(paramBoardId);
const board = await Boards.findOneAsync(paramBoardId, { transform: null });
if (!board) {
sendJsonResult(res, { code: 404, data: { error: 'Board not found' } });
return;
}
if (!checkRevision(req, res, board)) return;
const input = Object.assign({}, req.body || {});
// Form-encoded callers send JSON text for the structured fields.
for (const key of ['boardViewSettings', 'boardViewOrder']) {
@@ -2070,9 +2107,9 @@ WebApp.handlers.put('/api/boards/:boardId/boardViewSettings', async function(req
sendJsonResult(res, { code: 400, data: { error: 'no recognized board view settings in body' } });
return;
}
await Boards.updateAsync(paramBoardId, { $set: result.$set });
const updated = await ReactiveCache.getBoard(paramBoardId);
sendJsonResult(res, { code: 200, data: boardViewSettingsSnapshot(updated) });
if (!await writeRevision(res, Boards, { _id: paramBoardId }, board, { $set: result.$set })) return;
const updated = await Boards.findOneAsync(paramBoardId, { transform: null });
sendRevision(res, updated, boardViewSettingsSnapshot(updated));
} catch (error) {
sendJsonResult(res, publicErrorData(error));
}
+32 -17
View File
@@ -1,3 +1,4 @@
import { sendRevision, checkRevision, writeRevision } from '/server/lib/restRevision';
import { Meteor } from 'meteor/meteor';
import { WebApp } from 'meteor/webapp';
import { check, Match } from 'meteor/check';
@@ -898,36 +899,47 @@ WebApp.handlers.get('/api/boards/:boardId/lists/:listId', async function(req, re
const paramBoardId = req.params.boardId;
const paramListId = req.params.listId;
await Authentication.checkBoardAccess(req.userId, paramBoardId);
const list = await ReactiveCache.getList({
const list = await Lists.findOneAsync({
_id: paramListId,
boardId: paramBoardId,
archived: false,
deletedAt: null,
});
}, { transform: null });
// 404, not a 200 with an empty body (#6862).
if (!list) {
sendJsonResult(res, { code: 404, data: { error: 'List not found' } });
return;
}
sendJsonResult(res, { code: 200, data: list });
sendRevision(res, list);
} catch (error) {
sendJsonResult(res, publicErrorData(error));
}
});
async function restListSwimlane(body, boardId) {
if (!Object.hasOwn(body || {}, 'swimlaneId')) return undefined;
const { swimlaneId } = body;
if (swimlaneId === '' || swimlaneId === null) return '';
if (typeof swimlaneId === 'string' && await ReactiveCache.getSwimlane({ _id: swimlaneId, boardId, archived: false })) {
return swimlaneId;
}
throw new Meteor.Error(400, 'swimlaneId must identify an active swimlane on this board');
}
WebApp.handlers.post('/api/boards/:boardId/lists', async function(req, res) {
try {
const paramBoardId = req.params.boardId;
await Authentication.checkBoardWriteAccess(req.userId, paramBoardId);
const board = await ReactiveCache.getBoard(paramBoardId);
const defaultSwimlane = board.getDefaultSwimlineAsync
? await board.getDefaultSwimlineAsync()
: board.getDefaultSwimline();
const requested = await restListSwimlane(req.body, paramBoardId);
const defaultSwimlane = requested === undefined
? (board.getDefaultSwimlineAsync ? await board.getDefaultSwimlineAsync() : board.getDefaultSwimline())
: null;
const id = await Lists.insertAsync({
title: req.body.title,
boardId: paramBoardId,
sort: board.lists().length,
swimlaneId: req.body.swimlaneId || defaultSwimlane?._id,
swimlaneId: requested ?? defaultSwimlane?._id,
});
sendJsonResult(res, { code: 200, data: { _id: id } });
} catch (error) {
@@ -940,18 +952,16 @@ WebApp.handlers.put('/api/boards/:boardId/lists/:listId', async function(req, re
const paramBoardId = req.params.boardId;
const paramListId = req.params.listId;
let updated = false;
await Authentication.checkBoardWriteAccess(req.userId, paramBoardId);
await Authentication.checkBoardWriteAccess(req.userId, paramBoardId);
const list = await ReactiveCache.getList({
_id: paramListId,
boardId: paramBoardId,
archived: false,
});
const scope = { _id: paramListId, boardId: paramBoardId, archived: false };
const list = await Lists.findOneAsync(scope, { transform: null });
if (!list) {
sendJsonResult(res, { code: 404, data: { error: 'List not found' } });
return;
}
if (!checkRevision(req, res, list)) return;
// #5396: edit a list's title/color (and starred/wipLimit) via the REST API,
// like cards can be edited. The color is validated with normalizeListColor
@@ -972,12 +982,17 @@ WebApp.handlers.put('/api/boards/:boardId/lists/:listId', async function(req, re
await Authentication.checkBoardAdmin(req.userId, paramBoardId);
}
const swimlaneId = await restListSwimlane(req.body, paramBoardId);
if (swimlaneId !== undefined) set.swimlaneId = swimlaneId;
if (Object.keys(set).length > 0) {
await Lists.direct.updateAsync(
{ _id: paramListId, boardId: paramBoardId, archived: false },
{ $set: set },
);
if (!await writeRevision(res, Lists, scope, list, { $set: set }, { removeEmptyStrings: false })) return;
updated = true;
if (swimlaneId && swimlaneId !== list.swimlaneId) {
await Cards.updateAsync(
{ boardId: paramBoardId, listId: paramListId, swimlaneId: { $ne: swimlaneId } },
{ $set: { swimlaneId } }, { multi: true },
);
}
}
if (!updated) {
+9 -11
View File
@@ -1,3 +1,4 @@
import { sendRevision, checkRevision, writeRevision } from '/server/lib/restRevision';
import { Meteor } from 'meteor/meteor';
import { WebApp } from 'meteor/webapp';
import { check } from 'meteor/check';
@@ -179,17 +180,17 @@ WebApp.handlers.get('/api/boards/:boardId/swimlanes/:swimlaneId', async function
const paramSwimlaneId = req.params.swimlaneId;
await Authentication.checkBoardAccess(req.userId, paramBoardId);
const swimlane = await ReactiveCache.getSwimlane({
const swimlane = await Swimlanes.findOneAsync({
_id: paramSwimlaneId,
boardId: paramBoardId,
archived: false,
});
}, { transform: null });
// 404, not a 200 with an empty body (#6862).
if (!swimlane) {
sendJsonResult(res, { code: 404, data: { error: 'Swimlane not found' } });
return;
}
sendJsonResult(res, { code: 200, data: swimlane });
sendRevision(res, swimlane);
} catch (error) {
sendJsonResult(res, publicErrorData(error));
}
@@ -231,17 +232,14 @@ WebApp.handlers.put('/api/boards/:boardId/swimlanes/:swimlaneId', async function
const paramSwimlaneId = req.params.swimlaneId;
await Authentication.checkBoardWriteAccess(req.userId, paramBoardId);
await ReactiveCache.getBoard(paramBoardId);
const swimlane = await ReactiveCache.getSwimlane({
_id: paramSwimlaneId,
boardId: paramBoardId,
});
const scope = { _id: paramSwimlaneId, boardId: paramBoardId };
const swimlane = await Swimlanes.findOneAsync(scope, { transform: null });
if (!swimlane) {
throw new Meteor.Error('not-found', 'Swimlane not found');
}
await Swimlanes.direct.updateAsync(
{ _id: paramSwimlaneId },
{ $set: { title: req.body.title } },
);
if (!checkRevision(req, res, swimlane)) return;
if (!await writeRevision(res, Swimlanes, scope, swimlane, { $set: { title: req.body.title } })) return;
sendJsonResult(res, {
code: 200,
data: {
@@ -0,0 +1,55 @@
'use strict';
const { test, expect } = require('../fixtures');
const db = require('../helpers/db');
test('board, list and swimlane REST writes require a current resource revision', async ({ request, user, board }) => {
const boardUrl = '/api/boards/' + board.boardId;
const lane = db.findOne('swimlanes', { boardId: board.boardId });
const auth = { Authorization: 'Bearer ' + user.token };
const endpoints = [
[boardUrl, boardUrl + '/title'],
[boardUrl + '/lists/' + board.listIds[0]],
[boardUrl + '/swimlanes/' + lane._id],
];
for (const [url, writeUrl = url] of endpoints) {
const read = await request.get(url, { headers: auth });
expect(read.status()).toBe(200);
const original = await read.json();
const etag = read.headers().etag;
expect(etag).toBe('"' + original.revision + '"');
expect((await request.put(writeUrl, { headers: auth, data: { title: 'Missing revision' } })).status()).toBe(428);
expect((await request.put(writeUrl, {
headers: { ...auth, 'If-Match': '*' }, data: { title: 'Invalid revision' },
})).status()).toBe(400);
const results = await Promise.all(['One', 'Two'].map(title =>
request.put(writeUrl, { headers: { ...auth, 'If-Match': etag }, data: { title } })));
expect(results.map(response => response.status()).sort()).toEqual([200, 412]);
const updated = await (await request.get(url, { headers: auth })).json();
expect(updated.title).toBe(results[0].ok() ? 'One' : 'Two');
expect(updated.revision).not.toBe(original.revision);
}
});
test('revision-protected settings and label deletion update only the expected board', async ({ request, user, board }) => {
const boardUrl = '/api/boards/' + board.boardId;
const settings = boardUrl + '/boardViewSettings';
const label = { _id: db.uid('label'), name: 'Remove me', color: 'green' };
const card = db.findOne('cards', { boardId: board.boardId });
db.updateOne('boards', { _id: board.boardId }, { $push: { labels: label } });
db.updateOne('cards', { _id: card._id }, { $push: { labelIds: label._id } });
const auth = { Authorization: 'Bearer ' + user.token };
const before = await request.get(settings, { headers: auth });
expect(before.ok()).toBe(true);
const old = before.headers().etag;
const adjusted = await request.put(settings, {
headers: { ...auth, 'If-Match': old }, data: { autoWidth: true, defaultListWidth: 350 },
});
expect(adjusted.status()).toBe(200);
expect(await adjusted.json()).toMatchObject({ autoWidth: true, defaultListWidth: 350 });
const labelUrl = boardUrl + '/labels/' + label._id;
expect((await request.delete(labelUrl, { headers: { ...auth, 'If-Match': old } })).status()).toBe(412);
const current = adjusted.headers().etag;
expect((await request.delete(labelUrl, { headers: { ...auth, 'If-Match': current } })).status()).toBe(200);
await expect.poll(() => db.findOne('cards', { _id: card._id }).labelIds).not.toContain(label._id);
});