feat(safety): temporary write-unlock window for read-only connections

This commit is contained in:
Farahani authored and GitHub committed 2026-08-27 17:37:54 +08:00
1 parent 7933b7656f
commit 955558c81f
66 files changed
+1176 -124

No files matched your search

@@ -0,0 +1,118 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createPinia, setActivePinia } from "pinia";
import { useReadOnlyUnlockStore } from "@/stores/readOnlyUnlockStore";
import { connectionIsEffectivelyReadOnly, ensureReadOnlyWriteAccess, formatWriteUnlockRemaining, sqlLooksLikeMutation } from "../readOnlyWriteAccess";
const unlockConnectionWrites = vi.fn();
const lockConnectionWrites = vi.fn();
const connectionWriteUnlockState = vi.fn();
vi.mock("@/lib/backend/api", () => ({
unlockConnectionWrites: (...args: unknown[]) => unlockConnectionWrites(...args),
lockConnectionWrites: (...args: unknown[]) => lockConnectionWrites(...args),
connectionWriteUnlockState: (...args: unknown[]) => connectionWriteUnlockState(...args),
}));
async function waitForPending(connectionId: string) {
const store = useReadOnlyUnlockStore();
await vi.waitFor(() => {
expect(store.pending?.connectionId).toBe(connectionId);
});
return store;
}
describe("read-only write unlock", () => {
beforeEach(() => {
setActivePinia(createPinia());
unlockConnectionWrites.mockReset().mockResolvedValue(60_000);
lockConnectionWrites.mockReset().mockResolvedValue(undefined);
connectionWriteUnlockState.mockReset().mockResolvedValue(0);
vi.useRealTimers();
});
it("formats remaining time as m:ss", () => {
expect(formatWriteUnlockRemaining(60_000)).toBe("1:00");
expect(formatWriteUnlockRemaining(5_000)).toBe("0:05");
expect(formatWriteUnlockRemaining(0)).toBe("0:00");
});
it("classifies SQL and Redis writes without treating reads as mutations", () => {
expect(sqlLooksLikeMutation("SELECT 1", "mysql")).toBe(false);
expect(sqlLooksLikeMutation("INSERT INTO t VALUES (1)", "mysql")).toBe(true);
expect(sqlLooksLikeMutation("UPDATE t SET a = 1", "postgres")).toBe(true);
expect(sqlLooksLikeMutation("DELETE FROM t", "mysql")).toBe(true);
expect(sqlLooksLikeMutation("CREATE TABLE t (id INT)", "mysql")).toBe(true);
expect(sqlLooksLikeMutation("GET k", "redis")).toBe(false);
expect(sqlLooksLikeMutation("SET k v", "redis")).toBe(true);
});
it("keeps the persistent read-only flag on while a window is active", async () => {
const connection = { id: "prod", name: "prod-db", read_only: true, db_type: "mysql" as const };
expect(connectionIsEffectivelyReadOnly(connection)).toBe(true);
const pending = ensureReadOnlyWriteAccess({ connection, sql: "INSERT INTO t VALUES (1)", source: "SQL editor" });
const store = await waitForPending("prod");
expect(unlockConnectionWrites).not.toHaveBeenCalled();
await store.confirm(60);
await expect(pending).resolves.toBe(true);
expect(unlockConnectionWrites).toHaveBeenCalledWith("prod", 60);
expect(connection.read_only).toBe(true);
expect(connectionIsEffectivelyReadOnly(connection)).toBe(false);
expect(store.isUnlocked("prod")).toBe(true);
expect(store.isUnlocked("other")).toBe(false);
});
it("cancels without unlocking and forgets the window when locked or expired", async () => {
const connection = { id: "prod", name: "prod-db", read_only: true, db_type: "mysql" as const };
const cancelled = ensureReadOnlyWriteAccess({ connection, sql: "DELETE FROM t", source: "SQL editor" });
const store = await waitForPending("prod");
store.cancel();
await expect(cancelled).resolves.toBe(false);
expect(unlockConnectionWrites).not.toHaveBeenCalled();
expect(connectionIsEffectivelyReadOnly(connection)).toBe(true);
const unlocked = ensureReadOnlyWriteAccess({ connection, sql: "DELETE FROM t", source: "SQL editor" });
await waitForPending("prod");
await store.confirm(60);
await expect(unlocked).resolves.toBe(true);
expect(await ensureReadOnlyWriteAccess({ connection, sql: "UPDATE t SET a = 1" })).toBe(true);
expect(unlockConnectionWrites).toHaveBeenCalledTimes(1);
await store.lockNow("prod");
expect(lockConnectionWrites).toHaveBeenCalledWith("prod");
expect(store.isUnlocked("prod")).toBe(false);
expect(connectionIsEffectivelyReadOnly(connection)).toBe(true);
});
it("does not prompt for reads or writable connections", async () => {
const store = useReadOnlyUnlockStore();
await expect(ensureReadOnlyWriteAccess({ connection: { id: "w", read_only: false, db_type: "mysql" }, sql: "INSERT INTO t VALUES (1)" })).resolves.toBe(true);
await expect(ensureReadOnlyWriteAccess({ connection: { id: "r", read_only: true, db_type: "mysql" }, sql: "SELECT 1" })).resolves.toBe(true);
expect(store.pending).toBeUndefined();
expect(connectionWriteUnlockState).not.toHaveBeenCalled();
});
it("reuses an existing backend window without prompting again", async () => {
connectionWriteUnlockState.mockResolvedValue(45_000);
const connection = { id: "prod", name: "prod-db", read_only: true, db_type: "mysql" as const };
await expect(ensureReadOnlyWriteAccess({ connection, sql: "INSERT INTO t VALUES (1)" })).resolves.toBe(true);
expect(unlockConnectionWrites).not.toHaveBeenCalled();
expect(useReadOnlyUnlockStore().pending).toBeUndefined();
expect(connectionIsEffectivelyReadOnly(connection)).toBe(false);
});
it("returns to effectively read-only when the local timer expires", async () => {
vi.useFakeTimers();
const store = useReadOnlyUnlockStore();
const connection = { id: "prod", name: "prod-db", read_only: true, db_type: "mysql" as const };
store.rememberWindow("prod", 60_000);
expect(connectionIsEffectivelyReadOnly(connection)).toBe(false);
await vi.advanceTimersByTimeAsync(60_000);
expect(store.isUnlocked("prod")).toBe(false);
expect(connectionIsEffectivelyReadOnly(connection)).toBe(true);
expect(connection.read_only).toBe(true);
});
});
@@ -1,5 +1,6 @@
import type { ConnectionConfig, DatabaseType, TreeNodeType } from "@/types/database";
import { isMongoLegacyDriverProfile } from "@/lib/mongo/mongoCapabilities";
import { connectionIsEffectivelyReadOnly } from "@/lib/database/readOnlyWriteAccess";
export type DatabaseNamespaceCreationTarget = "database" | "schema" | "attach" | "special";
@@ -12,7 +13,7 @@ export interface DatabaseNamespaceCreationMatrixEntry {
deferred?: string;
}
type CreationConnection = (Pick<ConnectionConfig, "db_type" | "driver_profile" | "read_only"> & Partial<Pick<ConnectionConfig, "host" | "password">>) | undefined;
type CreationConnection = (Pick<ConnectionConfig, "db_type" | "driver_profile" | "read_only"> & Partial<Pick<ConnectionConfig, "host" | "password" | "id">>) | undefined;
// Keep creation target-specific: many products expose schemas, files, or provider-managed namespaces instead of a top-level database.
export const DATABASE_NAMESPACE_CREATION_MATRIX = {
@@ -97,7 +98,7 @@ export const DATABASE_NAMESPACE_CREATION_MATRIX = {
} satisfies Record<DatabaseType, DatabaseNamespaceCreationMatrixEntry>;
export function connectionNamespaceCreationTarget(connection: CreationConnection): ConnectionCreationTarget | null {
if (!connection || connection.read_only) return null;
if (!connection || connectionIsEffectivelyReadOnly(connection)) return null;
if (connection.db_type === "mongodb" && isMongoLegacyDriverProfile(connection.driver_profile)) return null;
if (connection.db_type === "sqlite" && (connection.host?.trim().toLowerCase() === ":memory:" || Boolean(connection.password))) {
return null;
@@ -107,7 +108,7 @@ export function connectionNamespaceCreationTarget(connection: CreationConnection
}
export function databaseNodeNamespaceCreationTarget(connection: CreationConnection, node: Pick<{ type: TreeNodeType; database?: string | null }, "type" | "database">): DatabaseNodeCreationTarget | null {
if (!connection || connection.read_only || node.type !== "database" || !node.database) return null;
if (!connection || connectionIsEffectivelyReadOnly(connection) || node.type !== "database" || !node.database) return null;
const entry: DatabaseNamespaceCreationMatrixEntry = DATABASE_NAMESPACE_CREATION_MATRIX[connection.db_type];
return entry.database ?? null;
}
@@ -1,5 +1,6 @@
import type { ConnectionConfig, DatabaseType, TreeNodeType } from "@/types/database";
import { supportsCreateDatabaseCharset } from "@/lib/database/createDatabaseSql";
import { connectionIsEffectivelyReadOnly } from "@/lib/database/readOnlyWriteAccess";
export type DatabasePropertyEditGroup = "charsetCollation" | "databaseComment" | "schemaComment";
@@ -9,7 +10,7 @@ export interface DatabasePropertyEditingEntry {
deferred?: string;
}
type PropertyEditConnection = Pick<ConnectionConfig, "db_type" | "driver_profile" | "read_only"> | undefined;
type PropertyEditConnection = (Pick<ConnectionConfig, "db_type" | "driver_profile" | "read_only"> & Partial<Pick<ConnectionConfig, "id">>) | undefined;
type DatabaseNode = Pick<{ type: TreeNodeType; database?: string | null }, "type" | "database">;
type SchemaNode = Pick<{ type: TreeNodeType; database?: string | null; schema?: string | null }, "type" | "database" | "schema">;
@@ -97,7 +98,7 @@ export const DATABASE_PROPERTY_EDITING_MATRIX = {
} satisfies Record<DatabaseType, DatabasePropertyEditingEntry>;
function entryFor(connection: PropertyEditConnection): DatabasePropertyEditingEntry | null {
if (!connection || connection.read_only) return null;
if (!connection || connectionIsEffectivelyReadOnly(connection)) return null;
return DATABASE_PROPERTY_EDITING_MATRIX[connection.db_type] ?? null;
}
@@ -1,5 +1,6 @@
import { useProductionSafetyStore } from "@/stores/productionSafetyStore";
import { assessProductionSql, productionContextForDatabase } from "@/lib/database/productionSafety";
import { ensureReadOnlyWriteAccess } from "@/lib/database/readOnlyWriteAccess";
import type { ConnectionConfig } from "@/types/database";
export interface ProductionSqlExecutionGuardOptions<T> {
@@ -11,6 +12,9 @@ export interface ProductionSqlExecutionGuardOptions<T> {
}
export async function executeWithProductionSqlGuard<T>(options: ProductionSqlExecutionGuardOptions<T>): Promise<T | undefined> {
if (!(await ensureReadOnlyWriteAccess({ connection: options.connection, sql: options.sql, source: options.source }))) {
return undefined;
}
const assessment = assessProductionSql(options.sql, options.connection, options.database);
if (assessment.active && assessment.isMutation) {
// Centralize production write confirmation so secondary tool surfaces cannot
@@ -41,6 +45,9 @@ export interface ProductionContextExecutionGuardOptions<T> {
* connection/database production scope rather than SQL risk classification.
*/
export async function executeWithProductionContextGuard<T>(options: ProductionContextExecutionGuardOptions<T>): Promise<T | undefined> {
if (!(await ensureReadOnlyWriteAccess({ connection: options.connection, sql: options.reviewText, source: options.source, treatAsMutation: true }))) {
return undefined;
}
const productionContext = productionContextForDatabase(options.connection, options.database);
if (productionContext.active) {
const confirmed = await useProductionSafetyStore().requestConfirmation({
@@ -0,0 +1,70 @@
import { getActivePinia } from "pinia";
import { useReadOnlyUnlockStore, type WriteUnlockDurationSecs } from "@/stores/readOnlyUnlockStore";
import { classifyRedisCommandSafety } from "@/lib/redis/redisCommandSafety";
import { classifySqlRisk, isSqlRiskMutation } from "@/lib/sql/sqlRisk";
import type { DatabaseType } from "@/types/database";
export type { WriteUnlockDurationSecs };
export const WRITE_UNLOCK_DURATIONS: WriteUnlockDurationSecs[] = [60, 300];
export function formatWriteUnlockRemaining(ms: number): string {
const totalSeconds = Math.max(0, Math.ceil(ms / 1000));
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
return `${minutes}:${String(seconds).padStart(2, "0")}`;
}
function unlockStoreOrNull() {
try {
if (!getActivePinia()) return null;
return useReadOnlyUnlockStore();
} catch {
return null;
}
}
export function isWriteUnlockActive(connectionId: string | undefined | null): boolean {
if (!connectionId) return false;
return unlockStoreOrNull()?.isUnlocked(connectionId) === true;
}
export function connectionIsEffectivelyReadOnly(connection?: { id?: string; read_only?: boolean } | null): boolean {
if (!connection?.read_only) return false;
return !isWriteUnlockActive(connection.id);
}
export function sqlLooksLikeMutation(sql: string | undefined, databaseType?: DatabaseType): boolean {
if (!sql?.trim()) return true;
if (databaseType === "redis") {
return sql.split("\n").some((line) => {
const command = line.trim();
return command.length > 0 && classifyRedisCommandSafety(command) !== "allowed";
});
}
return isSqlRiskMutation(classifySqlRisk(sql, { dialect: databaseType }).risk);
}
export interface ReadOnlyWriteAccessOptions {
connection?: { id?: string; name?: string; read_only?: boolean; db_type?: DatabaseType } | null;
sql?: string;
source?: string;
treatAsMutation?: boolean;
}
export async function ensureReadOnlyWriteAccess(options: ReadOnlyWriteAccessOptions): Promise<boolean> {
const connection = options.connection;
if (!connection?.read_only) return true;
if (!connection.id) return false;
const store = unlockStoreOrNull();
if (store?.isUnlocked(connection.id)) return true;
const isMutation = options.treatAsMutation === true || sqlLooksLikeMutation(options.sql, connection.db_type);
if (!isMutation) return true;
if (!store) return false;
return store.requestUnlock({
connectionId: connection.id,
connectionName: connection.name,
sql: options.sql,
source: options.source,
});
}