feat(etcd): restrict key browsing and writes by auth permissions

This commit is contained in:
二丫讲梵 authored and GitHub committed 2026-09-04 20:24:02 +08:00
1 parent c9c36a8453
commit 259071c09b
32 files changed
+1404 -100

No files matched your search

@@ -0,0 +1,217 @@
import { createPinia, setActivePinia } from "pinia";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { EtcdAuthPermission, KvValue } from "@/lib/backend/api";
import type { ConnectionConfig, TreeNode } from "@/types/database";
const utf8 = (data: string): KvValue => ({ encoding: "utf8", data });
const readPermission: EtcdAuthPermission = { access: "read", key: utf8(""), rangeEnd: utf8("\0"), resource: "all" };
function installLocalStorage() {
const data = new Map<string, string>();
vi.stubGlobal("localStorage", {
getItem: vi.fn((key: string) => data.get(key) ?? null),
setItem: vi.fn((key: string, value: string) => data.set(key, value)),
removeItem: vi.fn((key: string) => data.delete(key)),
});
}
describe("connectionStore etcd access", () => {
beforeEach(() => {
vi.resetModules();
vi.unstubAllGlobals();
installLocalStorage();
setActivePinia(createPinia());
});
async function loadEtcdTree(roles: string[], permissions: EtcdAuthPermission[] = [readPermission], options: { connection?: Partial<ConnectionConfig>; authEnabled?: boolean; authUser?: string; loadRoot?: boolean } = {}) {
const connection = {
id: "etcd-reader",
name: "restricted etcd",
db_type: "etcd",
host: "127.0.0.1",
port: 2379,
username: "reader",
password: "secret",
database: "",
...options.connection,
} as ConnectionConfig;
const etcdAuthCall = vi.fn((_connectionId: string, operation: string, args: { user?: string; role?: string }) => {
if (operation === "user_get") return Promise.resolve({ user: args.user || options.authUser || "reader", roles, authEnabled: options.authEnabled ?? true });
if (operation === "role_get") return Promise.resolve({ role: args.role, permissions });
throw new Error(`Unexpected etcd auth operation: ${operation}`);
});
vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
vi.doMock("@/lib/backend/api", () => ({
checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
etcdAuthCall,
listInstalledAgents: vi.fn().mockResolvedValue([]),
loadSchemaCache: vi.fn().mockResolvedValue(null),
saveConnections: vi.fn().mockResolvedValue(undefined),
saveSchemaCache: vi.fn().mockResolvedValue(undefined),
saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
}));
const { useConnectionStore } = await import("@/stores/connectionStore");
const store = useConnectionStore();
const root: TreeNode = {
id: connection.id,
label: connection.name,
type: "connection",
connectionId: connection.id,
isExpanded: false,
children: [],
};
store.connections = [connection];
store.treeNodes = [root];
store.connectedIds.add(connection.id);
if (options.loadRoot !== false) await store.loadEtcdRoot(connection.id);
return { root, etcdAuthCall, store };
}
it("hides management views for a regular etcd user", async () => {
const { root, etcdAuthCall, store } = await loadEtcdTree(["reader-role"]);
expect(etcdAuthCall).toHaveBeenCalledWith("etcd-reader", "user_get", {});
expect(etcdAuthCall).toHaveBeenCalledWith("etcd-reader", "role_get", { role: "reader-role" });
expect(root.children?.map((child) => child.type)).toEqual(["etcd-root"]);
expect(store.getEtcdAccessCapabilities("etcd-reader")).toEqual({ admin: false, writable: false, writePermissions: [] });
});
it("shows management views only for the root role", async () => {
const { root } = await loadEtcdTree(["reader-role", "root"]);
expect(root.children?.map((child) => child.type)).toEqual(["etcd-root", "etcd-access-control", "etcd-dashboard"]);
});
it("keeps Key mutations available to a non-admin role with write access", async () => {
const writePermission: EtcdAuthPermission = { access: "readwrite", key: utf8("/editable/"), rangeEnd: utf8("/editable0"), resource: "prefix" };
const { root, store } = await loadEtcdTree(["key-writer"], [writePermission]);
expect(root.children?.map((child) => child.type)).toEqual(["etcd-root"]);
expect(store.getEtcdAccessCapabilities("etcd-reader")).toEqual({ admin: false, writable: true, writePermissions: [writePermission] });
expect(store.canWriteEtcdKey("etcd-reader", "/editable/key")).toBe(true);
expect(store.canWriteEtcdKey("etcd-reader", "/readonly/key")).toBe(false);
});
it("loads capabilities without requiring the sidebar connection to be expanded", async () => {
const writePermission: EtcdAuthPermission = { access: "readwrite", key: utf8("/editable/"), rangeEnd: utf8("/editable0"), resource: "prefix" };
const { root, store } = await loadEtcdTree(["key-writer"], [writePermission], { loadRoot: false });
expect(root.isExpanded).toBe(false);
expect(store.getEtcdAccessCapabilities("etcd-reader")).toEqual({ admin: false, writable: false, writePermissions: [] });
await store.ensureEtcdAccessCapabilities("etcd-reader", { force: true, verifyHealth: false });
expect(root.isExpanded).toBe(false);
expect(store.canWriteEtcdKey("etcd-reader", "/editable/key")).toBe(true);
});
it("preserves confirmed write permissions when a forced refresh fails transiently", async () => {
const writePermission: EtcdAuthPermission = { access: "readwrite", key: utf8("/editable/"), rangeEnd: utf8("/editable0"), resource: "prefix" };
const { etcdAuthCall, store } = await loadEtcdTree(["key-writer"], [writePermission]);
etcdAuthCall.mockRejectedValueOnce(new Error("temporary auth timeout"));
await store.ensureEtcdAccessCapabilities("etcd-reader", { force: true, verifyHealth: false });
expect(store.getEtcdAccessCapabilities("etcd-reader")).toEqual({ admin: false, writable: true, writePermissions: [writePermission] });
expect(store.canWriteEtcdKey("etcd-reader", "/editable/key")).toBe(true);
});
it("preserves a confirmed root role when a forced refresh fails transiently", async () => {
const { etcdAuthCall, store } = await loadEtcdTree(["root"]);
etcdAuthCall.mockRejectedValueOnce(new Error("temporary auth timeout"));
await store.ensureEtcdAccessCapabilities("etcd-reader", { force: true, verifyHealth: false });
expect(store.getEtcdAccessCapabilities("etcd-reader")).toEqual({ admin: true, writable: true, writePermissions: null });
});
it("fails closed when initial capability discovery fails", async () => {
const { etcdAuthCall, store } = await loadEtcdTree(["key-writer"], [readPermission], { loadRoot: false });
etcdAuthCall.mockRejectedValueOnce(new Error("temporary auth timeout"));
await store.ensureEtcdAccessCapabilities("etcd-reader", { force: true, verifyHealth: false });
expect(store.getEtcdAccessCapabilities("etcd-reader")).toEqual({ admin: false, writable: false, writePermissions: [] });
});
it("does not let a read grant inherit write access from another range", async () => {
const permissions: EtcdAuthPermission[] = [
{ access: "read", key: utf8("/readonly/"), rangeEnd: utf8("/readonly0"), resource: "prefix" },
{ access: "readwrite", key: utf8("/editable/"), rangeEnd: utf8("/editable0"), resource: "prefix" },
];
const { store } = await loadEtcdTree(["mixed-role"], permissions);
expect(store.canWriteEtcdKey("etcd-reader", "/readonly/key")).toBe(false);
expect(store.canWriteEtcdKey("etcd-reader", "/editable/key")).toBe(true);
});
it("uses the agent's certificate identity for a restricted TLS user", async () => {
const { root, etcdAuthCall, store } = await loadEtcdTree(["cert-reader-role"], [readPermission], {
connection: { username: "", password: "", client_cert_path: "/tmp/cert.pem", client_key_path: "/tmp/key.pem" },
authUser: "cert-reader",
});
expect(etcdAuthCall).toHaveBeenCalledWith("etcd-reader", "user_get", {});
expect(root.children?.map((child) => child.type)).toEqual(["etcd-root"]);
expect(store.getEtcdAccessCapabilities("etcd-reader")).toEqual({ admin: false, writable: false, writePermissions: [] });
});
it("keeps certificate connections unrestricted when server auth is disabled", async () => {
const { root } = await loadEtcdTree([], [readPermission], {
connection: { username: "", password: "", client_cert_path: "/tmp/cert.pem", client_key_path: "/tmp/key.pem" },
authEnabled: false,
authUser: "transport-only-cert",
});
expect(root.children?.map((child) => child.type)).toEqual(["etcd-root", "etcd-access-control", "etcd-dashboard"]);
});
it("keeps anonymous connections unrestricted when server auth is disabled", async () => {
const { root, etcdAuthCall, store } = await loadEtcdTree([], [readPermission], {
connection: { username: "", password: "", client_cert_path: "", client_key_path: "" },
authEnabled: false,
authUser: "",
});
expect(etcdAuthCall).toHaveBeenCalledWith("etcd-reader", "user_get", {});
expect(root.children?.map((child) => child.type)).toEqual(["etcd-root", "etcd-access-control", "etcd-dashboard"]);
expect(store.getEtcdAccessCapabilities("etcd-reader")).toEqual({ admin: true, writable: true, writePermissions: null });
});
it("queries the configured user when resolving etcd v2 capabilities", async () => {
const writePermission: EtcdAuthPermission = { access: "write", key: utf8("/editable/"), rangeEnd: utf8("/editable0"), resource: "prefix" };
const { root, etcdAuthCall, store } = await loadEtcdTree(["v2-writer"], [writePermission], {
connection: { driver_profile: "etcd-v2" },
});
expect(etcdAuthCall).toHaveBeenCalledWith("etcd-reader", "user_get", { user: "reader" });
expect(root.children?.map((child) => child.type)).toEqual(["etcd-root"]);
expect(store.canWriteEtcdKey("etcd-reader", "/editable/key")).toBe(true);
expect(store.canWriteEtcdKey("etcd-reader", "/readonly/key")).toBe(false);
});
it("keeps anonymous etcd v2 Key operations available without probing an empty user", async () => {
const { root, etcdAuthCall, store } = await loadEtcdTree([], [readPermission], {
connection: { driver_profile: "etcd-v2", username: "", password: "" },
});
expect(etcdAuthCall).not.toHaveBeenCalled();
expect(root.children?.map((child) => child.type)).toEqual(["etcd-root"]);
expect(store.getEtcdAccessCapabilities("etcd-reader")).toEqual({ admin: false, writable: true, writePermissions: null });
});
it("preserves etcd v2 Key operations when auth capability discovery is unavailable", async () => {
const { etcdAuthCall, store } = await loadEtcdTree(["v2-writer"], [readPermission], {
connection: { driver_profile: "etcd-v2" },
loadRoot: false,
});
etcdAuthCall.mockRejectedValueOnce(new Error("v2 auth endpoint unavailable"));
await store.ensureEtcdAccessCapabilities("etcd-reader", { force: true, verifyHealth: false });
expect(store.getEtcdAccessCapabilities("etcd-reader")).toEqual({ admin: false, writable: true, writePermissions: null });
});
});
+153 -35
View File
@@ -140,6 +140,7 @@ import { isMongoLegacyDriverProfile } from "@/lib/mongo/mongoCapabilities";
import { mongoCollectionKindFromNode, toMongoCollectionKind, visibleMongoCollections } from "@/lib/sidebar/mongoCollectionMutation";
import { completionSchemasFromTree, completionTablesFromTree } from "@/lib/metadata/completionTreeIndex";
import { kvRootNodeLabel } from "@/lib/kv/kvRootPresentation";
import { etcdPermissionsAllowKey } from "@/lib/etcd/keyPermissions";
import { REDIS_SCAN_PAGE_SIZE_DEFAULT } from "@/lib/redis/redisKeyPattern";
import { normalizeRedisDatabaseAliases, redisDatabaseAlias, redisDatabaseLabel } from "@/lib/redis/redisDatabaseAlias";
import { normalizeRedisKeyTemplates } from "@/lib/redis/redisKeyTemplates";
@@ -195,6 +196,19 @@ const XUGU_TABLE_CHILD_METADATA_AGENT_VERSION = "0.1.23";
const SUPERSEDED_CONNECTION_ATTEMPT_MESSAGE = "Connection attempt was superseded by a newer attempt";
const SHARDINGSPHERE_PROXY_VERSION_MARKER = "shardingsphere-proxy";
export interface EtcdAccessCapabilities {
/** May access cluster-wide administration APIs such as status and leases. */
admin: boolean;
/** Has at least one etcd role that permits writes to a Key range. */
writable: boolean;
/** Null means unrestricted; otherwise writes are limited to these etcd ranges. */
writePermissions: api.EtcdAuthPermission[] | null;
}
const unrestrictedEtcdAccess: EtcdAccessCapabilities = { admin: true, writable: true, writePermissions: null };
const restrictedEtcdAccess: EtcdAccessCapabilities = { admin: false, writable: false, writePermissions: [] };
const fallbackEtcdV2Access: EtcdAccessCapabilities = { admin: false, writable: true, writePermissions: null };
function usesShardingSphereLogicalTables(databaseInfo: DatabaseConnectionInfo | undefined): boolean {
return databaseInfo?.productVersion?.toLowerCase().includes(SHARDINGSPHERE_PROXY_VERSION_MARKER) === true;
}
@@ -441,6 +455,9 @@ export const useConnectionStore = defineStore("connection", () => {
const activePinnedTreeNodeReorderKey = ref<string | null>(null);
let pinnedTreeNodePersistQueue: Promise<void> = Promise.resolve();
const connectedIds = ref<Set<string>>(new Set());
const etcdAccessCapabilities = ref<Record<string, EtcdAccessCapabilities>>({});
const etcdAccessCapabilityGenerations = new Map<string, number>();
const etcdAccessCapabilityLoads = new Map<string, Promise<EtcdAccessCapabilities>>();
const identifierQuotes = ref<Record<string, string>>({});
const lastConnectionHealthCheckAt = ref<Record<string, number>>({});
const agentDrivers = ref<AgentDriverInstallState[]>([]);
@@ -657,6 +674,99 @@ export const useConnectionStore = defineStore("connection", () => {
return configById.value.get(connectionId);
}
function getEtcdAccessCapabilities(connectionId: string): EtcdAccessCapabilities {
const config = getConfig(connectionId);
if (config?.db_type !== "etcd") return unrestrictedEtcdAccess;
const username = config.username?.trim() || "";
// Only an explicitly configured root user can be trusted before probing
// the server. Anonymous and certificate connections may still target an
// auth-enabled cluster, so keep privileged controls hidden until the
// agent reports the effective identity and authentication status.
if (username === "root") return unrestrictedEtcdAccess;
return etcdAccessCapabilities.value[connectionId] ?? (config.driver_profile === "etcd-v2" ? fallbackEtcdV2Access : restrictedEtcdAccess);
}
function canWriteEtcdKey(connectionId: string, key: string, keyBytes?: api.KvValue | null): boolean {
const access = getEtcdAccessCapabilities(connectionId);
if (!access.writable) return false;
if (access.writePermissions === null) return true;
return etcdPermissionsAllowKey(access.writePermissions, keyBytes ?? { encoding: "utf8", data: key });
}
async function resolveEtcdAccessCapabilities(connectionId: string, config: ConnectionConfig | undefined): Promise<EtcdAccessCapabilities> {
const username = config?.username?.trim() || "";
if (username === "root") return unrestrictedEtcdAccess;
// The v2 auth API cannot resolve the identity behind the active HTTP
// connection. Query an explicitly configured user, while anonymous v2
// connections retain their historical Key access and rely on the server
// as the authorization boundary.
if (config?.driver_profile === "etcd-v2" && !username) return fallbackEtcdV2Access;
// An empty user asks the agent for the authenticated identity. This also
// covers client-certificate CN authentication without duplicating X.509
// parsing in the UI.
const userParams = config?.driver_profile === "etcd-v2" ? { user: username } : {};
const user = await api.etcdAuthCall<api.EtcdAuthUserDetail>(connectionId, "user_get", userParams);
if (user.authEnabled === false) return unrestrictedEtcdAccess;
if (user.roles.includes("root")) return unrestrictedEtcdAccess;
const roles = await Promise.all(user.roles.map((role) => api.etcdAuthCall<api.EtcdAuthRoleDetail>(connectionId, "role_get", { role })));
const writePermissions = roles.flatMap((role) => role.permissions.filter((permission) => permission.access === "write" || permission.access === "readwrite"));
return {
admin: false,
writable: writePermissions.length > 0,
writePermissions,
};
}
async function ensureEtcdAccessCapabilities(connectionId: string, options: { force?: boolean; verifyHealth?: boolean } = {}): Promise<EtcdAccessCapabilities> {
const config = getConfig(connectionId);
if (config?.db_type !== "etcd") return unrestrictedEtcdAccess;
const cached = etcdAccessCapabilities.value[connectionId];
if (cached && !options.force) return cached;
const existing = etcdAccessCapabilityLoads.get(connectionId);
if (existing) return existing;
const load = (async () => {
await ensureConnected(connectionId, { verifyHealth: options.verifyHealth ?? false });
const currentConfig = getConfig(connectionId);
if (currentConfig?.db_type !== "etcd") return unrestrictedEtcdAccess;
const generation = etcdAccessCapabilityGenerations.get(connectionId) ?? 0;
const configFingerprint = connectionConfigFingerprint(currentConfig);
let access: EtcdAccessCapabilities;
try {
access = await resolveEtcdAccessCapabilities(connectionId, currentConfig);
} catch {
// Initial v3 discovery fails closed. Once a capability snapshot has
// been confirmed, however, a transient Auth RPC failure must not
// overwrite it and make controls flicker between states.
// The v2 API cannot discover an implicit current user, so preserve its
// pre-capability behavior on discovery errors and let etcd authorize
// each Key mutation. Administrative views remain hidden.
access = etcdAccessCapabilities.value[connectionId] ?? (currentConfig.driver_profile === "etcd-v2" ? fallbackEtcdV2Access : restrictedEtcdAccess);
}
if (generation === (etcdAccessCapabilityGenerations.get(connectionId) ?? 0) && connectedIds.value.has(connectionId) && connectionConfigFingerprint(getConfig(connectionId) ?? currentConfig) === configFingerprint) {
etcdAccessCapabilities.value = { ...etcdAccessCapabilities.value, [connectionId]: access };
return access;
}
return getEtcdAccessCapabilities(connectionId);
})();
etcdAccessCapabilityLoads.set(connectionId, load);
try {
return await load;
} finally {
if (etcdAccessCapabilityLoads.get(connectionId) === load) etcdAccessCapabilityLoads.delete(connectionId);
}
}
function clearEtcdAccessCapabilities(connectionId: string) {
etcdAccessCapabilityGenerations.set(connectionId, (etcdAccessCapabilityGenerations.get(connectionId) ?? 0) + 1);
etcdAccessCapabilityLoads.delete(connectionId);
if (connectionId in etcdAccessCapabilities.value) {
const next = { ...etcdAccessCapabilities.value };
delete next[connectionId];
etcdAccessCapabilities.value = next;
}
}
function connectionIdentifierQuote(connectionId?: string): string | undefined {
if (!connectionId) return undefined;
const override = gaussdbIdentifierQuoteOverride(getConfig(connectionId));
@@ -1099,6 +1209,7 @@ export const useConnectionStore = defineStore("connection", () => {
function markConnectionLost(connectionId: string, error: unknown) {
connectedIds.value.delete(connectionId);
clearEtcdAccessCapabilities(connectionId);
clearSidebarStorageCaches(connectionId);
clearPrimaryVisibleObjectNames(connectionId);
clearConnectionIdentifierQuote(connectionId);
@@ -3248,6 +3359,7 @@ export const useConnectionStore = defineStore("connection", () => {
for (const id of removedIds) {
clearConnectionError(id);
connectionErrorRevisions.delete(id);
clearEtcdAccessCapabilities(id);
connectedIds.value.delete(id);
clearSidebarStorageCaches(id);
clearPrimaryVisibleObjectNames(id);
@@ -3288,6 +3400,7 @@ export const useConnectionStore = defineStore("connection", () => {
syncTimeoutInheritanceBackup();
rebuildTreeNodes();
if (!runtimeConfigChanged) return;
clearEtcdAccessCapabilities(config.id);
clearPrimaryVisibleObjectNames(config.id);
connectedIds.value.delete(config.id);
clearSidebarStorageCaches(config.id);
@@ -3819,6 +3932,7 @@ export const useConnectionStore = defineStore("connection", () => {
if (!cancelled) return false;
clearConnectionError(connectionId);
connectedIds.value.delete(connectionId);
clearEtcdAccessCapabilities(connectionId);
clearSidebarStorageCaches(connectionId);
clearPrimaryVisibleObjectNames(connectionId);
clearConnectionIdentifierQuote(connectionId);
@@ -3839,6 +3953,7 @@ export const useConnectionStore = defineStore("connection", () => {
cancelLocalConnectionAttempt(connectionId);
connectedIds.value.delete(connectionId);
clearEtcdAccessCapabilities(connectionId);
clearSidebarStorageCaches(connectionId);
clearPrimaryVisibleObjectNames(connectionId);
clearConnectionIdentifierQuote(connectionId);
@@ -3963,6 +4078,7 @@ export const useConnectionStore = defineStore("connection", () => {
cancelObjectMetadataLoadsForConnection(connectionId);
clearMetadataRuntimeCacheForConnection(connectionId);
connectedIds.value.delete(connectionId);
clearEtcdAccessCapabilities(connectionId);
clearPrimaryVisibleObjectNames(connectionId);
clearConnectionHealthCheck(connectionId);
if (activeConnectionId.value === connectionId) activeConnectionId.value = null;
@@ -4498,42 +4614,41 @@ export const useConnectionStore = defineStore("connection", () => {
load = reclaimTreeNodeLoad(load, node);
const targetNode = treeNodeLoadTarget(load);
if (!targetNode) return;
setChildren(
targetNode,
withSavedSqlRoot(
const etcdAccess = await ensureEtcdAccessCapabilities(connectionId, { force: true, verifyHealth: false });
const children: TreeNode[] = [
{
id: `${connectionId}:etcd`,
label: kvRootNodeLabel("etcd"),
type: "etcd-root" as const,
connectionId,
[
{
id: `${connectionId}:etcd`,
label: kvRootNodeLabel("etcd"),
type: "etcd-root" as const,
connectionId,
database: "",
isExpanded: false,
children: [],
},
{
id: `${connectionId}:etcd-access-control`,
label: "用户和角色",
type: "etcd-access-control" as const,
connectionId,
database: "",
isExpanded: false,
children: [],
},
{
id: `${connectionId}:etcd-dashboard`,
label: "服务仪表盘",
type: "etcd-dashboard" as const,
connectionId,
database: "",
isExpanded: false,
children: [],
},
],
targetNode,
),
);
database: "",
isExpanded: false,
children: [],
},
];
if (etcdAccess.admin) {
children.push(
{
id: `${connectionId}:etcd-access-control`,
label: "用户和角色",
type: "etcd-access-control" as const,
connectionId,
database: "",
isExpanded: false,
children: [],
},
{
id: `${connectionId}:etcd-dashboard`,
label: "服务仪表盘",
type: "etcd-dashboard" as const,
connectionId,
database: "",
isExpanded: false,
children: [],
},
);
}
setChildren(targetNode, withSavedSqlRoot(connectionId, children, targetNode));
targetNode.isExpanded = true;
} catch (e) {
recordMetadataLoadError(connectionId, e, load);
@@ -8894,6 +9009,9 @@ export const useConnectionStore = defineStore("connection", () => {
connectionGroupOptions,
selectedConnectionGroupId,
getConfig,
getEtcdAccessCapabilities,
ensureEtcdAccessCapabilities,
canWriteEtcdKey,
connectionIdentifierQuote,
isTreeNodePinned,
orderByPinnedTreeNodes,