A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(api/sso): validate SSO button labels and domain lists
Hampus449c7d4d80f4
diff --git a/fluxer_api/src/api/admin/tests/SsoDiscoveryCache.test.ts b/fluxer_api/src/api/admin/tests/SsoDiscoveryCache.test.tsnew file mode 100644index 000000000..b0de897f3--- /dev/null+++ b/fluxer_api/src/api/admin/tests/SsoDiscoveryCache.test.ts@@ -0,0 +1,60 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {ssoDiscoveryCacheKey} from '@app/api/auth/services/SsoService';+import {createTestAccount, setUserACLs, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';+import {getCacheService} from '@app/api/middleware/ServiceSingletons';+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';+import {createBuilder} from '@app/api/test/TestRequestBuilder';+import {AdminACLs} from '@fluxer/constants/src/AdminACLs';+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';++const OLD_ISSUER = 'https://old-sso.example.com';+const NEW_ISSUER = 'https://new-sso.example.com';++describe('SSO provider discovery cache', () => {+ let harness: ApiTestHarness;+ let admin: TestAccount;++ beforeAll(async () => {+ harness = await createApiTestHarness();+ });++ beforeEach(async () => {+ await harness.reset();+ admin = await setUserACLs(harness, await createTestAccount(harness), [+ AdminACLs.AUTHENTICATE,+ AdminACLs.INSTANCE_CONFIG_VIEW,+ AdminACLs.INSTANCE_CONFIG_UPDATE,+ ]);+ });++ afterAll(async () => {+ await harness.shutdown();+ });++ const saveSso = (sso: Record<string, unknown>) =>+ createBuilder(harness, admin.token).patch('/admin/instance/config').body({sso}).execute();++ const cachedFor = (issuer: string) => getCacheService().get(ssoDiscoveryCacheKey(issuer));++ it('forgets the discovered endpoints of the old and new issuer when the SSO settings are saved', async () => {+ await saveSso({enabled: false, issuer: OLD_ISSUER});+ const stale = {issuer: OLD_ISSUER, authorization_endpoint: 'https://old-sso.example.com/authorize'};+ await getCacheService().set(ssoDiscoveryCacheKey(OLD_ISSUER), stale, 3600);+ await getCacheService().set(ssoDiscoveryCacheKey(NEW_ISSUER), {...stale, issuer: NEW_ISSUER}, 3600);++ await saveSso({enabled: false, issuer: NEW_ISSUER});++ expect(await cachedFor(OLD_ISSUER)).toBeNull();+ expect(await cachedFor(NEW_ISSUER)).toBeNull();+ });++ it('forgets the discovered endpoints when other SSO settings change', async () => {+ await saveSso({enabled: false, issuer: OLD_ISSUER});+ await getCacheService().set(ssoDiscoveryCacheKey(OLD_ISSUER), {issuer: OLD_ISSUER}, 3600);++ await saveSso({client_id: 'another-client'});++ expect(await cachedFor(OLD_ISSUER)).toBeNull();+ });+});diff --git a/fluxer_api/src/api/instance/SsoConfigValidation.test.ts b/fluxer_api/src/api/instance/SsoConfigValidation.test.tsindex a3e4b9ac3..2d18e8748 100644--- a/fluxer_api/src/api/instance/SsoConfigValidation.test.ts+++ b/fluxer_api/src/api/instance/SsoConfigValidation.test.ts@@ -1,6 +1,11 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import {isTestSsoProvider, normalizeAndValidateSsoConfig} from '@app/api/instance/SsoConfigValidation';+import {+ isTestSsoProvider,+ normalizeAndValidateSsoConfig,+ normalizeSsoButtonLabel,+} from '@app/api/instance/SsoConfigValidation';+import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';import {describe, expect, it} from 'vitest';@@ -53,3 +58,60 @@ describe('normalizeAndValidateSsoConfig placeholder endpoints', () => {).rejects.toBeInstanceOf(InputValidationError);});});++describe('normalizeSsoButtonLabel', () => {+ it('trims the text and treats empty text as the default', () => {+ expect(normalizeSsoButtonLabel(' Sign in with Acme ')).toBe('Sign in with Acme');+ expect(normalizeSsoButtonLabel(' ')).toBeNull();+ expect(normalizeSsoButtonLabel('')).toBeNull();+ expect(normalizeSsoButtonLabel(null)).toBeNull();+ });++ it('accepts 64 characters, including right-to-left text and emoji joiners', () => {+ expect(normalizeSsoButtonLabel('a'.repeat(64))).toBe('a'.repeat(64));+ expect(normalizeSsoButtonLabel('\u0648\u0631\u0648\u062F \u0628\u0627 SSO')).toBe(+ '\u0648\u0631\u0648\u062F \u0628\u0627 SSO',+ );+ expect(normalizeSsoButtonLabel('Acme \u{1F469}\u200D\u{1F4BB}')).toBe('Acme \u{1F469}\u200D\u{1F4BB}');+ });++ it('rejects control, line break and bidirectional formatting characters', () => {+ for (const label of [+ 'Sign\tin',+ 'Sign\nin',+ 'Sign\u0000in',+ 'Sign\u0085in',+ 'Sign\u2028in',+ 'Sign\u202Ein',+ 'Sign\u2067in',+ ]) {+ expect(() => normalizeSsoButtonLabel(label)).toThrow(InputValidationError);+ }+ });++ it('rejects text made only of invisible characters', () => {+ for (const label of ['\u200B', '\u3164', '\u2800', '\u00AD\u200F', '\u200B \uFEFF']) {+ expect(() => normalizeSsoButtonLabel(label)).toThrow(InputValidationError);+ }+ });+});++describe('normalizeAndValidateSsoConfig URL scheme', () => {+ it('names the https rule when an endpoint uses http', async () => {+ await expect(+ normalizeAndValidateSsoConfig(+ {...ssoConfig({authorizationUrl: null, tokenUrl: null}), issuer: 'http://sso.example.com'},+ {testModeEnabled: false},+ ),+ ).rejects.toMatchObject({localizedErrors: [{path: 'issuer', code: ValidationErrorCodes.URL_MUST_USE_HTTPS}]});+ });++ it('keeps the format code for text that is not a URL', async () => {+ await expect(+ normalizeAndValidateSsoConfig(+ {...ssoConfig({authorizationUrl: null, tokenUrl: null}), issuer: 'not a url'},+ {testModeEnabled: false},+ ),+ ).rejects.toMatchObject({localizedErrors: [{path: 'issuer', code: ValidationErrorCodes.INVALID_URL_FORMAT}]});+ });+});diff --git a/fluxer_api/src/api/instance/SsoConfigValidation.ts b/fluxer_api/src/api/instance/SsoConfigValidation.tsindex 6b5ef1e54..be44b0021 100644--- a/fluxer_api/src/api/instance/SsoConfigValidation.ts+++ b/fluxer_api/src/api/instance/SsoConfigValidation.ts@@ -49,8 +49,25 @@ function normalizeOptionalSsoString(value: string | null): string | null {return trimmed.length > 0 ? trimmed : null;}-function throwInvalidDomain(): never {- throw InputValidationError.fromCode('allowed_domains', ValidationErrorCodes.INVALID_FORMAT);+const SSO_BUTTON_LABEL_FORBIDDEN_REGEX = /[\p{Cc}\u2028\u2029\u202A-\u202E\u2066-\u2069]/u;+const SSO_BUTTON_LABEL_INVISIBLE_REGEX = /[\p{Default_Ignorable_Code_Point}\u2800\s]/gu;++export function normalizeSsoButtonLabel(value: string | null): string | null {+ const normalized = normalizeOptionalSsoString(value);+ if (normalized === null) {+ return null;+ }+ if (+ SSO_BUTTON_LABEL_FORBIDDEN_REGEX.test(normalized) ||+ normalized.replace(SSO_BUTTON_LABEL_INVISIBLE_REGEX, '').length === 0+ ) {+ throw InputValidationError.fromCode('button_label', ValidationErrorCodes.INVALID_FORMAT);+ }+ return normalized;+}++function throwInvalidDomain(field: string, domain: string): never {+ throw InputValidationError.fromCode(field, ValidationErrorCodes.INVALID_ALLOWED_DOMAIN, {domain});}export function deriveSsoRedirectUri(webAppEndpoint: string): string {@@ -74,34 +91,35 @@ export function isTestSsoProvider();}-export function normalizeSsoAllowedEmailDomains(domains: unknown): Array<string> {+export function normalizeAllowedEmailDomains(domains: unknown, field = 'allowed_domains'): Array<string> {const result = SsoAllowedDomainsSchema.safeParse(domains);- if (!result.success) throwInvalidDomain();+ if (!result.success) throw InputValidationError.fromCode(field, ValidationErrorCodes.INVALID_FORMAT);const normalized = new Set<string>();for (const rawDomain of result.data) {- const trimmed = rawDomain.trim().toLowerCase();- if (!trimmed) {+ const entry = rawDomain.trim();+ if (!entry) {continue;}+ const lowered = entry.toLowerCase();if (- trimmed.includes('@') ||- trimmed.includes('/') ||- trimmed.includes('\\') ||- trimmed.includes(':') ||- trimmed.startsWith('.') ||- trimmed.endsWith('.') ||- trimmed.startsWith('*.') ||- trimmed.includes('*')+ lowered.includes('@') ||+ lowered.includes('/') ||+ lowered.includes('\\') ||+ lowered.includes(':') ||+ lowered.startsWith('.') ||+ lowered.endsWith('.') ||+ lowered.startsWith('*.') ||+ lowered.includes('*')) {- throwInvalidDomain();+ throwInvalidDomain(field, entry);}- const asciiDomain = domainToASCII(trimmed);+ const asciiDomain = domainToASCII(lowered);if (!asciiDomain || asciiDomain.length > 253 || !asciiDomain.includes('.')) {- throwInvalidDomain();+ throwInvalidDomain(field, entry);}const labels = asciiDomain.split('.');if (labels.some((label) => !DOMAIN_LABEL_REGEX.test(label)) || /^\d+$/.test(labels[labels.length - 1] ?? '')) {- throwInvalidDomain();+ throwInvalidDomain(field, entry);}normalized.add(asciiDomain);}@@ -115,7 +133,10 @@ export async function validateSsoPublicOutboundUrl(rawUrl: string, fieldName: st} catch {throw InputValidationError.fromCode(fieldName, ValidationErrorCodes.INVALID_URL_FORMAT);}- if (parsedUrl.protocol !== 'https:' || parsedUrl.username || parsedUrl.password || parsedUrl.hash) {+ if (parsedUrl.protocol !== 'https:') {+ throw InputValidationError.fromCode(fieldName, ValidationErrorCodes.URL_MUST_USE_HTTPS);+ }+ if (parsedUrl.username || parsedUrl.password || parsedUrl.hash) {throw InputValidationError.fromCode(fieldName, ValidationErrorCodes.INVALID_URL_FORMAT);}try {@@ -170,7 +191,7 @@ export async function normalizeAndValidateSsoConfig(userInfoUrl: normalizeOptionalSsoString(config.userInfoUrl),jwksUrl: normalizeOptionalSsoString(config.jwksUrl),clientId: normalizeOptionalSsoString(config.clientId),- allowedEmailDomains: normalizeSsoAllowedEmailDomains(config.allowedEmailDomains),+ allowedEmailDomains: normalizeAllowedEmailDomains(config.allowedEmailDomains),};const isTestProvider = isTestSsoProvider(baseConfig, options.testModeEnabled);const skipUrlValidation = isTestProvider || !baseConfig.enabled;