From 2088dedf4298b528da65fa3e289f851fe66c96ba Mon Sep 17 00:00:00 2001 From: Daniel Salazar Date: Wed, 25 Nov 2026 14:17:04 -0700 Subject: [PATCH] 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. --- .../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 +++++++++ src/backend/stores/user/UserStore.test.ts | 31 +++++++++- src/backend/stores/user/UserStore.ts | 56 ++++++++----------- src/backend/util/dbError.test.ts | 45 +++++++++++++++ src/backend/util/dbError.ts | 24 ++++++++ src/backend/util/narrowCharset.test.ts | 46 +++++++++++++++ src/backend/util/narrowCharset.ts | 45 +++++++++++++++ 14 files changed, 320 insertions(+), 43 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 5117014ce..6dd53ab21 100644 --- a/src/backend/services/metering/MeteringService.ts +++ b/src/backend/services/metering/MeteringService.ts @@ -711,7 +711,7 @@ export class MeteringService extends PuterService { return await this.#addonsForSettle(actor); } catch (e) { settleReadError = e as Error; - return null; + return undefined; } })(), ]); @@ -3087,7 +3087,7 @@ export class MeteringService extends PuterService { userId: string; actorUsages: UsageByType; actorSubscription: SubscriptionPolicy; - actorAddons: UsageAddons; + actorAddons?: UsageAddons; incrementCost: number; batchUsages: UsageInput[]; }): void { @@ -3113,9 +3113,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/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..c06e7ca41 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,47 @@ 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 (...)` reports the three- and n-operand forms. + 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); + expect( + isCharsetMismatch({ + code: 'ER_CANT_AGGREGATE_NCOLLATIONS', + message: "Illegal mix of collations for operation ' IN ' (COERCIBLE)", + }), + ).toBe(true); + }); + + 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..e17c8fe66 100644 --- a/src/backend/util/dbError.ts +++ b/src/backend/util/dbError.ts @@ -80,3 +80,27 @@ export function isMissingTable(err: unknown): boolean { String(message ?? err), ); } + +const COLLATION_MIX_CODES = new Set([ + 'ER_CANT_AGGREGATE_2COLLATIONS', + 'ER_CANT_AGGREGATE_3COLLATIONS', + 'ER_CANT_AGGREGATE_NCOLLATIONS', +]); + +/** + * 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; +};