Files
OmniRoute/tests/unit/db-backup-extended.test.ts
Diego Rodrigues de Sa e Souza 35dbf0eea1 Release v3.8.25 (#3866)
* chore(release): continue v3.8.25 development cycle after main code-sync (r5)

main fast-forwarded to release/v3.8.25 (#3863): unblocked Build+Docker via
#3864, plus #3837 (mimocode proxy) and #3862 (trivy bump). This marker
re-opens the umbrella PR for further v3.8.25 work. No version bump.

* fix(db): persist the Keep-latest-backups retention setting (#3834) (#3867)

* fix(oauth): clear GitLab Duo setup message instead of 500 (#3861) (#3868)

* test(oauth): prove refresh_token preserved on real gemini-cli/antigravity dispatch (#3850) (#3869)

* feat(compression-ui): unified compression config UI — per-engine pages + combos editor + menu + WS default-on (#3860)

Integrated into release/v3.8.25 — feat(compression-ui): unified compression configuration UI (Compression Hub + per-engine Lite/Aggressive/Ultra pages + combos editor + sidebar entry + live-WS default-on). File-size re-baselined for sidebarVisibility.ts/chatCore.ts growth; orphan ws test relocated to a collected path.

* docs(changelog): complete the v3.8.25 release notes + credit all contributors

Audited every commit since v3.8.24 and filled the gaps the [3.8.25] section
was missing: a New Features section (compression engines + Compression Studios
#3848, compression UI #3860, injection-guard #3857, kiro discovery #3836, Veo
#3839, mimocode proxy #3837, Arena ELO flag #3821), 9 more Fixed entries
(#3811/#3807/#3759/#3849/#3838/#3835/#3814/#3820/#3819), a Security section
(CCR IDOR #3859, supply-chain #3824), and an Internal/Quality section. Every
contributor and issue reporter is now credited.

* docs(changelog): restore + complete the v3.8.25 release notes

Re-adds CHANGELOG.md (a prior server-side commit accidentally dropped it) with
the complete, audited [3.8.25] section: New Features, the full Fixed list,
Security & Hardening, and Internal/Quality — every contributor and issue
reporter credited.

* chore(release): finalize v3.8.25 — reconcile CHANGELOG + i18n mirrors, document OMNIROUTE_MAX_PENDING_MIGRATIONS, green the unit suite

Release-gate reconciliation for v3.8.25:
- CHANGELOG: dated 2026-06-14, linked #3826, rolled up file-size re-baselines (#3823/#3833),
  recorded the test-greening; re-synced all 41 i18n CHANGELOG mirrors.
- Documented OMNIROUTE_MAX_PENDING_MIGRATIONS (#3416) in .env.example + ENVIRONMENT.md.
- Greened the unit suite (was merged red on 4 CI shards): aligned 10 stale tests to this
  cycle's intended behavior (#3838/#3822/#3501/SOCKS5/Vertex-Express/Antigravity) and the
  same-provider 503 fall-through test; de-flaked the compression benchmark reproducibility
  and ServiceSupervisor crash tests. No production code changed.

* ci(security): clear OpenSSF Scorecard code-scanning noise + harden workflow token permissions

The Security tab held 155 open alerts, ALL from the advisory OpenSSF Scorecard tool
(#3824) — supply-chain/posture scores, not code vulnerabilities — which drowned out
real CodeQL findings.

- scorecard.yml: stop uploading SARIF to the code-scanning tab (drop the upload-sarif
  step + the now-unused security-events: write). The run still produces the OpenSSF
  badge (publish_results) and a downloadable SARIF artifact.
- TokenPermissions hardening (the high-severity, genuinely-valuable subset): set each
  workflow's top-level token to read-only and grant the exact writes at the job level
  that needs them — npm-publish (id-token/packages on publish jobs), docker-publish
  (packages on build), electron-release (contents on build/release, id-token/packages
  on publish-npm), build-fork (packages on build), claude (empty top-level; job grants
  its own). The 155 existing alerts were dismissed.

Not adopting repo-wide SHA-pinning (143 PinnedDependencies advisories) — declined.

* test(integration): align stale wiring/socks5 integration tests to this cycle's behavior

These were red on the CI Integration job (pre-existing). No production code changed:
- integration-wiring: the combos page no longer renders a per-page EmailPrivacyToggle
  (#3822 consolidated it into Settings → Appearance); the provider-detail test-result
  masking and upstream-proxy copy moved to decomposed components (#3501
  BatchTestResultsModal / UpstreamProxyCard) — assertions now read the owning files.
- api-routes-critical: SOCKS5 is now enabled by default (opt-out), so the disabled-
  rejection test must set ENABLE_SOCKS5_PROXY=false explicitly (an unset env now means
  enabled).

(The ~32 live-Gemini integration tests are gated on OMNIROUTE_API_KEY and skip in CI;
they only 'fail' locally when that key is present without a running server.)
2026-06-15 03:32:11 -03:00

225 lines
8.1 KiB
TypeScript

import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-backup-"));
const isWindows = process.platform === "win32";
process.env.DATA_DIR = TEST_DATA_DIR;
const core = await import("../../src/lib/db/core.ts");
const backupDb = await import("../../src/lib/db/backup.ts");
async function resetStorage() {
core.resetDbInstance();
await new Promise((resolve) => setTimeout(resolve, 50));
if (fs.existsSync(TEST_DATA_DIR)) {
for (const entry of fs.readdirSync(TEST_DATA_DIR, { recursive: true }).sort().reverse()) {
const targetPath = path.join(TEST_DATA_DIR, entry);
const stat = fs.lstatSync(targetPath);
if (stat.isDirectory()) {
fs.rmSync(targetPath, { recursive: true, force: true });
} else {
await backupDb.unlinkFileWithRetry(targetPath, { maxAttempts: 20, baseDelayMs: 25 });
}
}
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
}
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
}
function seedConnections(count = 8) {
const db = core.getDbInstance();
const now = new Date().toISOString();
const insert = db.prepare(
"INSERT INTO provider_connections (id, provider, auth_type, name, is_active, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)"
);
for (let index = 0; index < count; index++) {
insert.run(`backup-conn-${index}`, "openai", "apikey", `backup-${index}`, 1, now, now);
}
}
async function waitForFile(filePath) {
for (let attempt = 0; attempt < 20; attempt++) {
if (fs.existsSync(filePath)) return;
await new Promise((resolve) => setTimeout(resolve, 50));
}
throw new Error(`Timed out waiting for file: ${filePath}`);
}
test.beforeEach(async () => {
await resetStorage();
});
test.after(async () => {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
});
test("backupDbFile creates manual backups and listDbBackups returns metadata", async () => {
seedConnections(12);
const result = backupDb.backupDbFile("manual");
assert.ok(result);
const backupPath = path.join(core.DB_BACKUPS_DIR, result.filename);
await waitForFile(backupPath);
const backups = await backupDb.listDbBackups();
assert.equal(backups.length >= 1, true);
assert.equal(backups[0].reason, "manual");
assert.equal(backups[0].connectionCount, 12);
assert.equal(fs.existsSync(backupPath), true);
});
test("listDbBackups returns an empty list when the backup directory is missing", async () => {
fs.rmSync(core.DB_BACKUPS_DIR, { recursive: true, force: true });
const backups = await backupDb.listDbBackups();
assert.deepEqual(backups, []);
});
test(
"restoreDbBackup rejects invalid identifiers and corrupt backup files",
{ skip: isWindows },
async () => {
await assert.rejects(() => backupDb.restoreDbBackup("../escape.sqlite"), /Invalid backup ID/);
const missingId = "db_2000-01-01T00-00-00-000Z_manual.sqlite";
await assert.rejects(() => backupDb.restoreDbBackup(missingId), /Backup not found/);
fs.mkdirSync(core.DB_BACKUPS_DIR, { recursive: true });
const corruptId = "db_2001-01-01T00-00-00-000Z_manual.sqlite";
fs.writeFileSync(path.join(core.DB_BACKUPS_DIR, corruptId), "not a sqlite database");
await assert.rejects(() => backupDb.restoreDbBackup(corruptId), /Backup file is corrupt/);
await backupDb.unlinkFileWithRetry(path.join(core.DB_BACKUPS_DIR, corruptId), {
maxAttempts: 20,
baseDelayMs: 25,
});
}
);
test("restoreDbBackup restores SQLite contents and returns entity counts", async () => {
seedConnections(1);
const backupId = "db_2002-01-01T00-00-00-000Z_manual.sqlite";
fs.mkdirSync(core.DB_BACKUPS_DIR, { recursive: true });
await core.getDbInstance().backup(path.join(core.DB_BACKUPS_DIR, backupId));
core
.getDbInstance()
.prepare("DELETE FROM provider_connections WHERE id = ?")
.run("backup-conn-0");
const restored = await backupDb.restoreDbBackup(backupId);
const row = core
.getDbInstance()
.prepare("SELECT COUNT(*) AS cnt FROM provider_connections WHERE id = ?")
.get("backup-conn-0");
assert.equal(restored.restored, true);
assert.equal(restored.backupId, backupId);
assert.equal(restored.connectionCount, 1);
assert.equal(restored.nodeCount, 0);
assert.equal(restored.comboCount, 0);
assert.equal(restored.apiKeyCount, 0);
assert.equal((row as any).cnt, 1);
});
test("cleanupDbBackups removes overflow families and orphaned sidecars", async () => {
fs.mkdirSync(core.DB_BACKUPS_DIR, { recursive: true });
const makeFamily = (baseName, minutesAgo) => {
const familyPath = path.join(core.DB_BACKUPS_DIR, baseName);
fs.writeFileSync(familyPath, baseName);
fs.writeFileSync(`${familyPath}-wal`, `${baseName}-wal`);
fs.writeFileSync(`${familyPath}-shm`, `${baseName}-shm`);
const time = new Date(Date.now() - minutesAgo * 60 * 1000);
fs.utimesSync(familyPath, time, time);
fs.utimesSync(`${familyPath}-wal`, time, time);
fs.utimesSync(`${familyPath}-shm`, time, time);
};
makeFamily("db_2026-04-10T00-00-00-000Z_manual.sqlite", 60);
makeFamily("db_2026-04-10T01-00-00-000Z_manual.sqlite", 40);
makeFamily("db_2026-04-10T02-00-00-000Z_manual.sqlite", 20);
fs.writeFileSync(
path.join(core.DB_BACKUPS_DIR, "db_2026-04-09T00-00-00-000Z_manual.sqlite-wal"),
"orphan-wal"
);
const result = backupDb.cleanupDbBackups({ maxFiles: 2, retentionDays: 0 });
const remaining = fs.readdirSync(core.DB_BACKUPS_DIR).sort();
assert.equal(result.deletedBackupFamilies, 2);
assert.equal(
remaining.includes("db_2026-04-10T00-00-00-000Z_manual.sqlite"),
false,
"oldest backup family should be removed"
);
assert.equal(
remaining.some((name) => name.startsWith("db_2026-04-09T00-00-00-000Z_manual.sqlite")),
false,
"orphaned backup sidecars should be removed"
);
assert.equal(
remaining.includes("db_2026-04-10T02-00-00-000Z_manual.sqlite"),
true,
"newest backup family should remain"
);
});
test("cleanupDbBackups honors retentionDays for older backups", async () => {
fs.mkdirSync(core.DB_BACKUPS_DIR, { recursive: true });
const oldBackup = path.join(core.DB_BACKUPS_DIR, "db_2026-04-01T00-00-00-000Z_manual.sqlite");
const freshBackup = path.join(core.DB_BACKUPS_DIR, "db_2026-04-15T00-00-00-000Z_manual.sqlite");
fs.writeFileSync(oldBackup, "old");
fs.writeFileSync(freshBackup, "fresh");
const oldTime = new Date(Date.now() - 10 * 24 * 60 * 60 * 1000);
const freshTime = new Date();
fs.utimesSync(oldBackup, oldTime, oldTime);
fs.utimesSync(freshBackup, freshTime, freshTime);
const result = backupDb.cleanupDbBackups({ maxFiles: 10, retentionDays: 5 });
assert.equal(result.deletedBackupFamilies, 1);
assert.equal(fs.existsSync(oldBackup), false);
assert.equal(fs.existsSync(freshBackup), true);
});
// Regression for #3834: the "Keep latest backups" value did not persist — it always
// snapped back to 20 because getDbBackupMaxFiles() only read the env var (no setter,
// no stored value). It now round-trips through a dedicated key_value store.
test("getDbBackupMaxFiles defaults to 20 when nothing is stored (#3834)", () => {
delete process.env.DB_BACKUP_MAX_FILES;
core.getDbInstance(); // ensure the DB + key_value table exist
assert.equal(backupDb.getDbBackupMaxFiles(), 20);
});
test("setDbBackupMaxFiles persists and getDbBackupMaxFiles reflects it (#3834)", () => {
delete process.env.DB_BACKUP_MAX_FILES;
core.getDbInstance();
backupDb.setDbBackupMaxFiles(5);
assert.equal(backupDb.getDbBackupMaxFiles(), 5);
// A second value overwrites the first (operator changes the setting again).
backupDb.setDbBackupMaxFiles(12);
assert.equal(backupDb.getDbBackupMaxFiles(), 12);
});
test("DB_BACKUP_MAX_FILES env override wins over the persisted value (#3834)", () => {
core.getDbInstance();
backupDb.setDbBackupMaxFiles(5);
process.env.DB_BACKUP_MAX_FILES = "7";
try {
assert.equal(backupDb.getDbBackupMaxFiles(), 7);
} finally {
delete process.env.DB_BACKUP_MAX_FILES;
}
});