Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

fix(agent-vault): address review on product-scoped variables

Scott Wilson6811a3fc3935
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.ts
index bc5526ea44..f9f140dff5 100644
--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts
+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts
@@ -1118,7 +1118,7 @@ describe("Agent Vault V1 Router", async () => {
expect(renamed.statusCode).toBe(200);
expect(JSON.parse(renamed.payload).variable).toMatchObject({
key: "NEW_NAME",
- usedBy: [{ id: serviceId, name: "echo", accessBundleId: bundle.id, accessBundleName: bundle.name }]
+ usedByServices: [{ id: serviceId, name: "echo", accessBundleId: bundle.id, accessBundleName: bundle.name }]
});
const detail = JSON.parse((await inject("GET", `/api/v1/agent-vault/access-bundles/${bundle.id}`)).payload) as {
@@ -1255,7 +1255,7 @@ describe("Agent Vault V1 Router", async () => {
expect(listed.statusCode).toBe(200);
expect(listed.payload).not.toContain("hidden_value");
const [listedVariable] = JSON.parse(listed.payload).variables;
- expect(listedVariable).toMatchObject({ key: "HIDDEN", usedBy: [] });
+ expect(listedVariable).toMatchObject({ key: "HIDDEN", usedByServices: [] });
expect(listedVariable).not.toHaveProperty("accessBundleId");
expect(listedVariable).not.toHaveProperty("value");
expect(listedVariable).not.toHaveProperty("isSecret");
@@ -1336,7 +1336,7 @@ describe("Agent Vault V1 Router", async () => {
expect(await list("limit=2&offset=2")).toEqual({ keys: ["GAMMA_KEY"], totalCount: 3 });
expect(await list("search=token")).toEqual({ keys: ["ALPHA_TOKEN", "BETA_TOKEN"], totalCount: 2 });
expect(await list("search=%25")).toEqual({ keys: [], totalCount: 0 });
- expect(await list("orderBy=usedBy&orderDirection=desc")).toEqual({
+ expect(await list("orderBy=serviceCount&orderDirection=desc")).toEqual({
keys: ["GAMMA_KEY", "BETA_TOKEN", "ALPHA_TOKEN"],
totalCount: 3
});
@@ -1349,6 +1349,27 @@ describe("Agent Vault V1 Router", async () => {
});
expect(await list("keys=TOKEN")).toEqual({ keys: [], totalCount: 0 });
expect((await inject("GET", `${variablesUrl}?keys=lower_case`)).statusCode).toBe(422);
+ // A trailing comma's empty entry is dropped rather than refused.
+ expect(await list("keys=GAMMA_KEY,")).toEqual({ keys: ["GAMMA_KEY"], totalCount: 1 });
+ });
+
+ test("a lookup by keys returns every key that exists, past the default page size", async () => {
+ const keys = Array.from({ length: 25 }, (_, index) => `LOOKUP_KEY_${String(index).padStart(2, "0")}`);
+ await Promise.all(keys.map((key) => createVariable({ key, value: "v" })));
+
+ const res = await inject("GET", `${variablesUrl}?keys=${keys.join(",")}`);
+ expect(res.statusCode).toBe(200);
+ const body = JSON.parse(res.payload) as { variables: { key: string }[]; totalCount: number };
+ expect(body.totalCount).toBe(25);
+ expect(body.variables.map((variable) => variable.key)).toEqual(keys);
+
+ // An explicit limit still caps it.
+ const capped = JSON.parse((await inject("GET", `${variablesUrl}?keys=${keys.join(",")}&limit=5`)).payload) as {
+ variables: unknown[];
+ totalCount: number;
+ };
+ expect(capped).toMatchObject({ totalCount: 25 });
+ expect(capped.variables).toHaveLength(5);
});
test("services in different bundles share a variable, and each resolves it", async () => {
@@ -1371,9 +1392,9 @@ describe("Agent Vault V1 Router", async () => {
await expectReferencesMatchSealedText(second.id);
const listed = JSON.parse((await inject("GET", variablesUrl)).payload) as {
- variables: { id: string; usedBy: Record<string, string>[] }[];
+ variables: { id: string; usedByServices: Record<string, string>[] }[];
};
- expect(listed.variables.find((entry) => entry.id === variable.id)?.usedBy).toEqual([
+ expect(listed.variables.find((entry) => entry.id === variable.id)?.usedByServices).toEqual([
{
id: firstService.id,
name: "shared-one",
@@ -1682,9 +1703,11 @@ describe("Agent Vault V1 Router", async () => {
);
const listed = JSON.parse((await inject("GET", variablesUrl)).payload) as {
- variables: { id: string; usedBy: unknown[] }[];
+ variables: { id: string; usedByServices: unknown[] }[];
};
- expect(listed.variables).toEqual([expect.objectContaining({ id: variable.id, key: "TOKEN", usedBy: [] })]);
+ expect(listed.variables).toEqual([
+ expect.objectContaining({ id: variable.id, key: "TOKEN", usedByServices: [] })
+ ]);
expect((await inject("DELETE", `${variablesUrl}/${variable.id}`)).statusCode).toBe(200);
});
diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts
index 08c56fa56f..2b00197177 100644
--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts
+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts
@@ -251,16 +251,16 @@ export const AgentVaultVariableValueSchema = z
export const AgentVaultVariableSchema = z.object({
id: z.string().uuid().describe(AGENT_VAULT.VARIABLE.variableId),
key: z.string().describe(AGENT_VAULT.VARIABLE.key),
- usedBy: z
+ usedByServices: z
.object({
- id: z.string().uuid().describe(AGENT_VAULT.VARIABLE.usedById),
- name: z.string().describe(AGENT_VAULT.VARIABLE.usedByName),
- hostPattern: z.string().describe(AGENT_VAULT.VARIABLE.usedByHostPattern),
- accessBundleId: z.string().uuid().describe(AGENT_VAULT.VARIABLE.usedByAccessBundleId),
- accessBundleName: z.string().describe(AGENT_VAULT.VARIABLE.usedByAccessBundleName)
+ id: z.string().uuid().describe(AGENT_VAULT.VARIABLE.usedByServiceId),
+ name: z.string().describe(AGENT_VAULT.VARIABLE.usedByServiceName),
+ hostPattern: z.string().describe(AGENT_VAULT.VARIABLE.usedByServiceHostPattern),
+ accessBundleId: z.string().uuid().describe(AGENT_VAULT.VARIABLE.usedByServiceAccessBundleId),
+ accessBundleName: z.string().describe(AGENT_VAULT.VARIABLE.usedByServiceAccessBundleName)
})
.array()
- .describe(AGENT_VAULT.VARIABLE.usedBy),
+ .describe(AGENT_VAULT.VARIABLE.usedByServices),
createdAt: z.date().describe(AGENT_VAULT.VARIABLE.createdAt),
updatedAt: z.date().describe(AGENT_VAULT.VARIABLE.updatedAt)
});
diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-variable-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-variable-router.ts
index 548f3f9387..4fe6c40ef2 100644
--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-variable-router.ts
+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-variable-router.ts
@@ -32,16 +32,19 @@ export const registerAgentVaultVariableRouter = async (server: FastifyZodProvide
description: "List the variables in Agent Vault",
tags: [ApiDocsTags.AgentVaultVariables],
querystring: z.object({
- orderBy: z.enum(["key", "usedBy"]).default("key").describe(AGENT_VAULT.VARIABLE.orderBy),
+ orderBy: z.enum(["key", "serviceCount"]).default("key").describe(AGENT_VAULT.VARIABLE.orderBy),
orderDirection: z.enum(["asc", "desc"]).default("asc").describe(AGENT_VAULT.VARIABLE.orderDirection),
keys: z
.string()
.max(AGENT_VAULT_LIST_MAX_KEYS * (AGENT_VAULT_VARIABLE_KEY_MAX_LENGTH + 1))
- .transform((val) => [...new Set(val.split(",").map((key) => key.trim()))])
+ // Empty entries, as from a trailing comma, are dropped rather than refused.
+ .transform((val) => [...new Set(val.split(",").map((key) => key.trim()))].filter(Boolean))
.pipe(AgentVaultVariableKeySchema.array().min(1).max(AGENT_VAULT_LIST_MAX_KEYS))
.optional()
.describe(AGENT_VAULT.VARIABLE.keys),
- ...agentVaultListQuery(AGENT_VAULT.VARIABLE)
+ ...agentVaultListQuery(AGENT_VAULT.VARIABLE),
+ // No default here: the service defaults it to the number of keys for a lookup, and to 20 otherwise.
+ limit: z.coerce.number().int().min(1).max(100).optional().describe(AGENT_VAULT.VARIABLE.limit)
}),
response: {
200: z.object({
@@ -154,7 +157,7 @@ export const registerAgentVaultVariableRouter = async (server: FastifyZodProvide
variableId: variable.id,
keyChanged: previousKey !== variable.key,
valueReplaced: req.body.value !== undefined,
- usedByServiceCount: variable.usedBy.length
+ usedByServiceCount: variable.usedByServices.length
}
});
diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts
index 8bdc58b750..aa8ce81636 100644
--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts
+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts
@@ -558,8 +558,8 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
)
);
- // The reference is stored by id, so a variable deleted between the key lookup and the commit only shows
- // up at commit, as the deferred foreign key.
+ // The reference is stored by id, so a variable deleted after the key lookup is caught when the save locks the
+ // rows it references (insertReferenceRows). The deferred foreign key is only the backstop.
const VARIABLE_DELETED_DURING_SAVE_MESSAGE =
"A variable this service uses was deleted while it was being saved. Check its variable references and save again.";
diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-variable-reference-dal.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-variable-reference-dal.ts
index 6776c973b0..11128156ae 100644
--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-variable-reference-dal.ts
+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-variable-reference-dal.ts
@@ -35,22 +35,5 @@ export const agentVaultServiceVariableReferenceDALFactory = (db: TDbClient) => {
}
};
- // Reads the primary even without a tx, so a service saved a moment ago shows as using its variables.
- const findByVariableIds = async (
- variableIds: string[],
- tx?: Knex
- ): Promise<TAgentVaultServiceVariableReferences[]> => {
- if (!variableIds.length) return [];
- try {
- return (await (tx || db)(TableName.AgentVaultServiceVariableReference)
- .whereIn("variableId", variableIds)
- .select(
- selectAllTableCols(TableName.AgentVaultServiceVariableReference)
- )) as TAgentVaultServiceVariableReferences[];
- } catch (error) {
- throw new DatabaseError({ error, name: "Find agent vault variable references by variable" });
- }
- };
-
- return { ...orm, findByServiceIds, findByVariableIds };
+ return { ...orm, findByServiceIds };
};
diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.ts
index f635534972..9728fc4129 100644
--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.ts
+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.ts
@@ -9,7 +9,6 @@ export type TAgentVaultResolveDALFactory = ReturnType<typeof agentVaultResolveDA
export type TResolveServiceRow = {
id: string;
name: string;
- accessBundleId: string;
accessBundleName: string;
hostPattern: string;
credentialType: string;
@@ -70,7 +69,6 @@ export const agentVaultResolveDALFactory = (db: TDbClient) => {
db.ref("encryptedCredential").withSchema(TableName.AgentVaultService),
db.ref("allowedMethods").withSchema(TableName.AgentVaultService),
db.ref("allowedPathPrefixes").withSchema(TableName.AgentVaultService),
- db.ref("accessBundleId").withSchema(TableName.AgentVaultService),
// Resolve only reaches live bundles, so the current name is always the truthful one here.
db.ref("name").withSchema(TableName.AgentVaultAccessBundle).as("accessBundleName"),
db.ref("position").withSchema(TableName.AgentVaultSessionAccessBundle)
diff --git a/backend/src/ee/services/agent-vault-variable/agent-vault-variable-dal.ts b/backend/src/ee/services/agent-vault-variable/agent-vault-variable-dal.ts
index cb778439b8..a6dfe953e8 100644
--- a/backend/src/ee/services/agent-vault-variable/agent-vault-variable-dal.ts
+++ b/backend/src/ee/services/agent-vault-variable/agent-vault-variable-dal.ts
@@ -11,7 +11,7 @@ export type TAgentVaultVariableDALFactory = ReturnType<typeof agentVaultVariable
// accessBundleId is left over from bundle-scoped variables and no longer read, so it stays off every row.
export type TAgentVaultVariable = Omit<TAgentVaultVariables, "accessBundleId">;
-export type TAgentVaultVariableOrderBy = "key" | "usedBy";
+export type TAgentVaultVariableOrderBy = "key" | "serviceCount";
export type TFindAgentVaultVariablesDTO = {
projectId: string;
@@ -25,7 +25,7 @@ export type TFindAgentVaultVariablesDTO = {
export type TAgentVaultVariableValueRow = Pick<TAgentVaultVariables, "id" | "encryptedValue">;
-export type TAgentVaultVariableUser = {
+export type TAgentVaultServiceUsingVariable = {
variableId: string;
serviceId: string;
serviceName: string;
@@ -41,8 +41,8 @@ export const agentVaultVariableDALFactory = (db: TDbClient) => {
const columns = VARIABLE_COLUMNS.map((column) => `${TableName.AgentVaultVariable}.${column}`);
- // Reads the primary even without a tx, so a variable created a moment ago is always listed. usedBy counts the
- // services that use a variable, each once however many of its fields do.
+ // Reads the primary even without a tx, so a variable created a moment ago is always listed. serviceCount counts
+ // the services that use a variable, each once however many of its fields do.
const findForList = async (
{ projectId, search, keys, orderBy, orderDirection, limit, offset }: TFindAgentVaultVariablesDTO,
tx?: Knex
@@ -66,7 +66,7 @@ export const agentVaultVariableDALFactory = (db: TDbClient) => {
const pageQuery = applyFilters(conn(TableName.AgentVaultVariable)).limit(limit).offset(offset).select(columns);
- if (orderBy === "usedBy") {
+ if (orderBy === "serviceCount") {
// Counted over this project's variables only; the references table holds every org's.
const usageCounts = conn(TableName.AgentVaultServiceVariableReference)
.join(
@@ -168,7 +168,7 @@ export const agentVaultVariableDALFactory = (db: TDbClient) => {
};
// Reads the primary even without a tx, so a service saved a moment ago shows as using its variables.
- const findUsers = async (variableIds: string[], tx?: Knex): Promise<TAgentVaultVariableUser[]> => {
+ const findServicesUsing = async (variableIds: string[], tx?: Knex): Promise<TAgentVaultServiceUsingVariable[]> => {
if (!variableIds.length) return [];
try {
return (await (tx || db)(TableName.AgentVaultServiceVariableReference)
@@ -194,9 +194,9 @@ export const agentVaultVariableDALFactory = (db: TDbClient) => {
.orderBy([
{ column: "accessBundleName", order: "asc" },
{ column: "serviceName", order: "asc" }
- ])) as TAgentVaultVariableUser[];
+ ])) as TAgentVaultServiceUsingVariable[];
} catch (error) {
- throw new DatabaseError({ error, name: "Find agent vault variable users" });
+ throw new DatabaseError({ error, name: "Find services using agent vault variables" });
}
};
@@ -234,7 +234,7 @@ export const agentVaultVariableDALFactory = (db: TDbClient) => {
findByKeyInProject,
lockByIdInProject,
lockForReference,
- findUsers,
+ findServicesUsing,
findValuesForResolve
};
};
diff --git a/backend/src/ee/services/agent-vault-variable/agent-vault-variable-service.ts b/backend/src/ee/services/agent-vault-variable/agent-vault-variable-service.ts
index 82b9aca58e..cf8c7b695f 100644
--- a/backend/src/ee/services/agent-vault-variable/agent-vault-variable-service.ts
+++ b/backend/src/ee/services/agent-vault-variable/agent-vault-variable-service.ts
@@ -15,14 +15,14 @@ import { KmsDataKey } from "@app/services/kms/kms-types";
import { isUniqueViolation } from "../agent-vault/agent-vault-db-error-fns";
import { getAgentVaultPermission } from "../agent-vault/agent-vault-permission";
import { AGENT_VAULT_MAX_VARIABLES } from "../agent-vault/agent-vault-variable-fns";
-import { TAgentVaultProjectScoped } from "../agent-vault-access-bundle/agent-vault-access-bundle-types";
import {
+ TAgentVaultServiceUsingVariable,
TAgentVaultVariable,
- TAgentVaultVariableDALFactory,
- TAgentVaultVariableUser
+ TAgentVaultVariableDALFactory
} from "./agent-vault-variable-dal";
import {
- TAgentVaultVariableUsedBy,
+ TAgentVaultVariableScoped,
+ TAgentVaultVariableUsedByService,
TCreateVariableDTO,
TListVariablesDTO,
TUpdateVariableDTO,
@@ -35,6 +35,8 @@ type TAgentVaultVariableServiceFactoryDep = {
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
};
+const AGENT_VAULT_VARIABLE_LIST_DEFAULT_LIMIT = 20;
+
export type TAgentVaultVariableServiceFactory = ReturnType<typeof agentVaultVariableServiceFactory>;
export const agentVaultVariableServiceFactory = ({
@@ -47,7 +49,7 @@ export const agentVaultVariableServiceFactory = ({
// Variables are admin only, reads included: a member can use a service without seeing what it is built from, and
// Edit on access bundles is the action only an admin holds.
- const assertCanManageVariables = async ({ projectId, ctx }: TAgentVaultProjectScoped) => {
+ const assertCanManageVariables = async ({ projectId, ctx }: TAgentVaultVariableScoped) => {
const { permission } = await getAgentVaultPermission({ permissionService }, { projectId, ctx });
ForbiddenError.from(permission).throwUnlessCan(
ProjectPermissionAgentVaultAccessBundleActions.Edit,
@@ -56,18 +58,18 @@ export const agentVaultVariableServiceFactory = ({
};
// Values never leave through this projection; only the audited value endpoint returns one.
- const projectVariable = (variable: TAgentVaultVariable, users: TAgentVaultVariableUser[]) => ({
+ const projectVariable = (variable: TAgentVaultVariable, services: TAgentVaultServiceUsingVariable[]) => ({
id: variable.id,
key: variable.key,
- usedBy: users
- .filter((user) => user.variableId === variable.id)
+ usedByServices: services
+ .filter((service) => service.variableId === variable.id)
.map(
- (user): TAgentVaultVariableUsedBy => ({
- id: user.serviceId,
- name: user.serviceName,
- hostPattern: user.hostPattern,
- accessBundleId: user.accessBundleId,
- accessBundleName: user.accessBundleName
+ (service): TAgentVaultVariableUsedByService => ({
+ id: service.serviceId,
+ name: service.serviceName,
+ hostPattern: service.hostPattern,
+ accessBundleId: service.accessBundleId,
+ accessBundleName: service.accessBundleName
})
),
createdAt: variable.createdAt,
@@ -78,20 +80,28 @@ export const agentVaultVariableServiceFactory = ({
const duplicateKeyMessage = (key: string) => `A variable named '${key}' already exists.`;
- const inUseMessage = (key: string, users: TAgentVaultVariableUser[]) => {
- const names = users.map((user) => `'${user.serviceName}' (access bundle '${user.accessBundleName}')`).join(", ");
- return users.length === 1
+ const inUseMessage = (key: string, services: TAgentVaultServiceUsingVariable[]) => {
+ const names = services
+ .map((service) => `'${service.serviceName}' (access bundle '${service.accessBundleName}')`)
+ .join(", ");
+ return services.length === 1
? `The variable '${key}' is used by the service ${names}. Remove it from that service before deleting it.`
: `The variable '${key}' is used by the services ${names}. Remove it from those services before deleting it.`;
};
- const listVariables = async ({ projectId, ctx, ...query }: TListVariablesDTO) => {
+ const listVariables = async ({ projectId, ctx, limit, ...query }: TListVariablesDTO) => {
await assertCanManageVariables({ projectId, ctx });
- const { variables, totalCount } = await agentVaultVariableDAL.findForList({ projectId, ...query });
- const users = await agentVaultVariableDAL.findUsers(variables.map((variable) => variable.id));
+ // A lookup by keys returns every key that exists unless the caller caps it, so a missing entry always means
+ // the key doesn't exist.
+ const { variables, totalCount } = await agentVaultVariableDAL.findForList({
+ projectId,
+ ...query,
+ limit: limit ?? query.keys?.length ?? AGENT_VAULT_VARIABLE_LIST_DEFAULT_LIMIT
+ });
+ const services = await agentVaultVariableDAL.findServicesUsing(variables.map((variable) => variable.id));
- return { variables: variables.map((variable) => projectVariable(variable, users)), totalCount };
+ return { variables: variables.map((variable) => projectVariable(variable, services)), totalCount };
};
const createVariable = async ({ key, value, ...rest }: TCreateVariableDTO) => {
@@ -158,8 +168,8 @@ export const agentVaultVariableServiceFactory = ({
{ id: current.id, projectId: rest.projectId },
tx
);
- const users = await agentVaultVariableDAL.findUsers([current.id], tx);
- return { previous: current, updated: updated!, users };
+ const services = await agentVaultVariableDAL.findServicesUsing([current.id], tx);
+ return { previous: current, updated: updated!, services };
});
let result;
@@ -170,7 +180,7 @@ export const agentVaultVariableServiceFactory = ({
throw err;
}
- return { variable: projectVariable(result.updated, result.users), previousKey: result.previous.key };
+ return { variable: projectVariable(result.updated, result.services), previousKey: result.previous.key };
};
const deleteVariable = async ({ variableId, ...rest }: TVariableByIdDTO) => {
@@ -186,8 +196,8 @@ export const agentVaultVariableServiceFactory = ({
);
if (!variable) throw notFound(variableId);
- const users = await agentVaultVariableDAL.findUsers([variable.id], tx);
- if (users.length) throw new ConflictError({ message: inUseMessage(variable.key, users) });
+ const services = await agentVaultVariableDAL.findServicesUsing([variable.id], tx);
+ if (services.length) throw new ConflictError({ message: inUseMessage(variable.key, services) });
await agentVaultVariableDAL.deleteById(variable.id, tx);
return variable;
diff --git a/backend/src/ee/services/agent-vault-variable/agent-vault-variable-types.ts b/backend/src/ee/services/agent-vault-variable/agent-vault-variable-types.ts
index 852e6541ec..2b6b809e60 100644
--- a/backend/src/ee/services/agent-vault-variable/agent-vault-variable-types.ts
+++ b/backend/src/ee/services/agent-vault-variable/agent-vault-variable-types.ts
@@ -1,15 +1,19 @@
-import { TAgentVaultProjectScoped } from "../agent-vault-access-bundle/agent-vault-access-bundle-types";
+import { TGenericPermission } from "@app/lib/types";
+
import { TFindAgentVaultVariablesDTO } from "./agent-vault-variable-dal";
-export type TListVariablesDTO = TAgentVaultProjectScoped & Omit<TFindAgentVaultVariablesDTO, "projectId">;
+export type TAgentVaultVariableScoped = { projectId: string; ctx: TGenericPermission };
+
+export type TListVariablesDTO = TAgentVaultVariableScoped &
+ Omit<TFindAgentVaultVariablesDTO, "projectId" | "limit"> & { limit?: number };
-export type TCreateVariableDTO = TAgentVaultProjectScoped & { key: string; value: string };
+export type TCreateVariableDTO = TAgentVaultVariableScoped & { key: string; value: string };
-export type TUpdateVariableDTO = TAgentVaultProjectScoped & { variableId: string; key?: string; value?: string };
+export type TUpdateVariableDTO = TAgentVaultVariableScoped & { variableId: string; key?: string; value?: string };
-export type TVariableByIdDTO = TAgentVaultProjectScoped & { variableId: string };
+export type TVariableByIdDTO = TAgentVaultVariableScoped & { variableId: string };
-export type TAgentVaultVariableUsedBy = {
+export type TAgentVaultVariableUsedByService = {
id: string;
name: string;
hostPattern: string;
diff --git a/backend/src/ee/services/agent-vault/CLAUDE.md b/backend/src/ee/services/agent-vault/CLAUDE.md
index e34c10ea79..1dcce497af 100644
--- a/backend/src/ee/services/agent-vault/CLAUDE.md
+++ b/backend/src/ee/services/agent-vault/CLAUDE.md
@@ -177,9 +177,7 @@ path decides what a service can reach, so it stays literal.
- **Sealed text names a variable by id, `{{<uuid>}}`, never by key.** The key form exists only at the API
boundary: a service write maps keys to ids before it seals (`toStoredVariableReferences`), reading the
primary, since a variable created a moment earlier may not be on a replica yet. So a rename is one row.
-- The variable list and its Used By rows read the primary too. The service sheet refetches the list the moment
- it creates a variable, and a replica that has not caught up would drop the new key and fail the reference
- to it.
+- The variable list and its Used By rows read the primary too.
- `agent_vault_service_variable_references` holds a row per field per variable. It drives Used By, the delete
refusal, and the keys the service sheet lists under a stored value. **Resolve does not read it**: it pulls
the ids out of the decrypted fields, so a service saved mid-poll can never leave the two describing
@@ -188,12 +186,10 @@ path decides what a service can reach, so it stays literal.
project's own variables, which is exactly what resolve expands. Nothing in the database can compare the
rows with sealed text, and an id with no row is a variable the delete refusal lets go while a service still
sends it. Any new path that seals a service field derives its rows the same way. Resolve expands only the
- session project's variables, so a service can move between bundles without remapping its ids.
-- **A variable delete and a service save meet on the variable row, not the bundle.** The delete takes it `FOR
- UPDATE` and then reads the references; a save takes the rows it is about to reference `FOR SHARE` right before
- inserting them (`insertReferenceRows`). So the delete waits for an in-flight save and refuses with a 409 naming
- each service and its bundle, and a save whose variable went first fails with a 400. Create serialises on a
- per-project advisory lock for the cap and the key check; the `(projectId, key)` unique index is the backstop.
+ session project's variables.
+- **A variable delete and a service save meet on the variable row**: the delete locks it `FOR UPDATE`, a save
+ locks what it references `FOR SHARE` (`insertReferenceRows`). Create serialises on a per-project advisory lock;
+ the `(projectId, key)` unique index is the backstop.
- A stored value never comes back in any form, a lone `{{KEY}}` included. The sheet lists the keys a stored
field uses under the field and keeps the field masked until it is retyped. Settled: putting a lone
reference back in its field made it the one stored field that shows, and left a field mixing text with a
@@ -212,11 +208,8 @@ path decides what a service can reach, so it stays literal.
to its variables in one statement, and an immediate check can fire before the service cascade has removed the
rows, depending on which constraint was created first. The refusal that matters is the one under the variable
row lock; the deferred key is the backstop and only raises at commit. Deleting a bundle keeps its variables.
-- **Variables were per bundle until AGE2-130.** The migration gave each its bundle's project and, where two
- bundles shared a key, kept it on the oldest and renamed the rest `KEY_1`, `KEY_2`, ... (skipping any key already
- taken). That was safe only because sealed text names ids. `accessBundleId` survives, nullable and `SET NULL`,
- so a pod on the previous release keeps resolving during the rollout; nothing reads or writes it, and a follow-up
- migration drops it. Audit events from before the move still carry `accessBundleId` and `accessBundleName`.
+- `accessBundleId` on `agent_vault_variables` is a dead column kept for one release; nothing reads or writes it.
+ Older variable audit events still carry `accessBundleId` and `accessBundleName`.
- Every `{{...}}` in a value must be an existing, well-formed key, or the save fails. A malformed one is
refused without quoting it, because the text was cut from a secret. Placeholders and header prefixes (the
bearer prefix and custom header prefixes) can't contain double braces, which would read as a reference the
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 93f92f19ed..79eb911013 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -4476,20 +4476,20 @@ export const AGENT_VAULT = {
value: "The value the proxy puts in place of each `{{KEY}}`.",
updateValue: "The value the proxy puts in place of each `{{KEY}}`. Omit to keep the stored value.",
revealedValue: "The variable's value.",
- orderBy: "What to sort variables by: key, or usedBy for how many services use each one.",
+ orderBy: "What to sort variables by: key, or serviceCount for how many services use each one.",
orderDirection: "Which way to sort: asc or desc.",
search: "Match variables whose key contains this text.",
- keys: "Return only the variables with these exact keys, comma-separated. A key that doesn't exist is left out, which is how to check whether one does.",
- limit: "The maximum number of variables to return.",
+ keys: "Return only the variables with these exact keys, comma-separated. Every one that exists is returned unless limit is set.",
+ limit: "The maximum number of variables to return. Defaults to 20, or to the number of keys when keys is given.",
offset: "How many variables to skip.",
totalCount: "How many variables match the search, across every page.",
- usedBy:
+ usedByServices:
"The services that use this variable, across every access bundle, ordered by access bundle name and then service name. A variable in use can't be deleted.",
- usedById: "The ID of a service that uses this variable.",
- usedByName: "The name of the service.",
- usedByHostPattern: "The host pattern of the service.",
- usedByAccessBundleId: "The ID of the access bundle the service belongs to.",
- usedByAccessBundleName: "The name of the access bundle the service belongs to.",
+ usedByServiceId: "The ID of a service that uses this variable.",
+ usedByServiceName: "The name of the service.",
+ usedByServiceHostPattern: "The host pattern of the service.",
+ usedByServiceAccessBundleId: "The ID of the access bundle the service belongs to.",
+ usedByServiceAccessBundleName: "The name of the access bundle the service belongs to.",
createdAt: "When the variable was added.",
updatedAt: "When the variable was last changed."
},
diff --git a/docs/documentation/platform/agent-vault/variables.mdx b/docs/documentation/platform/agent-vault/variables.mdx
index e95ea17cbb..df208d8668 100644
--- a/docs/documentation/platform/agent-vault/variables.mdx
+++ b/docs/documentation/platform/agent-vault/variables.mdx
@@ -33,10 +33,10 @@ To add a variable:
</Step>
<Step>
- Enter a **Key** and a **Value**. The value is hidden once you save it. To view the value later, select the eye icon next to it. Each time someone views or copies a value, Infisical adds an event to the audit log.
+ Enter a **Key** and a **Value**. To view the value later, select the eye icon next to it. Each time someone views or copies a value, Infisical adds an event to the audit log.
<Note>
- A key must start with a letter, use only uppercase letters, numbers, and underscores, and can be up to 64 characters long. No two variables can have the same key.
+ A key can be up to 64 characters long. It must start with a letter and use only uppercase letters, numbers, and underscores. No two variables can have the same key.
</Note>
</Step>
@@ -44,7 +44,7 @@ To add a variable:
Select **Add Variable**. The variable appears in the list on the **Variables** page.
<Frame>
- <img src="/images/platform/agent-vault/variables.png" alt="The Variables page listing seven variables with hidden values. The Used By column shows access bundle badges, such as code-review, on-call, and +1 more for GITHUB_TOKEN, with a tooltip listing the github service in code-review. SENTRY_AUTH_TOKEN shows Unused." />
+ <img src="/images/platform/agent-vault/variables.png" alt="The Variables page listing seven variables with hidden values. The Used By column shows access bundle badges, such as code-review, on-call, and release-notes for GITHUB_TOKEN, with a tooltip listing the github service in code-review. SLACK_BOT_TOKEN shows three badges and +1 for one more access bundle. SENTRY_AUTH_TOKEN shows Unused." />
</Frame>
</Step>
@@ -101,7 +101,7 @@ To check which services are using a variable:
In Agent Vault, go to **Variables**.
</Step>
<Step>
- In the variable's **Used By** column, find the access bundles whose services use the variable. Hover over an access bundle to see those services, or select it to open the access bundle. If more access bundles use the variable than the column can show, select **+N more** to see the rest. If no service uses the variable, the column shows **Unused**.
+ In the variable's **Used By** column, hover over an access bundle to see which of the access bundle's services use the variable.
</Step>
</Steps>
@@ -125,7 +125,7 @@ To update a variable:
</Steps>
<Note>
-If you rename a variable, the services that use it keep working without changes. If you change a variable's value, the proxy sends the new value within one [poll interval](/documentation/platform/agent-vault/proxies#poll-interval) (60 seconds by default), so you don't need to restart running agents.
+If you rename a variable, the services that use it keep working without changes. If you change a variable's value, the proxy starts using the new value within one [poll interval](/documentation/platform/agent-vault/proxies#poll-interval) (60 seconds by default), so you don't need to restart running agents.
</Note>
## Delete a variable
diff --git a/docs/images/platform/agent-vault/variables.png b/docs/images/platform/agent-vault/variables.png
index 8126871afb..dcfbbb974a 100644
Binary files a/docs/images/platform/agent-vault/variables.png and b/docs/images/platform/agent-vault/variables.png differ
diff --git a/frontend/src/components/agent-vault/ServiceIconStack.tsx b/frontend/src/components/agent-vault/ServiceIconStack.tsx
index 0977eb06d4..29d35d677d 100644
--- a/frontend/src/components/agent-vault/ServiceIconStack.tsx
+++ b/frontend/src/components/agent-vault/ServiceIconStack.tsx
@@ -1,11 +1,10 @@
-import { ComponentPropsWithoutRef, forwardRef, ReactNode, useMemo, useState } from "react";
+import { ComponentPropsWithoutRef, forwardRef, useMemo, useState } from "react";
import { GlobeIcon } from "lucide-react";
import { Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";
import { ProviderIcon } from "@app/components/v3/platform/ProviderIcon";
import { cn } from "@app/components/v3/utils";
import { findTemplateForHostPattern } from "@app/helpers/agentVaultTemplates";
-import { TAgentVaultService } from "@app/hooks/api/agentVault/types";
type TServiceIcon = {
label: string;
@@ -81,36 +80,17 @@ export const ServiceIcon = ({
return <ServiceChip icon={icon} className={className} />;
};
-// Host patterns collapse to one chip per provider. Services keep a chip each under their own name,
-// since two services on one provider are still two services.
+// Host patterns collapse to one chip per provider.
type Props = {
+ hostPatterns: string[];
maxVisible?: number;
- emptyPlaceholder?: ReactNode;
className?: string;
-} & (
- | { hostPatterns: string[]; services?: never }
- | { services: Pick<TAgentVaultService, "name" | "hostPattern">[]; hostPatterns?: never }
-);
+};
-export const ServiceIconStack = ({
- hostPatterns,
- services,
- maxVisible = 4,
- emptyPlaceholder = <span className="text-muted">&mdash;</span>,
- className
-}: Props) => {
- const icons = useMemo(
- () =>
- services
- ? services.map((service) => ({
- label: service.name,
- image: findTemplateForHostPattern(service.hostPattern)?.image
- }))
- : iconsFromHostPatterns(hostPatterns),
- [hostPatterns, services]
- );
+export const ServiceIconStack = ({ hostPatterns, maxVisible = 4, className }: Props) => {
+ const icons = useMemo(() => iconsFromHostPatterns(hostPatterns), [hostPatterns]);
- if (icons.length === 0) return emptyPlaceholder;
+ if (icons.length === 0) return <span className="text-muted">&mdash;</span>;
const visible = icons.slice(0, maxVisible);
const hidden = icons.slice(maxVisible);
diff --git a/frontend/src/components/agent-vault/VariableFormDialog.tsx b/frontend/src/components/agent-vault/VariableFormDialog.tsx
index 2d6ec51dbc..c44e5be679 100644
--- a/frontend/src/components/agent-vault/VariableFormDialog.tsx
+++ b/frontend/src/components/agent-vault/VariableFormDialog.tsx
@@ -1,6 +1,7 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { Controller, useForm, useWatch } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
+import axios from "axios";
import { EyeIcon, EyeOffIcon } from "lucide-react";
import { z } from "zod";
@@ -39,6 +40,7 @@ import {
useUpdateAgentVaultVariable
} from "@app/hooks/api/agentVault";
import { TAgentVaultVariable } from "@app/hooks/api/agentVault/types";
+import { ApiErrorTypes, TApiErrors } from "@app/hooks/api/types";
// eslint-disable-next-line no-control-regex
const NO_CONTROL_CHARS_RE = /^[^\x00-\x1f\x7f]*$/;
@@ -82,18 +84,19 @@ type Props = {
onCloseAutoFocus?: (event: Event) => void;
};
-export const VariableFormDialog = ({
+// Mounted with the dialog's content, which unmounts while the dialog is closed, so every open starts from a fresh
+// form: no key, lookup or error is carried over from the last one.
+const VariableForm = ({
isOpen,
onOpenChange,
variable,
initialKey,
- onCreated,
- onCloseAutoFocus
-}: Props) => {
+ onCreated
+}: Omit<Props, "onCloseAutoFocus">) => {
const createVariable = useCreateAgentVaultVariable();
const updateVariable = useUpdateAgentVaultVariable();
const isUpdate = Boolean(variable);
- const usedByCount = variable?.usedBy.length ?? 0;
+ const usedByCount = variable?.usedByServices.length ?? 0;
const [isValueVisible, setIsValueVisible] = useState(false);
const takenKeysRef = useRef<ReadonlySet<string>>(new Set());
@@ -102,23 +105,32 @@ export const VariableFormDialog = ({
const {
control,
handleSubmit,
- reset,
+ setError,
setFocus,
trigger,
getFieldState,
formState: { isDirty, isSubmitting }
- } = useForm<FormData>({ resolver: zodResolver(schema) });
+ } = useForm<FormData>({
+ resolver: zodResolver(schema),
+ defaultValues: { key: variable?.key ?? initialKey ?? "", value: "" }
+ });
const key = useWatch({ control, name: "key" });
- // Checked against that one key, not a list, so it holds however many variables there are. The API refuses a
- // duplicate that is saved before the answer comes back.
+ // Asked of the server each time typing pauses, never from a cache, since another admin can add or delete the key
+ // at any time. A duplicate saved before the answer arrives is refused by the API and flagged under the field.
const [debouncedKey] = useDebounce(key ?? "", 300);
const lookupKey =
- isOpen && VARIABLE_KEY_RE.test(debouncedKey) && debouncedKey !== variable?.key
- ? debouncedKey
+ isOpen &&
+ !isSubmitting &&
+ debouncedKey === key &&
+ VARIABLE_KEY_RE.test(key) &&
+ key !== variable?.key
+ ? key
: null;
- const { existing } = useAgentVaultVariableKeyStatus(lookupKey ? [lookupKey] : [], isOpen);
+ const { existing } = useAgentVaultVariableKeyStatus(lookupKey ? [lookupKey] : [], {
+ isCached: false
+ });
takenKeysRef.current = existing;
// Re-checked when the answer flags the key, and when a key that was flagged is changed, so the message comes
// and goes with the lookup rather than waiting for a submit.
@@ -128,14 +140,10 @@ export const VariableFormDialog = ({
}, [lookupKey, existing, trigger, getFieldState]);
const isRenaming = Boolean(variable) && Boolean(key) && key !== variable?.key;
+ // A key that arrives filled in leaves the value as the one thing left to type.
useEffect(() => {
- if (!isOpen) return;
- reset({
- key: variable?.key ?? initialKey ?? "",
- value: ""
- });
- setIsValueVisible(false);
- }, [isOpen, variable, initialKey, reset]);
+ if (initialKey) setFocus("value");
+ }, [initialKey, setFocus]);
const onSubmit = async (data: FormData) => {
try {
@@ -155,115 +163,133 @@ export const VariableFormDialog = ({
createNotification({ text: `Variable "${data.key}" created`, type: "success" });
}
onOpenChange(false);
- } catch {
- // A failed request returns a 4xx that the global request handler surfaces as a toast
+ } catch (error) {
+ // The global request handler toasts every failure. A duplicate key is also shown on the field it concerns.
+ const serverResponse = axios.isAxiosError(error)
+ ? (error.response?.data as TApiErrors | undefined)
+ : undefined;
+ if (
+ serverResponse?.error === ApiErrorTypes.BadRequestError &&
+ serverResponse.message.endsWith("already exists.")
+ ) {
+ setError("key", { message: serverResponse.message });
+ }
}
};
return (
- <Dialog open={isOpen} onOpenChange={onOpenChange}>
- <DialogContent
- // A key that arrives filled in leaves the value as the one thing left to type.
- onOpenAutoFocus={(event) => {
- if (!initialKey) return;
- event.preventDefault();
- setFocus("value");
- }}
- onCloseAutoFocus={onCloseAutoFocus}
- >
- <DialogHeader>
- <DialogTitle>{isUpdate ? "Edit Variable" : "Add Variable"}</DialogTitle>
- <DialogDescription>
- Store a value once and use it from any service in any access bundle.
- </DialogDescription>
- </DialogHeader>
+ <>
+ <DialogHeader>
+ <DialogTitle>{isUpdate ? "Edit Variable" : "Add Variable"}</DialogTitle>
+ <DialogDescription>
+ Store a value once and use it from any service in any access bundle.
+ </DialogDescription>
+ </DialogHeader>
- <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4">
- <Controller
- control={control}
- name="key"
- render={({ field, fieldState }) => (
- <Field>
- <FieldLabel>Key</FieldLabel>
- <FieldContent>
- <Input
+ <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4">
+ <Controller
+ control={control}
+ name="key"
+ render={({ field, fieldState }) => (
+ <Field>
+ <FieldLabel>Key</FieldLabel>
+ <FieldContent>
+ <Input
+ {...field}
+ onChange={(event) => field.onChange(normalizeVariableKey(event.target.value))}
+ placeholder="GITHUB_TOKEN"
+ autoComplete="off"
+ spellCheck={false}
+ className="font-mono"
+ isError={Boolean(fieldState.error)}
+ />
+ <FieldDescription>
+ {isRenaming && usedByCount > 0 ? (
+ <>
+ {usedByCount === 1
+ ? "The service that uses it keeps working"
+ : `The ${usedByCount} services that use it keep working`}{" "}
+ under the new key.
+ </>
+ ) : (
+ <>
+ Services use it as{" "}
+ <code className="font-mono">{toVariableReference(key || "KEY")}</code>.
+ </>
+ )}
+ </FieldDescription>
+ <FieldError>{fieldState.error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
+ <Controller
+ control={control}
+ name="value"
+ render={({ field, fieldState }) => (
+ <Field>
+ <FieldLabel>Value</FieldLabel>
+ <FieldContent>
+ <InputGroup>
+ <InputGroupInput
{...field}
- onChange={(event) => field.onChange(normalizeVariableKey(event.target.value))}
- placeholder="GITHUB_TOKEN"
+ type={isValueVisible ? "text" : "password"}
+ placeholder={
+ variable ? "Leave blank to keep the current value" : "Enter the value"
+ }
autoComplete="off"
spellCheck={false}
- className="font-mono"
isError={Boolean(fieldState.error)}
/>
- <FieldDescription>
- {isRenaming && usedByCount > 0 ? (
- <>
- {usedByCount === 1
- ? "The service that uses it keeps working"
- : `The ${usedByCount} services that use it keep working`}{" "}
- under the new key.
- </>
- ) : (
- <>
- Services use it as{" "}
- <code className="font-mono">{toVariableReference(key || "KEY")}</code>.
- </>
- )}
- </FieldDescription>
- <FieldError>{fieldState.error?.message}</FieldError>
- </FieldContent>
- </Field>
- )}
- />
- <Controller
- control={control}
- name="value"
- render={({ field, fieldState }) => (
- <Field>
- <FieldLabel>Value</FieldLabel>
- <FieldContent>
- <InputGroup>
- <InputGroupInput
- {...field}
- type={isValueVisible ? "text" : "password"}
- placeholder={
- variable ? "Leave blank to keep the current value" : "Enter the value"
- }
- autoComplete="off"
- spellCheck={false}
- isError={Boolean(fieldState.error)}
- />
- <InputGroupAddon align="inline-end">
- <InputGroupButton
- isDisabled={!field.value}
- aria-label={isValueVisible ? "Hide value" : "Show value"}
- onClick={() => setIsValueVisible((prev) => !prev)}
- >
- {isValueVisible ? <EyeOffIcon /> : <EyeIcon />}
- </InputGroupButton>
- </InputGroupAddon>
- </InputGroup>
- <FieldError>{fieldState.error?.message}</FieldError>
- </FieldContent>
- </Field>
- )}
- />
+ <InputGroupAddon align="inline-end">
+ <InputGroupButton
+ isDisabled={!field.value}
+ aria-label={isValueVisible ? "Hide value" : "Show value"}
+ onClick={() => setIsValueVisible((prev) => !prev)}
+ >
+ {isValueVisible ? <EyeOffIcon /> : <EyeIcon />}
+ </InputGroupButton>
+ </InputGroupAddon>
+ </InputGroup>
+ <FieldError>{fieldState.error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
- <DialogFooter>
- <Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>
- Cancel
- </Button>
- <Button
- type="submit"
- variant="av"
- isPending={isSubmitting}
- isDisabled={isUpdate && !isDirty}
- >
- {isUpdate ? "Save" : "Add Variable"}
- </Button>
- </DialogFooter>
- </form>
- </DialogContent>
- </Dialog>
+ <DialogFooter>
+ <Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button
+ type="submit"
+ variant="av"
+ isPending={isSubmitting}
+ isDisabled={isUpdate && !isDirty}
+ >
+ {isUpdate ? "Save" : "Add Variable"}
+ </Button>
+ </DialogFooter>
+ </form>
+ </>
);
};
+
+export const VariableFormDialog = ({
+ isOpen,
+ onOpenChange,
+ onCloseAutoFocus,
+ ...formProps
+}: Props) => (
+ <Dialog open={isOpen} onOpenChange={onOpenChange}>
+ <DialogContent
+ // The form focuses the value itself when the key arrives filled in.
+ onOpenAutoFocus={(event) => {
+ if (formProps.initialKey) event.preventDefault();
+ }}
+ onCloseAutoFocus={onCloseAutoFocus}
+ >
+ <VariableForm isOpen={isOpen} onOpenChange={onOpenChange} {...formProps} />
+ </DialogContent>
+ </Dialog>
+);
diff --git a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx
index 85cff341e2..20afa08ac4 100644
--- a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx
+++ b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx
@@ -221,7 +221,7 @@ export const ServiceSheet = ({
const [debouncedReferencedKeys] = useDebounce(referencedKeys, 300);
const { missing: missingKeys } = useAgentVaultVariableKeyStatus(
debouncedReferencedKeys ? debouncedReferencedKeys.split(",") : [],
- isOpen
+ { enabled: isOpen }
);
missingKeysRef.current = missingKeys;
diff --git a/frontend/src/components/agent-vault/service-sheet/ServiceVariablesContext.ts b/frontend/src/components/agent-vault/service-sheet/ServiceVariablesContext.ts
index 75cbde57d7..dcb2267aa4 100644
--- a/frontend/src/components/agent-vault/service-sheet/ServiceVariablesContext.ts
+++ b/frontend/src/components/agent-vault/service-sheet/ServiceVariablesContext.ts
@@ -13,7 +13,7 @@ type TServiceVariables = {
substitutions: Record<string, string[]>;
};
/** Opens the new-variable dialog on top of the sheet. Resolves to null if it is dismissed. */
- requestVariable?: (key: string) => Promise<TAgentVaultVariable | null>;
+ requestVariable: (key: string) => Promise<TAgentVaultVariable | null>;
};
export const NO_STORED_KEYS: TServiceVariables["storedKeys"] = {
@@ -25,9 +25,11 @@ export const NO_STORED_KEYS: TServiceVariables["storedKeys"] = {
export const NO_MISSING_KEYS: ReadonlySet<string> = new Set();
+// Only the previews outside the credential step read the default, and they never ask for a variable.
export const ServiceVariablesContext = createContext<TServiceVariables>({
missingKeys: NO_MISSING_KEYS,
- storedKeys: NO_STORED_KEYS
+ storedKeys: NO_STORED_KEYS,
+ requestVariable: async () => null
});
export const useServiceVariables = () => useContext(ServiceVariablesContext);
diff --git a/frontend/src/components/agent-vault/service-sheet/VariableSuggestions.tsx b/frontend/src/components/agent-vault/service-sheet/VariableSuggestions.tsx
index 7d9053bb49..6a9c975eca 100644
--- a/frontend/src/components/agent-vault/service-sheet/VariableSuggestions.tsx
+++ b/frontend/src/components/agent-vault/service-sheet/VariableSuggestions.tsx
@@ -41,7 +41,7 @@ export const useVariableAutocomplete = ({
// Searched on the server, so the list never has to hold every variable. The last page stays up while the next
// loads, filtered to the new text, which a longer query only narrows.
- const { data } = useListAgentVaultVariables(
+ const { data, isPlaceholderData } = useListAgentVaultVariables(
{ search: debouncedQuery || undefined, limit: SUGGESTION_LIMIT },
{ enabled: isOpen }
);
@@ -49,7 +49,7 @@ export const useVariableAutocomplete = ({
// asked of that key alone.
const { existing } = useAgentVaultVariableKeyStatus(
isOpen && VARIABLE_KEY_RE.test(debouncedQuery) ? [debouncedQuery] : [],
- isOpen
+ { enabled: isOpen }
);
const [activeIndex, setActiveIndex] = useState(0);
// Escape closes the list for the reference being typed, not for the field: it opens again at the next {{.
@@ -77,15 +77,15 @@ export const useVariableAutocomplete = ({
.sort((a, b) => rank(a) - rank(b) || a.localeCompare(b))
.map((candidate) => ({ type: "variable" as const, key: candidate }));
- if (!requestVariable || keyExists) return matches;
+ if (!key || keyExists) return matches;
return [...matches, { type: "create", key, isKeyValid: VARIABLE_KEY_RE.test(key) }];
- }, [openReference, query, data, existing, requestVariable]);
+ }, [openReference, query, data, existing]);
// The search returns one page, plus the exact key when it exists. When matches are still left out, the list says
- // how many it shows and how to narrow it. Not while the text is ahead of the results, whose count it isn't.
+ // how many it shows and how to narrow it.
const shownCount = suggestions.filter((suggestion) => suggestion.type === "variable").length;
const truncation =
- data && query === debouncedQuery && data.totalCount > shownCount
+ data && !isPlaceholderData && query === debouncedQuery && data.totalCount > shownCount
? { shown: shownCount, total: data.totalCount }
: null;
@@ -151,7 +151,7 @@ export const useVariableAutocomplete = ({
// Settles once the dialog has closed. The field cannot change while it is open, so what surrounded
// the reference still does, and focus comes back to where the caret was.
- const created = await requestVariable?.(suggestion.key);
+ const created = await requestVariable(suggestion.key);
input.focus();
if (created) insert(created.key);
else input.setSelectionRange(caret, caret);
@@ -180,7 +180,6 @@ export const useVariableAutocomplete = ({
return {
isOpen,
isLoading: isOpen && !data,
- query,
truncation,
suggestions,
activeIndex,
@@ -209,7 +208,6 @@ export const VariableSuggestions = ({
const {
isOpen,
isLoading,
- query,
truncation,
suggestions,
activeIndex,
@@ -311,11 +309,7 @@ export const VariableSuggestions = ({
</>
) : (
<p className="px-2 py-1.5 text-xs text-muted">
- {(() => {
- if (isLoading) return "Loading variables...";
- if (query) return "No variable matches that name.";
- return "No variables yet. Add one under Variables.";
- })()}
+ {isLoading ? "Loading variables..." : "No variables yet. Type a key to create one."}
</p>
)}
</PopoverContent>
diff --git a/frontend/src/hooks/api/agentVault/mutations.tsx b/frontend/src/hooks/api/agentVault/mutations.tsx
index 03fb09b38b..e9febb7bc4 100644
--- a/frontend/src/hooks/api/agentVault/mutations.tsx
+++ b/frontend/src/hooks/api/agentVault/mutations.tsx
@@ -4,7 +4,7 @@ import { apiRequest } from "@app/config/request";
import { useOrganization } from "@app/context";
import { ApiErrorTypes } from "../types";
-import { agentVaultKeys, markAgentVaultVariablesChanged } from "./queries";
+import { agentVaultKeys } from "./queries";
import {
TAddAgentVaultMembersDTO,
TAddAgentVaultProductMembersDTO,
@@ -65,7 +65,7 @@ export const useUpdateAgentVaultAccessBundle = () => {
queryClient.invalidateQueries({
queryKey: agentVaultKeys.accessBundle(currentOrg.id, accessBundleId)
});
- // A variable's usedBy names each service's bundle.
+ // A variable's usedByServices names each service's bundle.
queryClient.invalidateQueries({ queryKey: agentVaultKeys.variables(currentOrg.id) });
}
});
@@ -394,13 +394,11 @@ export const useUpdateAgentVaultSessionLogSettings = () => {
};
// A rename changes the keys each service's variableReferences reports, so the bundles refresh too.
-const invalidateVariables = (queryClient: ReturnType<typeof useQueryClient>, orgId: string) => {
- markAgentVaultVariablesChanged(orgId);
- return Promise.all([
+const invalidateVariables = (queryClient: ReturnType<typeof useQueryClient>, orgId: string) =>
+ Promise.all([
queryClient.invalidateQueries({ queryKey: agentVaultKeys.variables(orgId) }),
queryClient.invalidateQueries({ queryKey: agentVaultKeys.accessBundles(orgId) })
]);
-};
export const useCreateAgentVaultVariable = () => {
const { currentOrg } = useOrganization();
@@ -413,12 +411,7 @@ export const useCreateAgentVaultVariable = () => {
);
return data.variable;
},
- onSuccess: (variable) => {
- // Known before the refetch lands, so a reference to it that was just inserted isn't flagged.
- markAgentVaultVariablesChanged(currentOrg.id);
- queryClient.setQueryData(agentVaultKeys.variableKeyStatus(currentOrg.id, variable.key), true);
- return invalidateVariables(queryClient, currentOrg.id);
- }
+ onSuccess: () => invalidateVariables(queryClient, currentOrg.id)
});
};
diff --git a/frontend/src/hooks/api/agentVault/queries.tsx b/frontend/src/hooks/api/agentVault/queries.tsx
index cbc99bbfa0..d21cda2c84 100644
--- a/frontend/src/hooks/api/agentVault/queries.tsx
+++ b/frontend/src/hooks/api/agentVault/queries.tsx
@@ -1,13 +1,5 @@
-import { useEffect, useMemo, useRef, useState } from "react";
-import {
- InfiniteData,
- SkipToken,
- skipToken,
- useInfiniteQuery,
- useQueries,
- useQuery,
- useQueryClient
-} from "@tanstack/react-query";
+import { useMemo, useRef, useState } from "react";
+import { InfiniteData, useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";
import axios from "axios";
import { apiRequest } from "@app/config/request";
@@ -101,8 +93,8 @@ export const agentVaultKeys = {
variables: (orgId: string) => [...agentVaultKeys.all(orgId), "variables"] as const,
variableList: (orgId: string, params: TListAgentVaultVariablesDTO) =>
[...agentVaultKeys.variables(orgId), "list", params] as const,
- variableKeyStatus: (orgId: string, key: string) =>
- [...agentVaultKeys.variables(orgId), "key-status", key] as const,
+ variableKeyStatus: (orgId: string, keys: string[]) =>
+ [...agentVaultKeys.variables(orgId), "key-status", keys] as const,
members: (orgId: string) => [...agentVaultKeys.all(orgId), "members"] as const,
memberList: (orgId: string, params?: TListAgentVaultMembersDTO) =>
[...agentVaultKeys.members(orgId), params] as const,
@@ -566,110 +558,52 @@ export const useListAgentVaultVariables = (
const KEY_LOOKUP_BATCH_SIZE = 100;
-// Bumped by every variable create, rename and delete. A lookup that was in flight across a change drops its answers
-// rather than writing them, since they may predate it: otherwise one sent just before a variable was created could
-// land after it and mark the new key missing. The change also invalidates the answers, so a fresh lookup asks again.
-const variableChangeCounts = new Map<string, number>();
-
-export const markAgentVaultVariablesChanged = (orgId: string) => {
- variableChangeCounts.set(orgId, (variableChangeCounts.get(orgId) ?? 0) + 1);
-};
-
// The API refuses a whole batch that holds one key it would never accept, so such a key isn't sent. No variable can
// have it, so it counts as missing, as the API says on save.
const isPossibleVariableKey = (key: string) =>
key.length <= VARIABLE_KEY_MAX_LENGTH && VARIABLE_KEY_RE.test(key);
-// A missing answer blocks a save, and another admin may create the key at any time, so it is asked again when the
-// window regains focus and on this interval while any key is flagged. An existing answer never blocks anything.
-const MISSING_RECHECK_MS = 30_000;
-
-// Whether each key exists. Each key's answer is cached on its own, so a key checked once isn't asked about again
-// until a variable changes, but the keys still to check go out together through the keys filter, in batches of
-// the API's maximum, rather than a request each. Only keys whose answer has arrived are in either set.
-export const useAgentVaultVariableKeyStatus = (keys: readonly string[], enabled = true) => {
+// Whether each key exists, asked through the keys filter in one request per 100 keys. Asked again on window focus
+// and whenever the variables are invalidated, since another admin may create or delete one at any time. A key is in
+// neither set until an answer that asked about it arrives; the previous answer stays up meanwhile, so a key it
+// already covered doesn't flicker while the next set loads.
+export const useAgentVaultVariableKeyStatus = (
+ keys: readonly string[],
+ { enabled = true, isCached = true }: { enabled?: boolean; isCached?: boolean } = {}
+) => {
const { currentOrg } = useOrganization();
- const queryClient = useQueryClient();
- const statusKey = (key: string) => agentVaultKeys.variableKeyStatus(currentOrg.id, key);
- const possibleKeys = keys.filter(isPossibleVariableKey);
- const impossibleKeys = keys.filter((key) => !isPossibleVariableKey(key));
-
- // Read-only: these never fetch, the batch below fills them.
- const { existing, missing, hasRecheckableMissing } = useQueries({
- queries: possibleKeys.map((key) => ({
- queryKey: statusKey(key),
- queryFn: skipToken as SkipToken
- })),
- combine: (results) => ({
- existing: possibleKeys.filter((_, index) => results[index]?.data === true).join(","),
- missing: [
- ...impossibleKeys,
- ...possibleKeys.filter((_, index) => results[index]?.data === false)
- ].join(","),
- hasRecheckableMissing: possibleKeys.some((_, index) => results[index]?.data === false)
- })
- });
+ const possibleKeys = [...new Set(keys.filter(isPossibleVariableKey))].sort();
- const [recheckMissingAt, setRecheckMissingAt] = useState(() => Date.now());
- useEffect(() => {
- if (!enabled || !hasRecheckableMissing) return undefined;
- const recheck = () => setRecheckMissingAt(Date.now());
- const recheckIfVisible = () => {
- if (document.visibilityState === "visible") recheck();
- };
- window.addEventListener("focus", recheck);
- document.addEventListener("visibilitychange", recheckIfVisible);
- const interval = window.setInterval(recheck, MISSING_RECHECK_MS);
- return () => {
- window.removeEventListener("focus", recheck);
- document.removeEventListener("visibilitychange", recheckIfVisible);
- window.clearInterval(interval);
- };
- }, [enabled, hasRecheckableMissing]);
-
- // Unanswered keys, answered ones a variable change has invalidated since, and missing ones answered before the
- // last recheck.
- const unchecked = [...possibleKeys]
- .filter((key) => {
- const state = queryClient.getQueryState(statusKey(key));
- if (state?.data === undefined || state.isInvalidated) return true;
- return state.data === false && state.dataUpdatedAt < recheckMissingAt;
- })
- .sort();
-
- // The change count is part of the key, so a change starts a new lookup instead of joining one still in flight,
- // whose answers that change has made stale.
- const changeCount = variableChangeCounts.get(currentOrg.id) ?? 0;
- useQuery({
- queryKey: [
- ...agentVaultKeys.variables(currentOrg.id),
- "key-status-batch",
- changeCount,
- recheckMissingAt,
- unchecked
- ],
+ const { data } = useQuery({
+ queryKey: agentVaultKeys.variableKeyStatus(currentOrg.id, possibleKeys),
queryFn: async () => {
- const found = new Set<string>();
- for (let i = 0; i < unchecked.length; i += KEY_LOOKUP_BATCH_SIZE) {
+ const found: string[] = [];
+ for (let i = 0; i < possibleKeys.length; i += KEY_LOOKUP_BATCH_SIZE) {
// eslint-disable-next-line no-await-in-loop
const page = await fetchAgentVaultVariables({
- keys: unchecked.slice(i, i + KEY_LOOKUP_BATCH_SIZE),
- limit: KEY_LOOKUP_BATCH_SIZE
+ keys: possibleKeys.slice(i, i + KEY_LOOKUP_BATCH_SIZE)
});
- page.variables.forEach((variable) => found.add(variable.key));
+ found.push(...page.variables.map((variable) => variable.key));
}
- if ((variableChangeCounts.get(currentOrg.id) ?? 0) !== changeCount) return 0;
- unchecked.forEach((key) => queryClient.setQueryData<boolean>(statusKey(key), found.has(key)));
- return unchecked.length;
+ return { asked: possibleKeys, found };
},
- enabled: enabled && unchecked.length > 0
+ enabled: enabled && possibleKeys.length > 0,
+ placeholderData: (prev) => prev,
+ refetchOnWindowFocus: true,
+ staleTime: 0,
+ ...(isCached ? {} : { gcTime: 0 })
});
- return useMemo(
- () => ({
- existing: new Set(existing ? existing.split(",") : []) as ReadonlySet<string>,
- missing: new Set(missing ? missing.split(",") : []) as ReadonlySet<string>
- }),
- [existing, missing]
- );
+ const keySignature = keys.join(",");
+ return useMemo(() => {
+ const asked = new Set(data?.asked);
+ const found = new Set(data?.found);
+ const current = keySignature ? keySignature.split(",") : [];
+ return {
+ existing: new Set(current.filter((key) => found.has(key))) as ReadonlySet<string>,
+ missing: new Set(
+ current.filter((key) => !isPossibleVariableKey(key) || (asked.has(key) && !found.has(key)))
+ ) as ReadonlySet<string>
+ };
+ }, [data, keySignature]);
};
diff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.ts
index 5ec7873cd5..3b3dd5e736 100644
--- a/frontend/src/hooks/api/agentVault/types.ts
+++ b/frontend/src/hooks/api/agentVault/types.ts
@@ -142,7 +142,7 @@ export type TListAgentVaultVariablesDTO = {
search?: string;
/** Exact keys. A key that doesn't exist is left out of the response. */
keys?: string[];
- orderBy?: "key" | "usedBy";
+ orderBy?: "key" | "serviceCount";
orderDirection?: "asc" | "desc";
limit?: number;
offset?: number;
@@ -406,7 +406,7 @@ export type TAgentVaultDecryptedSessionLogPage<
decrypted: Record<string, TAgentVaultDecryptedChunk>;
};
-export type TAgentVaultVariableUsage = {
+export type TAgentVaultVariableUsedByService = {
id: string;
name: string;
hostPattern: string;
@@ -418,7 +418,7 @@ export type TAgentVaultVariable = {
id: string;
key: string;
// Every service that references the variable, across all access bundles.
- usedBy: TAgentVaultVariableUsage[];
+ usedByServices: TAgentVaultVariableUsedByService[];
createdAt: string;
updatedAt: string;
};
diff --git a/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/DeleteVariableDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/DeleteVariableDialog.tsx
index 74fdc8015c..b3ffd2f757 100644
--- a/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/DeleteVariableDialog.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/DeleteVariableDialog.tsx
@@ -24,8 +24,8 @@ type Props = {
export const DeleteVariableDialog = ({ variable, onOpenChange }: Props) => {
const { currentOrg } = useOrganization();
const deleteVariable = useDeleteAgentVaultVariable();
- const usedBy = variable?.usedBy ?? [];
- const isInUse = usedBy.length > 0;
+ const usedByServices = variable?.usedByServices ?? [];
+ const isInUse = usedByServices.length > 0;
const handleDelete = async () => {
if (!variable) return;
@@ -45,14 +45,14 @@ export const DeleteVariableDialog = ({ variable, onOpenChange }: Props) => {
<AlertDialogTitle>Delete &quot;{variable?.key}&quot;</AlertDialogTitle>
<AlertDialogDescription>
{isInUse
- ? `${usedBy.length === 1 ? "A service uses" : `${usedBy.length} services use`} this variable. Remove the reference from ${usedBy.length === 1 ? "it" : "them"} before you delete it.`
+ ? `${usedByServices.length === 1 ? "A service uses" : `${usedByServices.length} services use`} this variable. Remove the reference from ${usedByServices.length === 1 ? "it" : "them"} before you delete it.`
: "Its value is deleted with it. This cannot be undone."}
</AlertDialogDescription>
</AlertDialogHeader>
{isInUse && (
<ul className="flex max-h-48 flex-col gap-2 overflow-y-auto rounded-md border border-border bg-container/50 p-3">
- {usedBy.map((service) => (
+ {usedByServices.map((service) => (
<li key={service.id} className="flex items-center gap-2">
<ServiceIcon hostPattern={service.hostPattern} />
<div className="flex min-w-0 flex-col">
diff --git a/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/UsedByBundleBadges.tsx b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/UsedByBundleBadges.tsx
index 262ffe1208..2155b16fbf 100644
--- a/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/UsedByBundleBadges.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/UsedByBundleBadges.tsx
@@ -1,108 +1,73 @@
-import { Link } from "@tanstack/react-router";
+import { useMemo } from "react";
+import { linkOptions } from "@tanstack/react-router";
import { PackageIcon } from "lucide-react";
import { ServiceIcon } from "@app/components/agent-vault/ServiceIconStack";
-import {
- Badge,
- Popover,
- PopoverContent,
- PopoverTrigger,
- Tooltip,
- TooltipContent,
- TooltipTrigger
-} from "@app/components/v3";
+import { OverflowBadgeList } from "@app/components/v3";
import { useOrganization } from "@app/context";
-import { TAgentVaultVariable } from "@app/hooks/api/agentVault/types";
-
-type TUsage = TAgentVaultVariable["usedBy"][number];
+import { TAgentVaultVariableUsedByService } from "@app/hooks/api/agentVault/types";
type TBundleUsage = {
accessBundleId: string;
accessBundleName: string;
- services: TUsage[];
+ services: TAgentVaultVariableUsedByService[];
};
-const DEFAULT_MAX_VISIBLE = 2;
-
-const groupByBundle = (usedBy: TUsage[]): TBundleUsage[] => {
+const groupByBundle = (usedByServices: TAgentVaultVariableUsedByService[]): TBundleUsage[] => {
const byBundle = new Map<string, TBundleUsage>();
- usedBy.forEach((usage) => {
- const bundle = byBundle.get(usage.accessBundleId) ?? {
- accessBundleId: usage.accessBundleId,
- accessBundleName: usage.accessBundleName,
+ usedByServices.forEach((service) => {
+ const bundle = byBundle.get(service.accessBundleId) ?? {
+ accessBundleId: service.accessBundleId,
+ accessBundleName: service.accessBundleName,
services: []
};
- bundle.services.push(usage);
- byBundle.set(usage.accessBundleId, bundle);
+ bundle.services.push(service);
+ byBundle.set(service.accessBundleId, bundle);
});
return [...byBundle.values()].sort((a, b) =>
a.accessBundleName.localeCompare(b.accessBundleName)
);
};
-const BundleBadge = ({ bundle }: { bundle: TBundleUsage }) => {
- const { currentOrg } = useOrganization();
+const BundleServices = ({ bundle }: { bundle: TBundleUsage }) => (
+ <>
+ <p className="mb-2 break-all text-muted">{bundle.accessBundleName}</p>
+ <ul className="flex flex-col gap-1.5">
+ {bundle.services.map((service) => (
+ <li key={service.id} className="flex items-center gap-2">
+ <ServiceIcon hostPattern={service.hostPattern} className="size-5" />
+ <span className="truncate">{service.name}</span>
+ </li>
+ ))}
+ </ul>
+ </>
+);
- return (
- <Tooltip>
- <TooltipTrigger asChild>
- <Badge variant="neutral" isTruncatable className="max-w-[10rem]" asChild>
- <Link
- to="/organizations/$orgId/agent-vault/access-bundles/$accessBundleId"
- params={{ orgId: currentOrg.id, accessBundleId: bundle.accessBundleId }}
- >
- <PackageIcon />
- <span>{bundle.accessBundleName}</span>
- </Link>
- </Badge>
- </TooltipTrigger>
- <TooltipContent className="max-w-xs">
- <p className="mb-2 break-all text-muted">{bundle.accessBundleName}</p>
- <ul className="flex flex-col gap-1.5">
- {bundle.services.map((service) => (
- <li key={service.id} className="flex items-center gap-2">
- <ServiceIcon hostPattern={service.hostPattern} className="size-5" />
- <span className="truncate">{service.name}</span>
- </li>
- ))}
- </ul>
- </TooltipContent>
- </Tooltip>
- );
-};
+const renderBundleServices = (bundle: TBundleUsage) => <BundleServices bundle={bundle} />;
export const UsedByBundleBadges = ({
- usedBy,
- maxVisible = DEFAULT_MAX_VISIBLE
+ usedByServices
}: {
- usedBy: TUsage[];
- maxVisible?: number;
+ usedByServices: TAgentVaultVariableUsedByService[];
}) => {
- if (usedBy.length === 0) return <span className="text-sm text-muted">Unused</span>;
+ const { currentOrg } = useOrganization();
+ const bundles = useMemo(() => groupByBundle(usedByServices), [usedByServices]);
- const bundles = groupByBundle(usedBy);
- const visible = bundles.slice(0, maxVisible);
- const overflow = bundles.slice(maxVisible);
+ if (bundles.length === 0) return <span className="text-sm text-muted">Unused</span>;
return (
- <div className="flex min-w-0 items-center gap-1.5">
- {visible.map((bundle) => (
- <BundleBadge key={bundle.accessBundleId} bundle={bundle} />
- ))}
- {overflow.length > 0 && (
- <Popover>
- <PopoverTrigger asChild>
- <Badge variant="neutral" asChild>
- <button type="button">+{overflow.length} more</button>
- </Badge>
- </PopoverTrigger>
- <PopoverContent side="bottom" align="end" className="flex flex-wrap gap-1.5">
- {overflow.map((bundle) => (
- <BundleBadge key={bundle.accessBundleId} bundle={bundle} />
- ))}
- </PopoverContent>
- </Popover>
- )}
- </div>
+ <OverflowBadgeList
+ items={bundles}
+ getKey={(bundle) => bundle.accessBundleId}
+ getLabel={(bundle) => bundle.accessBundleName}
+ icon={<PackageIcon />}
+ getTooltip={renderBundleServices}
+ getLinkProps={(bundle) =>
+ linkOptions({
+ to: "/organizations/$orgId/agent-vault/access-bundles/$accessBundleId",
+ params: { orgId: currentOrg.id, accessBundleId: bundle.accessBundleId }
+ })
+ }
+ />
);
};
diff --git a/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/VariablesCard.tsx b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/VariablesCard.tsx
index 5cdae6d1fb..194eef2560 100644
--- a/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/VariablesCard.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/VariablesCard.tsx
@@ -66,7 +66,7 @@ import { UsedByBundleBadges } from "./UsedByBundleBadges";
enum SortColumn {
Key = "key",
- UsedBy = "usedBy"
+ ServiceCount = "serviceCount"
}
const MASK = "•".repeat(8);
@@ -236,6 +236,8 @@ export const VariablesCard = () => {
const displayed = data?.variables ?? [];
const totalCount = data?.totalCount ?? 0;
useResetPageHelper({ totalCount, offset: (page - 1) * perPage, setPage });
+ // A search narrows totalCount, so whether the cap is reached is read off an unfiltered count.
+ const { data: unfilteredData } = useListAgentVaultVariables({ limit: 1 });
const handleSort = (column: SortColumn, direction: "ascending" | "descending" | "none") => {
setPage(1);
@@ -301,8 +303,7 @@ export const VariablesCard = () => {
};
const hasVariables = totalCount > 0 || Boolean(searchTerm);
- // A search narrows totalCount, so only an unfiltered count says whether the cap is reached.
- const isAtLimit = !searchTerm && totalCount >= MAX_VARIABLES;
+ const isAtLimit = (unfilteredData?.totalCount ?? 0) >= MAX_VARIABLES;
const openForm = (variable: TAgentVaultVariable | null) => {
setVariableToEdit(variable);
@@ -391,11 +392,11 @@ export const VariablesCard = () => {
</TableHead>
<TableHead className="w-[35%]">Value</TableHead>
<TableHead
- sortDirection={sortColumn === SortColumn.UsedBy ? sortDirection : "none"}
- onSortChange={(direction) => handleSort(SortColumn.UsedBy, direction)}
+ sortDirection={sortColumn === SortColumn.ServiceCount ? sortDirection : "none"}
+ onSortChange={(direction) => handleSort(SortColumn.ServiceCount, direction)}
>
Used By
- <ChevronDownIcon className={sortIconClassName(SortColumn.UsedBy)} />
+ <ChevronDownIcon className={sortIconClassName(SortColumn.ServiceCount)} />
</TableHead>
<TableHead variant="action" className="w-12" />
</TableRow>
@@ -439,7 +440,7 @@ export const VariablesCard = () => {
</div>
</TableCell>
<TableCell>
- <UsedByBundleBadges usedBy={variable.usedBy} />
+ <UsedByBundleBadges usedByServices={variable.usedByServices} />
</TableCell>
<TableCell variant="action">
<DropdownMenu>