fix(docsync): switches that did not switch off, a webhook nobody could authenticate, and a counter that only grew

More from the audit, each checked against the code before it was touched.

The webhook obeyed neither the Documents addon nor the app_settings kill
switch, so "switch document sync off" stopped the poll while every provider
holding a webhook carried on driving full runs. Both are now read on arrival
and again when the debounce timer fires, so a switch thrown mid-window still
takes effect.

Nextcloud's subscription registered its secret under `X-TREK-Docsync-Signature`
while the endpoint reads `x-trek-docsync-secret`: the subscription existed, the
calls arrived, and every one of them was dropped for carrying no secret the
controller could find. The two names now agree, and the test pins the one the
endpoint actually reads.

A WebDAV create was an unconditional PUT, so a name already taken upstream was
silently overwritten — two trips bound to one folder, or a `receipt.pdf` a
person put there by hand, is enough. Creates now send `If-None-Match: *`.

The per-item retry bookkeeping was stuck at both ends: the backoff was computed
at step 1 every time, so three of the curve's four steps were unreachable, and
the attempt counter only ever grew, which shelved a row that failed once a
month after six months of otherwise healthy syncing. A successful pass now
clears it, which is what makes the limit mean six failures in a row.

Also: a manual run on an orphaned binding is refused with 409 (its credential
belongs to somebody no longer on the trip, and the scheduler already refuses
it, so the button was a way around that); a document deleted while a run is in
flight is no longer uploaded anyway; a path-shaped WebDAV id containing `..` is
rejected instead of addressing a file outside the bound folder; and Papra's
multipart part header no longer takes an unescaped media type, which a CR could
end early.

Client: three writes in useDocSync swallowed their failure into `void` call
sites, a load failure blanked the panel to "no providers available" whatever
the cause, and overlapping loads let the slowest response win. Writes now
report, only 403/404 blanks the panel, and a generation stamp keeps the newest
answer. The dead lastRun state went with them.
This commit is contained in:
Maurice
2026-09-19 00:31:13 +02:00
parent 4fa06c3483
commit 7237a1881d
14 changed files with 692 additions and 50 deletions
@@ -16,6 +16,8 @@ vi.mock('../../../../src/db/database', () => ({
import { DocSyncWebhookController } from '../../../../src/nest/doc-sync/doc-sync-webhook.controller';
import type { DocSyncConfigService, LinkRow } from '../../../../src/nest/doc-sync/doc-sync-config.service';
import type { DocSyncService } from '../../../../src/nest/doc-sync/doc-sync.service';
import type { AddonsService } from '../../../../src/nest/addons/addons.service';
import type { DatabaseService } from '../../../../src/nest/database/database.service';
/**
* The webhook endpoint, with both services stubbed.
@@ -69,6 +71,15 @@ const config = {
webhookSecret: vi.fn(() => SECRET),
};
const settings = new Map<string, string>();
const addons = { isAddonEnabled: vi.fn(() => true) };
const db = {
get: vi.fn((_sql: string, key?: unknown) => {
const value = settings.get(String(key));
return value === undefined ? undefined : { value };
}),
};
const sync = {
syncLink: vi.fn(async (_link: LinkRow) => ({ state: 'ok', pulled: 0, pushed: 0, conflicts: 0, missing: 0 })),
};
@@ -76,6 +87,8 @@ const sync = {
const controller = new DocSyncWebhookController(
config as unknown as DocSyncConfigService,
sync as unknown as DocSyncService,
addons as unknown as AddonsService,
db as unknown as DatabaseService,
);
/** Only what the handler reads: headers, the parsed body, and the raw bytes. */
@@ -105,6 +118,8 @@ function papraReq(payload: string, signature: string, sent = payload): Request {
beforeEach(() => {
vi.clearAllMocks();
vi.useFakeTimers();
settings.clear();
addons.isAddonEnabled.mockReturnValue(true);
config.getLinkByToken.mockImplementation((token: string) => (token === 'tok-live' ? link() : undefined));
config.getLink.mockImplementation((id: number) => (id === 4 ? link() : undefined));
config.webhookSecret.mockReturnValue(SECRET);
@@ -320,3 +335,39 @@ describe('a burst of nudges', () => {
expect(sync.syncLink).not.toHaveBeenCalled();
});
});
/**
* The switches an admin expects to mean "off".
*
* The scheduler obeys both the Documents addon and the app_settings kill
* switch; the webhook obeyed neither, so switching document sync off stopped
* the poll while every provider holding a webhook carried on driving full runs.
*/
describe('the admin switches', () => {
it('does nothing while the Documents addon is off', () => {
addons.isAddonEnabled.mockReturnValue(false);
expect(controller.nudge('tok-live', makeReq({ 'x-trek-docsync-secret': SECRET }))).toEqual({ received: true });
settle();
expect(sync.syncLink).not.toHaveBeenCalled();
});
it('does nothing while the kill switch is set', () => {
settings.set('docsync_sync_enabled', 'false');
controller.nudge('tok-live', makeReq({ 'x-trek-docsync-secret': SECRET }));
settle();
expect(sync.syncLink).not.toHaveBeenCalled();
});
it('drops a scheduled run when the addon goes off inside the window', () => {
controller.nudge('tok-live', makeReq({ 'x-trek-docsync-secret': SECRET }));
addons.isAddonEnabled.mockReturnValue(false);
settle();
expect(sync.syncLink).not.toHaveBeenCalled();
});
it('runs normally while both are on', () => {
controller.nudge('tok-live', makeReq({ 'x-trek-docsync-secret': SECRET }));
settle();
expect(sync.syncLink).toHaveBeenCalledTimes(1);
});
});