feat(settings): set the Google Maps key through PLACES_API_KEY

The server already put PLACES_API_KEY ahead of the key saved in the admin
panel, but nothing said so: the variable was in no template and the admin
field kept showing a stored value that no search used.

GET /me/settings now answers env_keys, the variable behind each key the
environment sets (Google, Unsplash, Amap), and null for that key's value.
The admin field turns read-only and names the variable, Test still probes
the key a search resolves to, and a save leaves those names out so the
stored fallback survives. The variable is documented in .env.example,
docker-compose.yml, the Helm chart (as a secret) and the wiki.

Addresses discussion #1881.
This commit is contained in:
Maurice
2026-09-24 16:17:54 +02:00
parent 79cd3095e0
commit 8906b66bc8
45 changed files with 308 additions and 36 deletions
+2
View File
@@ -58,6 +58,8 @@ DEMO_MODE=false # Demo mode - resets data hourly
# TREK_PLACES_ENABLED=false # Whether place search asks the TREK Places API at https://places.liketrek.com: suggestions, the full search, the category buttons on the map, the Road trip search along the route, import geocoding and offline downloads. It is on by default and has no switch in the admin panel, because whether searches leave the instance is a deployment decision. Set false to search the way it did before 4.3.0 (OpenStreetMap, or your Google/Amap key) and send nothing to that host. (default: true)
# TREK_PLACES_URL=https://places.liketrek.com # Base URL of a copy of the Places API you run yourself; it has to answer the same /v1 API. Read from configuration rather than typed by a user, so an address on your LAN or Docker network works without ALLOW_INTERNAL_NETWORK. (default: https://places.liketrek.com)
# PLACES_API_KEY= # Google Maps API key (Places API (New) enabled) for place search, photos, details and Google transit. Overrides the key set in Admin > Settings > API Keys, whose field then shows this variable read-only. The value never reaches the browser.
# AMAP_API_KEY= # Amap (高德地图) Web 服务 key for place search and geocoding inside mainland China. Overrides the key set in Admin > Settings > API Keys. A Web 端 (JS API) key is a different credential and is rejected with INVALID_USER_KEY.
# 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)
+13 -3
View File
@@ -8,6 +8,7 @@ import { EMAIL_REGEX, mask_stored_api_key } from './auth.helpers';
import { splitManagedKeys, MANAGED_LOCKED_PROFILE_KEYS } from '../common/managed';
import {
INSTANCE_API_KEY_NAMES,
operatorKeyVariables,
readInstanceApiKey,
resolveApiKey,
writeInstanceApiKey,
@@ -270,12 +271,21 @@ export class UserProfileService {
// first. Showing the admin their own column while every request used another
// value is the confusion #1939 reported. Their column still answers while no
// instance value exists — on that install it is what the resolver picks too.
//
// Ahead of both sits the operator's environment variable. A key set there
// comes back as null plus the variable's name in `env_keys`: the stored
// value is not what any search uses, and the variable's value is the
// operator's, not the panel's to hand out (#1881).
const envKeys = operatorKeyVariables();
const shown = (name: InstanceApiKeyName, own: unknown) =>
envKeys[name] ? null : (readInstanceApiKey(this.db, name) ?? decrypt_api_key(own));
return {
settings: {
maps_api_key: readInstanceApiKey(this.db, 'maps_api_key') ?? decrypt_api_key(user.maps_api_key),
maps_api_key: shown('maps_api_key', user.maps_api_key),
openweather_api_key: decrypt_api_key(user.openweather_api_key),
unsplash_api_key: readInstanceApiKey(this.db, 'unsplash_api_key') ?? decrypt_api_key(user.unsplash_api_key),
amap_api_key: readInstanceApiKey(this.db, 'amap_api_key') ?? decrypt_api_key(user.amap_api_key),
unsplash_api_key: shown('unsplash_api_key', user.unsplash_api_key),
amap_api_key: shown('amap_api_key', user.amap_api_key),
env_keys: envKeys,
},
};
}
@@ -1,3 +1,4 @@
import { readEnv } from '../../app-config';
import { DatabaseService } from '../database/database.service';
import { decrypt_api_key, maybe_encrypt_api_key } from '../common/crypto/apiKeyCrypto';
import type { ApiKeySource } from '@trek/shared';
@@ -46,6 +47,26 @@ const USER_ROW_SQL: Record<InstanceApiKeyName, string> = {
amap_api_key: 'SELECT amap_api_key FROM users WHERE id = ?',
};
/**
* The environment variable that overrides each instance key. Whatever it holds
* is the operator key resolveApiKey puts first, so the admin panel names the
* variable rather than showing a field that nothing reads (#1881).
*/
const OPERATOR_KEY_ENV: Record<InstanceApiKeyName, { variable: string; read: () => string | undefined }> = {
maps_api_key: { variable: 'PLACES_API_KEY', read: () => readEnv().maps.placesApiKey },
unsplash_api_key: { variable: 'UNSPLASH_ACCESS_KEY', read: () => readEnv().integrations.unsplashAccessKey },
amap_api_key: { variable: 'AMAP_API_KEY', read: () => readEnv().maps.amapApiKey },
};
/** The instance keys an environment variable sets, each with that variable's name. Never the value. */
export function operatorKeyVariables(): Partial<Record<InstanceApiKeyName, string>> {
const set: Partial<Record<InstanceApiKeyName, string>> = {};
for (const name of INSTANCE_API_KEY_NAMES) {
if (OPERATOR_KEY_ENV[name].read()) set[name] = OPERATOR_KEY_ENV[name].variable;
}
return set;
}
/** The instance-wide value in cleartext, or null when unset/cleared. */
export function readInstanceApiKey(db: DatabaseService, name: InstanceApiKeyName): string | null {
const row = db.get<{ value: string | null }>('SELECT value FROM app_settings WHERE key = ?', name);
+16
View File
@@ -292,6 +292,22 @@ describe('Auth e2e (real auth guard + real service + real cookie service + temp
expect(auditRows('settings.api_keys_update')).toBe(before + 1);
}, 10000);
it('GET /me/settings names the variable behind a key set in the environment, never its value (#1881)', async () => {
const admin = createUser(db as never, { username: 'env-keys-admin', email: 'env-keys-admin@example.test', role: 'admin' });
const prev = process.env.PLACES_API_KEY;
process.env.PLACES_API_KEY = 'e2e-google-from-env';
try {
const res = await request(server).get('/api/auth/me/settings').set('Cookie', sessionCookie(admin.user.id));
expect(res.status).toBe(200);
expect(res.body.settings.maps_api_key).toBeNull();
expect(res.body.settings.env_keys).toEqual({ maps_api_key: 'PLACES_API_KEY' });
expect(JSON.stringify(res.body)).not.toContain('e2e-google-from-env');
} finally {
if (prev === undefined) delete process.env.PLACES_API_KEY;
else process.env.PLACES_API_KEY = prev;
}
});
it('GET /app-config answers has_maps_key from the instance row, never from an admin column (#1939)', async () => {
const member = createUser(db as never, { username: 'keys-member', email: 'keys-member@example.test' });
const admin = createUser(db as never, { username: 'keys-cfg-admin', email: 'keys-cfg-admin@example.test', role: 'admin' });
@@ -38,7 +38,7 @@ describe('OVERPASS_TIMEOUT_MS in the templates', () => {
describe('the Places and Amap switches in the templates', () => {
// The index is asked by default and the only way to stop that is this
// variable, so an operator has to be able to find it where they look.
const documented = ['TREK_PLACES_ENABLED', 'TREK_PLACES_URL', 'AMAP_API_KEY', 'AMAP_API_SECRET', 'AMAP_API_BASE'];
const documented = ['TREK_PLACES_ENABLED', 'TREK_PLACES_URL', 'PLACES_API_KEY', 'AMAP_API_KEY', 'AMAP_API_SECRET', 'AMAP_API_BASE'];
it('.env.example documents every one of them', () => {
for (const name of documented) {
@@ -66,12 +66,12 @@ describe('the Places and Amap switches in the templates', () => {
expect(helmConfigMap).toContain('{{- if not (kindIs "invalid" .Values.env.TREK_PLACES_ENABLED) }}');
});
it('the Helm chart carries the Amap credentials in the Secret, never in the ConfigMap', () => {
it('the Helm chart carries the Google and Amap credentials in the Secret, never in the ConfigMap', () => {
// A ConfigMap is readable by anyone who can read the namespace; the key and
// its signing secret belong next to the other credentials, in both the
// plain and the generated branch of the Secret, and the pod reads them from
// there like it reads the Unsplash key.
for (const name of ['AMAP_API_KEY', 'AMAP_API_SECRET']) {
for (const name of ['PLACES_API_KEY', 'AMAP_API_KEY', 'AMAP_API_SECRET']) {
expect(helmValues).toContain(` ${name}: ""`);
expect(helmSecret).toContain(`${name}: {{ .Values.secretEnv.${name} | b64enc | quote }}`);
expect(helmSecret).toContain(`${name}: {{ .Values.secretEnv.${name} }}`);
@@ -32,6 +32,7 @@ import {
readInstanceApiKey,
writeInstanceApiKey,
resolveApiKey,
operatorKeyVariables,
} from '../../../../src/nest/settings/instance-api-keys';
const db = new DatabaseService(testDb);
@@ -137,3 +138,43 @@ describe('instance API keys', () => {
expect(resolveApiKey(db, 'unsplash_api_key', user.id, undefined)).toEqual({ key: null, source: null });
});
});
describe('operatorKeyVariables (#1881)', () => {
const VARS = ['PLACES_API_KEY', 'UNSPLASH_ACCESS_KEY', 'AMAP_API_KEY'] as const;
const saved: Partial<Record<(typeof VARS)[number], string>> = {};
beforeEach(() => {
for (const v of VARS) {
saved[v] = process.env[v];
delete process.env[v];
}
});
afterAll(() => {
for (const v of VARS) {
if (saved[v] === undefined) delete process.env[v];
else process.env[v] = saved[v];
}
});
it('INSTKEY-010: names nothing while no variable is set', () => {
expect(operatorKeyVariables()).toEqual({});
});
it('INSTKEY-011: names the variable behind each key that has one, never its value', () => {
process.env.PLACES_API_KEY = 'google-from-env';
process.env.UNSPLASH_ACCESS_KEY = 'unsplash-from-env';
process.env.AMAP_API_KEY = 'amap-from-env';
const set = operatorKeyVariables();
expect(set).toEqual({
maps_api_key: 'PLACES_API_KEY',
unsplash_api_key: 'UNSPLASH_ACCESS_KEY',
amap_api_key: 'AMAP_API_KEY',
});
expect(JSON.stringify(set)).not.toContain('from-env');
});
it('INSTKEY-012: a blank variable does not count as set', () => {
process.env.PLACES_API_KEY = '';
process.env.UNSPLASH_ACCESS_KEY = ' ';
expect(operatorKeyVariables()).toEqual({});
});
});
@@ -157,6 +157,30 @@ describe('getSettings', () => {
// getSettings returns the stored key to the admin.
expect(profile.getSettings(user.id).settings?.unsplash_api_key).toBe('unsplash-secret-key');
});
it('AUTH-DB-010c: a key set in the environment comes back as its variable name, not a value (#1881)', () => {
const prev = process.env.PLACES_API_KEY;
process.env.PLACES_API_KEY = 'google-from-env';
try {
const { user } = createAdmin(testDb);
profile.updateApiKeys(user.id, { maps_api_key: 'stored-but-overridden', unsplash_api_key: 'stored-unsplash' });
const settings = profile.getSettings(user.id).settings;
// Neither the stored value nobody searches with nor the operator's own.
expect(settings?.maps_api_key).toBeNull();
expect(settings?.env_keys).toEqual({ maps_api_key: 'PLACES_API_KEY' });
expect(JSON.stringify(settings)).not.toContain('google-from-env');
// A key without a variable reads as before.
expect(settings?.unsplash_api_key).toBe('stored-unsplash');
} finally {
if (prev === undefined) delete process.env.PLACES_API_KEY;
else process.env.PLACES_API_KEY = prev;
}
});
it('AUTH-DB-010d: without a variable env_keys is empty', () => {
const { user } = createAdmin(testDb);
expect(profile.getSettings(user.id).settings?.env_keys).toEqual({});
});
});
// ---------------------------------------------------------------------------