fix(maps): resolve the Places key per instance, not per whoever is asking

Searching worked for the admin and 403'd for every other member. getMapsKey read
the calling user's own row first and then fell through to "any admin" via LIMIT 1
with no ORDER BY, so the admin who pasted the key hit their own row while everyone
else got a non-deterministic stranger's. That fallback is what CLAUDE.md forbids.

The Places and Unsplash keys bill the install, not the account that pasted them
in, so they become instance configuration: an encrypted app_settings row, resolved
as env -> instance -> the caller's own row, the same shape #1772 chose for the LLM
endpoint. The per-user column stays as the last step because /me/api-keys has
always accepted a personal key.

The trailing migration carries an existing install's key into the instance row so
nothing degrades to OpenStreetMap on upgrade, but only where that key already was
the whole install's: as soon as a second row holds one, it is left alone, because
the instance row outranks everybody's own column and an upgrade must not move a
member onto someone else's key and bill.

Two things from the same report:

The key test button probed with field mask places.displayName while the search
asks for places.rating and more, which is a separate SKU and can be restricted on
its own, so the button could pass while every search failed. It now probes the
resolved key with the search's own mask.

Saving API keys wrote no audit line. It now writes one settings.api_keys_update
row naming which fields changed, never their values, comparing cleartext because
the random IV makes every ciphertext look different.

Closes #1939
This commit is contained in:
Maurice
2026-08-17 14:20:45 +02:00
committed by Maurice
parent c9124c9b63
commit 1a0834b866
20 changed files with 1171 additions and 110 deletions
@@ -0,0 +1,141 @@
/**
* Unit test for the instance API-key backfill migration (#1939).
*
* The Places/Unsplash credential moved from "whichever admin row the resolver
* happened to find" to an instance-wide app_settings row. An install that
* upgrades must keep searching with the key it already had, so the migration
* copies the value the old resolver would have handed out — the lowest-id admin
* who has one — and leaves the users columns alone. It only does so where that
* value was the whole install's key: as soon as a second row holds one, the
* promotion is skipped, because the instance row outranks everybody's own
* column and nobody may be moved onto a stranger's key by an upgrade.
*
* Seeded before runMigrations rather than by rewinding schema_version
* afterwards: createTables already brings users.role and both key columns, so
* the backfill fires on its normal pass and finds the rows. That keeps this
* file independent of where the entry sits in the append-only array, so
* appending the next migration does not drag it along. The one guard that does
* have to track the tail is tests/integration/leg-mode-incoming.test.ts, which
* says so in place.
*/
import { describe, it, expect } from 'vitest';
import Database from 'better-sqlite3';
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
function freshDb() {
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
createTables(db);
return db;
}
function seedUser(
db: Database.Database,
id: number,
role: 'admin' | 'user',
keys: { maps?: string; unsplash?: string } = {},
) {
db.prepare(
`INSERT INTO users (id, username, email, password_hash, role, maps_api_key, unsplash_api_key)
VALUES (?, ?, ?, 'x', ?, ?, ?)`
).run(id, `u${id}`, `u${id}@test.local`, role, keys.maps ?? null, keys.unsplash ?? null);
}
const setting = (db: Database.Database, key: string) =>
(db.prepare('SELECT value FROM app_settings WHERE key = ?').get(key) as { value: string } | undefined)?.value;
describe('instance API-key backfill migration', () => {
it('KEYFILL-001: copies the one key the install was searching with and keeps the column', () => {
const db = freshDb();
seedUser(db, 1, 'admin', { maps: 'the-admin-google', unsplash: 'the-admin-unsplash' });
seedUser(db, 2, 'user');
runMigrations(db);
expect(setting(db, 'maps_api_key')).toBe('the-admin-google');
expect(setting(db, 'unsplash_api_key')).toBe('the-admin-unsplash');
// Nothing is taken away: the columns are still the per-user fallback.
const row = db.prepare('SELECT maps_api_key FROM users WHERE id = 1').get() as { maps_api_key: string };
expect(row.maps_api_key).toBe('the-admin-google');
db.close();
});
it('KEYFILL-002: skips an admin whose column is empty and takes the next one', () => {
const db = freshDb();
seedUser(db, 1, 'admin', { maps: '' });
seedUser(db, 2, 'admin', { maps: 'the-only-real-key' });
runMigrations(db);
expect(setting(db, 'maps_api_key')).toBe('the-only-real-key');
db.close();
});
it('KEYFILL-003: never overwrites a value the admin has already saved instance-wide', () => {
const db = freshDb();
seedUser(db, 1, 'admin', { maps: 'old-column-key' });
db.prepare("INSERT INTO app_settings (key, value) VALUES ('maps_api_key', 'already-instance-wide')").run();
runMigrations(db);
expect(setting(db, 'maps_api_key')).toBe('already-instance-wide');
db.close();
});
it('KEYFILL-004: ignores a non-admin key and writes no row at all', () => {
const db = freshDb();
seedUser(db, 1, 'user', { maps: 'members-own-key' });
runMigrations(db);
// A member's key stays theirs — the resolver still finds it for them, and
// promoting it would hand their billing to the whole instance.
expect(setting(db, 'maps_api_key')).toBeUndefined();
db.close();
});
it('KEYFILL-005: writes nothing on an install that never had a key', () => {
const db = freshDb();
seedUser(db, 1, 'admin');
runMigrations(db);
expect(setting(db, 'maps_api_key')).toBeUndefined();
expect(setting(db, 'unsplash_api_key')).toBeUndefined();
db.close();
});
it('KEYFILL-006: leaves a column alone once a member holds a key of their own', () => {
const db = freshDb();
seedUser(db, 1, 'admin', { maps: 'admins-own-google', unsplash: 'admins-own-unsplash' });
seedUser(db, 7, 'user', { maps: 'members-own-google' });
runMigrations(db);
// Member 7 pays for their own Google key. Promoting the admin's would put
// every one of their searches on his key and his bill, because the instance
// row is resolved before their own column.
expect(setting(db, 'maps_api_key')).toBeUndefined();
// Decided per column: nobody else has an Unsplash key, so that one really
// was the whole install's and stays it.
expect(setting(db, 'unsplash_api_key')).toBe('admins-own-unsplash');
const row = db.prepare('SELECT maps_api_key FROM users WHERE id = 7').get() as { maps_api_key: string };
expect(row.maps_api_key).toBe('members-own-google');
db.close();
});
it('KEYFILL-007: two admins with their own keys both keep them', () => {
const db = freshDb();
seedUser(db, 1, 'admin', { maps: 'first-admin-google' });
seedUser(db, 2, 'admin', { maps: 'second-admin-google' });
runMigrations(db);
expect(setting(db, 'maps_api_key')).toBeUndefined();
const rows = db.prepare('SELECT maps_api_key FROM users ORDER BY id').all() as { maps_api_key: string }[];
expect(rows.map((r) => r.maps_api_key)).toEqual(['first-admin-google', 'second-admin-google']);
db.close();
});
});
@@ -170,6 +170,24 @@ describe('writeAudit', () => {
testDb.prepare('ALTER TABLE audit_log_gone RENAME TO audit_log').run();
});
it('AUDIT-SVC-018: settings.api_keys_update names the changed keys and nothing else (#1939)', () => {
seedUser(1, 'admin@b.c');
svc.writeAudit({
userId: 1,
action: 'settings.api_keys_update',
resource: 'api_keys',
details: { changed: ['maps_api_key', 'unsplash_api_key'] },
ip: '1.2.3.4',
});
expect(logInfo).toHaveBeenLastCalledWith('admin@b.c updated API keys (maps_api_key, unsplash_api_key) ip=1.2.3.4');
// A details blob without the array (or with an empty one) leaves the brief off
// rather than stringifying whatever else is in there.
svc.writeAudit({ userId: 1, action: 'settings.api_keys_update', details: { changed: [] }, ip: '1.2.3.4' });
expect(logInfo).toHaveBeenLastCalledWith('admin@b.c updated API keys ip=1.2.3.4');
svc.writeAudit({ userId: 1, action: 'settings.api_keys_update', details: { other: 'x' }, ip: '1.2.3.4' });
expect(logInfo).toHaveBeenLastCalledWith('admin@b.c updated API keys ip=1.2.3.4');
});
it('AUDIT-SVC-014: buildInfoSummary variants (settings parts, login empty brief)', () => {
seedUser(1, 'a@b.c');
svc.writeAudit({ userId: 1, action: 'settings.app_update', details: { notification_channel: 'smtp', require_mfa: false }, ip: '1.1.1.1' });
+41 -4
View File
@@ -289,15 +289,52 @@ describe('AuthController (authenticated)', () => {
it('maps-key + api-keys pass straight through to the service', () => {
const updateMapsKey = vi.fn().mockReturnValue({ success: true });
expect(ac(asvc({}), rl(), {}, { updateMapsKey }).mapsKey(user, { maps_api_key: 'k' })).toEqual({ success: true });
expect(ac(asvc({}), rl(), {}, { updateMapsKey }).mapsKey(user, { maps_api_key: 'k' }, req)).toEqual({ success: true });
expect(updateMapsKey).toHaveBeenCalledWith(1, 'k');
const updateApiKeys = vi.fn().mockReturnValue({ ok: 1 });
expect(ac(asvc({}), rl(), {}, { updateApiKeys }).apiKeys(user, anyBody({ a: 1 } as never))).toEqual({ ok: 1 });
expect(ac(asvc({}), rl(), {}, { updateApiKeys }).apiKeys(user, anyBody({ a: 1 } as never), req)).toEqual({ ok: 1 });
// No changedKeys from the service (and none in the body): nothing to audit.
expect(writeAudit).not.toHaveBeenCalled();
});
it('api-keys audits one settings.api_keys_update with the changed names only (#1939)', () => {
const updateApiKeys = vi.fn().mockReturnValue({ success: true, user: { id: 1 }, changedKeys: ['maps_api_key'] });
const c = ac(asvc({}), rl(), {}, { updateApiKeys });
// changedKeys is stripped off the response — the client body is unchanged.
expect(c.apiKeys(user, anyBody({ maps_api_key: 'AIza-super-secret' } as never), req)).toEqual({ success: true, user: { id: 1 } });
expect(writeAudit).toHaveBeenCalledTimes(1);
expect(writeAudit).toHaveBeenCalledWith({
userId: 1,
action: 'settings.api_keys_update',
resource: 'api_keys',
ip: '1.2.3.4',
details: { changed: ['maps_api_key'] },
});
// Never the value, not even truncated: details is rendered raw in the panel.
expect(JSON.stringify(writeAudit.mock.calls)).not.toContain('AIza-super-secret');
});
it('maps-key and settings audit the same action; an unchanged save writes nothing', () => {
const mapsC = ac(asvc({}), rl(), {}, { updateMapsKey: vi.fn().mockReturnValue({ success: true, changedKeys: ['maps_api_key'] }) });
mapsC.mapsKey(user, { maps_api_key: 'k' }, req);
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'settings.api_keys_update', details: { changed: ['maps_api_key'] } }));
writeAudit.mockClear();
const setC = ac(asvc({}), rl(), {}, { updateSettings: vi.fn().mockReturnValue({ success: true, user: { id: 1 }, changedKeys: ['unsplash_api_key'] }) });
expect(setC.updateSettings(user, {}, req)).toEqual({ success: true, user: { id: 1 } });
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'settings.api_keys_update', details: { changed: ['unsplash_api_key'] } }));
// The test button in the panel saves before every click — an identical value
// must not cost a log line.
writeAudit.mockClear();
ac(asvc({}), rl(), {}, { updateApiKeys: vi.fn().mockReturnValue({ success: true, changedKeys: [] }) })
.apiKeys(user, anyBody({ maps_api_key: 'same' } as never), req);
expect(writeAudit).not.toHaveBeenCalled();
});
it('update-settings + get-settings map errors, else return their payloads', () => {
expect(thrown(() => ac(asvc({}), rl(), {}, { updateSettings: vi.fn().mockReturnValue({ error: 'Bad', status: 400 }) }).updateSettings(user, {}))).toEqual({ status: 400, body: { error: 'Bad' } });
expect(ac(asvc({}), rl(), {}, { updateSettings: vi.fn().mockReturnValue({ success: true, user: { id: 1 } }) }).updateSettings(user, {})).toEqual({ success: true, user: { id: 1 } });
expect(thrown(() => ac(asvc({}), rl(), {}, { updateSettings: vi.fn().mockReturnValue({ error: 'Bad', status: 400 }) }).updateSettings(user, {}, req))).toEqual({ status: 400, body: { error: 'Bad' } });
expect(ac(asvc({}), rl(), {}, { updateSettings: vi.fn().mockReturnValue({ success: true, user: { id: 1 } }) }).updateSettings(user, {}, req)).toEqual({ success: true, user: { id: 1 } });
expect(thrown(() => ac(asvc({}), rl(), {}, { getSettings: vi.fn().mockReturnValue({ error: 'Nope', status: 404 }) }).getSettings(user))).toEqual({ status: 404, body: { error: 'Nope' } });
expect(ac(asvc({}), rl(), {}, { getSettings: vi.fn().mockReturnValue({ settings: { theme: 'dark' } }) }).getSettings(user)).toEqual({ settings: { theme: 'dark' } });
});
+91 -14
View File
@@ -38,6 +38,8 @@ type SsrfCheckStub = Pick<SsrfResult, 'allowed' | 'error'>;
const {
mockDbGet,
mockDbRun,
mockInstanceGet,
preparedSql,
mockCheckSsrf,
mockCacheGet,
mockCacheGetErrored,
@@ -47,8 +49,14 @@ const {
mockCacheSetInFlight,
mockServeFilePath,
} = vi.hoisted(() => ({
mockDbGet: vi.fn(() => undefined as any),
mockDbGet: vi.fn((..._args: unknown[]) => undefined as any),
mockDbRun: vi.fn(),
// The instance-wide key row (#1939) is read before the caller's own row, so it
// gets its own seam: every case below that stubs mockDbGet means "this user's
// row holds a key", and would otherwise have its stub eaten by the
// app_settings lookup.
mockInstanceGet: vi.fn((..._args: unknown[]) => undefined as any),
preparedSql: [] as string[],
mockCheckSsrf: vi.fn(async (_url: string, _bypassInternalIpAllowed?: boolean): Promise<SsrfCheckStub> => ({
allowed: true,
})),
@@ -69,7 +77,14 @@ const {
vi.mock('../../../src/db/database', () => ({
db: {
prepare: () => ({ get: mockDbGet, all: vi.fn(() => []), run: mockDbRun }),
prepare: (sql: string) => {
preparedSql.push(sql);
return {
get: (...args: unknown[]) => (sql.includes('app_settings') ? mockInstanceGet(...args) : mockDbGet(...args)),
all: vi.fn(() => []),
run: mockDbRun,
};
},
},
}));
@@ -96,6 +111,8 @@ vi.mock('../../../src/utils/ssrfGuard', () => {
vi.mock('../../../src/nest/common/crypto/apiKeyCrypto', () => ({
decrypt_api_key: (v: string | null) => v,
// Unused by the read paths here, but instance-api-keys imports it.
maybe_encrypt_api_key: (v: string | null) => v,
}));
vi.mock('../../../src/config', () => ({
@@ -131,6 +148,9 @@ afterEach(() => {
vi.unstubAllGlobals();
mockDbGet.mockReset();
mockDbGet.mockReturnValue(undefined);
mockInstanceGet.mockReset();
mockInstanceGet.mockReturnValue(undefined);
preparedSql.length = 0;
mockDbRun.mockReset();
mockCheckSsrf.mockReset();
mockCheckSsrf.mockResolvedValue({ allowed: true });
@@ -392,24 +412,48 @@ describe('buildOsmDetails', () => {
});
});
// ── getMapsKey ────────────────────────────────────────────────────────────────
// ── resolveMapsKey / getMapsKey ───────────────────────────────────────────────
describe('getMapsKey', () => {
it('MAPS-015: returns user key when user has one', () => {
describe('resolveMapsKey', () => {
const ORIGINAL_PLACES_KEY = process.env.PLACES_API_KEY;
afterEach(() => {
if (ORIGINAL_PLACES_KEY === undefined) delete process.env.PLACES_API_KEY;
else process.env.PLACES_API_KEY = ORIGINAL_PLACES_KEY;
});
it('MAPS-015: returns the caller own row key when nothing above it is set', () => {
mockDbGet.mockReturnValue({ maps_api_key: 'user-api-key' });
expect(svc.resolveMapsKey(1)).toEqual({ key: 'user-api-key', source: 'user-row' });
expect(svc.getMapsKey(1)).toBe('user-api-key'); // the wrapper reads the same chain
});
it('MAPS-016: the instance-wide key wins over the caller own row (#1939)', () => {
mockInstanceGet.mockReturnValueOnce({ value: 'instance-api-key' });
mockDbGet.mockReturnValueOnce({ maps_api_key: 'user-api-key' });
expect(svc.getMapsKey(1)).toBe('user-api-key');
expect(svc.resolveMapsKey(1)).toEqual({ key: 'instance-api-key', source: 'instance' });
});
it('MAPS-016: falls back to admin key when user has none', () => {
mockDbGet.mockReturnValueOnce({ maps_api_key: null });
mockDbGet.mockReturnValueOnce({ maps_api_key: 'admin-api-key' });
expect(svc.getMapsKey(1)).toBe('admin-api-key');
});
it('MAPS-017: returns null when neither user nor admin has a key', () => {
mockDbGet.mockReturnValue(undefined);
it('MAPS-017: returns null with no source when nothing is set anywhere', () => {
expect(svc.resolveMapsKey(1)).toEqual({ key: null, source: null });
expect(svc.getMapsKey(1)).toBeNull();
});
it('MAPS-017b: the operator env key wins and the database is never asked', () => {
process.env.PLACES_API_KEY = 'operator-key';
expect(svc.resolveMapsKey(1)).toEqual({ key: 'operator-key', source: 'operator-env' });
expect(mockInstanceGet).not.toHaveBeenCalled();
expect(mockDbGet).not.toHaveBeenCalled();
});
it("MAPS-017c: never reads another user's row — the admin fallback is gone (#1939)", () => {
svc.resolveMapsKey(1);
// Two statements, both scoped: the instance row and this caller's own row.
// The old chain ended in "WHERE role = 'admin' ... LIMIT 1", which handed a
// stranger's credential to every non-admin.
expect(preparedSql).toHaveLength(2);
expect(preparedSql.join(' ')).not.toContain("role = 'admin'");
expect(preparedSql.some((sql) => sql.includes('WHERE id = ?'))).toBe(true);
});
});
// ── reverseGeocode ────────────────────────────────────────────────────────────
@@ -1153,6 +1197,25 @@ describe('searchPlaces (fetch stubbed)', () => {
});
});
it('MAPS-039h: a Google rejection logs which credential was used, never the credential (#1939)', async () => {
mockInstanceGet.mockReturnValueOnce({ value: 'instance-secret-key' });
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
ok: false,
status: 403,
json: async () => ({ error: { message: 'The caller does not have permission' } }),
}),
);
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
await expect(svc.searchPlaces(7, 'anything')).rejects.toMatchObject({ status: 403 });
const logged = errorSpy.mock.calls.map((c) => String(c[0])).join('\n');
expect(logged).toContain('keySource=instance');
expect(logged).toContain('userId=7');
expect(logged).not.toContain('instance-secret-key');
errorSpy.mockRestore();
});
it('MAPS-039c: throws with generic message when Google error has no message', async () => {
mockDbGet.mockReturnValueOnce({ maps_api_key: 'some-key' });
vi.stubGlobal(
@@ -1319,6 +1382,20 @@ describe('autocompletePlaces (fetch stubbed)', () => {
});
});
it('MAPS-083b: the autocomplete rejection logs the key source too (#1939)', async () => {
mockDbGet.mockReturnValueOnce({ maps_api_key: 'own-row-secret' });
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({ ok: false, status: 403, json: async () => ({ error: { message: 'nope' } }) }),
);
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
await expect(svc.autocompletePlaces(4, 'anything')).rejects.toMatchObject({ status: 403 });
const logged = errorSpy.mock.calls.map((c) => String(c[0])).join('\n');
expect(logged).toContain('keySource=user-row');
expect(logged).not.toContain('own-row-secret');
errorSpy.mockRestore();
});
it('MAPS-084: throws generic message when Google error has no message', async () => {
mockDbGet.mockReturnValueOnce({ maps_api_key: 'some-key' });
vi.stubGlobal(
@@ -0,0 +1,139 @@
/**
* instance-api-keys.test.ts — INSTKEY-001 through INSTKEY-008.
*
* The shared resolver behind #1939: the Places/Unsplash credential is instance
* configuration, so it comes from the env or an encrypted app_settings row, and
* only then from the caller's own users row. Run against a real in-memory DB
* with real apiKeyCrypto (a fixed ENCRYPTION_KEY), because the round trip
* through the random IV is half of what these functions promise.
*/
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
return { testDb: db, dbMock: { db, closeDb: () => {}, reinitialize: () => {} } };
});
vi.mock('../../../../src/db/database', () => dbMock);
vi.mock('../../../../src/config', () => ({
JWT_SECRET: 'test-secret',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
}));
import { describe, it, expect, beforeAll, beforeEach, afterAll, vi } from 'vitest';
import { createTables } from '../../../../src/db/schema';
import { runMigrations } from '../../../../src/db/migrations';
import { createUser, createAdmin } from '../../../helpers/factories';
import { resetTestDb } from '../../../helpers/test-db';
import { DatabaseService } from '../../../../src/nest/database/database.service';
import {
readInstanceApiKey,
writeInstanceApiKey,
resolveApiKey,
} from '../../../../src/nest/settings/instance-api-keys';
const db = new DatabaseService(testDb);
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
delete process.env.PLACES_API_KEY;
});
afterAll(() => {
testDb.close();
});
const storedValue = (key: string) =>
(testDb.prepare('SELECT value FROM app_settings WHERE key = ?').get(key) as { value: string } | undefined)?.value;
describe('instance API keys', () => {
it('INSTKEY-001: round-trips through encryption at rest', () => {
writeInstanceApiKey(db, 'maps_api_key', 'AIza-instance-key');
expect(storedValue('maps_api_key')).toMatch(/^enc:v1:/);
expect(storedValue('maps_api_key')).not.toContain('AIza-instance-key');
expect(readInstanceApiKey(db, 'maps_api_key')).toBe('AIza-instance-key');
});
it('INSTKEY-002: a second write of the same value replaces the row (no second one)', () => {
writeInstanceApiKey(db, 'maps_api_key', 'same-key');
const first = storedValue('maps_api_key');
writeInstanceApiKey(db, 'maps_api_key', 'same-key');
// Same plaintext, different blob — the IV is random. That is exactly why
// "did this change?" is never asked of the stored value.
expect(storedValue('maps_api_key')).not.toBe(first);
expect(readInstanceApiKey(db, 'maps_api_key')).toBe('same-key');
const rows = testDb.prepare("SELECT COUNT(*) AS n FROM app_settings WHERE key = 'maps_api_key'").get() as { n: number };
expect(rows.n).toBe(1);
});
it('INSTKEY-003: a blank value reads back as unset but keeps the row', () => {
writeInstanceApiKey(db, 'unsplash_api_key', ' ');
expect(storedValue('unsplash_api_key')).toBe('');
expect(readInstanceApiKey(db, 'unsplash_api_key')).toBeNull();
});
it('INSTKEY-004: a legacy plaintext row still reads', () => {
testDb.prepare("INSERT INTO app_settings (key, value) VALUES ('maps_api_key', 'plain-old-key')").run();
expect(readInstanceApiKey(db, 'maps_api_key')).toBe('plain-old-key');
});
it('INSTKEY-005: the operator env key wins and the database is never read', () => {
process.env.PLACES_API_KEY = 'operator-key';
writeInstanceApiKey(db, 'maps_api_key', 'instance-key');
expect(resolveApiKey(db, 'maps_api_key', 1, process.env.PLACES_API_KEY)).toEqual({
key: 'operator-key',
source: 'operator-env',
});
});
it('INSTKEY-006: the instance value wins over the caller own row', () => {
const { user } = createAdmin(testDb);
testDb.prepare('UPDATE users SET maps_api_key = ? WHERE id = ?').run('personal-key', user.id);
writeInstanceApiKey(db, 'maps_api_key', 'instance-key');
expect(resolveApiKey(db, 'maps_api_key', user.id, undefined)).toEqual({ key: 'instance-key', source: 'instance' });
});
it("INSTKEY-007: without an instance value the caller's own row answers — and nobody else's (#1939)", () => {
const { user: admin } = createAdmin(testDb);
testDb.prepare('UPDATE users SET maps_api_key = ? WHERE id = ?').run('admins-own-key', admin.id);
const { user: member } = createUser(testDb);
// The admin gets theirs...
expect(resolveApiKey(db, 'maps_api_key', admin.id, undefined)).toEqual({
key: 'admins-own-key',
source: 'user-row',
});
// ...and the member gets nothing rather than the admin's, which is the whole
// point: they used to get it, and Google answered them with a 403.
expect(resolveApiKey(db, 'maps_api_key', member.id, undefined)).toEqual({ key: null, source: null });
});
it('INSTKEY-009: userId 0 asks about the instance only', () => {
const { user } = createAdmin(testDb);
testDb.prepare('UPDATE users SET maps_api_key = ? WHERE id = ?').run('personal-key', user.id);
// app-config is optional-auth: with nobody asking there is no own row, and
// the answer must not be some other row that happens to be first.
expect(resolveApiKey(db, 'maps_api_key', 0, undefined)).toEqual({ key: null, source: null });
writeInstanceApiKey(db, 'maps_api_key', 'instance-key');
expect(resolveApiKey(db, 'maps_api_key', 0, undefined)).toEqual({ key: 'instance-key', source: 'instance' });
});
it('INSTKEY-008: an empty instance value does not fall through to the own row', () => {
const { user } = createAdmin(testDb);
testDb.prepare('UPDATE users SET unsplash_api_key = ? WHERE id = ?').run('stale-personal', user.id);
writeInstanceApiKey(db, 'unsplash_api_key', 'to-be-cleared');
writeInstanceApiKey(db, 'unsplash_api_key', '');
// The admin who cleared the field cleared their column in the same save, so
// the fallback finding the old value would only happen on a row nobody
// touched — here it must not resurrect a cleared instance key for them.
testDb.prepare('UPDATE users SET unsplash_api_key = NULL WHERE id = ?').run(user.id);
expect(resolveApiKey(db, 'unsplash_api_key', user.id, undefined)).toEqual({ key: null, source: null });
});
});
@@ -6,12 +6,28 @@ import path from 'path';
// safeFetch is mocked so saveUnsplashCover never hits the network.
// db is mocked so getUnsplashKey resolves from a controllable stub, and
// decrypt_api_key is a passthrough so stored values compare as plaintext.
const { safeFetch, mockDbGet } = vi.hoisted(() => ({ safeFetch: vi.fn(), mockDbGet: vi.fn(() => undefined as unknown) }));
// The instance-wide row (#1939) is read before the user's own, so it gets its
// own seam rather than eating the mockDbGet stub of every case below.
const { safeFetch, mockDbGet, mockInstanceGet } = vi.hoisted(() => ({
safeFetch: vi.fn(),
mockDbGet: vi.fn((..._args: unknown[]) => undefined as unknown),
mockInstanceGet: vi.fn((..._args: unknown[]) => undefined as unknown),
}));
vi.mock('../../../../src/utils/ssrfGuard', () => ({ safeFetch }));
vi.mock('../../../../src/db/database', () => ({
db: { prepare: () => ({ get: mockDbGet, all: vi.fn(() => []), run: vi.fn() }) },
db: {
prepare: (sql: string) => ({
get: (...args: unknown[]) => (sql.includes('app_settings') ? mockInstanceGet(...args) : mockDbGet(...args)),
all: vi.fn(() => []),
run: vi.fn(),
}),
},
}));
vi.mock('../../../../src/nest/common/crypto/apiKeyCrypto', () => ({
decrypt_api_key: (v: string | null) => v,
// Unused by the read path here, but instance-api-keys imports it.
maybe_encrypt_api_key: (v: string | null) => v,
}));
vi.mock('../../../../src/nest/common/crypto/apiKeyCrypto', () => ({ decrypt_api_key: (v: string | null) => v }));
import { UnsplashService } from '../../../../src/nest/unsplash/unsplash.service';
import { DatabaseService } from '../../../../src/nest/database/database.service';
@@ -31,6 +47,7 @@ afterEach(() => {
vi.clearAllMocks();
vi.unstubAllGlobals();
mockDbGet.mockReturnValue(undefined);
mockInstanceGet.mockReturnValue(undefined);
if (ORIGINAL_UNSPLASH_ENV === undefined) delete process.env.UNSPLASH_ACCESS_KEY;
else process.env.UNSPLASH_ACCESS_KEY = ORIGINAL_UNSPLASH_ENV;
});
@@ -65,6 +82,37 @@ describe('unsplashService.searchUnsplashPhotos', () => {
expect(await searchUnsplashPhotos('paris')).toEqual({ error: 'Rate limited', status: 429 });
});
it('UNSPLASH-016: a 200 carrying unparseable JSON becomes a 502, not a crash', async () => {
// The web endpoint answers 200 with an HTML challenge page when it decides the
// caller is a datacenter (#1449), so a parse failure on an ok response is an
// upstream problem, not the caller's.
const bad = fakeRes({ ok: true, type: 'text/html' });
(bad as { json: () => Promise<unknown> }).json = async () => {
throw new SyntaxError('Unexpected token < in JSON');
};
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(bad));
expect(await searchUnsplashPhotos('paris')).toEqual({ error: 'Unsplash search unavailable', status: 502 });
});
it('UNSPLASH-017: a failing response with unparseable JSON keeps its own status', async () => {
const bad = fakeRes({ ok: false, status: 503, type: 'text/html' });
(bad as { json: () => Promise<unknown> }).json = async () => {
throw new SyntaxError('Unexpected token < in JSON');
};
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(bad));
expect(await searchUnsplashPhotos('paris')).toEqual({ error: 'Unsplash search unavailable', status: 503 });
});
it('UNSPLASH-018: falls back to the generic message when a non-ok body names no error', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(fakeRes({ ok: false, status: 500, type: 'application/json', json: {} })));
expect(await searchUnsplashPhotos('paris')).toEqual({ error: 'Unsplash search unavailable', status: 500 });
});
it('UNSPLASH-019: uses the single error field when the errors array is absent', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(fakeRes({ ok: false, status: 401, type: 'application/json', json: { error: 'Bad credentials' } })));
expect(await searchUnsplashPhotos('paris')).toEqual({ error: 'Bad credentials', status: 401 });
});
it('UNSPLASH-004: returns normalised photos on success and drops entries missing a url/thumb', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(fakeRes({
ok: true,
@@ -115,18 +163,28 @@ describe('unsplashService.getUnsplashKey', () => {
expect(getUnsplashKey(1)).toBe('user-key');
});
it('UNSPLASH-014: falls back to the admin key when the user has none', () => {
it('UNSPLASH-014: the instance-wide key wins over the user own key (#1939)', () => {
delete process.env.UNSPLASH_ACCESS_KEY;
mockDbGet.mockReturnValueOnce({ unsplash_api_key: null });
mockDbGet.mockReturnValueOnce({ unsplash_api_key: 'admin-key' });
expect(getUnsplashKey(1)).toBe('admin-key');
mockInstanceGet.mockReturnValue({ value: 'instance-key' });
mockDbGet.mockReturnValue({ unsplash_api_key: 'user-key' });
expect(getUnsplashKey(1)).toBe('instance-key');
expect(mockDbGet).not.toHaveBeenCalled(); // the own row is not even read
});
it('UNSPLASH-015: returns null when neither env, user, nor admin has a key', () => {
it('UNSPLASH-015: returns null when neither env, instance, nor the user has a key', () => {
delete process.env.UNSPLASH_ACCESS_KEY;
mockDbGet.mockReturnValue(undefined);
expect(getUnsplashKey(1)).toBeNull();
});
it("UNSPLASH-015b: never reads another user's key — the admin fallback is gone (#1939)", () => {
delete process.env.UNSPLASH_ACCESS_KEY;
mockDbGet.mockReturnValue(undefined);
expect(getUnsplashKey(1)).toBeNull();
// Both reads are scoped: the instance row and this caller's own row.
expect(mockDbGet).toHaveBeenCalledTimes(1);
expect(mockDbGet).toHaveBeenCalledWith(1);
});
});
describe('unsplashService.saveUnsplashCover', () => {
@@ -40,6 +40,7 @@ import { resetTestDb } from '../../helpers/test-db';
import { createUser, createAdmin } from '../../helpers/factories';
import { UserProfileService } from '../../../src/nest/auth/user-profile.service';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { SEARCH_TEXT_FIELD_MASK } from '../../../src/nest/maps/maps.helpers';
const profile = new UserProfileService(new DatabaseService(testDb));
@@ -253,6 +254,55 @@ describe('validateKeys', () => {
if (prevAppUrl === undefined) delete process.env.APP_URL;
else process.env.APP_URL = prevAppUrl;
});
it('AUTH-DB-111: probes the operator key on an install where the admin has no column of their own', async () => {
const prevPlacesKey = process.env.PLACES_API_KEY;
process.env.PLACES_API_KEY = 'operator-key';
const fetchSpy = vi.spyOn(global, 'fetch').mockResolvedValueOnce({
status: 200,
statusText: 'OK',
text: async () => '',
} as Response);
try {
// The admin column stays empty on purpose: on an operator-run install the
// key belongs to whoever runs the box, and the panel used to answer
// "no maps key" while every search on that same install worked.
const { user } = createAdmin(testDb);
const result = await profile.validateKeys(user.id);
const headers = (fetchSpy.mock.calls[0]?.[1]?.headers ?? {}) as Record<string, string>;
expect(headers['X-Goog-Api-Key']).toBe('operator-key');
expect(result.maps).toBe(true);
} finally {
fetchSpy.mockRestore();
if (prevPlacesKey === undefined) delete process.env.PLACES_API_KEY;
else process.env.PLACES_API_KEY = prevPlacesKey;
}
});
it('AUTH-DB-112: probes the instance key, not a stale value in the admin own column', async () => {
const { user } = createAdmin(testDb);
// What a second admin sees after the instance key was saved by the first
// one: their column still holds whatever they pasted long ago, while every
// search on the install runs on the app_settings row.
testDb.prepare('UPDATE users SET maps_api_key = ? WHERE id = ?').run('stale-personal-key', user.id);
testDb.prepare("INSERT INTO app_settings (key, value) VALUES ('maps_api_key', 'live-instance-key')").run();
const fetchSpy = vi.spyOn(global, 'fetch').mockResolvedValueOnce({
status: 200,
statusText: 'OK',
text: async () => '',
} as Response);
await profile.validateKeys(user.id);
const headers = (fetchSpy.mock.calls[0]?.[1]?.headers ?? {}) as Record<string, string>;
expect(headers['X-Goog-Api-Key']).toBe('live-instance-key');
// And it asks for the fields the real search asks for, so a key restricted
// to fewer Places SKUs fails the test button instead of passing it.
expect(headers['X-Goog-FieldMask']).toBe(SEARCH_TEXT_FIELD_MASK);
fetchSpy.mockRestore();
});
});
describe('updateMapsKey / avatar', () => {
@@ -285,3 +335,110 @@ describe('profile quirk fixes', () => {
expect(result.success).toBe(true);
});
});
// ---------------------------------------------------------------------------
// Instance-wide keys + changedKeys (#1939)
//
// apiKeyCrypto is mocked to identity in this file, so nothing here asserts
// anything about encryption — the random-IV half of changedKeys is pinned in
// tests/integration/security.test.ts, which runs with a real ENCRYPTION_KEY.
// ---------------------------------------------------------------------------
const instanceRow = (key: string) =>
(testDb.prepare('SELECT value FROM app_settings WHERE key = ?').get(key) as { value: string } | undefined)?.value;
describe('instance-wide API keys', () => {
it('AUTH-DB-102: an admin save lands in app_settings AND in their own column', () => {
const { user } = createAdmin(testDb);
profile.updateApiKeys(user.id, { maps_api_key: 'instance-google-key', unsplash_api_key: 'instance-unsplash-key' });
expect(instanceRow('maps_api_key')).toBe('instance-google-key');
expect(instanceRow('unsplash_api_key')).toBe('instance-unsplash-key');
// The column stays in step so clearing the field clears both.
const row = testDb.prepare('SELECT maps_api_key FROM users WHERE id = ?').get(user.id) as { maps_api_key: string };
expect(row.maps_api_key).toBe('instance-google-key');
});
it('AUTH-DB-103: a non-admin save never touches the instance value', () => {
const { user: admin } = createAdmin(testDb);
profile.updateApiKeys(admin.id, { maps_api_key: 'admin-set' });
const { user } = createUser(testDb);
profile.updateApiKeys(user.id, { maps_api_key: 'members-own' });
expect(instanceRow('maps_api_key')).toBe('admin-set');
const row = testDb.prepare('SELECT maps_api_key FROM users WHERE id = ?').get(user.id) as { maps_api_key: string };
expect(row.maps_api_key).toBe('members-own');
});
it('AUTH-DB-104: clearing the field stores an empty instance value rather than dropping the row', () => {
const { user } = createAdmin(testDb);
profile.updateApiKeys(user.id, { maps_api_key: 'to-be-removed' });
profile.updateApiKeys(user.id, { maps_api_key: '' });
// '' and not a missing row: a missing row would fall through to whatever
// still sat in the admin's own column.
expect(instanceRow('maps_api_key')).toBe('');
});
it('AUTH-DB-105: getSettings reads the instance value, not the admin own column', () => {
const { user } = createAdmin(testDb);
testDb.prepare('UPDATE users SET maps_api_key = ? WHERE id = ?').run('stale-personal-key', user.id);
testDb.prepare("INSERT INTO app_settings (key, value) VALUES ('maps_api_key', 'live-instance-key')").run();
expect(profile.getSettings(user.id).settings?.maps_api_key).toBe('live-instance-key');
// openweather is per-user and unaffected.
expect(profile.getSettings(user.id).settings?.openweather_api_key).toBeNull();
});
it('AUTH-DB-106: updateMapsKey mirrors for an admin and stays personal for a member', () => {
const { user: admin } = createAdmin(testDb);
expect(profile.updateMapsKey(admin.id, 'via-maps-key-route').changedKeys).toEqual(['maps_api_key']);
expect(instanceRow('maps_api_key')).toBe('via-maps-key-route');
const { user } = createUser(testDb);
profile.updateMapsKey(user.id, 'members-own');
expect(instanceRow('maps_api_key')).toBe('via-maps-key-route');
});
it('AUTH-DB-107: updateSettings mirrors the key half without touching name/email handling', () => {
const { user } = createAdmin(testDb);
const result = profile.updateSettings(user.id, { maps_api_key: 'from-settings-route', username: 'renamed' });
expect(result.success).toBe(true);
expect(result.user?.username).toBe('renamed');
expect(instanceRow('maps_api_key')).toBe('from-settings-route');
expect(result.changedKeys).toEqual(['maps_api_key']);
});
});
describe('changedKeys', () => {
it('AUTH-DB-108: only the names in the body count, and clearing counts as a change', () => {
const { user } = createAdmin(testDb);
profile.updateApiKeys(user.id, { maps_api_key: 'k1', openweather_api_key: 'w1' });
// unsplash was never sent, so it can never be reported.
expect(profile.updateApiKeys(user.id, { openweather_api_key: 'w2' }).changedKeys).toEqual(['openweather_api_key']);
expect(profile.updateApiKeys(user.id, { maps_api_key: '' }).changedKeys).toEqual(['maps_api_key']);
});
it('AUTH-DB-109: an unchanged value reports nothing, whitespace included', () => {
const { user } = createAdmin(testDb);
profile.updateApiKeys(user.id, { maps_api_key: 'unchanged-key' });
expect(profile.updateApiKeys(user.id, { maps_api_key: 'unchanged-key' }).changedKeys).toEqual([]);
// maybe_encrypt_api_key trims on the way in, so the comparison has to too.
expect(profile.updateApiKeys(user.id, { maps_api_key: ' unchanged-key ' }).changedKeys).toEqual([]);
// A member is measured against their own column, not the instance value.
const { user: member } = createUser(testDb);
expect(profile.updateApiKeys(member.id, { maps_api_key: 'unchanged-key' }).changedKeys).toEqual(['maps_api_key']);
});
it('AUTH-DB-110: a managed install reports no change for the names it refuses to write', () => {
const prev = process.env.TREK_MANAGED;
process.env.TREK_MANAGED = 'true';
try {
const { user } = createAdmin(testDb);
const result = profile.updateApiKeys(user.id, { maps_api_key: 'operator-owns-this' });
expect(result.managed_keys).toEqual(['maps_api_key']);
expect(result.changedKeys).toEqual([]);
expect(instanceRow('maps_api_key')).toBeUndefined();
expect(profile.updateMapsKey(user.id, 'operator-owns-this').changedKeys).toEqual([]);
expect(profile.updateSettings(user.id, { maps_api_key: 'operator-owns-this' }).changedKeys).toEqual([]);
} finally {
if (prev === undefined) delete process.env.TREK_MANAGED;
else process.env.TREK_MANAGED = prev;
}
});
});