Skip to content

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

feat(agent-vault): offer only ungranted members in the access bundle grant picker

Scott Wilson49148eb450ab
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.ts
index d11d64b90c..65a30caa73 100644
--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts
+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts
@@ -2559,6 +2559,92 @@ describe("Agent Vault V1 Router", async () => {
expect(await testDb("membership_roles").where({ membershipId: grant.id })).toHaveLength(0);
});
+ test("available lists the members who could still be granted the bundle, and drops each as it is granted", async () => {
+ const projectId = await getProjectId();
+ const bundle = await createAccessBundle(`available-grantees-${Date.now()}`);
+ const other = await createAccessBundle(`available-grantees-other-${Date.now()}`);
+ const group = await createProjectGroup(projectId, "av-grantee-group", ProjectMembershipRole.Member);
+ const availableUrl = `/api/v1/agent-vault/access-bundles/${bundle.id}/members/available`;
+
+ const listAvailable = async (query = "") => {
+ const res = await inject("GET", `${availableUrl}${query ? `?${query}` : ""}`);
+ expect(res.statusCode).toBe(200);
+ return JSON.parse(res.payload) as {
+ members: { actor: { type: string; id: string } }[];
+ totalCount: number;
+ };
+ };
+
+ try {
+ const idsOf = (members: { actor: { id: string } }[]) => members.map((member) => member.actor.id);
+
+ // Candidates are the product's own members, and the bundle is new, so nobody holds it yet.
+ const before = await listAvailable("limit=100");
+ expect(idsOf(before.members)).toContain(group.id);
+
+ expect(
+ (await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, { groupIds: [group.id] }))
+ .statusCode
+ ).toBe(200);
+
+ const afterGrant = await listAvailable("limit=100");
+ expect(idsOf(afterGrant.members)).not.toContain(group.id);
+ expect(afterGrant.totalCount).toBe(before.totalCount - 1);
+
+ // The grant is per bundle, so holding one leaves the actor a candidate for every other.
+ const otherRes = await inject(
+ "GET",
+ `/api/v1/agent-vault/access-bundles/${other.id}/members/available?limit=100`
+ );
+ expect(otherRes.statusCode).toBe(200);
+ expect(
+ (JSON.parse(otherRes.payload) as { members: { actor: { id: string } }[] }).members.map(
+ (member) => member.actor.id
+ )
+ ).toContain(group.id);
+
+ expect(
+ (
+ await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members/revoke`, {
+ groupIds: [group.id]
+ })
+ ).statusCode
+ ).toBe(200);
+ const afterRevoke = await listAvailable("limit=100");
+ expect(idsOf(afterRevoke.members)).toContain(group.id);
+ expect(afterRevoke.totalCount).toBe(before.totalCount);
+
+ // totalCount counts the whole set rather than the page, so a picker can say it is truncated.
+ const firstPage = await listAvailable("limit=1");
+ expect(firstPage.members).toHaveLength(1);
+ expect(firstPage.totalCount).toBe(before.totalCount);
+ } finally {
+ await group.cleanup();
+ await inject("DELETE", `/api/v1/agent-vault/access-bundles/${bundle.id}`);
+ await inject("DELETE", `/api/v1/agent-vault/access-bundles/${other.id}`);
+ }
+ });
+
+ test("available on a bundle rejects the out-of-range query values the member list does", async () => {
+ const bundle = await createAccessBundle(`available-grantees-query-${Date.now()}`);
+ const availableUrl = `/api/v1/agent-vault/access-bundles/${bundle.id}/members/available`;
+
+ try {
+ expect((await inject("GET", `${availableUrl}?limit=0`)).statusCode).toBe(422);
+ expect((await inject("GET", `${availableUrl}?limit=101`)).statusCode).toBe(422);
+ expect((await inject("GET", `${availableUrl}?offset=10001`)).statusCode).toBe(422);
+
+ // An unreachable bundle is a 404 here as everywhere else, never a 403 confirming it exists.
+ const unknown = await inject(
+ "GET",
+ `/api/v1/agent-vault/access-bundles/${crypto.randomUUID()}/members/available`
+ );
+ expect(unknown.statusCode).toBe(404);
+ } finally {
+ await inject("DELETE", `/api/v1/agent-vault/access-bundles/${bundle.id}`);
+ }
+ });
+
test("a revoke is confined to the named bundle, actor and actor type", async () => {
const projectId = await getProjectId();
const [held, other] = [await createAccessBundle("revoke-held"), await createAccessBundle("revoke-other")];
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 09c6bdc242..02d5a75650 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
@@ -32,6 +32,7 @@ import {
AgentVaultMemberRevokeIdsSchema,
AgentVaultMemberSchema,
AgentVaultNameSchema,
+ AgentVaultProductMemberSchema,
AgentVaultRemovedMemberSchema,
AgentVaultServiceSchema,
AgentVaultSubstitutionsInputSchema,
@@ -519,6 +520,33 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro
})
});
+ server.route({
+ method: "GET",
+ url: "/:accessBundleId/members/available",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "listAvailableAgentVaultAccessBundleMembers",
+ description: "List the Agent Vault members who can still be granted an access bundle",
+ tags: [ApiDocsTags.AgentVaultAccessBundles],
+ params: z.object({
+ accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId)
+ }),
+ querystring: z.object(agentVaultListQuery(AGENT_VAULT.AVAILABLE_GRANTEE)),
+ response: {
+ 200: z.object({ members: AgentVaultProductMemberSchema.array(), totalCount: z.number() })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
+ handler: async (req) =>
+ server.services.agentVaultAccessBundle.listAvailableMembers({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req),
+ accessBundleId: req.params.accessBundleId,
+ ...req.query
+ })
+ });
+
server.route({
method: "POST",
url: "/:accessBundleId/members",
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 b9a938323f..d282ebf1f2 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
@@ -38,6 +38,7 @@ import {
AgentVaultSubstitutionSurface
} from "../agent-vault/agent-vault-enums";
import { getAgentVaultReachability } from "../agent-vault/agent-vault-permission";
+import { TAgentVaultMemberDALFactory } from "../agent-vault-member/agent-vault-member-dal";
import { TAgentVaultAccessBundleActorRef, TAgentVaultAccessBundleDALFactory } from "./agent-vault-access-bundle-dal";
import {
TAddMembersDTO,
@@ -72,6 +73,7 @@ type TAgentVaultAccessBundleServiceFactoryDep = {
"findOne" | "find" | "insertMany" | "delete" | "deleteById" | "transaction" | "findResourceMembershipsForActor"
>;
membershipRoleDAL: Pick<TMembershipRoleDALFactory, "insertMany">;
+ agentVaultMemberDAL: Pick<TAgentVaultMemberDALFactory, "findProductMembers">;
userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;
identityGroupMembershipDAL: Pick<TIdentityGroupMembershipDALFactory, "find">;
};
@@ -81,6 +83,12 @@ export type TAgentVaultAccessBundleServiceFactory = ReturnType<typeof agentVault
// The old shape capped the array at 100 entries; the cap moves here now that the body is three lists.
export const AGENT_VAULT_MAX_GRANTEES = 100;
+const ALL_GRANTEE_ACTOR_TYPES = [
+ AgentVaultMemberType.User,
+ AgentVaultMemberType.Group,
+ AgentVaultMemberType.MachineIdentity
+];
+
export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundleServiceFactoryDep) => {
const {
agentVaultAccessBundleDAL,
@@ -91,6 +99,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
kmsService,
membershipDAL,
membershipRoleDAL,
+ agentVaultMemberDAL,
userGroupMembershipDAL,
identityGroupMembershipDAL
} = deps;
@@ -922,6 +931,26 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
});
};
+ // The candidates for a grant are the product's own members, since addMembers refuses anyone else, minus
+ // whoever already holds this bundle. A member reaching it only through a granted group stays a
+ // candidate: an individual grant is a different thing, and it outlives the group membership.
+ const listAvailableMembers = async ({ accessBundleId, search, limit, offset, ...rest }: TListMembersDTO) => {
+ const { bundle, permission } = await resolveReachableBundle({ ...rest, accessBundleId });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionAgentVaultAccessBundleActions.ManageMembers,
+ ProjectPermissionSub.AgentVaultAccessBundles
+ );
+ return agentVaultMemberDAL.findProductMembers({
+ projectId: rest.projectId,
+ orgId: rest.ctx.actorOrgId,
+ actorTypes: ALL_GRANTEE_ACTOR_TYPES,
+ search,
+ limit,
+ offset,
+ excludeAccessBundleId: bundle.id
+ });
+ };
+
const addMembers = async ({ accessBundleId, userIds, groupIds, machineIdentityIds, ...rest }: TAddMembersDTO) => {
const { bundle, permission } = await resolveReachableBundle({ ...rest, accessBundleId });
ForbiddenError.from(permission).throwUnlessCan(
@@ -1068,6 +1097,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
updateService,
deleteService,
listMembers,
+ listAvailableMembers,
addMembers,
revokeMembers
};
diff --git a/backend/src/ee/services/agent-vault-member/agent-vault-member-dal.ts b/backend/src/ee/services/agent-vault-member/agent-vault-member-dal.ts
index cb26d4de0b..824e01c4ca 100644
--- a/backend/src/ee/services/agent-vault-member/agent-vault-member-dal.ts
+++ b/backend/src/ee/services/agent-vault-member/agent-vault-member-dal.ts
@@ -1,7 +1,14 @@
import { Knex } from "knex";
import { TDbClient } from "@app/db";
-import { AccessScope, OrgMembershipStatus, ProjectMembershipRole, TableName } from "@app/db/schemas";
+import {
+ AccessScope,
+ OrgMembershipStatus,
+ ProjectMembershipRole,
+ RESOURCE_SCOPE,
+ ResourceType,
+ TableName
+} from "@app/db/schemas";
import { AgentVaultMemberType } from "@app/ee/services/agent-vault/agent-vault-enums";
import { DatabaseError } from "@app/lib/errors";
import { sanitizeSqlLikeString } from "@app/lib/fn/string";
@@ -88,13 +95,15 @@ type TFindProductMembersDTO = {
search?: string;
limit: number;
offset: number;
+ // Set to list the members who could still be granted that bundle.
+ excludeAccessBundleId?: string;
};
-type TFindAvailableActorsDTO = TFindProductMembersDTO;
+type TFindAvailableActorsDTO = Omit<TFindProductMembersDTO, "excludeAccessBundleId">;
export const agentVaultMemberDALFactory = (db: TDbClient) => {
const findProductMembers = async (
- { projectId, orgId, actorTypes, search, limit, offset }: TFindProductMembersDTO,
+ { projectId, orgId, actorTypes, search, limit, offset, excludeAccessBundleId }: TFindProductMembersDTO,
tx?: Knex
): Promise<{ members: TAgentVaultProductMember[]; totalCount: number }> => {
if (!actorTypes.length) return { members: [], totalCount: 0 };
@@ -102,6 +111,15 @@ export const agentVaultMemberDALFactory = (db: TDbClient) => {
try {
const conn = tx || db.replicaNode();
+ const alreadyGranted = (column: (typeof ACTOR_COLUMN)[AgentVaultMemberType]) =>
+ conn(TableName.Membership)
+ .where(`${TableName.Membership}.scope`, RESOURCE_SCOPE)
+ .where(`${TableName.Membership}.scopeProjectId`, projectId)
+ .where(`${TableName.Membership}.scopeResourceType`, ResourceType.AgentVaultAccessBundle)
+ .where(`${TableName.Membership}.scopeResourceId`, excludeAccessBundleId!)
+ .whereNotNull(`${TableName.Membership}.${column}`)
+ .select(column);
+
const applyFilters = (query: Knex.QueryBuilder) => {
void query
.where(`${TableName.Membership}.scope`, AccessScope.Project)
@@ -114,7 +132,15 @@ export const agentVaultMemberDALFactory = (db: TDbClient) => {
void query.where((qb) => {
actorTypes.forEach((type) => {
- void qb.orWhereNotNull(`${TableName.Membership}.${ACTOR_COLUMN[type]}`);
+ const column = ACTOR_COLUMN[type];
+ void qb.orWhere((typeQb) => {
+ void typeQb.whereNotNull(`${TableName.Membership}.${column}`);
+ // Inside the block, where the column is known non-null: a bare whereNotIn would read
+ // NULL NOT IN (...) as NULL for the other two types and drop every one of their rows.
+ if (excludeAccessBundleId) {
+ void typeQb.whereNotIn(`${TableName.Membership}.${column}`, alreadyGranted(column));
+ }
+ });
});
});
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 20fb612be4..55ebc92ec5 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -4337,6 +4337,11 @@ export const AGENT_VAULT = {
limit: "The maximum number of candidates to return.",
offset: "How many candidates to skip."
},
+ AVAILABLE_GRANTEE: {
+ search: "Match candidates by name, username or email address.",
+ limit: "The maximum number of candidates to return.",
+ offset: "How many candidates to skip."
+ },
PROXY: {
proxyId: "The ID of the proxy.",
name: "The name of the proxy.",
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index d18edd49f3..0de74e2ef7 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1862,6 +1862,7 @@ export const registerRoutes = async (
kmsService,
membershipDAL,
membershipRoleDAL,
+ agentVaultMemberDAL,
userGroupMembershipDAL,
identityGroupMembershipDAL
});
diff --git a/docs/api-reference/endpoints/agent-vault-access-bundle-members/list-available.mdx b/docs/api-reference/endpoints/agent-vault-access-bundle-members/list-available.mdx
new file mode 100644
index 0000000000..dced591d53
--- /dev/null
+++ b/docs/api-reference/endpoints/agent-vault-access-bundle-members/list-available.mdx
@@ -0,0 +1,4 @@
+---
+title: "List available bundle members"
+openapi: "GET /api/v1/agent-vault/access-bundles/{accessBundleId}/members/available"
+---
diff --git a/docs/docs.json b/docs/docs.json
index 1924ba2945..6e2ea9b738 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -4457,6 +4457,7 @@
"group": "Access bundle members",
"pages": [
"api-reference/endpoints/agent-vault-access-bundle-members/list",
+ "api-reference/endpoints/agent-vault-access-bundle-members/list-available",
"api-reference/endpoints/agent-vault-access-bundle-members/add",
"api-reference/endpoints/agent-vault-access-bundle-members/revoke"
]
diff --git a/frontend/src/components/agent-vault/GrantAccessDialog.tsx b/frontend/src/components/agent-vault/GrantAccessDialog.tsx
index 922b2c21cb..988944170a 100644
--- a/frontend/src/components/agent-vault/GrantAccessDialog.tsx
+++ b/frontend/src/components/agent-vault/GrantAccessDialog.tsx
@@ -18,7 +18,7 @@ import { actorIdsPayload } from "@app/helpers/agentVaultMembers";
import { useDebounce } from "@app/hooks";
import {
useAddAgentVaultAccessBundleMembers,
- useListAgentVaultMembers
+ useListAvailableAgentVaultAccessBundleMembers
} from "@app/hooks/api/agentVault";
import { AgentVaultMemberType } from "@app/hooks/api/agentVault/enums";
import { TAgentVaultProductActor } from "@app/hooks/api/agentVault/types";
@@ -26,8 +26,6 @@ import { TAgentVaultProductActor } from "@app/hooks/api/agentVault/types";
import { MEMBER_KIND, memberDisplayName, memberSubtitle } from "./MemberName";
import { PendingInvitationBadge } from "./PendingInvitationBadge";
-const PICKER_LIMIT = 50;
-
type Option = {
actor: TAgentVaultProductActor;
label: string;
@@ -54,8 +52,9 @@ export const GrantAccessDialog = ({ isOpen, onOpenChange, accessBundleId }: Prop
}
}, [isOpen]);
- const { data, isFetching } = useListAgentVaultMembers(
- { search: debouncedSearch.trim() || undefined, limit: PICKER_LIMIT },
+ const { data, isFetching } = useListAvailableAgentVaultAccessBundleMembers(
+ accessBundleId,
+ { search: debouncedSearch.trim() || undefined },
isOpen
);
@@ -121,19 +120,17 @@ export const GrantAccessDialog = ({ isOpen, onOpenChange, accessBundleId }: Prop
multiple
options={options}
value={selected}
- shouldFilter={false}
isLoading={isFetching}
- // Without this a chip already picked vanishes when the next search returns a page it is not on.
- includeMissingSelectedOptions
- onInputValueChange={setSearch}
+ onSearchChange={setSearch}
getOptionValue={(option) => `${option.actor.type}:${option.actor.id}`}
getOptionLabel={(option) => option.label}
- getOptionKeywords={(option) => [option.subtitle]}
placeholder="Pick users, groups, or machine identities..."
searchPlaceholder="Pick users, groups, or machine identities..."
searchAriaLabel="Search users, groups, and machine identities"
emptyMessage={(inputValue) =>
- inputValue ? "No matches." : "No members yet. Add them under Access Control first."
+ inputValue
+ ? "No matches who do not already have this bundle."
+ : "Everyone in Agent Vault already has this bundle."
}
clearAriaLabel="Clear all grantees"
modal
diff --git a/frontend/src/hooks/api/agentVault/queries.tsx b/frontend/src/hooks/api/agentVault/queries.tsx
index 36c54f3833..7fdfb949d3 100644
--- a/frontend/src/hooks/api/agentVault/queries.tsx
+++ b/frontend/src/hooks/api/agentVault/queries.tsx
@@ -9,6 +9,7 @@ import {
TAgentVaultAccessBundleListItem,
TAgentVaultMember,
TAgentVaultProductActor,
+ TAgentVaultProductMember,
TAgentVaultProductMemberOf,
TAgentVaultProxy,
TAgentVaultSession,
@@ -47,6 +48,12 @@ export const agentVaultKeys = {
accessBundleId: string,
params?: Omit<TListAgentVaultMembersDTO, "actorType">
) => [...agentVaultKeys.accessBundleMembers(orgId, accessBundleId), params] as const,
+ // Nested under accessBundleMembers() so a grant invalidates the candidate list too.
+ availableAccessBundleMemberList: (
+ orgId: string,
+ accessBundleId: string,
+ params?: Omit<TListAgentVaultMembersDTO, "actorType">
+ ) => [...agentVaultKeys.accessBundleMembers(orgId, accessBundleId), "available", params] as const,
members: (orgId: string) => [...agentVaultKeys.all(orgId), "members"] as const,
memberList: (orgId: string, params?: TListAgentVaultMembersDTO) =>
[...agentVaultKeys.members(orgId), params] as const,
@@ -80,6 +87,28 @@ export const useListAgentVaultMembers = <T extends AgentVaultMemberType = AgentV
// dialogs page the same way.
const AVAILABLE_MEMBER_LIMIT = 50;
+export const useListAvailableAgentVaultAccessBundleMembers = (
+ accessBundleId: string,
+ { limit = AVAILABLE_MEMBER_LIMIT, ...rest }: Omit<TListAgentVaultMembersDTO, "actorType"> = {},
+ enabled = true
+) => {
+ const { currentOrg } = useOrganization();
+ const params = { ...rest, limit };
+
+ return useQuery({
+ queryKey: agentVaultKeys.availableAccessBundleMemberList(currentOrg.id, accessBundleId, params),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{
+ members: TAgentVaultProductMember[];
+ totalCount: number;
+ }>(`/api/v1/agent-vault/access-bundles/${accessBundleId}/members/available`, { params });
+ return data;
+ },
+ enabled: enabled && Boolean(accessBundleId),
+ placeholderData: (prev) => prev
+ });
+};
+
export const useListAvailableAgentVaultMembers = <
T extends AgentVaultMemberType = AgentVaultMemberType
>(