Skip to content

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

fix(agent-vault): address Saif's third review on personal values

Scott Wilsonc837a5fa79d7
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.ts
index e434440c23..98a5fe52d5 100644
--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts
+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts
@@ -1851,7 +1851,7 @@ describe("Agent Vault V1 Router", async () => {
return new Map(accessBundle.services.map((service) => [service.id, service.personalValues]));
};
- // The bundles granted to the caller that still require their values, with the services that do.
+ // The bundles the caller reaches that still require their values, with the services that do.
const pendingOf = async (as: (method: "GET", url: string) => ReturnType<typeof inject>) => {
const res = await as("GET", "/api/v1/agent-vault/access-bundles?requiresSetup=true&limit=100");
expect(res.statusCode).toBe(200);
@@ -2458,22 +2458,202 @@ describe("Agent Vault V1 Router", async () => {
}
});
- test("an admin is asked for values only on the bundles granted to them", async () => {
+ test("deleting a bundle while a member is being removed from Agent Vault doesn't deadlock", async () => {
+ const bundle = await createAccessBundle("mp-delete-vs-remove");
+ const service = await createService(bundle.id, {
+ name: "linear",
+ hostPattern: "linear-deadlock.example.com",
+ credential: { type: "bearer", memberProvidedFields: ["credential-value"] }
+ });
+
+ const member = await createMemberIdentity(`mp-delete-vs-remove-${Date.now()}`);
+ try {
+ expect((await inject("POST", membersUrl(bundle.id), { machineIdentityIds: [member.id] })).statusCode).toBe(200);
+ expect((await setValues(member.as, bundle.id, service.id, { "credential-value": "mine" })).statusCode).toBe(
+ 200
+ );
+
+ // What a removal does: delete the member's grants, then their saved values, in one transaction.
+ const trx = await testDb.transaction();
+ let pending: ReturnType<typeof inject> | undefined;
+ try {
+ const { rows } = await trx.raw("select pg_backend_pid() as pid");
+ await trx("memberships").where({ scopeResourceId: bundle.id, actorIdentityId: member.id }).delete();
+
+ pending = inject("DELETE", `/api/v1/agent-vault/access-bundles/${bundle.id}`);
+ await waitUntilBlockedBy(rows[0].pid);
+ await trx("agent_vault_personal_values").where({ identityId: member.id }).delete();
+ await trx.commit();
+
+ expect((await pending).statusCode).toBe(200);
+ } catch (err) {
+ if (!trx.isCompleted()) await trx.rollback();
+ await pending?.catch(() => undefined);
+ throw err;
+ }
+ expect(await testDb("agent_vault_access_bundles").where({ id: bundle.id })).toHaveLength(0);
+ } finally {
+ await member.cleanup();
+ }
+ });
+
+ test("until a member sets up their half, resolve sends no credential, not the admin's half", async () => {
+ const bundle = await createAccessBundle("mp-half");
+ await createService(bundle.id, {
+ name: "jira",
+ hostPattern: "jira-half.example.com",
+ credential: { type: "basic", password: "admin-password", memberProvidedFields: ["credential-username"] }
+ });
+
+ const member = await createMemberIdentity(`mp-half-${Date.now()}`);
+ try {
+ expect((await inject("POST", membersUrl(bundle.id), { machineIdentityIds: [member.id] })).statusCode).toBe(200);
+ const resolve = await enrollProxy("mp-half");
+ const unset = await resolve(await mintSession(member.as, bundle.name), "jira");
+ expect(unset.personalValuesMissing).toBe(true);
+ expect(unset.credential).toEqual({ type: "passthrough" });
+ } finally {
+ await member.cleanup();
+ }
+ });
+
+ test("taking every field back from members on the same type deletes their values", async () => {
+ const bundle = await createAccessBundle("mp-take-all");
+ const service = await createService(bundle.id, {
+ name: "confluence",
+ hostPattern: "confluence-all.example.com",
+ credential: { type: "basic", memberProvidedFields: ["credential-username", "credential-value"] }
+ });
+
+ const member = await createMemberIdentity(`mp-take-all-${Date.now()}`);
+ try {
+ expect((await inject("POST", membersUrl(bundle.id), { machineIdentityIds: [member.id] })).statusCode).toBe(200);
+ expect(
+ (await setValues(member.as, bundle.id, service.id, { "credential-username": "u", "credential-value": "p" }))
+ .statusCode
+ ).toBe(200);
+
+ const takeBack = await inject("PATCH", `${servicesUrl(bundle.id)}/${service.id}`, {
+ credential: { type: "basic", username: "admin-u", password: "admin-p", memberProvidedFields: [] }
+ });
+ expect(takeBack.statusCode).toBe(200);
+ expect((await statusesOf(member.as, bundle.id)).get(service.id)).toBeNull();
+ expect(await testDb("agent_vault_personal_values").where({ serviceId: service.id })).toHaveLength(0);
+ } finally {
+ await member.cleanup();
+ }
+ });
+
+ test("a user loses their values with a direct revoke, and a group member with the group's", async () => {
+ const bundle = await createAccessBundle("mp-users");
+ const service = await createService(bundle.id, {
+ name: "notion",
+ hostPattern: "notion-users.example.com",
+ credential: { type: "bearer", memberProvidedFields: ["credential-value"] }
+ });
+ const group = await createProjectGroup(await getProjectId(), "mp-users-group", ProjectMembershipRole.Member);
+ const direct = await createUser("mp-direct");
+ const viaGroup = await createUser("mp-via-group");
+ try {
+ const asUser = async (userId: string) => {
+ await addUserMembership({ userId, orgId: seedData1.organization.id, role: OrgMembershipRole.Member });
+ expect(
+ (await inject("POST", "/api/v1/agent-vault/members", { userIds: [userId], role: "member" })).statusCode
+ ).toBe(200);
+ const token = await createUserAccessToken({ userId, orgId: seedData1.organization.id });
+ return (method: "GET" | "POST" | "PATCH" | "DELETE", url: string, body?: Record<string, unknown>) =>
+ testServer.inject({
+ method,
+ url,
+ headers: { authorization: `Bearer ${token}` },
+ ...(body ? { body } : {})
+ });
+ };
+ const directAs = await asUser(direct.userId);
+ const groupAs = await asUser(viaGroup.userId);
+ await testDb("user_group_membership").insert({ groupId: group.id, userId: viaGroup.userId });
+
+ expect((await inject("POST", membersUrl(bundle.id), { userIds: [direct.userId] })).statusCode).toBe(200);
+ expect((await inject("POST", membersUrl(bundle.id), { groupIds: [group.id] })).statusCode).toBe(200);
+ expect((await setValues(directAs, bundle.id, service.id, { "credential-value": "a" })).statusCode).toBe(200);
+ expect((await setValues(groupAs, bundle.id, service.id, { "credential-value": "b" })).statusCode).toBe(200);
+
+ expect((await inject("DELETE", membersUrl(bundle.id), { userIds: [direct.userId] })).statusCode).toBe(200);
+ expect(await testDb("agent_vault_personal_values").where({ userId: direct.userId })).toHaveLength(0);
+ expect(await testDb("agent_vault_personal_values").where({ userId: viaGroup.userId })).toHaveLength(1);
+
+ expect((await inject("DELETE", membersUrl(bundle.id), { groupIds: [group.id] })).statusCode).toBe(200);
+ expect(await testDb("agent_vault_personal_values").where({ userId: viaGroup.userId })).toHaveLength(0);
+ } finally {
+ await testDb("user_group_membership").where({ groupId: group.id }).delete();
+ await group.cleanup();
+ await deleteUsers([direct.userId, viaGroup.userId]);
+ }
+ });
+
+ test("a save made against a stale credential type is refused, not stored under the new type", async () => {
+ const bundle = await createAccessBundle("mp-stale-type");
+ const service = await createService(bundle.id, {
+ name: "bitbucket",
+ hostPattern: "bitbucket-stale.example.com",
+ credential: { type: "basic", username: "admin-u", memberProvidedFields: ["credential-value"] }
+ });
+
+ const member = await createMemberIdentity(`mp-stale-type-${Date.now()}`);
+ try {
+ expect((await inject("POST", membersUrl(bundle.id), { machineIdentityIds: [member.id] })).statusCode).toBe(200);
+ // The member's page still shows basic, but an admin has since switched the service to bearer.
+ expect(
+ (
+ await inject("PATCH", `${servicesUrl(bundle.id)}/${service.id}`, {
+ credential: { type: "bearer", memberProvidedFields: ["credential-value"] }
+ })
+ ).statusCode
+ ).toBe(200);
+ const stale = await member.as("PATCH", personalValuesUrl(bundle.id, service.id), {
+ values: [{ field: "credential-value", value: "my-password" }],
+ credentialType: "basic"
+ });
+ expect(stale.statusCode).toBe(409);
+ expect(await testDb("agent_vault_personal_values").where({ identityId: member.id })).toHaveLength(0);
+
+ const current = await member.as("PATCH", personalValuesUrl(bundle.id, service.id), {
+ values: [{ field: "credential-value", value: "my-token" }],
+ credentialType: "bearer"
+ });
+ expect(current.statusCode).toBe(200);
+ } finally {
+ await member.cleanup();
+ }
+ });
+
+ test("an admin is asked for values on a bundle they reach only by role, flagged as not granted", async () => {
const ungranted = await createAccessBundle("mp-mine-ungranted");
const service = await createService(ungranted.id, {
name: "openai",
hostPattern: "api.openai.com",
credential: { type: "bearer", memberProvidedFields: ["credential-value"] }
});
+ const granted = await createAccessBundle("mp-mine-granted");
expect((await inject("DELETE", membersUrl(ungranted.id), { userIds: [seedData1.id] })).statusCode).toBe(200);
const listed = await inject("GET", "/api/v1/agent-vault/access-bundles?search=mp-mine&limit=100");
- expect(JSON.parse(listed.payload).accessBundles).toEqual([
- expect.objectContaining({ id: ungranted.id, servicesRequiringSetup: [] })
- ]);
- expect((await pendingOf(inject)).has(ungranted.id)).toBe(false);
+ expect(JSON.parse(listed.payload).accessBundles).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ id: ungranted.id,
+ isGranted: false,
+ servicesRequiringSetup: [{ id: service.id, name: "openai" }]
+ }),
+ expect.objectContaining({ id: granted.id, isGranted: true, servicesRequiringSetup: [] })
+ ])
+ );
+ expect((await pendingOf(inject)).get(ungranted.id)).toEqual(["openai"]);
+ const setUp = await inject("GET", "/api/v1/agent-vault/access-bundles?requiresSetup=false&search=mp-mine");
+ expect(
+ (JSON.parse(setUp.payload) as { accessBundles: { id: string }[] }).accessBundles.map((bundle) => bundle.id)
+ ).toEqual([granted.id]);
expect((await inject("GET", "/api/v1/agent-vault/access-bundles?requiresSetup=maybe")).statusCode).toBe(422);
- // Opening the bundle still shows what a session from it would need.
expect((await statusesOf(inject, ungranted.id)).get(service.id)?.isConfigured).toBe(false);
});
diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts
index a764e6f958..e944bc1f28 100644
--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts
+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts
@@ -89,6 +89,7 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro
serviceCount: z.number().describe(AGENT_VAULT.ACCESS_BUNDLE.serviceCount),
memberCount: z.number().describe(AGENT_VAULT.ACCESS_BUNDLE.memberCount),
hostPatterns: z.string().array().describe(AGENT_VAULT.ACCESS_BUNDLE.hostPatterns),
+ isGranted: z.boolean().describe(AGENT_VAULT.ACCESS_BUNDLE.isGranted),
servicesRequiringSetup: z
.object({
id: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.servicesRequiringSetupId),
@@ -542,7 +543,11 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro
serviceId: z.string().uuid().describe(AGENT_VAULT.SERVICE.serviceId)
}),
body: z.object({
- values: AgentVaultPersonalValueInputSchema.array().min(1).max(2).describe(AGENT_VAULT.PERSONAL_VALUE.values)
+ values: AgentVaultPersonalValueInputSchema.array().min(1).max(2).describe(AGENT_VAULT.PERSONAL_VALUE.values),
+ credentialType: z
+ .nativeEnum(AgentVaultCredentialType)
+ .optional()
+ .describe(AGENT_VAULT.PERSONAL_VALUE.credentialType)
}),
response: { 200: z.object({ personalValues: AgentVaultPersonalValuesSchema }) }
},
@@ -553,7 +558,8 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro
ctx: actorContext(req),
accessBundleId: req.params.accessBundleId,
serviceId: req.params.serviceId,
- values: req.body.values
+ values: req.body.values,
+ credentialType: req.body.credentialType
});
await server.services.auditLog.createAuditLog({
@@ -567,6 +573,7 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro
accessBundleName: personalValues.accessBundleName,
serviceId: personalValues.serviceId,
serviceName: personalValues.serviceName,
+ credentialType: personalValues.credentialType,
fields: req.body.values.map((value) => value.field),
variableKeys: [
...new Set(
@@ -618,7 +625,8 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro
accessBundleId: personalValues.accessBundleId,
accessBundleName: personalValues.accessBundleName,
serviceId: personalValues.serviceId,
- serviceName: personalValues.serviceName
+ serviceName: personalValues.serviceName,
+ credentialType: personalValues.credentialType
}
}
});
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 0c9f224904..f1fd5aa825 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
@@ -61,7 +61,11 @@ import {
} from "../agent-vault-personal-value/agent-vault-personal-value-fns";
import { TAgentVaultPersonalValueServiceFactory } from "../agent-vault-personal-value/agent-vault-personal-value-service";
import { TAgentVaultVariableDALFactory } from "../agent-vault-variable/agent-vault-variable-dal";
-import { TAgentVaultAccessBundleActorRef, TAgentVaultAccessBundleDALFactory } from "./agent-vault-access-bundle-dal";
+import {
+ TAgentVaultAccessBundleActorRef,
+ TAgentVaultAccessBundleDALFactory,
+ TAgentVaultAccessBundleListRow
+} from "./agent-vault-access-bundle-dal";
import {
TAddMembersDTO,
TAgentVaultBasicMemberField,
@@ -443,7 +447,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
const missing = findVariableKeys(text).find((key) => !idOfKey.has(key));
if (missing) {
throw new BadRequestError({
- message: `${label} uses ${toVariableReference(missing)}, but Agent Vault has no variable named '${missing}'. Add it under Variables, or correct the name.`
+ message: `${label} uses ${toVariableReference(missing)}, but there's no global variable named '${missing}'. Add it under Variables, or correct the name.`
});
}
});
@@ -586,8 +590,8 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
return { bundle, ...reachability };
};
- // Setup is counted over the bundles granted to the caller, the ones they take on. An admin reaches every bundle,
- // but one they were never granted asks nothing of them until they open it.
+ // Setup is counted over every bundle the caller reaches, since an admin can start a session on one they were never
+ // granted. isGranted lets the sidebar nag only about the bundles they take on.
const listAccessBundles = async ({ projectId, ctx, requiresSetup, ...page }: TListAccessBundlesDTO) => {
const { permission, accessBundleIds, grantedAccessBundleIds } = await getAgentVaultGrantedReachability(
{ permissionService, membershipDAL },
@@ -599,9 +603,10 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
);
const owner = ownerOrNullOf(ctx);
- const pendingByBundleOf = async (bundleIds: string[]) => {
+ const granted = new Set(grantedAccessBundleIds);
+ const pendingByBundleOf = async (bundleIds: string[] | null) => {
const byBundle = new Map<string, { id: string; name: string }[]>();
- if (!owner || !bundleIds.length) return byBundle;
+ if (!owner || bundleIds?.length === 0) return byBundle;
const statuses = await agentVaultPersonalValueService.findStatusesForOwner({
projectId,
owner,
@@ -618,23 +623,26 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
);
return byBundle;
};
+ const withSetup = (
+ accessBundles: TAgentVaultAccessBundleListRow[],
+ pendingByBundle: Map<string, { id: string; name: string }[]>
+ ) =>
+ accessBundles.map((bundle) => ({
+ ...bundle,
+ isGranted: granted.has(bundle.id),
+ servicesRequiringSetup: pendingByBundle.get(bundle.id) ?? []
+ }));
- // Either filter needs every granted bundle's status before it can page; the plain list only needs the page's.
+ // Either filter needs every reachable bundle's status before it can page; the plain list only needs the page's.
if (requiresSetup !== undefined) {
- const pendingByBundle = await pendingByBundleOf(grantedAccessBundleIds);
+ const pendingByBundle = await pendingByBundleOf(accessBundleIds);
const pendingIds = [...pendingByBundle.keys()];
const { accessBundles, totalCount } = await agentVaultAccessBundleDAL.findForList({
projectId,
...(requiresSetup ? { accessBundleIds: pendingIds } : { accessBundleIds, excludeAccessBundleIds: pendingIds }),
...page
});
- return {
- accessBundles: accessBundles.map((bundle) => ({
- ...bundle,
- servicesRequiringSetup: pendingByBundle.get(bundle.id) ?? []
- })),
- totalCount
- };
+ return { accessBundles: withSetup(accessBundles, pendingByBundle), totalCount };
}
const { accessBundles, totalCount } = await agentVaultAccessBundleDAL.findForList({
@@ -642,17 +650,8 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
accessBundleIds,
...page
});
- const granted = new Set(grantedAccessBundleIds);
- const pendingByBundle = await pendingByBundleOf(
- accessBundles.map((bundle) => bundle.id).filter((id) => granted.has(id))
- );
- return {
- accessBundles: accessBundles.map((bundle) => ({
- ...bundle,
- servicesRequiringSetup: pendingByBundle.get(bundle.id) ?? []
- })),
- totalCount
- };
+ const pendingByBundle = await pendingByBundleOf(accessBundles.map((bundle) => bundle.id));
+ return { accessBundles: withSetup(accessBundles, pendingByBundle), totalCount };
};
const getAccessBundleById = async (dto: TGetAccessBundleDTO) => {
@@ -787,11 +786,13 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
ProjectPermissionSub.AgentVaultAccessBundles
);
- // Bundle row first: its DELETE holds the row lock addMember takes. Roles cascade.
+ // Bundle row first, for the row lock addMember takes. Then the grants before the bundle's own delete, which
+ // cascades to its services' personal values: a removal from Agent Vault deletes grants and then those values,
+ // and taking them in the same order is what keeps the two from deadlocking. Roles cascade with the grants.
return agentVaultAccessBundleDAL.transaction(async (tx) => {
- const deleted = await agentVaultAccessBundleDAL.deleteById(bundle.id, tx);
+ await agentVaultAccessBundleDAL.lockByIdInProject({ id: bundle.id, projectId: rest.projectId }, tx);
await membershipDAL.delete(bundleScope(rest.projectId, bundle.id), tx);
- return deleted;
+ return agentVaultAccessBundleDAL.deleteById(bundle.id, tx);
});
};
diff --git a/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.test.ts b/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.test.ts
index 5029870538..09c85d46ee 100644
--- a/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.test.ts
+++ b/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.test.ts
@@ -189,6 +189,11 @@ describe("agentVaultMembership guards", () => {
await service.revokeProductMembers({ projectId: PROJECT_ID, ...addIds, ctx });
expect(deps.membershipDAL.delete).toHaveBeenCalledWith({ $in: { id: ["mem-1"] } }, expect.anything());
+ // Leaving Agent Vault loses every bundle, so the cleanup covers the whole project for this identity.
+ expect(deps.agentVaultPersonalValueDAL.deleteForActorsWithoutGrant).toHaveBeenCalledWith(
+ { projectId: PROJECT_ID, accessBundleId: undefined, userIds: [], identityIds: [IDENTITY_ID] },
+ expect.anything()
+ );
});
// A sub-organization reaches one of its parent's groups through a membership of its own, and the group
@@ -407,6 +412,11 @@ describe("agentVaultMembership guards", () => {
[{ membershipId: "mem-1", role: ProjectMembershipRole.Member }],
expect.anything()
);
+ // A demoted admin no longer reaches the bundles they hold no grant on.
+ expect(deps.agentVaultPersonalValueDAL.deleteForActorsWithoutGrant).toHaveBeenCalledWith(
+ { projectId: PROJECT_ID, accessBundleId: undefined, userIds: [], identityIds: [IDENTITY_ID] },
+ expect.anything()
+ );
});
test("skips a member who already has the role instead of rewriting it", async () => {
@@ -462,6 +472,8 @@ describe("agentVaultMembership guards", () => {
[{ membershipId: "mem-identity", role: ProjectMembershipRole.Admin }],
expect.anything()
);
+ // A promotion takes nothing away, so nothing is cleared.
+ expect(deps.agentVaultPersonalValueDAL.deleteForActorsWithoutGrant).not.toHaveBeenCalled();
});
test("refuses one batch that would demote every remaining admin", async () => {
diff --git a/backend/src/ee/services/agent-vault-personal-value/agent-vault-personal-value-service.ts b/backend/src/ee/services/agent-vault-personal-value/agent-vault-personal-value-service.ts
index 29831ff6c8..d70e30c5ad 100644
--- a/backend/src/ee/services/agent-vault-personal-value/agent-vault-personal-value-service.ts
+++ b/backend/src/ee/services/agent-vault-personal-value/agent-vault-personal-value-service.ts
@@ -60,7 +60,7 @@ const fieldName = (credentialType: string, field: TAgentVaultMemberProvidedField
};
const SERVICE_CHANGED_DURING_SAVE_MESSAGE =
- "An admin changed which values this service takes from you while you were saving. Reload the service and save again.";
+ "An admin changed this service's credential while you were setting up your values. Reload the service and save again.";
const VARIABLE_DELETED_DURING_SAVE_MESSAGE =
"A variable one of your values uses was deleted while it was being saved. Check its variable references and save again.";
@@ -159,7 +159,7 @@ export const agentVaultPersonalValueServiceFactory = ({
const findStatusesForOwner = (args: {
projectId: string;
owner: TAgentVaultOwner;
- accessBundleIds: string[];
+ accessBundleIds: string[] | null;
withVariableReferences?: boolean;
}) => loadServices(args);
@@ -178,8 +178,11 @@ export const agentVaultPersonalValueServiceFactory = ({
return { ...caller, service };
};
- const setPersonalValues = async ({ values, ...dto }: TSetPersonalValuesDTO) => {
+ const setPersonalValues = async ({ values, credentialType, ...dto }: TSetPersonalValuesDTO) => {
const { owner, service, isAdmin } = await findReachableService(dto);
+ if (credentialType && credentialType !== service.credentialType) {
+ throw new ConflictError({ message: SERVICE_CHANGED_DURING_SAVE_MESSAGE });
+ }
const memberProvidedFields = (service.memberProvidedFields ?? []) as TAgentVaultMemberProvidedField[];
if (!memberProvidedFields.length) {
@@ -210,7 +213,7 @@ export const agentVaultPersonalValueServiceFactory = ({
const unknown = findVariableKeys(value).find((key) => !idOfKey.has(key));
if (unknown) {
throw new BadRequestError({
- message: `Your ${name(field)} uses ${toVariableReference(unknown)}, but you have no personal variable named '${unknown}'. Add it under Variables, or correct the name.`
+ message: `Your ${name(field)} uses ${toVariableReference(unknown)}, but you have no personal variable named '${unknown}'. Add it as a personal variable, or correct the name.`
});
}
});
diff --git a/backend/src/ee/services/agent-vault-personal-value/agent-vault-personal-value-types.ts b/backend/src/ee/services/agent-vault-personal-value/agent-vault-personal-value-types.ts
index 2fc3fd60e7..4f2f1a3f53 100644
--- a/backend/src/ee/services/agent-vault-personal-value/agent-vault-personal-value-types.ts
+++ b/backend/src/ee/services/agent-vault-personal-value/agent-vault-personal-value-types.ts
@@ -1,8 +1,11 @@
-import { TAgentVaultMemberProvidedField } from "../agent-vault/agent-vault-enums";
+import { AgentVaultCredentialType, TAgentVaultMemberProvidedField } from "../agent-vault/agent-vault-enums";
import { TAgentVaultProjectScoped } from "../agent-vault-access-bundle/agent-vault-access-bundle-types";
export type TPersonalValuesByServiceDTO = TAgentVaultProjectScoped & { accessBundleId: string; serviceId: string };
export type TSetPersonalValuesDTO = TPersonalValuesByServiceDTO & {
values: { field: TAgentVaultMemberProvidedField; value: string }[];
+ // The type the caller's copy of the service shows, so a save made against a stale copy fails instead of storing
+ // a password as a token.
+ credentialType?: AgentVaultCredentialType;
};
diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts
index d423467940..c0dbce99dd 100644
--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts
+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts
@@ -803,7 +803,7 @@ export const agentVaultProxyServiceFactory = ({
const sessionLogs = $sessionLogs();
logger.info(
- `agentVaultResolve: resolved [sessionId=${session.id}] [proxyId=${proxyId}] [services=${services.length}]`
+ `agentVaultResolve: resolved [sessionId=${session.id}] [proxyId=${proxyId}] [services=${services.length}] [personalValuesMissing=${services.filter((service) => service.personalValuesMissing).length}]`
);
return {
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 c432caadd5..0ce7692abb 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
@@ -15,8 +15,9 @@ export type TAgentVaultVariable = Omit<TAgentVaultVariables, "accessBundleId">;
export type TAgentVaultVariableOrderBy = "key" | "serviceCount";
-// `owner: null` is the global variables; an owner is that user's or identity's personal ones. Every read and lock
-// names one, so a global lookup never matches a personal key and the other way round.
+// `owner: null` is the global variables; an owner is that user's or identity's personal ones. Every read and lock by
+// key or for a list names one, so a global lookup never matches a personal key and the other way round. The by-id
+// reads take any owner, and the service checks it.
export type TAgentVaultVariableOwnerScope = { projectId: string; owner: TAgentVaultOwner | null };
// Each owner is one scope to list, null the global one: a list can span both for an admin.
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 82c90bd4fb..8624a6f3b3 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
@@ -213,8 +213,8 @@ export const agentVaultVariableServiceFactory = ({
.join(", ");
if (owner) {
return services.length === 1
- ? `The variable '${key}' is used by your personal values for the service ${names}. Change those values before deleting it.`
- : `The variable '${key}' is used by your personal values for the services ${names}. Change those values before deleting it.`;
+ ? `The variable '${key}' is used by your personal values for the service ${names}. Remove it from the service before you delete it.`
+ : `The variable '${key}' is used by your personal values for the services ${names}. Remove it from those services before you delete it.`;
}
return services.length === 1
? `The variable '${key}' is used by the service ${names}. Remove it from that service before deleting it.`
@@ -276,8 +276,8 @@ export const agentVaultVariableServiceFactory = ({
if (existing.length >= cap) {
throw new BadRequestError({
message: owner
- ? `You can keep at most ${cap} variables in Agent Vault. Delete one that none of your values use first.`
- : `Agent Vault can hold at most ${cap} global variables. Delete one that no service uses first.`
+ ? `You can keep at most ${cap} personal variables. Delete an unused one first.`
+ : `Agent Vault can hold at most ${cap} global variables. Delete an unused one first.`
});
}
@@ -383,7 +383,7 @@ export const agentVaultVariableServiceFactory = ({
if (hasPostgresErrorCode(err, DatabaseErrorCode.ForeignKeyViolation)) {
throw new ConflictError({
message: scope.owner
- ? "One of your values still uses this variable. Change every value that uses it, then delete it."
+ ? "One of your personal values still uses this variable. Remove it from every service that uses it, then delete it."
: "This variable is still used by a service. Remove it from every service that uses it, then delete it."
});
}
diff --git a/backend/src/ee/services/agent-vault/CLAUDE.md b/backend/src/ee/services/agent-vault/CLAUDE.md
index 57427accb2..a2e9d4dde5 100644
--- a/backend/src/ee/services/agent-vault/CLAUDE.md
+++ b/backend/src/ee/services/agent-vault/CLAUDE.md
@@ -179,10 +179,10 @@ header" is the name in every layer; unqualified "header" means the credential's
## Variables
-A variable is a key and a sealed value on the Agent Vault project, so every bundle's services share one set and keys
-are unique per project. A service uses one as `{{KEY}}` in its token, username, password, a custom header value or a
-substitution value. Nothing else takes one: a host pattern, method or
-path decides what a service can reach, so it stays literal.
+A global variable is a key and a sealed value on the Agent Vault project, so every bundle's services share one set
+and global keys are unique per project (personal variables are covered under Member-provided values). A service uses
+one as `{{KEY}}` in its token, username, password, a custom header value or a substitution value. Nothing else takes
+one: a host pattern, method or 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
@@ -238,7 +238,7 @@ path decides what a service can reach, so it stays literal.
query can land on a different replica. An id with no variable behind it on either stays as text and is
logged rather than dropping the service, which would also drop the service's method and path restrictions.
Values saved before variables existed hold no id tokens, so they pass through untouched.
-- Global variables are admin only, reads included: their routes check `Edit` on access bundles, which a member lacks,
+- Global variables are admin only, reads included: the service checks `Edit` on access bundles, which a member lacks,
and the bundle read gives a member its services without `variableReferences` (left out, not empty, since
an empty list would claim they use none). Every value is sealed and no response but the value route returns
one. That route is a GET with no-store headers and one audit event per read.
@@ -247,23 +247,25 @@ path decides what a service can reach, so it stays literal.
An admin can leave a credential field to each member: the bearer token, or either half of a basic credential
(`memberProvidedFields` on the service, named like variable references: `credential-value` is a token or a password,
-`credential-username` a username). Custom header and substitution values can't be member-provided yet, but every
-personal-value shape already carries the reference tables' target columns and field descriptors, so they can join
-without a migration or an API change. Each actor saves their own **personal values** for the service, one row per
-field, and a session uses the values of whoever it belongs to. Every actor, admins included, also keeps **personal
-variables**, rows of `agent_vault_variables` with an owner, that only their own personal values can reference.
-
-- **The column is NULL, never `{}`, for a credential the admin sets in full**, like `allowedMethods`. The
- service's sealed secret holds only the admin's fields, so a bearer token left to members stores no secret at
- all and the column is NULL. Code that reads `encryptedCredential` NULL as passthrough has to check
+`credential-username` a username). Custom header and substitution values can't be member-provided yet. The personal
+value tables already carry the reference tables' target columns, but adding them still needs the service's check
+constraint and the API's field enum widened. Each actor saves their own **personal values** for the service, one row
+per field, and a session uses the values of whoever it belongs to. Every actor, admins included, also keeps
+**personal variables**, rows of `agent_vault_variables` with an owner, that only their own personal values can
+reference.
+
+- **`memberProvidedFields` is NULL, never `{}`, for a credential the admin sets in full**, like `allowedMethods`. The
+ service's sealed secret holds only the admin's fields, so a bearer token left to members stores no secret at all
+ and `encryptedCredential` is NULL. Code that reads `encryptedCredential` NULL as passthrough has to check
`memberProvidedFields` first.
- **One variables resource, two scopes.** `scope` on `/agent-vault/variables` (`global` or `personal`) picks the list
and is required for a new one; a list without it returns everything the caller can see (their own, plus the global
- ones for an admin), and the service sheet's picker asks for `global` explicitly. Every variable read and lock in
- the DAL takes an owner (`null` for global) so a global lookup never matches a personal key, and resolve expands
- each kind only against its own. By id, a variable the caller may not act on is a 404, never a 403: someone else's
- personal one, and a global one for a member. Global keys are unique per project (500 cap), personal ones per owner
- (100 cap), each enforced by a partial unique index plus an advisory lock per project or per owner.
+ ones for an admin), and the service sheet's picker asks for `global` explicitly. Every variable read and lock by
+ key or for a list takes an owner (`null` for global), so a global lookup never matches a personal key, and resolve
+ expands each kind only against its own. The by-id reads and locks take any owner, and the service checks it. By id,
+ a variable the caller may not act on is a 404, never a 403: someone else's personal one, and a global one for a
+ member. Global keys are unique per project (500 cap), personal ones per owner (100 cap), each enforced by a partial
+ unique index plus an advisory lock per project or per owner.
- **Everything personal is scoped to the caller, never to an id the caller sends.** No route names another actor,
so an admin can't list, read or set anyone else's variables or values. The owner is a user or a machine identity
(`ownerOf`); the UI only covers users for now, but resolve and the API already work for an identity's own
@@ -286,13 +288,17 @@ variables**, rows of `agent_vault_variables` with an owner, that only their own
the new one.
- **Losing a bundle through Agent Vault clears what an actor saved for its services**
(`clearPersonalValuesAfterRevoke`). It runs on a bundle revoke, on removal from Agent Vault, and on a demotion from
- admin, for the actors named and the members of a named group, after that change is written. It skips anyone who
- still holds the bundle through another grant, and anyone who is still a project admin, since an admin reaches every
- bundle. Platform paths (group removal, a lapsed role, project, org or SCIM removal) don't run it, so values can
- outlive the grant there and return with a later one. They are only ever the same actor's, and resolve still checks
- reach. Deleting a personal variable also clears the owner's values on bundles they no longer reach, which otherwise
- would hold the variable in place with nothing able to edit them. Personal variables survive all of this, and their
- Used By lists only the bundles the owner still reaches.
+ admin, for the actors named and the members of a named group, after that change is written. It takes the project's
+ `ClearAgentVaultPersonalValues` advisory lock last, after those writes, so of two changes that each leave the
+ other's access in place (a demotion and the revoke of the last grant) the second checks against the first once
+ committed. It skips anyone who still holds the bundle through another grant, and anyone who is still a project
+ admin, since an admin reaches every bundle. Platform paths don't run it: group removal, a lapsed role, org or SCIM
+ removal, and the generic project membership routes (role change, deactivate, remove from project, leave, and their
+ identity and group forms, which also reach the Agent Vault project), so values can outlive the grant there and
+ return with a later one. They are only ever the same actor's, and resolve still checks reach. Deleting a personal
+ variable also clears the owner's values on bundles they no longer reach, which otherwise would hold the variable in
+ place with nothing able to edit them. Personal variables survive all of this, and their Used By lists only the
+ bundles the owner still reaches.
- Personal variables follow the global variables' reference rules: sealed text names them by id, a reference row
per personal value (`agent_vault_personal_value_references`, a deferred foreign key), the delete takes the variable
row `FOR UPDATE` and a personal values save takes the rows it references `FOR SHARE`. Used By on a variable reads
@@ -302,8 +308,9 @@ variables**, rows of `agent_vault_variables` with an owner, that only their own
Reads ride along: the bundle read puts the caller's status on each service (`personalValues`, null when nothing
is member-provided), and the bundle list gives `servicesRequiringSetup` (`{ id, name }`) per bundle plus a
`requiresSetup` filter for the sidebar and banners (`false` is the rest of what the caller reaches). Both count
- only the bundles granted to the caller, so an admin isn't nagged about bundles they reach only by role; the
- bundle read still shows them.
+ every bundle the caller reaches, because an admin can start a session on one they were never granted. Each
+ list item also carries `isGranted`, and the sidebar warns only about granted bundles, so an admin isn't nagged
+ in the nav about bundles they reach only by role.
## Credentials at rest
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index acec6d9375..fb0084a1b6 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -6648,6 +6648,8 @@ interface AgentVaultPersonalValuesSetEvent {
accessBundleName: string;
serviceId: string;
serviceName: string;
+ // Which credential the fields belong to: credential-value is a token for bearer and a password for basic.
+ credentialType: string;
// The fields this update set. A field it left out kept its saved value.
fields: string[];
variableKeys: string[];
@@ -6661,6 +6663,7 @@ interface AgentVaultPersonalValuesDeleteEvent {
accessBundleName: string;
serviceId: string;
serviceName: string;
+ credentialType: string;
};
}
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 8a47267b51..295f5cb15b 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -4484,9 +4484,11 @@ export const AGENT_VAULT = {
offset: "How many access bundles to skip.",
hostPatterns: "Every host pattern the access bundle's services cover.",
requiresSetup:
- "true lists only the access bundles granted to you, directly or through a group, that have services still requiring your personal values. false lists the rest of the access bundles you can reach. Omit to list them all.",
+ "true lists only the access bundles you can reach that have services still requiring your personal values. false lists the rest of them. Omit to list them all.",
+ isGranted:
+ "Whether the access bundle is granted to you, directly or through a group. false for one you reach only as an admin.",
servicesRequiringSetup:
- "The services in this access bundle that still require your personal values. Counted only for access bundles granted to you, so empty for one you reach only as an admin.",
+ "The services in this access bundle that still require your personal values.",
servicesRequiringSetupId: "The ID of the service, for setting your personal values on it.",
servicesRequiringSetupName: "The name of the service."
},
@@ -4543,6 +4545,8 @@ export const AGENT_VAULT = {
"The credential fields each member sets for themselves: credential-value (a bearer token or a basic password) and credential-username. Empty when the admin sets the whole credential."
},
PERSONAL_VALUE: {
+ credentialType:
+ "The credential type you expect the service to have. If it no longer matches, the request fails with a 409.",
personalValues:
"Your personal values for the service, or null if the service leaves no fields to its members. Only you can see these, and a stored value never comes back.",
isConfigured:
diff --git a/docs/documentation/platform/agent-vault/proxies.mdx b/docs/documentation/platform/agent-vault/proxies.mdx
index 7dcf08d0f0..fcb9d0d74a 100644
--- a/docs/documentation/platform/agent-vault/proxies.mdx
+++ b/docs/documentation/platform/agent-vault/proxies.mdx
@@ -185,7 +185,7 @@ The proxy also returns a 403 for:
- A request to a port the service's [host pattern](/documentation/platform/agent-vault/services#host-patterns) doesn't name, such as `example.com:8443` for a service on `example.com`, which only covers port `443`
- A request that breaks the service's [method or path rules](/documentation/platform/agent-vault/services#methods-and-paths), under either traffic policy
-- A request to a service that needs [your personal values](/documentation/platform/agent-vault/access-bundles#set-up-your-personal-values), before you set them up
+- A request to a service that needs the session owner's [personal values](/documentation/platform/agent-vault/access-bundles#set-up-your-personal-values), before they set them up
### Exceptions
diff --git a/docs/documentation/platform/agent-vault/services.mdx b/docs/documentation/platform/agent-vault/services.mdx
index 6396b805ed..9e7414b2b9 100644
--- a/docs/documentation/platform/agent-vault/services.mdx
+++ b/docs/documentation/platform/agent-vault/services.mdx
@@ -72,7 +72,7 @@ For **Bearer** and **Basic** services, if the agent's request already carries a
## Member-provided values
-By default, you set the whole credential and every session uses it. If each member should call the API with their own token or login, such as a personal API key, you can make that part of the credential member provided. Each member then sets a personal value, and a session uses the personal value of the member who created the session.
+By default, you set the whole credential and every session uses it. If each member should call the API with their own token or login, such as a personal API key, you can make that part of the credential member provided. Each member then [sets a personal value](/documentation/platform/agent-vault/access-bundles#set-up-your-personal-values), and a session uses the personal value of the member who created the session.
You can make these credential fields member provided:
@@ -97,7 +97,7 @@ To make a field member provided:
If you change the credential type, each member has to set up their personal values for the service again.
</Warning>
-Until a member [sets up their personal values](/documentation/platform/agent-vault/access-bundles#set-up-your-personal-values), the proxy refuses their sessions' requests to the service with a `403` response. Requests to the bundle's other services still go through.
+Until a member sets up their personal values, the proxy refuses their sessions' requests to the service with a `403` response. Requests to the bundle's other services still go through.
## Host patterns
diff --git a/docs/documentation/platform/agent-vault/variables.mdx b/docs/documentation/platform/agent-vault/variables.mdx
index 8b1940296c..c6c4508b26 100644
--- a/docs/documentation/platform/agent-vault/variables.mdx
+++ b/docs/documentation/platform/agent-vault/variables.mdx
@@ -3,7 +3,7 @@ title: "Variables"
description: "Values you store once and use in any service in Agent Vault."
---
-A variable is a value that you can use in any [service](/documentation/platform/agent-vault/services) in Agent Vault, whichever [access bundle](/documentation/platform/agent-vault/access-bundles) the service is in. You define the variable once and give it a key, such as `GITHUB_TOKEN`. Then, any service can use the variable by referencing the key within double braces: `{{GITHUB_TOKEN}}`.
+A global variable is a value that you can use in any [service](/documentation/platform/agent-vault/services) in Agent Vault, whichever [access bundle](/documentation/platform/agent-vault/access-bundles) the service is in. You define the variable once and give it a key, such as `GITHUB_TOKEN`. Then, any service can use the variable by referencing the key within double braces: `{{GITHUB_TOKEN}}`.
When an agent sends a request, the [proxy](/documentation/platform/agent-vault/proxies) replaces each reference with the variable's value.
@@ -17,7 +17,7 @@ To add a variable:
<Steps>
<Step>
- In Agent Vault, go to **Variables** > **Global Variables**.
+ In Agent Vault, go to **Variables** and select the **Global Variables** tab.
<Frame>
<img src="/images/platform/agent-vault/variables-empty.png" alt="The Variables page with no variables and an Add Variable button" />
diff --git a/frontend/src/components/agent-vault/PersonalValuesDialog.tsx b/frontend/src/components/agent-vault/PersonalValuesDialog.tsx
index 32ae6e7968..730ebedec1 100644
--- a/frontend/src/components/agent-vault/PersonalValuesDialog.tsx
+++ b/frontend/src/components/agent-vault/PersonalValuesDialog.tsx
@@ -38,6 +38,7 @@ import {
AgentVaultVariableScope,
TAgentVaultMemberProvidedField,
useDeleteAgentVaultPersonalValues,
+ useGetAgentVaultAccessBundle,
useListAgentVaultVariables,
useSetAgentVaultPersonalValues
} from "@app/hooks/api/agentVault";
@@ -135,7 +136,14 @@ type Props = {
*/
export const PersonalValuesDialog = ({ target, onOpenChange }: Props) => {
const isOpen = Boolean(target);
- const service = target?.service;
+ // Read from the bundle query rather than the copy the dialog opened with, so a refetch after an admin changes the
+ // service (a save answered 409) shows the service as it is now.
+ const { data: liveBundle } = useGetAgentVaultAccessBundle(
+ isOpen ? (target?.service.accessBundleId ?? "") : ""
+ );
+ const service =
+ liveBundle?.services.find((candidate) => candidate.id === target?.service.id) ??
+ target?.service;
const personalValues = service?.personalValues;
const setValues = useSetAgentVaultPersonalValues();
const deleteValues = useDeleteAgentVaultPersonalValues();
@@ -182,9 +190,10 @@ export const PersonalValuesDialog = ({ target, onOpenChange }: Props) => {
formState: { isSubmitting }
} = formMethods;
+ // A new type gives the same fields a different meaning (a password becomes a token), so what was typed goes.
useEffect(() => {
if (isOpen) reset({ secret: "", username: "" });
- }, [isOpen, service?.id, reset]);
+ }, [isOpen, service?.id, service?.credential.type, reset]);
// One dialog for every field, settled once it has closed, as in the service sheet.
const [isRemoveOpen, setIsRemoveOpen] = useState(false);
@@ -242,6 +251,7 @@ export const PersonalValuesDialog = ({ target, onOpenChange }: Props) => {
await setValues.mutateAsync({
accessBundleId: service.accessBundleId,
serviceId: service.id,
+ credentialType: service.credential.type,
// A blank field keeps its saved value, so only the ones typed are sent.
values: fields
.map((field) => ({
@@ -280,7 +290,7 @@ export const PersonalValuesDialog = ({ target, onOpenChange }: Props) => {
return (
<Dialog open={isOpen} onOpenChange={onOpenChange}>
- <DialogContent>
+ <DialogContent isPending={isSubmitting}>
<DialogHeader>
<DialogTitle>
{personalValues?.isConfigured ? "Update" : "Set Up"} Personal Values for {service?.name}
@@ -356,7 +366,12 @@ export const PersonalValuesDialog = ({ target, onOpenChange }: Props) => {
<span />
)}
<div className="flex gap-2">
- <Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>
+ <Button
+ type="button"
+ variant="ghost"
+ isDisabled={isSubmitting}
+ onClick={() => onOpenChange(false)}
+ >
Cancel
</Button>
<Button
@@ -382,7 +397,7 @@ export const PersonalValuesDialog = ({ target, onOpenChange }: Props) => {
<AlertDialogHeader>
<AlertDialogTitle>Remove your personal {service?.name} values?</AlertDialogTitle>
<AlertDialogDescription>
- Until you set it up again, {service?.name} rejects requests from your sessions. Your
+ Until you set them up again, your sessions can&apos;t reach {service?.name}. Your
variables are kept.
</AlertDialogDescription>
</AlertDialogHeader>
diff --git a/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx b/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx
index 012963eea1..56fcece513 100644
--- a/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx
+++ b/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx
@@ -389,6 +389,23 @@ export const CredentialFields = ({ storedType, storedMemberFields = [] }: Props)
if (valid.length !== memberProvidedFields.length) setValue("memberProvidedFields", valid);
}, [credentialType, memberProvidedFields, setValue]);
+ // Switching away and back to the stored type changes nothing, so the stored values and toggles come back as they
+ // were rather than staying cleared by the switch.
+ const previousType = useRef(credentialType);
+ useEffect(() => {
+ const wasType = previousType.current;
+ previousType.current = credentialType;
+ if (!storedType || wasType === credentialType || credentialType !== storedType) return;
+ setValue("memberProvidedFields", storedMemberFields);
+ if (!storedMemberFields.includes(secretCredentialField)) setValue("secret", UNCHANGED_SECRET);
+ if (
+ credentialType === AgentVaultCredentialType.Basic &&
+ !storedMemberFields.includes(AgentVaultVariableReferenceField.CredentialUsername)
+ ) {
+ setValue("username", UNCHANGED_SECRET);
+ }
+ }, [credentialType, storedType, storedMemberFields, secretCredentialField, setValue]);
+
// Handing a field to members drops what was typed for it. Taking it back restores what is stored, if anything.
const setMemberProvided = (field: TAgentVaultMemberProvidedField, isOn: boolean) => {
const formField = FORM_FIELD_OF_CREDENTIAL_FIELD[field];
diff --git a/frontend/src/components/agent-vault/service-sheet/VariableSuggestions.tsx b/frontend/src/components/agent-vault/service-sheet/VariableSuggestions.tsx
index 0f5d94962c..8eae00ad7c 100644
--- a/frontend/src/components/agent-vault/service-sheet/VariableSuggestions.tsx
+++ b/frontend/src/components/agent-vault/service-sheet/VariableSuggestions.tsx
@@ -227,7 +227,7 @@ export const useVariableAutocomplete = ({
type TAutocomplete = ReturnType<typeof useVariableAutocomplete>;
const usedByLabel = (count: number) => {
- if (count === 0) return "Not used yet";
+ if (count === 0) return "Unused";
return `Used by ${count} service${count === 1 ? "" : "s"}`;
};
diff --git a/frontend/src/components/agent-vault/service-sheet/stepMeta.ts b/frontend/src/components/agent-vault/service-sheet/stepMeta.ts
index fa2991d96c..de84f58948 100644
--- a/frontend/src/components/agent-vault/service-sheet/stepMeta.ts
+++ b/frontend/src/components/agent-vault/service-sheet/stepMeta.ts
@@ -40,7 +40,7 @@ export const SERVICE_STEPS: StepMeta[] = [
rightDescription:
"Agents reach this service without ever holding the credential themselves. Custom headers go out on top of it, and a substitution swaps a placeholder your agent already sends for the real value.",
rightTip:
- "To use a global variable, type {{ in any value and pick it from the list. The proxy puts the variable's value in its place. For a member-provided field, each member sets their own value after the service is added, and can use their personal variables there."
+ "To use a global variable, type {{ in any value and pick it from the list. The proxy puts the variable's value in its place. For a member-provided field, each member sets their own value, and can use their personal variables there."
},
{
step: ServiceStep.Review,
diff --git a/frontend/src/helpers/agentVaultVariables.ts b/frontend/src/helpers/agentVaultVariables.ts
index e7cc7732d9..30f3a737c2 100644
--- a/frontend/src/helpers/agentVaultVariables.ts
+++ b/frontend/src/helpers/agentVaultVariables.ts
@@ -94,8 +94,8 @@ export const variableReferenceError = (
const missing = refs.find((ref) => missingKeys?.has(ref));
if (missing) {
return isPersonal
- ? `You have no personal variable named '${missing}'. Add it under Variables, or correct the name.`
- : `Agent Vault has no variable named '${missing}'. Add it under Variables, or correct the name.`;
+ ? `You have no personal variable named '${missing}'. Add it as a personal variable, or correct the name.`
+ : `There's no global variable named '${missing}'. Add it under Variables, or correct the name.`;
}
return null;
diff --git a/frontend/src/hooks/api/agentVault/mutations.tsx b/frontend/src/hooks/api/agentVault/mutations.tsx
index dd47ced47d..6659e70b8f 100644
--- a/frontend/src/hooks/api/agentVault/mutations.tsx
+++ b/frontend/src/hooks/api/agentVault/mutations.tsx
@@ -1,4 +1,5 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
+import axios from "axios";
import { apiRequest } from "@app/config/request";
import { useOrganization } from "@app/context";
@@ -492,7 +493,13 @@ export const useSetAgentVaultPersonalValues = () => {
return data.personalValues;
},
onSuccess: (_, { accessBundleId }) =>
- invalidatePersonalValues(queryClient, currentOrg.id, accessBundleId)
+ invalidatePersonalValues(queryClient, currentOrg.id, accessBundleId),
+ // The service changed under the dialog, so its copy is stale: reload it before the member saves again.
+ onError: (error, { accessBundleId }) => {
+ if (axios.isAxiosError(error) && error.response?.status === 409) {
+ invalidatePersonalValues(queryClient, currentOrg.id, accessBundleId).catch(() => undefined);
+ }
+ }
});
};
diff --git a/frontend/src/hooks/api/agentVault/queries.tsx b/frontend/src/hooks/api/agentVault/queries.tsx
index 64c7d06ec1..06ec33ce95 100644
--- a/frontend/src/hooks/api/agentVault/queries.tsx
+++ b/frontend/src/hooks/api/agentVault/queries.tsx
@@ -220,7 +220,7 @@ export const useListAgentVaultAccessBundles = (params: TListAgentVaultAccessBund
};
// The sidebar and the access bundle list ask the same question, so they share one cached answer. One page holds them
-// all in practice: it is only the bundles granted to the caller that still require their values.
+// all in practice: it is only the bundles the caller reaches that still require their values.
export const useListAgentVaultAccessBundlesRequiringSetup = () =>
useListAgentVaultAccessBundles({ requiresSetup: true, limit: 100 });
diff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.ts
index ded79b2421..bed4699bb2 100644
--- a/frontend/src/hooks/api/agentVault/types.ts
+++ b/frontend/src/hooks/api/agentVault/types.ts
@@ -207,7 +207,8 @@ export type TAgentVaultAccessBundleListItem = TAgentVaultAccessBundle & {
serviceCount: number;
memberCount: number;
hostPatterns: string[];
- // Counted over the bundles granted to the caller, so empty on one an admin reaches only by role.
+ // False on a bundle an admin reaches only by role.
+ isGranted: boolean;
servicesRequiringSetup: { id: string; name: string }[];
};
@@ -475,6 +476,8 @@ export type TSetAgentVaultPersonalValuesDTO = {
accessBundleId: string;
serviceId: string;
values: { field: TAgentVaultMemberProvidedField; value: string }[];
+ /** The type the dialog shows. If an admin changed it since, the save fails with a 409 instead of mislabeling a value. */
+ credentialType: AgentVaultCredentialType;
};
export type TDeleteAgentVaultPersonalValuesDTO = { accessBundleId: string; serviceId: string };
diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsx b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsx
index a4f34c68b1..149fe4c85c 100644
--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsx
+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsx
@@ -30,7 +30,8 @@ export const AgentVaultNav = ({ onSubmenuOpen }: { onSubmenuOpen: (submenu: Subm
const { data: sessionLogHealth } = useGetAgentVaultSessionLogHealth(isAdmin);
const { subscription } = useSubscription();
const { data: requiringSetup } = useListAgentVaultAccessBundlesRequiringSetup();
- const needsSetup = Boolean(requiringSetup?.totalCount);
+ // An admin can use any bundle, but the nav only nags about the ones granted to them.
+ const needsSetup = Boolean(requiringSetup?.accessBundles.some((bundle) => bundle.isGranted));
const accessItems: NavItem[] = [
{ label: "Sessions", icon: IdCard, pathSuffix: "sessions" },
diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/CreateSessionDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/CreateSessionDialog.tsx
index 4314f3034d..3d28b158bb 100644
--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/CreateSessionDialog.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/CreateSessionDialog.tsx
@@ -249,9 +249,9 @@ export const CreateSessionDialog = ({ isOpen, onOpenChange, onCreated }: Props)
</AlertTitle>
<AlertDescription>
<p>
- Until you set {needsSetup.length === 1 ? "it" : "them"} up,{" "}
- {needsSetup.length === 1 ? "it rejects" : "they reject"} requests from this
- session.
+ {needsSetup.length === 1
+ ? "Until you set it up, this session can't reach it."
+ : "Until you set them up, this session can't reach them."}
</p>
<ul className="mt-2 w-full divide-y divide-warning/15 rounded-md border border-warning/20">
{shownNeedsSetup.map((service) => (
diff --git a/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/DeleteVariableDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/DeleteVariableDialog.tsx
index b19c909362..cba818bd48 100644
--- a/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/DeleteVariableDialog.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/DeleteVariableDialog.tsx
@@ -46,7 +46,7 @@ export const DeleteVariableDialog = ({ variable, onOpenChange }: Props) => {
<AlertDialogTitle>Delete &quot;{variable?.key}&quot;</AlertDialogTitle>
<AlertDialogDescription>
{isInUse && isPersonal
- ? `${usedByServices.length === 1 ? "Your personal values for a service use" : `Your personal values for ${usedByServices.length} services use`} this variable. Change ${usedByServices.length === 1 ? "them" : "those values"} before you delete it.`
+ ? `${usedByServices.length === 1 ? "Your personal values for a service use" : `Your personal values for ${usedByServices.length} services use`} this variable. Remove it from ${usedByServices.length === 1 ? "the service" : "those services"} before you delete it.`
: null}
{isInUse && !isPersonal
? `${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.`
diff --git a/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/VariablesCard.tsx b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/VariablesCard.tsx
index e328c42120..ddbdff10fc 100644
--- a/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/VariablesCard.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/VariablesCard.tsx
@@ -358,8 +358,8 @@ export const VariablesCard = ({ scope = AgentVaultVariableScope.Global }: Props)
</TooltipTrigger>
<TooltipContent className="max-w-xs">
{isPersonal
- ? `You can keep at most ${maxVariables} variables in Agent Vault. Delete one that none of your values use first.`
- : `Agent Vault can hold at most ${maxVariables} variables. Delete one that no service uses first.`}
+ ? `You can keep at most ${maxVariables} personal variables. Delete an unused one first.`
+ : `Agent Vault can hold at most ${maxVariables} global variables. Delete an unused one first.`}
</TooltipContent>
</Tooltip>
) : (