feat(safety): temporary write-unlock window for read-only connections
This commit is contained in:
1 parent
7933b7656f
commit
955558c81f
66 files changed
+1176
-124
No files matched your search
@@ -56,6 +56,9 @@ export const testConnectionWithInfo = forward("testConnectionWithInfo");
|
||||
export const connectDb = forward("connectDb");
|
||||
export const connectionDatabaseInfo = forward("connectionDatabaseInfo");
|
||||
export const saveConnectionDatabaseInfo = forward("saveConnectionDatabaseInfo");
|
||||
export const unlockConnectionWrites = forward("unlockConnectionWrites");
|
||||
export const lockConnectionWrites = forward("lockConnectionWrites");
|
||||
export const connectionWriteUnlockState = forward("connectionWriteUnlockState");
|
||||
export const connectionFinalProxyPort = forward("connectionFinalProxyPort");
|
||||
export const disconnectDb = forward("disconnectDb");
|
||||
export const sessionCredentialStatus = forward("sessionCredentialStatus");
|
||||
|
||||
@@ -399,6 +399,20 @@ export async function saveConnectionDatabaseInfo(connectionId: string, databaseI
|
||||
});
|
||||
}
|
||||
|
||||
export async function unlockConnectionWrites(connectionId: string, durationSecs: number): Promise<number> {
|
||||
const state = await post<{ remainingMs: number }>("/api/connection/write-unlock", { connectionId, durationSecs });
|
||||
return state.remainingMs;
|
||||
}
|
||||
|
||||
export async function lockConnectionWrites(connectionId: string): Promise<void> {
|
||||
return post("/api/connection/write-unlock/lock", { connectionId });
|
||||
}
|
||||
|
||||
export async function connectionWriteUnlockState(connectionId: string): Promise<number> {
|
||||
const state = await post<{ remainingMs: number }>("/api/connection/write-unlock/state", { connectionId });
|
||||
return state.remainingMs;
|
||||
}
|
||||
|
||||
export async function connectionFinalProxyPort(config: ConnectionConfig): Promise<number> {
|
||||
return post("/api/connection/final-proxy-port", { config });
|
||||
}
|
||||
|
||||
@@ -1023,6 +1023,24 @@ export async function saveConnectionDatabaseInfo(connectionId: string, databaseI
|
||||
});
|
||||
}
|
||||
|
||||
export interface WriteUnlockState {
|
||||
remainingMs: number;
|
||||
}
|
||||
|
||||
export async function unlockConnectionWrites(connectionId: string, durationSecs: number): Promise<number> {
|
||||
const state = await invokeBackend<WriteUnlockState>("unlock_connection_writes", { connectionId, durationSecs });
|
||||
return state.remainingMs;
|
||||
}
|
||||
|
||||
export async function lockConnectionWrites(connectionId: string): Promise<void> {
|
||||
return invokeBackend("lock_connection_writes", { connectionId });
|
||||
}
|
||||
|
||||
export async function connectionWriteUnlockState(connectionId: string): Promise<number> {
|
||||
const state = await invokeBackend<WriteUnlockState>("connection_write_unlock_state", { connectionId });
|
||||
return state.remainingMs;
|
||||
}
|
||||
|
||||
export async function connectionFinalProxyPort(config: ConnectionConfig): Promise<number> {
|
||||
return invokeBackend("connection_final_proxy_port", { config });
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { connectionIsEffectivelyReadOnly } from "@/lib/database/readOnlyWriteAccess";
|
||||
|
||||
type AgentTargetConnection = {
|
||||
id?: string;
|
||||
read_only?: boolean;
|
||||
transport_layers?: Array<{ enabled?: boolean }>;
|
||||
external_config?: unknown;
|
||||
@@ -32,7 +35,7 @@ export function consulAgentAddressesMatch(left: string, right: string): boolean
|
||||
}
|
||||
|
||||
export function consulAgentWriteTargetSafe(connection: AgentTargetConnection | undefined, identityNode: string | undefined): boolean {
|
||||
if (!connection || connection.read_only || connection.transport_layers?.some((layer) => layer.enabled !== false)) return false;
|
||||
if (!connection || connectionIsEffectivelyReadOnly(connection) || connection.transport_layers?.some((layer) => layer.enabled !== false)) return false;
|
||||
const external = connection.external_config;
|
||||
if (!external || typeof external !== "object" || Array.isArray(external)) return false;
|
||||
const config = external as Record<string, unknown>;
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { ConnectionConfig } from "@/types/database";
|
||||
import { connectionIsEffectivelyReadOnly } from "@/lib/database/readOnlyWriteAccess";
|
||||
|
||||
type MongoConnectionProfile = Pick<ConnectionConfig, "db_type" | "driver_profile" | "read_only">;
|
||||
type MongoConnectionProfile = Pick<ConnectionConfig, "db_type" | "driver_profile" | "read_only"> & Partial<Pick<ConnectionConfig, "id">>;
|
||||
|
||||
/** Accept historical Legacy profile spellings while persisted configs are normalized. */
|
||||
export function isMongoLegacyDriverProfile(driverProfile?: string): boolean {
|
||||
@@ -10,7 +11,7 @@ export function isMongoLegacyDriverProfile(driverProfile?: string): boolean {
|
||||
|
||||
/** Capabilities implemented by both the native driver and the Legacy Agent. */
|
||||
export function supportsMongoAllDriverMutations(connection?: MongoConnectionProfile): boolean {
|
||||
return connection?.db_type === "mongodb" && !connection.read_only;
|
||||
return connection?.db_type === "mongodb" && !connectionIsEffectivelyReadOnly(connection);
|
||||
}
|
||||
|
||||
/** MongoDB views do not own indexes; collections and time-series collections do. */
|
||||
|
||||
Reference in new issue
Block a user