Skip to content

Commit 8eca84e

Browse files
author
Volodymyr Malyhin
committed
feat: add migration for secret records
1 parent bde4b04 commit 8eca84e

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import { Knex } from 'knex';
2+
3+
import { EntityTypes } from '../versioning/interfaces';
4+
import { sanitizeSnapshot, Snapshot } from '../versioning/utils/secretSanitizer';
5+
6+
const ENTITY_TYPES = [EntityTypes.settings, EntityTypes.settings_domain_value, EntityTypes.auth_entities];
7+
8+
function sanitizeIfChanged(json: string | null, entityType: string, secretKeys: Set<string>): string | null {
9+
if (!json) {
10+
return null;
11+
}
12+
const sanitized = JSON.stringify(sanitizeSnapshot(entityType, JSON.parse(json) as Snapshot, secretKeys));
13+
return sanitized !== json ? sanitized : null;
14+
}
15+
16+
export async function up(knex: Knex): Promise<void> {
17+
const secretSettings: { key: string }[] = await knex('settings').select('key').where('secret', true);
18+
const secretKeys = new Set(secretSettings.map((s) => s.key));
19+
20+
let count = 0;
21+
const stream = knex('versioning')
22+
.select('id', 'entity_type', 'data', 'data_after')
23+
.whereIn('entity_type', ENTITY_TYPES)
24+
.stream();
25+
26+
for await (const row of stream) {
27+
const data = sanitizeIfChanged(row.data, row.entity_type, secretKeys);
28+
const dataAfter = sanitizeIfChanged(row.data_after, row.entity_type, secretKeys);
29+
30+
if (data || dataAfter) {
31+
const update: Record<string, string> = {};
32+
if (data) {
33+
update.data = data;
34+
}
35+
if (dataAfter) {
36+
update.data_after = dataAfter;
37+
}
38+
await knex('versioning').where('id', row.id).update(update);
39+
count++;
40+
}
41+
}
42+
43+
console.log(`Sanitized ${count} versioning records`);
44+
}
45+
46+
export async function down(): Promise<void> {
47+
throw new Error('Irreversible migration: secret values cannot be recovered');
48+
}

0 commit comments

Comments
 (0)