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
@@ -43,8 +43,9 @@ describe('incoming_leg_transport_mode migration', () => {
//
// >>> Appending a migration? Re-point the "undo" below at whatever yours
// >>> does. That is the whole maintenance cost of this guard. The current
// >>> trailing slot deletes reservation_day_positions rows whose reservation
// >>> and day sit on different trips, so undoing it means putting one back.
// >>> trailing slot copies the lowest-id admin's Google and Unsplash keys
// >>> into app_settings, so undoing it means clearing those rows and
// >>> leaving an admin holding a key for it to find again.
const upgraded = new Database(':memory:');
upgraded.exec('PRAGMA foreign_keys = ON');
createTables(upgraded);
@@ -52,23 +53,30 @@ describe('incoming_leg_transport_mode migration', () => {
const { version } = upgraded.prepare('SELECT version FROM schema_version').get() as { version: number };
upgraded.prepare("INSERT INTO users (id, username, email, password_hash) VALUES (1, 'a', 'a@test.local', 'x')").run();
upgraded.prepare("INSERT INTO users (id, username, email, password_hash) VALUES (2, 'b', 'b@test.local', 'x')").run();
const tripA = upgraded.prepare("INSERT INTO trips (user_id, title) VALUES (1, 'A')").run().lastInsertRowid;
const tripB = upgraded.prepare("INSERT INTO trips (user_id, title) VALUES (2, 'B')").run().lastInsertRowid;
const reservationOnA = upgraded.prepare("INSERT INTO reservations (trip_id, title, type) VALUES (?, 'r', 'other')").run(tripA).lastInsertRowid;
const dayOnA = upgraded.prepare("INSERT INTO days (trip_id, day_number, date) VALUES (?, 1, '2026-01-01')").run(tripA).lastInsertRowid;
const dayOnB = upgraded.prepare("INSERT INTO days (trip_id, day_number, date) VALUES (?, 1, '2026-01-01')").run(tripB).lastInsertRowid;
const insertPosition = upgraded.prepare('INSERT INTO reservation_day_positions (reservation_id, day_id, position) VALUES (?, ?, ?)');
insertPosition.run(reservationOnA, dayOnB, 1); // the mismatched pair the migration clears
insertPosition.run(reservationOnA, dayOnA, 2); // a legitimate one it must leave alone
upgraded.prepare("DELETE FROM app_settings WHERE key IN ('maps_api_key', 'unsplash_api_key')").run();
upgraded
.prepare(
`INSERT INTO users (id, username, email, password_hash, role, maps_api_key)
VALUES (2, 'b', 'b@test.local', 'x', 'admin', NULL)`
)
.run();
// The only key on the install, which is the one condition under which the
// migration promotes it at all; the rest of that decision is pinned in
// tests/unit/db/instance-api-key-backfill.test.ts.
upgraded
.prepare(
`INSERT INTO users (id, username, email, password_hash, role, maps_api_key)
VALUES (1, 'a', 'a@test.local', 'x', 'admin', 'key-of-the-first-admin')`
)
.run();
upgraded.prepare('UPDATE schema_version SET version = ?').run(version - 1);
runMigrations(upgraded);
const rows = upgraded.prepare('SELECT day_id FROM reservation_day_positions ORDER BY day_id').all() as { day_id: number }[];
expect(rows).toEqual([{ day_id: Number(dayOnA) }]);
expect(upgraded.prepare("SELECT value FROM app_settings WHERE key = 'maps_api_key'").get()).toEqual({
value: 'key-of-the-first-admin',
});
expect(upgraded.prepare('SELECT version FROM schema_version').get()).toEqual({ version });
upgraded.close();
});
+29
View File
@@ -136,6 +136,35 @@ describe('API key encryption', () => {
expect(row.openweather_api_key).toMatch(/^enc:v1:/);
});
it('SEC-008 — saving keys audits the names and never the values (#1939)', async () => {
const { user } = createUser(testDb);
const save = () =>
request(app)
.put('/api/auth/me/api-keys')
.set('Cookie', authCookie(user.id))
.send({ openweather_api_key: 'test-api-key-12345' });
const first = await save();
expect(first.status).toBe(200);
// changedKeys is internal: the client body is what it always was.
expect(first.body).not.toHaveProperty('changedKeys');
const rows = () =>
testDb
.prepare("SELECT details FROM audit_log WHERE action = 'settings.api_keys_update'")
.all() as { details: string | null }[];
expect(rows()).toHaveLength(1);
expect(rows()[0].details).toContain('openweather_api_key');
expect(rows()[0].details).not.toContain('test-api-key-12345');
// The same value again writes no second row. This is the real test of the
// cleartext comparison: encryption uses a random IV, so the stored blob
// differs on every save even when the key does not.
await save();
expect(rows()).toHaveLength(1);
});
it('SEC-008 — GET /api/auth/me does not return plaintext API key', async () => {
const { user } = createUser(testDb);
await request(app)