Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 38 additions & 1 deletion graphile/graphile-i18n/src/__tests__/i18n.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ describe('graphile-i18n plugin', () => {

const connections = await (getConnections as any)(
{
schemas: ['i18n_test'],
schemas: ['i18n_test', 'i18n-quoted"schema'],
preset: testPreset,
useRoot: true,
authRole: 'postgres',
Expand All @@ -77,6 +77,43 @@ describe('graphile-i18n plugin', () => {
await teardown();
});

beforeEach(async () => {
await db.beforeEach();
});

afterEach(async () => {
await db.afterEach();
});

it('reads snake_case base and companion tables in a quoted schema', async () => {
const result = await query<{ allI18NQuotedSchemaSnakePosts: { nodes: PostNode[] } }>(`
{ allI18NQuotedSchemaSnakePosts(orderBy: ROW_ID_ASC) {
nodes { rowId title body localeStrings { langCode title body } }
} }
`, {}, false, { langCodes: ['fr'] });

expect(result.errors).toBeUndefined();
expect(result.data?.allI18NQuotedSchemaSnakePosts.nodes).toEqual([
{
rowId: 1, title: 'Source title', body: 'Source body',
localeStrings: { langCode: 'fr', title: 'Titre traduit', body: 'Corps traduit' },
},
{
rowId: 2, title: 'Untranslated title', body: null,
localeStrings: { langCode: null, title: 'Untranslated title', body: null },
},
]);
});

it('returns null for a missing row in a quoted schema', async () => {
const result = await query<{ i18NQuotedSchemaSnakePostByRowId: PostNode | null }>(`
{ i18NQuotedSchemaSnakePostByRowId(rowId: 999) { localeStrings { langCode title body } } }
`);

expect(result.errors).toBeUndefined();
expect(result.data?.i18NQuotedSchemaSnakePostByRowId).toBeNull();
});

it('should add localeStrings field to posts with @i18n tag', async () => {
const result = await query<AllPostsResult>(`
{
Expand Down
27 changes: 27 additions & 0 deletions graphile/graphile-i18n/src/__tests__/setup.sql
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,30 @@ SELECT setval('i18n_test.posts_id_seq', 10);
-- Grant access so withPgClient pool can query
GRANT ALL ON ALL TABLES IN SCHEMA i18n_test TO PUBLIC;
GRANT ALL ON ALL SEQUENCES IN SCHEMA i18n_test TO PUBLIC;

CREATE SCHEMA "i18n-quoted""schema";
GRANT USAGE ON SCHEMA "i18n-quoted""schema" TO PUBLIC;

CREATE TABLE "i18n-quoted""schema".snake_posts (
id serial PRIMARY KEY,
title text NOT NULL,
body text
);
COMMENT ON TABLE "i18n-quoted""schema".snake_posts IS E'@i18n snake_posts_translations';

CREATE TABLE "i18n-quoted""schema".snake_posts_translations (
id serial PRIMARY KEY,
snake_posts_id int NOT NULL REFERENCES "i18n-quoted""schema".snake_posts(id),
lang_code text NOT NULL,
title text NOT NULL,
body text,
UNIQUE (snake_posts_id, lang_code)
);

INSERT INTO "i18n-quoted""schema".snake_posts (id, title, body) VALUES
(1, 'Source title', 'Source body'),
(2, 'Untranslated title', NULL);
INSERT INTO "i18n-quoted""schema".snake_posts_translations (snake_posts_id, lang_code, title, body) VALUES
(1, 'fr', 'Titre traduit', 'Corps traduit');

GRANT SELECT ON ALL TABLES IN SCHEMA "i18n-quoted""schema" TO PUBLIC;
43 changes: 14 additions & 29 deletions graphile/graphile-i18n/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { TYPES } from '@dataplan/pg';
import { context as grafastContext, lambda, object } from 'grafast';
import type { GraphileConfig } from 'graphile-config';
import { withRequestPgClient } from 'graphile-plugin-utils';
import { sql } from 'pg-sql2';

import type { I18nPluginOptions, I18nTableInfo, TranslatableField } from './types';

Expand Down Expand Up @@ -95,16 +96,15 @@ export function createI18nPlugin(options: I18nPluginOptions = {}): GraphileConfi
const translationTableName = hasI18nTag(c);
if (!translationTableName) continue;

// Get schema name from the codec's pg extensions
let schemaName = (c.extensions as any)?.pg?.schemaName ?? 'public';
const pg = (c.extensions as any)?.pg;
if (!pg?.schemaName || !pg?.name) continue;
const schemaName = pg.schemaName;
const baseTable = pg.name;
let pkColumn: string | null = null;
let pkType = 'text';
for (const [, resource] of Object.entries(build.input.pgRegistry.pgResources)) {
const r = resource as any;
if (r.codec === c) {
// Try multiple sources for schema name
const rSchema = r.extensions?.pg?.schemaName ?? r.schemaName;
if (rSchema) schemaName = rSchema;
// Extract PK from the resource's uniques array
const uniques = r.uniques as Array<{ attributes: string[]; isPrimary?: boolean }> | undefined;
if (uniques) {
Expand All @@ -122,38 +122,21 @@ export function createI18nPlugin(options: I18nPluginOptions = {}): GraphileConfi
}
if (!pkColumn) continue;

// Find the translation codec. The @i18n tag value is the SQL table name
// (e.g. 'posts_translations'), but PostGraphile inflects codec names
// to camelCase (e.g. 'postsTranslations'). Match via resource name.
let translationCodec: PgCodecWithAttributes | null = null;
for (const [, resource] of Object.entries(build.input.pgRegistry.pgResources)) {
const r = resource as any;
if (!r.codec?.attributes) continue;
// Match by the resource's SQL name (which preserves snake_case)
const sqlName = r.codec?.extensions?.pg?.name ?? r.name;
if (sqlName === translationTableName) {
const translationPg = r.codec.extensions?.pg;
if (translationPg?.schemaName === schemaName && translationPg?.name === translationTableName) {
translationCodec = r.codec as PgCodecWithAttributes;
break;
}
}
// Fallback: try matching the inflected codec name directly
if (!translationCodec) {
const inflectedName = build.inflection.camelCase(translationTableName);
for (const [, tCodec] of Object.entries(build.input.pgRegistry.pgCodecs)) {
const tc = tCodec as any;
if (!tc.attributes) continue;
if (tc.name === translationTableName || tc.name === inflectedName) {
translationCodec = tc;
break;
}
}
}

if (!translationCodec) continue;

// Find FK column on translation table — convention first, then type match
let fkColumn: string | null = null;
const conventionalFk = `${c.name}_id`;
const conventionalFk = `${baseTable}_id`;
if (translationCodec.attributes[conventionalFk]) {
fkColumn = conventionalFk;
}
Expand Down Expand Up @@ -191,8 +174,8 @@ export function createI18nPlugin(options: I18nPluginOptions = {}): GraphileConfi
if (Object.keys(fields).length === 0) continue;

i18nRegistry[c.name] = {
baseTable: c.name,
translationTable: translationTableName,
baseTable,
translationTable: (translationCodec.extensions as any).pg.name,
schemaName,
fkColumn,
pkColumn,
Expand Down Expand Up @@ -235,15 +218,17 @@ export function createI18nPlugin(options: I18nPluginOptions = {}): GraphileConfi
const localeType = localeTypeCache[localeTypeName];

const { schemaName, baseTable, translationTable, fkColumn, pkColumn, pkType, fields: i18nFields } = info;
const baseTableSql = sql.compile(sql.identifier(schemaName, baseTable)).text;
const translationTableSql = sql.compile(sql.identifier(schemaName, translationTable)).text;

const coalescedCols = Object.values(i18nFields)
.map(f => `coalesce(v."${f.column}", b."${f.column}") as "${f.column}"`)
.join(', ');

// Build the SQL query template
const sqlQuery = `SELECT v."${langCodeColumn}" AS "lang_code", ${coalescedCols}
FROM "${schemaName}"."${baseTable}" b
LEFT JOIN "${schemaName}"."${translationTable}" v
FROM ${baseTableSql} b
LEFT JOIN ${translationTableSql} v
ON v."${fkColumn}" = b."${pkColumn}"
AND array_position($2::text[], v."${langCodeColumn}") IS NOT NULL
WHERE b."${pkColumn}" = $1::${pkType}
Expand Down
70 changes: 69 additions & 1 deletion graphql/server-test/__tests__/websocket.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,21 @@ const DATABASE = '80a2eaaf-f77e-4bfe-8506-df929ef1b8d9';
const shared = path.join(__dirname, '../../../__fixtures__/seed');
let releasePulse: () => void;
const probe = makeExtendSchemaPlugin({
typeDefs: 'extend type Subscription { identity: String! pulse: Int! }',
typeDefs: `extend type Query { requestLanguages: String! }
extend type Subscription { identity: String! pulse: Int! requestLanguages: String! }`,
plans: {
Query: {
requestLanguages: () => lambda(context(), (ctx: { langCodes?: string[] }) => JSON.stringify(ctx.langCodes ?? null))
},
Subscription: {
requestLanguages: {
subscribePlan() {
return lambda(context(), async function* (ctx: { langCodes?: string[] }) {
yield JSON.stringify(ctx.langCodes ?? null);
});
},
plan: ($event) => $event
},
pulse: {
subscribePlan() {
return lambda(context(), async function* () {
Expand Down Expand Up @@ -127,6 +139,62 @@ describe('public tenant WebSocket subscriptions', () => {
expect(JSON.parse(result.data.identity)['jwt.claims.user_id']).toBe(ACTOR);
});

it.each([
[undefined, null],
['', null],
[';;;', null],
['*;q=1, fr;q=0', null],
['en;q=0', []],
['fr; q=0, en;q=0.5', ['en']],
['fr ; q = 0, en ; q = 0.5', ['en']],
['zh-hant, zh-Hant-TW;q=0.9', ['zh-Hant', 'zh-Hant-TW']],
['de-DE-1996', ['de-DE-1996']],
['SL-ROZAJ, es-419;q=0.9, EN-latn-us;q=0.8', ['sl-rozaj', 'es-419', 'en-Latn-US']],
['fr;q=0.8, en;q=1, fr-CA;q=0.9', ['en', 'fr-CA', 'fr']],
['FR-ca, fr;q=0.9, fr;q=0.8', ['fr-CA', 'fr']]
])('parses HTTP request languages %p', async (header, expected) => {
const req = request.post('/graphql').set('Host', HOST).set('Authorization', `Bearer ${token}`);
if (header !== undefined) req.set('Accept-Language', header as string);
const result = await req.send({ query: '{ requestLanguages }' });
expect(result.status).toBe(200);
expect(result.body.errors).toBeUndefined();
expect(JSON.parse(result.body.data.requestLanguages)).toEqual(expected);
});

it('keeps HTTP request languages independent across cached handler executions', async () => {
for (const language of ['en', 'fr', 'en', 'fr']) {
const result = await request.post('/graphql').set('Host', HOST)
.set('Authorization', `Bearer ${token}`).set('Accept-Language', language)
.send({ query: '{ requestLanguages }' });
expect(result.body.errors).toBeUndefined();
expect(JSON.parse(result.body.data.requestLanguages)).toEqual([language]);
}
});

it.each([
[{}, { 'Accept-Language': 'fr' }, ['fr']],
[{}, { 'Accept-Language': 'de-DE-1996' }, ['de-DE-1996']],
[{ 'Accept-Language': 'fr; q=0, en;q=0.5' }, {}, ['en']],
[{ 'Accept-Language': 'fr-CA, fr;q=0.8, en;q=0.5' }, {}, ['fr-CA', 'fr', 'en']],
[{ 'aCcEpT-LaNgUaGe': 'en' }, { 'Accept-Language': 'fr' }, ['en']],
[{}, {}, null]
])('parses WebSocket request languages from parameters or upgrade headers %#', async (params, headers, expected) => {
const result = await subscribe({ Authorization: `Bearer ${token}`, ...params }, headers,
'subscription { requestLanguages }');
expect(result.errors).toBeUndefined();
expect(JSON.parse(result.data.requestLanguages)).toEqual(expected);
});

it.each([
{ 'Accept-Language': ['fr'] },
{ 'Accept-Language': 'fr', 'accept-language': 'en' }
])('rejects malformed WebSocket request languages %p', async (params) => {
await expect(subscribe({ Authorization: `Bearer ${token}`, ...params }, {},
'subscription { requestLanguages }')).rejects.toEqual(expect.arrayContaining([
expect.objectContaining({ message: 'Invalid Accept-Language', extensions: expect.objectContaining({ code: 'BAD_USER_INPUT' }) })
]));
});

it.each([
{ query: `subscription { identity } #${'é'.repeat(600)}` },
{ query: 'subscription { identity }', variables: { value: 'é'.repeat(600) } }
Expand Down
2 changes: 2 additions & 0 deletions graphql/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
"@pgpmjs/types": "workspace:^",
"@pgsql/quotes": "^18.2.4",
"@simplewebauthn/server": "13.3.2",
"accept-language-parser": "^1.5.0",
"cookie-parser": "^1.4.7",
"cors": "^2.8.6",
"deepmerge": "^4.3.1",
Expand Down Expand Up @@ -85,6 +86,7 @@
"postgraphile": "5.1.4"
},
"devDependencies": {
"@types/accept-language-parser": "^1.5.4",
"@aws-sdk/client-s3": "^3.1052.0",
"@types/cookie-parser": "^1.4.10",
"@types/cors": "^2.8.17",
Expand Down
27 changes: 24 additions & 3 deletions graphql/server/src/middleware/graphile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type { ComputeConfig } from '@constructive-io/express-context';
import { DEFAULT_REQUEST_PROTECTION, protectionPgSettings } from '@constructive-io/express-context';
import type { ConstructiveOptions } from '@constructive-io/graphql-types';
import { Logger } from '@pgpmjs/logger';
import { parse as parseAcceptLanguage } from 'accept-language-parser';
import type { NextFunction, Request, RequestHandler, Response } from 'express';
import {
cacheGraphileInstance,
Expand Down Expand Up @@ -78,6 +79,24 @@ export function clearInFlightMap(): void {
const log = new Logger('graphile');
const reqLabel = (req: Request): string => (req.requestId ? `[${req.requestId}]` : '[req]');

const requestLanguages = (header: string | string[] | undefined): string[] | undefined => {
const value = (Array.isArray(header) ? header.join(',') : header ?? '')
.replace(/\s*;\s*/g, ';').replace(/\s*=\s*/g, '=');
const preferences = parseAcceptLanguage(value);
const languages = preferences
.filter(({ code, quality }) => code !== '*' && quality > 0 && quality <= 1)
.map(({ code, script, region }) => [code, script, region].filter(Boolean)
.map((subtag, index) => {
if (index === 0) return subtag.toLowerCase();
if (/^[a-z]{4}$/i.test(subtag)) return subtag[0].toUpperCase() + subtag.slice(1).toLowerCase();
if (/^(?:[a-z]{2}|[0-9]{3})$/i.test(subtag)) return subtag.toUpperCase();
return subtag.toLowerCase();
}).join('-'));
if (languages.length) return [...new Set(languages)];
return preferences.length && !preferences.some(({ code, quality }) => code === '*' && quality > 0)
? [] : undefined;
};

/**
* Build a PostGraphile v5 preset for a tenant.
*
Expand Down Expand Up @@ -211,6 +230,7 @@ const buildPreset = (
? await authenticatedWebSocketRequest(ws.request, ws.normalizedConnectionParams, serverOptions)
: (requestContext as { expressv4?: { req?: Request } })?.expressv4?.req;
if (ws && req) ws.request = req;
const langCodes = requestLanguages(req?.headers?.['accept-language']);
const context: Record<string, string> = {};

// Timeouts travel with the transaction as GUCs, so they bound the work
Expand Down Expand Up @@ -286,7 +306,7 @@ const buildPreset = (
pgSettings['request.id'] = req.requestId;
}

return { pgSettings };
return { pgSettings, langCodes };
}

// Private (in-cluster) surface: there is no token — identity
Expand Down Expand Up @@ -322,7 +342,7 @@ const buildPreset = (
if (req.requestId) {
pgSettings['request.id'] = req.requestId;
}
return { pgSettings };
return { pgSettings, langCodes };
}
}

Expand All @@ -345,7 +365,8 @@ const buildPreset = (
}

return {
pgSettings: anonSettings
pgSettings: anonSettings,
langCodes
};
}
}
Expand Down
7 changes: 7 additions & 0 deletions graphql/server/src/middleware/websocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,13 @@ export async function authenticatedWebSocketRequest(
}
req.headers.authorization = authorizations[0][1];
}
const languages = Object.entries(params ?? {}).filter(([key]) => key.toLowerCase() === 'accept-language');
if (languages.length) {
if (languages.length !== 1 || typeof languages[0][1] !== 'string') {
throw new SafeError('Invalid Accept-Language', { code: 'BAD_USER_INPUT' });
}
req.headers['accept-language'] = languages[0][1];
}
if (!getBearerToken(req) && requiresAuth) {
throw new SafeError('Authentication required', { code: 'UNAUTHENTICATED' });
}
Expand Down
6 changes: 6 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading