fix: audit fixes — memory leak, input validation, deduplication
- Fix WASM DB memory leak: close database in finally block so errors during analysis don't leave it open until manual reset - Validate metadata.encryptionKey is a non-empty string before use - Extract shared findMigrationsFolder to backup/shared.ts (was duplicated in import and migrations routes) - Wrap export card error response JSON parse to handle non-JSON - Check migration exit code in run.sh — abort startup on failure
This commit is contained in:
6 files changed
+85
-80
No files matched your search
@@ -20,8 +20,11 @@ export const BackupExportCard = () => {
|
|||||||
try {
|
try {
|
||||||
const response = await fetch("/api/backup/export");
|
const response = await fetch("/api/backup/export");
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const data = await response.json();
|
const errorMessage = await response.json().then(
|
||||||
throw new Error(data.error ?? t("error"));
|
(data) => data.error,
|
||||||
|
() => `Server returned ${response.status}`,
|
||||||
|
);
|
||||||
|
throw new Error(errorMessage ?? t("error"));
|
||||||
}
|
}
|
||||||
|
|
||||||
const blob = await response.blob();
|
const blob = await response.blob();
|
||||||
|
|||||||
@@ -14,19 +14,12 @@ import { DB_CASING } from "@homarr/core/infrastructure/db/constants";
|
|||||||
import { dbEnv } from "@homarr/core/infrastructure/db/env";
|
import { dbEnv } from "@homarr/core/infrastructure/db/env";
|
||||||
import { db } from "@homarr/db";
|
import { db } from "@homarr/db";
|
||||||
|
|
||||||
|
import { findMigrationsFolder } from "../shared";
|
||||||
|
|
||||||
const REQUIRED_ZIP_ENTRIES = ["db.sqlite", "metadata.json"] as const;
|
const REQUIRED_ZIP_ENTRIES = ["db.sqlite", "metadata.json"] as const;
|
||||||
const ALGORITHM = "aes-256-cbc";
|
const ALGORITHM = "aes-256-cbc";
|
||||||
const HEX_KEY_REGEX = /^[0-9a-fA-F]{64}$/;
|
const HEX_KEY_REGEX = /^[0-9a-fA-F]{64}$/;
|
||||||
|
|
||||||
const migrationsFolderCandidates = [
|
|
||||||
path.join(process.cwd(), "db/migrations/sqlite"),
|
|
||||||
path.join(process.cwd(), "packages/db/migrations/sqlite"),
|
|
||||||
path.resolve(process.cwd(), "../../db/migrations/sqlite"),
|
|
||||||
"/app/db/migrations/sqlite",
|
|
||||||
];
|
|
||||||
|
|
||||||
const findMigrationsFolder = () => migrationsFolderCandidates.find((candidate) => fs.existsSync(candidate));
|
|
||||||
|
|
||||||
const reEncryptSecrets = (tempDb: InstanceType<typeof Database>, importedKeyHex: string) => {
|
const reEncryptSecrets = (tempDb: InstanceType<typeof Database>, importedKeyHex: string) => {
|
||||||
const currentKeyHex = env.SECRET_ENCRYPTION_KEY;
|
const currentKeyHex = env.SECRET_ENCRYPTION_KEY;
|
||||||
if (importedKeyHex === currentKeyHex) return;
|
if (importedKeyHex === currentKeyHex) return;
|
||||||
@@ -146,9 +139,8 @@ export async function POST(req: Request) {
|
|||||||
const metadataEntry = zip.getEntry("metadata.json")!;
|
const metadataEntry = zip.getEntry("metadata.json")!;
|
||||||
const metadata = JSON.parse(metadataEntry.getData().toString());
|
const metadata = JSON.parse(metadataEntry.getData().toString());
|
||||||
|
|
||||||
const importedKey =
|
const rawKey = metadata.encryptionKey ?? zip.getEntry("encryption-key.txt")?.getData().toString().trim();
|
||||||
metadata.encryptionKey ??
|
const importedKey = typeof rawKey === "string" && rawKey.length > 0 ? rawKey : undefined;
|
||||||
zip.getEntry("encryption-key.txt")?.getData().toString().trim();
|
|
||||||
|
|
||||||
const secretCount = (
|
const secretCount = (
|
||||||
tempDb.prepare('SELECT COUNT(*) as count FROM "integrationSecret"').get() as { count: number }
|
tempDb.prepare('SELECT COUNT(*) as count FROM "integrationSecret"').get() as { count: number }
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ import path from "path";
|
|||||||
|
|
||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
|
|
||||||
|
import { findMigrationsFolder } from "../shared";
|
||||||
|
|
||||||
interface JournalEntry {
|
interface JournalEntry {
|
||||||
idx: number;
|
idx: number;
|
||||||
version: string;
|
version: string;
|
||||||
@@ -18,15 +20,6 @@ interface MigrationFile {
|
|||||||
when: number;
|
when: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
const migrationsFolderCandidates = [
|
|
||||||
path.join(process.cwd(), "db/migrations/sqlite"),
|
|
||||||
path.join(process.cwd(), "packages/db/migrations/sqlite"),
|
|
||||||
path.resolve(process.cwd(), "../../db/migrations/sqlite"),
|
|
||||||
"/app/db/migrations/sqlite",
|
|
||||||
];
|
|
||||||
|
|
||||||
const findMigrationsFolder = () => migrationsFolderCandidates.find((candidate) => fs.existsSync(candidate));
|
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
try {
|
try {
|
||||||
const migrationsFolder = findMigrationsFolder();
|
const migrationsFolder = findMigrationsFolder();
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import fs from "fs";
|
||||||
|
import path from "path";
|
||||||
|
|
||||||
|
const migrationsFolderCandidates = [
|
||||||
|
path.join(process.cwd(), "db/migrations/sqlite"),
|
||||||
|
path.join(process.cwd(), "packages/db/migrations/sqlite"),
|
||||||
|
path.resolve(process.cwd(), "../../db/migrations/sqlite"),
|
||||||
|
"/app/db/migrations/sqlite",
|
||||||
|
];
|
||||||
|
|
||||||
|
export const findMigrationsFolder = () =>
|
||||||
|
migrationsFolderCandidates.find((candidate) => fs.existsSync(candidate));
|
||||||
@@ -98,72 +98,74 @@ export const useBackupAnalysis = () => {
|
|||||||
const db = new SQL.Database(dbBuffer);
|
const db = new SQL.Database(dbBuffer);
|
||||||
dbRef.current = db;
|
dbRef.current = db;
|
||||||
|
|
||||||
const appliedCount = getAppliedMigrationCount(db);
|
try {
|
||||||
const pendingMigrations = allMigrations.filter((m) => m.idx >= appliedCount);
|
const appliedCount = getAppliedMigrationCount(db);
|
||||||
|
const pendingMigrations = allMigrations.filter((m) => m.idx >= appliedCount);
|
||||||
|
|
||||||
const migrations: MigrationStatus = {
|
const migrations: MigrationStatus = {
|
||||||
applied: appliedCount,
|
applied: appliedCount,
|
||||||
pending: pendingMigrations,
|
pending: pendingMigrations,
|
||||||
total: allMigrations.length,
|
total: allMigrations.length,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (pendingMigrations.length > 0) {
|
if (pendingMigrations.length > 0) {
|
||||||
for (let i = 0; i < pendingMigrations.length; i++) {
|
for (let i = 0; i < pendingMigrations.length; i++) {
|
||||||
const migration = pendingMigrations[i]!;
|
const migration = pendingMigrations[i]!;
|
||||||
setMigrationProgress({
|
|
||||||
current: i + 1,
|
|
||||||
total: pendingMigrations.length,
|
|
||||||
tag: migration.tag,
|
|
||||||
phase: "applying",
|
|
||||||
});
|
|
||||||
|
|
||||||
await delay(100);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const statements = migration.sql
|
|
||||||
.split("--> statement-breakpoint")
|
|
||||||
.map((s) => s.trim())
|
|
||||||
.filter(Boolean);
|
|
||||||
|
|
||||||
for (const stmt of statements) {
|
|
||||||
db.run(stmt);
|
|
||||||
}
|
|
||||||
|
|
||||||
db.run(
|
|
||||||
`INSERT INTO "${DRIZZLE_MIGRATIONS_TABLE}" ("hash", "created_at") VALUES (?, ?)`,
|
|
||||||
[migration.tag, Date.now()],
|
|
||||||
);
|
|
||||||
} catch (migrationErr) {
|
|
||||||
setMigrationProgress({
|
setMigrationProgress({
|
||||||
current: i + 1,
|
current: i + 1,
|
||||||
total: pendingMigrations.length,
|
total: pendingMigrations.length,
|
||||||
tag: migration.tag,
|
tag: migration.tag,
|
||||||
phase: "error",
|
phase: "applying",
|
||||||
});
|
});
|
||||||
throw new Error(
|
|
||||||
`Migration ${migration.tag} failed: ${migrationErr instanceof Error ? migrationErr.message : "Unknown error"}`,
|
await delay(100);
|
||||||
);
|
|
||||||
|
try {
|
||||||
|
const statements = migration.sql
|
||||||
|
.split("--> statement-breakpoint")
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
|
||||||
|
for (const stmt of statements) {
|
||||||
|
db.run(stmt);
|
||||||
|
}
|
||||||
|
|
||||||
|
db.run(
|
||||||
|
`INSERT INTO "${DRIZZLE_MIGRATIONS_TABLE}" ("hash", "created_at") VALUES (?, ?)`,
|
||||||
|
[migration.tag, Date.now()],
|
||||||
|
);
|
||||||
|
} catch (migrationErr) {
|
||||||
|
setMigrationProgress({
|
||||||
|
current: i + 1,
|
||||||
|
total: pendingMigrations.length,
|
||||||
|
tag: migration.tag,
|
||||||
|
phase: "error",
|
||||||
|
});
|
||||||
|
throw new Error(
|
||||||
|
`Migration ${migration.tag} failed: ${migrationErr instanceof Error ? migrationErr.message : "Unknown error"}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
setMigrationProgress({
|
||||||
|
current: i + 1,
|
||||||
|
total: pendingMigrations.length,
|
||||||
|
tag: migration.tag,
|
||||||
|
phase: "done",
|
||||||
|
});
|
||||||
|
|
||||||
|
await delay(50);
|
||||||
}
|
}
|
||||||
|
|
||||||
setMigrationProgress({
|
|
||||||
current: i + 1,
|
|
||||||
total: pendingMigrations.length,
|
|
||||||
tag: migration.tag,
|
|
||||||
phase: "done",
|
|
||||||
});
|
|
||||||
|
|
||||||
await delay(50);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const counts = countEntities(db);
|
||||||
|
const boardNames = getBoardNames(db);
|
||||||
|
|
||||||
|
setMigrationProgress(null);
|
||||||
|
setAnalysis({ metadata, counts, boardNames, migrations });
|
||||||
|
} finally {
|
||||||
|
db.close();
|
||||||
|
dbRef.current = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const counts = countEntities(db);
|
|
||||||
const boardNames = getBoardNames(db);
|
|
||||||
|
|
||||||
db.close();
|
|
||||||
dbRef.current = null;
|
|
||||||
|
|
||||||
setMigrationProgress(null);
|
|
||||||
setAnalysis({ metadata, counts, boardNames, migrations });
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err instanceof Error ? err.message : t("analyzeError"));
|
setError(err instanceof Error ? err.message : t("analyzeError"));
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
+4
-1
@@ -10,8 +10,11 @@ if [ "$DB_MIGRATIONS_DISABLED" = "true" ]; then
|
|||||||
echo "DB migrations are disabled, skipping"
|
echo "DB migrations are disabled, skipping"
|
||||||
else
|
else
|
||||||
echo "Running DB migrations"
|
echo "Running DB migrations"
|
||||||
# We disable redis logs during migration as the redis client is not yet started
|
|
||||||
DISABLE_REDIS_LOGS=true node ./db/migrations/$DB_DIALECT/migrate.cjs ./db/migrations/$DB_DIALECT
|
DISABLE_REDIS_LOGS=true node ./db/migrations/$DB_DIALECT/migrate.cjs ./db/migrations/$DB_DIALECT
|
||||||
|
if [ $? -ne 0 ]; then
|
||||||
|
echo "ERROR: DB migrations failed, aborting startup"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Auth secret is generated every time the container starts as it is required, but not used because we don't need JWTs or Mail hashing
|
# Auth secret is generated every time the container starts as it is required, but not used because we don't need JWTs or Mail hashing
|
||||||
|
|||||||
Reference in new issue
Block a user