From 787d8b2d37e2bac5f3c5f2b64db24d686b0e0ef6 Mon Sep 17 00:00:00 2001 From: Daniel Salazar Date: Wed, 25 Nov 2026 17:52:01 -0700 Subject: [PATCH 1/2] perf(metering): store a closed month's global total once; per-app aggregate off until it has a reader (#4776) * perf(metering): store a closed month's global total once; per-app aggregate off until it has a reader * perf(metering): a daily fleet job stores closed months' totals; shard deletion moves into it, off for now Reads no longer delete a closed month's shards. The job does, under its lease, behind MeteringService.DELETE_CLOSED_SHARDS (false): a version that sums the shards reports a deleted month as zero. --- doc/self-hosting.md | 3 + src/backend/services/jobs/systemJobs.test.ts | 6 + .../services/metering/MeteringService.test.ts | 168 ++++++++++++++++++ .../services/metering/MeteringService.ts | 149 +++++++++++++++- 4 files changed, 321 insertions(+), 5 deletions(-) diff --git a/doc/self-hosting.md b/doc/self-hosting.md index df2b1427a..e11dfe4d3 100644 --- a/doc/self-hosting.md +++ b/doc/self-hosting.md @@ -469,6 +469,9 @@ belong to, 3 by default. Set it to `0` to keep every month's records forever: Changing it, including to `0`, applies to records first written after the change; records already stamped keep their expiry. +The total across all accounts is the exception: once a month has ended, a +daily job stores its total as one record that never expires. + ### Captcha on signup / login Built-in proof-of-work captcha — no external service needed. diff --git a/src/backend/services/jobs/systemJobs.test.ts b/src/backend/services/jobs/systemJobs.test.ts index 89722d3e5..170b410a0 100644 --- a/src/backend/services/jobs/systemJobs.test.ts +++ b/src/backend/services/jobs/systemJobs.test.ts @@ -64,6 +64,12 @@ const EXPECTED_JOBS = { nearPrimary: false, leaseMs: 5 * MINUTE, }, + 'metering.closeGlobalMonths': { + every: 24 * HOUR, + scope: 'fleet', + nearPrimary: false, + leaseMs: 30 * MINUTE, + }, 'events.subscriptions.expirySweep': { every: HOUR, scope: 'fleet', diff --git a/src/backend/services/metering/MeteringService.test.ts b/src/backend/services/metering/MeteringService.test.ts index 037d6e583..ea78b78f1 100644 --- a/src/backend/services/metering/MeteringService.test.ts +++ b/src/backend/services/metering/MeteringService.test.ts @@ -13,6 +13,7 @@ import murmurhash from 'murmurhash'; import type { Actor } from '../../core/actor.ts'; import { SYSTEM_ACTOR, makeActor as resolveActor } from '../../core/actor.ts'; import { PuterServer } from '../../server.ts'; +import { testJobContext } from '../jobs/jobsTestUtil.ts'; import { bucketTag } from '../../stores/metering/MeteringBufferStore.ts'; import { setupTestServer } from '../../testUtil.ts'; import { @@ -1562,11 +1563,35 @@ describe('MeteringService', () => { auxSpy.mockRestore(); }); + /** Turns the per-app aggregate on for the running test. */ + const trackAppAggregate = () => { + const ctor = target.constructor as typeof MeteringService; + ctor.TRACK_APP_AGGREGATE = true; + onTestFinished(() => { + ctor.TRACK_APP_AGGREGATE = false; + }); + }; + + it('writes no per-app aggregate while tracking it is off', async () => { + const appActor: Actor = resolveActor({ + ...actor, + app: { uid: 'untracked-app' }, + }); + const auxSpy = vi.spyOn(server.stores.meteringBuffer, 'incrAux'); + await target.incrementUsage(appActor, 'kv:read', 1, 10); + const keys = auxSpy.mock.calls.map(([input]) => input.key); + expect( + keys.some((key) => key.startsWith(`${METRICS_V2_PREFIX}:app:`)), + ).toBe(false); + auxSpy.mockRestore(); + }); + // The per-app aggregate is what an app's developer reads. Usage with no // app behind it belongs to nobody there, and writing it anyway costs a // record per shard on every increment — which, now that ordinary // traffic is metered, is most of them. it('writes no per-app aggregate for an actor with no app', async () => { + trackAppAggregate(); const auxSpy = vi.spyOn(server.stores.meteringBuffer, 'incrAux'); await target.batchIncrementUsages(actor, [ { usageType: 'egress:bytes', usageAmount: 10, costOverride: 1 }, @@ -1579,6 +1604,7 @@ describe('MeteringService', () => { }); it('still writes the per-app aggregate for an app actor', async () => { + trackAppAggregate(); const appActor: Actor = resolveActor({ ...actor, app: { uid: 'batch-app' }, @@ -1600,6 +1626,7 @@ describe('MeteringService', () => { }); it('writes the global and per-app aggregates as {total} only, once per call', async () => { + trackAppAggregate(); const appActor: Actor = resolveActor({ ...actor, app: { uid: 'agg-app' }, @@ -3510,6 +3537,147 @@ describe('MeteringService', () => { list.mockRestore(); }); + describe('a closed month', () => { + const ctor = () => target.constructor as typeof MeteringService; + const shardKey = (shard: number, month: string) => + `${METRICS_V2_PREFIX}:puter:${shard}:${month}`; + const totalKey = (month: string) => + `${METRICS_V2_PREFIX}:puter:total:${month}`; + const seedShards = async (month: string, each: number) => { + for (let shard = 0; shard < ctor().GLOBAL_SHARD_COUNT; shard++) { + await server.stores.kv.set({ + key: shardKey(shard, month), + value: { total: each }, + }); + } + }; + const drainAux = () => + Promise.allSettled([...internals.pendingAuxPromises]); + const liveShards = async (month: string) => { + const { res } = await server.stores.kv.get({ + key: Array.from( + { length: ctor().GLOBAL_SHARD_COUNT }, + (_, shard) => shardKey(shard, month), + ), + }); + return (res as unknown[]).filter((value) => value !== null) + .length; + }; + + it('stores the total on the first read and answers from it after', async () => { + const month = '1997-01'; + await seedShards(month, 25); + const sum = 25 * ctor().GLOBAL_SHARD_COUNT; + + expect((await target.getGlobalUsage(month)).total).toBe(sum); + await drainAux(); + const { res } = await server.stores.kv.get({ + key: totalKey(month), + }); + expect(res).toMatchObject({ total: sum }); + + // The stored total stands whatever the shards say afterwards, + // and a read deletes none of them. + await server.stores.kv.set({ + key: shardKey(0, month), + value: { total: 9999 }, + }); + expect((await target.getGlobalUsage(month)).total).toBe(sum); + await drainAux(); + expect(await liveShards(month)).toBe(ctor().GLOBAL_SHARD_COUNT); + }); + + it('the job stores a total nothing has read', async () => { + const month = '1997-03'; + await seedShards(month, 4); + + await target.closeGlobalMonths(); + await drainAux(); + + const { res } = await server.stores.kv.get({ + key: totalKey(month), + }); + expect(res).toMatchObject({ + total: 4 * ctor().GLOBAL_SHARD_COUNT, + }); + }); + + it('only the job deletes the shards, once the stored total is old enough', async () => { + const month = '1997-02'; + const pageItems = ctor().CLOSED_SHARD_DELETE_PAGE_ITEMS; + const unitsPerSecond = + ctor().CLOSED_SHARD_DELETE_UNITS_PER_SECOND; + ctor().CLOSED_SHARD_DELETE_PAGE_ITEMS = 3; + ctor().CLOSED_SHARD_DELETE_UNITS_PER_SECOND = 1e6; + onTestFinished(() => { + ctor().CLOSED_SHARD_DELETE_PAGE_ITEMS = pageItems; + ctor().CLOSED_SHARD_DELETE_UNITS_PER_SECOND = + unitsPerSecond; + ctor().DELETE_CLOSED_SHARDS = false; + }); + const count = ctor().GLOBAL_SHARD_COUNT; + await seedShards(month, 7); + await server.stores.kv.set({ + key: totalKey(month), + value: { + total: 1234, + closedAt: + Date.now() - ctor().CLOSED_SHARD_DELETE_DELAY_MS, + }, + }); + + // Off by default: neither a read nor the job deletes. + await target.closeGlobalMonths(); + expect(await liveShards(month)).toBe(count); + + ctor().DELETE_CLOSED_SHARDS = true; + expect((await target.getGlobalUsage(month)).total).toBe(1234); + await drainAux(); + expect(await liveShards(month)).toBe(count); + + // A run that lost the job stops before its next batch. + const lost = testJobContext(); + lost.abort(); + await target.closeGlobalMonths(lost.signal); + expect(await liveShards(month)).toBe(count); + + await target.closeGlobalMonths(testJobContext().signal); + expect(await liveShards(month)).toBe(0); + expect((await target.getGlobalUsage(month)).total).toBe(1234); + }); + + it('keeps summing a month still inside the close grace', async () => { + const now = new Date(); + const lastMonth = new Date( + Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - 1, 1), + ); + const month = `${lastMonth.getUTCFullYear()}-${String( + lastMonth.getUTCMonth() + 1, + ).padStart(2, '0')}`; + const grace = ctor().GLOBAL_MONTH_CLOSE_GRACE_MS; + // Long enough that last month is still open today. + ctor().GLOBAL_MONTH_CLOSE_GRACE_MS = 40 * 24 * 60 * 60 * 1000; + onTestFinished(async () => { + ctor().GLOBAL_MONTH_CLOSE_GRACE_MS = grace; + await server.stores.kv.batchDel({ + keys: Array.from( + { length: ctor().GLOBAL_SHARD_COUNT }, + (_, shard) => shardKey(shard, month), + ), + }); + }); + await seedShards(month, 5); + + await target.getGlobalUsage(month); + await drainAux(); + + const { res } = await server.stores.kv.get({ + key: totalKey(month), + }); + expect(res).toBeNull(); + }); + }); + it('returns total only, with no per-model breakdown', async () => { const user1: Actor = { user: makeUser() }; await target.incrementUsage(user1, 'kv:read', 1, 100); diff --git a/src/backend/services/metering/MeteringService.ts b/src/backend/services/metering/MeteringService.ts index 5117014ce..673f4d502 100644 --- a/src/backend/services/metering/MeteringService.ts +++ b/src/backend/services/metering/MeteringService.ts @@ -120,6 +120,8 @@ type UsageWriteResult = { /** Every month's global shard sits under this, as `:`. */ const GLOBAL_USAGE_PREFIX = `${METRICS_V2_PREFIX}:puter:`; const GLOBAL_SHARD_KEY_RE = /^\d+:(\d{4}-\d{2})$/; +/** A closed month's total, one item beside the shards as `total:`. */ +const GLOBAL_MONTH_TOTAL_KEY_RE = /^total:(\d{4}-\d{2})$/; /** * Read units a sweep of the global shards draws per second. Their partition * serves 3,000 and every request's metering reads share it. @@ -131,6 +133,11 @@ const GLOBAL_RATE_CHECK_JOB = 'metering.globalRateCheck'; const GLOBAL_RATE_CHECK_EVERY_MS = 25 * 60 * 1000; const GLOBAL_RATE_CHECK_LEASE_MS = 5 * 60 * 1000; +/** Stores closed months' global totals whether or not anything reads them. */ +const GLOBAL_MONTH_CLOSE_JOB = 'metering.closeGlobalMonths'; +const GLOBAL_MONTH_CLOSE_EVERY_MS = 24 * 60 * 60 * 1000; +const GLOBAL_MONTH_CLOSE_LEASE_MS = 30 * 60 * 1000; + // -- Helpers ---------------------------------------------------------- /** @@ -193,8 +200,30 @@ export class MeteringService extends PuterService { */ static GLOBAL_SHARD_COUNT = 10000; static APP_SHARD_COUNT = 10000; + /** Off while nothing reads the per-app aggregate; flip it on with a reader. */ + static TRACK_APP_AGGREGATE = false; /** Shards one page of a sweep reads; the pause between pages is the pacing. */ static SHARD_SWEEP_PAGE_ITEMS = 1000; + /** + * How long after a month ends its global total is stored as one item. Usage + * is written under the month it happened in, so this only has to outlast + * buffered counters and replication between deployments. + */ + static GLOBAL_MONTH_CLOSE_GRACE_MS = 24 * 60 * 60 * 1000; + /** + * Off until every version a deployment can roll back to reads stored month + * totals: an older one sums the shards, and reports a deleted month as + * zero. + */ + static DELETE_CLOSED_SHARDS = false; + /** + * How long a stored month total stands before its shards are deleted, so no + * sweep that began without the total sums a partly deleted month. + */ + static CLOSED_SHARD_DELETE_DELAY_MS = 60 * 60 * 1000; + /** Closed shards deleted per call, and the write units drawn per second. */ + static CLOSED_SHARD_DELETE_PAGE_ITEMS = 100; + static CLOSED_SHARD_DELETE_UNITS_PER_SECOND = 100; /** * Share of the allowance past which an approximate running total is no @@ -443,6 +472,13 @@ export class MeteringService extends PuterService { }, ); + this.services.jobs.register(GLOBAL_MONTH_CLOSE_JOB, { + every: GLOBAL_MONTH_CLOSE_EVERY_MS, + scope: 'fleet', + leaseMs: GLOBAL_MONTH_CLOSE_LEASE_MS, + run: ({ signal }) => this.closeGlobalMonths(signal), + }); + const maxPerMinute = this.config.maxGlobalUsagePerMinute; if (maxPerMinute && maxPerMinute > 0) { this.services.jobs.register(GLOBAL_RATE_CHECK_JOB, { @@ -869,7 +905,9 @@ export class MeteringService extends PuterService { (totals.res as unknown as UsageByType).detailPaths ?? 0, appTotalCost, appCallCount, - includeAppAggregate: appId !== GLOBAL_APP_KEY, + includeAppAggregate: + MeteringService.TRACK_APP_AGGREGATE && + appId !== GLOBAL_APP_KEY, }); } catch (e) { // The total is already settled — a detail failure must never @@ -2546,9 +2584,34 @@ export class MeteringService extends PuterService { * The global total of every month on record, by `YYYY-MM`. Shards sort by * number before month, so one listing covers them all; it is charged by * bytes read, where getting each shard by key is charged per key. + * + * A month past `GLOBAL_MONTH_CLOSE_GRACE_MS` is summed once: the first read + * stores its total and later reads answer from that item. */ async getGlobalUsageByMonth(): Promise> { + return (await this.#sweepGlobalUsage()).totals; + } + + /** + * The daily job: a sweep, which stores the total of each month that closed + * since the last one, then the deletion of shards a stored total replaced. + * Deleting only here keeps it to the one process holding the job. + */ + async closeGlobalMonths(signal?: AbortSignal): Promise { + const { replaced } = await this.#sweepGlobalUsage(); + if (MeteringService.DELETE_CLOSED_SHARDS) + await this.#deleteClosedShards(replaced, signal); + } + + /** Every month's total, and the shard keys a stored total has replaced. */ + async #sweepGlobalUsage(): Promise<{ + totals: Map; + replaced: string[]; + }> { + const now = Date.now(); const totals = new Map(); + const stored = new Map(); + const closedShardKeys = new Map(); let cursor: string | undefined; do { const startedAt = Date.now(); @@ -2563,10 +2626,28 @@ export class MeteringService extends PuterService { cursor?: string; }; for (const { key, value } of page.items) { - const month = GLOBAL_SHARD_KEY_RE.exec( - key.slice(GLOBAL_USAGE_PREFIX.length), - )?.[1]; + const suffix = key.slice(GLOBAL_USAGE_PREFIX.length); + const storedMonth = GLOBAL_MONTH_TOTAL_KEY_RE.exec(suffix)?.[1]; + if (storedMonth) { + const item = value as { + total?: number; + closedAt?: number; + } | null; + const total = Number(item?.total); + if (Number.isFinite(total)) + stored.set(storedMonth, { + total, + closedAt: Number(item?.closedAt) || 0, + }); + continue; + } + const month = GLOBAL_SHARD_KEY_RE.exec(suffix)?.[1]; if (!month) continue; + if (this.#globalMonthClosed(month, now)) { + const keys = closedShardKeys.get(month); + if (keys) keys.push(key); + else closedShardKeys.set(month, [key]); + } const total = Number((value as UsageByType | null)?.total); if (Number.isFinite(total)) totals.set(month, (totals.get(month) ?? 0) + total); @@ -2577,7 +2658,65 @@ export class MeteringService extends PuterService { (Date.now() - startedAt); if (cursor && waitMs > 0) await sleep(waitMs); } while (cursor); - return totals; + + const replaced: string[] = []; + for (const [month, keys] of closedShardKeys) { + const total = stored.get(month); + if (!total) { + // Another deployment may be storing the same sum; first wins. + this.handleAuxPromise( + `globalMonthTotal ${month}`, + this.stores.kv.set({ + key: `${GLOBAL_USAGE_PREFIX}total:${month}`, + value: { total: totals.get(month) ?? 0, closedAt: now }, + onlyIfAbsent: true, + }), + ); + } else if ( + now - total.closedAt >= + MeteringService.CLOSED_SHARD_DELETE_DELAY_MS + ) { + for (const key of keys) replaced.push(key); + } + } + + // A stored total is final: shards still listed beside it are leftovers. + for (const [month, { total }] of stored) totals.set(month, total); + return { totals, replaced }; + } + + /** Whether `month` (`YYYY-MM`) ended at least the close grace ago. */ + #globalMonthClosed(month: string, now: number): boolean { + const [year, monthOfYear] = month.split('-').map(Number); + // `Date.UTC` takes a 0-indexed month, so this is the next month's start. + return ( + now >= + Date.UTC(year!, monthOfYear!, 1) + + MeteringService.GLOBAL_MONTH_CLOSE_GRACE_MS + ); + } + + /** Deletes shards a stored month total replaced, paced by write units. */ + async #deleteClosedShards( + keys: string[], + signal?: AbortSignal, + ): Promise { + const pageItems = MeteringService.CLOSED_SHARD_DELETE_PAGE_ITEMS; + for (let i = 0; i < keys.length; i += pageItems) { + // The rest are listed again by the next run. + if (signal?.aborted) return; + const startedAt = Date.now(); + const { usage } = await this.stores.kv.batchDel({ + keys: keys.slice(i, i + pageItems), + }); + const waitMs = + (usage.write / + MeteringService.CLOSED_SHARD_DELETE_UNITS_PER_SECOND) * + 1000 - + (Date.now() - startedAt); + if (i + pageItems < keys.length && waitMs > 0) + await sleep(waitMs, undefined, { ref: false }); + } } async updateAddonCredit( From 79e7ddfee843a71d20dac162a8e8066c7b53365b Mon Sep 17 00:00:00 2001 From: Daniel Salazar Date: Wed, 25 Nov 2026 17:52:58 -0700 Subject: [PATCH 2/2] fix(db): a value a narrow column cannot hold matches no row instead of failing the request (#4778) * fix(db): a value a narrow column cannot hold matches no row instead of failing the request MySQL fails a statement that compares an ascii or latin1 column with a value it cannot convert to that charset. Lookups that took such a value from a request answered 500. - util/narrowCharset: one check for whether a value fits an ascii or latin1 column, used by the stores before they query. - UserStore: username is checked as ascii and uuid as latin1; the write guard follows the same per-column charsets. - AppStore: uid lookups (single, batch, existence, descendants) return no match for a value the column cannot hold. - Events: an appUid named in a request has to have the app uid shape. - The HTTP error handler and WebDAV answer 400 for this MySQL error wherever a lookup still reaches it, and log the route. - MeteringService: the addons read that can fail is typed as optional. * fix(db): permission lists leave out values the ascii column cannot hold; the n-operand collation error is not classified MySQL's ER_CANT_AGGREGATE_NCOLLATIONS (IN with three or more values) names no operand, so isCharsetMismatch cannot tell a literal from two columns that disagree and no longer lists it. PermissionStore filters its IN lists on MySQL instead. --- .../controllers/webdav/WebDAVController.ts | 5 + .../core/http/middleware/errorHandler.test.ts | 27 ++++++ .../core/http/middleware/errorHandler.ts | 15 +++ src/backend/services/events/EventsService.ts | 3 + .../events/userHandlers.integration.test.ts | 19 ++++ .../services/metering/MeteringService.ts | 8 +- src/backend/stores/app/AppStore.js | 14 ++- src/backend/stores/app/AppStore.test.js | 25 +++++ .../stores/permission/PermissionStore.test.ts | 95 +++++++++++++++++++ .../stores/permission/PermissionStore.ts | 29 ++++-- src/backend/stores/user/UserStore.test.ts | 31 +++++- src/backend/stores/user/UserStore.ts | 56 +++++------ src/backend/util/dbError.test.ts | 50 ++++++++++ src/backend/util/dbError.ts | 26 +++++ src/backend/util/narrowCharset.test.ts | 46 +++++++++ src/backend/util/narrowCharset.ts | 45 +++++++++ 16 files changed, 444 insertions(+), 50 deletions(-) create mode 100644 src/backend/util/narrowCharset.test.ts create mode 100644 src/backend/util/narrowCharset.ts diff --git a/src/backend/controllers/webdav/WebDAVController.ts b/src/backend/controllers/webdav/WebDAVController.ts index 35e29f924..a983f2f41 100644 --- a/src/backend/controllers/webdav/WebDAVController.ts +++ b/src/backend/controllers/webdav/WebDAVController.ts @@ -85,6 +85,7 @@ import { peekRateLimit, } from '../../core/http/middleware/rateLimit.js'; import { assertActorHasCredits } from '../../services/metering/enforcement.js'; +import { isCharsetMismatch } from '../../util/dbError.js'; import { isTemporaryPasswordExpired } from '../../util/temporaryPassword.js'; import type { ResolvedShare } from '../../services/share/ShareService.js'; @@ -1268,6 +1269,10 @@ function sendDavError(res: Response, err: unknown): void { res.status(err.statusCode).send(err.message); return; } + if (isCharsetMismatch(err)) { + res.status(400).send('Bad Request'); + return; + } console.error('[webdav] unhandled error', err); res.status(500).send('Internal Server Error'); } diff --git a/src/backend/core/http/middleware/errorHandler.test.ts b/src/backend/core/http/middleware/errorHandler.test.ts index 9fd9b7a0b..0857a66f1 100644 --- a/src/backend/core/http/middleware/errorHandler.test.ts +++ b/src/backend/core/http/middleware/errorHandler.test.ts @@ -356,3 +356,30 @@ describe('createErrorHandler — dbBatchFailed load-shed errors', () => { expect(onUnhandled).toHaveBeenCalledTimes(1); }); }); + +describe('createErrorHandler — value outside a column charset', () => { + it('answers 400 with a client code instead of a generic 500', () => { + const onUnhandled = vi.fn(); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const handler = createErrorHandler({ onUnhandled }); + const err = Object.assign(new Error('Illegal mix of collations'), { + code: 'ER_CANT_AGGREGATE_2COLLATIONS', + sqlMessage: + "Illegal mix of collations (ascii_general_ci,IMPLICIT) and (utf8mb4_unicode_ci,COERCIBLE) for operation '='", + sql: "SELECT * FROM `user` WHERE `username` = 'secret-value'", + }); + const { out } = runHandler(handler, err, { + req: { method: 'POST', path: '/lookup' }, + }); + + expect(out.statusCode).toBe(400); + expect(out.body).toMatchObject({ code: 'client_bad_characters' }); + expect(JSON.stringify(out.body)).not.toContain('secret-value'); + expect(onUnhandled).not.toHaveBeenCalled(); + // The route is logged, the statement is not. + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0][0])).toContain('POST /lookup'); + expect(String(warn.mock.calls[0][0])).not.toContain('secret-value'); + warn.mockRestore(); + }); +}); diff --git a/src/backend/core/http/middleware/errorHandler.ts b/src/backend/core/http/middleware/errorHandler.ts index 1959e82d3..4f105b1ee 100644 --- a/src/backend/core/http/middleware/errorHandler.ts +++ b/src/backend/core/http/middleware/errorHandler.ts @@ -18,6 +18,7 @@ */ import type { ErrorRequestHandler, RequestHandler } from 'express'; +import { isCharsetMismatch } from '../../../util/dbError.js'; import { HttpError, isHttpError } from '../HttpError'; interface ErrorHandlerOptions { @@ -83,6 +84,12 @@ export const createErrorHandler = ( const translated = translateKnownClientError(err); if (translated) { + // Names the route so its lookup can refuse the value itself. + if (isCharsetMismatch(err)) { + console.warn( + `[v2] ${req.method} ${req.path}: value outside the column charset`, + ); + } err = translated; } @@ -148,6 +155,8 @@ export const createErrorHandler = ( * - Body-parser `entity.parse.failed` (malformed JSON in request body) * - Body-parser `request.aborted` / `ECONNABORTED` (client closed socket * mid-upload) + * - A request value MySQL could not convert to the charset of the column it was + * compared with * - Anything else that already opted into `expose: true` with a numeric * `statusCode` is mapped to `client_bad_request` so it surfaces with the * declared status instead of becoming a 500. @@ -159,6 +168,12 @@ const translateKnownClientError = (err: unknown): HttpError | null => { }); } + if (isCharsetMismatch(err)) { + return new HttpError(400, 'Request contains unsupported characters', { + legacyCode: 'client_bad_characters', + }); + } + if (!err || typeof err !== 'object') return null; const e = err as { type?: string; diff --git a/src/backend/services/events/EventsService.ts b/src/backend/services/events/EventsService.ts index 5ff57bfbd..50b000c9a 100644 --- a/src/backend/services/events/EventsService.ts +++ b/src/backend/services/events/EventsService.ts @@ -239,6 +239,7 @@ import { } from './registry.js'; import { SubscriptionCache } from './subscriptionCache.js'; import { + APP_UID_SHAPE, kvShareAccessOf, kvShareGrantCovers, kvSharePermission, @@ -1572,6 +1573,8 @@ const parseAppUid = (value: unknown): string | null => { if (value === undefined || value === null || value === '') return null; if (typeof value !== 'string') throw badRequest('appUid must be a string', 'bad_request'); + if (!APP_UID_SHAPE.test(value)) + throw badRequest('appUid is not an app uid', 'bad_request'); return value; }; diff --git a/src/backend/services/events/userHandlers.integration.test.ts b/src/backend/services/events/userHandlers.integration.test.ts index 7191d7a2e..58ac87cb7 100644 --- a/src/backend/services/events/userHandlers.integration.test.ts +++ b/src/backend/services/events/userHandlers.integration.test.ts @@ -388,6 +388,25 @@ describe('who may publish into a user scope', () => { expect(refused.status).toBe(400); }); + it('rejects a named app that is not an app uid', async () => { + for (const named of ['app-\u7528\u6237', 'not an app', 'app-']) { + const listed = await call( + 'GET', + `/events/handlers/list?scope=user&appUid=${encodeURIComponent(named)}`, + userToken, + ); + expect(listed.status).toBe(400); + expect(listed.body.code).toBe('bad_request'); + const removed = await call( + 'POST', + '/events/handlers/remove', + userToken, + { scope: 'user', name: 'daily', appUid: named }, + ); + expect(removed.status).toBe(400); + } + }); + it('reserves `@` names for what the server mints from a source', async () => { const refused = await publishUser( userToken, diff --git a/src/backend/services/metering/MeteringService.ts b/src/backend/services/metering/MeteringService.ts index 673f4d502..206dfd684 100644 --- a/src/backend/services/metering/MeteringService.ts +++ b/src/backend/services/metering/MeteringService.ts @@ -747,7 +747,7 @@ export class MeteringService extends PuterService { return await this.#addonsForSettle(actor); } catch (e) { settleReadError = e as Error; - return null; + return undefined; } })(), ]); @@ -3226,7 +3226,7 @@ export class MeteringService extends PuterService { userId: string; actorUsages: UsageByType; actorSubscription: SubscriptionPolicy; - actorAddons: UsageAddons; + actorAddons?: UsageAddons; incrementCost: number; batchUsages: UsageInput[]; }): void { @@ -3252,9 +3252,9 @@ export class MeteringService extends PuterService { // allowance-sized expense the moment the credit runs dry. (Purchased // credit is a lifetime balance, so in the month it finally runs out this // also grants a small grace window before paging.) - const purchasedCredits = actorAddons.purchasedCredits || 0; + const purchasedCredits = actorAddons?.purchasedCredits || 0; const consumedPurchaseCredits = - actorAddons.consumedPurchaseCredits || 0; + actorAddons?.consumedPurchaseCredits || 0; const netUsage = actorUsages.total - purchasedCredits; const previousNetUsage = netUsage - incrementCost; diff --git a/src/backend/stores/app/AppStore.js b/src/backend/stores/app/AppStore.js index 5a111df35..e8c0052f7 100644 --- a/src/backend/stores/app/AppStore.js +++ b/src/backend/stores/app/AppStore.js @@ -28,6 +28,7 @@ import { import { HttpError } from '../../core/http/HttpError.js'; import { chunk, runWithConcurrencyLimit } from '../../util/concurrency.js'; import { isUniqueViolation } from '../../util/dbError.js'; +import { fitsCharset } from '../../util/narrowCharset.js'; import { escapeLike } from '../../util/sqlLike.js'; import { validateUrl, @@ -184,6 +185,12 @@ const ADMIN_FLAG_COLUMNS = new Set([ const COLUMN_NAME = /^[a-z_][a-z0-9_]*$/; // Unique-key columns `#getManyByProperty` may build an IN-list against. const BATCH_LOOKUP_COLUMNS = new Set(['id', 'uid', 'name']); + +// `uid` is a latin1 column: a value it cannot hold matches no app, and would +// fail the statement at MySQL. +const isStorableUid = (uid) => + typeof uid === 'string' && fitsCharset(uid, 'latin1'); + const APP_BOOLEAN_COLUMNS = new Set([ 'godmode', 'maximize_on_start', @@ -298,7 +305,7 @@ export class AppStore extends PuterStore { * extensions. */ async uidExistsOnPrimary(uid) { - if (!uid || typeof uid !== 'string') return false; + if (!uid || !isStorableUid(uid)) return false; const rows = await this.clients.db.pread( 'SELECT `id` FROM `apps` WHERE `uid` = ? LIMIT 1', [uid], @@ -350,7 +357,8 @@ export class AppStore extends PuterStore { // Same rule as `#getByProperty`: only `id` takes a number. const present = (Array.isArray(values) ? values : []).filter( (value) => - typeof value === 'string' || + (typeof value === 'string' && + (prop !== 'uid' || isStorableUid(value))) || (prop === 'id' && typeof value === 'number'), ); return this.#cache.getMany(prop, present, async (missing, primary) => { @@ -792,6 +800,7 @@ export class AppStore extends PuterStore { /** App bindings owned by this user beneath an app, including the root. */ async listOwnedDescendantUids(userId, appUid) { + if (!isStorableUid(appUid)) return []; const rows = await this.clients.db.pread( 'WITH RECURSIVE appTree AS (' + 'SELECT `id`, `uid` FROM `apps` WHERE `uid` = ? ' + @@ -1400,6 +1409,7 @@ export class AppStore extends PuterStore { !(prop === 'id' && typeof value === 'number') ) return null; + if (prop === 'uid' && !isStorableUid(value)) return null; return this.#cache.get( this.#cache.key(prop, value), async (primary) => { diff --git a/src/backend/stores/app/AppStore.test.js b/src/backend/stores/app/AppStore.test.js index 1c3ae1533..8ad8f1079 100644 --- a/src/backend/stores/app/AppStore.test.js +++ b/src/backend/stores/app/AppStore.test.js @@ -379,6 +379,31 @@ describe('AppStore batched lookups', () => { expect((await appStore.getByUid(a.uid))?.id).toBe(a.id); }); + it('uid lookups match no row for a value the column cannot hold', async () => { + const a = await createApp('Narrow'); + const db = server.clients.db; + const reads = [ + vi.spyOn(db, 'read'), + vi.spyOn(db, 'pread'), + vi.spyOn(db, 'tryHardRead'), + ]; + for (const uid of ['app-\u7528\u6237', 'app-\u0080', 'app-\u{1F600}']) { + expect(await appStore.getByUid(uid)).toBeNull(); + expect(await appStore.uidExistsOnPrimary(uid)).toBe(false); + expect((await appStore.getByUids([uid])).size).toBe(0); + expect(await appStore.listOwnedDescendantUids(1, uid)).toEqual([]); + } + for (const spy of reads) { + expect(spy).not.toHaveBeenCalled(); + spy.mockRestore(); + } + // A name is utf8mb4, and a mixed batch keeps its storable uids. + expect(await appStore.getByName('\u7528\u6237')).toBeNull(); + expect([ + ...(await appStore.getByUids([a.uid, 'app-\u7528\u6237'])).keys(), + ]).toEqual([a.uid]); + }); + it('getByIds still resolves id-keyed lookups off the shared engine', async () => { const a = await createApp('Alpha'); diff --git a/src/backend/stores/permission/PermissionStore.test.ts b/src/backend/stores/permission/PermissionStore.test.ts index 6ac7cbf76..db587c1a5 100644 --- a/src/backend/stores/permission/PermissionStore.test.ts +++ b/src/backend/stores/permission/PermissionStore.test.ts @@ -21,13 +21,19 @@ import { readFileSync } from 'fs'; import { v4 as uuidv4 } from 'uuid'; import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { + AbstractDatabaseClient, + type WriteResult, +} from '../../clients/database/DatabaseClient.ts'; import { PuterServer } from '../../server.ts'; import { PermissionUtil } from '../../services/permission/permissionUtil.ts'; import { lagReadReplica, setupTestServer } from '../../testUtil.ts'; import { decodeCursor } from '../../util/pagination.ts'; +import type { IConfig } from '../../types'; import { CACHE_TOMBSTONE_SUFFIX } from '../types.ts'; import { FLAT_PERM_SCAN_CONCURRENCY, + PermissionStore, U2U_CACHE_MAX_ROWS, U2U_EXACT_DELETE_CHUNK, } from './PermissionStore.ts'; @@ -3344,4 +3350,93 @@ describe('PermissionStore', () => { ]); }); }); + + // -- values an ascii `permission` column cannot hold ---------------- + + describe('permission lists with a non-ASCII value', () => { + const WIDE = 'kv-share:owner:app:\u7528\u6237'; + const LIST = ['fs:a:read', 'fs:b:read', WIDE]; + + /** Answers no rows and records what it was asked. */ + class RecordingClient extends AbstractDatabaseClient { + override readonly engineName = 'mysql'; + readonly params: unknown[][] = []; + + constructor() { + super({ port: 0, extensions: [] } as IConfig); + } + + override async read(_query: string, params: unknown[] = []) { + this.params.push(params); + return []; + } + + override async pread(_query: string, params: unknown[] = []) { + this.params.push(params); + return []; + } + + override async write( + _query: string, + params: unknown[] = [], + ): Promise { + this.params.push(params); + return { insertId: 0, affectedRows: 0, anyRowsAffected: false }; + } + } + + it('leaves it out of the lists sent to MySQL', async () => { + const db = new RecordingClient(); + const mysqlStore = new PermissionStore( + { port: 0, extensions: [], jwt_secret_v2: 'x' } as IConfig, + { db } as unknown as ConstructorParameters< + typeof PermissionStore + >[1], + ); + + await mysqlStore.findUserUserPermsByIssuer(1, 2, LIST); + await mysqlStore.deleteUserUserPermsByHolder(1, LIST, 2); + await mysqlStore.readLinkedUserUserPermsForHolders([1, 2], LIST); + await mysqlStore.readUserGroupPermsForHolders([1, 2], LIST); + await mysqlStore.deleteUserGroupPerms(1, 2, LIST); + await mysqlStore.listUserUserAudit({ permissions: LIST }); + await mysqlStore.countUserUserAudit({ permissions: LIST }); + + const sent = db.params.flat(); + expect(sent).not.toContain(WIDE); + expect(sent).toContain('fs:a:read'); + + // Nothing but such values: no statement names one. + db.params.length = 0; + expect( + await mysqlStore.findUserUserPermsByIssuer(1, 2, [WIDE]), + ).toEqual([]); + expect( + await mysqlStore.deleteUserUserPermByHolder(1, WIDE, 2), + ).toBe(false); + expect( + await mysqlStore.readUserGroupPermsForHolders([1], [WIDE]), + ).toEqual([]); + expect( + (await mysqlStore.listUserUserAudit({ permissions: [WIDE] })) + .items, + ).toEqual([]); + expect(db.params.flat()).not.toContain(WIDE); + }); + + it('still matches it where the column holds any text', async () => { + if (server.clients.db.engineName === 'mysql') return; + const issuer = await makeUser(); + const holder = await makeUser(); + await store.upsertUserUserPerm(holder.id, issuer.id, WIDE, {}); + + expect( + await store.findUserUserPermsByIssuer(holder.id, issuer.id, [ + 'fs:a:read', + 'fs:b:read', + WIDE, + ]), + ).toEqual([WIDE]); + }); + }); }); diff --git a/src/backend/stores/permission/PermissionStore.ts b/src/backend/stores/permission/PermissionStore.ts index 6e6c69f40..64affc5cb 100644 --- a/src/backend/stores/permission/PermissionStore.ts +++ b/src/backend/stores/permission/PermissionStore.ts @@ -35,6 +35,7 @@ import { } from '../../services/permission/consts'; import { chunk, runWithConcurrencyLimit } from '../../util/concurrency'; import { kv } from '../../util/kvSingleton'; +import { fitsCharset } from '../../util/narrowCharset'; import { clampLimit, keysetPage, openIdCursor } from '../../util/pagination'; import { bumpGeneration } from '../../util/redisGeneration'; import { escapeLike } from '../../util/sqlLike'; @@ -725,7 +726,8 @@ export class PermissionStore extends PuterStore { issuerUserId: number, permissions: readonly string[], ): { scope: string; params: unknown[] } { - const unique = [...new Set(permissions)]; + const unique = this.#matchable(permissions); + if (unique.length === 0) return { scope: '1 = 0', params: [] }; const list = unique.map(() => '?').join(', '); const exact = this.clients.db.case({ mysql: { @@ -740,6 +742,17 @@ export class PermissionStore extends PuterStore { }; } + /** + * `permissions` without duplicates and, on MySQL, without the values its + * ascii `permission` columns cannot hold: such a value matches no row, and + * in an `IN` list it fails the statement. + */ + #matchable(permissions: readonly string[]): string[] { + const unique = [...new Set(permissions)]; + if (this.clients.db.engineName !== 'mysql') return unique; + return unique.filter((permission) => fitsCharset(permission, 'ascii')); + } + /** * The grants an account issued, as flat-view refs. Read before the account * row goes: the SQL rows cascade with it, the holders' flat entries do @@ -1068,13 +1081,14 @@ export class PermissionStore extends PuterStore { params.push(filter.holderUserId); } if (filter.permissions !== undefined) { - if (filter.permissions.length === 0) { + const permissions = this.#matchable(filter.permissions); + if (permissions.length === 0) { return { sql: '1 = 0', params: [] }; } clauses.push( - `\`permission\` IN (${filter.permissions.map(() => '?').join(', ')})`, + `\`permission\` IN (${permissions.map(() => '?').join(', ')})`, ); - params.push(...filter.permissions); + params.push(...permissions); } if (clauses.length === 0) { throw new Error('listUserUserAudit requires a filter'); @@ -1699,7 +1713,7 @@ export class PermissionStore extends PuterStore { Array<{ holder_user_id: number; permission: string; user_id: number }> > { const holders = [...new Set(userIds)]; - const perms = [...new Set(permissions)]; + const perms = this.#matchable(permissions); if (holders.length === 0 || perms.length === 0) return []; const changed = await this.tombstonedCacheKeys( holders.map((holder) => this.#u2gCacheKey(holder)), @@ -1799,7 +1813,7 @@ export class PermissionStore extends PuterStore { issuerUserId: number, permissions: readonly string[], ): Promise<{ removed: string[]; members: GroupMember[] }> { - const unique = [...new Set(permissions)]; + const unique = this.#matchable(permissions); if (unique.length === 0) return { removed: [], members: [] }; const where = '`group_id` = ? AND `user_id` = ? AND `permission` IN (' + @@ -2321,8 +2335,9 @@ export class PermissionStore extends PuterStore { perms: string[], ): Promise { const rows: LinkedUserUserPermRow[] = []; + const permChunks = chunk(this.#matchable(perms), 700); for (const holderChunk of chunk(holders, 200)) { - for (const permChunk of chunk(perms, 700)) { + for (const permChunk of permChunks) { const found = await read( 'SELECT * FROM `user_to_user_permissions` WHERE ' + `\`holder_user_id\` IN (${holderChunk.map(() => '?').join(', ')}) ` + diff --git a/src/backend/stores/user/UserStore.test.ts b/src/backend/stores/user/UserStore.test.ts index 50d689bcd..7d4687919 100644 --- a/src/backend/stores/user/UserStore.test.ts +++ b/src/backend/stores/user/UserStore.test.ts @@ -837,11 +837,33 @@ describe('UserStore batched and uncached lookups', () => { ).toBe(0); }); - it('short-circuits identifying lookups whose value cannot exist in a latin1 column', async () => { - expect(await server.stores.user.getByUsername('用户')).toBeNull(); + it('short-circuits identifying lookups whose value the column cannot hold', async () => { + const db = server.clients.db; + const reads = [ + vi.spyOn(db, 'read'), + vi.spyOn(db, 'pread'), + vi.spyOn(db, 'tryHardRead'), + ]; + // `username` is ascii, so a latin1 letter is already out. + for (const username of ['用户', 'm\u00e1genta', 'a\u0080']) + expect(await server.stores.user.getByUsername(username)).toBeNull(); + for (const email of ['用户@test.local', 'a\u0085b@test.local']) + expect(await server.stores.user.getByEmail(email)).toBeNull(); + expect(await server.stores.user.getByUuid('用户')).toBeNull(); + for (const spy of reads) { + expect(spy).not.toHaveBeenCalled(); + spy.mockRestore(); + } + }); + + it('still looks up an address with latin1 letters', async () => { expect( - await server.stores.user.getByEmail('用户@test.local'), + await server.stores.user.getByEmail('jos\u00e9-nobody@test.local'), ).toBeNull(); + const user = await makeUser(); + expect((await server.stores.user.getByEmail(user.email))?.id).toBe( + user.id, + ); }); it('matches no row on a text column for a value that is not a string', async () => { @@ -893,6 +915,9 @@ describe('UserStore batched and uncached lookups', () => { await expect( server.stores.user.update(user.id, { username: '用户' }), ).rejects.toMatchObject({ code: 'userFieldNotLatin1' }); + await expect( + server.stores.user.update(user.id, { username: 'm\u00e1genta' }), + ).rejects.toMatchObject({ code: 'userFieldNotLatin1' }); // Columns outside the latin1 set are unaffected. await expect( server.stores.user.update(user.id, { diff --git a/src/backend/stores/user/UserStore.ts b/src/backend/stores/user/UserStore.ts index 924b26aa6..48143deac 100644 --- a/src/backend/stores/user/UserStore.ts +++ b/src/backend/stores/user/UserStore.ts @@ -20,6 +20,7 @@ import { chunk } from '../../util/concurrency.js'; import { isUniqueViolation } from '../../util/dbError.js'; import { cleanEmail, isSameAddress } from '../../util/email.js'; +import { fitsCharset, type NarrowCharset } from '../../util/narrowCharset.js'; import { normalizeReferralCode } from '../../util/referralCode.js'; import { PuterStore } from '../types'; @@ -137,28 +138,21 @@ export const isOwnedEmailConflict = (e: unknown): boolean => { // backends without splitting the cap by driver. const BULK_QUERY_CHUNK_SIZE = 200; -// The `email`, `clean_email`, and `username` columns are latin1_swedish_ci. -// MySQL throws ER_CANT_AGGREGATE_2COLLATIONS on `=` when a utf8mb4 param -// contains any character > U+00FF, since the implicit conversion to latin1 -// would lose data. No stored row can match such a value anyway, so we -// short-circuit these lookups at the boundary instead of letting the driver -// surface the collation error. -const isStorableAsLatin1 = (value: string): boolean => { - for (let i = 0; i < value.length; i++) { - if (value.charCodeAt(i) > 0xff) return false; - } - return true; -}; - -// Columns on the `user` table that are stored as latin1_swedish_ci. Used by -// both the read path (skip the DB on un-storable lookups) and the write path -// (reject inserts/updates before MySQL throws on conversion). -const LATIN1_USER_COLUMNS: ReadonlySet = new Set([ - 'email', - 'username', - 'clean_email', - 'phone', +// `user` columns narrower than the utf8mb4 connection. Reads skip the DB for a +// value that cannot be stored there (no row can match, and MySQL would fail +// the statement); writes are refused before MySQL throws on conversion. +// `clean_email` and `phone` hold only what `email` and a dialled number can. +const NARROW_USER_COLUMNS: ReadonlyMap = new Map([ + ['username', 'ascii'], + ['uuid', 'latin1'], + ['email', 'latin1'], + ['clean_email', 'latin1'], + ['phone', 'latin1'], ]); +const fitsUserColumn = (column: string, value: string): boolean => { + const charset = NARROW_USER_COLUMNS.get(column); + return charset === undefined || fitsCharset(value, charset); +}; const USER_BOOLEAN_COLUMNS: ReadonlySet = new Set([ 'requires_email_confirmation', 'email_confirmed', @@ -173,11 +167,10 @@ const USER_BOOLEAN_COLUMNS: ReadonlySet = new Set([ const assertLatin1Writable = (fields: Record): void => { for (const [key, value] of Object.entries(fields)) { - if (!LATIN1_USER_COLUMNS.has(key)) continue; if (typeof value !== 'string') continue; - if (isStorableAsLatin1(value)) continue; + if (fitsUserColumn(key, value)) continue; const err = new Error( - `User field '${key}' contains characters outside latin1`, + `User field '${key}' contains characters outside ${NARROW_USER_COLUMNS.get(key)}`, ); (err as { code?: string }).code = 'userFieldNotLatin1'; throw err; @@ -349,7 +342,7 @@ export class UserStore extends PuterStore { ): Promise { if (!cleanEmailValue || typeof cleanEmailValue !== 'string') return null; - if (!isStorableAsLatin1(cleanEmailValue)) return null; + if (!fitsUserColumn('clean_email', cleanEmailValue)) return null; const sql = `SELECT \`id\`, \`clean_email\` FROM \`user\` WHERE \`clean_email\` = ? ${EMAIL_OWNER_ORDER} LIMIT 1`; const rows = (await (opts.force ? this.clients.db.pread(sql, [cleanEmailValue]) @@ -427,7 +420,7 @@ export class UserStore extends PuterStore { excludeUserId: number, ): Promise { if (!phone || typeof phone !== 'string') return 0; - if (!isStorableAsLatin1(phone)) return 0; + if (!fitsUserColumn('phone', phone)) return 0; const rows = (await this.clients.db.tryHardRead( 'SELECT COUNT(*) AS n FROM `user` WHERE `phone` = ? AND `id` != ?', [phone, excludeUserId], @@ -458,15 +451,10 @@ export class UserStore extends PuterStore { ) return null; - // Reject lookup values that can't exist in a latin1 column before - // the driver turns them into a collation-mix error at MySQL. - if ( - LATIN1_USER_COLUMNS.has(prop) && - typeof value === 'string' && - !isStorableAsLatin1(value) - ) { + // A value the column cannot hold matches no row, and would fail the + // statement at MySQL. + if (typeof value === 'string' && !fitsUserColumn(prop, value)) return null; - } // Replication-aware read: on `force` (or a tombstoned key), go // straight to the primary (`pread`) to bypass replica lag for hot diff --git a/src/backend/util/dbError.test.ts b/src/backend/util/dbError.test.ts index 3f97bb2b2..b4bada61a 100644 --- a/src/backend/util/dbError.test.ts +++ b/src/backend/util/dbError.test.ts @@ -19,6 +19,7 @@ import { describe, expect, it } from 'vitest'; import { + isCharsetMismatch, isMissingParentViolation, isMissingTable, isUniqueViolation, @@ -123,3 +124,52 @@ describe('isMissingTable', () => { expect(isMissingTable(undefined)).toBe(false); }); }); + +describe('isCharsetMismatch', () => { + const mix = (code: string, sqlMessage: string) => ({ code, sqlMessage }); + + it('matches a literal MySQL could not convert to the column charset', () => { + expect( + isCharsetMismatch( + mix( + 'ER_CANT_AGGREGATE_2COLLATIONS', + "Illegal mix of collations (ascii_general_ci,IMPLICIT) and (utf8mb4_unicode_ci,COERCIBLE) for operation '='", + ), + ), + ).toBe(true); + // `IN` with two values. + expect( + isCharsetMismatch( + mix( + 'ER_CANT_AGGREGATE_3COLLATIONS', + "Illegal mix of collations (latin1_swedish_ci,IMPLICIT), (utf8mb4_unicode_ci,COERCIBLE), (utf8mb4_unicode_ci,COERCIBLE) for operation ' IN '", + ), + ), + ).toBe(true); + }); + + it('leaves the n-operand form alone, which names no operands', () => { + expect( + isCharsetMismatch( + mix( + 'ER_CANT_AGGREGATE_NCOLLATIONS', + "Illegal mix of collations for operation ' IN '", + ), + ), + ).toBe(false); + }); + + it('leaves a mismatch between two columns, and other errors, alone', () => { + expect( + isCharsetMismatch( + mix( + 'ER_CANT_AGGREGATE_2COLLATIONS', + "Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8mb4_unicode_ci,IMPLICIT) for operation '='", + ), + ), + ).toBe(false); + expect(isCharsetMismatch({ code: 'ER_DUP_ENTRY' })).toBe(false); + expect(isCharsetMismatch(new Error('COERCIBLE'))).toBe(false); + expect(isCharsetMismatch(null)).toBe(false); + }); +}); diff --git a/src/backend/util/dbError.ts b/src/backend/util/dbError.ts index 6abbeb416..f139b68c6 100644 --- a/src/backend/util/dbError.ts +++ b/src/backend/util/dbError.ts @@ -80,3 +80,29 @@ export function isMissingTable(err: unknown): boolean { String(message ?? err), ); } + +// The n-operand form (`IN` with three or more values) names no operands, so it +// can't be told from two columns that disagree. A lookup that builds such a +// list checks its values with `fitsCharset` first. +const COLLATION_MIX_CODES = new Set([ + 'ER_CANT_AGGREGATE_2COLLATIONS', + 'ER_CANT_AGGREGATE_3COLLATIONS', +]); + +/** + * True when MySQL refused a comparison because a value in the statement does + * not convert to the column's charset (see `narrowCharset.ts`). `COERCIBLE` + * marks a literal operand, which tells this apart from two columns that + * genuinely disagree. + */ +export function isCharsetMismatch(err: unknown): boolean { + if (!err || typeof err !== 'object') return false; + const { code, message, sqlMessage } = err as { + code?: unknown; + message?: unknown; + sqlMessage?: unknown; + }; + if (typeof code !== 'string' || !COLLATION_MIX_CODES.has(code)) + return false; + return String(sqlMessage ?? message ?? '').includes('COERCIBLE'); +} diff --git a/src/backend/util/narrowCharset.test.ts b/src/backend/util/narrowCharset.test.ts new file mode 100644 index 000000000..2ad0c3b3f --- /dev/null +++ b/src/backend/util/narrowCharset.test.ts @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2024-present Puter Technologies Inc. + * + * This file is part of Puter. + * + * Puter is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published + * by the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import { describe, expect, it } from 'vitest'; +import { fitsCharset } from './narrowCharset.js'; + +describe('fitsCharset', () => { + it('accepts only 7-bit values for ascii', () => { + expect(fitsCharset('', 'ascii')).toBe(true); + expect(fitsCharset('plain_name-01\x7f', 'ascii')).toBe(true); + for (const value of ['m\u00e1genta', 'a\u0080', 'a\u00ff', '\u7528\u6237']) + expect(fitsCharset(value, 'ascii')).toBe(false); + }); + + it('accepts U+00A0 to U+00FF for latin1 and nothing above or between', () => { + expect(fitsCharset('jos\u00e9@example.com\u00a0\u00ff', 'latin1')).toBe( + true, + ); + // The C1 range and everything past U+00FF, cp1252 extras included. + for (const value of [ + 'a\u0080', + 'a\u009f', + 'a\u0100', + 'a\u20ac', + '\u7528\u6237', + 'a\u{1F600}', + ]) + expect(fitsCharset(value, 'latin1')).toBe(false); + }); +}); diff --git a/src/backend/util/narrowCharset.ts b/src/backend/util/narrowCharset.ts new file mode 100644 index 000000000..aa9fd3a35 --- /dev/null +++ b/src/backend/util/narrowCharset.ts @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2024-present Puter Technologies Inc. + * + * This file is part of Puter. + * + * Puter is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published + * by the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +/** + * Some MySQL columns are `ascii` or `latin1` while the connection is utf8mb4. + * Comparing such a column with a value MySQL cannot convert to its charset + * fails the whole statement (`Illegal mix of collations`) instead of matching + * no row. A value like that cannot be stored there either, so a lookup can + * answer "no match" without asking. + */ +export type NarrowCharset = 'ascii' | 'latin1'; + +/** + * Whether `value` is certain to convert to `charset`. + * + * Deliberately narrower than MySQL's `latin1` (cp1252): the C1 range + * U+0080–U+009F converts for only a few code points, and cp1252's extras above + * U+00FF (€, Œ, …) are refused too. No identifier stored in these columns uses + * either. + */ +export const fitsCharset = (value: string, charset: NarrowCharset): boolean => { + for (let i = 0; i < value.length; i++) { + const code = value.charCodeAt(i); + if (code <= 0x7f) continue; + if (charset === 'latin1' && code >= 0xa0 && code <= 0xff) continue; + return false; + } + return true; +};