feat(maps): MAP_EXTRA_CONNECT_HOSTS adds the operator's map hosts to the CSP

A GL map fetches its tiles and its style, so a template on a host of the
operator's own (a self-hosted tile server) was refused by connect-src while
Leaflet drew it as images. The new variable lists such hosts; each entry
becomes an https source in connect-src and the same list reaches the client
as map_extra_connect_hosts in the app config, so the renderer choice and the
policy can never disagree.

The variable is owned by readEnv() like the rest of the maps namespace and
read once when the middleware is applied. The boot refuses an entry outside
the shared grammar; a path that skips the boot check drops it, so a bad
value never widens the policy. Unset, the CSP and the app config are as
before apart from an empty list.

Documented in .env.example, docker-compose.yml, the Helm values and
ConfigMap and the wiki. Making room for the app config field shrinks
auth.service.ts by one line, and its size baseline follows.
This commit is contained in:
Maurice
2026-11-30 14:23:55 +01:00
parent 6c68f6ebec
commit 51dc0e6a82
16 changed files with 179 additions and 9 deletions
+2
View File
@@ -90,6 +90,8 @@ DEMO_MODE=false # Demo mode: resets data hourly
# AMAP_API_SECRET= # The private secret (数字签名) of that key. Required exactly when the key was created with signing enabled, because such a key rejects every unsigned request. Leave unset otherwise.
# AMAP_API_BASE=https://restapi.amap.com # Send the Amap calls through an egress proxy, a cache or a gateway that speaks the same API instead of restapi.amap.com directly. (default: https://restapi.amap.com)
# MAP_EXTRA_CONNECT_HOSTS=tiles.example.com # Hosts of your own map tiles or vector styles that the GL maps (MapLibre, Mapbox) may load, comma-separated, e.g. a self-hosted tile server. Each entry is a host name (tiles.example.com), optionally with a port (tiles.example.com:8443) or as a wildcard over its subdomains (*.tiles.example.com); https is implied, so no scheme or path. They are added to the Content-Security-Policy and told to the app, which otherwise draws a map template on such a host with the classic 2D map. An entry that is not a plain host name aborts startup. Read once at startup. (default: none)
# TRANSIT_API_URL=https://api.transitous.org # Base URL of the transit routing API the server proxies to. Point it at your own MOTIS instance to keep transit searches off third-party servers. A trailing slash is stripped. (default: https://api.transitous.org)
# TREK_PLACE_PHOTO_DIR= # Directory for cached Google place photos, e.g. a dedicated volume. Unset, they live in uploads/photos/google. Read once at startup. (default: uploads/photos/google)
+1 -1
View File
@@ -6,7 +6,7 @@
"src/db/repositories/Trips.repository.ts": 1120,
"src/db/repositories/Users.repository.ts": 1421,
"src/nest/atlas/atlas.service.ts": 1166,
"src/nest/auth/auth.service.ts": 1115,
"src/nest/auth/auth.service.ts": 1114,
"src/nest/budget/budget.service.ts": 1607,
"src/nest/collections/collections.service.ts": 1386,
"src/nest/doc-sync/doc-sync.service.ts": 1060,
+8 -1
View File
@@ -30,7 +30,7 @@ import {
resolveSessionTtlMs,
stripTrailingSlashes,
} from './parsers';
import { SUPPORTED_LANGUAGE_CODES } from '@trek/shared';
import { SUPPORTED_LANGUAGE_CODES, parseMapConnectHosts } from '@trek/shared';
export type RawEnv = Record<string, string | undefined>;
@@ -193,6 +193,13 @@ export function deriveMaps(raw: RawEnv) {
mapboxToken: raw.MAPBOX_ACCESS_TOKEN || undefined,
/** CARTO basemap key; without one the tiles come back watermarked (#2054). Public too. */
cartoKey: raw.CARTO_API_KEY || undefined,
/**
* MAP_EXTRA_CONNECT_HOSTS: the tile and style hosts a GL map may fetch from
* beyond the ones TREK ships, added to the CSP connect-src and handed to the
* client in the app config, so both read one list. The boot refuses a bad
* entry; read without that check (tests), a bad entry is left out, never kept.
*/
extraConnectHosts: parseMapConnectHosts(raw.MAP_EXTRA_CONNECT_HOSTS).hosts,
};
}
+9 -1
View File
@@ -18,7 +18,7 @@ import {
parseDurationMs,
parseLinkLocalAllowList,
} from './parsers';
import { SUPPORTED_LANGUAGE_CODES } from '@trek/shared';
import { SUPPORTED_LANGUAGE_CODES, parseMapConnectHosts } from '@trek/shared';
import { z } from 'zod';
@@ -231,6 +231,14 @@ export const envSchema = z.object({
AMAP_API_SECRET: anyString,
MAPBOX_ACCESS_TOKEN: anyString,
CARTO_API_KEY: anyString,
// Tile and style hosts a GL map may fetch from beyond the ones TREK ships. Every
// entry widens the Content-Security-Policy, so one that is not a plain host name
// refuses the boot rather than being dropped or read loosely.
MAP_EXTRA_CONNECT_HOSTS: optionalWith(
(v) => parseMapConnectHosts(v).invalid.length === 0,
'must be a comma-separated list of host names such as tiles.example.com, *.tiles.example.com or ' +
'tiles.example.com:8443 (https is implied: no scheme, path or user)',
),
DEMO_MODE: boolStr,
DEMO_ADMIN_USER: anyString,
DEMO_ADMIN_EMAIL: anyString,
@@ -155,6 +155,7 @@ export function applyGlobalMiddleware(
const { http = httpConfig(), extraConnectSrc = [] } = opts;
const liveHttp = readEnv().http;
const { nodeEnv, isProduction } = readEnv().app;
const mapExtraConnectSrc = readEnv().maps.extraConnectHosts.map((host) => `https://${host}`);
// Request correlation comes first, so the whole pipeline and every line the
// request logs run under its id. An X-Request-Id set by the proxy in front is
@@ -367,6 +368,10 @@ export function applyGlobalMiddleware(
// this the browser blocks it silently: no error the app can catch, just legs
// that never route (#1797).
...extraConnectSrc,
// The operator's own tile and style hosts (MAP_EXTRA_CONNECT_HOSTS). A GL map
// fetches its tiles and its style, so a host missing here draws nothing. The
// client reads the same list from the app config and draws only what it names.
...mapExtraConnectSrc,
],
workerSrc: ["'self'", 'blob:'],
childSrc: ["'self'", 'blob:'],
+4 -5
View File
@@ -322,15 +322,12 @@ export class AuthService {
const placesProvider = isPlacesProviderChoice(placesProviderRow) ? placesProviderRow : 'auto';
const oidcDisplayName = readEnv().oidc.displayName || settings.get('oidc_display_name') || null;
const oidcConfigured = isOidcConfiguredIn(settings);
const requireMfaValue = settings.get('require_mfa');
const notifChannel = settings.get('notification_channel') || 'none';
const tripReminderSetting = settings.get('notify_trip_reminder');
const hasSmtpHost = !!(readEnv().smtp.host || settings.get('smtp_host'));
const notifChannelsRaw = settings.get('notification_channels') || notifChannel;
const activeChannels = notifChannelsRaw === 'none' ? [] : notifChannelsRaw.split(',').map((c: string) => c.trim()).filter(Boolean);
const hasWebhookEnabled = activeChannels.includes('webhook');
const hasPushEnabled = activeChannels.includes(WEB_PUSH_CHANNEL_ID);
const tripRemindersEnabled = tripReminderSetting !== 'false';
const setupComplete = userCount > 0 && (await this.usersRepo.findAdminNeedingPasswordChange()) === null;
return {
@@ -359,7 +356,7 @@ export class AuthService {
places_provider: placesProvider,
oidc_configured: oidcConfigured,
oidc_display_name: oidcConfigured ? (oidcDisplayName || 'SSO') : undefined,
require_mfa: requireMfaValue === 'true',
require_mfa: settings.get('require_mfa') === 'true',
// The canonical live-read: same query + DEFAULT_ALLOWED_EXTENSIONS
// fallback the upload filters use, so the client's picker and the
// server's acceptance can never drift (the historical inline copy here
@@ -367,6 +364,8 @@ export class AuthService {
allowed_file_types: await this.allowedFileTypes.get(),
// FILE_UPLOAD_LIMIT_MB, so the pickers refuse a file before the upload starts (#1364).
max_upload_mb: readEnv().files.uploadLimitMb,
// The operator's own map hosts, which the CSP lets a GL map fetch from (MAP_EXTRA_CONNECT_HOSTS).
map_extra_connect_hosts: readEnv().maps.extraConnectHosts,
// Whether the configuration belongs to whoever operates this install
// rather than to its admin. The client uses it to stop offering settings
// the server would refuse anyway — it is an honesty flag for the UI, never
@@ -379,7 +378,7 @@ export class AuthService {
notification_channel: notifChannel,
notification_channels: activeChannels,
available_channels: { email: hasSmtpHost, webhook: hasWebhookEnabled, push: hasPushEnabled, inapp: true },
trip_reminders_enabled: tripRemindersEnabled,
trip_reminders_enabled: settings.get('notify_trip_reminder') !== 'false',
...publicFeatureFlags(settings),
permissions: authenticatedUser ? (await this.permissions.getAllPermissions()) : undefined,
// Case-sensitive on purpose (legacy parity).
@@ -0,0 +1,59 @@
/**
* MAP_EXTRA_CONNECT_HOSTS end to end, on the whole app: the operator's own map
* hosts reach the Content-Security-Policy the server sends and the app config
* the client reads, as one list, so a GL map is only asked to draw what the
* browser lets it fetch. Without the variable both stay as they were.
*/
import { buildApp } from '../../src/bootstrap';
import type { INestApplication } from '@nestjs/common';
import { mapExtraConnectHostsSchema } from '@trek/shared';
import request from 'supertest';
import { afterEach, describe, expect, it, vi } from 'vitest';
let app: INestApplication | undefined;
afterEach(async () => {
await app?.close();
app = undefined;
vi.unstubAllEnvs();
});
/** The connect-src sources and the app config of an app built with `hosts` as MAP_EXTRA_CONNECT_HOSTS. */
async function bootWith(hosts: string) {
vi.stubEnv('MAP_EXTRA_CONNECT_HOSTS', hosts);
app = await buildApp();
const res = await request(app.getHttpServer()).get('/api/auth/app-config');
const connectSrc =
String(res.headers['content-security-policy'] ?? '')
.split(';')
.map((directive) => directive.trim())
.find((directive) => directive.startsWith('connect-src'))
?.split(/\s+/)
.slice(1) ?? [];
return { status: res.status, config: res.body as Record<string, unknown>, connectSrc };
}
describe('the operator map hosts', () => {
it('MAPHOST-E2E-001: unset, the app config lists none and the policy names only the shipped hosts', async () => {
const { status, config, connectSrc } = await bootWith('');
expect(status).toBe(200);
expect(config.map_extra_connect_hosts).toEqual([]);
expect(connectSrc).toContain('https://tiles.openfreemap.org');
expect(connectSrc.some((source) => source.includes('example'))).toBe(false);
});
it('MAPHOST-E2E-002: set, both carry the same hosts, the config in the shared contract', async () => {
const { config, connectSrc } = await bootWith('Tiles.Example.com, *.maps.example.org:8443');
const hosts = mapExtraConnectHostsSchema.parse(config.map_extra_connect_hosts);
expect(hosts).toEqual(['tiles.example.com', '*.maps.example.org:8443']);
for (const host of hosts) expect(connectSrc).toContain(`https://${host}`);
expect(connectSrc).toContain('https://tiles.openfreemap.org');
});
it('MAPHOST-E2E-003: an entry the boot would refuse reaches neither the policy nor the client', async () => {
const { config, connectSrc } = await bootWith('tiles.example.com,https://evil.example.com,*.com');
expect(config.map_extra_connect_hosts).toEqual(['tiles.example.com']);
expect(connectSrc.filter((source) => source.includes('evil') || source === 'https://*.com')).toEqual([]);
});
});
@@ -90,6 +90,20 @@ describe('the Places and Amap switches in the templates', () => {
});
});
describe('MAP_EXTRA_CONNECT_HOSTS in the templates', () => {
// It widens the browser's policy, so an operator with a tile server of their
// own has to find it where they look, and the chart has to pass it through.
it('.env.example and docker-compose.yml document it', () => {
expect(envExample).toContain('# MAP_EXTRA_CONNECT_HOSTS=');
expect(compose).toContain('# - MAP_EXTRA_CONNECT_HOSTS=');
});
it('the Helm ConfigMap passes through what the values file documents', () => {
expect(helmValues).toContain('# MAP_EXTRA_CONNECT_HOSTS:');
expect(helmConfigMap).toContain('MAP_EXTRA_CONNECT_HOSTS: {{ .Values.env.MAP_EXTRA_CONNECT_HOSTS | quote }}');
});
});
describe('the Web Push keys in the templates', () => {
// All optional, since TREK keeps a generated pair in its database; an
// operator who wants their own pair has to find the names somewhere.
@@ -519,6 +519,23 @@ describe('deriveMaps', () => {
});
});
describe('deriveMaps extraConnectHosts', () => {
it('reads MAP_EXTRA_CONNECT_HOSTS as a lower-cased list and nothing when unset', () => {
expect(deriveMaps({} as never).extraConnectHosts).toEqual([]);
expect(
deriveMaps({ MAP_EXTRA_CONNECT_HOSTS: ' Tiles.Example.com, *.maps.example.org:8443 ' } as never),
).toMatchObject({
extraConnectHosts: ['tiles.example.com', '*.maps.example.org:8443'],
});
});
it('leaves out an entry the boot would refuse instead of widening the policy with it', () => {
// The schema aborts the boot on such a value; this covers the paths that skip validation.
const raw = { MAP_EXTRA_CONNECT_HOSTS: 'tiles.example.com,https://evil.example.com,*.com' };
expect(deriveMaps(raw as never).extraConnectHosts).toEqual(['tiles.example.com']);
});
});
describe('derivePush', () => {
it('passes the VAPID_* values through trimmed, blank counting as unset', () => {
expect(derivePush({})).toEqual({ vapidPublicKey: undefined, vapidPrivateKey: undefined, vapidSubject: undefined });
@@ -91,6 +91,17 @@ describe('validateEnvAtBoot', () => {
expect(() => validateEnvAtBoot({ ALLOW_LINK_LOCAL_IPS: '' })).not.toThrow();
});
it('refuses a MAP_EXTRA_CONNECT_HOSTS entry that is not a plain host name', () => {
// Every entry widens the CSP, so a value read loosely could open it far wider than meant.
expect(() => validateEnvAtBoot({ MAP_EXTRA_CONNECT_HOSTS: 'https://tiles.example.com' })).toThrow();
expect(() => validateEnvAtBoot({ MAP_EXTRA_CONNECT_HOSTS: 'tiles.example.com,*.com' })).toThrow();
expect(() => validateEnvAtBoot({ MAP_EXTRA_CONNECT_HOSTS: 'tiles.example.com/styles' })).toThrow();
expect(() =>
validateEnvAtBoot({ MAP_EXTRA_CONNECT_HOSTS: 'tiles.example.com, *.maps.example.org:8443' }),
).not.toThrow();
expect(() => validateEnvAtBoot({ MAP_EXTRA_CONNECT_HOSTS: '' })).not.toThrow();
});
it('checks the VAPID_* shapes and lets a well-formed set through', () => {
// The application server pair from RFC 8291 Appendix A, in the form the Web Push tools print.
const publicKey = 'BP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27mlmlMoZIIgDll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A8';
@@ -2,7 +2,7 @@ import { applyGlobalMiddleware, routingCspOrigins } from '../../../src/middlewar
import express from 'express';
import request from 'supertest';
import { describe, it, expect, afterEach } from 'vitest';
import { describe, it, expect, afterEach, vi } from 'vitest';
async function directiveSources(name: string): Promise<string[]> {
const app = express();
@@ -275,3 +275,33 @@ describe('connect-src with a self-hosted router', () => {
expect(connect).toContain('https://routing.openstreetmap.de/');
});
});
describe("connect-src with the operator's own map hosts (MAP_EXTRA_CONNECT_HOSTS)", () => {
afterEach(() => {
vi.unstubAllEnvs();
});
it('CSP-MAPHOST-001: names nothing beyond the shipped hosts while the variable is unset', async () => {
vi.stubEnv('MAP_EXTRA_CONNECT_HOSTS', '');
const sources = await connectSrcSources();
expect(sources).not.toContain('https://tiles.example.com');
expect(sources).toContain('https://tiles.openfreemap.org');
});
it('CSP-MAPHOST-002: adds every listed host as an https source, ports and wildcards included', async () => {
vi.stubEnv('MAP_EXTRA_CONNECT_HOSTS', 'Tiles.Example.com, *.maps.example.org:8443');
const sources = await connectSrcSources();
expect(sources).toContain('https://tiles.example.com');
expect(sources).toContain('https://*.maps.example.org:8443');
// The shipped hosts stay, so an operator's list only ever adds.
expect(sources).toContain('https://tiles.openfreemap.org');
});
it('CSP-MAPHOST-003: an entry outside the grammar widens nothing, even where the boot check was skipped', async () => {
vi.stubEnv('MAP_EXTRA_CONNECT_HOSTS', "tiles.example.com,https://evil.example.com,*.com,'unsafe-inline'");
const sources = await connectSrcSources();
expect(sources).toContain('https://tiles.example.com');
expect(sources.filter((source) => source.includes('evil') || source === 'https://*.com')).toEqual([]);
expect(sources).not.toContain("'unsafe-inline'");
});
});