Skip to content

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

fix(agent-vault): address Greptile review on personal values

Scott Wilsonf1aa62f5ea6e
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.ts
index 72b5d81ade..86009b140e 100644
--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts
+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts
@@ -241,6 +241,21 @@ const createMemberIdentity = async (name: string) => {
};
};
+// Resolves once a backend waits on a lock the given one holds: by then a request has done everything it
+// does before the lock and is queued behind it.
+const waitUntilBlockedBy = async (pid: number, attemptsLeft = 200): Promise<void> => {
+ const { rows } = await testDb.raw(
+ "select count(*)::int as waiting from pg_stat_activity where ? = any(pg_blocking_pids(pid))",
+ [pid]
+ );
+ if (rows[0].waiting > 0) return;
+ if (attemptsLeft === 0) throw new Error(`No request queued behind the lock held by backend ${pid}`);
+ await new Promise((resolve) => {
+ setTimeout(resolve, 25);
+ });
+ await waitUntilBlockedBy(pid, attemptsLeft - 1);
+};
+
// Enrollment only checks that it is a live CA. ECDSA P-256, because the FIPS image refuses Ed25519.
const createProxyCaPem = async () => {
const algorithm = { name: "ECDSA", namedCurve: "P-256", hash: "SHA-256" };
@@ -979,21 +994,6 @@ describe("Agent Vault V1 Router", async () => {
expect(actual.sort()).toEqual(expected.sort());
};
- // Resolves once a backend waits on a lock the given one holds: by then a request has done everything it
- // does before the lock and is queued behind it.
- const waitUntilBlockedBy = async (pid: number, attemptsLeft = 200): Promise<void> => {
- const { rows } = await testDb.raw(
- "select count(*)::int as waiting from pg_stat_activity where ? = any(pg_blocking_pids(pid))",
- [pid]
- );
- if (rows[0].waiting > 0) return;
- if (attemptsLeft === 0) throw new Error(`No request queued behind the lock held by backend ${pid}`);
- await new Promise((resolve) => {
- setTimeout(resolve, 25);
- });
- await waitUntilBlockedBy(pid, attemptsLeft - 1);
- };
-
test("a service uses a variable by key, and resolve puts the value in its place", async () => {
const bundle = await createAccessBundle("variables-resolve");
const token = await createVariable({ key: "GITHUB_TOKEN", value: "ghp_from_variable" });
@@ -2263,6 +2263,47 @@ describe("Agent Vault V1 Router", async () => {
}
});
+ test("an admin's save on a bundle they hold no grant on waits for a demotion, then 404s", async () => {
+ const bundle = await createAccessBundle("mp-admin-race");
+ const service = await createService(bundle.id, {
+ name: "vercel",
+ hostPattern: "api.vercel.com",
+ credential: { type: "bearer", memberProvidedFields: ["credential-value"] }
+ });
+
+ const admin = await createMemberIdentity(`mp-admin-race-${Date.now()}`);
+ try {
+ expect(
+ (await inject("PATCH", "/api/v1/agent-vault/members", { machineIdentityIds: [admin.id], role: "admin" }))
+ .statusCode
+ ).toBe(200);
+ const membership = await testDb("memberships").where({ scope: "project", actorIdentityId: admin.id }).first();
+
+ // What a demotion does: replace the admin role, and hold it until it commits.
+ const trx = await testDb.transaction();
+ let pending: ReturnType<typeof setValues> | undefined;
+ try {
+ const { rows } = await trx.raw("select pg_backend_pid() as pid");
+ await trx("membership_roles").where({ membershipId: membership.id }).delete();
+ await trx("membership_roles").insert({ membershipId: membership.id, role: "member" });
+
+ pending = setValues(admin.as, bundle.id, service.id, { "credential-value": "raced" });
+ await waitUntilBlockedBy(rows[0].pid);
+ await trx.commit();
+
+ expect((await pending).statusCode).toBe(404);
+ } catch (err) {
+ if (!trx.isCompleted()) await trx.rollback();
+ // Let the save finish before cleanup, so a failure here doesn't leave state for the tests after it.
+ await pending?.catch(() => undefined);
+ throw err;
+ }
+ expect(await testDb("agent_vault_personal_values").where({ identityId: admin.id })).toHaveLength(0);
+ } finally {
+ await admin.cleanup();
+ }
+ });
+
test("an admin is asked for values only on the bundles granted to them", async () => {
const ungranted = await createAccessBundle("mp-mine-ungranted");
const service = await createService(ungranted.id, {
diff --git a/backend/src/db/migrations/20261013120000_agent-vault-personal-values.ts b/backend/src/db/migrations/20261013120000_agent-vault-personal-values.ts
index fe1a690244..18553c8c8e 100644
--- a/backend/src/db/migrations/20261013120000_agent-vault-personal-values.ts
+++ b/backend/src/db/migrations/20261013120000_agent-vault-personal-values.ts
@@ -5,6 +5,7 @@ import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";
const PROJECT_KEY_UNIQUE = "agent_vault_variables_projectid_key_unique";
const GLOBAL_KEY_UNIQUE = "agent_vault_variables_global_key_unique";
+const SERVICE_REFERENCE_VARIABLE_FK = "agent_vault_service_variable_references_variableid_foreign";
const USER_KEY_UNIQUE = "agent_vault_variables_user_key_unique";
const IDENTITY_KEY_UNIQUE = "agent_vault_variables_identity_key_unique";
@@ -155,7 +156,15 @@ export async function down(knex: Knex): Promise<void> {
if (await knex.schema.hasColumn(TableName.AgentVaultVariable, "userId")) {
await knex.raw(`DROP VIEW IF EXISTS analytics.??`, [TableName.AgentVaultVariable]);
// Variables of one owner can't move into the global namespace, where their keys may clash.
- await knex(TableName.AgentVaultVariable).whereNotNull("userId").orWhereNotNull("identityId").delete();
+ await knex(TableName.AgentVaultVariable)
+ .where((owned) => {
+ void owned.whereNotNull("userId").orWhereNotNull("identityId");
+ })
+ .delete();
+ // The delete queues the deferred reference check, and Postgres won't alter a table with one pending. Run it now,
+ // then put the constraint back to deferred for the rest of the batch.
+ await knex.raw(`SET CONSTRAINTS ?? IMMEDIATE`, [SERVICE_REFERENCE_VARIABLE_FK]);
+ await knex.raw(`SET CONSTRAINTS ?? DEFERRED`, [SERVICE_REFERENCE_VARIABLE_FK]);
await knex.raw(`DROP INDEX IF EXISTS ??`, [GLOBAL_KEY_UNIQUE]);
await knex.raw(`DROP INDEX IF EXISTS ??`, [USER_KEY_UNIQUE]);
await knex.raw(`DROP INDEX IF EXISTS ??`, [IDENTITY_KEY_UNIQUE]);
diff --git a/backend/src/ee/services/agent-vault-personal-value/agent-vault-personal-value-dal.ts b/backend/src/ee/services/agent-vault-personal-value/agent-vault-personal-value-dal.ts
index a43abf50e7..3d59037558 100644
--- a/backend/src/ee/services/agent-vault-personal-value/agent-vault-personal-value-dal.ts
+++ b/backend/src/ee/services/agent-vault-personal-value/agent-vault-personal-value-dal.ts
@@ -278,6 +278,50 @@ export const agentVaultPersonalValueDALFactory = (db: TDbClient) => {
}
};
+ /**
+ * The owner's live project admin roles, direct or through a group they are in, taken FOR SHARE with their membership
+ * rows. A demotion or a removal deletes these rows in its own transaction, so this waits for one in flight and then
+ * sees the rows gone.
+ */
+ const lockAdminRolesForOwner = async (
+ { projectId, owner }: { projectId: string; owner: TAgentVaultOwner },
+ tx: Knex
+ ): Promise<{ id: string }[]> => {
+ try {
+ return (await tx(TableName.Membership)
+ .join(TableName.MembershipRole, `${TableName.MembershipRole}.membershipId`, `${TableName.Membership}.id`)
+ .where(`${TableName.Membership}.scope`, AccessScope.Project)
+ .where(`${TableName.Membership}.scopeProjectId`, projectId)
+ .where(`${TableName.Membership}.isActive`, true)
+ .where(`${TableName.MembershipRole}.role`, ProjectMembershipRole.Admin)
+ .where((live) => {
+ void live
+ .where(`${TableName.MembershipRole}.isTemporary`, false)
+ .orWhere(`${TableName.MembershipRole}.temporaryAccessEndTime`, ">", tx.fn.now());
+ })
+ .where((holder) => {
+ void holder
+ .where(
+ owner.userId ? `${TableName.Membership}.actorUserId` : `${TableName.Membership}.actorIdentityId`,
+ (owner.userId ?? owner.identityId) as string
+ )
+ .orWhereIn(`${TableName.Membership}.actorGroupId`, function ownerGroups() {
+ if (owner.userId) {
+ void this.select("groupId").from(TableName.UserGroupMembership).where({ userId: owner.userId });
+ } else {
+ void this.select("groupId")
+ .from(TableName.IdentityGroupMembership)
+ .where({ identityId: owner.identityId as string });
+ }
+ });
+ })
+ .forShare()
+ .select(`${TableName.MembershipRole}.id`)) as { id: string }[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Lock agent vault admin roles for owner" });
+ }
+ };
+
// Every member's values for the service, except those for the fields still left to members.
const deleteForServiceExceptFields = async (
{ serviceId, keepFields }: { serviceId: string; keepFields: string[] },
@@ -301,7 +345,8 @@ export const agentVaultPersonalValueDALFactory = (db: TDbClient) => {
lockForOwnerAndService,
findForResolve,
deleteForActorsWithoutGrant,
- lockGrantsForOwner
+ lockGrantsForOwner,
+ lockAdminRolesForOwner
};
};
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 d9d603afd6..f4e421ad8a 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
@@ -237,15 +237,19 @@ export const agentVaultPersonalValueServiceFactory = ({
) {
throw new ConflictError({ message: SERVICE_CHANGED_DURING_SAVE_MESSAGE });
}
- // A member reaches the bundle only through a grant, and a revoke clears what they saved. Saving under the
- // grant's lock means a revoke can't land between the reach check above and this write and leave values
- // behind. An admin reaches every bundle without one.
- if (!isAdmin) {
- const grants = await agentVaultPersonalValueDAL.lockGrantsForOwner(
- { projectId: dto.projectId, accessBundleId: service.accessBundleId, owner },
- tx
- );
- if (!grants.length) throw new NotFoundError({ message: `Service with ID '${dto.serviceId}' not found` });
+ // A revoke, a removal or a demotion clears what the caller saved on bundles they lose. Saving under the lock
+ // of whatever grants the reach (a grant, or for an admin without one, their admin role) means none of those
+ // can land between the reach check above and this write and leave values behind.
+ const grants = await agentVaultPersonalValueDAL.lockGrantsForOwner(
+ { projectId: dto.projectId, accessBundleId: service.accessBundleId, owner },
+ tx
+ );
+ const adminRoles =
+ !grants.length && isAdmin
+ ? await agentVaultPersonalValueDAL.lockAdminRolesForOwner({ projectId: dto.projectId, owner }, tx)
+ : [];
+ if (!grants.length && !adminRoles.length) {
+ throw new NotFoundError({ message: `Service with ID '${dto.serviceId}' not found` });
}
// A field left out keeps its saved value, so a member adds a newly required field without retyping the rest.
diff --git a/backend/src/ee/services/agent-vault/CLAUDE.md b/backend/src/ee/services/agent-vault/CLAUDE.md
index d8e2b0e9b5..cc33f34708 100644
--- a/backend/src/ee/services/agent-vault/CLAUDE.md
+++ b/backend/src/ee/services/agent-vault/CLAUDE.md
@@ -265,7 +265,10 @@ variables**, rows of `agent_vault_variables` with an owner, that only their own
change); an older proxy that ignores the flag forwards the request without a credential, never with the admin's.
- **A save is a PATCH**: a field sent replaces that field's saved value, a field left out keeps it, and every
member-provided field must be set once it's applied. The save takes the service row `FOR SHARE` and re-checks
- the fields it validated against, so an admin changing them either waits for it or makes it 409.
+ the fields it validated against, so an admin changing them either waits for it or makes it 409. It also takes
+ whatever grants the caller's reach `FOR SHARE`: their grants on the bundle, or for an admin without one, their
+ admin role rows. A revoke, removal or demotion then either waits for the save and clears it, or lands first and
+ the save 404s.
- **A service update deletes only the values that no longer apply**, in the same transaction that writes the
service row: a credential type change deletes every member's values for the service, and taking a field back
from members deletes that field's. Adding a member-provided field keeps what members saved, and they add only
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 314cc5bbde..6b087e5972 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -4506,7 +4506,7 @@ export const AGENT_VAULT = {
bearerMemberProvidedFields:
"Leave the token to each member: send `credential-value` here and no `value`. Every member sets their own, and a session uses the token of whoever it belongs to. Omit on update to keep the current setting; send an empty list to set the token yourself again, which then needs a `value`. Changing this clears every member's saved values for the service.",
basicMemberProvidedFields:
- "The halves of the basic credential each member sets for themselves: `credential-username`, `credential-value` (the password) or both. Send no value for a half listed here. A session uses the values of whoever it belongs to. Omit on update to keep the current setting. Changing this clears every member's saved values for the service.",
+ "The halves of the basic credential each member sets for themselves: `credential-username`, `credential-value` (the password) or both. Send no value for a half listed here. A session uses the values of whoever it belongs to. Omit on update to keep the current setting. Adding a half keeps what members saved, and taking one back deletes only that half's values. Changing the credential type deletes every member's values for the service.",
memberProvidedFields:
"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."
},
diff --git a/docs/api-reference/endpoints/agent-vault-services/set-personal-values.mdx b/docs/api-reference/endpoints/agent-vault-services/set-personal-values.mdx
index 32a8fd3e0a..d567bc1def 100644
--- a/docs/api-reference/endpoints/agent-vault-services/set-personal-values.mdx
+++ b/docs/api-reference/endpoints/agent-vault-services/set-personal-values.mdx
@@ -1,4 +1,4 @@
---
title: "Set personal values"
-openapi: "PUT /api/v1/agent-vault/access-bundles/{accessBundleId}/services/{serviceId}/personal-values"
+openapi: "PATCH /api/v1/agent-vault/access-bundles/{accessBundleId}/services/{serviceId}/personal-values"
---
diff --git a/frontend/src/components/agent-vault/PersonalValuesDialog.tsx b/frontend/src/components/agent-vault/PersonalValuesDialog.tsx
index 7bd9be06fa..f7fb79808a 100644
--- a/frontend/src/components/agent-vault/PersonalValuesDialog.tsx
+++ b/frontend/src/components/agent-vault/PersonalValuesDialog.tsx
@@ -340,7 +340,7 @@ export const PersonalValuesDialog = ({ target, onOpenChange }: Props) => {
})}
<DialogFooter className="sm:justify-between">
- {personalValues?.isConfigured ? (
+ {savedFields.size > 0 ? (
<Button type="button" variant="danger" onClick={() => setIsRemoveOpen(true)}>
Remove
</Button>
diff --git a/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx b/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx
index d103c091c5..c760aa4831 100644
--- a/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx
+++ b/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx
@@ -29,7 +29,6 @@ import {
InputGroupAddon,
InputGroupButton,
InputGroupInput,
- Label,
Select,
SelectContent,
SelectItem,
@@ -298,7 +297,7 @@ const MemberProvidedToggle = ({
className="size-3.5 text-muted"
/>
</HoverCardTrigger>
- <HoverCardContent className="w-80 text-xs">
+ <HoverCardContent className="w-80">
<p>Choose who sets the {label.toLowerCase()} the proxy sends for this service.</p>
<ul className="mt-2 flex list-disc flex-col gap-1 pl-4">
<li>Off: you set the {label.toLowerCase()} here, and every session uses it.</li>
@@ -318,9 +317,7 @@ const MemberProvidedToggle = ({
</a>
</HoverCardContent>
</HoverCard>
- <Label htmlFor={id} className="text-xs font-normal text-muted">
- Member provided
- </Label>
+ <FieldLabel htmlFor={id}>Member provided</FieldLabel>
<Toggle id={id} size="sm" variant="av" checked={isOn} onCheckedChange={onChange} />
</div>
);