Skip to content

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

feat(agent-vault): member-provided credential fields with personal values and variables

Scott Wilson01020d9d7533
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.ts
index f9f140dff5..20e6c509dd 100644
--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts
+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts
@@ -8,6 +8,7 @@ import { AccessScope, ActionProjectType, OrgMembershipRole, ProjectMembershipRol
import { seedData1 } from "@app/db/seed-data";
import { agentVaultServiceCustomHeaderDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-custom-header-dal";
import { agentVaultServiceSubstitutionDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-substitution-dal";
+import { agentVaultPersonalValueDALFactory } from "@app/ee/services/agent-vault-personal-value/agent-vault-personal-value-dal";
import { agentVaultProxyDALFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-dal";
import {
AGENT_VAULT_MAX_PROXIES_PER_ORG,
@@ -52,7 +53,7 @@ initLogger();
const authHeader = { authorization: `Bearer ${jwtAuthToken}` };
-const inject = (method: "GET" | "POST" | "PATCH" | "DELETE", url: string, body?: Record<string, unknown>) =>
+const inject = (method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE", url: string, body?: Record<string, unknown>) =>
testServer.inject({ method, url, headers: authHeader, ...(body ? { body } : {}) });
const createOrgIdentity = async (name: string) => {
@@ -234,12 +235,32 @@ const createMemberIdentity = async (name: string) => {
return {
id: identity.id,
- as: (method: "GET" | "POST" | "PATCH", url: string, body?: Record<string, unknown>) =>
+ as: (method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE", url: string, body?: Record<string, unknown>) =>
testServer.inject({ method, url, headers: { authorization: `Bearer ${token}` }, ...(body ? { body } : {}) }),
cleanup: () => inject("DELETE", `/api/v1/identities/${identity.id}`)
};
};
+// 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" };
+ const keys = await globalThis.crypto.subtle.generateKey(algorithm, true, ["sign", "verify"]);
+ const certificate = await x509.X509CertificateGenerator.createSelfSigned({
+ name: "CN=Agent Vault Variables Test CA",
+ serialNumber: "01",
+ notBefore: new Date(Date.now() - 60_000),
+ notAfter: new Date(Date.now() + 24 * 60 * 60 * 1000),
+ signingAlgorithm: algorithm,
+ keys,
+ extensions: [
+ new x509.BasicConstraintsExtension(true, undefined, true),
+ // eslint-disable-next-line no-bitwise
+ new x509.KeyUsagesExtension(x509.KeyUsageFlags.keyCertSign | x509.KeyUsageFlags.cRLSign, true)
+ ]
+ });
+ return certificate.toString("pem");
+};
+
const createAccessBundle = async (name: string) => {
const res = await inject("POST", "/api/v1/agent-vault/access-bundles", { name });
expect(res.statusCode).toBe(200);
@@ -454,7 +475,12 @@ describe("Agent Vault V1 Router", async () => {
service: { id: string; hostPattern: string; credential: Record<string, unknown> };
};
expect(service.hostPattern).toBe("API.GitHub.com");
- expect(service.credential).toEqual({ type: "bearer", headerName: "Authorization", headerPrefix: "Bearer" });
+ expect(service.credential).toEqual({
+ type: "bearer",
+ headerName: "Authorization",
+ headerPrefix: "Bearer",
+ memberProvidedFields: []
+ });
expect(res.payload).not.toContain("ghp_secret_value");
const detail = await inject("GET", `/api/v1/agent-vault/access-bundles/${bundle.id}`);
@@ -486,7 +512,8 @@ describe("Agent Vault V1 Router", async () => {
expect(JSON.parse(rotated.payload).service.credential).toEqual({
type: "bearer",
headerName: "DD-API-KEY",
- headerPrefix: ""
+ headerPrefix: "",
+ memberProvidedFields: []
});
expect((await sealed()).equals(before)).toBe(false);
@@ -509,7 +536,7 @@ describe("Agent Vault V1 Router", async () => {
const { service } = JSON.parse(created.payload) as {
service: { id: string; credential: Record<string, unknown> };
};
- expect(service.credential).toEqual({ type: "basic" });
+ expect(service.credential).toEqual({ type: "basic", memberProvidedFields: [] });
expect(created.payload).not.toContain("sk_live_key");
const url = `/api/v1/agent-vault/access-bundles/${bundle.id}/services/${service.id}`;
@@ -812,26 +839,6 @@ describe("Agent Vault V1 Router", async () => {
const referencesByField = (references: TReference[]) =>
references.map((reference) => `${reference.field}:${reference.key}`).sort();
- // 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" };
- const keys = await globalThis.crypto.subtle.generateKey(algorithm, true, ["sign", "verify"]);
- const certificate = await x509.X509CertificateGenerator.createSelfSigned({
- name: "CN=Agent Vault Variables Test CA",
- serialNumber: "01",
- notBefore: new Date(Date.now() - 60_000),
- notAfter: new Date(Date.now() + 24 * 60 * 60 * 1000),
- signingAlgorithm: algorithm,
- keys,
- extensions: [
- new x509.BasicConstraintsExtension(true, undefined, true),
- // eslint-disable-next-line no-bitwise
- new x509.KeyUsagesExtension(x509.KeyUsageFlags.keyCertSign | x509.KeyUsageFlags.cRLSign, true)
- ]
- });
- return certificate.toString("pem");
- };
-
type TResolved = {
services: {
name: string;
@@ -1759,7 +1766,9 @@ describe("Agent Vault V1 Router", async () => {
expect(listed.statusCode).toBe(403);
expect(listed.payload).not.toContain("admin_only_value");
expect(listed.payload).not.toContain("TOKEN");
- expect((await member.asIdentity("GET", `${variablesUrl}/${variable.id}/value`)).statusCode).toBe(403);
+ // By id, a shared variable reads to a member like one that does not exist, as another member's personal one does.
+ expect((await member.asIdentity("GET", `${variablesUrl}/${variable.id}/value`)).statusCode).toBe(404);
+ expect((await member.asIdentity("DELETE", `${variablesUrl}/${variable.id}`)).statusCode).toBe(404);
expect((await member.asIdentity("POST", variablesUrl, { key: "MINE", value: "x" })).statusCode).toBe(403);
} finally {
await deleteUaIdentity(member.id);
@@ -1767,6 +1776,459 @@ describe("Agent Vault V1 Router", async () => {
});
});
+ describe("member-provided values", async () => {
+ const servicesUrl = (accessBundleId: string) => `/api/v1/agent-vault/access-bundles/${accessBundleId}/services`;
+ const membersUrl = (accessBundleId: string) => `/api/v1/agent-vault/access-bundles/${accessBundleId}/members`;
+ const personalValuesUrl = (accessBundleId: string, serviceId: string) =>
+ `${servicesUrl(accessBundleId)}/${serviceId}/personal-values`;
+ const variablesUrl = "/api/v1/agent-vault/variables";
+ const personalVariablesUrl = `${variablesUrl}?scope=personal`;
+
+ // Personal variable keys are unique per owner, and the seeded admin owns them across every test here.
+ beforeEach(async () => {
+ const project = await testDb("projects")
+ .where({ orgId: seedData1.organization.id, type: ProjectType.AgentVault })
+ .first();
+ if (!project) return;
+ const variableIds = testDb("agent_vault_variables")
+ .where({ projectId: project.id })
+ .where((owned) => {
+ void owned.whereNotNull("userId").orWhereNotNull("identityId");
+ })
+ .select("id");
+ await testDb("agent_vault_personal_value_references").whereIn("variableId", variableIds).del();
+ await testDb("agent_vault_variables").whereIn("id", variableIds).del();
+ });
+
+ type TResolvedService = {
+ name: string;
+ credential: Record<string, string>;
+ personalValuesMissing: boolean;
+ };
+
+ type TPersonalValues = {
+ isConfigured: boolean;
+ fields: { field: string; isSet: boolean; variableReferences: { variableId: string; key: string }[] }[];
+ };
+
+ const enrollProxy = async (name: string) => {
+ const created = await inject("POST", "/api/v1/agent-vault/proxies", { name });
+ expect(created.statusCode).toBe(200);
+ const { token } = JSON.parse(created.payload) as { token: string };
+ const login = await testServer.inject({
+ method: "POST",
+ url: "/api/v1/agent-vault/proxy/login",
+ body: { method: ResourceAuthMethodType.Token, token, rootCaCertificate: await createProxyCaPem() }
+ });
+ expect(login.statusCode).toBe(200);
+ const { accessToken } = JSON.parse(login.payload) as { accessToken: string };
+
+ return async (sessionToken: string, serviceName: string) => {
+ const resolved = await testServer.inject({
+ method: "POST",
+ url: "/api/v1/agent-vault/proxy/resolve",
+ headers: { authorization: `Bearer ${accessToken}`, "x-infisical-agent-session": sessionToken }
+ });
+ expect(resolved.statusCode).toBe(200);
+ const { services } = JSON.parse(resolved.payload) as { services: TResolvedService[] };
+ return services.find((service) => service.name === serviceName)!;
+ };
+ };
+
+ const mintSession = async (
+ as: (method: "POST", url: string, body: Record<string, unknown>) => ReturnType<typeof inject>,
+ accessBundleName: string
+ ) => {
+ const mint = await as("POST", "/api/v1/agent-vault/sessions", { accessBundles: [accessBundleName], ttl: "1h" });
+ expect(mint.statusCode).toBe(200);
+ return (JSON.parse(mint.payload) as { session: { token: string } }).session.token;
+ };
+
+ const createService = async (accessBundleId: string, body: Record<string, unknown>) => {
+ const res = await inject("POST", servicesUrl(accessBundleId), body);
+ expect(res.statusCode).toBe(200);
+ return (
+ JSON.parse(res.payload) as {
+ service: { id: string; name: string; credential: { type: string; memberProvidedFields?: string[] } };
+ }
+ ).service;
+ };
+
+ // The caller's status for each service, as the bundle read returns it.
+ const statusesOf = async (
+ as: (method: "GET", url: string) => ReturnType<typeof inject>,
+ accessBundleId: string
+ ) => {
+ const res = await as("GET", `/api/v1/agent-vault/access-bundles/${accessBundleId}`);
+ expect(res.statusCode).toBe(200);
+ const { accessBundle } = JSON.parse(res.payload) as {
+ accessBundle: { services: { id: string; personalValues: TPersonalValues | null }[] };
+ };
+ 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.
+ 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);
+ const { accessBundles } = JSON.parse(res.payload) as {
+ accessBundles: { id: string; servicesRequiringSetup: string[] }[];
+ };
+ return new Map(accessBundles.map((bundle) => [bundle.id, bundle.servicesRequiringSetup]));
+ };
+
+ const setValues = (
+ as: (method: "PATCH", url: string, body: Record<string, unknown>) => ReturnType<typeof inject>,
+ accessBundleId: string,
+ serviceId: string,
+ values: Record<string, string>
+ ) =>
+ as("PATCH", personalValuesUrl(accessBundleId, serviceId), {
+ values: Object.entries(values).map(([field, value]) => ({ field, value }))
+ });
+
+ test("a member-provided token comes from whoever the session belongs to", async () => {
+ const bundle = await createAccessBundle("mp-bearer");
+ const service = await createService(bundle.id, {
+ name: "datadog",
+ hostPattern: "api.datadoghq.com",
+ credential: { type: "bearer", headerName: "DD-API-KEY", memberProvidedFields: ["credential-value"] }
+ });
+ expect(service.credential.memberProvidedFields).toEqual(["credential-value"]);
+
+ const both = await inject("POST", servicesUrl(bundle.id), {
+ name: "datadog-both",
+ hostPattern: "api.us5.datadoghq.com",
+ credential: { type: "bearer", value: "admin_value", memberProvidedFields: ["credential-value"] }
+ });
+ expect(both.statusCode).toBe(422);
+
+ // A PATCH that leaves the list out keeps it, so a token sent alongside is refused rather than dropped.
+ const dropped = await inject("PATCH", `${servicesUrl(bundle.id)}/${service.id}`, {
+ credential: { type: "bearer", value: "admin_value" }
+ });
+ expect(dropped.statusCode).toBe(400);
+ expect(JSON.parse(dropped.payload).message).toContain("'credential-value' is member provided");
+
+ const member = await createMemberIdentity(`mp-bearer-member-${Date.now()}`);
+ try {
+ expect((await inject("POST", membersUrl(bundle.id), { machineIdentityIds: [member.id] })).statusCode).toBe(200);
+
+ expect((await statusesOf(member.as, bundle.id)).get(service.id)).toEqual({
+ isConfigured: false,
+ fields: [expect.objectContaining({ field: "credential-value", isSet: false })]
+ });
+ expect((await pendingOf(member.as)).get(bundle.id)).toEqual(["datadog"]);
+ // The creator is granted the bundle, so it is one of the admin's own too.
+ expect((await statusesOf(inject, bundle.id)).get(service.id)?.isConfigured).toBe(false);
+ expect((await pendingOf(inject)).get(bundle.id)).toEqual(["datadog"]);
+
+ const resolve = await enrollProxy("mp-bearer");
+ const adminSession = await mintSession(inject, bundle.name);
+ const memberSession = await mintSession(member.as, bundle.name);
+
+ const unset = await resolve(adminSession, "datadog");
+ expect(unset.personalValuesMissing).toBe(true);
+ expect(unset.credential).toEqual({ type: "passthrough" });
+
+ // UUIDs are case-insensitive, so an upper-case bundle id in the path names the same bundle.
+ const set = await setValues(member.as, bundle.id.toUpperCase(), service.id, {
+ "credential-value": "member_token"
+ });
+ expect(set.statusCode).toBe(200);
+ expect(JSON.parse(set.payload).personalValues).toMatchObject({ isConfigured: true });
+ expect(set.payload).not.toContain("member_token");
+
+ expect(await resolve(memberSession, "datadog")).toMatchObject({
+ personalValuesMissing: false,
+ credential: { type: "bearer", headerName: "DD-API-KEY", headerPrefix: "", value: "member_token" }
+ });
+ expect((await resolve(adminSession, "datadog")).personalValuesMissing).toBe(true);
+
+ expect((await setValues(inject, bundle.id, service.id, { "credential-value": "admin_token" })).statusCode).toBe(
+ 200
+ );
+ expect((await resolve(adminSession, "datadog")).credential.value).toBe("admin_token");
+ expect((await resolve(memberSession, "datadog")).credential.value).toBe("member_token");
+
+ const wrongField = await setValues(member.as, bundle.id, service.id, { "credential-username": "x" });
+ expect(wrongField.statusCode).toBe(400);
+ expect((await member.as("PATCH", personalValuesUrl(bundle.id, service.id), { values: [] })).statusCode).toBe(
+ 422
+ );
+ expect((await statusesOf(member.as, bundle.id)).get(service.id)?.isConfigured).toBe(true);
+ expect((await pendingOf(member.as)).has(bundle.id)).toBe(false);
+
+ const removed = await member.as("DELETE", personalValuesUrl(bundle.id, service.id));
+ expect(removed.statusCode).toBe(200);
+ expect(JSON.parse(removed.payload).personalValues.isConfigured).toBe(false);
+ expect((await resolve(memberSession, "datadog")).personalValuesMissing).toBe(true);
+ expect((await member.as("DELETE", personalValuesUrl(bundle.id, service.id))).statusCode).toBe(404);
+ } finally {
+ await member.cleanup();
+ }
+ });
+
+ test("a member's own variables fill their values, and nobody else's do", async () => {
+ const bundle = await createAccessBundle("mp-variables");
+ const service = await createService(bundle.id, {
+ name: "github",
+ hostPattern: "api.github.com",
+ credential: { type: "bearer", memberProvidedFields: ["credential-value"] }
+ });
+
+ const member = await createMemberIdentity(`mp-variables-member-${Date.now()}`);
+ try {
+ expect((await inject("POST", membersUrl(bundle.id), { machineIdentityIds: [member.id] })).statusCode).toBe(200);
+
+ const adminVariable = await inject("POST", variablesUrl, {
+ scope: "personal",
+ key: "MY_TOKEN",
+ value: "admin_secret"
+ });
+ expect(adminVariable.statusCode).toBe(200);
+ const adminVariableId = (JSON.parse(adminVariable.payload) as { variable: { id: string } }).variable.id;
+
+ // The same key, owned by someone else, is a different variable.
+ const created = await member.as("POST", variablesUrl, {
+ scope: "personal",
+ key: "MY_TOKEN",
+ value: "member_secret"
+ });
+ expect(created.statusCode).toBe(200);
+ const memberVariableId = (JSON.parse(created.payload) as { variable: { id: string } }).variable.id;
+ expect(
+ (await member.as("POST", variablesUrl, { scope: "personal", key: "MY_TOKEN", value: "again" })).statusCode
+ ).toBe(400);
+
+ const unknown = await setValues(member.as, bundle.id, service.id, { "credential-value": "{{NOPE}}" });
+ expect(unknown.statusCode).toBe(400);
+ expect(JSON.parse(unknown.payload).message).toContain("no personal variable named 'NOPE'");
+
+ const set = await setValues(member.as, bundle.id, service.id, { "credential-value": "token {{MY_TOKEN}}" });
+ expect(set.statusCode).toBe(200);
+ expect(JSON.parse(set.payload).personalValues.fields).toEqual([
+ expect.objectContaining({
+ field: "credential-value",
+ isSet: true,
+ variableReferences: [{ variableId: memberVariableId, key: "MY_TOKEN" }]
+ })
+ ]);
+
+ const resolve = await enrollProxy("mp-variables");
+ const memberSession = await mintSession(member.as, bundle.name);
+ expect((await resolve(memberSession, "github")).credential.value).toBe("token member_secret");
+
+ const memberList = await member.as("GET", personalVariablesUrl);
+ expect(JSON.parse(memberList.payload).variables).toEqual([
+ expect.objectContaining({
+ key: "MY_TOKEN",
+ usedByServices: [expect.objectContaining({ id: service.id, accessBundleName: bundle.name })]
+ })
+ ]);
+ expect(memberList.payload).not.toContain("member_secret");
+ const adminList = await inject("GET", personalVariablesUrl);
+ expect(JSON.parse(adminList.payload).variables).toEqual([
+ expect.objectContaining({ id: adminVariableId, usedByServices: [] })
+ ]);
+
+ // Personal variables never show among the shared ones, and a member can't list those.
+ const sharedList = await inject("GET", variablesUrl);
+ expect(sharedList.statusCode).toBe(200);
+ expect(
+ (JSON.parse(sharedList.payload) as { variables: { id: string }[] }).variables.map((variable) => variable.id)
+ ).not.toContain(adminVariableId);
+ expect((await member.as("GET", variablesUrl)).statusCode).toBe(403);
+ expect(JSON.parse(created.payload).variable.scope).toBe("personal");
+
+ // Another actor's variable reads exactly like one that does not exist, an admin's included.
+ expect((await member.as("GET", `${variablesUrl}/${adminVariableId}/value`)).statusCode).toBe(404);
+ expect((await inject("GET", `${variablesUrl}/${memberVariableId}/value`)).statusCode).toBe(404);
+ const revealed = await member.as("GET", `${variablesUrl}/${memberVariableId}/value`);
+ expect(JSON.parse(revealed.payload).value).toBe("member_secret");
+
+ const inUse = await member.as("DELETE", `${variablesUrl}/${memberVariableId}`);
+ expect(inUse.statusCode).toBe(409);
+ expect(JSON.parse(inUse.payload).message).toContain("'github'");
+
+ expect((await member.as("PATCH", `${variablesUrl}/${memberVariableId}`, { value: "rotated" })).statusCode).toBe(
+ 200
+ );
+ expect((await resolve(memberSession, "github")).credential.value).toBe("token rotated");
+ } finally {
+ await member.cleanup();
+ }
+ });
+
+ test("changing which fields are member provided keeps the values that still apply", async () => {
+ const bundle = await createAccessBundle("mp-basic");
+ const service = await createService(bundle.id, {
+ name: "pagerduty",
+ hostPattern: "api.pagerduty.com",
+ credential: { type: "basic", password: "admin_pw", memberProvidedFields: ["credential-username"] }
+ });
+ expect(service.credential.memberProvidedFields).toEqual(["credential-username"]);
+ const patchService = (credential: Record<string, unknown>) =>
+ inject("PATCH", `${servicesUrl(bundle.id)}/${service.id}`, { credential });
+ // Which fields a member has saved for the service, read directly since no response lists them all at once.
+ const storedFields = async () =>
+ (await testDb("agent_vault_personal_values").where({ serviceId: service.id }).select("field"))
+ .map((row: { field: string }) => row.field)
+ .sort();
+
+ expect((await setValues(inject, bundle.id, service.id, { "credential-username": "admin_user" })).statusCode).toBe(
+ 200
+ );
+ const resolve = await enrollProxy("mp-basic");
+ const session = await mintSession(inject, bundle.name);
+ expect((await resolve(session, "pagerduty")).credential).toEqual({
+ type: "basic",
+ username: "admin_user",
+ password: "admin_pw"
+ });
+
+ // Handing the password over too keeps the saved username, and the member only adds the new field.
+ expect(
+ (await patchService({ type: "basic", memberProvidedFields: ["credential-username", "credential-value"] }))
+ .statusCode
+ ).toBe(200);
+ expect(await storedFields()).toEqual(["credential-username"]);
+ expect((await resolve(session, "pagerduty")).personalValuesMissing).toBe(true);
+ const onlyPassword = await setValues(inject, bundle.id, service.id, { "credential-value": "member_pw" });
+ expect(onlyPassword.statusCode).toBe(200);
+ expect(JSON.parse(onlyPassword.payload).personalValues.isConfigured).toBe(true);
+ expect((await resolve(session, "pagerduty")).credential).toEqual({
+ type: "basic",
+ username: "admin_user",
+ password: "member_pw"
+ });
+
+ // Taking the username back drops only the saved username. The admin's half starts empty.
+ expect((await patchService({ type: "basic", memberProvidedFields: ["credential-value"] })).statusCode).toBe(200);
+ expect(await storedFields()).toEqual(["credential-value"]);
+ expect(await resolve(session, "pagerduty")).toMatchObject({
+ personalValuesMissing: false,
+ credential: { type: "basic", username: "", password: "member_pw" }
+ });
+
+ // A new credential type drops every saved value, even for a field members still provide.
+ expect((await patchService({ type: "bearer", memberProvidedFields: ["credential-value"] })).statusCode).toBe(200);
+ expect(await storedFields()).toEqual([]);
+ expect((await resolve(session, "pagerduty")).personalValuesMissing).toBe(true);
+
+ // With nothing saved, a save has to send every field.
+ expect(
+ (await patchService({ type: "basic", memberProvidedFields: ["credential-username", "credential-value"] }))
+ .statusCode
+ ).toBe(200);
+ const half = await setValues(inject, bundle.id, service.id, { "credential-username": "only_user" });
+ expect(half.statusCode).toBe(400);
+ expect(JSON.parse(half.payload).message).toContain("password");
+
+ // A bearer service with no token and nothing left to members is not a credential at all.
+ expect((await patchService({ type: "bearer" })).statusCode).toBe(400);
+ });
+
+ test("losing a bundle clears the values a member saved for it, and keeps their variables", async () => {
+ const bundle = await createAccessBundle("mp-revoke");
+ const service = await createService(bundle.id, {
+ name: "slack",
+ hostPattern: "slack.com",
+ credential: { type: "bearer", memberProvidedFields: ["credential-value"] }
+ });
+
+ const member = await createMemberIdentity(`mp-revoke-member-${Date.now()}`);
+ try {
+ expect((await inject("POST", membersUrl(bundle.id), { machineIdentityIds: [member.id] })).statusCode).toBe(200);
+ expect(
+ (await member.as("POST", variablesUrl, { scope: "personal", key: "SLACK_TOKEN", value: "xoxb" })).statusCode
+ ).toBe(200);
+ expect(
+ (await setValues(member.as, bundle.id, service.id, { "credential-value": "{{SLACK_TOKEN}}" })).statusCode
+ ).toBe(200);
+ // The admin's own values are not the revoked member's to lose.
+ expect((await setValues(inject, bundle.id, service.id, { "credential-value": "admin" })).statusCode).toBe(200);
+
+ expect((await inject("DELETE", membersUrl(bundle.id), { machineIdentityIds: [member.id] })).statusCode).toBe(
+ 200
+ );
+ expect(
+ await testDb("agent_vault_personal_values").where({ serviceId: service.id, identityId: member.id })
+ ).toHaveLength(0);
+ expect(
+ await testDb("agent_vault_personal_values").where({ serviceId: service.id, userId: seedData1.id })
+ ).toHaveLength(1);
+ expect(await testDb("agent_vault_variables").where({ identityId: member.id })).toHaveLength(1);
+
+ expect((await inject("POST", membersUrl(bundle.id), { machineIdentityIds: [member.id] })).statusCode).toBe(200);
+ expect((await statusesOf(member.as, bundle.id)).get(service.id)?.isConfigured).toBe(false);
+
+ // Leaving Agent Vault clears them too.
+ expect((await setValues(member.as, bundle.id, service.id, { "credential-value": "again" })).statusCode).toBe(
+ 200
+ );
+ expect(
+ (await inject("DELETE", "/api/v1/agent-vault/members", { machineIdentityIds: [member.id] })).statusCode
+ ).toBe(200);
+ expect(await testDb("agent_vault_personal_values").where({ identityId: member.id })).toHaveLength(0);
+ } finally {
+ await member.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, {
+ name: "openai",
+ hostPattern: "api.openai.com",
+ credential: { type: "bearer", memberProvidedFields: ["credential-value"] }
+ });
+ 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((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);
+ });
+
+ test("a service out of reach is a 404, and one without member-provided fields takes no values", async () => {
+ const bundle = await createAccessBundle("mp-reach");
+ const memberService = await createService(bundle.id, {
+ name: "anthropic",
+ hostPattern: "api.anthropic.com",
+ credential: { type: "bearer", memberProvidedFields: ["credential-value"] }
+ });
+ const adminService = await createService(bundle.id, {
+ name: "mistral",
+ hostPattern: "api.mistral.ai",
+ credential: { type: "bearer", value: "admin_only" }
+ });
+
+ const member = await createMemberIdentity(`mp-reach-member-${Date.now()}`);
+ try {
+ expect((await setValues(member.as, bundle.id, memberService.id, { "credential-value": "x" })).statusCode).toBe(
+ 404
+ );
+ expect((await member.as("GET", `/api/v1/agent-vault/access-bundles/${bundle.id}`)).statusCode).toBe(404);
+ expect((await pendingOf(member.as)).size).toBe(0);
+ // A service named under another bundle reads as missing too.
+ const other = await createAccessBundle("mp-reach-other");
+ expect((await setValues(inject, other.id, memberService.id, { "credential-value": "x" })).statusCode).toBe(404);
+ } finally {
+ await member.cleanup();
+ }
+
+ const refused = await setValues(inject, bundle.id, adminService.id, { "credential-value": "x" });
+ expect(refused.statusCode).toBe(400);
+ expect(JSON.parse(refused.payload).message).toContain("doesn't take any values from its members");
+ expect((await statusesOf(inject, bundle.id)).get(adminService.id)).toBeNull();
+ });
+ });
+
describe("product membership", async () => {
const membersUrl = "/api/v1/agent-vault/members";
@@ -2907,6 +3369,7 @@ describe("Agent Vault V1 Router", async () => {
agentVaultServiceCustomHeaderDAL: agentVaultServiceCustomHeaderDALFactory(testDb),
agentVaultServiceSubstitutionDAL: agentVaultServiceSubstitutionDALFactory(testDb),
agentVaultVariableDAL: agentVaultVariableDALFactory(testDb),
+ agentVaultPersonalValueDAL: agentVaultPersonalValueDALFactory(testDb),
agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),
agentVaultSessionLogConfigDAL: agentVaultSessionLogConfigDALFactory(testDb),
membershipDAL: membershipDALFactory(testDb),
@@ -3038,6 +3501,7 @@ describe("Agent Vault V1 Router", async () => {
agentVaultServiceCustomHeaderDAL: agentVaultServiceCustomHeaderDALFactory(testDb),
agentVaultServiceSubstitutionDAL: agentVaultServiceSubstitutionDALFactory(testDb),
agentVaultVariableDAL: agentVaultVariableDALFactory(testDb),
+ agentVaultPersonalValueDAL: agentVaultPersonalValueDALFactory(testDb),
agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),
agentVaultSessionLogConfigDAL: agentVaultSessionLogConfigDALFactory(testDb),
membershipDAL: membershipDALFactory(testDb),
@@ -3205,6 +3669,7 @@ describe("Agent Vault V1 Router", async () => {
agentVaultServiceCustomHeaderDAL: agentVaultServiceCustomHeaderDALFactory(testDb),
agentVaultServiceSubstitutionDAL: agentVaultServiceSubstitutionDALFactory(testDb),
agentVaultVariableDAL: agentVaultVariableDALFactory(testDb),
+ agentVaultPersonalValueDAL: agentVaultPersonalValueDALFactory(testDb),
agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),
agentVaultSessionLogConfigDAL: agentVaultSessionLogConfigDALFactory(testDb),
membershipDAL: membershipDALFactory(testDb),
@@ -3944,6 +4409,7 @@ describe("Agent Vault V1 Router", async () => {
agentVaultServiceCustomHeaderDAL: agentVaultServiceCustomHeaderDALFactory(testDb),
agentVaultServiceSubstitutionDAL: agentVaultServiceSubstitutionDALFactory(testDb),
agentVaultVariableDAL: agentVaultVariableDALFactory(testDb),
+ agentVaultPersonalValueDAL: agentVaultPersonalValueDALFactory(testDb),
agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),
agentVaultSessionLogConfigDAL: agentVaultSessionLogConfigDALFactory(testDb),
membershipDAL: membershipDALFactory(testDb),
@@ -4043,6 +4509,7 @@ describe("Agent Vault V1 Router", async () => {
agentVaultServiceCustomHeaderDAL: agentVaultServiceCustomHeaderDALFactory(testDb),
agentVaultServiceSubstitutionDAL: agentVaultServiceSubstitutionDALFactory(testDb),
agentVaultVariableDAL: agentVaultVariableDALFactory(testDb),
+ agentVaultPersonalValueDAL: agentVaultPersonalValueDALFactory(testDb),
agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),
agentVaultSessionLogConfigDAL: agentVaultSessionLogConfigDALFactory(testDb),
membershipDAL: membershipDALFactory(testDb),
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index dc9074f969..51a4c4e59b 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -8,6 +8,7 @@ import { TAccessApprovalRequestServiceFactory } from "@app/ee/services/access-ap
import { TAgentProxyCaServiceFactory } from "@app/ee/services/agent-proxy-ca/agent-proxy-ca-service";
import { TAgentVaultAccessBundleServiceFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service";
import { TAgentVaultMembershipServiceFactory } from "@app/ee/services/agent-vault-member/agent-vault-membership-service";
+import { TAgentVaultPersonalValueServiceFactory } from "@app/ee/services/agent-vault-personal-value/agent-vault-personal-value-service";
import { TAgentVaultProjectResolverFactory } from "@app/ee/services/agent-vault-project/agent-vault-project-resolver";
import { TAgentVaultProxyServiceFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-service";
import { TAgentVaultSessionServiceFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-service";
@@ -387,6 +388,7 @@ declare module "fastify" {
agentVaultProjectResolver: TAgentVaultProjectResolverFactory;
agentVaultAccessBundle: TAgentVaultAccessBundleServiceFactory;
agentVaultVariable: TAgentVaultVariableServiceFactory;
+ agentVaultPersonalValue: TAgentVaultPersonalValueServiceFactory;
agentVaultProxy: TAgentVaultProxyServiceFactory;
agentVaultSession: TAgentVaultSessionServiceFactory;
agentVaultSessionLog: TAgentVaultSessionLogServiceFactory;
diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.ts
index 75742a3e81..16b5fec5d5 100644
--- a/backend/src/@types/knex.d.ts
+++ b/backend/src/@types/knex.d.ts
@@ -23,6 +23,12 @@ import {
TAgentVaultAccessBundles,
TAgentVaultAccessBundlesInsert,
TAgentVaultAccessBundlesUpdate,
+ TAgentVaultPersonalValueReferences,
+ TAgentVaultPersonalValueReferencesInsert,
+ TAgentVaultPersonalValueReferencesUpdate,
+ TAgentVaultPersonalValues,
+ TAgentVaultPersonalValuesInsert,
+ TAgentVaultPersonalValuesUpdate,
TAgentVaultProxies,
TAgentVaultProxiesInsert,
TAgentVaultProxiesUpdate,
@@ -1830,6 +1836,16 @@ declare module "knex/types/tables" {
TAgentVaultVariablesInsert,
TAgentVaultVariablesUpdate
>;
+ [TableName.AgentVaultPersonalValue]: KnexOriginal.CompositeTableType<
+ TAgentVaultPersonalValues,
+ TAgentVaultPersonalValuesInsert,
+ TAgentVaultPersonalValuesUpdate
+ >;
+ [TableName.AgentVaultPersonalValueReference]: KnexOriginal.CompositeTableType<
+ TAgentVaultPersonalValueReferences,
+ TAgentVaultPersonalValueReferencesInsert,
+ TAgentVaultPersonalValueReferencesUpdate
+ >;
[TableName.AgentVaultServiceVariableReference]: KnexOriginal.CompositeTableType<
TAgentVaultServiceVariableReferences,
TAgentVaultServiceVariableReferencesInsert,
diff --git a/backend/src/db/migrations/20261013120000_agent-vault-personal-values.ts b/backend/src/db/migrations/20261013120000_agent-vault-personal-values.ts
new file mode 100644
index 0000000000..9f8038e788
--- /dev/null
+++ b/backend/src/db/migrations/20261013120000_agent-vault-personal-values.ts
@@ -0,0 +1,173 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";
+
+const PROJECT_KEY_UNIQUE = "agent_vault_variables_projectid_key_unique";
+const SHARED_KEY_UNIQUE = "agent_vault_variables_shared_key_unique";
+const USER_KEY_UNIQUE = "agent_vault_variables_user_key_unique";
+const IDENTITY_KEY_UNIQUE = "agent_vault_variables_identity_key_unique";
+
+// A NULL never equals a NULL, so a unique index over the optional target columns would let one field be saved twice.
+const NO_TARGET = "'00000000-0000-0000-0000-000000000000'::uuid";
+
+export async function up(knex: Knex): Promise<void> {
+ // A variable with an owner is that user's or identity's own; one without is shared across Agent Vault.
+ if (!(await knex.schema.hasColumn(TableName.AgentVaultVariable, "userId"))) {
+ await knex.schema.alterTable(TableName.AgentVaultVariable, (t) => {
+ t.uuid("userId");
+ t.foreign("userId").references("id").inTable(TableName.Users).onDelete("CASCADE");
+ t.uuid("identityId");
+ t.foreign("identityId").references("id").inTable(TableName.Identity).onDelete("CASCADE");
+ t.dropUnique(["projectId", "key"], PROJECT_KEY_UNIQUE);
+ // The projectId foreign key's cascade needs an index over every row, which the partial ones below aren't.
+ t.index("projectId");
+ });
+ await knex.raw(
+ `ALTER TABLE ?? ADD CONSTRAINT "agent_vault_variables_one_owner" CHECK (num_nonnulls("userId", "identityId") <= 1)`,
+ [TableName.AgentVaultVariable]
+ );
+ await knex.raw(
+ `CREATE UNIQUE INDEX ?? ON ?? ("projectId", "key") WHERE "userId" IS NULL AND "identityId" IS NULL`,
+ [SHARED_KEY_UNIQUE, TableName.AgentVaultVariable]
+ );
+ // The owner column leads, so each index also serves its foreign key's cascade.
+ await knex.raw(`CREATE UNIQUE INDEX ?? ON ?? ("userId", "projectId", "key") WHERE "userId" IS NOT NULL`, [
+ USER_KEY_UNIQUE,
+ TableName.AgentVaultVariable
+ ]);
+ await knex.raw(`CREATE UNIQUE INDEX ?? ON ?? ("identityId", "projectId", "key") WHERE "identityId" IS NOT NULL`, [
+ IDENTITY_KEY_UNIQUE,
+ TableName.AgentVaultVariable
+ ]);
+ }
+
+ // NULL when the admin sets every field. An empty array is never stored, so NULL is the only "none".
+ if (!(await knex.schema.hasColumn(TableName.AgentVaultService, "memberProvidedFields"))) {
+ await knex.schema.alterTable(TableName.AgentVaultService, (t) => {
+ t.specificType("memberProvidedFields", "text[]");
+ });
+ await knex.raw(
+ `ALTER TABLE ?? ADD CONSTRAINT "agent_vault_services_member_provided_fields_check" CHECK (cardinality("memberProvidedFields") > 0 AND "memberProvidedFields" <@ ARRAY['credential-value', 'credential-username']::text[])`,
+ [TableName.AgentVaultService]
+ );
+ }
+
+ // One row per field a member has set, sealed like every other value. The target columns mirror the variable
+ // references table so a custom header or substitution can be member-provided later without reshaping this.
+ if (!(await knex.schema.hasTable(TableName.AgentVaultPersonalValue))) {
+ await knex.schema.createTable(TableName.AgentVaultPersonalValue, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+
+ t.uuid("serviceId").notNullable();
+ t.foreign("serviceId").references("id").inTable(TableName.AgentVaultService).onDelete("CASCADE");
+ t.index("serviceId");
+
+ t.string("field", 32).notNullable();
+
+ t.uuid("customHeaderId");
+ t.foreign("customHeaderId").references("id").inTable(TableName.AgentVaultServiceCustomHeader).onDelete("CASCADE");
+ t.index("customHeaderId");
+
+ t.uuid("substitutionId");
+ t.foreign("substitutionId").references("id").inTable(TableName.AgentVaultServiceSubstitution).onDelete("CASCADE");
+ t.index("substitutionId");
+
+ t.uuid("userId");
+ t.foreign("userId").references("id").inTable(TableName.Users).onDelete("CASCADE");
+
+ t.uuid("identityId");
+ t.foreign("identityId").references("id").inTable(TableName.Identity).onDelete("CASCADE");
+
+ t.binary("encryptedValue").notNullable();
+
+ t.timestamps(true, true, true);
+ });
+
+ await knex.raw(
+ `ALTER TABLE ?? ADD CONSTRAINT "agent_vault_personal_values_one_owner" CHECK (num_nonnulls("userId", "identityId") = 1)`,
+ [TableName.AgentVaultPersonalValue]
+ );
+ await knex.raw(
+ `ALTER TABLE ?? ADD CONSTRAINT "agent_vault_personal_values_field_check" CHECK (
+ ("field" = 'custom-header' AND "customHeaderId" IS NOT NULL AND "substitutionId" IS NULL)
+ OR ("field" = 'substitution' AND "substitutionId" IS NOT NULL AND "customHeaderId" IS NULL)
+ OR ("field" IN ('credential-value', 'credential-username') AND "customHeaderId" IS NULL AND "substitutionId" IS NULL)
+ )`,
+ [TableName.AgentVaultPersonalValue]
+ );
+ await knex.raw(
+ `CREATE UNIQUE INDEX "agent_vault_personal_values_user_unique" ON ?? ("userId", "serviceId", "field", COALESCE("customHeaderId", ${NO_TARGET}), COALESCE("substitutionId", ${NO_TARGET})) WHERE "userId" IS NOT NULL`,
+ [TableName.AgentVaultPersonalValue]
+ );
+ await knex.raw(
+ `CREATE UNIQUE INDEX "agent_vault_personal_values_identity_unique" ON ?? ("identityId", "serviceId", "field", COALESCE("customHeaderId", ${NO_TARGET}), COALESCE("substitutionId", ${NO_TARGET})) WHERE "identityId" IS NOT NULL`,
+ [TableName.AgentVaultPersonalValue]
+ );
+
+ await createOnUpdateTrigger(knex, TableName.AgentVaultPersonalValue);
+ }
+
+ if (!(await knex.schema.hasTable(TableName.AgentVaultPersonalValueReference))) {
+ await knex.schema.createTable(TableName.AgentVaultPersonalValueReference, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+
+ t.uuid("personalValueId").notNullable();
+ t.foreign("personalValueId", "agent_vault_personal_value_refs_value_foreign")
+ .references("id")
+ .inTable(TableName.AgentVaultPersonalValue)
+ .onDelete("CASCADE");
+ t.index("personalValueId");
+
+ // Deferred for the same reason as agent_vault_service_variable_references.variableId: deleting a user cascades
+ // to their variables and their personal values in one statement, and an immediate check can run before the
+ // personal value cascade has removed these rows.
+ t.uuid("variableId").notNullable();
+ t.foreign("variableId", "agent_vault_personal_value_refs_variable_foreign")
+ .references("id")
+ .inTable(TableName.AgentVaultVariable)
+ .deferrable("deferred");
+ t.index("variableId");
+
+ t.timestamps(true, true, true);
+ });
+
+ await createOnUpdateTrigger(knex, TableName.AgentVaultPersonalValueReference);
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ await knex.schema.dropTableIfExists(TableName.AgentVaultPersonalValueReference);
+ await dropOnUpdateTrigger(knex, TableName.AgentVaultPersonalValueReference);
+
+ await knex.schema.dropTableIfExists(TableName.AgentVaultPersonalValue);
+ await dropOnUpdateTrigger(knex, TableName.AgentVaultPersonalValue);
+
+ // The analytics views select these columns, and Postgres won't drop a column a view uses.
+ if (await knex.schema.hasColumn(TableName.AgentVaultService, "memberProvidedFields")) {
+ await knex.raw(`DROP VIEW IF EXISTS analytics.??`, [TableName.AgentVaultService]);
+ await knex.schema.alterTable(TableName.AgentVaultService, (t) => {
+ t.dropColumn("memberProvidedFields");
+ });
+ }
+
+ 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 shared namespace, where their keys may clash.
+ await knex(TableName.AgentVaultVariable).whereNotNull("userId").orWhereNotNull("identityId").delete();
+ await knex.raw(`DROP INDEX IF EXISTS ??`, [SHARED_KEY_UNIQUE]);
+ await knex.raw(`DROP INDEX IF EXISTS ??`, [USER_KEY_UNIQUE]);
+ await knex.raw(`DROP INDEX IF EXISTS ??`, [IDENTITY_KEY_UNIQUE]);
+ await knex.raw(`ALTER TABLE ?? DROP CONSTRAINT IF EXISTS "agent_vault_variables_one_owner"`, [
+ TableName.AgentVaultVariable
+ ]);
+ await knex.schema.alterTable(TableName.AgentVaultVariable, (t) => {
+ t.dropIndex("projectId");
+ t.dropForeign(["userId"]);
+ t.dropColumn("userId");
+ t.dropForeign(["identityId"]);
+ t.dropColumn("identityId");
+ t.unique(["projectId", "key"], { indexName: PROJECT_KEY_UNIQUE });
+ });
+ }
+}
diff --git a/backend/src/db/sanitized-schema.yaml b/backend/src/db/sanitized-schema.yaml
index 7da65aa13d..c55fff6d61 100644
--- a/backend/src/db/sanitized-schema.yaml
+++ b/backend/src/db/sanitized-schema.yaml
@@ -43,6 +43,17 @@ tables:
- createdAt
- updatedAt
+ - name: agent_vault_personal_values
+ source: public.agent_vault_personal_values
+ columns:
+ - id
+ - serviceId
+ - field
+ - userId
+ - identityId
+ - createdAt
+ - updatedAt
+
- name: agent_vault_proxies
source: public.agent_vault_proxies
columns:
@@ -78,6 +89,7 @@ tables:
- credentialType
- allowedMethods
- allowedPathPrefixes
+ - memberProvidedFields
- createdAt
- updatedAt
@@ -116,6 +128,8 @@ tables:
columns:
- id
- projectId
+ - userId
+ - identityId
- accessBundleId
- createdAt
- updatedAt
diff --git a/backend/src/db/schemas/agent-vault-personal-value-references.ts b/backend/src/db/schemas/agent-vault-personal-value-references.ts
new file mode 100644
index 0000000000..b2a2a66e2e
--- /dev/null
+++ b/backend/src/db/schemas/agent-vault-personal-value-references.ts
@@ -0,0 +1,25 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const AgentVaultPersonalValueReferencesSchema = z.object({
+ id: z.string().uuid(),
+ personalValueId: z.string().uuid(),
+ variableId: z.string().uuid(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TAgentVaultPersonalValueReferences = z.infer<typeof AgentVaultPersonalValueReferencesSchema>;
+export type TAgentVaultPersonalValueReferencesInsert = Omit<
+ z.input<typeof AgentVaultPersonalValueReferencesSchema>,
+ TImmutableDBKeys
+>;
+export type TAgentVaultPersonalValueReferencesUpdate = Partial<
+ Omit<z.input<typeof AgentVaultPersonalValueReferencesSchema>, TImmutableDBKeys>
+>;
diff --git a/backend/src/db/schemas/agent-vault-personal-values.ts b/backend/src/db/schemas/agent-vault-personal-values.ts
new file mode 100644
index 0000000000..2ac547aea1
--- /dev/null
+++ b/backend/src/db/schemas/agent-vault-personal-values.ts
@@ -0,0 +1,29 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { zodBuffer } from "@app/lib/zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const AgentVaultPersonalValuesSchema = z.object({
+ id: z.string().uuid(),
+ serviceId: z.string().uuid(),
+ field: z.string(),
+ customHeaderId: z.string().uuid().nullable().optional(),
+ substitutionId: z.string().uuid().nullable().optional(),
+ userId: z.string().uuid().nullable().optional(),
+ identityId: z.string().uuid().nullable().optional(),
+ encryptedValue: zodBuffer,
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TAgentVaultPersonalValues = z.infer<typeof AgentVaultPersonalValuesSchema>;
+export type TAgentVaultPersonalValuesInsert = Omit<z.input<typeof AgentVaultPersonalValuesSchema>, TImmutableDBKeys>;
+export type TAgentVaultPersonalValuesUpdate = Partial<
+ Omit<z.input<typeof AgentVaultPersonalValuesSchema>, TImmutableDBKeys>
+>;
diff --git a/backend/src/db/schemas/agent-vault-services.ts b/backend/src/db/schemas/agent-vault-services.ts
index cf9dc6c62a..a9b8ee45ab 100644
--- a/backend/src/db/schemas/agent-vault-services.ts
+++ b/backend/src/db/schemas/agent-vault-services.ts
@@ -20,7 +20,8 @@ export const AgentVaultServicesSchema = z.object({
createdAt: z.date(),
updatedAt: z.date(),
allowedMethods: z.string().array().nullable().optional(),
- allowedPathPrefixes: z.string().array().nullable().optional()
+ allowedPathPrefixes: z.string().array().nullable().optional(),
+ memberProvidedFields: z.string().array().nullable().optional()
});
export type TAgentVaultServices = z.infer<typeof AgentVaultServicesSchema>;
diff --git a/backend/src/db/schemas/agent-vault-variables.ts b/backend/src/db/schemas/agent-vault-variables.ts
index 214c1bdd81..d4918d9597 100644
--- a/backend/src/db/schemas/agent-vault-variables.ts
+++ b/backend/src/db/schemas/agent-vault-variables.ts
@@ -16,7 +16,9 @@ export const AgentVaultVariablesSchema = z.object({
encryptedValue: zodBuffer,
createdAt: z.date(),
updatedAt: z.date(),
- projectId: z.string()
+ projectId: z.string(),
+ userId: z.string().uuid().nullable().optional(),
+ identityId: z.string().uuid().nullable().optional()
});
export type TAgentVaultVariables = z.infer<typeof AgentVaultVariablesSchema>;
diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.ts
index 6539387a61..6cbf752782 100644
--- a/backend/src/db/schemas/index.ts
+++ b/backend/src/db/schemas/index.ts
@@ -5,6 +5,8 @@ export * from "./access-approval-requests";
export * from "./access-approval-requests-reviewers";
export * from "./additional-privileges";
export * from "./agent-vault-access-bundles";
+export * from "./agent-vault-personal-value-references";
+export * from "./agent-vault-personal-values";
export * from "./agent-vault-proxies";
export * from "./agent-vault-service-custom-headers";
export * from "./agent-vault-service-substitutions";
diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.ts
index 2afbf3e508..bf1f16a92f 100644
--- a/backend/src/db/schemas/models.ts
+++ b/backend/src/db/schemas/models.ts
@@ -280,6 +280,8 @@ export enum TableName {
AgentVaultServiceSubstitution = "agent_vault_service_substitutions",
AgentVaultVariable = "agent_vault_variables",
AgentVaultServiceVariableReference = "agent_vault_service_variable_references",
+ AgentVaultPersonalValue = "agent_vault_personal_values",
+ AgentVaultPersonalValueReference = "agent_vault_personal_value_references",
AgentVaultSession = "agent_vault_sessions",
AgentVaultSessionAccessBundle = "agent_vault_session_access_bundles",
AgentVaultProxy = "agent_vault_proxies",
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 f6780f89eb..43932efd76 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
@@ -33,6 +33,8 @@ import {
AgentVaultMemberRevokeIdsSchema,
AgentVaultMemberSchema,
AgentVaultNameSchema,
+ AgentVaultPersonalValueInputSchema,
+ AgentVaultPersonalValuesSchema,
AgentVaultProductMemberSchema,
AgentVaultServiceSchema,
AgentVaultSubstitutionsInputSchema,
@@ -81,6 +83,11 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro
description: "List the Agent Vault access bundles you can reach",
tags: [ApiDocsTags.AgentVaultAccessBundles],
querystring: z.object({
+ requiresSetup: z
+ .enum(["true", "false"])
+ .transform((value) => value === "true")
+ .optional()
+ .describe(AGENT_VAULT.ACCESS_BUNDLE.requiresSetup),
orderBy: z
.enum(["name", "serviceCount", "createdAt"])
.default("createdAt")
@@ -93,7 +100,8 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro
accessBundles: AccessBundleSchema.extend({
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)
+ hostPatterns: z.string().array().describe(AGENT_VAULT.ACCESS_BUNDLE.hostPatterns),
+ servicesRequiringSetup: z.string().array().describe(AGENT_VAULT.ACCESS_BUNDLE.servicesRequiringSetup)
}).array(),
totalCount: z.number()
})
@@ -169,7 +177,9 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro
response: {
200: z.object({
accessBundle: AccessBundleSchema.extend({
- services: AgentVaultServiceSchema.partial({ variableReferences: true }).array()
+ services: AgentVaultServiceSchema.partial({ variableReferences: true })
+ .extend({ personalValues: AgentVaultPersonalValuesSchema.nullable() })
+ .array()
})
})
}
@@ -334,6 +344,10 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro
service.credential.type === AgentVaultCredentialType.Bearer ? service.credential.headerPrefix : undefined,
allowedMethods: service.allowedMethods,
allowedPathPrefixes: service.allowedPathPrefixes,
+ memberProvidedFields:
+ service.credential.type === AgentVaultCredentialType.Passthrough
+ ? undefined
+ : service.credential.memberProvidedFields,
customHeaderNames: service.customHeaders.map((header) => header.name),
substitutionPlaceholders: service.substitutions.map((substitution) => substitution.placeholder),
variableKeys: variableKeysOf(service)
@@ -425,6 +439,11 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro
: undefined,
allowedMethods: req.body.allowedMethods,
allowedPathPrefixes: req.body.allowedPathPrefixes,
+ // The setting after the update, present whenever the update touched the credential.
+ memberProvidedFields:
+ req.body.credential && service.credential.type !== AgentVaultCredentialType.Passthrough
+ ? service.credential.memberProvidedFields
+ : undefined,
customHeaderNames: req.body.customHeaders?.map((header) => header.name),
// A row omitting a value keeps the stored secret, so sending one is what marks a rotation.
// Without this a rotation and a no-op save write the same row.
@@ -511,6 +530,109 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro
}
});
+ // The caller's own values for a service that leaves some fields to each member. Always the caller's: nobody, an
+ // admin included, can name or read another's, and a stored value never comes back. Read them with the bundle.
+ server.route({
+ method: "PATCH",
+ url: "/:accessBundleId/services/:serviceId/personal-values",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "setAgentVaultServicePersonalValues",
+ description:
+ "Set your personal values for a service. A field you send replaces what you saved for it, and a field you leave out keeps its saved value. Every field the service leaves to its members must be set once the update is applied.",
+ tags: [ApiDocsTags.AgentVaultAccessBundles],
+ params: z.object({
+ accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId),
+ 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)
+ }),
+ response: { 200: z.object({ personalValues: AgentVaultPersonalValuesSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
+ handler: async (req) => {
+ const { personalValues, replaced } = await server.services.agentVaultPersonalValue.setPersonalValues({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req),
+ accessBundleId: req.params.accessBundleId,
+ serviceId: req.params.serviceId,
+ values: req.body.values
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_PERSONAL_VALUES_SET,
+ metadata: {
+ accessBundleId: personalValues.accessBundleId,
+ accessBundleName: personalValues.accessBundleName,
+ serviceId: personalValues.serviceId,
+ serviceName: personalValues.serviceName,
+ fields: req.body.values.map((value) => value.field),
+ replaced,
+ variableKeys: [
+ ...new Set(
+ personalValues.fields
+ .filter((field) => req.body.values.some((value) => value.field === field.field))
+ .flatMap((field) => field.variableReferences.map((reference) => reference.key))
+ )
+ ]
+ }
+ }
+ });
+
+ return { personalValues: { isConfigured: personalValues.isConfigured, fields: personalValues.fields } };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:accessBundleId/services/:serviceId/personal-values",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "deleteAgentVaultServicePersonalValues",
+ description:
+ "Delete your personal values for a service. Until you set them again, the proxy refuses that service's requests from your sessions.",
+ tags: [ApiDocsTags.AgentVaultAccessBundles],
+ params: z.object({
+ accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId),
+ serviceId: z.string().uuid().describe(AGENT_VAULT.SERVICE.serviceId)
+ }),
+ response: { 200: z.object({ personalValues: AgentVaultPersonalValuesSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
+ handler: async (req) => {
+ const { personalValues } = await server.services.agentVaultPersonalValue.deletePersonalValues({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req),
+ accessBundleId: req.params.accessBundleId,
+ serviceId: req.params.serviceId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_PERSONAL_VALUES_DELETE,
+ metadata: {
+ accessBundleId: personalValues.accessBundleId,
+ accessBundleName: personalValues.accessBundleName,
+ serviceId: personalValues.serviceId,
+ serviceName: personalValues.serviceName
+ }
+ }
+ });
+
+ return { personalValues: { isConfigured: personalValues.isConfigured, fields: personalValues.fields } };
+ }
+ });
+
server.route({
method: "GET",
url: "/:accessBundleId/members",
diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.ts
index 80c17f6e36..941a1636a9 100644
--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.ts
+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.ts
@@ -182,7 +182,8 @@ export const registerAgentVaultProxyAgentRouter = async (server: FastifyZodProvi
customHeaders: z.object({ name: z.string(), prefix: z.string(), value: z.string() }).array(),
substitutions: z
.object({ placeholder: z.string(), surfaces: z.string().array(), value: z.string() })
- .array()
+ .array(),
+ personalValuesMissing: z.boolean()
})
.array(),
sessionLogs: z.object({
diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts
index 2b00197177..e46266af89 100644
--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts
+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts
@@ -10,7 +10,9 @@ import {
AgentVaultHttpMethod,
AgentVaultMemberType,
AgentVaultSubstitutionSurface,
- AgentVaultVariableReferenceField
+ AgentVaultVariableReferenceField,
+ AgentVaultVariableScope,
+ TAgentVaultMemberProvidedField
} from "@app/ee/services/agent-vault/agent-vault-enums";
import { hostPatternSchema } from "@app/ee/services/agent-vault/agent-vault-host-pattern-fns";
import { agentVaultPathPrefixListSchema } from "@app/ee/services/agent-vault/agent-vault-path-prefix-schemas";
@@ -41,23 +43,75 @@ export const AgentVaultNameSchema = slugSchema({ max: 64, field: "Name" });
export const AgentVaultHostPatternSchema = hostPatternSchema.describe(AGENT_VAULT.SERVICE.hostPattern);
-const basicHalvesAreNotBothEmpty = (
- data: { type: AgentVaultCredentialType; username?: string; password?: string },
- ctx: z.RefinementCtx
-) => {
- // Either half may be blank, but not both. The check cannot be an object-level refine, because
- // discriminatedUnion options must be plain objects.
- if (data.type !== AgentVaultCredentialType.Basic) return;
- if (data.username === undefined || data.password === undefined) return;
- if (data.username.length > 0 || data.password.length > 0) return;
-
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- path: ["username"],
- message: "A basic credential needs a username, a password, or both"
- });
+const bearerMemberProvidedFieldsSchema = z
+ .enum([AgentVaultVariableReferenceField.CredentialValue])
+ .array()
+ .max(1)
+ .describe(AGENT_VAULT.SERVICE.bearerMemberProvidedFields);
+
+const basicMemberProvidedFieldsSchema = z
+ .enum([AgentVaultVariableReferenceField.CredentialUsername, AgentVaultVariableReferenceField.CredentialValue])
+ .array()
+ .max(2)
+ .describe(AGENT_VAULT.SERVICE.basicMemberProvidedFields);
+
+type TCredentialShape = {
+ type: AgentVaultCredentialType;
+ value?: string;
+ username?: string;
+ password?: string;
+ memberProvidedFields?: TAgentVaultMemberProvidedField[];
+};
+
+// The member-provided field each admin credential field stands in for.
+const MEMBER_FIELD_OF_INPUT: Record<"value" | "username" | "password", TAgentVaultMemberProvidedField> = {
+ value: AgentVaultVariableReferenceField.CredentialValue,
+ username: AgentVaultVariableReferenceField.CredentialUsername,
+ password: AgentVaultVariableReferenceField.CredentialValue
};
+// Discriminated union options must be plain objects, so the checks that read two fields run on the union.
+const checkCredentialFields =
+ ({ requireValues }: { requireValues: boolean }) =>
+ (data: TCredentialShape, ctx: z.RefinementCtx) => {
+ const memberProvided = new Set(data.memberProvidedFields ?? []);
+
+ // A member-provided field has no admin value: each member sends their own.
+ (["value", "username", "password"] as const).forEach((field) => {
+ if (data[field] !== undefined && memberProvided.has(MEMBER_FIELD_OF_INPUT[field])) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: [field],
+ message: `Leave '${field}' out: memberProvidedFields lists '${MEMBER_FIELD_OF_INPUT[field]}', so each member sets it.`
+ });
+ }
+ });
+
+ if (!requireValues) return;
+
+ if (
+ data.type === AgentVaultCredentialType.Bearer &&
+ data.value === undefined &&
+ !memberProvided.has(AgentVaultVariableReferenceField.CredentialValue)
+ ) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["value"],
+ message: "A bearer credential needs a token. Set one, or leave the token to each member."
+ });
+ }
+
+ // Either half may be blank, but not both, unless a member sets one of them.
+ if (data.type === AgentVaultCredentialType.Basic && !memberProvided.size && !data.username && !data.password) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["username"],
+ message: "A basic credential needs a username, a password, or both"
+ });
+ }
+ };
+
+// Value fields are optional in the shape so a member-provided one can be left out; the refine requires the rest.
export const AgentVaultCredentialInputSchema = z
.discriminatedUnion("type", [
z
@@ -67,7 +121,10 @@ export const AgentVaultCredentialInputSchema = z
headerPrefix: agentVaultHeaderPrefixSchema.optional().describe(AGENT_VAULT.SERVICE.headerPrefix),
value: acceptsVariableReferences(
z.string().min(1).max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)
- ).describe(AGENT_VAULT.SERVICE.value)
+ )
+ .optional()
+ .describe(AGENT_VAULT.SERVICE.value),
+ memberProvidedFields: bearerMemberProvidedFieldsSchema.optional()
})
.describe(JSON.stringify({ title: "Bearer" })),
z
@@ -75,17 +132,22 @@ export const AgentVaultCredentialInputSchema = z
type: z.literal(AgentVaultCredentialType.Basic),
username: acceptsVariableReferences(
z.string().trim().max(256).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)
- ).describe(AGENT_VAULT.SERVICE.username),
+ )
+ .optional()
+ .describe(AGENT_VAULT.SERVICE.username),
password: acceptsVariableReferences(
z.string().max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)
- ).describe(AGENT_VAULT.SERVICE.password)
+ )
+ .optional()
+ .describe(AGENT_VAULT.SERVICE.password),
+ memberProvidedFields: basicMemberProvidedFieldsSchema.optional()
})
.describe(JSON.stringify({ title: "Basic Auth" })),
z
.object({ type: z.literal(AgentVaultCredentialType.Passthrough) })
.describe(JSON.stringify({ title: "Pass-through" }))
])
- .superRefine(basicHalvesAreNotBothEmpty);
+ .superRefine(checkCredentialFields({ requireValues: true }));
// Not derived from the create schema: its `.default()`s would turn an omitted field into a reset on a PATCH.
export const AgentVaultCredentialUpdateSchema = z
@@ -99,7 +161,8 @@ export const AgentVaultCredentialUpdateSchema = z
z.string().min(1).max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)
)
.optional()
- .describe(AGENT_VAULT.SERVICE.updateValue)
+ .describe(AGENT_VAULT.SERVICE.updateValue),
+ memberProvidedFields: bearerMemberProvidedFieldsSchema.optional()
})
.describe(JSON.stringify({ title: "Bearer" })),
z
@@ -114,24 +177,54 @@ export const AgentVaultCredentialUpdateSchema = z
z.string().max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)
)
.optional()
- .describe(AGENT_VAULT.SERVICE.updatePassword)
+ .describe(AGENT_VAULT.SERVICE.updatePassword),
+ memberProvidedFields: basicMemberProvidedFieldsSchema.optional()
})
.describe(JSON.stringify({ title: "Basic Auth" })),
z
.object({ type: z.literal(AgentVaultCredentialType.Passthrough) })
.describe(JSON.stringify({ title: "Pass-through" }))
])
- .superRefine(basicHalvesAreNotBothEmpty);
+ .superRefine((data, ctx) => {
+ checkCredentialFields({ requireValues: false })(data, ctx);
+ // A full basic update must still leave a half to send. A partial one is checked against what is stored.
+ if (
+ data.type === AgentVaultCredentialType.Basic &&
+ data.username !== undefined &&
+ data.password !== undefined &&
+ !data.memberProvidedFields?.length &&
+ !data.username &&
+ !data.password
+ ) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["username"],
+ message: "A basic credential needs a username, a password, or both"
+ });
+ }
+ });
export const AgentVaultCredentialSummarySchema = z.discriminatedUnion("type", [
z
.object({
type: z.literal(AgentVaultCredentialType.Bearer),
headerName: z.string().describe(AGENT_VAULT.SERVICE.headerName),
- headerPrefix: z.string().describe(AGENT_VAULT.SERVICE.headerPrefix)
+ headerPrefix: z.string().describe(AGENT_VAULT.SERVICE.headerPrefix),
+ memberProvidedFields: z
+ .enum([AgentVaultVariableReferenceField.CredentialValue])
+ .array()
+ .describe(AGENT_VAULT.SERVICE.memberProvidedFields)
})
.describe(JSON.stringify({ title: "Bearer" })),
- z.object({ type: z.literal(AgentVaultCredentialType.Basic) }).describe(JSON.stringify({ title: "Basic Auth" })),
+ z
+ .object({
+ type: z.literal(AgentVaultCredentialType.Basic),
+ memberProvidedFields: z
+ .enum([AgentVaultVariableReferenceField.CredentialUsername, AgentVaultVariableReferenceField.CredentialValue])
+ .array()
+ .describe(AGENT_VAULT.SERVICE.memberProvidedFields)
+ })
+ .describe(JSON.stringify({ title: "Basic Auth" })),
z
.object({ type: z.literal(AgentVaultCredentialType.Passthrough) })
.describe(JSON.stringify({ title: "Pass-through" }))
@@ -251,6 +344,7 @@ export const AgentVaultVariableValueSchema = z
export const AgentVaultVariableSchema = z.object({
id: z.string().uuid().describe(AGENT_VAULT.VARIABLE.variableId),
key: z.string().describe(AGENT_VAULT.VARIABLE.key),
+ scope: z.nativeEnum(AgentVaultVariableScope).describe(AGENT_VAULT.VARIABLE.scope),
usedByServices: z
.object({
id: z.string().uuid().describe(AGENT_VAULT.VARIABLE.usedByServiceId),
@@ -265,6 +359,40 @@ export const AgentVaultVariableSchema = z.object({
updatedAt: z.date().describe(AGENT_VAULT.VARIABLE.updatedAt)
});
+const personalValueFieldSchema = z
+ .enum([AgentVaultVariableReferenceField.CredentialValue, AgentVaultVariableReferenceField.CredentialUsername])
+ .describe(AGENT_VAULT.PERSONAL_VALUE.field);
+
+// The caller's own values for one service. Fields are listed as descriptors, so a custom header or substitution left
+// to members can join them with its id and no change to this shape.
+export const AgentVaultPersonalValuesSchema = z
+ .object({
+ isConfigured: z.boolean().describe(AGENT_VAULT.PERSONAL_VALUE.isConfigured),
+ fields: z
+ .object({
+ field: personalValueFieldSchema,
+ isSet: z.boolean().describe(AGENT_VAULT.PERSONAL_VALUE.isSet),
+ updatedAt: z.date().nullable().describe(AGENT_VAULT.PERSONAL_VALUE.updatedAt),
+ variableReferences: z
+ .object({
+ variableId: z.string().uuid().describe(AGENT_VAULT.VARIABLE.variableId),
+ key: z.string().describe(AGENT_VAULT.VARIABLE.key)
+ })
+ .array()
+ .describe(AGENT_VAULT.PERSONAL_VALUE.variableReferences)
+ })
+ .array()
+ .describe(AGENT_VAULT.PERSONAL_VALUE.fields)
+ })
+ .describe(AGENT_VAULT.PERSONAL_VALUE.personalValues);
+
+export const AgentVaultPersonalValueInputSchema = z.object({
+ field: personalValueFieldSchema,
+ value: acceptsVariableReferences(
+ z.string().min(1).max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)
+ ).describe(AGENT_VAULT.PERSONAL_VALUE.value)
+});
+
const memberIdsShape = (docs: { userIds: string; machineIdentityIds: string; groupIds: string }) => ({
userIds: z.string().uuid().array().default([]).describe(docs.userIds),
machineIdentityIds: z.string().uuid().array().default([]).describe(docs.machineIdentityIds),
diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-variable-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-variable-router.ts
index 4fe6c40ef2..48e291d97a 100644
--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-variable-router.ts
+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-variable-router.ts
@@ -1,5 +1,6 @@
import { z } from "zod";
+import { AgentVaultVariableScope } from "@app/ee/services/agent-vault/agent-vault-enums";
import { AGENT_VAULT_VARIABLE_KEY_MAX_LENGTH } from "@app/ee/services/agent-vault/agent-vault-variable-fns";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { AGENT_VAULT } from "@app/lib/api-docs";
@@ -29,9 +30,13 @@ export const registerAgentVaultVariableRouter = async (server: FastifyZodProvide
schema: {
hide: false,
operationId: "listAgentVaultVariables",
- description: "List the variables in Agent Vault",
+ description: "List Agent Vault's shared variables, or your own personal ones",
tags: [ApiDocsTags.AgentVaultVariables],
querystring: z.object({
+ scope: z
+ .nativeEnum(AgentVaultVariableScope)
+ .default(AgentVaultVariableScope.Shared)
+ .describe(AGENT_VAULT.VARIABLE.listScope),
orderBy: z.enum(["key", "serviceCount"]).default("key").describe(AGENT_VAULT.VARIABLE.orderBy),
orderDirection: z.enum(["asc", "desc"]).default("asc").describe(AGENT_VAULT.VARIABLE.orderDirection),
keys: z
@@ -69,9 +74,13 @@ export const registerAgentVaultVariableRouter = async (server: FastifyZodProvide
schema: {
hide: false,
operationId: "createAgentVaultVariable",
- description: "Create a variable in Agent Vault",
+ description: "Create a shared variable, or a personal one of your own",
tags: [ApiDocsTags.AgentVaultVariables],
body: z.object({
+ scope: z
+ .nativeEnum(AgentVaultVariableScope)
+ .default(AgentVaultVariableScope.Shared)
+ .describe(AGENT_VAULT.VARIABLE.createScope),
key: AgentVaultVariableKeySchema.describe(AGENT_VAULT.VARIABLE.key),
value: AgentVaultVariableValueSchema.describe(AGENT_VAULT.VARIABLE.value)
}),
@@ -91,13 +100,13 @@ export const registerAgentVaultVariableRouter = async (server: FastifyZodProvide
projectId: req.internalAgentVaultProjectId,
event: {
type: EventType.AGENT_VAULT_VARIABLE_CREATE,
- metadata: { variableId: variable.id, key: variable.key }
+ metadata: { variableId: variable.id, key: variable.key, scope: variable.scope }
}
});
emitAgentVaultTelemetry(server.services.telemetry, req, {
event: PostHogEventTypes.AgentVaultVariableCreated,
- properties: { variableId: variable.id }
+ properties: { variableId: variable.id, scope: variable.scope }
});
return { variable };
@@ -111,7 +120,7 @@ export const registerAgentVaultVariableRouter = async (server: FastifyZodProvide
schema: {
hide: false,
operationId: "updateAgentVaultVariable",
- description: "Update a variable in Agent Vault",
+ description: "Update a shared variable, or a personal one of your own",
tags: [ApiDocsTags.AgentVaultVariables],
params: z.object({
variableId: z.string().uuid().describe(AGENT_VAULT.VARIABLE.variableId)
@@ -145,6 +154,7 @@ export const registerAgentVaultVariableRouter = async (server: FastifyZodProvide
metadata: {
variableId: variable.id,
key: variable.key,
+ scope: variable.scope,
previousKey: previousKey === variable.key ? undefined : previousKey,
valueReplaced: req.body.value !== undefined
}
@@ -155,6 +165,7 @@ export const registerAgentVaultVariableRouter = async (server: FastifyZodProvide
event: PostHogEventTypes.AgentVaultVariableUpdated,
properties: {
variableId: variable.id,
+ scope: variable.scope,
keyChanged: previousKey !== variable.key,
valueReplaced: req.body.value !== undefined,
usedByServiceCount: variable.usedByServices.length
@@ -172,7 +183,8 @@ export const registerAgentVaultVariableRouter = async (server: FastifyZodProvide
schema: {
hide: false,
operationId: "deleteAgentVaultVariable",
- description: "Delete a variable from Agent Vault. A variable a service uses can't be deleted.",
+ description:
+ "Delete a shared variable, or a personal one of your own. A variable in use, by a service or by your personal values, can't be deleted.",
tags: [ApiDocsTags.AgentVaultVariables],
params: z.object({
variableId: z.string().uuid().describe(AGENT_VAULT.VARIABLE.variableId)
@@ -193,13 +205,13 @@ export const registerAgentVaultVariableRouter = async (server: FastifyZodProvide
projectId: req.internalAgentVaultProjectId,
event: {
type: EventType.AGENT_VAULT_VARIABLE_DELETE,
- metadata: { variableId: variable.id, key: variable.key }
+ metadata: { variableId: variable.id, key: variable.key, scope: variable.scope }
}
});
emitAgentVaultTelemetry(server.services.telemetry, req, {
event: PostHogEventTypes.AgentVaultVariableDeleted,
- properties: { variableId: variable.id }
+ properties: { variableId: variable.id, scope: variable.scope }
});
return { variable };
@@ -213,7 +225,7 @@ export const registerAgentVaultVariableRouter = async (server: FastifyZodProvide
schema: {
hide: false,
operationId: "getAgentVaultVariableValue",
- description: "Get the value of a variable in Agent Vault",
+ description: "Get the value of a shared variable, or a personal one of your own",
tags: [ApiDocsTags.AgentVaultVariables],
params: z.object({
variableId: z.string().uuid().describe(AGENT_VAULT.VARIABLE.variableId)
@@ -222,7 +234,7 @@ export const registerAgentVaultVariableRouter = async (server: FastifyZodProvide
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
handler: async (req, reply) => {
- const { variableId, key, value } = await server.services.agentVaultVariable.getVariableValue({
+ const { variable, value } = await server.services.agentVaultVariable.getVariableValue({
projectId: req.internalAgentVaultProjectId,
ctx: actorContext(req),
variableId: req.params.variableId
@@ -234,7 +246,7 @@ export const registerAgentVaultVariableRouter = async (server: FastifyZodProvide
projectId: req.internalAgentVaultProjectId,
event: {
type: EventType.AGENT_VAULT_VARIABLE_VALUE_VIEW,
- metadata: { variableId, key }
+ metadata: { variableId: variable.id, key: variable.key, scope: variable.scope }
}
});
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 aa8ce81636..cb8793dd3a 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
@@ -45,9 +45,11 @@ import {
AgentVaultMemberType,
AgentVaultResourceRole,
AgentVaultSubstitutionSurface,
- AgentVaultVariableReferenceField
+ AgentVaultVariableReferenceField,
+ TAgentVaultMemberProvidedField
} from "../agent-vault/agent-vault-enums";
-import { getAgentVaultReachability } from "../agent-vault/agent-vault-permission";
+import { ownerOrNullOf } from "../agent-vault/agent-vault-owner-fns";
+import { getAgentVaultGrantedReachability, getAgentVaultReachability } from "../agent-vault/agent-vault-permission";
import {
findStoredVariableIds,
findVariableKeys,
@@ -55,10 +57,18 @@ import {
toVariableReference
} from "../agent-vault/agent-vault-variable-fns";
import { TAgentVaultMemberDALFactory } from "../agent-vault-member/agent-vault-member-dal";
+import { TAgentVaultPersonalValueDALFactory } from "../agent-vault-personal-value/agent-vault-personal-value-dal";
+import {
+ clearPersonalValuesAfterRevoke,
+ sameMemberProvidedFields
+} 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 {
TAddMembersDTO,
+ TAgentVaultBasicMemberField,
+ TAgentVaultBearerMemberField,
TAgentVaultCredentialInput,
TAgentVaultCredentialSummary,
TAgentVaultCredentialUpdate,
@@ -88,8 +98,13 @@ type TAgentVaultAccessBundleServiceFactoryDep = {
agentVaultServiceDAL: TAgentVaultServiceDALFactory;
agentVaultServiceCustomHeaderDAL: TAgentVaultServiceCustomHeaderDALFactory;
agentVaultServiceSubstitutionDAL: TAgentVaultServiceSubstitutionDALFactory;
- agentVaultVariableDAL: Pick<TAgentVaultVariableDALFactory, "findKeysByProjectId" | "lockForReference">;
+ agentVaultVariableDAL: Pick<TAgentVaultVariableDALFactory, "findKeys" | "lockForReference">;
agentVaultServiceVariableReferenceDAL: TAgentVaultServiceVariableReferenceDALFactory;
+ agentVaultPersonalValueDAL: Pick<
+ TAgentVaultPersonalValueDALFactory,
+ "delete" | "deleteForServiceExceptFields" | "deleteForActorsWithoutGrant"
+ >;
+ agentVaultPersonalValueService: Pick<TAgentVaultPersonalValueServiceFactory, "findStatusesForOwner">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
membershipDAL: Pick<
@@ -121,6 +136,8 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
agentVaultServiceSubstitutionDAL,
agentVaultVariableDAL,
agentVaultServiceVariableReferenceDAL,
+ agentVaultPersonalValueDAL,
+ agentVaultPersonalValueService,
permissionService,
kmsService,
membershipDAL,
@@ -298,30 +315,80 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });
// `null` clears the sealed column, `undefined` leaves it alone. $decryptCredential reads a NULL secret
- // as passthrough, so the two are not interchangeable.
- type TCredentialWrite = { config: TAgentVaultCredentialConfig; secret: Record<string, string> | null | undefined };
+ // as passthrough, so the two are not interchangeable. The secret holds only the fields the admin sets, so a
+ // credential every member supplies in full stores none.
+ type TCredentialWrite = {
+ config: TAgentVaultCredentialConfig;
+ secret: Record<string, string> | null | undefined;
+ memberProvidedFields: TAgentVaultMemberProvidedField[] | null;
+ };
+
+ const BASIC_NEEDS_A_HALF_MESSAGE =
+ "A basic credential needs a username, a password, or both. Set one, or leave one to each member.";
+
+ // NULL, never an empty list, is what the column stores for a credential the admin sets in full.
+ const memberFieldsOf = (credential: TAgentVaultCredentialInput): TAgentVaultMemberProvidedField[] | null => {
+ if (credential.type === AgentVaultCredentialType.Passthrough) return null;
+ const fields = [...new Set<TAgentVaultMemberProvidedField>(credential.memberProvidedFields ?? [])];
+ return fields.length ? fields : null;
+ };
const splitCredential = (credential: TAgentVaultCredentialInput): TCredentialWrite => {
+ const memberProvidedFields = memberFieldsOf(credential);
+ const isMemberProvided = (field: TAgentVaultMemberProvidedField) => Boolean(memberProvidedFields?.includes(field));
+
switch (credential.type) {
case AgentVaultCredentialType.Bearer: {
const config = AgentVaultBearerConfigSchema.parse({
headerName: credential.headerName,
headerPrefix: credential.headerPrefix
});
- return { config: { type: credential.type, ...config }, secret: { value: credential.value } };
+ if (isMemberProvided(AgentVaultVariableReferenceField.CredentialValue)) {
+ return { config: { type: credential.type, ...config }, secret: null, memberProvidedFields };
+ }
+ if (credential.value === undefined) {
+ throw new BadRequestError({
+ message: "A bearer credential needs a token. Set one, or leave the token to each member."
+ });
+ }
+ return {
+ config: { type: credential.type, ...config },
+ secret: { value: credential.value },
+ memberProvidedFields
+ };
}
case AgentVaultCredentialType.Basic: {
- if (!credential.username && !credential.password) {
- throw new BadRequestError({ message: "A basic credential needs a username, a password, or both" });
+ const secret = Object.fromEntries(
+ (
+ [
+ [AgentVaultVariableReferenceField.CredentialUsername, "username", credential.username],
+ [AgentVaultVariableReferenceField.CredentialValue, "password", credential.password]
+ ] as const
+ ).flatMap(([field, key, value]) => (isMemberProvided(field) ? [] : [[key, value ?? ""]]))
+ ) as Record<string, string>;
+ if (!memberProvidedFields && !Object.values(secret).some(Boolean)) {
+ throw new BadRequestError({ message: BASIC_NEEDS_A_HALF_MESSAGE });
}
return {
config: { type: credential.type },
- secret: { username: credential.username, password: credential.password }
+ secret: Object.keys(secret).length ? secret : null,
+ memberProvidedFields
};
}
default:
- return { config: { type: AgentVaultCredentialType.Passthrough }, secret: null };
+ return { config: { type: AgentVaultCredentialType.Passthrough }, secret: null, memberProvidedFields: null };
+ }
+ };
+
+ // The member-provided fields a PATCH ends with: an omitted list keeps the stored one.
+ const nextMemberFieldsOf = (credential: TAgentVaultCredentialUpdate, stored: TAgentVaultServices) => {
+ if (credential.type !== stored.credentialType || credential.type === AgentVaultCredentialType.Passthrough) {
+ return memberFieldsOf(credential);
}
+ if (credential.memberProvidedFields === undefined) {
+ return (stored.memberProvidedFields as TAgentVaultMemberProvidedField[] | null | undefined) ?? null;
+ }
+ return memberFieldsOf(credential);
};
const mergeCredential = (
@@ -330,58 +397,108 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
storedSecret: Record<string, string> | null
): TCredentialWrite => {
if (credential.type !== stored.credentialType) {
- if (credential.type === AgentVaultCredentialType.Bearer && credential.value === undefined) {
+ if (
+ credential.type === AgentVaultCredentialType.Bearer &&
+ credential.value === undefined &&
+ !memberFieldsOf(credential)?.includes(AgentVaultVariableReferenceField.CredentialValue)
+ ) {
throw new BadRequestError({
message:
- "Provide a new token when changing the credential type to bearer. The stored secret belongs to the previous type"
+ "Provide a new token when changing the credential type to bearer, or leave the token to each member. The stored secret belongs to the previous type"
});
}
- return splitCredential(
- credential.type === AgentVaultCredentialType.Basic
- ? { type: credential.type, username: credential.username ?? "", password: credential.password ?? "" }
- : (credential as TAgentVaultCredentialInput)
- );
+ return splitCredential(credential);
}
const prev = (stored.credentialConfig ?? {}) as { headerName?: string; headerPrefix?: string };
+ const previousMemberFields = (stored.memberProvidedFields ?? []) as TAgentVaultMemberProvidedField[];
+ const memberProvidedFields = nextMemberFieldsOf(credential, stored);
+ const memberFieldsChanged = !sameMemberProvidedFields(memberProvidedFields, previousMemberFields);
+ const isMemberProvided = (field: TAgentVaultMemberProvidedField) => Boolean(memberProvidedFields?.includes(field));
+
+ // The schema only sees the member-provided list a request sends. One that leaves the list out keeps the stored
+ // one, so a value for a field that list hands to members is refused here rather than dropped.
+ const memberFieldOfKey: Record<string, TAgentVaultMemberProvidedField> =
+ credential.type === AgentVaultCredentialType.Bearer
+ ? { value: AgentVaultVariableReferenceField.CredentialValue }
+ : {
+ username: AgentVaultVariableReferenceField.CredentialUsername,
+ password: AgentVaultVariableReferenceField.CredentialValue
+ };
+ const sentToMemberField = Object.entries(memberFieldOfKey).find(
+ ([key, field]) => (credential as Record<string, unknown>)[key] !== undefined && isMemberProvided(field)
+ );
+ if (sentToMemberField) {
+ throw new BadRequestError({
+ message: `Leave '${sentToMemberField[0]}' out: '${sentToMemberField[1]}' is member provided, so each member sets it. To set it yourself, send memberProvidedFields without '${sentToMemberField[1]}'.`
+ });
+ }
switch (credential.type) {
- case AgentVaultCredentialType.Bearer:
- return {
- config: {
- type: credential.type,
- headerName: credential.headerName ?? prev.headerName ?? "Authorization",
- headerPrefix: credential.headerPrefix ?? prev.headerPrefix ?? ""
- },
- secret: credential.value === undefined ? undefined : { value: credential.value }
+ case AgentVaultCredentialType.Bearer: {
+ const config = {
+ type: credential.type,
+ headerName: credential.headerName ?? prev.headerName ?? "Authorization",
+ headerPrefix: credential.headerPrefix ?? prev.headerPrefix ?? ""
};
+ if (isMemberProvided(AgentVaultVariableReferenceField.CredentialValue)) {
+ return { config, secret: memberFieldsChanged ? null : undefined, memberProvidedFields };
+ }
+ if (credential.value !== undefined) {
+ return { config, secret: { value: credential.value }, memberProvidedFields };
+ }
+ if (memberFieldsChanged) {
+ throw new BadRequestError({
+ message: "Provide a token when you stop leaving it to each member. Nothing is stored for it yet."
+ });
+ }
+ return { config, secret: undefined, memberProvidedFields };
+ }
case AgentVaultCredentialType.Basic: {
- if (credential.username === undefined && credential.password === undefined) {
- return { config: { type: credential.type }, secret: undefined };
+ if (credential.username === undefined && credential.password === undefined && !memberFieldsChanged) {
+ return { config: { type: credential.type }, secret: undefined, memberProvidedFields };
}
- const username = credential.username ?? storedSecret?.username ?? "";
- const password = credential.password ?? storedSecret?.password ?? "";
- if (!username && !password) {
- throw new BadRequestError({ message: "A basic credential needs a username, a password, or both" });
+ // A half that was member-provided has nothing stored to keep, so taking it back starts it empty.
+ const adminHalf = (field: TAgentVaultMemberProvidedField, key: "username" | "password") => {
+ if (isMemberProvided(field)) return [];
+ const sent = credential[key];
+ if (sent !== undefined) return [[key, sent]];
+ return [[key, previousMemberFields.includes(field) ? "" : (storedSecret?.[key] ?? "")]];
+ };
+ const secret = Object.fromEntries([
+ ...adminHalf(AgentVaultVariableReferenceField.CredentialUsername, "username"),
+ ...adminHalf(AgentVaultVariableReferenceField.CredentialValue, "password")
+ ]) as Record<string, string>;
+ if (!memberProvidedFields && !Object.values(secret).some(Boolean)) {
+ throw new BadRequestError({ message: BASIC_NEEDS_A_HALF_MESSAGE });
}
- return { config: { type: credential.type }, secret: { username, password } };
+ return {
+ config: { type: credential.type },
+ secret: Object.keys(secret).length ? secret : null,
+ memberProvidedFields
+ };
}
default:
- return { config: { type: AgentVaultCredentialType.Passthrough }, secret: null };
+ return { config: { type: AgentVaultCredentialType.Passthrough }, secret: null, memberProvidedFields: null };
}
};
const summarizeCredential = (service: TAgentVaultServices): TAgentVaultCredentialSummary => {
const config = service.credentialConfig as Record<string, string>;
+ const memberProvidedFields = service.memberProvidedFields ?? [];
switch (service.credentialType as AgentVaultCredentialType) {
case AgentVaultCredentialType.Bearer:
return {
type: AgentVaultCredentialType.Bearer,
headerName: config.headerName,
- headerPrefix: config.headerPrefix
+ headerPrefix: config.headerPrefix,
+ memberProvidedFields: memberProvidedFields as TAgentVaultBearerMemberField[]
};
case AgentVaultCredentialType.Basic:
- return { type: AgentVaultCredentialType.Basic };
+ return {
+ type: AgentVaultCredentialType.Basic,
+ memberProvidedFields: memberProvidedFields as TAgentVaultBasicMemberField[]
+ };
default:
return { type: AgentVaultCredentialType.Passthrough };
}
@@ -484,7 +601,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
return { idOfKey: new Map<string, string>(), variableIds: new Set<string>() };
}
- const variables = await agentVaultVariableDAL.findKeysByProjectId(projectId);
+ const variables = await agentVaultVariableDAL.findKeys({ projectId, owner: null });
const idOfKey = new Map(variables.map((variable) => [variable.key, variable.id]));
texts.forEach(({ label, text }) => {
@@ -576,7 +693,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
) => {
if (!rows.length) return;
const variableIds = [...new Set(rows.map((row) => row.variableId))];
- const present = await agentVaultVariableDAL.lockForReference({ projectId, variableIds }, tx);
+ const present = await agentVaultVariableDAL.lockForReference({ projectId, owner: null, variableIds }, tx);
if (present.length !== variableIds.length) {
throw new BadRequestError({ message: VARIABLE_DELETED_DURING_SAVE_MESSAGE });
}
@@ -634,8 +751,10 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
return { bundle, ...reachability };
};
- const listAccessBundles = async ({ projectId, ctx, ...page }: TListAccessBundlesDTO) => {
- const { permission, accessBundleIds } = await getAgentVaultReachability(
+ // 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.
+ const listAccessBundles = async ({ projectId, ctx, requiresSetup, ...page }: TListAccessBundlesDTO) => {
+ const { permission, accessBundleIds, grantedAccessBundleIds } = await getAgentVaultGrantedReachability(
{ permissionService, membershipDAL },
{ projectId, ctx }
);
@@ -644,7 +763,57 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
ProjectPermissionSub.AgentVaultAccessBundles
);
- return agentVaultAccessBundleDAL.findForList({ projectId, accessBundleIds, ...page });
+ const owner = ownerOrNullOf(ctx);
+ const pendingByBundleOf = async (bundleIds: string[]) => {
+ const byBundle = new Map<string, string[]>();
+ if (!owner || !bundleIds.length) return byBundle;
+ const statuses = await agentVaultPersonalValueService.findStatusesForOwner({
+ projectId,
+ owner,
+ accessBundleIds: bundleIds,
+ withVariableReferences: false
+ });
+ statuses
+ .filter((status) => !status.isConfigured)
+ .forEach((status) =>
+ byBundle.set(status.accessBundleId, [...(byBundle.get(status.accessBundleId) ?? []), status.serviceName])
+ );
+ return byBundle;
+ };
+
+ // The filter needs every granted bundle's status before it can page; the plain list only needs the page's.
+ if (requiresSetup) {
+ const pendingByBundle = await pendingByBundleOf(grantedAccessBundleIds);
+ const { accessBundles, totalCount } = await agentVaultAccessBundleDAL.findForList({
+ projectId,
+ accessBundleIds: [...pendingByBundle.keys()],
+ ...page
+ });
+ return {
+ accessBundles: accessBundles.map((bundle) => ({
+ ...bundle,
+ servicesRequiringSetup: pendingByBundle.get(bundle.id) ?? []
+ })),
+ totalCount
+ };
+ }
+
+ const { accessBundles, totalCount } = await agentVaultAccessBundleDAL.findForList({
+ projectId,
+ 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 getAccessBundleById = async (dto: TGetAccessBundleDTO) => {
@@ -666,6 +835,14 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
undefined,
{ withVariableReferences: canReadVariables }
);
+ const owner = ownerOrNullOf(dto.ctx);
+ const statuses = owner
+ ? await agentVaultPersonalValueService.findStatusesForOwner({
+ projectId: dto.projectId,
+ owner,
+ accessBundleIds: [bundle.id]
+ })
+ : [];
return {
id: bundle.id,
@@ -680,7 +857,13 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
substitutions.filter((substitution) => substitution.serviceId === service.id),
variableReferences.filter((reference) => reference.serviceId === service.id)
);
- return canReadVariables ? projected : { ...projected, variableReferences: undefined };
+ const status = statuses.find((entry) => entry.serviceId === service.id);
+ return {
+ ...projected,
+ ...(canReadVariables ? {} : { variableReferences: undefined }),
+ // The caller's own values, null when the admin sets the whole credential.
+ personalValues: status ? { isConfigured: status.isConfigured, fields: status.fields } : null
+ };
})
};
};
@@ -831,9 +1014,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
const store = (text: string) => toStoredVariableReferences(text, idOfKey);
// Encrypt before the lock: KMS is a network call and the transaction has to stay short.
- const { config, secret } = splitCredential(
- storeCredentialReferences(credential, store) as TAgentVaultCredentialInput
- );
+ const { config, secret, memberProvidedFields } = splitCredential(storeCredentialReferences(credential, store));
assertCustomHeadersDoNotShadowCredential(config, customHeaders);
const { encryptor } = await getProjectCipher(rest.projectId);
@@ -879,7 +1060,8 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
allowedPathPrefixes: allowedPathPrefixes ?? null,
credentialType: credential.type,
credentialConfig: config,
- encryptedCredential
+ encryptedCredential,
+ memberProvidedFields
},
tx
);
@@ -990,13 +1172,29 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
});
}
- // A partial basic update keeps the other half from the sealed secret read here, before the lock, so the write
- // re-checks under the lock that nothing replaced it since.
+ // A basic update that rewrites the secret keeps any admin half it left out from the sealed secret read here,
+ // before the lock, so the write re-checks under the lock that nothing replaced it since. A half that was
+ // member-provided has nothing stored to keep.
+ const previousMemberFields = (service.memberProvidedFields ?? []) as TAgentVaultMemberProvidedField[];
+ const nextMemberFields = credential ? nextMemberFieldsOf(credential, service) : null;
+ const credentialTypeChanged = Boolean(credential) && credential!.type !== service.credentialType;
+ const memberFieldsChanged =
+ credentialTypeChanged ||
+ (Boolean(credential) && !sameMemberProvidedFields(nextMemberFields, previousMemberFields));
const needsStoredSecret =
credential?.type === AgentVaultCredentialType.Basic &&
service.credentialType === AgentVaultCredentialType.Basic &&
- (credential.username === undefined) !== (credential.password === undefined) &&
- Boolean(service.encryptedCredential);
+ Boolean(service.encryptedCredential) &&
+ (credential.username !== undefined || credential.password !== undefined || memberFieldsChanged) &&
+ (
+ [
+ [AgentVaultVariableReferenceField.CredentialUsername, "username"],
+ [AgentVaultVariableReferenceField.CredentialValue, "password"]
+ ] as const
+ ).some(
+ ([field, key]) =>
+ credential[key] === undefined && !nextMemberFields?.includes(field) && !previousMemberFields.includes(field)
+ );
const storedSecretCipher = needsStoredSecret ? await getProjectCipher(rest.projectId) : null;
const storedSecret = storedSecretCipher
? (JSON.parse(
@@ -1027,7 +1225,11 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
let writtenSecret: TCredentialWrite["secret"];
let effectiveCredentialConfig = service.credentialConfig as TAgentVaultCredentialConfig;
if (credential) {
- const { config, secret } = mergeCredential(storeCredentialReferences(credential, store), service, storedSecret);
+ const { config, secret, memberProvidedFields } = mergeCredential(
+ storeCredentialReferences(credential, store),
+ service,
+ storedSecret
+ );
let encryptedCredential: Buffer | null | undefined;
if (secret === null) encryptedCredential = null;
if (secret) {
@@ -1039,6 +1241,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
credentialUpdate = {
credentialType: credential.type,
credentialConfig: config,
+ memberProvidedFields,
...(encryptedCredential === undefined ? {} : { encryptedCredential })
};
effectiveCredentialConfig = config;
@@ -1104,7 +1307,11 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
if (!current) throw new NotFoundError({ message: `Service with ID '${serviceId}' not found` });
const secretChanged =
storedSecret !== null && !current.encryptedCredential?.equals(service.encryptedCredential!);
- if (current.credentialType !== service.credentialType || secretChanged) {
+ if (
+ current.credentialType !== service.credentialType ||
+ !sameMemberProvidedFields(current.memberProvidedFields, service.memberProvidedFields) ||
+ secretChanged
+ ) {
throw new ConflictError({ message: CREDENTIAL_CHANGED_DURING_SAVE_MESSAGE });
}
}
@@ -1147,6 +1354,20 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
)
: service;
+ // A saved value goes only when it no longer applies: a new credential type drops every one, and a field the
+ // admin takes back drops that field's. A field members still provide keeps what they saved. The update above
+ // wrote the service row, which is what a personal values save waits on.
+ if (memberFieldsChanged) {
+ if (credentialTypeChanged || !nextMemberFields?.length) {
+ await agentVaultPersonalValueDAL.delete({ serviceId: service.id }, tx);
+ } else {
+ await agentVaultPersonalValueDAL.deleteForServiceExceptFields(
+ { serviceId: service.id, keepFields: nextMemberFields },
+ tx
+ );
+ }
+ }
+
// Outside the lock, two concurrent PATCHes both pass the ownership check and the loser's writes no-op.
const applyDiff = async <TRow extends { id: string; encryptedValue: Buffer }, TColumns>(
dal: {
@@ -1478,6 +1699,17 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
const rows = held.map((actor) => heldByKey.get(actorKey(actor))!);
await membershipDAL.delete({ $in: { id: rows.map((row) => row.id) } }, tx);
+ await clearPersonalValuesAfterRevoke(
+ { agentVaultPersonalValueDAL, userGroupMembershipDAL, identityGroupMembershipDAL },
+ {
+ projectId: rest.projectId,
+ accessBundleId: bundle.id,
+ userIds: rows.flatMap((row) => (row.actorUserId ? [row.actorUserId] : [])),
+ identityIds: rows.flatMap((row) => (row.actorIdentityId ? [row.actorIdentityId] : [])),
+ groupIds: rows.flatMap((row) => (row.actorGroupId ? [row.actorGroupId] : []))
+ },
+ tx
+ );
return { removed: rows, skipped };
});
diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts
index 052012abea..ae4e3a527b 100644
--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts
+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts
@@ -8,19 +8,38 @@ import {
} from "../agent-vault/agent-vault-enums";
import { TAgentVaultAccessBundleOrderBy } from "./agent-vault-access-bundle-dal";
+export type TAgentVaultBearerMemberField = AgentVaultVariableReferenceField.CredentialValue;
+export type TAgentVaultBasicMemberField =
+ | AgentVaultVariableReferenceField.CredentialUsername
+ | AgentVaultVariableReferenceField.CredentialValue;
+
+// A member-provided field never carries a value here: each member sends their own.
export type TAgentVaultCredentialInput =
- | { type: AgentVaultCredentialType.Bearer; headerName?: string; headerPrefix?: string; value: string }
- | { type: AgentVaultCredentialType.Basic; username: string; password: string }
+ | {
+ type: AgentVaultCredentialType.Bearer;
+ headerName?: string;
+ headerPrefix?: string;
+ value?: string;
+ memberProvidedFields?: TAgentVaultBearerMemberField[];
+ }
+ | {
+ type: AgentVaultCredentialType.Basic;
+ username?: string;
+ password?: string;
+ memberProvidedFields?: TAgentVaultBasicMemberField[];
+ }
| { type: AgentVaultCredentialType.Passthrough };
-export type TAgentVaultCredentialUpdate =
- | { type: AgentVaultCredentialType.Bearer; headerName?: string; headerPrefix?: string; value?: string }
- | { type: AgentVaultCredentialType.Basic; username?: string; password?: string }
- | { type: AgentVaultCredentialType.Passthrough };
+export type TAgentVaultCredentialUpdate = TAgentVaultCredentialInput;
export type TAgentVaultCredentialSummary =
- | { type: AgentVaultCredentialType.Bearer; headerName: string; headerPrefix: string }
- | { type: AgentVaultCredentialType.Basic }
+ | {
+ type: AgentVaultCredentialType.Bearer;
+ headerName: string;
+ headerPrefix: string;
+ memberProvidedFields: TAgentVaultBearerMemberField[];
+ }
+ | { type: AgentVaultCredentialType.Basic; memberProvidedFields: TAgentVaultBasicMemberField[] }
| { type: AgentVaultCredentialType.Passthrough };
export type TAgentVaultVariableReferenceSummary = { variableId: string; key: string } & (
@@ -32,6 +51,7 @@ export type TAgentVaultVariableReferenceSummary = { variableId: string; key: str
export type TAgentVaultProjectScoped = { projectId: string; ctx: TGenericPermission };
export type TListAccessBundlesDTO = TAgentVaultProjectScoped & {
+ requiresSetup?: boolean;
search?: string;
orderBy: TAgentVaultAccessBundleOrderBy;
orderDirection: "asc" | "desc";
diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-dal.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-dal.ts
index 74a7b99173..3f28831d3b 100644
--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-dal.ts
+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-dal.ts
@@ -32,5 +32,46 @@ export const agentVaultServiceDALFactory = (db: TDbClient) => {
}
};
- return { ...orm, findByAccessBundleId, findByIdInAccessBundle };
+ // Reads the primary even without a tx, like findByIdInAccessBundle.
+ const findByIdInProject = async (
+ { id, projectId }: { id: string; projectId: string },
+ tx?: Knex
+ ): Promise<(TAgentVaultServices & { accessBundleName: string }) | undefined> => {
+ try {
+ return (await (tx || db)(TableName.AgentVaultService)
+ .join(
+ TableName.AgentVaultAccessBundle,
+ `${TableName.AgentVaultService}.accessBundleId`,
+ `${TableName.AgentVaultAccessBundle}.id`
+ )
+ .where(`${TableName.AgentVaultService}.id`, id)
+ .where(`${TableName.AgentVaultAccessBundle}.projectId`, projectId)
+ .first(
+ `${TableName.AgentVaultService}.*`,
+ db.ref("name").withSchema(TableName.AgentVaultAccessBundle).as("accessBundleName")
+ )) as (TAgentVaultServices & { accessBundleName: string }) | undefined;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find agent vault service in project" });
+ }
+ };
+
+ // A personal values save holds this until it commits. A service update writes the row, so it waits for the
+ // save, and a save that starts after the update reads the fields the update left.
+ const lockForPersonalValues = async (
+ id: string,
+ tx: Knex
+ ): Promise<Pick<TAgentVaultServices, "id" | "credentialType" | "memberProvidedFields"> | undefined> => {
+ try {
+ return (await tx(TableName.AgentVaultService)
+ .where({ id })
+ .forShare()
+ .first("id", "credentialType", "memberProvidedFields")) as
+ | Pick<TAgentVaultServices, "id" | "credentialType" | "memberProvidedFields">
+ | undefined;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Lock agent vault service for personal values" });
+ }
+ };
+
+ return { ...orm, findByAccessBundleId, findByIdInAccessBundle, findByIdInProject, lockForPersonalValues };
};
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 b1b2e09d2e..5029870538 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
@@ -103,7 +103,10 @@ const buildService = ({
delete: vi.fn().mockResolvedValue(undefined)
},
projectAccessRequestDAL: { delete: vi.fn().mockResolvedValue(undefined) },
- usageMeteringService: { emitForProject: vi.fn() }
+ usageMeteringService: { emitForProject: vi.fn() },
+ agentVaultPersonalValueDAL: { deleteForActorsWithoutGrant: vi.fn().mockResolvedValue(0) },
+ userGroupMembershipDAL: { find: vi.fn().mockResolvedValue([]) },
+ identityGroupMembershipDAL: { find: vi.fn().mockResolvedValue([]) }
};
const service = agentVaultMembershipServiceFactory(
diff --git a/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.ts b/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.ts
index 1759d08aa8..42f23f7dfe 100644
--- a/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.ts
+++ b/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.ts
@@ -35,6 +35,10 @@ import { resolveUsersBySsoExternalId } from "@app/services/user-alias/user-alias
import { resolveAgentVaultActorNames, TAgentVaultActorName } from "../agent-vault/agent-vault-actor-name-fns";
import { AgentVaultMemberType } from "../agent-vault/agent-vault-enums";
+import {
+ clearPersonalValuesAfterRevoke,
+ TClearPersonalValuesDeps
+} from "../agent-vault-personal-value/agent-vault-personal-value-fns";
import { TAgentVaultMemberDALFactory } from "./agent-vault-member-dal";
type TAgentVaultMembershipServiceFactoryDep = {
@@ -49,7 +53,7 @@ type TAgentVaultMembershipServiceFactoryDep = {
orgDAL: Pick<TOrgDALFactory, "findById">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
usageMeteringService: Pick<TUsageMeteringServiceFactory, "emitForProject">;
-};
+} & TClearPersonalValuesDeps;
export type TAgentVaultMembershipServiceFactory = ReturnType<typeof agentVaultMembershipServiceFactory>;
@@ -135,7 +139,10 @@ export const agentVaultMembershipServiceFactory = ({
userAliasDAL,
orgDAL,
permissionService,
- usageMeteringService
+ usageMeteringService,
+ agentVaultPersonalValueDAL,
+ userGroupMembershipDAL,
+ identityGroupMembershipDAL
}: TAgentVaultMembershipServiceFactoryDep) => {
const getActorPermission = (projectId: string, ctx: TGenericPermission) =>
permissionService.getProjectPermission({
@@ -651,6 +658,18 @@ export const agentVaultMembershipServiceFactory = ({
// membership_roles cascades on the membership FK, so the roles go with these rows.
await membershipDAL.delete({ $in: { id: membershipIds } }, tx);
+ // Their bundle grants went above. Their own variables stay, as they would if they only lost a bundle.
+ await clearPersonalValuesAfterRevoke(
+ { agentVaultPersonalValueDAL, userGroupMembershipDAL, identityGroupMembershipDAL },
+ {
+ projectId,
+ userIds: named(held, AgentVaultMemberType.User),
+ identityIds: named(held, AgentVaultMemberType.MachineIdentity),
+ groupIds: named(held, AgentVaultMemberType.Group)
+ },
+ tx
+ );
+
return {
removed: held.map((actor) => ({
type: actor.type,
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
new file mode 100644
index 0000000000..a46921a7d2
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-personal-value/agent-vault-personal-value-dal.ts
@@ -0,0 +1,302 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import {
+ RESOURCE_SCOPE,
+ ResourceType,
+ TableName,
+ TAgentVaultPersonalValueReferences,
+ TAgentVaultPersonalValues
+} from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+import { ormify } from "@app/lib/knex";
+
+import { TAgentVaultOwner, whereOwner } from "../agent-vault/agent-vault-owner-fns";
+
+export type TAgentVaultPersonalValueDALFactory = ReturnType<typeof agentVaultPersonalValueDALFactory>;
+export type TAgentVaultPersonalValueReferenceDALFactory = ReturnType<typeof agentVaultPersonalValueReferenceDALFactory>;
+
+export type TAgentVaultPersonalValueServiceRow = {
+ serviceId: string;
+ serviceName: string;
+ hostPattern: string;
+ credentialType: string;
+ memberProvidedFields: string[];
+ accessBundleId: string;
+ accessBundleName: string;
+};
+
+export type TAgentVaultPersonalValueSummaryRow = Pick<
+ TAgentVaultPersonalValues,
+ "id" | "serviceId" | "field" | "updatedAt"
+>;
+
+export type TAgentVaultPersonalValueReferenceWithKey = TAgentVaultPersonalValueReferences & { key: string };
+
+const table = TableName.AgentVaultPersonalValue;
+
+export const agentVaultPersonalValueDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.AgentVaultPersonalValue);
+
+ /**
+ * Every service in these bundles that leaves a field to each member. `null` bundle ids means every bundle in the
+ * project. Reads the primary even without a tx, so a service changed a moment ago is listed as it is now.
+ */
+ const findServicesNeedingValues = async (
+ {
+ projectId,
+ accessBundleIds,
+ serviceId
+ }: { projectId: string; accessBundleIds: string[] | null; serviceId?: string },
+ tx?: Knex
+ ): Promise<TAgentVaultPersonalValueServiceRow[]> => {
+ if (accessBundleIds?.length === 0) return [];
+ try {
+ const query = (tx || db)(TableName.AgentVaultService)
+ .join(
+ TableName.AgentVaultAccessBundle,
+ `${TableName.AgentVaultService}.accessBundleId`,
+ `${TableName.AgentVaultAccessBundle}.id`
+ )
+ .where(`${TableName.AgentVaultAccessBundle}.projectId`, projectId)
+ .whereNotNull(`${TableName.AgentVaultService}.memberProvidedFields`);
+
+ if (accessBundleIds) void query.whereIn(`${TableName.AgentVaultAccessBundle}.id`, accessBundleIds);
+ if (serviceId) void query.where(`${TableName.AgentVaultService}.id`, serviceId);
+
+ return (await query
+ .select(
+ db.ref("id").withSchema(TableName.AgentVaultService).as("serviceId"),
+ db.ref("name").withSchema(TableName.AgentVaultService).as("serviceName"),
+ db.ref("hostPattern").withSchema(TableName.AgentVaultService),
+ db.ref("credentialType").withSchema(TableName.AgentVaultService),
+ db.ref("memberProvidedFields").withSchema(TableName.AgentVaultService),
+ db.ref("id").withSchema(TableName.AgentVaultAccessBundle).as("accessBundleId"),
+ db.ref("name").withSchema(TableName.AgentVaultAccessBundle).as("accessBundleName")
+ )
+ .orderBy([
+ { column: "accessBundleName", order: "asc" },
+ { column: "serviceName", order: "asc" }
+ ])) as TAgentVaultPersonalValueServiceRow[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find agent vault services needing personal values" });
+ }
+ };
+
+ // Reads the primary even without a tx, so a value saved a moment ago shows as set.
+ const findForOwner = async (
+ { serviceIds, owner }: { serviceIds: string[]; owner: TAgentVaultOwner },
+ tx?: Knex
+ ): Promise<TAgentVaultPersonalValueSummaryRow[]> => {
+ if (!serviceIds.length) return [];
+ try {
+ return (await whereOwner((tx || db)(table).whereIn(`${table}.serviceId`, serviceIds), table, owner).select(
+ `${table}.id`,
+ `${table}.serviceId`,
+ `${table}.field`,
+ `${table}.updatedAt`
+ )) as TAgentVaultPersonalValueSummaryRow[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find agent vault personal values" });
+ }
+ };
+
+ const lockForOwnerAndService = async (
+ { serviceId, owner }: { serviceId: string; owner: TAgentVaultOwner },
+ tx: Knex
+ ): Promise<TAgentVaultPersonalValues[]> => {
+ try {
+ return (await whereOwner(tx(table).where(`${table}.serviceId`, serviceId), table, owner)
+ .orderBy(`${table}.id`)
+ .forUpdate()
+ .select(`${table}.*`)) as TAgentVaultPersonalValues[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Lock agent vault personal values" });
+ }
+ };
+
+ // The hot path, on a replica. A value saved within the replica's lag reads as not set for one poll.
+ const findForResolve = async ({
+ serviceIds,
+ owner
+ }: {
+ serviceIds: string[];
+ owner: TAgentVaultOwner;
+ }): Promise<Pick<TAgentVaultPersonalValues, "serviceId" | "field" | "encryptedValue">[]> => {
+ if (!serviceIds.length) return [];
+ try {
+ return (await whereOwner(db.replicaNode()(table).whereIn(`${table}.serviceId`, serviceIds), table, owner).select(
+ `${table}.serviceId`,
+ `${table}.field`,
+ `${table}.encryptedValue`
+ )) as Pick<TAgentVaultPersonalValues, "serviceId" | "field" | "encryptedValue">[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find agent vault personal values for resolve" });
+ }
+ };
+
+ /**
+ * Clears what these actors saved for the services of `accessBundleId` (or of every bundle in the project) where
+ * they no longer hold a grant, directly or through any group they are in, so being granted the bundle again
+ * starts from nothing. An admin reaches every bundle without a grant, so only the actors a revoke named are
+ * considered: everyone else's values are left alone.
+ */
+ const deleteForActorsWithoutGrant = async (
+ {
+ projectId,
+ accessBundleId,
+ userIds,
+ identityIds
+ }: { projectId: string; accessBundleId?: string; userIds: string[]; identityIds: string[] },
+ tx: Knex
+ ) => {
+ if (!userIds.length && !identityIds.length) return 0;
+ try {
+ const services = tx(TableName.AgentVaultService)
+ .join(
+ TableName.AgentVaultAccessBundle,
+ `${TableName.AgentVaultService}.accessBundleId`,
+ `${TableName.AgentVaultAccessBundle}.id`
+ )
+ .where(`${TableName.AgentVaultAccessBundle}.projectId`, projectId)
+ .whereRaw(`??.?? = ??.??`, [TableName.AgentVaultService, "id", table, "serviceId"])
+ .whereNotExists((grant) => {
+ void grant
+ .from(TableName.Membership)
+ .where(`${TableName.Membership}.scope`, RESOURCE_SCOPE)
+ .where(`${TableName.Membership}.scopeProjectId`, projectId)
+ .where(`${TableName.Membership}.scopeResourceType`, ResourceType.AgentVaultAccessBundle)
+ .whereRaw(`??.?? = ??.??::text`, [
+ TableName.Membership,
+ "scopeResourceId",
+ TableName.AgentVaultAccessBundle,
+ "id"
+ ])
+ .where((holder) => {
+ void holder
+ .whereRaw(`??.?? = ??.??`, [TableName.Membership, "actorUserId", table, "userId"])
+ .orWhereRaw(`??.?? = ??.??`, [TableName.Membership, "actorIdentityId", table, "identityId"])
+ .orWhereIn(
+ `${TableName.Membership}.actorGroupId`,
+ tx(TableName.UserGroupMembership)
+ .whereRaw(`??.?? = ??.??`, [TableName.UserGroupMembership, "userId", table, "userId"])
+ .select("groupId")
+ )
+ .orWhereIn(
+ `${TableName.Membership}.actorGroupId`,
+ tx(TableName.IdentityGroupMembership)
+ .whereRaw(`??.?? = ??.??`, [TableName.IdentityGroupMembership, "identityId", table, "identityId"])
+ .select("groupId")
+ );
+ })
+ .select(tx.raw("1"));
+ })
+ .select(tx.raw("1"));
+ if (accessBundleId) void services.where(`${TableName.AgentVaultAccessBundle}.id`, accessBundleId);
+
+ return await tx(table)
+ .where((actor) => {
+ if (userIds.length) void actor.whereIn(`${table}.userId`, userIds);
+ if (identityIds.length) void actor.orWhereIn(`${table}.identityId`, identityIds);
+ })
+ .whereExists(services)
+ .delete();
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Delete agent vault personal values without a grant" });
+ }
+ };
+
+ /**
+ * The owner's grants on the bundle, direct or through a group they are in, taken FOR SHARE. A revoke deletes these
+ * rows in its own transaction, so this waits for one in flight and then sees the rows gone.
+ */
+ const lockGrantsForOwner = async (
+ { projectId, accessBundleId, owner }: { projectId: string; accessBundleId: string; owner: TAgentVaultOwner },
+ tx: Knex
+ ): Promise<{ id: string }[]> => {
+ try {
+ return (await tx(TableName.Membership)
+ .where(`${TableName.Membership}.scope`, RESOURCE_SCOPE)
+ .where(`${TableName.Membership}.scopeProjectId`, projectId)
+ .where(`${TableName.Membership}.scopeResourceType`, ResourceType.AgentVaultAccessBundle)
+ .where(`${TableName.Membership}.scopeResourceId`, accessBundleId)
+ .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.Membership}.id`)) as { id: string }[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Lock agent vault access bundle grants 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[] },
+ tx: Knex
+ ) => {
+ try {
+ return await tx(table).where(`${table}.serviceId`, serviceId).whereNotIn(`${table}.field`, keepFields).delete();
+ } catch (error) {
+ throw new DatabaseError({
+ error,
+ name: "Delete agent vault personal values for fields no longer member-provided"
+ });
+ }
+ };
+
+ return {
+ ...orm,
+ deleteForServiceExceptFields,
+ findServicesNeedingValues,
+ findForOwner,
+ lockForOwnerAndService,
+ findForResolve,
+ deleteForActorsWithoutGrant,
+ lockGrantsForOwner
+ };
+};
+
+export const agentVaultPersonalValueReferenceDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.AgentVaultPersonalValueReference);
+
+ // The key comes from the variable, so a rename shows through without touching these rows. Reads the primary even
+ // without a tx, so a value saved a moment ago lists the keys it uses.
+ const findByPersonalValueIds = async (
+ personalValueIds: string[],
+ tx?: Knex
+ ): Promise<TAgentVaultPersonalValueReferenceWithKey[]> => {
+ if (!personalValueIds.length) return [];
+ try {
+ return (await (tx || db)(TableName.AgentVaultPersonalValueReference)
+ .join(
+ TableName.AgentVaultVariable,
+ `${TableName.AgentVaultPersonalValueReference}.variableId`,
+ `${TableName.AgentVaultVariable}.id`
+ )
+ .whereIn(`${TableName.AgentVaultPersonalValueReference}.personalValueId`, personalValueIds)
+ .orderBy(`${TableName.AgentVaultVariable}.key`, "asc")
+ .select(
+ `${TableName.AgentVaultPersonalValueReference}.*`,
+ db.ref("key").withSchema(TableName.AgentVaultVariable)
+ )) as TAgentVaultPersonalValueReferenceWithKey[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find agent vault personal value references" });
+ }
+ };
+
+ return { ...orm, findByPersonalValueIds };
+};
diff --git a/backend/src/ee/services/agent-vault-personal-value/agent-vault-personal-value-fns.ts b/backend/src/ee/services/agent-vault-personal-value/agent-vault-personal-value-fns.ts
new file mode 100644
index 0000000000..f93be7223a
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-personal-value/agent-vault-personal-value-fns.ts
@@ -0,0 +1,52 @@
+import { Knex } from "knex";
+
+import { TIdentityGroupMembershipDALFactory } from "@app/ee/services/group/identity-group-membership-dal";
+import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
+
+import { TAgentVaultPersonalValueDALFactory } from "./agent-vault-personal-value-dal";
+
+export type TClearPersonalValuesDeps = {
+ agentVaultPersonalValueDAL: Pick<TAgentVaultPersonalValueDALFactory, "deleteForActorsWithoutGrant">;
+ userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;
+ identityGroupMembershipDAL: Pick<TIdentityGroupMembershipDALFactory, "find">;
+};
+
+/**
+ * Losing a bundle clears the values an actor saved for its services, so a later grant starts from nothing. A
+ * group's revoke reaches its members, and anyone who still holds the bundle another way keeps theirs. Without
+ * `accessBundleId` this covers every bundle in the project, for an actor leaving Agent Vault.
+ */
+export const clearPersonalValuesAfterRevoke = async (
+ { agentVaultPersonalValueDAL, userGroupMembershipDAL, identityGroupMembershipDAL }: TClearPersonalValuesDeps,
+ {
+ projectId,
+ accessBundleId,
+ userIds,
+ identityIds,
+ groupIds
+ }: { projectId: string; accessBundleId?: string; userIds: string[]; identityIds: string[]; groupIds: string[] },
+ tx: Knex
+) => {
+ const [groupUsers, groupIdentities] = groupIds.length
+ ? await Promise.all([
+ userGroupMembershipDAL.find({ $in: { groupId: groupIds } }, { tx }),
+ identityGroupMembershipDAL.find({ $in: { groupId: groupIds } }, { tx })
+ ])
+ : [[], []];
+
+ return agentVaultPersonalValueDAL.deleteForActorsWithoutGrant(
+ {
+ projectId,
+ accessBundleId,
+ userIds: [...new Set([...userIds, ...groupUsers.map((row) => row.userId)])],
+ identityIds: [...new Set([...identityIds, ...groupIdentities.map((row) => row.identityId)])]
+ },
+ tx
+ );
+};
+
+// Member-provided field lists are sets: the same fields in another order are the same setting.
+export const sameMemberProvidedFields = (
+ a: readonly string[] | null | undefined,
+ b: readonly string[] | null | undefined
+) => [...(a ?? [])].sort().join(",") === [...(b ?? [])].sort().join(",");
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
new file mode 100644
index 0000000000..d9d603afd6
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-personal-value/agent-vault-personal-value-service.ts
@@ -0,0 +1,351 @@
+import { ForbiddenError } from "@casl/ability";
+import { Knex } from "knex";
+
+import { TAgentVaultPersonalValueReferencesInsert } from "@app/db/schemas";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import {
+ ProjectPermissionAgentVaultAccessBundleActions,
+ ProjectPermissionSub
+} from "@app/ee/services/permission/project-permission";
+import { DatabaseErrorCode } from "@app/lib/error-codes";
+import { BadRequestError, ConflictError, NotFoundError } from "@app/lib/errors";
+import { hasPostgresConstraintViolation, hasPostgresErrorCode } from "@app/lib/errors/postgres";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { KmsDataKey } from "@app/services/kms/kms-types";
+import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
+
+import { isUniqueViolation } from "../agent-vault/agent-vault-db-error-fns";
+import {
+ AgentVaultCredentialType,
+ AgentVaultVariableReferenceField,
+ TAgentVaultMemberProvidedField
+} from "../agent-vault/agent-vault-enums";
+import { ownerColumns, ownerOf, TAgentVaultOwner } from "../agent-vault/agent-vault-owner-fns";
+import { getAgentVaultGrantedReachability } from "../agent-vault/agent-vault-permission";
+import {
+ findStoredVariableIds,
+ findVariableKeys,
+ toStoredVariableReferences,
+ toVariableReference
+} from "../agent-vault/agent-vault-variable-fns";
+import { TAgentVaultProjectScoped } from "../agent-vault-access-bundle/agent-vault-access-bundle-types";
+import { TAgentVaultServiceDALFactory } from "../agent-vault-access-bundle/agent-vault-service-dal";
+import { TAgentVaultVariableDALFactory } from "../agent-vault-variable/agent-vault-variable-dal";
+import {
+ TAgentVaultPersonalValueDALFactory,
+ TAgentVaultPersonalValueReferenceDALFactory,
+ TAgentVaultPersonalValueReferenceWithKey,
+ TAgentVaultPersonalValueServiceRow,
+ TAgentVaultPersonalValueSummaryRow
+} from "./agent-vault-personal-value-dal";
+import { sameMemberProvidedFields } from "./agent-vault-personal-value-fns";
+import { TPersonalValuesByServiceDTO, TSetPersonalValuesDTO } from "./agent-vault-personal-value-types";
+
+type TAgentVaultPersonalValueServiceFactoryDep = {
+ agentVaultPersonalValueDAL: TAgentVaultPersonalValueDALFactory;
+ agentVaultPersonalValueReferenceDAL: TAgentVaultPersonalValueReferenceDALFactory;
+ agentVaultVariableDAL: Pick<TAgentVaultVariableDALFactory, "findKeys" | "lockForReference">;
+ agentVaultServiceDAL: Pick<TAgentVaultServiceDALFactory, "findByIdInProject" | "lockForPersonalValues">;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
+ membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+};
+
+export type TAgentVaultPersonalValueServiceFactory = ReturnType<typeof agentVaultPersonalValueServiceFactory>;
+
+// What an error calls each field, by the service's credential type. Never its value, which is secret.
+const fieldName = (credentialType: string, field: TAgentVaultMemberProvidedField) => {
+ if (field === AgentVaultVariableReferenceField.CredentialUsername) return "username";
+ return credentialType === AgentVaultCredentialType.Basic ? "password" : "token";
+};
+
+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.";
+
+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.";
+
+const REFERENCE_VARIABLE_FOREIGN_KEY = "agent_vault_personal_value_refs_variable_foreign";
+
+export const agentVaultPersonalValueServiceFactory = ({
+ agentVaultPersonalValueDAL,
+ agentVaultPersonalValueReferenceDAL,
+ agentVaultVariableDAL,
+ agentVaultServiceDAL,
+ permissionService,
+ membershipDAL,
+ kmsService
+}: TAgentVaultPersonalValueServiceFactoryDep) => {
+ const getProjectCipher = (projectId: string) =>
+ kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });
+
+ const resolveCaller = async ({ projectId, ctx }: TAgentVaultProjectScoped) => {
+ const reachability = await getAgentVaultGrantedReachability(
+ { permissionService, membershipDAL },
+ { projectId, ctx }
+ );
+ ForbiddenError.from(reachability.permission).throwUnlessCan(
+ ProjectPermissionAgentVaultAccessBundleActions.Read,
+ ProjectPermissionSub.AgentVaultAccessBundles
+ );
+ return { ...reachability, owner: ownerOf(ctx) };
+ };
+
+ const isReachable = (accessBundleIds: string[] | null, accessBundleId: string) =>
+ !accessBundleIds || accessBundleIds.includes(accessBundleId.toLowerCase());
+
+ const projectService = (
+ service: TAgentVaultPersonalValueServiceRow,
+ values: TAgentVaultPersonalValueSummaryRow[],
+ references: TAgentVaultPersonalValueReferenceWithKey[]
+ ) => {
+ const fields = (service.memberProvidedFields as TAgentVaultMemberProvidedField[]).map((field) => {
+ const saved = values.find((value) => value.serviceId === service.serviceId && value.field === field);
+ return {
+ field,
+ isSet: Boolean(saved),
+ updatedAt: saved?.updatedAt ?? null,
+ variableReferences: saved
+ ? references
+ .filter((reference) => reference.personalValueId === saved.id)
+ .map((reference) => ({ variableId: reference.variableId, key: reference.key }))
+ : []
+ };
+ });
+ return {
+ serviceId: service.serviceId,
+ serviceName: service.serviceName,
+ hostPattern: service.hostPattern,
+ accessBundleId: service.accessBundleId,
+ accessBundleName: service.accessBundleName,
+ credentialType: service.credentialType as AgentVaultCredentialType.Bearer | AgentVaultCredentialType.Basic,
+ isConfigured: fields.every((field) => field.isSet),
+ fields
+ };
+ };
+
+ const loadServices = async (
+ {
+ withVariableReferences = true,
+ ...args
+ }: {
+ projectId: string;
+ owner: TAgentVaultOwner;
+ accessBundleIds: string[] | null;
+ serviceId?: string;
+ withVariableReferences?: boolean;
+ },
+ tx?: Knex
+ ) => {
+ const services = await agentVaultPersonalValueDAL.findServicesNeedingValues(args, tx);
+ const values = await agentVaultPersonalValueDAL.findForOwner(
+ { serviceIds: services.map((service) => service.serviceId), owner: args.owner },
+ tx
+ );
+ const references = withVariableReferences
+ ? await agentVaultPersonalValueReferenceDAL.findByPersonalValueIds(
+ values.map((value) => value.id),
+ tx
+ )
+ : [];
+ return services.map((service) => projectService(service, values, references));
+ };
+
+ /**
+ * The caller's status for every service in these bundles that takes values from members. No permission check: the
+ * access bundle service calls it for bundles it has already resolved the caller's reach to. Without variable
+ * references, each field's list is empty.
+ */
+ const findStatusesForOwner = (args: {
+ projectId: string;
+ owner: TAgentVaultOwner;
+ accessBundleIds: string[];
+ withVariableReferences?: boolean;
+ }) => loadServices(args);
+
+ // A service outside the caller's reach, or in another bundle than the path names, reads exactly like one that does
+ // not exist.
+ const findReachableService = async (dto: TPersonalValuesByServiceDTO) => {
+ const caller = await resolveCaller(dto);
+ const service = await agentVaultServiceDAL.findByIdInProject({ id: dto.serviceId, projectId: dto.projectId });
+ if (
+ !service ||
+ service.accessBundleId !== dto.accessBundleId.toLowerCase() ||
+ !isReachable(caller.accessBundleIds, service.accessBundleId)
+ ) {
+ throw new NotFoundError({ message: `Service with ID '${dto.serviceId}' not found` });
+ }
+ return { ...caller, service };
+ };
+
+ const setPersonalValues = async ({ values, ...dto }: TSetPersonalValuesDTO) => {
+ const { owner, service, isAdmin } = await findReachableService(dto);
+
+ const memberProvidedFields = (service.memberProvidedFields ?? []) as TAgentVaultMemberProvidedField[];
+ if (!memberProvidedFields.length) {
+ throw new BadRequestError({
+ message: `The service '${service.name}' doesn't take any values from its members. Its admin sets the whole credential.`
+ });
+ }
+
+ const name = (field: TAgentVaultMemberProvidedField) => fieldName(service.credentialType, field);
+ const seen = new Set<string>();
+ values.forEach(({ field }) => {
+ if (seen.has(field)) {
+ throw new BadRequestError({ message: `Send '${field}' once. It appears more than once in values.` });
+ }
+ seen.add(field);
+ if (!memberProvidedFields.includes(field)) {
+ throw new BadRequestError({
+ message: `The service '${service.name}' doesn't take a ${name(field)} ('${field}') from you. Send only ${memberProvidedFields.map((el) => `'${el}'`).join(" and ")}.`
+ });
+ }
+ });
+
+ const variables = values.some(({ value }) => findVariableKeys(value).length)
+ ? await agentVaultVariableDAL.findKeys({ projectId: dto.projectId, owner })
+ : [];
+ const idOfKey = new Map(variables.map((variable) => [variable.key, variable.id]));
+ values.forEach(({ field, value }) => {
+ 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.`
+ });
+ }
+ });
+ const variableIds = new Set(variables.map((variable) => variable.id));
+
+ // Encrypt before the transaction: KMS can be a network call.
+ const { encryptor } = await getProjectCipher(dto.projectId);
+ const sealed = values.map(({ field, value }) => {
+ const stored = toStoredVariableReferences(value, idOfKey);
+ return {
+ field,
+ stored,
+ encryptedValue: encryptor({ plainText: Buffer.from(JSON.stringify({ value: stored })) }).cipherTextBlob
+ };
+ });
+
+ const write = () =>
+ agentVaultPersonalValueDAL.transaction(async (tx) => {
+ const current = await agentVaultServiceDAL.lockForPersonalValues(service.id, tx);
+ if (!current) throw new NotFoundError({ message: `Service with ID '${dto.serviceId}' not found` });
+ if (
+ current.credentialType !== service.credentialType ||
+ !sameMemberProvidedFields(current.memberProvidedFields, service.memberProvidedFields)
+ ) {
+ 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 field left out keeps its saved value, so a member adds a newly required field without retyping the rest.
+ // What they send replaces what was saved for those fields, and the reference rows cascade with it.
+ const existing = await agentVaultPersonalValueDAL.lockForOwnerAndService({ serviceId: service.id, owner }, tx);
+ const missing = memberProvidedFields.find(
+ (field) => !seen.has(field) && !existing.some((row) => row.field === field)
+ );
+ if (missing) {
+ throw new BadRequestError({
+ message: `The service '${service.name}' needs your ${name(missing)}. Send '${missing}' with your other values.`
+ });
+ }
+ const replacedRows = existing.filter((row) => seen.has(row.field));
+ if (replacedRows.length) {
+ await agentVaultPersonalValueDAL.delete({ $in: { id: replacedRows.map((row) => row.id) } }, tx);
+ }
+ const saved = await agentVaultPersonalValueDAL.insertMany(
+ sealed.map(({ field, encryptedValue }) => ({
+ serviceId: service.id,
+ field,
+ ...ownerColumns(owner),
+ encryptedValue
+ })),
+ tx
+ );
+
+ // Read off the stored text, the way resolve reads it, never off the request.
+ const referenceRows: TAgentVaultPersonalValueReferencesInsert[] = sealed.flatMap(({ field, stored }) => {
+ const personalValueId = saved.find((row) => row.field === field)!.id;
+ return [...new Set(findStoredVariableIds(stored))]
+ .filter((variableId) => variableIds.has(variableId))
+ .map((variableId) => ({ personalValueId, variableId }));
+ });
+ if (referenceRows.length) {
+ const referenced = [...new Set(referenceRows.map((row) => row.variableId))];
+ const present = await agentVaultVariableDAL.lockForReference(
+ { projectId: dto.projectId, owner, variableIds: referenced },
+ tx
+ );
+ if (present.length !== referenced.length) {
+ throw new BadRequestError({ message: VARIABLE_DELETED_DURING_SAVE_MESSAGE });
+ }
+ await agentVaultPersonalValueReferenceDAL.insertMany(referenceRows, tx);
+ }
+
+ const [projected] = await loadServices(
+ { projectId: dto.projectId, owner, accessBundleIds: [service.accessBundleId], serviceId: service.id },
+ tx
+ );
+ return { personalValues: projected, replaced: existing.length > 0 };
+ });
+
+ try {
+ return await write();
+ } catch (err) {
+ if (isUniqueViolation(err)) {
+ throw new ConflictError({
+ message: "Your values for this service were saved by another request at the same time. Save them again."
+ });
+ }
+ if (hasPostgresConstraintViolation(err, DatabaseErrorCode.ForeignKeyViolation, REFERENCE_VARIABLE_FOREIGN_KEY)) {
+ throw new BadRequestError({ message: VARIABLE_DELETED_DURING_SAVE_MESSAGE });
+ }
+ // The only other key a save can trip is the service's, deleted while the save ran.
+ if (hasPostgresErrorCode(err, DatabaseErrorCode.ForeignKeyViolation)) {
+ throw new NotFoundError({ message: `Service with ID '${dto.serviceId}' not found` });
+ }
+ throw err;
+ }
+ };
+
+ const deletePersonalValues = async (dto: TPersonalValuesByServiceDTO) => {
+ const { owner, service } = await findReachableService(dto);
+
+ return agentVaultPersonalValueDAL.transaction(async (tx) => {
+ const existing = await agentVaultPersonalValueDAL.lockForOwnerAndService({ serviceId: service.id, owner }, tx);
+ if (!existing.length) {
+ throw new NotFoundError({ message: `You haven't set any values for the service '${service.name}'.` });
+ }
+ await agentVaultPersonalValueDAL.delete({ $in: { id: existing.map((row) => row.id) } }, tx);
+
+ const [projected] = await loadServices(
+ { projectId: dto.projectId, owner, accessBundleIds: [service.accessBundleId], serviceId: service.id },
+ tx
+ );
+ return {
+ personalValues: projected ?? {
+ serviceId: service.id,
+ serviceName: service.name,
+ hostPattern: service.hostPattern,
+ accessBundleId: service.accessBundleId,
+ accessBundleName: service.accessBundleName,
+ credentialType: service.credentialType as AgentVaultCredentialType.Bearer | AgentVaultCredentialType.Basic,
+ isConfigured: false,
+ fields: []
+ }
+ };
+ });
+ };
+
+ return { findStatusesForOwner, setPersonalValues, deletePersonalValues };
+};
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
new file mode 100644
index 0000000000..2fc3fd60e7
--- /dev/null
+++ b/backend/src/ee/services/agent-vault-personal-value/agent-vault-personal-value-types.ts
@@ -0,0 +1,8 @@
+import { 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 }[];
+};
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 367fe1ca56..def40c8366 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
@@ -23,11 +23,18 @@ import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
import { TOrgDALFactory } from "@app/services/org/org-dal";
import { isUniqueViolation } from "../agent-vault/agent-vault-db-error-fns";
-import { AgentVaultCredentialType, AgentVaultTrafficPolicy } from "../agent-vault/agent-vault-enums";
+import {
+ AgentVaultCredentialType,
+ AgentVaultTrafficPolicy,
+ AgentVaultVariableReferenceField,
+ TAgentVaultMemberProvidedField
+} from "../agent-vault/agent-vault-enums";
+import { TAgentVaultOwner } from "../agent-vault/agent-vault-owner-fns";
import { findReachableAccessBundleIds, liveGroupIdsFrom } from "../agent-vault/agent-vault-permission";
import { expandStoredVariableReferences, findStoredVariableIds } from "../agent-vault/agent-vault-variable-fns";
import { TAgentVaultServiceCustomHeaderDALFactory } from "../agent-vault-access-bundle/agent-vault-service-custom-header-dal";
import { TAgentVaultServiceSubstitutionDALFactory } from "../agent-vault-access-bundle/agent-vault-service-substitution-dal";
+import { TAgentVaultPersonalValueDALFactory } from "../agent-vault-personal-value/agent-vault-personal-value-dal";
import { TAgentVaultSessionDALFactory } from "../agent-vault-session/agent-vault-session-dal";
import { hashSessionToken } from "../agent-vault-session/agent-vault-session-fns";
import { TAgentVaultSessionLogConfigDALFactory } from "../agent-vault-session-log/agent-vault-session-log-config-dal";
@@ -54,7 +61,7 @@ import {
TResolveSessionDTO,
TUpdateProxyDTO
} from "./agent-vault-proxy-types";
-import { TAgentVaultResolveDALFactory } from "./agent-vault-resolve-dal";
+import { TAgentVaultResolveDALFactory, TResolveServiceRow } from "./agent-vault-resolve-dal";
export const AGENT_VAULT_MAX_PROXIES_PER_ORG = 10;
@@ -67,6 +74,7 @@ type TAgentVaultProxyServiceFactoryDep = {
agentVaultServiceCustomHeaderDAL: Pick<TAgentVaultServiceCustomHeaderDALFactory, "findByServiceIds">;
agentVaultServiceSubstitutionDAL: Pick<TAgentVaultServiceSubstitutionDALFactory, "findByServiceIds">;
agentVaultVariableDAL: Pick<TAgentVaultVariableDALFactory, "findValuesForResolve">;
+ agentVaultPersonalValueDAL: Pick<TAgentVaultPersonalValueDALFactory, "findForResolve">;
agentVaultSessionDAL: Pick<TAgentVaultSessionDALFactory, "findByTokenHash">;
agentVaultSessionLogConfigDAL: Pick<TAgentVaultSessionLogConfigDALFactory, "findOne">;
membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;
@@ -82,12 +90,38 @@ type TAgentVaultProxyServiceFactoryDep = {
export type TAgentVaultProxyServiceFactory = ReturnType<typeof agentVaultProxyServiceFactory>;
+// Opens each variable at most once per resolve. An id with no row stays as text, and the service that used it is
+// recorded so one log line can name every service affected.
+const createVariableLookup = (
+ rows: { id: string; encryptedValue: Buffer }[],
+ decryptValue: (encryptedValue: Buffer) => string
+) => {
+ const encrypted = new Map(rows.map((row) => [row.id, row.encryptedValue]));
+ const opened = new Map<string, string>();
+ const unresolvedServiceIds = new Set<string>();
+ const valueOfFor = (serviceId: string) => (variableId: string) => {
+ const encryptedValue = encrypted.get(variableId);
+ if (!encryptedValue) {
+ unresolvedServiceIds.add(serviceId);
+ return undefined;
+ }
+ let value = opened.get(variableId);
+ if (value === undefined) {
+ value = decryptValue(encryptedValue);
+ opened.set(variableId, value);
+ }
+ return value;
+ };
+ return { valueOfFor, unresolvedServiceIds };
+};
+
export const agentVaultProxyServiceFactory = ({
agentVaultProxyDAL,
agentVaultResolveDAL,
agentVaultServiceCustomHeaderDAL,
agentVaultServiceSubstitutionDAL,
agentVaultVariableDAL,
+ agentVaultPersonalValueDAL,
agentVaultSessionDAL,
agentVaultSessionLogConfigDAL,
membershipDAL,
@@ -366,31 +400,14 @@ export const agentVaultProxyServiceFactory = ({
];
if (!variableIds.length) return services;
- const variables = new Map(
- (await agentVaultVariableDAL.findValuesForResolve({ variableIds, projectId })).map((variable) => [
- variable.id,
- variable
- ])
+ // The lookup is scoped to the session's project, so a stored id never reaches another org's variable.
+ const { valueOfFor, unresolvedServiceIds } = createVariableLookup(
+ await agentVaultVariableDAL.findValuesForResolve({ variableIds, projectId, owner: null }),
+ decryptValue
);
- const opened = new Map<string, string>();
- const unresolvedServiceIds = new Set<string>();
-
const expanded = services.map((service) => {
- const valueOf = (variableId: string) => {
- // The lookup is scoped to the session's project, so a stored id never reaches another org's variable.
- const variable = variables.get(variableId);
- if (!variable) {
- unresolvedServiceIds.add(service.id);
- return undefined;
- }
- let value = opened.get(variableId);
- if (value === undefined) {
- value = decryptValue(variable.encryptedValue);
- opened.set(variableId, value);
- }
- return value;
- };
+ const valueOf = valueOfFor(service.id);
const expand = (text: string) => expandStoredVariableReferences(text, valueOf);
let { credential } = service;
@@ -426,6 +443,103 @@ export const agentVaultProxyServiceFactory = ({
return expanded;
};
+ /**
+ * A member-provided field comes from what the session's actor saved for the service, expanded against their own
+ * personal variables only, after the admin's fields were expanded against the shared ones: a value is never
+ * expanded twice. A service whose actor hasn't set every field the admin leaves to them goes out flagged and
+ * without a credential, so the proxy refuses it instead of sending a half-built one.
+ */
+ const $applyPersonalValues = async ({
+ sessionId,
+ projectId,
+ owner,
+ rows,
+ services,
+ decryptValue,
+ decryptJson
+ }: {
+ sessionId: string;
+ projectId: string;
+ owner: TAgentVaultOwner;
+ rows: TResolveServiceRow[];
+ services: TResolvedService[];
+ decryptValue: (encryptedValue: Buffer) => string;
+ decryptJson: (encrypted: Buffer) => unknown;
+ }): Promise<TResolvedService[]> => {
+ const rowById = new Map(rows.map((row) => [row.id, row]));
+ const memberFieldsOf = (serviceId: string) =>
+ (rowById.get(serviceId)?.memberProvidedFields ?? []) as TAgentVaultMemberProvidedField[];
+
+ const serviceIds = services.filter((service) => memberFieldsOf(service.id).length).map((service) => service.id);
+ if (!serviceIds.length) return services;
+
+ // Stored text per service, then per field, with personal variable references still as ids.
+ const stored = new Map<string, Map<string, string>>();
+ (await agentVaultPersonalValueDAL.findForResolve({ serviceIds, owner })).forEach((row) => {
+ const fields = stored.get(row.serviceId) ?? new Map<string, string>();
+ fields.set(row.field, (decryptJson(row.encryptedValue) as { value: string }).value);
+ stored.set(row.serviceId, fields);
+ });
+
+ const variableIds = [
+ ...new Set([...stored.values()].flatMap((fields) => [...fields.values()].flatMap(findStoredVariableIds)))
+ ];
+ const { valueOfFor, unresolvedServiceIds } = createVariableLookup(
+ await agentVaultVariableDAL.findValuesForResolve({ variableIds, projectId, owner }),
+ decryptValue
+ );
+
+ const resolved = services.map((service): TResolvedService => {
+ const memberFields = memberFieldsOf(service.id);
+ if (!memberFields.length) return service;
+
+ const fields = stored.get(service.id);
+ if (!fields || memberFields.some((field) => !fields.has(field))) {
+ return { ...service, credential: { type: "passthrough" }, personalValuesMissing: true };
+ }
+
+ const valueOf = valueOfFor(service.id);
+ const personalValue = (field: TAgentVaultMemberProvidedField) =>
+ expandStoredVariableReferences(fields.get(field) ?? "", valueOf);
+
+ const row = rowById.get(service.id)!;
+ const config = (row.credentialConfig ?? {}) as Record<string, string>;
+ if (row.credentialType === AgentVaultCredentialType.Bearer) {
+ return {
+ ...service,
+ credential: {
+ type: "bearer",
+ headerName: config.headerName,
+ headerPrefix: config.headerPrefix,
+ value: personalValue(AgentVaultVariableReferenceField.CredentialValue)
+ }
+ };
+ }
+
+ const adminHalves = service.credential.type === "basic" ? service.credential : { username: "", password: "" };
+ return {
+ ...service,
+ credential: {
+ type: "basic",
+ // Trimmed for the same reason as an admin's username a variable fills in.
+ username: memberFields.includes(AgentVaultVariableReferenceField.CredentialUsername)
+ ? personalValue(AgentVaultVariableReferenceField.CredentialUsername).trim()
+ : adminHalves.username,
+ password: memberFields.includes(AgentVaultVariableReferenceField.CredentialValue)
+ ? personalValue(AgentVaultVariableReferenceField.CredentialValue)
+ : adminHalves.password
+ }
+ };
+ });
+
+ if (unresolvedServiceIds.size) {
+ logger.error(
+ `agentVaultResolve: stored personal variable reference with no variable [sessionId=${sessionId}] [serviceIds=${[...unresolvedServiceIds].join(",")}]`
+ );
+ }
+ return resolved;
+ };
+
/** The only endpoint that decrypts a credential. The proxy's JWT authorizes; the session token is a selector. */
const resolveSession = async ({ proxyId, orgId, sessionToken, hasSessionLogKey }: TResolveSessionDTO) => {
const session = await agentVaultSessionDAL.findByTokenHash(hashSessionToken(sessionToken));
@@ -525,7 +639,7 @@ export const agentVaultProxyServiceFactory = ({
// A bundle of pass-through services has nothing sealed, so deriving the project data key would be
// a kms_keys read (or an external KMS round trip) per resolve for nothing.
const hasSealedValue =
- rows.some((row) => row.encryptedCredential) ||
+ rows.some((row) => row.encryptedCredential || row.memberProvidedFields?.length) ||
customHeaderRows.length > 0 ||
substitutionRows.length > 0 ||
sessionLogKeyNeeded;
@@ -538,10 +652,11 @@ export const agentVaultProxyServiceFactory = ({
).decryptor
: null;
- const $decryptValue = (encryptedValue: Buffer) => {
+ const $decryptJson = (encrypted: Buffer): unknown => {
if (!decryptor) throw new InternalServerError({ message: "Failed to resolve the session's credentials" });
- return (JSON.parse(decryptor({ cipherTextBlob: encryptedValue }).toString("utf-8")) as { value: string }).value;
+ return JSON.parse(decryptor({ cipherTextBlob: encrypted }).toString("utf-8"));
};
+ const $decryptValue = (encryptedValue: Buffer) => ($decryptJson(encryptedValue) as { value: string }).value;
const decryptedServices: TResolvedService[] = rows.map((row) => ({
id: row.id,
@@ -560,14 +675,23 @@ export const agentVaultProxyServiceFactory = ({
placeholder: substitution.placeholder,
surfaces: substitution.surfaces,
value: $decryptValue(substitution.encryptedValue)
- }))
+ })),
+ personalValuesMissing: false
}));
- const services = await $expandVariableReferences({
+ const services = await $applyPersonalValues({
sessionId: session.id,
projectId: session.projectId,
- services: decryptedServices,
- decryptValue: $decryptValue
+ owner: session.userId ? { userId: session.userId } : { identityId: session.identityId! },
+ rows,
+ services: await $expandVariableReferences({
+ sessionId: session.id,
+ projectId: session.projectId,
+ services: decryptedServices,
+ decryptValue: $decryptValue
+ }),
+ decryptValue: $decryptValue,
+ decryptJson: $decryptJson
});
// A key that can't be opened turns logs off for this session instead of cutting the agent off from its services.
diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts
index ed74325f31..cacea10698 100644
--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts
+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts
@@ -64,4 +64,7 @@ export type TResolvedService = {
| { type: "passthrough" };
customHeaders: { name: string; prefix: string; value: string }[];
substitutions: { placeholder: string; surfaces: string[]; value: string }[];
+ // The service takes part of its credential from each member and the session's actor has not set their values,
+ // so the proxy refuses its requests rather than sending them without one.
+ personalValuesMissing: boolean;
};
diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.ts
index 9728fc4129..5d25a8faee 100644
--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.ts
+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.ts
@@ -16,6 +16,7 @@ export type TResolveServiceRow = {
encryptedCredential: Buffer | null;
allowedMethods: string[] | null;
allowedPathPrefixes: string[] | null;
+ memberProvidedFields: string[] | null;
position: number;
};
@@ -69,6 +70,7 @@ export const agentVaultResolveDALFactory = (db: TDbClient) => {
db.ref("encryptedCredential").withSchema(TableName.AgentVaultService),
db.ref("allowedMethods").withSchema(TableName.AgentVaultService),
db.ref("allowedPathPrefixes").withSchema(TableName.AgentVaultService),
+ db.ref("memberProvidedFields").withSchema(TableName.AgentVaultService),
// Resolve only reaches live bundles, so the current name is always the truthful one here.
db.ref("name").withSchema(TableName.AgentVaultAccessBundle).as("accessBundleName"),
db.ref("position").withSchema(TableName.AgentVaultSessionAccessBundle)
diff --git a/backend/src/ee/services/agent-vault-variable/agent-vault-variable-dal.test.ts b/backend/src/ee/services/agent-vault-variable/agent-vault-variable-dal.test.ts
index edb5508b7d..42dd5375f9 100644
--- a/backend/src/ee/services/agent-vault-variable/agent-vault-variable-dal.test.ts
+++ b/backend/src/ee/services/agent-vault-variable/agent-vault-variable-dal.test.ts
@@ -2,13 +2,23 @@ import { TableName } from "@app/db/schemas";
import { agentVaultVariableDALFactory } from "./agent-vault-variable-dal";
-type TRow = { id: string; projectId: string; encryptedValue: Buffer };
+type TRow = { id: string; projectId: string; userId: string | null; encryptedValue: Buffer };
const PROJECT_ID = "0b6f6c1e-5a8d-4c2b-9e7f-3d1a2b4c5d6e";
const FIRST_ID = "4f1e2d3c-6b5a-4978-8a6b-5c4d3e2f1a0b";
const SECOND_ID = "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d";
-const row = (id: string): TRow => ({ id, projectId: PROJECT_ID, encryptedValue: Buffer.from(id) });
+const USER_ID = "2c3d4e5f-6a7b-4c8d-9e0f-1a2b3c4d5e6f";
+
+const row = (id: string, userId: string | null = null): TRow => ({
+ id,
+ projectId: PROJECT_ID,
+ userId,
+ encryptedValue: Buffer.from(id)
+});
+
+// Columns arrive qualified with the table name; the fake only cares about the column.
+const columnOf = (column: string) => column.split(".").pop();
// One database node: it answers with the rows it holds among the ids asked for, and records each lookup,
// so a test can tell which node was asked for what.
@@ -16,19 +26,28 @@ const buildNode = (rows: TRow[]) => {
const lookups: { table: string; ids: string[]; projectId?: string }[] = [];
const node = (table: string) => {
const lookup = { table, ids: [] as string[], projectId: undefined as string | undefined };
+ let userId: string | null | undefined;
const chain = {
whereIn: (column: string, values: string[]) => {
- if (column === "id") lookup.ids = values;
+ if (columnOf(column) === "id") lookup.ids = values;
return chain;
},
where: (column: string, value: string) => {
- if (column === "projectId") lookup.projectId = value;
+ if (columnOf(column) === "projectId") lookup.projectId = value;
+ if (columnOf(column) === "userId") userId = value;
+ return chain;
+ },
+ whereNull: (column: string) => {
+ if (columnOf(column) === "userId") userId = null;
return chain;
},
select: async () => {
lookups.push(lookup);
return rows.filter(
- (candidate) => lookup.ids.includes(candidate.id) && candidate.projectId === lookup.projectId
+ (candidate) =>
+ lookup.ids.includes(candidate.id) &&
+ candidate.projectId === lookup.projectId &&
+ (userId === undefined || candidate.userId === userId)
);
}
};
@@ -51,7 +70,11 @@ describe("findValuesForResolve", () => {
replicaRows: [row(FIRST_ID), row(SECOND_ID)]
});
- const values = await dal.findValuesForResolve({ variableIds: [FIRST_ID, SECOND_ID], projectId: PROJECT_ID });
+ const values = await dal.findValuesForResolve({
+ variableIds: [FIRST_ID, SECOND_ID],
+ projectId: PROJECT_ID,
+ owner: null
+ });
expect(values.map((value) => value.id)).toEqual([FIRST_ID, SECOND_ID]);
expect(replica.lookups).toHaveLength(1);
@@ -64,7 +87,11 @@ describe("findValuesForResolve", () => {
replicaRows: [row(FIRST_ID)]
});
- const values = await dal.findValuesForResolve({ variableIds: [FIRST_ID, SECOND_ID], projectId: PROJECT_ID });
+ const values = await dal.findValuesForResolve({
+ variableIds: [FIRST_ID, SECOND_ID],
+ projectId: PROJECT_ID,
+ owner: null
+ });
expect(values.map((value) => value.id)).toEqual([FIRST_ID, SECOND_ID]);
expect(primary.lookups).toEqual([{ table: TableName.AgentVaultVariable, ids: [SECOND_ID], projectId: PROJECT_ID }]);
@@ -73,7 +100,11 @@ describe("findValuesForResolve", () => {
test("an id neither node has is left out, for resolve to report", async () => {
const { dal, primary } = buildDAL({ primaryRows: [row(FIRST_ID)], replicaRows: [row(FIRST_ID)] });
- const values = await dal.findValuesForResolve({ variableIds: [FIRST_ID, SECOND_ID], projectId: PROJECT_ID });
+ const values = await dal.findValuesForResolve({
+ variableIds: [FIRST_ID, SECOND_ID],
+ projectId: PROJECT_ID,
+ owner: null
+ });
expect(values.map((value) => value.id)).toEqual([FIRST_ID]);
expect(primary.lookups).toHaveLength(1);
@@ -83,8 +114,31 @@ describe("findValuesForResolve", () => {
const foreign = { ...row(SECOND_ID), projectId: "another-project" };
const { dal } = buildDAL({ primaryRows: [row(FIRST_ID), foreign], replicaRows: [row(FIRST_ID), foreign] });
- const values = await dal.findValuesForResolve({ variableIds: [FIRST_ID, SECOND_ID], projectId: PROJECT_ID });
+ const values = await dal.findValuesForResolve({
+ variableIds: [FIRST_ID, SECOND_ID],
+ projectId: PROJECT_ID,
+ owner: null
+ });
expect(values.map((value) => value.id)).toEqual([FIRST_ID]);
});
+
+ test("a shared lookup never returns a personal variable, and a personal one returns only its owner's", async () => {
+ const personal = row(SECOND_ID, USER_ID);
+ const { dal } = buildDAL({ primaryRows: [row(FIRST_ID), personal], replicaRows: [row(FIRST_ID), personal] });
+
+ const shared = await dal.findValuesForResolve({
+ variableIds: [FIRST_ID, SECOND_ID],
+ projectId: PROJECT_ID,
+ owner: null
+ });
+ const own = await dal.findValuesForResolve({
+ variableIds: [FIRST_ID, SECOND_ID],
+ projectId: PROJECT_ID,
+ owner: { userId: USER_ID }
+ });
+
+ expect(shared.map((value) => value.id)).toEqual([FIRST_ID]);
+ expect(own.map((value) => value.id)).toEqual([SECOND_ID]);
+ });
});
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 a6dfe953e8..5613b4906f 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
@@ -6,6 +6,8 @@ import { DatabaseError } from "@app/lib/errors";
import { sanitizeSqlLikeString } from "@app/lib/fn/string";
import { ormify } from "@app/lib/knex";
+import { TAgentVaultOwner, whereOwner } from "../agent-vault/agent-vault-owner-fns";
+
export type TAgentVaultVariableDALFactory = ReturnType<typeof agentVaultVariableDALFactory>;
// accessBundleId is left over from bundle-scoped variables and no longer read, so it stays off every row.
@@ -13,8 +15,11 @@ export type TAgentVaultVariable = Omit<TAgentVaultVariables, "accessBundleId">;
export type TAgentVaultVariableOrderBy = "key" | "serviceCount";
-export type TFindAgentVaultVariablesDTO = {
- projectId: string;
+// `owner: null` is the shared variables; an owner is that user's or identity's personal ones. Every read and lock
+// names one, so a shared lookup never matches a personal key and the other way round.
+export type TAgentVaultVariableOwnerScope = { projectId: string; owner: TAgentVaultOwner | null };
+
+export type TFindAgentVaultVariablesDTO = TAgentVaultVariableOwnerScope & {
search?: string;
keys?: string[];
orderBy: TAgentVaultVariableOrderBy;
@@ -34,24 +39,62 @@ export type TAgentVaultServiceUsingVariable = {
accessBundleName: string;
};
-const VARIABLE_COLUMNS = ["id", "projectId", "key", "encryptedValue", "createdAt", "updatedAt"] as const;
+const VARIABLE_COLUMNS = [
+ "id",
+ "projectId",
+ "userId",
+ "identityId",
+ "key",
+ "encryptedValue",
+ "createdAt",
+ "updatedAt"
+] as const;
+
+// Each (variable, service) pair a reference row records: a service's own fields, or a member's value for one.
+const referencingServices = (conn: Knex, variableIds?: string[]) => {
+ const serviceRefs = conn(TableName.AgentVaultServiceVariableReference).select(
+ `${TableName.AgentVaultServiceVariableReference}.variableId`,
+ `${TableName.AgentVaultServiceVariableReference}.serviceId`
+ );
+ const personalValueRefs = conn(TableName.AgentVaultPersonalValueReference)
+ .join(
+ TableName.AgentVaultPersonalValue,
+ `${TableName.AgentVaultPersonalValueReference}.personalValueId`,
+ `${TableName.AgentVaultPersonalValue}.id`
+ )
+ .select(
+ `${TableName.AgentVaultPersonalValueReference}.variableId`,
+ `${TableName.AgentVaultPersonalValue}.serviceId`
+ );
+ if (variableIds) {
+ void serviceRefs.whereIn(`${TableName.AgentVaultServiceVariableReference}.variableId`, variableIds);
+ void personalValueRefs.whereIn(`${TableName.AgentVaultPersonalValueReference}.variableId`, variableIds);
+ }
+ return serviceRefs.unionAll(personalValueRefs as unknown as typeof serviceRefs);
+};
export const agentVaultVariableDALFactory = (db: TDbClient) => {
const orm = ormify(db, TableName.AgentVaultVariable);
const columns = VARIABLE_COLUMNS.map((column) => `${TableName.AgentVaultVariable}.${column}`);
+ const scoped = (conn: Knex, { projectId, owner }: TAgentVaultVariableOwnerScope) =>
+ whereOwner(
+ conn(TableName.AgentVaultVariable).where(`${TableName.AgentVaultVariable}.projectId`, projectId),
+ TableName.AgentVaultVariable,
+ owner
+ );
+
// Reads the primary even without a tx, so a variable created a moment ago is always listed. serviceCount counts
// the services that use a variable, each once however many of its fields do.
const findForList = async (
- { projectId, search, keys, orderBy, orderDirection, limit, offset }: TFindAgentVaultVariablesDTO,
+ { projectId, owner, search, keys, orderBy, orderDirection, limit, offset }: TFindAgentVaultVariablesDTO,
tx?: Knex
): Promise<{ variables: TAgentVaultVariable[]; totalCount: number }> => {
try {
const conn = tx || db;
const applyFilters = (query: Knex.QueryBuilder) => {
- void query.where(`${TableName.AgentVaultVariable}.projectId`, projectId);
if (search) {
void query.whereILike(`${TableName.AgentVaultVariable}.key`, `%${sanitizeSqlLikeString(search)}%`);
}
@@ -59,25 +102,21 @@ export const agentVaultVariableDALFactory = (db: TDbClient) => {
return query;
};
- const countResult = (await applyFilters(conn(TableName.AgentVaultVariable))
+ const countResult = (await applyFilters(scoped(conn, { projectId, owner }))
.count(`${TableName.AgentVaultVariable}.id as count`)
.first()) as { count: string } | undefined;
const totalCount = parseInt(countResult?.count || "0", 10);
- const pageQuery = applyFilters(conn(TableName.AgentVaultVariable)).limit(limit).offset(offset).select(columns);
+ const pageQuery = applyFilters(scoped(conn, { projectId, owner })).limit(limit).offset(offset).select(columns);
if (orderBy === "serviceCount") {
- // Counted over this project's variables only; the references table holds every org's.
- const usageCounts = conn(TableName.AgentVaultServiceVariableReference)
- .join(
- TableName.AgentVaultVariable,
- `${TableName.AgentVaultServiceVariableReference}.variableId`,
- `${TableName.AgentVaultVariable}.id`
- )
- .where(`${TableName.AgentVaultVariable}.projectId`, projectId)
- .select(`${TableName.AgentVaultServiceVariableReference}.variableId`)
- .countDistinct(`${TableName.AgentVaultServiceVariableReference}.serviceId as count`)
- .groupBy(`${TableName.AgentVaultServiceVariableReference}.variableId`)
+ // Counted over this list's variables only; the references tables hold every org's.
+ const usageCounts = conn
+ .from(referencingServices(conn).as("refs"))
+ .whereIn("refs.variableId", scoped(conn, { projectId, owner }).select(`${TableName.AgentVaultVariable}.id`))
+ .select("refs.variableId")
+ .countDistinct("refs.serviceId as count")
+ .groupBy("refs.variableId")
.as("uc");
void pageQuery.leftJoin(usageCounts, function joinUsageCount() {
@@ -96,17 +135,21 @@ export const agentVaultVariableDALFactory = (db: TDbClient) => {
};
// Reads the primary even without a tx, so a key created a moment ago is always found.
- const findKeysByProjectId = async (
- projectId: string,
+ const findKeys = async (
+ scope: TAgentVaultVariableOwnerScope,
tx?: Knex
): Promise<Pick<TAgentVaultVariables, "id" | "key">[]> => {
try {
- return await (tx || db)(TableName.AgentVaultVariable).where({ projectId }).select("id", "key");
+ return (await scoped(tx || db, scope).select(
+ `${TableName.AgentVaultVariable}.id`,
+ `${TableName.AgentVaultVariable}.key`
+ )) as Pick<TAgentVaultVariables, "id" | "key">[];
} catch (error) {
throw new DatabaseError({ error, name: "Find agent vault variable keys" });
}
};
+ // Any owner's. The service decides whether the caller may act on what it finds.
const findByIdInProject = async (
{ id, projectId }: { id: string; projectId: string },
tx?: Knex
@@ -120,21 +163,21 @@ export const agentVaultVariableDALFactory = (db: TDbClient) => {
}
};
- const findByKeyInProject = async (
- { key, projectId }: { key: string; projectId: string },
+ const findByKey = async (
+ { key, ...scope }: TAgentVaultVariableOwnerScope & { key: string },
tx?: Knex
): Promise<TAgentVaultVariable | undefined> => {
try {
- return (await (tx || db)(TableName.AgentVaultVariable).where({ key, projectId }).first(columns)) as
- | TAgentVaultVariable
- | undefined;
+ return (await scoped(tx || db, scope)
+ .where(`${TableName.AgentVaultVariable}.key`, key)
+ .first(columns)) as TAgentVaultVariable | undefined;
} catch (error) {
throw new DatabaseError({ error, name: "Find agent vault variable by key" });
}
};
- // Taken by a variable delete, update or rename. A service save takes the same rows FOR SHARE, so a delete waits for
- // a save that is adding a reference, then sees it.
+ // Taken by a variable delete, update or rename. A save that references variables takes the same rows FOR SHARE, so
+ // a delete waits for a save that is adding a reference, then sees it.
const lockByIdInProject = async (
{ id, projectId }: { id: string; projectId: string },
tx: Knex
@@ -150,41 +193,39 @@ export const agentVaultVariableDALFactory = (db: TDbClient) => {
// Returns the ids that still exist. One missing was deleted after the save looked its key up.
const lockForReference = async (
- { variableIds, projectId }: { variableIds: string[]; projectId: string },
+ { variableIds, ...scope }: TAgentVaultVariableOwnerScope & { variableIds: string[] },
tx: Knex
): Promise<string[]> => {
if (!variableIds.length) return [];
try {
- const rows = await tx(TableName.AgentVaultVariable)
- .where({ projectId })
- .whereIn("id", variableIds)
- .orderBy("id")
+ const rows = (await scoped(tx, scope)
+ .whereIn(`${TableName.AgentVaultVariable}.id`, variableIds)
+ .orderBy(`${TableName.AgentVaultVariable}.id`)
.forShare()
- .select("id");
+ .select(`${TableName.AgentVaultVariable}.id`)) as { id: string }[];
return rows.map((row) => row.id);
} catch (error) {
throw new DatabaseError({ error, name: "Lock agent vault variables for reference" });
}
};
- // Reads the primary even without a tx, so a service saved a moment ago shows as using its variables.
+ // Reads the primary even without a tx, so a service or personal value saved a moment ago shows as using its
+ // variables. A shared variable is referenced by services, a personal one by its owner's personal values, so each
+ // variable only ever appears in one of the two.
const findServicesUsing = async (variableIds: string[], tx?: Knex): Promise<TAgentVaultServiceUsingVariable[]> => {
if (!variableIds.length) return [];
+ const conn = tx || db;
try {
- return (await (tx || db)(TableName.AgentVaultServiceVariableReference)
- .join(
- TableName.AgentVaultService,
- `${TableName.AgentVaultServiceVariableReference}.serviceId`,
- `${TableName.AgentVaultService}.id`
- )
+ return (await conn
+ .from(referencingServices(conn, variableIds).as("refs"))
+ .join(TableName.AgentVaultService, "refs.serviceId", `${TableName.AgentVaultService}.id`)
.join(
TableName.AgentVaultAccessBundle,
`${TableName.AgentVaultService}.accessBundleId`,
`${TableName.AgentVaultAccessBundle}.id`
)
- .whereIn(`${TableName.AgentVaultServiceVariableReference}.variableId`, variableIds)
.distinct(
- db.ref("variableId").withSchema(TableName.AgentVaultServiceVariableReference),
+ db.ref("variableId").withSchema("refs"),
db.ref("id").withSchema(TableName.AgentVaultService).as("serviceId"),
db.ref("name").withSchema(TableName.AgentVaultService).as("serviceName"),
db.ref("hostPattern").withSchema(TableName.AgentVaultService),
@@ -200,22 +241,21 @@ export const agentVaultVariableDALFactory = (db: TDbClient) => {
}
};
- // Resolve is the hot path, so it reads a replica. A variable is always saved before any service that uses it,
- // but each query picks its own replica, and the one serving this read can trail the one that served the
- // service. So an id the replica does not have is asked of the primary before resolve gives up on it.
+ // Resolve is the hot path, so it reads a replica. A variable is always saved before anything that uses it, but each
+ // query picks its own replica, and the one serving this read can trail the one that served the service. So an id
+ // the replica does not have is asked of the primary before resolve gives up on it.
const findValuesForResolve = async ({
variableIds,
- projectId
- }: {
- variableIds: string[];
- projectId: string;
- }): Promise<TAgentVaultVariableValueRow[]> => {
+ ...scope
+ }: TAgentVaultVariableOwnerScope & { variableIds: string[] }): Promise<TAgentVaultVariableValueRow[]> => {
if (!variableIds.length) return [];
- const read = async (conn: Knex, ids: string[]): Promise<TAgentVaultVariableValueRow[]> =>
- conn(TableName.AgentVaultVariable)
- .whereIn("id", ids)
- .where("projectId", projectId)
- .select("id", "encryptedValue");
+ const read = async (conn: Knex, ids: string[]) =>
+ (await scoped(conn, scope)
+ .whereIn(`${TableName.AgentVaultVariable}.id`, ids)
+ .select(
+ `${TableName.AgentVaultVariable}.id`,
+ `${TableName.AgentVaultVariable}.encryptedValue`
+ )) as TAgentVaultVariableValueRow[];
try {
const rows = await read(db.replicaNode(), variableIds);
const found = new Set(rows.map((row) => row.id));
@@ -229,9 +269,9 @@ export const agentVaultVariableDALFactory = (db: TDbClient) => {
return {
...orm,
findForList,
- findKeysByProjectId,
+ findKeys,
findByIdInProject,
- findByKeyInProject,
+ findByKey,
lockByIdInProject,
lockForReference,
findServicesUsing,
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 cf8c7b695f..34121612dd 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
@@ -13,12 +13,15 @@ import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
import { isUniqueViolation } from "../agent-vault/agent-vault-db-error-fns";
+import { AgentVaultVariableScope } from "../agent-vault/agent-vault-enums";
+import { ownerOf, TAgentVaultOwner } from "../agent-vault/agent-vault-owner-fns";
import { getAgentVaultPermission } from "../agent-vault/agent-vault-permission";
-import { AGENT_VAULT_MAX_VARIABLES } from "../agent-vault/agent-vault-variable-fns";
+import { AGENT_VAULT_MAX_PERSONAL_VARIABLES, AGENT_VAULT_MAX_VARIABLES } from "../agent-vault/agent-vault-variable-fns";
import {
TAgentVaultServiceUsingVariable,
TAgentVaultVariable,
- TAgentVaultVariableDALFactory
+ TAgentVaultVariableDALFactory,
+ TAgentVaultVariableOwnerScope
} from "./agent-vault-variable-dal";
import {
TAgentVaultVariableScoped,
@@ -39,6 +42,11 @@ const AGENT_VAULT_VARIABLE_LIST_DEFAULT_LIMIT = 20;
export type TAgentVaultVariableServiceFactory = ReturnType<typeof agentVaultVariableServiceFactory>;
+const isPersonal = (variable: TAgentVaultVariable) => Boolean(variable.userId || variable.identityId);
+
+const isOwnedBy = (variable: TAgentVaultVariable, owner: TAgentVaultOwner) =>
+ owner.userId ? variable.userId === owner.userId : variable.identityId === owner.identityId;
+
export const agentVaultVariableServiceFactory = ({
agentVaultVariableDAL,
permissionService,
@@ -47,20 +55,64 @@ export const agentVaultVariableServiceFactory = ({
const getProjectCipher = (projectId: string) =>
kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });
- // Variables are admin only, reads included: a member can use a service without seeing what it is built from, and
- // Edit on access bundles is the action only an admin holds.
- const assertCanManageVariables = async ({ projectId, ctx }: TAgentVaultVariableScoped) => {
+ /**
+ * Shared variables are admin only, reads included: a member can use a service without seeing what it is built
+ * from, and Edit on access bundles is the action only an admin holds. Personal variables are the caller's own,
+ * and any Agent Vault member keeps them. Nobody, an admin included, can name or read another actor's.
+ */
+ const resolveScope = async (
+ { projectId, ctx }: TAgentVaultVariableScoped,
+ scope: AgentVaultVariableScope
+ ): Promise<TAgentVaultVariableOwnerScope> => {
const { permission } = await getAgentVaultPermission({ permissionService }, { projectId, ctx });
+ if (scope === AgentVaultVariableScope.Shared) {
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionAgentVaultAccessBundleActions.Edit,
+ ProjectPermissionSub.AgentVaultAccessBundles
+ );
+ return { projectId, owner: null };
+ }
ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionAgentVaultAccessBundleActions.Edit,
+ ProjectPermissionAgentVaultAccessBundleActions.Read,
ProjectPermissionSub.AgentVaultAccessBundles
);
+ return { projectId, owner: ownerOf(ctx) };
+ };
+
+ const notFound = (variableId: string) => new NotFoundError({ message: `Variable with ID '${variableId}' not found` });
+
+ // A variable the caller may not act on reads exactly like one that does not exist, so an id never confirms that
+ // someone else's personal variable is there.
+ const findAccessibleVariable = async ({ variableId, projectId, ctx }: TVariableByIdDTO) => {
+ const variable = await agentVaultVariableDAL.findByIdInProject({ id: variableId, projectId });
+ const { permission } = await getAgentVaultPermission({ permissionService }, { projectId, ctx });
+
+ if (!variable) throw notFound(variableId);
+ if (isPersonal(variable)) {
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionAgentVaultAccessBundleActions.Read,
+ ProjectPermissionSub.AgentVaultAccessBundles
+ );
+ const owner = ownerOf(ctx);
+ if (!isOwnedBy(variable, owner)) throw notFound(variableId);
+ return { variable, scope: { projectId, owner } };
+ }
+ if (
+ permission.cannot(
+ ProjectPermissionAgentVaultAccessBundleActions.Edit,
+ ProjectPermissionSub.AgentVaultAccessBundles
+ )
+ ) {
+ throw notFound(variableId);
+ }
+ return { variable, scope: { projectId, owner: null } };
};
// Values never leave through this projection; only the audited value endpoint returns one.
const projectVariable = (variable: TAgentVaultVariable, services: TAgentVaultServiceUsingVariable[]) => ({
id: variable.id,
key: variable.key,
+ scope: isPersonal(variable) ? AgentVaultVariableScope.Personal : AgentVaultVariableScope.Shared,
usedByServices: services
.filter((service) => service.variableId === variable.id)
.map(
@@ -76,26 +128,37 @@ export const agentVaultVariableServiceFactory = ({
updatedAt: variable.updatedAt
});
- const notFound = (variableId: string) => new NotFoundError({ message: `Variable with ID '${variableId}' not found` });
-
- const duplicateKeyMessage = (key: string) => `A variable named '${key}' already exists.`;
+ const duplicateKeyMessage = (key: string, { owner }: TAgentVaultVariableOwnerScope) =>
+ owner ? `You already have a variable named '${key}'.` : `A variable named '${key}' already exists.`;
- const inUseMessage = (key: string, services: TAgentVaultServiceUsingVariable[]) => {
+ const inUseMessage = (
+ key: string,
+ services: TAgentVaultServiceUsingVariable[],
+ { owner }: TAgentVaultVariableOwnerScope
+ ) => {
const names = services
.map((service) => `'${service.serviceName}' (access bundle '${service.accessBundleName}')`)
.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.`;
+ }
return services.length === 1
? `The variable '${key}' is used by the service ${names}. Remove it from that service before deleting it.`
: `The variable '${key}' is used by the services ${names}. Remove it from those services before deleting it.`;
};
- const listVariables = async ({ projectId, ctx, limit, ...query }: TListVariablesDTO) => {
- await assertCanManageVariables({ projectId, ctx });
+ const sealValue = async (projectId: string, value: string) =>
+ (await getProjectCipher(projectId)).encryptor({ plainText: Buffer.from(JSON.stringify({ value })) }).cipherTextBlob;
+
+ const listVariables = async ({ projectId, ctx, scope: scopeName, limit, ...query }: TListVariablesDTO) => {
+ const scope = await resolveScope({ projectId, ctx }, scopeName);
// A lookup by keys returns every key that exists unless the caller caps it, so a missing entry always means
// the key doesn't exist.
const { variables, totalCount } = await agentVaultVariableDAL.findForList({
- projectId,
+ ...scope,
...query,
limit: limit ?? query.keys?.length ?? AGENT_VAULT_VARIABLE_LIST_DEFAULT_LIMIT
});
@@ -104,50 +167,59 @@ export const agentVaultVariableServiceFactory = ({
return { variables: variables.map((variable) => projectVariable(variable, services)), totalCount };
};
- const createVariable = async ({ key, value, ...rest }: TCreateVariableDTO) => {
- await assertCanManageVariables(rest);
-
- const { encryptor } = await getProjectCipher(rest.projectId);
- const encryptedValue = encryptor({ plainText: Buffer.from(JSON.stringify({ value })) }).cipherTextBlob;
+ const createVariable = async ({ key, value, scope: scopeName, ...rest }: TCreateVariableDTO) => {
+ const scope = await resolveScope(rest, scopeName);
+ const { owner } = scope;
+ const encryptedValue = await sealValue(rest.projectId, value);
+ const cap = owner ? AGENT_VAULT_MAX_PERSONAL_VARIABLES : AGENT_VAULT_MAX_VARIABLES;
- // Serialised per project so the count and the key check are authoritative. The unique index is the backstop.
+ // Serialised per project, or per owner for personal variables, so the count and the key check are
+ // authoritative. The unique indexes are the backstop.
const write = () =>
agentVaultVariableDAL.transaction(async (tx) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
- await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.CreateAgentVaultVariable(rest.projectId)]);
+ await tx.raw("SELECT pg_advisory_xact_lock(?)", [
+ owner
+ ? PgSqlLock.CreateAgentVaultPersonalVariable(rest.projectId, owner.userId ?? owner.identityId!)
+ : PgSqlLock.CreateAgentVaultVariable(rest.projectId)
+ ]);
- const existing = await agentVaultVariableDAL.findKeysByProjectId(rest.projectId, tx);
+ const existing = await agentVaultVariableDAL.findKeys(scope, tx);
if (existing.some((variable) => variable.key === key)) {
- throw new BadRequestError({ message: duplicateKeyMessage(key) });
+ throw new BadRequestError({ message: duplicateKeyMessage(key, scope) });
}
- if (existing.length >= AGENT_VAULT_MAX_VARIABLES) {
+ if (existing.length >= cap) {
throw new BadRequestError({
- message: `Agent Vault can hold at most ${AGENT_VAULT_MAX_VARIABLES} variables. Delete one that no service uses first.`
+ 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} shared variables. Delete one that no service uses first.`
});
}
- return agentVaultVariableDAL.create({ projectId: rest.projectId, key, encryptedValue }, tx);
+ return agentVaultVariableDAL.create(
+ {
+ projectId: rest.projectId,
+ userId: owner?.userId ?? null,
+ identityId: owner?.identityId ?? null,
+ key,
+ encryptedValue
+ },
+ tx
+ );
});
try {
return { variable: projectVariable(await write(), []) };
} catch (err) {
- if (isUniqueViolation(err)) throw new BadRequestError({ message: duplicateKeyMessage(key) });
+ if (isUniqueViolation(err)) throw new BadRequestError({ message: duplicateKeyMessage(key, scope) });
throw err;
}
};
const updateVariable = async ({ variableId, key, value, ...rest }: TUpdateVariableDTO) => {
- await assertCanManageVariables(rest);
-
- const variable = await agentVaultVariableDAL.findByIdInProject({ id: variableId, projectId: rest.projectId });
- if (!variable) throw notFound(variableId);
+ const { variable, scope } = await findAccessibleVariable({ variableId, ...rest });
- const encryptedValue =
- value === undefined
- ? undefined
- : (await getProjectCipher(rest.projectId)).encryptor({ plainText: Buffer.from(JSON.stringify({ value })) })
- .cipherTextBlob;
+ const encryptedValue = value === undefined ? undefined : await sealValue(rest.projectId, value);
const write = () =>
agentVaultVariableDAL.transaction(async (tx) => {
@@ -158,11 +230,11 @@ export const agentVaultVariableServiceFactory = ({
if (!current) throw notFound(variableId);
if (key !== undefined && key !== current.key) {
- const clash = await agentVaultVariableDAL.findByKeyInProject({ key, projectId: rest.projectId }, tx);
- if (clash) throw new BadRequestError({ message: duplicateKeyMessage(key) });
+ const clash = await agentVaultVariableDAL.findByKey({ key, ...scope }, tx);
+ if (clash) throw new BadRequestError({ message: duplicateKeyMessage(key, scope) });
}
- // A rename is this row alone. Sealed fields name the variable by id, so nothing that uses it changes.
+ // A rename is this row alone. Sealed text names the variable by id, so nothing that uses it changes.
await agentVaultVariableDAL.updateById(current.id, { key, ...(encryptedValue ? { encryptedValue } : {}) }, tx);
const updated = await agentVaultVariableDAL.findByIdInProject(
{ id: current.id, projectId: rest.projectId },
@@ -176,7 +248,9 @@ export const agentVaultVariableServiceFactory = ({
try {
result = await write();
} catch (err) {
- if (isUniqueViolation(err)) throw new BadRequestError({ message: duplicateKeyMessage(key ?? variable.key) });
+ if (isUniqueViolation(err)) {
+ throw new BadRequestError({ message: duplicateKeyMessage(key ?? variable.key, scope) });
+ }
throw err;
}
@@ -184,10 +258,10 @@ export const agentVaultVariableServiceFactory = ({
};
const deleteVariable = async ({ variableId, ...rest }: TVariableByIdDTO) => {
- await assertCanManageVariables(rest);
+ const { scope } = await findAccessibleVariable({ variableId, ...rest });
- // The refusal here is the real check. The row lock waits for any service save adding a reference to this
- // variable, since those take it FOR SHARE. The deferred foreign key only backs it up, and only raises at commit.
+ // The refusal here is the real check. The row lock waits for any save adding a reference to this variable, since
+ // those take it FOR SHARE. The deferred foreign keys only back it up, and only raise at commit.
const remove = () =>
agentVaultVariableDAL.transaction(async (tx) => {
const variable = await agentVaultVariableDAL.lockByIdInProject(
@@ -197,7 +271,7 @@ export const agentVaultVariableServiceFactory = ({
if (!variable) throw notFound(variableId);
const services = await agentVaultVariableDAL.findServicesUsing([variable.id], tx);
- if (services.length) throw new ConflictError({ message: inUseMessage(variable.key, services) });
+ if (services.length) throw new ConflictError({ message: inUseMessage(variable.key, services, scope) });
await agentVaultVariableDAL.deleteById(variable.id, tx);
return variable;
@@ -208,8 +282,9 @@ export const agentVaultVariableServiceFactory = ({
} catch (err) {
if (hasPostgresErrorCode(err, DatabaseErrorCode.ForeignKeyViolation)) {
throw new ConflictError({
- message:
- "This variable is still used by a service. Remove it from every service that uses it, then delete it."
+ message: scope.owner
+ ? "One of your values still uses this variable. Change every value 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."
});
}
throw err;
@@ -217,16 +292,13 @@ export const agentVaultVariableServiceFactory = ({
};
const getVariableValue = async ({ variableId, ...rest }: TVariableByIdDTO) => {
- await assertCanManageVariables(rest);
-
- const variable = await agentVaultVariableDAL.findByIdInProject({ id: variableId, projectId: rest.projectId });
- if (!variable) throw notFound(variableId);
+ const { variable } = await findAccessibleVariable({ variableId, ...rest });
const { decryptor } = await getProjectCipher(rest.projectId);
const { value } = JSON.parse(decryptor({ cipherTextBlob: variable.encryptedValue }).toString("utf-8")) as {
value: string;
};
- return { variableId: variable.id, key: variable.key, value };
+ return { variable: projectVariable(variable, []), value };
};
return { listVariables, createVariable, updateVariable, deleteVariable, getVariableValue };
diff --git a/backend/src/ee/services/agent-vault-variable/agent-vault-variable-types.ts b/backend/src/ee/services/agent-vault-variable/agent-vault-variable-types.ts
index 2b6b809e60..3fe09bf0aa 100644
--- a/backend/src/ee/services/agent-vault-variable/agent-vault-variable-types.ts
+++ b/backend/src/ee/services/agent-vault-variable/agent-vault-variable-types.ts
@@ -1,13 +1,21 @@
import { TGenericPermission } from "@app/lib/types";
+import { AgentVaultVariableScope } from "../agent-vault/agent-vault-enums";
import { TFindAgentVaultVariablesDTO } from "./agent-vault-variable-dal";
export type TAgentVaultVariableScoped = { projectId: string; ctx: TGenericPermission };
export type TListVariablesDTO = TAgentVaultVariableScoped &
- Omit<TFindAgentVaultVariablesDTO, "projectId" | "limit"> & { limit?: number };
+ Omit<TFindAgentVaultVariablesDTO, "projectId" | "owner" | "limit"> & {
+ limit?: number;
+ scope: AgentVaultVariableScope;
+ };
-export type TCreateVariableDTO = TAgentVaultVariableScoped & { key: string; value: string };
+export type TCreateVariableDTO = TAgentVaultVariableScoped & {
+ scope: AgentVaultVariableScope;
+ key: string;
+ value: string;
+};
export type TUpdateVariableDTO = TAgentVaultVariableScoped & { variableId: string; key?: string; value?: string };
diff --git a/backend/src/ee/services/agent-vault/CLAUDE.md b/backend/src/ee/services/agent-vault/CLAUDE.md
index 1dcce497af..c646d59827 100644
--- a/backend/src/ee/services/agent-vault/CLAUDE.md
+++ b/backend/src/ee/services/agent-vault/CLAUDE.md
@@ -8,18 +8,19 @@ would get something wrong from the code alone; cut anything the code already sta
attaches the real credential on the way out. What an agent may reach lives in a **session** row on our side,
never in anything the agent holds.
-| Noun | What it is |
-| --- | --- |
-| **Access bundle** | A named set of services. The unit you grant |
-| **Service** | One host pattern set plus its credential |
-| **Session** | A minted token naming one actor, one of their bundles, and an expiry. The token *is* the session |
-| **Proxy** | One deployed egress node with its own CA. One row per box |
+| Noun | What it is |
+| ----------------- | ------------------------------------------------------------------------------------------------ |
+| **Access bundle** | A named set of services. The unit you grant |
+| **Service** | One host pattern set plus its credential |
+| **Session** | A minted token naming one actor, one of their bundles, and an expiry. The token _is_ the session |
+| **Proxy** | One deployed egress node with its own CA. One row per box |
```
agent-vault/ shared: enums, host grammar, conflict detection, reachability
agent-vault-access-bundle/ bundles, services, credential encryption, grants
-agent-vault-variable/ product-wide variables and the reads behind Used By
+agent-vault-variable/ shared and personal variables and the reads behind Used By
agent-vault-member/ product membership (list, add, role, remove)
+agent-vault-personal-value/ each actor's own values for the fields a service leaves to members
agent-vault-session/ mint, revoke, list, get
agent-vault-project/ the per-org project's lazy bootstrap and resolver
agent-vault-proxy/ login (enrollment), heartbeat, resolve
@@ -128,8 +129,8 @@ and `packages/agentvault/` in the CLI repo. Frontend: `frontend/src/pages/agent-
`agent-vault-host-pattern-fns.ts` is the grammar of record. The CLI matcher (`packages/agentvault/match.go`) does
the matching at runtime and reimplements the same rules, so a change here needs the same change there.
-- Paths are rejected *in a host pattern*; `allowedPathPrefixes` is a separate filter that never decodes.
- A filter is judged by what it *allows*, so the refusals are the load-bearing half. The grammar is an
+- Paths are rejected _in a host pattern_; `allowedPathPrefixes` is a separate filter that never decodes.
+ A filter is judged by what it _allows_, so the refusals are the load-bearing half. The grammar is an
allowlist because a prefix is compared against the escaped path: one carrying anything Go's encoder
rewrites could never match. `agent-vault-path-prefix-schemas.ts` is the grammar of record, `policy.go` the match.
- Methods and path prefixes are filters on a service that already matched, **not** part of the match key,
@@ -189,7 +190,7 @@ path decides what a service can reach, so it stays literal.
session project's variables.
- **A variable delete and a service save meet on the variable row**: the delete locks it `FOR UPDATE`, a save
locks what it references `FOR SHARE` (`insertReferenceRows`). Create serialises on a per-project advisory lock;
- the `(projectId, key)` unique index is the backstop.
+ the shared-key partial unique index is the backstop.
- A stored value never comes back in any form, a lone `{{KEY}}` included. The sheet lists the keys a stored
field uses under the field and keeps the field masked until it is retyped. Settled: putting a lone
reference back in its field made it the one stored field that shows, and left a field mixing text with a
@@ -228,11 +229,62 @@ 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.
-- Admin only, reads included: every `/agent-vault/variables` route checks `Edit` on access bundles, which a member lacks,
+- Shared variables are admin only, reads included: their routes check `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.
+## Member-provided values
+
+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
+ `memberProvidedFields` first.
+- **One variables resource, two scopes.** `scope` on `/agent-vault/variables` (`shared`, the default, or
+ `personal`) picks the list and the owner of a new one; every variable read and lock in the DAL takes an owner
+ (`null` for shared) so a shared 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
+ shared one for a member. Shared 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
+ sessions.
+- **Resolve fills member fields last**: the admin's fields are expanded against shared variables first, then each
+ personal value against the session actor's personal variables only, so neither is ever expanded twice and a
+ personal `{{KEY}}` can't reach a shared variable. A service whose actor hasn't set every member-provided field
+ goes out with `personalValuesMissing: true` and a passthrough credential. The proxy refuses it with a 403 (CLI
+ 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.
+- **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
+ the new one.
+- **Losing a bundle clears what an actor saved for its services** (`clearPersonalValuesAfterRevoke`), so a later grant
+ starts from nothing. It runs on a bundle revoke and on removal from Agent Vault, for the actors the revoke named
+ and the members of a named group, and skips anyone who still holds the bundle through another grant. Admins
+ reach every bundle without a grant, so the cleanup never sweeps actors the revoke didn't name. Personal variables survive all of this.
+- Personal variables follow the shared 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
+ both reference tables; any one variable only ever appears in one of them.
+- **The API calls them personal values**, the UI's word: a sub-resource of the service
+ (`PATCH`/`DELETE .../services/:serviceId/personal-values`), always the caller's own, with no collection route. 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` per bundle
+ plus a `requiresSetup=true` filter for the sidebar and banners. 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.
+
## Credentials at rest
- The KMS cipher pair is project-scoped (`KmsDataKey.SecretManager`) and built once per resolve.
diff --git a/backend/src/ee/services/agent-vault/agent-vault-enums.ts b/backend/src/ee/services/agent-vault/agent-vault-enums.ts
index 1316ba44cb..b728033891 100644
--- a/backend/src/ee/services/agent-vault/agent-vault-enums.ts
+++ b/backend/src/ee/services/agent-vault/agent-vault-enums.ts
@@ -54,3 +54,21 @@ export enum AgentVaultVariableReferenceField {
CustomHeader = "custom-header",
Substitution = "substitution"
}
+
+export enum AgentVaultVariableScope {
+ Shared = "shared",
+ Personal = "personal"
+}
+
+/**
+ * The fields an admin can leave to each member, named as variable references name them: `credential-value` is a
+ * bearer token or a basic password, `credential-username` a basic username.
+ */
+export type TAgentVaultMemberProvidedField =
+ | AgentVaultVariableReferenceField.CredentialValue
+ | AgentVaultVariableReferenceField.CredentialUsername;
+
+export const AGENT_VAULT_MEMBER_PROVIDED_FIELDS: readonly TAgentVaultMemberProvidedField[] = [
+ AgentVaultVariableReferenceField.CredentialValue,
+ AgentVaultVariableReferenceField.CredentialUsername
+];
diff --git a/backend/src/ee/services/agent-vault/agent-vault-owner-fns.ts b/backend/src/ee/services/agent-vault/agent-vault-owner-fns.ts
new file mode 100644
index 0000000000..c643512c18
--- /dev/null
+++ b/backend/src/ee/services/agent-vault/agent-vault-owner-fns.ts
@@ -0,0 +1,36 @@
+import { Knex } from "knex";
+
+import { ForbiddenRequestError } from "@app/lib/errors";
+import { TGenericPermission } from "@app/lib/types";
+import { ActorType } from "@app/services/auth/auth-type";
+
+// A personal variable or a personal value belongs to exactly one user or machine identity, the actor a session names.
+export type TAgentVaultOwner = { userId: string; identityId?: never } | { identityId: string; userId?: never };
+
+// Null for any other actor, which keeps no values of its own.
+export const ownerOrNullOf = (ctx: TGenericPermission): TAgentVaultOwner | null => {
+ if (ctx.actor === ActorType.USER) return { userId: ctx.actorId };
+ if (ctx.actor === ActorType.IDENTITY) return { identityId: ctx.actorId };
+ return null;
+};
+
+export const ownerOf = (ctx: TGenericPermission): TAgentVaultOwner => {
+ const owner = ownerOrNullOf(ctx);
+ if (owner) return owner;
+ throw new ForbiddenRequestError({
+ message: "Only a user or a machine identity can keep their own Agent Vault variables and values"
+ });
+};
+
+export const ownerColumns = (owner: TAgentVaultOwner | null) => {
+ if (!owner) return { userId: null, identityId: null };
+ return owner.userId ? { userId: owner.userId, identityId: null } : { userId: null, identityId: owner.identityId! };
+};
+
+// `null` matches the rows no one owns, the shared ones.
+export const whereOwner = <T extends Knex.QueryBuilder>(query: T, table: string, owner: TAgentVaultOwner | null) => {
+ if (!owner) return query.whereNull(`${table}.userId`).whereNull(`${table}.identityId`);
+ return owner.userId
+ ? query.where(`${table}.userId`, owner.userId)
+ : query.where(`${table}.identityId`, owner.identityId as string);
+};
diff --git a/backend/src/ee/services/agent-vault/agent-vault-permission.ts b/backend/src/ee/services/agent-vault/agent-vault-permission.ts
index 5299b21510..228b25eac6 100644
--- a/backend/src/ee/services/agent-vault/agent-vault-permission.ts
+++ b/backend/src/ee/services/agent-vault/agent-vault-permission.ts
@@ -104,3 +104,28 @@ export const getAgentVaultReachability = async (
return { isAdmin: false, accessBundleIds, permission };
};
+
+/**
+ * Reachability, plus the bundles the actor holds through a grant whatever their role. For a member the two are the
+ * same; for an admin, who reaches every bundle, the granted ones are what "mine" means.
+ */
+export const getAgentVaultGrantedReachability = async (
+ { permissionService, membershipDAL }: { permissionService: TPermissionDep; membershipDAL: TMembershipDep },
+ { projectId, ctx }: { projectId: string; ctx: TGenericPermission }
+): Promise<TAgentVaultReachability & { grantedAccessBundleIds: string[] }> => {
+ const { permission, isAdmin, memberships } = await $loadAgentVaultPermission(
+ { permissionService },
+ { projectId, ctx }
+ );
+ if (ctx.actor !== ActorType.USER && ctx.actor !== ActorType.IDENTITY) {
+ return { isAdmin, accessBundleIds: isAdmin ? null : [], grantedAccessBundleIds: [], permission };
+ }
+
+ const grantedAccessBundleIds = await findReachableAccessBundleIds(membershipDAL, {
+ projectId,
+ actor: { type: ctx.actor, id: ctx.actorId },
+ groupIds: liveGroupIdsFrom(memberships)
+ });
+
+ return { isAdmin, accessBundleIds: isAdmin ? null : grantedAccessBundleIds, grantedAccessBundleIds, permission };
+};
diff --git a/backend/src/ee/services/agent-vault/agent-vault-variable-fns.ts b/backend/src/ee/services/agent-vault/agent-vault-variable-fns.ts
index 9422cf69e6..722fd124b0 100644
--- a/backend/src/ee/services/agent-vault/agent-vault-variable-fns.ts
+++ b/backend/src/ee/services/agent-vault/agent-vault-variable-fns.ts
@@ -3,6 +3,7 @@ import RE2 from "re2";
export const AGENT_VAULT_VARIABLE_KEY_MAX_LENGTH = 64;
export const AGENT_VAULT_VARIABLE_VALUE_MAX_LENGTH = 8192;
export const AGENT_VAULT_MAX_VARIABLES = 500;
+export const AGENT_VAULT_MAX_PERSONAL_VARIABLES = 100;
// Counts every {{...}}, a repeat included: repeating one short reference is what would let a field fill in to
// millions of characters. With the value limit this is the whole bound on a filled-in field, the text as typed
// plus three values, so no save reads another row to hold a field to it and none can race another past it.
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 82fdc90bfb..0d65864885 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -819,6 +819,8 @@ export enum EventType {
AGENT_VAULT_VARIABLE_UPDATE = "agent-vault-variable-update",
AGENT_VAULT_VARIABLE_DELETE = "agent-vault-variable-delete",
AGENT_VAULT_VARIABLE_VALUE_VIEW = "agent-vault-variable-value-view",
+ AGENT_VAULT_PERSONAL_VALUES_SET = "agent-vault-personal-values-set",
+ AGENT_VAULT_PERSONAL_VALUES_DELETE = "agent-vault-personal-values-delete",
AGENT_VAULT_MEMBER_ADD = "agent-vault-member-add",
AGENT_VAULT_MEMBER_UPDATE = "agent-vault-member-update",
AGENT_VAULT_MEMBER_REMOVE = "agent-vault-member-remove",
@@ -6486,6 +6488,8 @@ interface AgentVaultServiceCreateEvent {
headerPrefix?: string;
allowedMethods?: string[] | null;
allowedPathPrefixes?: string[] | null;
+ // The fields each member sets for themselves, such as credential-value or credential-username.
+ memberProvidedFields?: string[];
// Names and placeholders only. A sealed value must never reach an audit row.
customHeaderNames?: string[];
substitutionPlaceholders?: string[];
@@ -6506,6 +6510,8 @@ interface AgentVaultServiceUpdateEvent {
headerPrefix?: string;
allowedMethods?: string[] | null;
allowedPathPrefixes?: string[] | null;
+ // The fields each member sets for themselves after the update, present when it touched the credential.
+ memberProvidedFields?: string[];
customHeaderNames?: string[];
customHeadersReplaced?: string[];
substitutionPlaceholders?: string[];
@@ -6535,6 +6541,8 @@ interface AgentVaultVariableCreateEvent {
accessBundleName?: string;
variableId: string;
key: string;
+ // shared, or personal for a variable only its owner sees and uses. Absent on events from before personal ones.
+ scope?: string;
};
}
@@ -6545,6 +6553,8 @@ interface AgentVaultVariableUpdateEvent {
accessBundleName?: string;
variableId: string;
key: string;
+ // shared, or personal for a variable only its owner sees and uses. Absent on events from before personal ones.
+ scope?: string;
// Present only when the update changed the key.
previousKey?: string;
valueReplaced: boolean;
@@ -6558,6 +6568,8 @@ interface AgentVaultVariableDeleteEvent {
accessBundleName?: string;
variableId: string;
key: string;
+ // shared, or personal for a variable only its owner sees and uses. Absent on events from before personal ones.
+ scope?: string;
};
}
@@ -6568,6 +6580,34 @@ interface AgentVaultVariableValueViewEvent {
accessBundleName?: string;
variableId: string;
key: string;
+ // shared, or personal for a variable only its owner sees and uses. Absent on events from before personal ones.
+ scope?: string;
+ };
+}
+
+// The personal values the actor set for a service that leaves some fields to each member. Field names only, never a value.
+interface AgentVaultPersonalValuesSetEvent {
+ type: EventType.AGENT_VAULT_PERSONAL_VALUES_SET;
+ metadata: {
+ accessBundleId: string;
+ accessBundleName: string;
+ serviceId: string;
+ serviceName: string;
+ // The fields this update set. A field it left out kept its saved value.
+ fields: string[];
+ // False the first time the actor sets up their personal values for this service.
+ replaced: boolean;
+ variableKeys: string[];
+ };
+}
+
+interface AgentVaultPersonalValuesDeleteEvent {
+ type: EventType.AGENT_VAULT_PERSONAL_VALUES_DELETE;
+ metadata: {
+ accessBundleId: string;
+ accessBundleName: string;
+ serviceId: string;
+ serviceName: string;
};
}
@@ -8562,6 +8602,8 @@ export type Event =
| AgentVaultVariableUpdateEvent
| AgentVaultVariableDeleteEvent
| AgentVaultVariableValueViewEvent
+ | AgentVaultPersonalValuesSetEvent
+ | AgentVaultPersonalValuesDeleteEvent
| AgentVaultProductMemberAddEvent
| AgentVaultProductMemberUpdateEvent
| AgentVaultProductMemberRemoveEvent
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index eab3843df0..373e03cf2d 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -32,6 +32,8 @@ export const PgSqlLock = {
CreateGateway: (orgId: string) => pgAdvisoryLockHashText(`create-gateway:${orgId}`),
CreateAgentVaultProxy: (projectId: string) => pgAdvisoryLockHashText(`create-agent-vault-proxy:${projectId}`),
CreateAgentVaultVariable: (projectId: string) => pgAdvisoryLockHashText(`create-agent-vault-variable:${projectId}`),
+ CreateAgentVaultPersonalVariable: (projectId: string, ownerId: string) =>
+ pgAdvisoryLockHashText(`create-agent-vault-personal-variable:${projectId}:${ownerId}`),
AccessSharedSecret: (sharedSecretId: string) => pgAdvisoryLockHashText(`access-shared-secret:${sharedSecretId}`),
KmsOrgKeyCreation: (orgId: string) => pgAdvisoryLockHashText(`kms-org-key:${orgId}`),
KmsOrgDataKeyCreation: (orgId: string) => pgAdvisoryLockHashText(`kms-org-data-key:${orgId}`),
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index e8ec427d52..49397127d0 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -4452,7 +4452,11 @@ export const AGENT_VAULT = {
search: "Match access bundles by name or description.",
limit: "The maximum number of access bundles to return.",
offset: "How many access bundles to skip.",
- hostPatterns: "Every host pattern the access bundle's services cover."
+ 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.",
+ servicesRequiringSetup:
+ "The names of 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."
},
SERVICE: {
serviceId: "The ID of the service.",
@@ -4494,15 +4498,42 @@ export const AGENT_VAULT = {
substitutionValue: `The real value the placeholder is replaced with. ${AGENT_VAULT_VARIABLE_REFERENCES} Never returned once saved.`,
updateSubstitutionValue: `The real value the placeholder is replaced with. ${AGENT_VAULT_VARIABLE_REFERENCES} Omit to keep the value already stored.`,
variableReferences:
- "The variables this service's credential, custom header values and substitution values use. Not returned to Agent Vault members, since only admins can see variables.",
+ "The shared variables this service's credential, custom header values and substitution values use. Not returned to Agent Vault members, since only admins can see shared variables. A member's own personal variables are listed under personalValues.",
referenceField:
"Which value uses the variable: credential-value (a bearer token or a basic password), credential-username, custom-header or substitution.",
referenceCustomHeaderId: "The custom header whose value uses the variable.",
- referenceSubstitutionId: "The substitution whose value uses the variable."
+ referenceSubstitutionId: "The substitution whose value uses the variable.",
+ 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.",
+ 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."
+ },
+ PERSONAL_VALUE: {
+ 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:
+ "Whether you have set every value this service requires from you. Until you do, the proxy refuses this service's requests from your sessions.",
+ fields: "Each value the service requires from you, and whether you have set it.",
+ field:
+ "Which value: credential-value (a bearer token or a basic password) or credential-username (a basic username).",
+ isSet: "Whether you have set this value.",
+ updatedAt: "When you last set this value, or null if you haven't.",
+ variableReferences: "Your personal variables that this value uses.",
+ values:
+ "The values to set, at most one per field the service leaves to its members. A field you leave out keeps its saved value, so after a field becomes member provided you only need to send that one.",
+ value: `The value. Can use up to ${AGENT_VAULT_MAX_REFERENCES_PER_FIELD} references to your personal variables, written as \`{{KEY}}\`. Never returned once saved.`
},
VARIABLE: {
variableId: "The ID of the variable.",
- key: "The name services use to refer to the variable, as `{{KEY}}`. Starts with a letter and uses only upper case letters, numbers and underscores.",
+ scope:
+ "shared for a variable admins set up for services, or personal for one of your own, which only your personal values can use and only you can see. Personal keys are unique among your own variables.",
+ listScope:
+ "Which variables to list: shared (the default), which needs the admin role, or personal for your own. Nobody can list another member's personal variables.",
+ createScope:
+ "shared (the default) creates a variable services can use, which needs the admin role. personal creates one of your own, which only your personal values can use.",
+ key: "The name values use to refer to the variable, as `{{KEY}}`. Starts with a letter and uses only upper case letters, numbers and underscores.",
value: "The value the proxy puts in place of each `{{KEY}}`.",
updateValue: "The value the proxy puts in place of each `{{KEY}}`. Omit to keep the stored value.",
revealedValue: "The variable's value.",
@@ -4514,7 +4545,7 @@ export const AGENT_VAULT = {
offset: "How many variables to skip.",
totalCount: "How many variables match the search, across every page.",
usedByServices:
- "The services that use this variable, across every access bundle, ordered by access bundle name and then service name. A variable in use can't be deleted.",
+ "The services that use this variable, across every access bundle, ordered by access bundle name and then service name. For a personal variable, the services whose personal values, as you set them, use it. A variable in use can't be deleted.",
usedByServiceId: "The ID of a service that uses this variable.",
usedByServiceName: "The name of the service.",
usedByServiceHostPattern: "The host pattern of the service.",
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 736562113a..1f3b896fd2 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -32,6 +32,11 @@ import { agentVaultServiceSubstitutionDALFactory } from "@app/ee/services/agent-
import { agentVaultServiceVariableReferenceDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-variable-reference-dal";
import { agentVaultMemberDALFactory } from "@app/ee/services/agent-vault-member/agent-vault-member-dal";
import { agentVaultMembershipServiceFactory } from "@app/ee/services/agent-vault-member/agent-vault-membership-service";
+import {
+ agentVaultPersonalValueDALFactory,
+ agentVaultPersonalValueReferenceDALFactory
+} from "@app/ee/services/agent-vault-personal-value/agent-vault-personal-value-dal";
+import { agentVaultPersonalValueServiceFactory } from "@app/ee/services/agent-vault-personal-value/agent-vault-personal-value-service";
import { agentVaultProjectResolverFactory } from "@app/ee/services/agent-vault-project/agent-vault-project-resolver";
import { agentVaultProxyDALFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-dal";
import { agentVaultProxyServiceFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-service";
@@ -1995,6 +2000,8 @@ export const registerRoutes = async (
const agentVaultServiceSubstitutionDAL = agentVaultServiceSubstitutionDALFactory(db);
const agentVaultVariableDAL = agentVaultVariableDALFactory(db);
const agentVaultServiceVariableReferenceDAL = agentVaultServiceVariableReferenceDALFactory(db);
+ const agentVaultPersonalValueDAL = agentVaultPersonalValueDALFactory(db);
+ const agentVaultPersonalValueReferenceDAL = agentVaultPersonalValueReferenceDALFactory(db);
const agentVaultSessionDAL = agentVaultSessionDALFactory(db);
const agentVaultSessionAccessBundleDAL = agentVaultSessionAccessBundleDALFactory(db);
const agentVaultProxyDAL = agentVaultProxyDALFactory(db);
@@ -2007,6 +2014,16 @@ export const registerRoutes = async (
kmsService
});
+ const agentVaultPersonalValueService = agentVaultPersonalValueServiceFactory({
+ agentVaultPersonalValueDAL,
+ agentVaultPersonalValueReferenceDAL,
+ agentVaultVariableDAL,
+ agentVaultServiceDAL,
+ permissionService,
+ membershipDAL,
+ kmsService
+ });
+
const agentVaultAccessBundleService = agentVaultAccessBundleServiceFactory({
agentVaultAccessBundleDAL,
agentVaultServiceDAL,
@@ -2014,6 +2031,8 @@ export const registerRoutes = async (
agentVaultServiceSubstitutionDAL,
agentVaultVariableDAL,
agentVaultServiceVariableReferenceDAL,
+ agentVaultPersonalValueDAL,
+ agentVaultPersonalValueService,
permissionService,
kmsService,
membershipDAL,
@@ -2054,7 +2073,10 @@ export const registerRoutes = async (
userAliasDAL,
orgDAL,
permissionService,
- usageMeteringService
+ usageMeteringService,
+ agentVaultPersonalValueDAL,
+ userGroupMembershipDAL,
+ identityGroupMembershipDAL
});
const pamProjectResolver = pamProjectResolverFactory({
@@ -2142,6 +2164,7 @@ export const registerRoutes = async (
agentVaultServiceCustomHeaderDAL,
agentVaultServiceSubstitutionDAL,
agentVaultVariableDAL,
+ agentVaultPersonalValueDAL,
agentVaultSessionDAL,
agentVaultSessionLogConfigDAL,
membershipDAL,
@@ -4700,6 +4723,7 @@ export const registerRoutes = async (
agentVaultProjectResolver,
agentVaultAccessBundle: agentVaultAccessBundleService,
agentVaultVariable: agentVaultVariableService,
+ agentVaultPersonalValue: agentVaultPersonalValueService,
agentVaultProxy: agentVaultProxyService,
agentVaultSession: agentVaultSessionService,
agentVaultSessionLog: agentVaultSessionLogService,
diff --git a/backend/src/services/telemetry/telemetry-types.ts b/backend/src/services/telemetry/telemetry-types.ts
index 8cf3c68a0e..3aaaf95280 100644
--- a/backend/src/services/telemetry/telemetry-types.ts
+++ b/backend/src/services/telemetry/telemetry-types.ts
@@ -2480,13 +2480,14 @@ export type TAgentVaultServiceDeletedEvent = {
export type TAgentVaultVariableCreatedEvent = {
event: PostHogEventTypes.AgentVaultVariableCreated;
- properties: TAgentVaultEventBase & { variableId: string };
+ properties: TAgentVaultEventBase & { variableId: string; scope: string };
};
export type TAgentVaultVariableUpdatedEvent = {
event: PostHogEventTypes.AgentVaultVariableUpdated;
properties: TAgentVaultEventBase & {
variableId: string;
+ scope: string;
keyChanged: boolean;
valueReplaced: boolean;
usedByServiceCount: number;
@@ -2495,7 +2496,7 @@ export type TAgentVaultVariableUpdatedEvent = {
export type TAgentVaultVariableDeletedEvent = {
event: PostHogEventTypes.AgentVaultVariableDeleted;
- properties: TAgentVaultEventBase & { variableId: string };
+ properties: TAgentVaultEventBase & { variableId: string; scope: string };
};
export type TAgentVaultAccessBundleMemberAddedEvent = {
diff --git a/docs/api-reference/endpoints/agent-vault-services/delete-personal-values.mdx b/docs/api-reference/endpoints/agent-vault-services/delete-personal-values.mdx
new file mode 100644
index 0000000000..1e8d6520f0
--- /dev/null
+++ b/docs/api-reference/endpoints/agent-vault-services/delete-personal-values.mdx
@@ -0,0 +1,4 @@
+---
+title: "Delete personal values"
+openapi: "DELETE /api/v1/agent-vault/access-bundles/{accessBundleId}/services/{serviceId}/personal-values"
+---
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
new file mode 100644
index 0000000000..32a8fd3e0a
--- /dev/null
+++ b/docs/api-reference/endpoints/agent-vault-services/set-personal-values.mdx
@@ -0,0 +1,4 @@
+---
+title: "Set personal values"
+openapi: "PUT /api/v1/agent-vault/access-bundles/{accessBundleId}/services/{serviceId}/personal-values"
+---
diff --git a/docs/docs.json b/docs/docs.json
index 732f8ec921..51fea8c94a 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -4520,7 +4520,9 @@
"pages": [
"api-reference/endpoints/agent-vault-services/create",
"api-reference/endpoints/agent-vault-services/update",
- "api-reference/endpoints/agent-vault-services/delete"
+ "api-reference/endpoints/agent-vault-services/delete",
+ "api-reference/endpoints/agent-vault-services/set-personal-values",
+ "api-reference/endpoints/agent-vault-services/delete-personal-values"
]
},
{
diff --git a/docs/documentation/platform/agent-vault/access-bundles.mdx b/docs/documentation/platform/agent-vault/access-bundles.mdx
index f1eeb921b7..316be9ef6b 100644
--- a/docs/documentation/platform/agent-vault/access-bundles.mdx
+++ b/docs/documentation/platform/agent-vault/access-bundles.mdx
@@ -12,7 +12,10 @@ You can reuse access bundles across as many sessions as you like. This makes the
- A **marketing** bundle that grants access to Twilio and Google Docs
<Frame>
- <img src="/images/platform/agent-vault/access-bundles-list.png" alt="The Access Bundles page listing four access bundles with their services and member counts" />
+ <img
+ src="/images/platform/agent-vault/access-bundles-list.png"
+ alt="The Access Bundles page listing four access bundles with their services and member counts"
+ />
</Frame>
## Create an access bundle
@@ -21,14 +24,14 @@ To create a new access bundle:
<Steps>
<Step>
- In Agent Vault, go to **Access Bundles** and select **Create Access Bundle**.
+ In Agent Vault, go to **Access Bundles** and select **Create Access
+ Bundle**.
</Step>
<Step>
- Give the bundle a name that says what job it's for, like **code-review** or **marketing**.
- </Step>
- <Step>
- Select **Create**. The access bundle will appear in the list.
+ Give the bundle a name that says what job it's for, like **code-review** or
+ **marketing**.
</Step>
+ <Step>Select **Create**. The access bundle will appear in the list.</Step>
</Steps>
Now you can [add services](/documentation/platform/agent-vault/services#add-a-service) to the access bundle so agents using it can make authenticated requests.
@@ -55,4 +58,32 @@ To allow a user, group, or machine identity to create sessions for a given acces
### Revoke access
-To revoke access from a user, group, or machine identity, open the bundle and select **Options** > **Manage Access**. Find them with the search box, open their actions menu, and select **Revoke Access**. If any of their agents are running, those agents lose the bundle's credentials within one [poll interval](/documentation/platform/agent-vault/proxies#poll-interval).
\ No newline at end of file
+To revoke access from a user, group, or machine identity, open the bundle and select **Options** > **Manage Access**. Find them with the search box, open their actions menu, and select **Revoke Access**. If any of their agents are running, those agents lose the bundle's credentials within one [poll interval](/documentation/platform/agent-vault/proxies#poll-interval).
+
+## Set up your personal values
+
+Some services ask you for part of their credential, such as your own API key (see [member-provided values](/documentation/platform/agent-vault/services#member-provided-values)). Until you set up your personal values for one of these services, your sessions can't use it, and the service shows **Requires Setup**. This applies to admins too.
+
+To set up your personal values:
+
+<Steps>
+ <Step>
+ In Agent Vault, go to **Access Bundles** and select the access bundle.
+ </Step>
+ <Step>
+ Select **Requires Setup** next to the service, or open the service's actions menu and select **Set Up My Personal Values**.
+ </Step>
+ <Step>
+ Enter each value. To use one of your [personal variables](/documentation/platform/agent-vault/variables#personal-variables), type `{{` or select the arrow at the end of the field, then pick a variable from the list.
+ </Step>
+ <Step>
+ Select **Save**. The service shows **Configured**.
+ </Step>
+</Steps>
+
+Only you can read your personal values, so admins can't see them either.
+
+- To change your personal values, open the service's actions menu, select **Update My Personal Values**, and enter the values you want to change (a field you leave blank keeps its saved value)
+- To delete your personal values, select **Remove** in the same dialog, then select **Remove Personal Values**
+
+If you lose access to the access bundle, Infisical deletes the personal values you set up for its services.
diff --git a/docs/documentation/platform/agent-vault/services.mdx b/docs/documentation/platform/agent-vault/services.mdx
index 7bf606d3d0..cde0a92047 100644
--- a/docs/documentation/platform/agent-vault/services.mdx
+++ b/docs/documentation/platform/agent-vault/services.mdx
@@ -6,13 +6,18 @@ description: "External APIs that an AI agent can securely call during a session.
A service represents one external API that an agent can access during a [session](/documentation/platform/agent-vault/sessions). Each service defines the external API’s [host URL](#host-patterns), its [authentication method](#credential-types), and a real credential to attach when forwarding requests from the agent.
<Tip>
-A service can also limit which [HTTP methods and paths](#methods-and-paths) the agent can use, [add custom headers](#custom-headers) to each request, and [replace placeholder values](#substitutions) the agent sends with real ones.
+ A service can also limit which [HTTP methods and paths](#methods-and-paths)
+ the agent can use, [add custom headers](#custom-headers) to each request, and
+ [replace placeholder values](#substitutions) the agent sends with real ones.
</Tip>
You can configure services within an [access bundle](/documentation/platform/agent-vault/access-bundles). For example, you might create a **code-review** access bundle and add services for Slack, GitHub, and Anthropic:
<Frame>
- <img src="/images/platform/agent-vault/access-bundle-services.png" alt="The code-review access bundle's Services table listing its GitHub, Slack, and Anthropic services with their credentials and hosts" />
+ <img
+ src="/images/platform/agent-vault/access-bundle-services.png"
+ alt="The code-review access bundle's Services table listing its GitHub, Slack, and Anthropic services with their credentials and hosts"
+ />
</Frame>
## Add a service
@@ -29,11 +34,13 @@ To add a service to an access bundle:
<Frame>
<img src="/images/platform/agent-vault/service-template-picker.png" alt="The Choose a template panel with Custom, OpenAI, Anthropic, Slack, GitHub, and Google Workspace" />
</Frame>
+
</Step>
<Step>
Follow the steps and paste your credentials in the **Credential** section.
To use a value that several services share, type `{{` in a [field that accepts variables](/documentation/platform/agent-vault/variables#use-a-variable-in-a-service) and select a variable from the list that opens.
+
</Step>
<Step>
Select **Add Service**. The service appears in the bundle's list.
@@ -45,7 +52,8 @@ To add a service to an access bundle:
When configuring a service, you have the option to set its credential type. This determines what the proxy attaches to outbound requests.
<Tip>
-If you're configuring a service with a template, you can usually leave the credential type set to the default.
+ If you're configuring a service with a template, you can usually leave the
+ credential type set to the default.
</Tip>
### Bearer
@@ -67,15 +75,52 @@ The proxy attaches no credential. Unless the service adds [custom headers](#cust
Pass-through is the right choice when the proxy's strict [traffic policy](/documentation/platform/agent-vault/proxies#traffic-policy) would otherwise block the host. It lets the request reach the API without attaching a credential.
<Note>
-For **Bearer** and **Basic** services, if the agent's request already carries a header with the same name as the one the service sends, the proxy replaces it with the service's credential.
+ For **Bearer** and **Basic** services, if the agent's request already carries
+ a header with the same name as the one the service sends, the proxy replaces
+ it with the service's credential.
</Note>
+## 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.
+
+You can make these credential fields member provided:
+
+- **Token** in a [Bearer](#bearer) credential
+- **Username**, **Password**, or both in a [Basic](#basic) credential
+
+To make a field member provided:
+
+<Steps>
+ <Step>
+ In Agent Vault, go to **Access Bundles** and select the access bundle. Open
+ the service's actions menu and select **Edit**, then go to the
+ **Credential** step.
+ </Step>
+ <Step>Next to the field, turn on **Member provided**.</Step>
+ <Step>Select **Continue**, then select **Save**.</Step>
+</Steps>
+
+When you change which fields are member provided, members keep the values that still apply:
+
+- If you make another field member provided, each member keeps their saved values and only has to add the new one
+- If you stop leaving a field to members, Infisical deletes their values for that field only
+
+<Warning>
+ If you change the credential type, Infisical deletes every member's personal
+ values for the service, and each member has to set them up 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.
+
## Host patterns
When configuring a service, you have the option to set which host patterns it matches. A host pattern controls which outbound requests get the service's credential attached.
<Tip>
-For security reasons, we recommend keeping host patterns as narrow as the API allows. If you're configuring a service with a template, you can usually leave the host set to the default.
+ For security reasons, we recommend keeping host patterns as narrow as the API
+ allows. If you're configuring a service with a template, you can usually leave
+ the host set to the default.
</Tip>
### Multiple hosts
@@ -117,7 +162,9 @@ internal-api.example.com:8080
If you don't name the port, the host will only match [port `443`](#default-port):
<Warning>
-The proxy sends the credential to a plaintext host unencrypted, so anyone who can read traffic between the proxy and the API can read the credential. Only use plaintext hosts on a network you trust.
+ The proxy sends the credential to a plaintext host unencrypted, so anyone who
+ can read traffic between the proxy and the API can read the credential. Only
+ use plaintext hosts on a network you trust.
</Warning>
### Wildcards
@@ -140,11 +187,16 @@ However, two services can match the same host if they define the host pattern di
In the above example, requests to `api.github.com` are handled by the first service.
<Warning>
-The proxy applies only the more specific service's [methods and paths](#methods-and-paths). This means that if the `api.github.com` service allows only `GET`, the proxy refuses a `POST` to `api.github.com`, even if that same `POST` request would succeed through `*.github.com`.
+ The proxy applies only the more specific service's [methods and
+ paths](#methods-and-paths). This means that if the `api.github.com` service
+ allows only `GET`, the proxy refuses a `POST` to `api.github.com`, even if
+ that same `POST` request would succeed through `*.github.com`.
</Warning>
<Note>
-Different access bundles can cover the same host with different credentials, since an agent only gets the credential from the access bundle its session is scoped to.
+ Different access bundles can cover the same host with different credentials,
+ since an agent only gets the credential from the access bundle its session is
+ scoped to.
</Note>
## Methods and paths
@@ -152,7 +204,10 @@ Different access bundles can cover the same host with different credentials, sin
By default, a service allows every HTTP method and every path on its hosts. When configuring a service, you have the option to narrow it to only the methods and paths your agent needs.
<Frame>
- <img src="/images/platform/agent-vault/service-details.png" alt="The Details step of a GitHub service, allowing GET and POST on the path prefixes /repos and /search" />
+ <img
+ src="/images/platform/agent-vault/service-details.png"
+ alt="The Details step of a GitHub service, allowing GET and POST on the path prefixes /repos and /search"
+ />
</Frame>
### Methods
@@ -164,7 +219,10 @@ On the **Details** step, clear **All Methods** and select the HTTP methods the s
On the **Details** step's **Paths** field, enter each path prefix the service allows. A path prefix matches whole segments, so `/repos` covers `/repos/octo/hello` but not `/repositories`. Write the path exactly as it appears in the URL.
<Note>
-If a service has path prefixes, the proxy also refuses any path that different servers would resolve differently, such as one containing `..` or an encoded slash. Ordinary paths still work, including ones with a space or a non-ASCII character such as `/repos/owner/repo/contents/café.md`.
+ If a service has path prefixes, the proxy also refuses any path that different
+ servers would resolve differently, such as one containing `..` or an encoded
+ slash. Ordinary paths still work, including ones with a space or a non-ASCII
+ character such as `/repos/owner/repo/contents/café.md`.
</Note>
### Refused requests
@@ -188,13 +246,19 @@ service "github" does not allow path "/admin": blocked by service policy
Some APIs need a header alongside the credential, such as an organization ID or an API version. On the **Credential** step, under **Advanced Options**, select **Add Custom Header** and enter a name, an optional prefix, and a value. The proxy attaches it to every request to that service, whatever credential type the service uses.
<Frame>
- <img src="/images/platform/agent-vault/service-advanced-options.png" alt="The Credential step with an API version custom header and a substitution that swaps the agent's placeholder for the real token, matched in the header" />
+ <img
+ src="/images/platform/agent-vault/service-advanced-options.png"
+ alt="The Credential step with an API version custom header and a substitution that swaps the agent's placeholder for the real token, matched in the header"
+ />
</Frame>
Infisical won't save a custom header with the same name as the credential's header, because the proxy would overwrite it with the credential. Infisical also won't save a custom header that the proxy sets itself, such as `Host`, `Content-Length`, or `Connection`.
<Tip>
-A custom header's value can include a [substitution](#substitutions) placeholder. If that substitution has **Headers** selected under **Replace In**, the proxy replaces the placeholder with the real value, so several headers can reuse one secret.
+ A custom header's value can include a [substitution](#substitutions)
+ placeholder. If that substitution has **Headers** selected under **Replace
+ In**, the proxy replaces the placeholder with the real value, so several
+ headers can reuse one secret.
</Tip>
## Substitutions
@@ -212,7 +276,7 @@ GitHub receives the real token, and the agent never holds it.
We recommend using substitutions when your agent's tool won't run without a token of its own, or when the API expects the credential outside a header, such as in the URL path or the query string.
<Info>
-Substitutions work with every credential type, including pass-through.
+ Substitutions work with every credential type, including pass-through.
</Info>
### Add a substitution
@@ -227,6 +291,7 @@ Substitutions work with every credential type, including pass-through.
<Tip>
The proxy replaces every occurrence of the placeholder, so pick one that won't appear anywhere else in the request.
</Tip>
+
</Step>
<Step>
Under **Replace In**, select where the proxy looks for the placeholder: **URL Path**, **Query String**, **Headers**, or **Body**.
@@ -237,6 +302,7 @@ Substitutions work with every credential type, including pass-through.
<Tip>
Some tools check a token's format before they send it. If the agent's tool does, make the placeholder match the format of the real key, such as `ghp_` followed by 36 characters for a GitHub token.
</Tip>
+
</Step>
</Steps>
diff --git a/docs/documentation/platform/agent-vault/sessions.mdx b/docs/documentation/platform/agent-vault/sessions.mdx
index 2b6824e396..c1fe76fa28 100644
--- a/docs/documentation/platform/agent-vault/sessions.mdx
+++ b/docs/documentation/platform/agent-vault/sessions.mdx
@@ -24,6 +24,8 @@ Anyone granted at least one access bundle can create a session. Admins can creat
<Step>
Pick the **Access Bundle** the agent should use, set a duration under **Expires**, then select **Create Session**.
+ If a service in the bundle still requires [your personal values](/documentation/platform/agent-vault/access-bundles#set-up-your-personal-values), the dialog lists the service with a **Set Up** button. You can create the session before you set up your personal values, but until you do, the proxy refuses the session's requests to that service.
+
<Frame>
<img src="/images/platform/agent-vault/session-create.png" alt="The Create Session dialog with an access bundle picked and a seven day expiry" />
</Frame>
diff --git a/docs/documentation/platform/agent-vault/variables.mdx b/docs/documentation/platform/agent-vault/variables.mdx
index df208d8668..a2062d0247 100644
--- a/docs/documentation/platform/agent-vault/variables.mdx
+++ b/docs/documentation/platform/agent-vault/variables.mdx
@@ -8,7 +8,7 @@ A variable is a value that you can use in any [service](/documentation/platform/
When an agent sends a request, the [proxy](/documentation/platform/agent-vault/proxies) replaces each reference with the variable's value.
<Info>
- Only [Agent Vault admins](/documentation/platform/agent-vault/access-control#product-membership) can view and update variables. If you're a member, **Variables** doesn't appear in the Agent Vault sidebar.
+ Only [Agent Vault admins](/documentation/platform/agent-vault/access-control#product-membership) can view and update shared variables, the variables that services use. Every member, including admins, can also keep [personal variables](#personal-variables).
</Info>
## Add a variable
@@ -17,7 +17,7 @@ To add a variable:
<Steps>
<Step>
- In Agent Vault, go to **Variables**.
+ In Agent Vault, go to **Variables** > **Shared Variables**.
<Frame>
<img src="/images/platform/agent-vault/variables-empty.png" alt="The Variables page with no variables and an Add Variable button" />
@@ -25,7 +25,7 @@ To add a variable:
</Step>
<Step>
- Select **Add Variable**.
+ Select **Add Shared Variable**.
<Frame>
<img src="/images/platform/agent-vault/variable-create.png" alt="The Add Variable dialog with GITHUB_TOKEN as the key and a hidden value" />
@@ -41,7 +41,7 @@ To add a variable:
</Step>
<Step>
- Select **Add Variable**. The variable appears in the list on the **Variables** page.
+ Select **Add Shared Variable**. The variable appears in the list on the **Shared Variables** tab.
<Frame>
<img src="/images/platform/agent-vault/variables.png" alt="The Variables page listing seven variables with hidden values. The Used By column shows access bundle badges, such as code-review, on-call, and release-notes for GITHUB_TOKEN, with a tooltip listing the github service in code-review. SLACK_BOT_TOKEN shows three badges and +1 for one more access bundle. SENTRY_AUTH_TOKEN shows Unused." />
@@ -81,7 +81,7 @@ To use a variable:
Select a variable from the list. Infisical inserts the reference, such as `{{GITHUB_TOKEN}}`.
<Tip>
- You can also create a variable without leaving the service. Type its key, then select **Create** at the end of the list. The **Add Variable** dialog opens with the key filled in, so you only need to enter a **Value**.
+ You can also create a variable without leaving the service. Type its key, then select **Create** at the end of the list. The **Add Shared Variable** dialog opens with the key filled in, so you only need to enter a **Value**.
</Tip>
<Frame>
@@ -147,3 +147,14 @@ To delete a variable:
<Note>
If any service still uses the variable, the dialog lists those services, and you can't delete the variable until you [remove the reference](#use-a-variable-in-a-service) from each one.
</Note>
+
+## Personal variables
+
+A personal variable works like a shared variable, with two differences: only your [personal values](/documentation/platform/agent-vault/access-bundles#set-up-your-personal-values) can use it, and only you can read it. Use one when several services ask you for the same value, such as a personal GitHub token that services in two access bundles require.
+
+To see your personal variables, go to **Variables** in Agent Vault. If you're an admin, select the **Personal Variables** tab.
+
+You add, update, and delete personal variables the same way as [shared variables](#add-a-variable), with these limits:
+
+- You can keep up to 100 personal variables
+- If your personal values for a service use a variable, you can't delete the variable until you change those values
diff --git a/frontend/src/components/agent-vault/PersonalValuesDialog.tsx b/frontend/src/components/agent-vault/PersonalValuesDialog.tsx
new file mode 100644
index 0000000000..7bd9be06fa
--- /dev/null
+++ b/frontend/src/components/agent-vault/PersonalValuesDialog.tsx
@@ -0,0 +1,418 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { Controller, ControllerRenderProps, FormProvider, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { format } from "date-fns";
+import { z } from "zod";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ AlertDialog,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ Button,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldLabel
+} from "@app/components/v3";
+import { findTemplateForHostPattern } from "@app/helpers/agentVaultTemplates";
+import {
+ findVariableReferences,
+ MAX_PERSONAL_VARIABLES,
+ variableReferenceError
+} from "@app/helpers/agentVaultVariables";
+import {
+ AgentVaultCredentialType,
+ AgentVaultVariableReferenceField,
+ AgentVaultVariableScope,
+ TAgentVaultMemberProvidedField,
+ useDeleteAgentVaultPersonalValues,
+ useListAgentVaultVariables,
+ useSetAgentVaultPersonalValues
+} from "@app/hooks/api/agentVault";
+import { TAgentVaultService, TAgentVaultVariable } from "@app/hooks/api/agentVault/types";
+
+import { SecretInput } from "./service-sheet/CredentialFields";
+import { TServiceForm } from "./service-sheet/serviceSchema";
+import {
+ NO_MISSING_KEYS,
+ NO_STORED_KEYS,
+ ServiceVariablesContext
+} from "./service-sheet/ServiceVariablesContext";
+import { VariableKeyChips } from "./service-sheet/VariableChips";
+import { VariableFormDialog } from "./VariableFormDialog";
+
+// Mirrors AGENT_VAULT_NO_CONTROL_CHARS_RE on the backend.
+// eslint-disable-next-line no-control-regex
+const NO_CONTROL_CHARS_RE = /^[^\x00-\x1f\x7f]*$/;
+
+const CONTROL_CHARS_MESSAGE =
+ "This can't contain line breaks or other control characters. Check for a stray newline if you pasted it.";
+
+// The fields reuse the service sheet's secret input, which names them as the sheet does: a token or a basic
+// password is `secret`.
+type TFormField = "secret" | "username";
+
+const FORM_FIELD_OF: Record<TAgentVaultMemberProvidedField, TFormField> = {
+ [AgentVaultVariableReferenceField.CredentialValue]: "secret",
+ [AgentVaultVariableReferenceField.CredentialUsername]: "username"
+};
+
+// credential-value is a bearer token or a basic password.
+const fieldLabel = (
+ credentialType: AgentVaultCredentialType,
+ field: TAgentVaultMemberProvidedField
+) => {
+ if (field === AgentVaultVariableReferenceField.CredentialUsername) return "Username";
+ return credentialType === AgentVaultCredentialType.Basic ? "Password" : "Token";
+};
+
+const MAX_LENGTH = 8192;
+
+type TFormData = { secret: string; username: string };
+
+// A field with a saved value may be left blank, which keeps that value.
+const buildSchema = (
+ fields: TAgentVaultMemberProvidedField[],
+ savedFields: ReadonlySet<TAgentVaultMemberProvidedField>,
+ variableKeys?: string[]
+) => {
+ const keys = variableKeys ? new Set(variableKeys) : undefined;
+ return z.object({ secret: z.string(), username: z.string() }).superRefine((data, ctx) => {
+ fields.forEach((field) => {
+ const formField = FORM_FIELD_OF[field];
+ const value =
+ field === AgentVaultVariableReferenceField.CredentialUsername
+ ? data[formField].trim()
+ : data[formField];
+ const at = (message: string) =>
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: [formField], message });
+
+ if (!value) {
+ if (!savedFields.has(field)) at("Required");
+ } else if (value.length > MAX_LENGTH) {
+ at(`This can be at most ${MAX_LENGTH} characters.`);
+ } else if (!NO_CONTROL_CHARS_RE.test(value)) at(CONTROL_CHARS_MESSAGE);
+ else {
+ // Only once the list has loaded: until then no key can be called missing.
+ const missingKeys = keys
+ ? new Set(findVariableReferences(value).filter((ref) => !keys.has(ref)))
+ : undefined;
+ const referenceError = variableReferenceError(value, missingKeys, { isPersonal: true });
+ if (referenceError) at(referenceError);
+ }
+ });
+ });
+};
+
+export type TPersonalValuesTarget = { service: TAgentVaultService; accessBundleName: string };
+
+type Props = {
+ target: TPersonalValuesTarget | null;
+ onOpenChange: (isOpen: boolean) => void;
+};
+
+/**
+ * Sets the caller's own values for a service that leaves some of its fields to each member. Values never come back,
+ * so ones already set are replaced in full by typing them again.
+ */
+export const PersonalValuesDialog = ({ target, onOpenChange }: Props) => {
+ const isOpen = Boolean(target);
+ const service = target?.service;
+ const personalValues = service?.personalValues;
+ const setValues = useSetAgentVaultPersonalValues();
+ const deleteValues = useDeleteAgentVaultPersonalValues();
+ // A member keeps at most MAX_PERSONAL_VARIABLES, so one page holds every one of them.
+ const { data: variablePage } = useListAgentVaultVariables(
+ { scope: AgentVaultVariableScope.Personal, limit: MAX_PERSONAL_VARIABLES },
+ { enabled: isOpen }
+ );
+ const variables = variablePage?.variables;
+ const variableKeys = useMemo(() => variables?.map((variable) => variable.key), [variables]);
+
+ const fields = useMemo(
+ () =>
+ // The username comes first, the way a basic credential reads.
+ (personalValues?.fields ?? [])
+ .map(({ field }) => field)
+ .sort(
+ (a, b) =>
+ Number(b === AgentVaultVariableReferenceField.CredentialUsername) -
+ Number(a === AgentVaultVariableReferenceField.CredentialUsername)
+ ),
+ [personalValues]
+ );
+ const savedFields = useMemo(
+ () =>
+ new Set(
+ (personalValues?.fields ?? []).filter((entry) => entry.isSet).map((entry) => entry.field)
+ ),
+ [personalValues]
+ );
+ const schema = useMemo(
+ () => buildSchema(fields, savedFields, variableKeys),
+ [fields, savedFields, variableKeys]
+ );
+
+ const formMethods = useForm<TFormData>({
+ defaultValues: { secret: "", username: "" },
+ resolver: zodResolver(schema)
+ });
+ const {
+ control,
+ handleSubmit,
+ reset,
+ formState: { isSubmitting }
+ } = formMethods;
+
+ useEffect(() => {
+ if (isOpen) reset({ secret: "", username: "" });
+ }, [isOpen, service?.id, reset]);
+
+ // One dialog for every field, settled once it has closed, as in the service sheet.
+ const [isRemoveOpen, setIsRemoveOpen] = useState(false);
+ const [newVariableKey, setNewVariableKey] = useState<string | null>(null);
+ const newVariableRequest = useRef<{
+ resolve: (variable: TAgentVaultVariable | null) => void;
+ created: TAgentVaultVariable | null;
+ } | null>(null);
+ const requestVariable = useCallback(
+ (key: string) =>
+ new Promise<TAgentVaultVariable | null>((resolve) => {
+ newVariableRequest.current?.resolve(null);
+ newVariableRequest.current = { resolve, created: null };
+ setNewVariableKey(key);
+ }),
+ []
+ );
+ const formValues = formMethods.watch();
+ const referencedKeys = fields.flatMap((field) =>
+ findVariableReferences(formValues[FORM_FIELD_OF[field]] ?? "")
+ );
+ const missingKeys = useMemo(() => {
+ if (!variableKeys) return NO_MISSING_KEYS;
+ const known = new Set(variableKeys);
+ return new Set(referencedKeys.filter((key) => !known.has(key)));
+ // Keyed on the joined list, which is new on every render as an array.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [variableKeys, referencedKeys.join(",")]);
+ const ownVariables = useMemo(
+ () => ({
+ missingKeys,
+ storedKeys: NO_STORED_KEYS,
+ requestVariable,
+ localVariables: variables,
+ isLocal: true
+ }),
+ [missingKeys, variables, requestVariable]
+ );
+
+ const template = service ? findTemplateForHostPattern(service.hostPattern) : undefined;
+ const providerName = template?.name ?? service?.name;
+
+ const storedKeysOf = (field: TAgentVaultMemberProvidedField) =>
+ (personalValues?.fields.find((entry) => entry.field === field)?.variableReferences ?? []).map(
+ (reference) => reference.key
+ );
+ const lastSetAt = personalValues?.fields.reduce<string | null>(
+ (latest, { updatedAt }) => (updatedAt && (!latest || updatedAt > latest) ? updatedAt : latest),
+ null
+ );
+
+ const onSubmit = async (data: TFormData) => {
+ if (!service) return;
+ try {
+ await setValues.mutateAsync({
+ accessBundleId: service.accessBundleId,
+ serviceId: service.id,
+ // A blank field keeps its saved value, so only the ones typed are sent.
+ values: fields
+ .map((field) => ({
+ field,
+ value:
+ field === AgentVaultVariableReferenceField.CredentialUsername
+ ? data.username.trim()
+ : data[FORM_FIELD_OF[field]]
+ }))
+ .filter(({ value }) => value.length > 0)
+ });
+ createNotification({ text: `${service.name} set up`, type: "success" });
+ onOpenChange(false);
+ } catch {
+ // A failed request returns a 4xx that the global request handler surfaces as a toast
+ }
+ };
+
+ const handleRemove = async () => {
+ if (!service) return;
+ try {
+ await deleteValues.mutateAsync({
+ accessBundleId: service.accessBundleId,
+ serviceId: service.id
+ });
+ createNotification({
+ text: `Your personal values for ${service.name} were removed`,
+ type: "success"
+ });
+ setIsRemoveOpen(false);
+ onOpenChange(false);
+ } catch {
+ // A failed request returns a 4xx that the global request handler surfaces as a toast
+ }
+ };
+
+ return (
+ <Dialog open={isOpen} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Set up {service?.name}</DialogTitle>
+ <DialogDescription>
+ {personalValues?.isConfigured && lastSetAt
+ ? `You set these up on ${format(new Date(lastSetAt), "MMM d, yyyy")}. Sessions you start with ${target?.accessBundleName} use them. A field you leave blank keeps its saved value.`
+ : `Sessions you start with ${target?.accessBundleName} use your personal ${providerName} values. Only you can read them.`}
+ </DialogDescription>
+ </DialogHeader>
+
+ <FormProvider {...formMethods}>
+ <ServiceVariablesContext.Provider value={ownVariables}>
+ <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4">
+ {fields.map((field) => {
+ const label = fieldLabel(
+ service?.credential.type ?? AgentVaultCredentialType.Bearer,
+ field
+ );
+ const storedKeys = storedKeysOf(field);
+ return (
+ <Controller
+ key={field}
+ control={control}
+ name={FORM_FIELD_OF[field]}
+ render={({ field: formField, fieldState }) => (
+ <Field>
+ <FieldLabel>
+ {providerName} {label.toLowerCase()}
+ </FieldLabel>
+ <FieldContent>
+ <SecretInput
+ // The input is the service sheet's, typed against its form. This form names the
+ // same two fields, so only the type differs.
+ field={
+ formField as unknown as ControllerRenderProps<
+ TServiceForm,
+ TFormField
+ >
+ }
+ label={label}
+ placeholder={
+ savedFields.has(field)
+ ? "Leave blank to keep your saved value"
+ : "Enter a value or choose a variable"
+ }
+ isError={Boolean(fieldState.error)}
+ isUntouched={false}
+ hasStoredSecret={false}
+ canBeCleared={false}
+ canInsertVariable
+ />
+ {savedFields.has(field) && storedKeys.length > 0 && (
+ <FieldDescription className="flex flex-wrap items-center gap-1">
+ Your current {label.toLowerCase()} uses
+ <VariableKeyChips keys={storedKeys} />
+ </FieldDescription>
+ )}
+ <FieldError>{fieldState.error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
+ );
+ })}
+
+ <DialogFooter className="sm:justify-between">
+ {personalValues?.isConfigured ? (
+ <Button type="button" variant="danger" onClick={() => setIsRemoveOpen(true)}>
+ Remove
+ </Button>
+ ) : (
+ <span />
+ )}
+ <div className="flex gap-2">
+ <Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button
+ type="submit"
+ variant="av"
+ isPending={isSubmitting}
+ // Every field is saved and none was typed, so there is nothing to send.
+ isDisabled={fields.every(
+ (field) =>
+ savedFields.has(field) && !(formValues[FORM_FIELD_OF[field]] ?? "").trim()
+ )}
+ >
+ Save
+ </Button>
+ </div>
+ </DialogFooter>
+ </form>
+ </ServiceVariablesContext.Provider>
+ </FormProvider>
+
+ <AlertDialog open={isRemoveOpen} onOpenChange={setIsRemoveOpen}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Remove your personal {service?.name} values?</AlertDialogTitle>
+ <AlertDialogDescription>
+ Until you set it up again, {service?.name} rejects requests from your sessions. Your
+ variables are kept.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel variant="outline">Cancel</AlertDialogCancel>
+ {/* A plain button rather than AlertDialogAction, which closes on click and would drop the
+ pending state before the request settles. */}
+ <Button
+ variant="danger"
+ size="sm"
+ isPending={deleteValues.isPending}
+ onClick={handleRemove}
+ >
+ Remove Personal Values
+ </Button>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+
+ <VariableFormDialog
+ scope={AgentVaultVariableScope.Personal}
+ isOpen={newVariableKey !== null}
+ onOpenChange={(open) => {
+ if (!open) setNewVariableKey(null);
+ }}
+ initialKey={newVariableKey ?? undefined}
+ onCreated={(variable) => {
+ if (newVariableRequest.current) newVariableRequest.current.created = variable;
+ }}
+ onCloseAutoFocus={(event) => {
+ const request = newVariableRequest.current;
+ if (!request) return;
+ event.preventDefault();
+ newVariableRequest.current = null;
+ request.resolve(request.created);
+ }}
+ />
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/components/agent-vault/VariableFormDialog.tsx b/frontend/src/components/agent-vault/VariableFormDialog.tsx
index 5bec6928e4..df73d75322 100644
--- a/frontend/src/components/agent-vault/VariableFormDialog.tsx
+++ b/frontend/src/components/agent-vault/VariableFormDialog.tsx
@@ -35,6 +35,7 @@ import {
} from "@app/helpers/agentVaultVariables";
import { useDebounce } from "@app/hooks";
import {
+ AgentVaultVariableScope,
useAgentVaultVariableKeyStatus,
useCreateAgentVaultVariable,
useUpdateAgentVaultVariable
@@ -51,7 +52,11 @@ const NO_CONTROL_CHARS_RE = /^[^\x00-\x1f\x7f]*$/;
// A stored value never comes back, so on edit its field starts empty and empty keeps it. Taken keys are read
// when the form validates, as the lookup of the typed key answers after it was typed.
-const buildSchema = (getTakenKeys: () => ReadonlySet<string>, isValueRequired: boolean) =>
+const buildSchema = (
+ getTakenKeys: () => ReadonlySet<string>,
+ isValueRequired: boolean,
+ isPersonal: boolean
+) =>
z.object({
key: z
.string()
@@ -60,7 +65,11 @@ const buildSchema = (getTakenKeys: () => ReadonlySet<string>, isValueRequired: b
.regex(VARIABLE_KEY_RE, VARIABLE_KEY_MESSAGE)
.refine(
(key) => !getTakenKeys().has(key),
- (key) => ({ message: `A variable named '${key}' already exists.` })
+ (key) => ({
+ message: isPersonal
+ ? `You already have a variable named '${key}'.`
+ : `A variable named '${key}' already exists.`
+ })
),
value: z
.string()
@@ -86,6 +95,8 @@ type Props = {
initialKey?: string;
onCreated?: (variable: TAgentVaultVariable) => void;
onCloseAutoFocus?: (event: Event) => void;
+ /** Personal for one of the caller's own variables, which only their personal values use. */
+ scope?: AgentVaultVariableScope;
};
// Mounted with the dialog's content, which unmounts while the dialog is closed, so every open starts from a fresh
@@ -95,8 +106,10 @@ const VariableForm = ({
onOpenChange,
variable,
initialKey,
- onCreated
+ onCreated,
+ scope = AgentVaultVariableScope.Shared
}: Omit<Props, "onCloseAutoFocus">) => {
+ const isPersonal = scope === AgentVaultVariableScope.Personal;
const createVariable = useCreateAgentVaultVariable();
const updateVariable = useUpdateAgentVaultVariable();
const isUpdate = Boolean(variable);
@@ -104,7 +117,10 @@ const VariableForm = ({
const [isValueVisible, setIsValueVisible] = useState(false);
const takenKeysRef = useRef<ReadonlySet<string>>(new Set());
- const schema = useMemo(() => buildSchema(() => takenKeysRef.current, !variable), [variable]);
+ const schema = useMemo(
+ () => buildSchema(() => takenKeysRef.current, !variable, isPersonal),
+ [variable, isPersonal]
+ );
const {
control,
@@ -134,7 +150,8 @@ const VariableForm = ({
? key
: null;
const { existing } = useAgentVaultVariableKeyStatus(lookupKey ? [lookupKey] : [], {
- isCached: false
+ isCached: false,
+ scope
});
takenKeysRef.current = existing;
// Re-checked when the answer flags the key, and when a key that was flagged is changed, so the message comes
@@ -177,6 +194,7 @@ const VariableForm = ({
createNotification({ text: `Variable "${data.key}" updated`, type: "success" });
} else {
const created = await createVariable.mutateAsync({
+ scope,
key: data.key,
value: data.value
});
@@ -191,7 +209,8 @@ const VariableForm = ({
: undefined;
if (
serverResponse?.error === ApiErrorTypes.BadRequestError &&
- serverResponse.message.endsWith("already exists.")
+ (serverResponse.message.endsWith("already exists.") ||
+ serverResponse.message.startsWith("You already have a variable named"))
) {
setError("key", { type: TAKEN_KEY_ERROR_TYPE, message: serverResponse.message });
}
@@ -201,9 +220,13 @@ const VariableForm = ({
return (
<>
<DialogHeader>
- <DialogTitle>{isUpdate ? "Edit Variable" : "Add Variable"}</DialogTitle>
+ <DialogTitle>
+ {isUpdate ? "Edit" : "Add"} {isPersonal ? "Personal" : "Shared"} Variable
+ </DialogTitle>
<DialogDescription>
- Store a value once and use it from any service in any access bundle.
+ {isPersonal
+ ? "Store a value once and reuse it for any service that asks you for a value. Only you can read it."
+ : "Store a value once and use it from any service in any access bundle."}
</DialogDescription>
</DialogHeader>
@@ -234,7 +257,7 @@ const VariableForm = ({
</>
) : (
<>
- Services use it as{" "}
+ {isPersonal ? "Your personal values use" : "Services use"} it as{" "}
<code className="font-mono">{toVariableReference(key || "KEY")}</code>.
</>
)}
@@ -288,7 +311,7 @@ const VariableForm = ({
isPending={isSubmitting}
isDisabled={isUpdate && !isDirty}
>
- {isUpdate ? "Save" : "Add Variable"}
+ {isUpdate ? "Save" : `Add ${isPersonal ? "Personal" : "Shared"} Variable`}
</Button>
</DialogFooter>
</form>
diff --git a/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx b/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx
index ca76823da1..d103c091c5 100644
--- a/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx
+++ b/frontend/src/components/agent-vault/service-sheet/CredentialFields.tsx
@@ -1,34 +1,59 @@
import { useEffect, useId, useLayoutEffect, useRef, useState } from "react";
import { Controller, ControllerRenderProps, useFormContext } from "react-hook-form";
-import { EyeIcon, EyeOffIcon, XIcon } from "lucide-react";
+import {
+ ChevronDownIcon,
+ ExternalLinkIcon,
+ EyeIcon,
+ EyeOffIcon,
+ InfoIcon,
+ LockIcon,
+ XIcon
+} from "lucide-react";
import {
Alert,
AlertDescription,
AlertTitle,
+ ButtonGroup,
Field,
FieldContent,
FieldDescription,
FieldError,
FieldLabel,
+ HoverCard,
+ HoverCardContent,
+ HoverCardTrigger,
+ IconButton,
Input,
InputGroup,
InputGroupAddon,
InputGroupButton,
InputGroupInput,
+ Label,
Select,
SelectContent,
SelectItem,
SelectTrigger,
- SelectValue
+ SelectValue,
+ Toggle
} from "@app/components/v3";
import { cn } from "@app/components/v3/utils";
import { isVariableReferenceOnly } from "@app/helpers/agentVaultVariables";
-import { AgentVaultCredentialType } from "@app/hooks/api/agentVault";
+import {
+ AgentVaultCredentialType,
+ AgentVaultVariableReferenceField,
+ TAgentVaultMemberProvidedField
+} from "@app/hooks/api/agentVault";
+import { AgentVaultDocsUrls } from "@app/pages/agent-vault/agent-vault-docs-urls";
import { ReferenceHighlights } from "./ReferenceHighlights";
import { SendsPreview } from "./SendsPreview";
-import { CREDENTIAL_LABELS, TServiceForm, UNCHANGED_SECRET } from "./serviceSchema";
+import {
+ CREDENTIAL_LABELS,
+ FORM_FIELD_OF_CREDENTIAL_FIELD,
+ TServiceForm,
+ UNCHANGED_SECRET
+} from "./serviceSchema";
import { useServiceVariables } from "./ServiceVariablesContext";
import { VariableKeyChips } from "./VariableChips";
import { useVariableAutocomplete, VariableSuggestions } from "./VariableSuggestions";
@@ -51,7 +76,8 @@ export const SecretInput = <TName extends SecretName>({
isUntouched,
hasStoredSecret,
canBeCleared,
- storedKeys
+ storedKeys,
+ canInsertVariable
}: {
field: ControllerRenderProps<TServiceForm, TName>;
label: string;
@@ -67,6 +93,8 @@ export const SecretInput = <TName extends SecretName>({
canBeCleared: boolean;
/** The keys of the variables the stored value uses, listed under the field while that value is kept. */
storedKeys?: string[];
+ /** Joins a chevron button to the input that opens the variable list, for readers who would not know to type {{. */
+ canInsertVariable?: boolean;
}) => {
const { setFocus } = useFormContext<TServiceForm>();
const [isVisible, setIsVisible] = useState(false);
@@ -122,98 +150,111 @@ export const SecretInput = <TName extends SecretName>({
syncOverlay();
});
+ const showVariables = () => {
+ inputRef.current?.focus();
+ autocomplete.openPicker();
+ };
+
const lowerLabel = label.toLowerCase();
const isClearable = canBeCleared && hasStoredSecret;
return (
<>
<VariableSuggestions autocomplete={autocomplete}>
- <InputGroup>
- <div className="relative flex min-w-0 flex-1 items-center self-stretch">
- {isHighlighted && <ReferenceHighlights value={value} overlayRef={overlayRef} />}
- <InputGroupInput
- {...field}
- ref={(element) => {
- field.ref(element);
- inputRef.current = element;
- }}
- aria-label={ariaLabel}
- aria-describedby={hasStoredKeys && isStoredValueKept ? descriptionId : undefined}
- role="combobox"
- aria-autocomplete="list"
- aria-expanded={autocomplete.isOpen}
- aria-controls={autocomplete.isOpen ? autocomplete.listId : undefined}
- aria-activedescendant={autocomplete.activeOptionId}
- // Not type="password": that opens the browser's and password managers' autofill menus over
- // the variable list, so the field is masked in CSS and each manager is told to skip it.
- className={cn(
- !isShown && "[-webkit-text-security:disc]",
- isHighlighted && "text-transparent caret-foreground"
- )}
- autoComplete="off"
- autoCorrect="off"
- autoCapitalize="off"
- spellCheck={false}
- data-form-type="other"
- data-1p-ignore
- data-lpignore="true"
- data-bwignore
- onChange={(event) => {
- setIsCleared(false);
- // An emptied field masks again, since what is typed next may be a real secret.
- if (!event.target.value) setIsVisible(false);
- field.onChange(event);
- autocomplete.refresh();
- }}
- onKeyDown={autocomplete.onKeyDown}
- onKeyUp={(event) => {
- if (!SUGGESTION_KEYS.has(event.key)) autocomplete.refresh();
- }}
- onClick={autocomplete.refresh}
- onSelect={syncOverlay}
- onScroll={syncOverlay}
- onFocus={() => {
- if (isUntouched) field.onChange("");
- }}
- // Empty reads the same whether the secret was meant to go or the field was only clicked into,
- // so the clear button is made the one way to say it and passing through loses nothing.
- onBlur={() => {
- autocomplete.close();
- if (hasStoredSecret && !field.value && !isCleared) field.onChange(UNCHANGED_SECRET);
- field.onBlur();
- }}
- placeholder={placeholder}
- isError={isError}
- />
- </div>
- {(isClearable || !isUntouched) && (
- <InputGroupAddon align="inline-end">
- {isClearable && (
- <InputGroupButton
- isDisabled={isCleared}
- aria-label={`Clear ${lowerLabel}`}
- onClick={() => {
- setIsCleared(true);
- field.onChange("");
- setFocus(field.name);
- }}
- >
- <XIcon />
- </InputGroupButton>
- )}
- {/* A stored credential is never returned, so until it is replaced there is nothing to reveal. */}
- {!isUntouched && (
- <InputGroupButton
- isDisabled={!field.value || isReferenceOnly}
- aria-label={`${isVisible ? "Hide" : "Show"} ${lowerLabel}`}
- onClick={() => setIsVisible((prev) => !prev)}
- >
- {isVisible ? <EyeOffIcon /> : <EyeIcon />}
- </InputGroupButton>
- )}
- </InputGroupAddon>
+ <ButtonGroup className="w-full">
+ <InputGroup className="flex-1">
+ <div className="relative flex min-w-0 flex-1 items-center self-stretch">
+ {isHighlighted && <ReferenceHighlights value={value} overlayRef={overlayRef} />}
+ <InputGroupInput
+ {...field}
+ ref={(element) => {
+ field.ref(element);
+ inputRef.current = element;
+ }}
+ aria-label={ariaLabel}
+ aria-describedby={hasStoredKeys && isStoredValueKept ? descriptionId : undefined}
+ role="combobox"
+ aria-autocomplete="list"
+ aria-expanded={autocomplete.isOpen}
+ aria-controls={autocomplete.isOpen ? autocomplete.listId : undefined}
+ aria-activedescendant={autocomplete.activeOptionId}
+ // Not type="password": that opens the browser's and password managers' autofill menus over
+ // the variable list, so the field is masked in CSS and each manager is told to skip it.
+ className={cn(
+ !isShown && "[-webkit-text-security:disc]",
+ isHighlighted && "text-transparent caret-foreground"
+ )}
+ autoComplete="off"
+ autoCorrect="off"
+ autoCapitalize="off"
+ spellCheck={false}
+ data-form-type="other"
+ data-1p-ignore
+ data-lpignore="true"
+ data-bwignore
+ onChange={(event) => {
+ setIsCleared(false);
+ // An emptied field masks again, since what is typed next may be a real secret.
+ if (!event.target.value) setIsVisible(false);
+ field.onChange(event);
+ autocomplete.refresh();
+ }}
+ onKeyDown={autocomplete.onKeyDown}
+ onKeyUp={(event) => {
+ if (!SUGGESTION_KEYS.has(event.key)) autocomplete.refresh();
+ }}
+ onClick={autocomplete.refresh}
+ onSelect={syncOverlay}
+ onScroll={syncOverlay}
+ onFocus={() => {
+ if (isUntouched) field.onChange("");
+ }}
+ // Empty reads the same whether the secret was meant to go or the field was only clicked into,
+ // so the clear button is made the one way to say it and passing through loses nothing.
+ onBlur={() => {
+ autocomplete.close();
+ if (hasStoredSecret && !field.value && !isCleared)
+ field.onChange(UNCHANGED_SECRET);
+ field.onBlur();
+ }}
+ placeholder={placeholder}
+ isError={isError}
+ />
+ </div>
+ {(isClearable || !isUntouched) && (
+ <InputGroupAddon align="inline-end">
+ {isClearable && (
+ <InputGroupButton
+ isDisabled={isCleared}
+ aria-label={`Clear ${lowerLabel}`}
+ onClick={() => {
+ setIsCleared(true);
+ field.onChange("");
+ setFocus(field.name);
+ }}
+ >
+ <XIcon />
+ </InputGroupButton>
+ )}
+ {/* A stored credential is never returned, so until it is replaced there is nothing to reveal. */}
+ {!isUntouched && (
+ <InputGroupButton
+ isDisabled={!field.value || isReferenceOnly}
+ aria-label={`${isVisible ? "Hide" : "Show"} ${lowerLabel}`}
+ onClick={() => setIsVisible((prev) => !prev)}
+ >
+ {isVisible ? <EyeOffIcon /> : <EyeIcon />}
+ </InputGroupButton>
+ )}
+ </InputGroupAddon>
+ )}
+ </InputGroup>
+ {canInsertVariable && (
+ <IconButton variant="outline" aria-label="Show variables" onClick={showVariables}>
+ <ChevronDownIcon />
+ </IconButton>
)}
- </InputGroup>
+ </ButtonGroup>
</VariableSuggestions>
{hasStoredKeys && (
<FieldDescription
@@ -229,22 +270,101 @@ export const SecretInput = <TName extends SecretName>({
);
};
+const MEMBER_FIELDS_OF_TYPE: Record<AgentVaultCredentialType, TAgentVaultMemberProvidedField[]> = {
+ [AgentVaultCredentialType.Bearer]: [AgentVaultVariableReferenceField.CredentialValue],
+ [AgentVaultCredentialType.Basic]: [
+ AgentVaultVariableReferenceField.CredentialUsername,
+ AgentVaultVariableReferenceField.CredentialValue
+ ],
+ [AgentVaultCredentialType.Passthrough]: []
+};
+
+const MemberProvidedToggle = ({
+ label,
+ isOn,
+ onChange
+}: {
+ label: string;
+ isOn: boolean;
+ onChange: (isOn: boolean) => void;
+}) => {
+ const id = useId();
+ return (
+ <div className="flex items-center gap-1.5">
+ <HoverCard openDelay={150} closeDelay={150}>
+ <HoverCardTrigger asChild>
+ <InfoIcon
+ aria-label={`About member-provided ${label.toLowerCase()}s`}
+ className="size-3.5 text-muted"
+ />
+ </HoverCardTrigger>
+ <HoverCardContent className="w-80 text-xs">
+ <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>
+ <li>
+ On: each member sets their own from the access bundle page, and a session uses the{" "}
+ {label.toLowerCase()} of whoever started it.
+ </li>
+ </ul>
+ <a
+ href={AgentVaultDocsUrls.memberProvidedValues}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="mt-2 inline-flex items-center gap-1 underline underline-offset-2 hover:text-foreground"
+ >
+ Learn more
+ <ExternalLinkIcon className="size-3" />
+ </a>
+ </HoverCardContent>
+ </HoverCard>
+ <Label htmlFor={id} className="text-xs font-normal text-muted">
+ Member provided
+ </Label>
+ <Toggle id={id} size="sm" variant="av" checked={isOn} onCheckedChange={onChange} />
+ </div>
+ );
+};
+
+const MemberProvidedInput = ({ label }: { label: string }) => (
+ <InputGroup>
+ <InputGroupAddon>
+ <LockIcon />
+ </InputGroupAddon>
+ <InputGroupInput
+ disabled
+ aria-label={`${label}, set by each member`}
+ placeholder="Member provided"
+ />
+ </InputGroup>
+);
+
type Props = {
storedType?: AgentVaultCredentialType;
+ /** The fields that were member-provided when the sheet opened, which have no stored value behind them. */
+ storedMemberFields?: TAgentVaultMemberProvidedField[];
};
-export const CredentialFields = ({ storedType }: Props) => {
- const { control, watch, setValue } = useFormContext<TServiceForm>();
+export const CredentialFields = ({ storedType, storedMemberFields = [] }: Props) => {
+ const { control, watch, setValue, clearErrors } = useFormContext<TServiceForm>();
const { storedKeys } = useServiceVariables();
const credentialType = watch("credentialType");
const secret = watch("secret");
const username = watch("username");
+ const memberProvidedFields = watch("memberProvidedFields");
const isBasic = credentialType === AgentVaultCredentialType.Basic;
const isUntouched = secret === UNCHANGED_SECRET;
const isUsernameUntouched = username === UNCHANGED_SECRET;
// A stored secret belongs to the type it was saved under, so switching type leaves nothing behind it.
const hasStoredSecret = Boolean(storedType) && credentialType === storedType;
+ // Nor is anything stored for a field each member used to set.
+ const hasStoredValue = (field: TAgentVaultMemberProvidedField) =>
+ hasStoredSecret && !storedMemberFields.includes(field);
+ const isMemberProvided = (field: TAgentVaultMemberProvidedField) =>
+ memberProvidedFields.includes(field);
+ // A bearer token and a basic password are both credential-value.
+ const secretCredentialField = AgentVaultVariableReferenceField.CredentialValue;
useEffect(() => {
if (!storedType || credentialType === storedType) return;
@@ -252,26 +372,66 @@ export const CredentialFields = ({ storedType }: Props) => {
if (isUsernameUntouched) setValue("username", "");
}, [isUntouched, isUsernameUntouched, credentialType, storedType, setValue]);
+ // Which fields a member can set depends on the type, so a switch drops the ones the new type lacks.
+ useEffect(() => {
+ const valid = memberProvidedFields.filter((field) =>
+ MEMBER_FIELDS_OF_TYPE[credentialType].includes(field)
+ );
+ if (valid.length !== memberProvidedFields.length) setValue("memberProvidedFields", valid);
+ }, [credentialType, memberProvidedFields, 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];
+ setValue(
+ "memberProvidedFields",
+ isOn
+ ? [...memberProvidedFields, field]
+ : memberProvidedFields.filter((existing) => existing !== field),
+ { shouldDirty: true }
+ );
+ setValue(formField, !isOn && hasStoredValue(field) ? UNCHANGED_SECRET : "", {
+ shouldDirty: true
+ });
+ clearErrors([formField, "username"]);
+ };
+
+ const fieldLabel = (label: string, field: TAgentVaultMemberProvidedField) => (
+ <div className="flex items-center justify-between gap-2">
+ <FieldLabel>{label}</FieldLabel>
+ <MemberProvidedToggle
+ label={label}
+ isOn={isMemberProvided(field)}
+ onChange={(isOn) => setMemberProvided(field, isOn)}
+ />
+ </div>
+ );
+
+ const secretLabel = isBasic ? "Password" : "Token";
const secretField = (
<Controller
control={control}
name="secret"
render={({ field, fieldState }) => (
<Field className="flex-1">
- <FieldLabel>{isBasic ? "Password" : "Token"}</FieldLabel>
+ {fieldLabel(secretLabel, secretCredentialField)}
<FieldContent>
- <SecretInput
- field={field}
- label={isBasic ? "Password" : "Token"}
- placeholder={
- isBasic ? "Enter the password, or type {{" : "Enter the token, or type {{"
- }
- isError={Boolean(fieldState.error)}
- isUntouched={isUntouched}
- hasStoredSecret={hasStoredSecret}
- canBeCleared={isBasic}
- storedKeys={hasStoredSecret ? storedKeys.secret : undefined}
- />
+ {isMemberProvided(secretCredentialField) ? (
+ <MemberProvidedInput label={secretLabel} />
+ ) : (
+ <SecretInput
+ field={field}
+ label={secretLabel}
+ placeholder={
+ isBasic ? "Enter the password, or type {{" : "Enter the token, or type {{"
+ }
+ isError={Boolean(fieldState.error)}
+ isUntouched={isUntouched}
+ hasStoredSecret={hasStoredValue(secretCredentialField)}
+ canBeCleared={isBasic}
+ storedKeys={hasStoredValue(secretCredentialField) ? storedKeys.secret : undefined}
+ />
+ )}
<FieldError>{fieldState.error?.message}</FieldError>
</FieldContent>
</Field>
@@ -348,18 +508,28 @@ export const CredentialFields = ({ storedType }: Props) => {
name="username"
render={({ field, fieldState }) => (
<Field className="flex-1">
- <FieldLabel>Username</FieldLabel>
+ {fieldLabel("Username", AgentVaultVariableReferenceField.CredentialUsername)}
<FieldContent>
- <SecretInput
- field={field}
- label="Username"
- placeholder="Enter the username, or type {{"
- isError={Boolean(fieldState.error)}
- isUntouched={isUsernameUntouched}
- hasStoredSecret={hasStoredSecret}
- canBeCleared
- storedKeys={hasStoredSecret ? storedKeys.username : undefined}
- />
+ {isMemberProvided(AgentVaultVariableReferenceField.CredentialUsername) ? (
+ <MemberProvidedInput label="Username" />
+ ) : (
+ <SecretInput
+ field={field}
+ label="Username"
+ placeholder="Enter the username, or type {{"
+ isError={Boolean(fieldState.error)}
+ isUntouched={isUsernameUntouched}
+ hasStoredSecret={hasStoredValue(
+ AgentVaultVariableReferenceField.CredentialUsername
+ )}
+ canBeCleared
+ storedKeys={
+ hasStoredValue(AgentVaultVariableReferenceField.CredentialUsername)
+ ? storedKeys.username
+ : undefined
+ }
+ />
+ )}
<FieldError>{fieldState.error?.message}</FieldError>
</FieldContent>
</Field>
diff --git a/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx b/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx
index e889b61ef6..23dc8ff5ea 100644
--- a/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx
+++ b/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx
@@ -8,7 +8,11 @@ import {
DetailLabel,
DetailValue
} from "@app/components/v3";
-import { AgentVaultCredentialType } from "@app/hooks/api/agentVault";
+import {
+ AgentVaultCredentialType,
+ AgentVaultVariableReferenceField,
+ TAgentVaultMemberProvidedField
+} from "@app/hooks/api/agentVault";
import {
CREDENTIAL_LABELS,
@@ -24,11 +28,15 @@ const credentialPreview = (form: {
credentialType: AgentVaultCredentialType;
headerName?: string;
headerPrefix?: string;
+ memberProvidedFields: TAgentVaultMemberProvidedField[];
}): string | null => {
if (form.credentialType === AgentVaultCredentialType.Passthrough) return null;
if (form.credentialType === AgentVaultCredentialType.Basic) return `Authorization: Basic ${MASK}`;
const prefix = form.headerPrefix ? `${form.headerPrefix} ` : "";
- return `${form.headerName || "Authorization"}: ${prefix}${MASK}`;
+ const value = form.memberProvidedFields.includes(AgentVaultVariableReferenceField.CredentialValue)
+ ? "<member value>"
+ : MASK;
+ return `${form.headerName || "Authorization"}: ${prefix}${value}`;
};
const alignColumns = (rows: string[][]) => {
@@ -69,7 +77,12 @@ export const ReviewFields = ({ isUpdate }: Props) => {
: ""
]);
- const outcome = (value: string | undefined, canClear: boolean) => {
+ const outcome = (
+ value: string | undefined,
+ canClear: boolean,
+ field: TAgentVaultMemberProvidedField
+ ) => {
+ if (form.memberProvidedFields.includes(field)) return "Set by each member";
if (!isUpdate) return value ? "Set" : "None";
if (value === UNCHANGED_SECRET) return "Unchanged";
if (value) return "Replaced";
@@ -120,13 +133,17 @@ export const ReviewFields = ({ isUpdate }: Props) => {
{isBasic && (
<Detail>
<DetailLabel>Username</DetailLabel>
- <DetailValue>{outcome(form.username, true)}</DetailValue>
+ <DetailValue>
+ {outcome(form.username, true, AgentVaultVariableReferenceField.CredentialUsername)}
+ </DetailValue>
</Detail>
)}
{form.credentialType !== AgentVaultCredentialType.Passthrough && (
<Detail>
<DetailLabel>{secretLabel}</DetailLabel>
- <DetailValue>{outcome(form.secret, isBasic)}</DetailValue>
+ <DetailValue>
+ {outcome(form.secret, isBasic, AgentVaultVariableReferenceField.CredentialValue)}
+ </DetailValue>
</Detail>
)}
</div>
diff --git a/frontend/src/components/agent-vault/service-sheet/SendsPreview.tsx b/frontend/src/components/agent-vault/service-sheet/SendsPreview.tsx
index e3a77b0976..43420e16ba 100644
--- a/frontend/src/components/agent-vault/service-sheet/SendsPreview.tsx
+++ b/frontend/src/components/agent-vault/service-sheet/SendsPreview.tsx
@@ -2,7 +2,11 @@ import { ReactNode } from "react";
import { useFormContext, useWatch } from "react-hook-form";
import { splitVariableReferences } from "@app/helpers/agentVaultVariables";
-import { AgentVaultCredentialType } from "@app/hooks/api/agentVault";
+import {
+ AgentVaultCredentialType,
+ AgentVaultVariableReferenceField,
+ TAgentVaultMemberProvidedField
+} from "@app/hooks/api/agentVault";
import { TServiceForm, UNCHANGED_SECRET } from "./serviceSchema";
import { useMissingVariableKeys } from "./ServiceVariablesContext";
@@ -12,9 +16,18 @@ const MASK = "•".repeat(8);
// A reference holds no secret, so it is spelled out. Literal text is masked at a fixed length, which
// says nothing about the secret's own.
-const PreviewValue = ({ value, placeholder }: { value?: string; placeholder: string }) => {
+const PreviewValue = ({
+ value,
+ placeholder,
+ isMemberProvided
+}: {
+ value?: string;
+ placeholder: string;
+ isMemberProvided?: boolean;
+}) => {
const missingKeys = useMissingVariableKeys();
+ if (isMemberProvided) return <span className="text-muted">&lt;member value&gt;</span>;
if (!value) return <span className="text-muted">{placeholder}</span>;
if (value === UNCHANGED_SECRET) return <span>{MASK}</span>;
@@ -39,10 +52,28 @@ const PreviewValue = ({ value, placeholder }: { value?: string; placeholder: str
export const SendsPreview = () => {
const { control } = useFormContext<TServiceForm>();
- const [credentialType, headerName, headerPrefix, username, secret, customHeaders] = useWatch({
+ const [
+ credentialType,
+ headerName,
+ headerPrefix,
+ username,
+ secret,
+ memberProvidedFields,
+ customHeaders
+ ] = useWatch({
control,
- name: ["credentialType", "headerName", "headerPrefix", "username", "secret", "customHeaders"]
+ name: [
+ "credentialType",
+ "headerName",
+ "headerPrefix",
+ "username",
+ "secret",
+ "memberProvidedFields",
+ "customHeaders"
+ ]
});
+ const isMemberProvided = (field: TAgentVaultMemberProvidedField) =>
+ memberProvidedFields.includes(field);
const lines: { id: string; content: ReactNode }[] = [];
@@ -52,7 +83,11 @@ export const SendsPreview = () => {
content: (
<>
{headerName || "Authorization"}: {headerPrefix ? `${headerPrefix} ` : ""}
- <PreviewValue value={secret} placeholder="<token>" />
+ <PreviewValue
+ value={secret}
+ placeholder="<token>"
+ isMemberProvided={isMemberProvided(AgentVaultVariableReferenceField.CredentialValue)}
+ />
</>
)
});
@@ -64,8 +99,18 @@ export const SendsPreview = () => {
content: (
<>
Authorization: Basic base64(
- <PreviewValue value={username} placeholder="<username>" />:
- <PreviewValue value={secret} placeholder="<password>" />)
+ <PreviewValue
+ value={username}
+ placeholder="<username>"
+ isMemberProvided={isMemberProvided(AgentVaultVariableReferenceField.CredentialUsername)}
+ />
+ :
+ <PreviewValue
+ value={secret}
+ placeholder="<password>"
+ isMemberProvided={isMemberProvided(AgentVaultVariableReferenceField.CredentialValue)}
+ />
+ )
</>
)
});
diff --git a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx
index 20afa08ac4..703967b67b 100644
--- a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx
+++ b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx
@@ -27,6 +27,7 @@ import { useDebounce, useDiscardChangesGuard, useWizardSteps } from "@app/hooks"
import {
AgentVaultCredentialType,
AgentVaultVariableReferenceField,
+ TAgentVaultMemberProvidedField,
useAgentVaultVariableKeyStatus,
useCreateAgentVaultService,
useUpdateAgentVaultService
@@ -51,6 +52,7 @@ import {
isAllMethods,
SERVICE_STEP_FIELDS,
ServiceStep,
+ storedMemberFields,
TServiceForm,
UNCHANGED_SECRET
} from "./serviceSchema";
@@ -72,6 +74,7 @@ const BLANK_SERVICE_FORM: TServiceForm = {
headerPrefix: "Bearer",
username: "",
secret: "",
+ memberProvidedFields: [],
methods: [...HTTP_METHODS],
pathPrefixes: [],
customHeaders: [],
@@ -295,6 +298,10 @@ export const ServiceSheet = ({
if (service) {
const { credential } = service;
+ const memberProvidedFields = storedMemberFields(service);
+ // A member-provided field has no stored value, so it starts empty rather than as "unchanged".
+ const storedValue = (field: TAgentVaultMemberProvidedField) =>
+ memberProvidedFields.includes(field) ? "" : UNCHANGED_SECRET;
reset({
...BLANK_SERVICE_FORM,
name: service.name,
@@ -309,8 +316,15 @@ export const ServiceSheet = ({
: "Authorization",
headerPrefix:
credential.type === AgentVaultCredentialType.Bearer ? credential.headerPrefix : "Bearer",
- username: credential.type === AgentVaultCredentialType.Basic ? UNCHANGED_SECRET : undefined,
- secret: credential.type === AgentVaultCredentialType.Passthrough ? "" : UNCHANGED_SECRET,
+ username:
+ credential.type === AgentVaultCredentialType.Basic
+ ? storedValue(AgentVaultVariableReferenceField.CredentialUsername)
+ : undefined,
+ secret: (() => {
+ if (credential.type === AgentVaultCredentialType.Passthrough) return "";
+ return storedValue(AgentVaultVariableReferenceField.CredentialValue);
+ })(),
+ memberProvidedFields,
methods: service.allowedMethods ?? [...HTTP_METHODS],
pathPrefixes: service.allowedPathPrefixes ?? [],
// The stored values never come back, so each row carries the sentinel until it is retyped.
@@ -366,26 +380,52 @@ export const ServiceSheet = ({
setStep(0);
});
+ const memberFieldsOf = (data: TServiceForm) => {
+ const isMemberProvided = (field: TAgentVaultMemberProvidedField) =>
+ data.memberProvidedFields.includes(field);
+ return {
+ bearer: isMemberProvided(AgentVaultVariableReferenceField.CredentialValue)
+ ? [AgentVaultVariableReferenceField.CredentialValue as const]
+ : [],
+ basic: (
+ [
+ AgentVaultVariableReferenceField.CredentialUsername,
+ AgentVaultVariableReferenceField.CredentialValue
+ ] as TAgentVaultMemberProvidedField[]
+ ).filter(isMemberProvided),
+ isMemberProvided
+ };
+ };
+
+ // A member-provided field is sent without a value: each member sets their own.
const buildCredential = (data: TServiceForm) => {
+ const { bearer, basic, isMemberProvided } = memberFieldsOf(data);
if (data.credentialType === AgentVaultCredentialType.Passthrough) {
return { type: AgentVaultCredentialType.Passthrough as const };
}
if (data.credentialType === AgentVaultCredentialType.Basic) {
return {
type: AgentVaultCredentialType.Basic as const,
- username: data.username ?? "",
- password: data.secret ?? ""
+ username: isMemberProvided(AgentVaultVariableReferenceField.CredentialUsername)
+ ? undefined
+ : (data.username ?? ""),
+ password: isMemberProvided(AgentVaultVariableReferenceField.CredentialValue)
+ ? undefined
+ : (data.secret ?? ""),
+ memberProvidedFields: basic
};
}
return {
type: AgentVaultCredentialType.Bearer as const,
headerName: data.headerName || undefined,
headerPrefix: data.headerPrefix ?? "",
- value: data.secret ?? ""
+ value: bearer.length ? undefined : (data.secret ?? ""),
+ memberProvidedFields: bearer
};
};
const buildCredentialPatch = (data: TServiceForm) => {
+ const { bearer, basic, isMemberProvided } = memberFieldsOf(data);
if (data.credentialType === AgentVaultCredentialType.Passthrough) {
return { type: AgentVaultCredentialType.Passthrough as const };
}
@@ -394,15 +434,24 @@ export const ServiceSheet = ({
if (data.credentialType === AgentVaultCredentialType.Basic) {
return {
type: AgentVaultCredentialType.Basic as const,
- username: data.username === UNCHANGED_SECRET ? undefined : (data.username ?? ""),
- password: untouched ? undefined : (data.secret ?? "")
+ username:
+ isMemberProvided(AgentVaultVariableReferenceField.CredentialUsername) ||
+ data.username === UNCHANGED_SECRET
+ ? undefined
+ : (data.username ?? ""),
+ password:
+ isMemberProvided(AgentVaultVariableReferenceField.CredentialValue) || untouched
+ ? undefined
+ : (data.secret ?? ""),
+ memberProvidedFields: basic
};
}
return {
type: AgentVaultCredentialType.Bearer as const,
headerName: data.headerName || "Authorization",
headerPrefix: data.headerPrefix ?? "",
- value: untouched || !data.secret ? undefined : data.secret
+ value: bearer.length || untouched || !data.secret ? undefined : data.secret,
+ memberProvidedFields: bearer
};
};
@@ -645,7 +694,10 @@ export const ServiceSheet = ({
{current.step === ServiceStep.Credential && (
<ServiceVariablesContext.Provider value={serviceVariables}>
<div className="flex flex-col gap-5">
- <CredentialFields storedType={service?.credential.type} />
+ <CredentialFields
+ storedType={service?.credential.type}
+ storedMemberFields={storedMemberFields(service)}
+ />
<TransformationsFields openItem={openItem} onOpenChange={setOpenItem} />
</div>
</ServiceVariablesContext.Provider>
diff --git a/frontend/src/components/agent-vault/service-sheet/ServiceVariablesContext.ts b/frontend/src/components/agent-vault/service-sheet/ServiceVariablesContext.ts
index dcb2267aa4..29983022a2 100644
--- a/frontend/src/components/agent-vault/service-sheet/ServiceVariablesContext.ts
+++ b/frontend/src/components/agent-vault/service-sheet/ServiceVariablesContext.ts
@@ -14,6 +14,12 @@ type TServiceVariables = {
};
/** Opens the new-variable dialog on top of the sheet. Resolves to null if it is dismissed. */
requestVariable: (key: string) => Promise<TAgentVaultVariable | null>;
+ /**
+ * Set when the fields reference the caller's own variables instead of the shared ones. There are few enough to hold
+ * whole, so the list is filtered here rather than searched on the server. Undefined while it loads.
+ */
+ localVariables?: TAgentVaultVariable[];
+ isLocal?: boolean;
};
export const NO_STORED_KEYS: TServiceVariables["storedKeys"] = {
diff --git a/frontend/src/components/agent-vault/service-sheet/VariableSuggestions.tsx b/frontend/src/components/agent-vault/service-sheet/VariableSuggestions.tsx
index 6a9c975eca..81462d7bc1 100644
--- a/frontend/src/components/agent-vault/service-sheet/VariableSuggestions.tsx
+++ b/frontend/src/components/agent-vault/service-sheet/VariableSuggestions.tsx
@@ -17,12 +17,13 @@ import {
import { useServiceVariables } from "./ServiceVariablesContext";
-type TOpenReference = { start: number; query: string };
+// A picker opened from a button has no reference in the text: a pick replaces the whole value.
+type TOpenReference = { start: number; query: string; isPicker?: boolean };
const SUGGESTION_LIMIT = 50;
type TSuggestion =
- | { type: "variable"; key: string }
+ | { type: "variable"; key: string; usedByCount?: number }
| { type: "create"; key: string; isKeyValid: boolean };
export const useVariableAutocomplete = ({
@@ -33,7 +34,7 @@ export const useVariableAutocomplete = ({
/** The whole new value, and where in it the caret belongs. */
onInsert: (value: string, caret: number) => void;
}) => {
- const { requestVariable } = useServiceVariables();
+ const { requestVariable, localVariables, isLocal } = useServiceVariables();
const [openReference, setOpenReference] = useState<TOpenReference | null>(null);
const query = openReference ? normalizeVariableKey(openReference.query) : "";
const [debouncedQuery] = useDebounce(query, 200);
@@ -41,16 +42,22 @@ export const useVariableAutocomplete = ({
// Searched on the server, so the list never has to hold every variable. The last page stays up while the next
// loads, filtered to the new text, which a longer query only narrows.
- const { data, isPlaceholderData } = useListAgentVaultVariables(
+ const { data: searched, isPlaceholderData } = useListAgentVaultVariables(
{ search: debouncedQuery || undefined, limit: SUGGESTION_LIMIT },
- { enabled: isOpen }
+ { enabled: isOpen && !isLocal }
);
// A search can show only so many, and the exact key may not be among them, so whether to offer to create it is
// asked of that key alone.
const { existing } = useAgentVaultVariableKeyStatus(
- isOpen && VARIABLE_KEY_RE.test(debouncedQuery) ? [debouncedQuery] : [],
- { enabled: isOpen }
+ isOpen && !isLocal && VARIABLE_KEY_RE.test(debouncedQuery) ? [debouncedQuery] : [],
+ { enabled: isOpen && !isLocal }
);
+ const data = useMemo(() => {
+ if (!isLocal) return searched;
+ if (!localVariables) return undefined;
+ const variables = localVariables.filter((variable) => variable.key.includes(debouncedQuery));
+ return { variables, totalCount: variables.length };
+ }, [isLocal, searched, localVariables, debouncedQuery]);
const [activeIndex, setActiveIndex] = useState(0);
// Escape closes the list for the reference being typed, not for the field: it opens again at the next {{.
const dismissedAt = useRef<number | null>(null);
@@ -75,7 +82,12 @@ export const useVariableAutocomplete = ({
])
]
.sort((a, b) => rank(a) - rank(b) || a.localeCompare(b))
- .map((candidate) => ({ type: "variable" as const, key: candidate }));
+ .map((candidate) => ({
+ type: "variable" as const,
+ key: candidate,
+ usedByCount: data.variables.find((variable) => variable.key === candidate)?.usedByServices
+ .length
+ }));
if (!key || keyExists) return matches;
return [...matches, { type: "create", key, isKeyValid: VARIABLE_KEY_RE.test(key) }];
@@ -85,7 +97,10 @@ export const useVariableAutocomplete = ({
// how many it shows and how to narrow it.
const shownCount = suggestions.filter((suggestion) => suggestion.type === "variable").length;
const truncation =
- data && !isPlaceholderData && query === debouncedQuery && data.totalCount > shownCount
+ data &&
+ !(isPlaceholderData && !isLocal) &&
+ query === debouncedQuery &&
+ data.totalCount > shownCount
? { shown: shownCount, total: data.totalCount }
: null;
@@ -111,6 +126,12 @@ export const useVariableAutocomplete = ({
}
};
+ const openPicker = () => {
+ dismissedAt.current = null;
+ setOpenReference({ start: 0, query: "", isPicker: true });
+ setActiveIndex(0);
+ };
+
const dismiss = () => {
dismissedAt.current = openReference?.start ?? null;
close();
@@ -121,6 +142,7 @@ export const useVariableAutocomplete = ({
const surroundings = () => {
const input = inputRef.current;
if (!input || !openReference) return null;
+ if (openReference.isPicker) return { before: "", after: "" };
const reference = findVariableReferenceAtCaret(
input.value,
input.selectionStart ?? input.value.length
@@ -179,6 +201,7 @@ export const useVariableAutocomplete = ({
return {
isOpen,
+ isPicker: Boolean(openReference?.isPicker),
isLoading: isOpen && !data,
truncation,
suggestions,
@@ -188,6 +211,7 @@ export const useVariableAutocomplete = ({
activeOptionId: openReference && suggestions.length ? optionId(activeIndex) : undefined,
optionId,
refresh,
+ openPicker,
close,
dismiss,
choose,
@@ -197,6 +221,11 @@ export const useVariableAutocomplete = ({
type TAutocomplete = ReturnType<typeof useVariableAutocomplete>;
+const usedByLabel = (count: number) => {
+ if (count === 0) return "Not used yet";
+ return `Used by ${count} service${count === 1 ? "" : "s"}`;
+};
+
export const VariableSuggestions = ({
autocomplete,
children
@@ -207,6 +236,7 @@ export const VariableSuggestions = ({
const anchorRef = useRef<HTMLDivElement>(null);
const {
isOpen,
+ isPicker,
isLoading,
truncation,
suggestions,
@@ -237,7 +267,14 @@ export const VariableSuggestions = ({
onClick={() => choose(suggestion)}
>
{suggestion.type === "variable" ? (
- <span className="flex-1 truncate font-mono text-xs">{suggestion.key}</span>
+ <>
+ <span className="flex-1 truncate font-mono text-xs">{suggestion.key}</span>
+ {suggestion.usedByCount !== undefined && (
+ <span className="shrink-0 text-xs text-muted">
+ {usedByLabel(suggestion.usedByCount)}
+ </span>
+ )}
+ </>
) : (
<>
<PlusIcon className="size-3.5 shrink-0 text-muted" />
@@ -312,6 +349,16 @@ export const VariableSuggestions = ({
{isLoading ? "Loading variables..." : "No variables yet. Type a key to create one."}
</p>
)}
+ {/* Only when the list was opened from the button: someone who typed {{ already knows. */}
+ {isPicker && (
+ <>
+ <div className="-mx-1 my-1 h-px bg-border" />
+ <p className="px-2 py-1.5 text-xs text-muted">
+ Tip: type <code className="font-mono">{"{{"}</code> in the field to insert one
+ inline.
+ </p>
+ </>
+ )}
</PopoverContent>
)}
</Popover>
diff --git a/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts b/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts
index ad89f006c6..1a9d426e53 100644
--- a/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts
+++ b/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts
@@ -6,7 +6,9 @@ import { variableReferenceError } from "@app/helpers/agentVaultVariables";
import {
AgentVaultCredentialType,
AgentVaultHttpMethod,
- AgentVaultSubstitutionSurface
+ AgentVaultSubstitutionSurface,
+ AgentVaultVariableReferenceField,
+ TAgentVaultMemberProvidedField
} from "@app/hooks/api/agentVault";
import { TAgentVaultService } from "@app/hooks/api/agentVault/types";
import { slugSchema } from "@app/lib/schemas";
@@ -24,6 +26,26 @@ export const displayHostPattern = (hostPattern: string) =>
.map((host) => host.trim().replace(/:443$/, ""))
.join(", ");
+/**
+ * The form field that holds each member-provided field's admin value. credential-value is a bearer token or a basic
+ * password, which share the form's `secret`.
+ */
+export const FORM_FIELD_OF_CREDENTIAL_FIELD: Record<
+ TAgentVaultMemberProvidedField,
+ "secret" | "username"
+> = {
+ [AgentVaultVariableReferenceField.CredentialValue]: "secret",
+ [AgentVaultVariableReferenceField.CredentialUsername]: "username"
+};
+
+/** The member-provided fields a service had when the sheet opened. None stand behind a stored value. */
+export const storedMemberFields = (
+ service?: TAgentVaultService | null
+): TAgentVaultMemberProvidedField[] =>
+ service && service.credential.type !== AgentVaultCredentialType.Passthrough
+ ? service.credential.memberProvidedFields
+ : [];
+
export const CREDENTIAL_LABELS: Record<AgentVaultCredentialType, string> = {
[AgentVaultCredentialType.Bearer]: "Bearer",
[AgentVaultCredentialType.Basic]: "Basic Auth",
@@ -98,6 +120,7 @@ export const SERVICE_STEP_FIELDS: Record<ServiceStep, string[]> = {
"headerPrefix",
"username",
"secret",
+ "memberProvidedFields",
"customHeaders",
"substitutions"
],
@@ -133,6 +156,13 @@ export const buildServiceSchema = (
headerPrefix: z.string().trim().max(64).optional(),
username: z.string().trim().max(256).optional(),
secret: z.string().max(8192).optional(),
+ // Each member sets these for themselves, so the form holds no value for them.
+ memberProvidedFields: z.array(
+ z.enum([
+ AgentVaultVariableReferenceField.CredentialValue,
+ AgentVaultVariableReferenceField.CredentialUsername
+ ])
+ ),
methods: z.array(z.nativeEnum(AgentVaultHttpMethod)),
pathPrefixes: z
.array(z.string())
@@ -309,10 +339,19 @@ export const buildServiceSchema = (
if (message) ctx.addIssue({ code: z.ZodIssueCode.custom, path, message });
};
- if (data.credentialType !== AgentVaultCredentialType.Passthrough) {
+ const isMemberProvided = (field: TAgentVaultMemberProvidedField) =>
+ data.memberProvidedFields.includes(field);
+ const isSecretMemberProvided = isMemberProvided(
+ AgentVaultVariableReferenceField.CredentialValue
+ );
+ const isUsernameMemberProvided = isMemberProvided(
+ AgentVaultVariableReferenceField.CredentialUsername
+ );
+
+ if (data.credentialType !== AgentVaultCredentialType.Passthrough && !isSecretMemberProvided) {
addReferenceIssue(data.secret, ["secret"]);
}
- if (data.credentialType === AgentVaultCredentialType.Basic) {
+ if (data.credentialType === AgentVaultCredentialType.Basic && !isUsernameMemberProvided) {
addReferenceIssue(data.username, ["username"]);
}
data.customHeaders.forEach((header, index) =>
@@ -327,14 +366,26 @@ export const buildServiceSchema = (
const isUnchanged = data.secret === UNCHANGED_SECRET;
const typeChanged = Boolean(service) && service?.credential.type !== data.credentialType;
+ // A field each member used to set has nothing stored for the admin to keep.
+ const wasMemberProvided = (field: TAgentVaultMemberProvidedField) =>
+ !typeChanged && storedMemberFields(service).includes(field);
if (data.credentialType === AgentVaultCredentialType.Bearer) {
- if ((!service || typeChanged) && !data.secret) {
+ if (isSecretMemberProvided) return;
+ if (
+ (!service ||
+ typeChanged ||
+ wasMemberProvided(AgentVaultVariableReferenceField.CredentialValue)) &&
+ !data.secret
+ ) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["secret"], message: "Required" });
}
return;
}
+ // A member sends at least one half, so the credential is never empty.
+ if (isSecretMemberProvided || isUsernameMemberProvided) return;
+
const willHaveUsername = data.username === UNCHANGED_SECRET ? true : Boolean(data.username);
const willHavePassword = isUnchanged ? true : Boolean(data.secret);
if (
diff --git a/frontend/src/helpers/agentVaultVariables.ts b/frontend/src/helpers/agentVaultVariables.ts
index 6e482fad84..e7cc7732d9 100644
--- a/frontend/src/helpers/agentVaultVariables.ts
+++ b/frontend/src/helpers/agentVaultVariables.ts
@@ -2,6 +2,7 @@ export const VARIABLE_KEY_MAX_LENGTH = 64;
export const VARIABLE_VALUE_MAX_LENGTH = 8192;
export const MAX_REFERENCES_PER_FIELD = 3;
export const MAX_VARIABLES = 500;
+export const MAX_PERSONAL_VARIABLES = 100;
export const VARIABLE_KEY_RE = /^[A-Z][A-Z0-9_]*$/;
@@ -76,7 +77,8 @@ export const findVariableReferenceAtCaret = (text: string, caret: number) => {
*/
export const variableReferenceError = (
text: string,
- missingKeys?: ReadonlySet<string>
+ missingKeys?: ReadonlySet<string>,
+ { isPersonal = false }: { isPersonal?: boolean } = {}
): string | null => {
const refs = findVariableReferences(text);
@@ -91,7 +93,9 @@ export const variableReferenceError = (
const missing = refs.find((ref) => missingKeys?.has(ref));
if (missing) {
- return `Agent Vault has no variable named '${missing}'. Add it under Variables, or correct the name.`;
+ 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.`;
}
return null;
diff --git a/frontend/src/hooks/api/agentVault/enums.ts b/frontend/src/hooks/api/agentVault/enums.ts
index 75d997b948..f90bab6f4a 100644
--- a/frontend/src/hooks/api/agentVault/enums.ts
+++ b/frontend/src/hooks/api/agentVault/enums.ts
@@ -43,6 +43,12 @@ export enum AgentVaultSessionScope {
All = "all"
}
+/** Shared variables are an admin's, for services; personal ones are the caller's own, for their personal values. */
+export enum AgentVaultVariableScope {
+ Shared = "shared",
+ Personal = "personal"
+}
+
export enum AgentVaultSessionLogDecision {
Brokered = "brokered",
Passthrough = "passthrough",
diff --git a/frontend/src/hooks/api/agentVault/mutations.tsx b/frontend/src/hooks/api/agentVault/mutations.tsx
index e9febb7bc4..d459a7478a 100644
--- a/frontend/src/hooks/api/agentVault/mutations.tsx
+++ b/frontend/src/hooks/api/agentVault/mutations.tsx
@@ -15,6 +15,7 @@ import {
TAgentVaultGrantedMember,
TAgentVaultMemberWriteResult,
TAgentVaultMintedSession,
+ TAgentVaultPersonalValues,
TAgentVaultProxy,
TAgentVaultProxySettingsDTO,
TAgentVaultService,
@@ -25,6 +26,8 @@ import {
TCreateAgentVaultServiceDTO,
TCreateAgentVaultSessionDTO,
TCreateAgentVaultVariableDTO,
+ TDeleteAgentVaultPersonalValuesDTO,
+ TSetAgentVaultPersonalValuesDTO,
TUpdateAgentVaultAccessBundleDTO,
TUpdateAgentVaultMemberRolesDTO,
TUpdateAgentVaultServiceDTO,
@@ -393,7 +396,8 @@ export const useUpdateAgentVaultSessionLogSettings = () => {
});
};
-// A rename changes the keys each service's variableReferences reports, so the bundles refresh too.
+// A rename changes the keys each service's variableReferences, and each personal value's, reports, so those refresh
+// too.
const invalidateVariables = (queryClient: ReturnType<typeof useQueryClient>, orgId: string) =>
Promise.all([
queryClient.invalidateQueries({ queryKey: agentVaultKeys.variables(orgId) }),
@@ -454,3 +458,50 @@ export const useRevealAgentVaultVariableValue = () =>
return data.value;
}
});
+
+// The status shows on the bundle read and the bundle list, and Used By on personal variables follows the references.
+const invalidatePersonalValues = (
+ queryClient: ReturnType<typeof useQueryClient>,
+ orgId: string,
+ accessBundleId: string
+) =>
+ Promise.all([
+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.accessBundle(orgId, accessBundleId) }),
+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.accessBundles(orgId) }),
+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.variables(orgId) })
+ ]);
+
+export const useSetAgentVaultPersonalValues = () => {
+ const { currentOrg } = useOrganization();
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({
+ accessBundleId,
+ serviceId,
+ ...params
+ }: TSetAgentVaultPersonalValuesDTO) => {
+ const { data } = await apiRequest.patch<{ personalValues: TAgentVaultPersonalValues }>(
+ `/api/v1/agent-vault/access-bundles/${accessBundleId}/services/${serviceId}/personal-values`,
+ params
+ );
+ return data.personalValues;
+ },
+ onSuccess: (_, { accessBundleId }) =>
+ invalidatePersonalValues(queryClient, currentOrg.id, accessBundleId)
+ });
+};
+
+export const useDeleteAgentVaultPersonalValues = () => {
+ const { currentOrg } = useOrganization();
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ accessBundleId, serviceId }: TDeleteAgentVaultPersonalValuesDTO) => {
+ const { data } = await apiRequest.delete<{ personalValues: TAgentVaultPersonalValues }>(
+ `/api/v1/agent-vault/access-bundles/${accessBundleId}/services/${serviceId}/personal-values`
+ );
+ return data.personalValues;
+ },
+ onSuccess: (_, { accessBundleId }) =>
+ invalidatePersonalValues(queryClient, currentOrg.id, accessBundleId)
+ });
+};
diff --git a/frontend/src/hooks/api/agentVault/queries.tsx b/frontend/src/hooks/api/agentVault/queries.tsx
index d21cda2c84..b90718ff2b 100644
--- a/frontend/src/hooks/api/agentVault/queries.tsx
+++ b/frontend/src/hooks/api/agentVault/queries.tsx
@@ -6,7 +6,7 @@ import { apiRequest } from "@app/config/request";
import { useOrganization } from "@app/context";
import { VARIABLE_KEY_MAX_LENGTH, VARIABLE_KEY_RE } from "@app/helpers/agentVaultVariables";
-import { AgentVaultMemberType } from "./enums";
+import { AgentVaultMemberType, AgentVaultVariableScope } from "./enums";
import {
createSessionLogChunkCache,
decryptSessionLogPage,
@@ -93,8 +93,8 @@ export const agentVaultKeys = {
variables: (orgId: string) => [...agentVaultKeys.all(orgId), "variables"] as const,
variableList: (orgId: string, params: TListAgentVaultVariablesDTO) =>
[...agentVaultKeys.variables(orgId), "list", params] as const,
- variableKeyStatus: (orgId: string, keys: string[]) =>
- [...agentVaultKeys.variables(orgId), "key-status", keys] as const,
+ variableKeyStatus: (orgId: string, scope: AgentVaultVariableScope, keys: string[]) =>
+ [...agentVaultKeys.variables(orgId), "key-status", scope, keys] as const,
members: (orgId: string) => [...agentVaultKeys.all(orgId), "members"] as const,
memberList: (orgId: string, params?: TListAgentVaultMembersDTO) =>
[...agentVaultKeys.members(orgId), params] as const,
@@ -219,6 +219,11 @@ 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.
+export const useListAgentVaultAccessBundlesRequiringSetup = () =>
+ useListAgentVaultAccessBundles({ requiresSetup: true, limit: 100 });
+
export const useGetAgentVaultAccessBundle = (accessBundleId: string) => {
const { currentOrg } = useOrganization();
@@ -569,18 +574,23 @@ const isPossibleVariableKey = (key: string) =>
// already covered doesn't flicker while the next set loads.
export const useAgentVaultVariableKeyStatus = (
keys: readonly string[],
- { enabled = true, isCached = true }: { enabled?: boolean; isCached?: boolean } = {}
+ {
+ enabled = true,
+ isCached = true,
+ scope = AgentVaultVariableScope.Shared
+ }: { enabled?: boolean; isCached?: boolean; scope?: AgentVaultVariableScope } = {}
) => {
const { currentOrg } = useOrganization();
const possibleKeys = [...new Set(keys.filter(isPossibleVariableKey))].sort();
const { data } = useQuery({
- queryKey: agentVaultKeys.variableKeyStatus(currentOrg.id, possibleKeys),
+ queryKey: agentVaultKeys.variableKeyStatus(currentOrg.id, scope, possibleKeys),
queryFn: async () => {
const found: string[] = [];
for (let i = 0; i < possibleKeys.length; i += KEY_LOOKUP_BATCH_SIZE) {
// eslint-disable-next-line no-await-in-loop
const page = await fetchAgentVaultVariables({
+ scope,
keys: possibleKeys.slice(i, i + KEY_LOOKUP_BATCH_SIZE)
});
found.push(...page.variables.map((variable) => variable.key));
diff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.ts
index 3b3dd5e736..71a191d409 100644
--- a/frontend/src/hooks/api/agentVault/types.ts
+++ b/frontend/src/hooks/api/agentVault/types.ts
@@ -7,34 +7,47 @@ import {
AgentVaultSessionStatus,
AgentVaultSubstitutionSurface,
AgentVaultTrafficPolicy,
- AgentVaultVariableReferenceField
+ AgentVaultVariableReferenceField,
+ AgentVaultVariableScope
} from "./enums";
-export type TAgentVaultCredentialSummary =
- | { type: AgentVaultCredentialType.Bearer; headerName: string; headerPrefix: string }
- | { type: AgentVaultCredentialType.Basic }
- | { type: AgentVaultCredentialType.Passthrough };
+/** A field an admin can leave to each member: a bearer token or basic password, or a basic username. */
+export type TAgentVaultMemberProvidedField =
+ | AgentVaultVariableReferenceField.CredentialValue
+ | AgentVaultVariableReferenceField.CredentialUsername;
-export type TAgentVaultCredentialInput =
+export type TAgentVaultBearerMemberField = AgentVaultVariableReferenceField.CredentialValue;
+export type TAgentVaultBasicMemberField = TAgentVaultMemberProvidedField;
+
+export type TAgentVaultCredentialSummary =
| {
type: AgentVaultCredentialType.Bearer;
- headerName?: string;
- headerPrefix?: string;
- value: string;
+ headerName: string;
+ headerPrefix: string;
+ memberProvidedFields: TAgentVaultBearerMemberField[];
}
- | { type: AgentVaultCredentialType.Basic; username: string; password: string }
+ | { type: AgentVaultCredentialType.Basic; memberProvidedFields: TAgentVaultBasicMemberField[] }
| { type: AgentVaultCredentialType.Passthrough };
-export type TAgentVaultCredentialUpdate =
+// A member-provided field is sent without a value: each member sets their own.
+export type TAgentVaultCredentialInput =
| {
type: AgentVaultCredentialType.Bearer;
headerName?: string;
headerPrefix?: string;
value?: string;
+ memberProvidedFields?: TAgentVaultBearerMemberField[];
+ }
+ | {
+ type: AgentVaultCredentialType.Basic;
+ username?: string;
+ password?: string;
+ memberProvidedFields?: TAgentVaultBasicMemberField[];
}
- | { type: AgentVaultCredentialType.Basic; username?: string; password?: string }
| { type: AgentVaultCredentialType.Passthrough };
+export type TAgentVaultCredentialUpdate = TAgentVaultCredentialInput;
+
export type TAgentVaultCustomHeaderSummary = { id: string; name: string; prefix: string };
export type TAgentVaultSubstitutionSummary = {
@@ -85,6 +98,8 @@ export type TAgentVaultService = {
substitutions: TAgentVaultSubstitutionSummary[];
// Left out for a member, who can't see variables.
variableReferences?: TAgentVaultVariableReference[];
+ // The caller's own values, on the bundle read only. null when the admin sets the whole credential.
+ personalValues?: TAgentVaultPersonalValues | null;
createdAt: string;
updatedAt: string;
};
@@ -136,9 +151,12 @@ export type TListAgentVaultProxiesDTO = {
export type TListAgentVaultAccessBundlesDTO = Omit<TListAgentVaultProxiesDTO, "orderBy"> & {
orderBy?: "name" | "serviceCount" | "createdAt";
+ /** Only the bundles granted to the caller that still require their personal values. */
+ requiresSetup?: boolean;
};
export type TListAgentVaultVariablesDTO = {
+ scope?: AgentVaultVariableScope;
search?: string;
/** Exact keys. A key that doesn't exist is left out of the response. */
keys?: string[];
@@ -189,6 +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.
+ servicesRequiringSetup: string[];
};
export type TAgentVaultAccessBundleDetails = TAgentVaultAccessBundle & {
@@ -417,13 +437,16 @@ export type TAgentVaultVariableUsedByService = {
export type TAgentVaultVariable = {
id: string;
key: string;
- // Every service that references the variable, across all access bundles.
+ scope: AgentVaultVariableScope;
+ // Every service that references the variable, across all access bundles. For a personal variable, the services
+ // whose personal values, as the caller set them, use it.
usedByServices: TAgentVaultVariableUsedByService[];
createdAt: string;
updatedAt: string;
};
export type TCreateAgentVaultVariableDTO = {
+ scope?: AgentVaultVariableScope;
key: string;
value: string;
};
@@ -433,3 +456,22 @@ export type TUpdateAgentVaultVariableDTO = {
key?: string;
value?: string;
};
+
+// The caller's own values for one service, and which of them they have set. Values never come back.
+export type TAgentVaultPersonalValues = {
+ isConfigured: boolean;
+ fields: {
+ field: TAgentVaultMemberProvidedField;
+ isSet: boolean;
+ updatedAt: string | null;
+ variableReferences: { variableId: string; key: string }[];
+ }[];
+};
+
+export type TSetAgentVaultPersonalValuesDTO = {
+ accessBundleId: string;
+ serviceId: string;
+ values: { field: TAgentVaultMemberProvidedField; value: string }[];
+};
+
+export type TDeleteAgentVaultPersonalValuesDTO = { accessBundleId: string; serviceId: string };
diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsx
index 8b01fbd474..da238e331a 100644
--- a/frontend/src/hooks/api/auditLogs/constants.tsx
+++ b/frontend/src/hooks/api/auditLogs/constants.tsx
@@ -482,6 +482,8 @@ export const eventToNameMap: { [K in EventType]: string } = {
[EventType.AGENT_VAULT_VARIABLE_UPDATE]: "Update variable",
[EventType.AGENT_VAULT_VARIABLE_DELETE]: "Delete variable",
[EventType.AGENT_VAULT_VARIABLE_VALUE_VIEW]: "View variable value",
+ [EventType.AGENT_VAULT_PERSONAL_VALUES_SET]: "Set personal values",
+ [EventType.AGENT_VAULT_PERSONAL_VALUES_DELETE]: "Remove personal values",
[EventType.AGENT_VAULT_MEMBER_ADD]: "Add member",
[EventType.AGENT_VAULT_MEMBER_UPDATE]: "Change member role",
[EventType.AGENT_VAULT_MEMBER_REMOVE]: "Remove member",
@@ -563,6 +565,8 @@ export const projectToEventsMap: Partial<Record<ProjectType, EventType[]>> = {
EventType.AGENT_VAULT_VARIABLE_UPDATE,
EventType.AGENT_VAULT_VARIABLE_DELETE,
EventType.AGENT_VAULT_VARIABLE_VALUE_VIEW,
+ EventType.AGENT_VAULT_PERSONAL_VALUES_SET,
+ EventType.AGENT_VAULT_PERSONAL_VALUES_DELETE,
EventType.AGENT_VAULT_MEMBER_ADD,
EventType.AGENT_VAULT_MEMBER_UPDATE,
EventType.AGENT_VAULT_MEMBER_REMOVE,
diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsx
index 0915b412ab..b2fe318fc9 100644
--- a/frontend/src/hooks/api/auditLogs/enums.tsx
+++ b/frontend/src/hooks/api/auditLogs/enums.tsx
@@ -480,6 +480,8 @@ export enum EventType {
AGENT_VAULT_VARIABLE_UPDATE = "agent-vault-variable-update",
AGENT_VAULT_VARIABLE_DELETE = "agent-vault-variable-delete",
AGENT_VAULT_VARIABLE_VALUE_VIEW = "agent-vault-variable-value-view",
+ AGENT_VAULT_PERSONAL_VALUES_SET = "agent-vault-personal-values-set",
+ AGENT_VAULT_PERSONAL_VALUES_DELETE = "agent-vault-personal-values-delete",
AGENT_VAULT_MEMBER_ADD = "agent-vault-member-add",
AGENT_VAULT_MEMBER_UPDATE = "agent-vault-member-update",
AGENT_VAULT_MEMBER_REMOVE = "agent-vault-member-remove",
diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsx b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsx
index ed64de560d..a4f34c68b1 100644
--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsx
+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsx
@@ -14,7 +14,8 @@ import {
} from "@app/helpers/agentVaultSessionLogs";
import {
useGetAgentVaultSessionLogHealth,
- useGetAgentVaultSessionLogSettings
+ useGetAgentVaultSessionLogSettings,
+ useListAgentVaultAccessBundlesRequiringSetup
} from "@app/hooks/api/agentVault";
import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
@@ -28,11 +29,18 @@ export const AgentVaultNav = ({ onSubmenuOpen }: { onSubmenuOpen: (submenu: Subm
const { data: sessionLogSettings } = useGetAgentVaultSessionLogSettings(isAdmin);
const { data: sessionLogHealth } = useGetAgentVaultSessionLogHealth(isAdmin);
const { subscription } = useSubscription();
+ const { data: requiringSetup } = useListAgentVaultAccessBundlesRequiringSetup();
+ const needsSetup = Boolean(requiringSetup?.totalCount);
const accessItems: NavItem[] = [
{ label: "Sessions", icon: IdCard, pathSuffix: "sessions" },
- { label: "Access Bundles", icon: Package, pathSuffix: "access-bundles" },
- { label: "Variables", icon: Braces, pathSuffix: "variables", hidden: !isAdmin }
+ {
+ label: "Access Bundles",
+ icon: Package,
+ pathSuffix: "access-bundles",
+ alertVariant: needsSetup ? "warning" : undefined
+ },
+ { label: "Variables", icon: Braces, pathSuffix: "variables" }
];
const infrastructureItems: NavItem[] = [
diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx
index 9fe5248afe..c4ebeca866 100644
--- a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx
@@ -8,13 +8,18 @@ import {
PackageIcon,
PencilIcon,
TrashIcon,
+ TriangleAlertIcon,
UsersIcon
} from "lucide-react";
import { AccessBundleFormDialog } from "@app/components/agent-vault/AccessBundleFormDialog";
import { ManageAccessSheet } from "@app/components/agent-vault/ManageAccessSheet";
+import { PersonalValuesDialog } from "@app/components/agent-vault/PersonalValuesDialog";
import { ServiceSheet } from "@app/components/agent-vault/service-sheet";
import {
+ Alert,
+ AlertAction,
+ AlertDescription,
Button,
DropdownMenu,
DropdownMenuContent,
@@ -49,6 +54,10 @@ export const AgentVaultAccessBundleDetailPage = () => {
});
const { data: accessBundle, isPending } = useGetAgentVaultAccessBundle(accessBundleId);
+ const [serviceToSetUp, setServiceToSetUp] = useState<TAgentVaultService | null>(null);
+ const needsSetup = (accessBundle?.services ?? []).filter(
+ (service) => service.personalValues && !service.personalValues.isConfigured
+ );
const [isEditOpen, setIsEditOpen] = useState(false);
const [isManageAccessOpen, setIsManageAccessOpen] = useState(false);
@@ -125,8 +134,29 @@ export const AgentVaultAccessBundleDetailPage = () => {
)}
</PageHeader>
+ {needsSetup.length > 0 && (
+ <Alert variant="warning" className="mb-6">
+ <TriangleAlertIcon />
+ <AlertDescription>
+ <p>
+ {needsSetup.length === 1
+ ? `${needsSetup[0].name} requires your personal values.`
+ : `${needsSetup.length} services require your personal values: ${needsSetup.map((service) => service.name).join(", ")}.`}{" "}
+ Sessions from this bundle can&apos;t reach {needsSetup.length === 1 ? "it" : "them"}{" "}
+ until you set {needsSetup.length === 1 ? "it" : "them"} up.
+ </p>
+ <AlertAction>
+ <Button variant="outline" size="sm" onClick={() => setServiceToSetUp(needsSetup[0])}>
+ Set Up {needsSetup[0].name}
+ </Button>
+ </AlertAction>
+ </AlertDescription>
+ </Alert>
+ )}
+
<ServicesCard
accessBundleId={accessBundle.id}
+ onSetUp={setServiceToSetUp}
services={accessBundle.services}
canManage={isAdmin}
onAdd={() => {
@@ -139,6 +169,15 @@ export const AgentVaultAccessBundleDetailPage = () => {
}}
/>
+ <PersonalValuesDialog
+ target={
+ serviceToSetUp ? { service: serviceToSetUp, accessBundleName: accessBundle.name } : null
+ }
+ onOpenChange={(isOpen) => {
+ if (!isOpen) setServiceToSetUp(null);
+ }}
+ />
+
<ManageAccessSheet
accessBundle={isManageAccessOpen ? accessBundle : null}
onOpenChange={setIsManageAccessOpen}
diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx
index 0f58e3d003..12a25433aa 100644
--- a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx
@@ -2,11 +2,14 @@ import { useMemo, useState } from "react";
import { format } from "date-fns";
import {
ChevronDownIcon,
+ CircleCheckIcon,
+ KeyIcon,
MoreHorizontalIcon,
PencilIcon,
PlusIcon,
SearchIcon,
- TrashIcon
+ TrashIcon,
+ TriangleAlertIcon
} from "lucide-react";
import { twMerge } from "tailwind-merge";
@@ -14,6 +17,7 @@ import { displayHostPattern } from "@app/components/agent-vault/service-sheet/se
import { ServiceIcon } from "@app/components/agent-vault/ServiceIconStack";
import { createNotification } from "@app/components/notifications";
import {
+ Badge,
Button,
Card,
CardAction,
@@ -71,6 +75,7 @@ type Props = {
canManage: boolean;
onAdd: () => void;
onEdit: (service: TAgentVaultService) => void;
+ onSetUp: (service: TAgentVaultService) => void;
};
// Two hosts is what the column fits comfortably; the rest go behind the count so the table keeps its
@@ -94,7 +99,14 @@ const HostsCell = ({ hostPattern }: { hostPattern: string }) => {
);
};
-export const ServicesCard = ({ accessBundleId, services, canManage, onAdd, onEdit }: Props) => {
+export const ServicesCard = ({
+ accessBundleId,
+ services,
+ canManage,
+ onAdd,
+ onEdit,
+ onSetUp
+}: Props) => {
const [search, setSearch] = useState("");
const [serviceToDelete, setServiceToDelete] = useState<TAgentVaultService | null>(null);
const deleteService = useDeleteAgentVaultService();
@@ -225,59 +237,97 @@ export const ServicesCard = ({ accessBundleId, services, canManage, onAdd, onEdi
Created
<ChevronDownIcon className={sortIconClassName(SortColumn.Created)} />
</TableHead>
+ <TableHead className="w-0" />
<TableHead variant="action" />
</TableRow>
</TableHeader>
<TableBody>
- {displayed.map((service) => (
- <TableRow key={service.id}>
- <TableCell>
- <div className="flex items-center gap-2">
- <ServiceIcon hostPattern={service.hostPattern} />
- {service.name}
- </div>
- </TableCell>
- <TableCell>
- <HostsCell hostPattern={service.hostPattern} />
- </TableCell>
- <TableCell>
- <Tooltip>
- <TooltipTrigger asChild>
- <span className="text-sm">
- {format(new Date(service.createdAt), "MMM d, yyyy")}
- </span>
- </TooltipTrigger>
- <TooltipContent>
- {format(new Date(service.createdAt), "MMM d, yyyy h:mm a")}
- </TooltipContent>
- </Tooltip>
- </TableCell>
- <TableCell variant="action">
- {canManage && (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <IconButton variant="ghost" size="xs" aria-label="Open service actions">
- <MoreHorizontalIcon />
- </IconButton>
- </DropdownMenuTrigger>
- <DropdownMenuContent sideOffset={2} align="end">
- <DropdownMenuItem onClick={() => onEdit(service)}>
- <PencilIcon />
- Edit
- </DropdownMenuItem>
- <DropdownMenuItem
- variant="danger"
- onClick={() => setServiceToDelete(service)}
- >
- <TrashIcon />
- Delete
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- )}
- </TableCell>
- </TableRow>
- ))}
+ {displayed.map((service) => {
+ const serviceValues = service.personalValues;
+ return (
+ <TableRow key={service.id}>
+ <TableCell>
+ <div className="flex items-center gap-2">
+ <ServiceIcon hostPattern={service.hostPattern} />
+ {service.name}
+ </div>
+ </TableCell>
+ <TableCell>
+ <HostsCell hostPattern={service.hostPattern} />
+ </TableCell>
+ <TableCell>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="text-sm">
+ {format(new Date(service.createdAt), "MMM d, yyyy")}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>
+ {format(new Date(service.createdAt), "MMM d, yyyy h:mm a")}
+ </TooltipContent>
+ </Tooltip>
+ </TableCell>
+ <TableCell>
+ <div className="flex justify-center">
+ {serviceValues &&
+ (serviceValues.isConfigured ? (
+ <Badge variant="neutral" asChild>
+ <button type="button" onClick={() => onSetUp(service)}>
+ <CircleCheckIcon />
+ Configured
+ </button>
+ </Badge>
+ ) : (
+ <Badge variant="warning" asChild>
+ <button type="button" onClick={() => onSetUp(service)}>
+ <TriangleAlertIcon />
+ Requires Setup
+ </button>
+ </Badge>
+ ))}
+ </div>
+ </TableCell>
+ <TableCell variant="action">
+ <div className="flex items-center justify-end gap-1.5">
+ {(canManage || serviceValues) && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton variant="ghost" size="xs" aria-label="Open service actions">
+ <MoreHorizontalIcon />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent sideOffset={2} align="end">
+ {serviceValues && (
+ <DropdownMenuItem onClick={() => onSetUp(service)}>
+ <KeyIcon />
+ {serviceValues.isConfigured
+ ? "Update My Personal Values"
+ : "Set Up My Personal Values"}
+ </DropdownMenuItem>
+ )}
+ {canManage && (
+ <>
+ <DropdownMenuItem onClick={() => onEdit(service)}>
+ <PencilIcon />
+ Edit
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ variant="danger"
+ onClick={() => setServiceToDelete(service)}
+ >
+ <TrashIcon />
+ Delete
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </div>
+ </TableCell>
+ </TableRow>
+ );
+ })}
</TableBody>
</Table>
)}
diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundlesPage/AgentVaultAccessBundlesPage.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundlesPage/AgentVaultAccessBundlesPage.tsx
index a9d5fd010d..f56cad81df 100644
--- a/frontend/src/pages/agent-vault/AgentVaultAccessBundlesPage/AgentVaultAccessBundlesPage.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundlesPage/AgentVaultAccessBundlesPage.tsx
@@ -11,6 +11,7 @@ import {
PlusIcon,
SearchIcon,
TrashIcon,
+ TriangleAlertIcon,
UsersIcon
} from "lucide-react";
import { twMerge } from "tailwind-merge";
@@ -19,6 +20,10 @@ import { AccessBundleFormDialog } from "@app/components/agent-vault/AccessBundle
import { ManageAccessSheet } from "@app/components/agent-vault/ManageAccessSheet";
import { ServiceIconStack } from "@app/components/agent-vault/ServiceIconStack";
import {
+ Alert,
+ AlertAction,
+ AlertDescription,
+ Badge,
Button,
Card,
CardAction,
@@ -59,7 +64,10 @@ import {
setUserTablePreference
} from "@app/helpers/userTablePreferences";
import { useDebounce, useResetPageHelper } from "@app/hooks";
-import { useListAgentVaultAccessBundles } from "@app/hooks/api/agentVault";
+import {
+ useListAgentVaultAccessBundles,
+ useListAgentVaultAccessBundlesRequiringSetup
+} from "@app/hooks/api/agentVault";
import { TAgentVaultAccessBundleListItem } from "@app/hooks/api/agentVault/types";
import { ProjectType } from "@app/hooks/api/projects/types";
import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
@@ -106,6 +114,10 @@ export const AgentVaultAccessBundlesPage = () => {
});
const displayedBundles = data?.accessBundles ?? [];
+
+ // From its own query rather than the page shown, so a bundle on a later page is still called out.
+ const { data: requiringSetup } = useListAgentVaultAccessBundlesRequiringSetup();
+ const bundlesNeedingSetup = requiringSetup?.accessBundles ?? [];
const totalCount = data?.totalCount ?? 0;
useResetPageHelper({ totalCount, offset: (page - 1) * perPage, setPage });
@@ -155,6 +167,34 @@ export const AgentVaultAccessBundlesPage = () => {
description="Group the services an agent can reach through a session."
/>
+ {bundlesNeedingSetup.length > 0 && (
+ <Alert variant="warning" className="mb-6">
+ <TriangleAlertIcon />
+ <AlertDescription>
+ <p>
+ {bundlesNeedingSetup.length === 1
+ ? `${bundlesNeedingSetup[0].name} has services that require your personal values.`
+ : `${bundlesNeedingSetup.length} access bundles have services that require your personal values: ${bundlesNeedingSetup.map((bundle) => bundle.name).join(", ")}.`}{" "}
+ Sessions can&apos;t reach those services until you set them up.
+ </p>
+ <AlertAction>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() =>
+ navigate({
+ to: "/organizations/$orgId/agent-vault/access-bundles/$accessBundleId",
+ params: { orgId: currentOrg.id, accessBundleId: bundlesNeedingSetup[0].id }
+ })
+ }
+ >
+ Open {bundlesNeedingSetup[0].name}
+ </Button>
+ </AlertAction>
+ </AlertDescription>
+ </Alert>
+ )}
+
<Card>
<CardHeader>
<CardTitle>
@@ -174,8 +214,8 @@ export const AgentVaultAccessBundlesPage = () => {
</CardAction>
)}
</CardHeader>
- <CardContent>
- <InputGroup>
+ <CardContent className="flex items-center gap-2">
+ <InputGroup className="flex-1">
<InputGroupAddon>
<SearchIcon />
</InputGroupAddon>
@@ -227,6 +267,7 @@ export const AgentVaultAccessBundlesPage = () => {
Created
<ChevronDownIcon className={sortIconClassName(SortColumn.Created)} />
</TableHead>
+ <TableHead className="w-0" />
<TableHead variant="action" />
</TableRow>
</TableHeader>
@@ -302,51 +343,71 @@ export const AgentVaultAccessBundlesPage = () => {
</TooltipContent>
</Tooltip>
</TableCell>
+ <TableCell>
+ <div className="flex justify-center">
+ {bundle.servicesRequiringSetup.length > 0 && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge variant="warning">
+ <TriangleAlertIcon />
+ Requires Setup
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-xs">
+ Your personal values are missing for{" "}
+ {bundle.servicesRequiringSetup.join(", ")}.
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </div>
+ </TableCell>
<TableCell variant="action">
- {isAdmin && (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <IconButton
- variant="ghost"
- size="xs"
- aria-label="Open access bundle actions"
- onClick={(event) => event.stopPropagation()}
- >
- <MoreHorizontalIcon />
- </IconButton>
- </DropdownMenuTrigger>
- <DropdownMenuContent sideOffset={2} align="end">
- <DropdownMenuItem
- onClick={(event) => {
- event.stopPropagation();
- setBundleToManage(bundle);
- }}
- >
- <UsersIcon />
- Manage Access
- </DropdownMenuItem>
- <DropdownMenuItem
- onClick={(event) => {
- event.stopPropagation();
- setBundleToEdit(bundle);
- }}
- >
- <PencilIcon />
- Edit
- </DropdownMenuItem>
- <DropdownMenuItem
- variant="danger"
- onClick={(event) => {
- event.stopPropagation();
- setBundleToDelete(bundle);
- }}
- >
- <TrashIcon />
- Delete
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- )}
+ <div className="flex items-center justify-end gap-1.5">
+ {isAdmin && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ variant="ghost"
+ size="xs"
+ aria-label="Open access bundle actions"
+ onClick={(event) => event.stopPropagation()}
+ >
+ <MoreHorizontalIcon />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent sideOffset={2} align="end">
+ <DropdownMenuItem
+ onClick={(event) => {
+ event.stopPropagation();
+ setBundleToManage(bundle);
+ }}
+ >
+ <UsersIcon />
+ Manage Access
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={(event) => {
+ event.stopPropagation();
+ setBundleToEdit(bundle);
+ }}
+ >
+ <PencilIcon />
+ Edit
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ variant="danger"
+ onClick={(event) => {
+ event.stopPropagation();
+ setBundleToDelete(bundle);
+ }}
+ >
+ <TrashIcon />
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </div>
</TableCell>
</TableRow>
))}
diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/CreateSessionDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/CreateSessionDialog.tsx
index ac02cd7a15..07a2d8b495 100644
--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/CreateSessionDialog.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/CreateSessionDialog.tsx
@@ -1,9 +1,15 @@
import { useEffect, useRef, useState } from "react";
-import { PackageIcon } from "lucide-react";
+import { Link } from "@tanstack/react-router";
+import { PackageIcon, TriangleAlertIcon } from "lucide-react";
import ms from "ms";
+import { PersonalValuesDialog } from "@app/components/agent-vault/PersonalValuesDialog";
+import { ServiceIcon } from "@app/components/agent-vault/ServiceIconStack";
import { createNotification } from "@app/components/notifications";
import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
Button,
Combobox,
Dialog,
@@ -25,14 +31,17 @@ import {
SelectTrigger,
SelectValue
} from "@app/components/v3";
+import { useOrganization } from "@app/context";
import { useDebounce, useDiscardChangesGuard } from "@app/hooks";
import {
useCreateAgentVaultSession,
+ useGetAgentVaultAccessBundle,
useListAgentVaultAccessBundles
} from "@app/hooks/api/agentVault";
import {
TAgentVaultAccessBundleListItem,
- TAgentVaultMintedSession
+ TAgentVaultMintedSession,
+ TAgentVaultService
} from "@app/hooks/api/agentVault/types";
const NEVER_TTL = "never";
@@ -73,6 +82,7 @@ type Props = {
};
export const CreateSessionDialog = ({ isOpen, onOpenChange, onCreated }: Props) => {
+ const { currentOrg } = useOrganization();
const [bundleSearch, setBundleSearch] = useState("");
const [debouncedBundleSearch] = useDebounce(bundleSearch);
const { data: accessBundles, isFetching: isSearchingBundles } = useListAgentVaultAccessBundles({
@@ -86,6 +96,17 @@ export const CreateSessionDialog = ({ isOpen, onOpenChange, onCreated }: Props)
const [selectedBundle, setSelectedBundle] = useState<TAgentVaultAccessBundleListItem | null>(
null
);
+ const { data: selectedBundleDetails } = useGetAgentVaultAccessBundle(selectedBundle?.id ?? "");
+ const needsSetup =
+ selectedBundle && selectedBundleDetails?.id === selectedBundle.id
+ ? selectedBundleDetails.services.filter(
+ (service) => service.personalValues && !service.personalValues.isConfigured
+ )
+ : [];
+ // Past four, three are listed and the rest link to the bundle, whose table lists every one.
+ const shownNeedsSetup = needsSetup.length > 4 ? needsSetup.slice(0, 3) : needsSetup;
+ const hiddenNeedsSetupCount = needsSetup.length - shownNeedsSetup.length;
+ const [serviceToSetUp, setServiceToSetUp] = useState<TAgentVaultService | null>(null);
const [ttlPreset, setTtlPreset] = useState(DEFAULT_TTL_PRESET);
const [customTtl, setCustomTtl] = useState("");
const customTtlInputRef = useRef<HTMLInputElement>(null);
@@ -229,6 +250,54 @@ export const CreateSessionDialog = ({ isOpen, onOpenChange, onCreated }: Props)
)}
</FieldContent>
</Field>
+
+ {/* A warning, not a block: the session works for every other service, and picks up values
+ set up later on the proxy's next poll. */}
+ {needsSetup.length > 0 && selectedBundle && (
+ <Alert variant="warning">
+ <TriangleAlertIcon />
+ <AlertTitle>
+ {needsSetup.length === 1
+ ? "1 service requires your personal values"
+ : `${needsSetup.length} services require your personal values`}
+ </AlertTitle>
+ <AlertDescription>
+ <p>
+ Until you set {needsSetup.length === 1 ? "it" : "them"} up,{" "}
+ {needsSetup.length === 1 ? "it rejects" : "they reject"} requests from this
+ session.
+ </p>
+ <ul className="mt-2 w-full divide-y divide-warning/15 rounded-md border border-warning/20">
+ {shownNeedsSetup.map((service) => (
+ <li key={service.id} className="flex items-center gap-2 px-2.5 py-1.5">
+ <ServiceIcon hostPattern={service.hostPattern} />
+ <span className="min-w-0 flex-1 truncate text-sm text-foreground">
+ {service.name}
+ </span>
+ <Button
+ variant="warning"
+ size="xs"
+ onClick={() => setServiceToSetUp(service)}
+ >
+ Set Up
+ </Button>
+ </li>
+ ))}
+ {hiddenNeedsSetupCount > 0 && (
+ <li className="px-2.5 py-1.5 text-xs">
+ <Link
+ to="/organizations/$orgId/agent-vault/access-bundles/$accessBundleId"
+ params={{ orgId: currentOrg.id, accessBundleId: selectedBundle.id }}
+ className="underline underline-offset-2 hover:text-foreground"
+ >
+ {hiddenNeedsSetupCount} more in {selectedBundle.name}
+ </Link>
+ </li>
+ )}
+ </ul>
+ </AlertDescription>
+ </Alert>
+ )}
</div>
<DialogFooter>
@@ -245,6 +314,17 @@ export const CreateSessionDialog = ({ isOpen, onOpenChange, onCreated }: Props)
</Button>
</DialogFooter>
+ <PersonalValuesDialog
+ target={
+ serviceToSetUp && selectedBundle
+ ? { service: serviceToSetUp, accessBundleName: selectedBundle.name }
+ : null
+ }
+ onOpenChange={(open) => {
+ if (!open) setServiceToSetUp(null);
+ }}
+ />
+
<DiscardChangesAlertDialog
open={isDiscardDialogOpen}
onOpenChange={setIsDiscardDialogOpen}
diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogRow.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogRow.tsx
index b7ba4a3213..aa6431d8eb 100644
--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogRow.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogRow.tsx
@@ -4,7 +4,7 @@ import {
ArrowRightIcon,
CircleHelpIcon,
CircleXIcon,
- KeyRoundIcon,
+ KeyIcon,
type LucideIcon,
PlusIcon,
ShieldBanIcon
@@ -40,7 +40,7 @@ export const DECISION_PRESENTATION: Record<
[AgentVaultSessionLogDecision.Brokered]: {
label: "Brokered",
variant: "success",
- icon: KeyRoundIcon,
+ icon: KeyIcon,
iconClassName: "text-success"
},
[AgentVaultSessionLogDecision.Passthrough]: {
diff --git a/frontend/src/pages/agent-vault/AgentVaultVariablesPage/AgentVaultVariablesPage.tsx b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/AgentVaultVariablesPage.tsx
index 7c37d60503..ed66c74a52 100644
--- a/frontend/src/pages/agent-vault/AgentVaultVariablesPage/AgentVaultVariablesPage.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/AgentVaultVariablesPage.tsx
@@ -1,19 +1,42 @@
import { Helmet } from "react-helmet";
import { useTranslation } from "react-i18next";
+import { useNavigate, useSearch } from "@tanstack/react-router";
import { BracesIcon } from "lucide-react";
-import { AccessRestrictedDialog, PageHeader } from "@app/components/v3";
-import { useProjectPermission } from "@app/context";
+import { PageHeader, Tabs, TabsContent, TabsList, TabsTrigger } from "@app/components/v3";
+import { useOrganization, useProjectPermission } from "@app/context";
+import { AgentVaultVariableScope } from "@app/hooks/api/agentVault";
import { ProjectType } from "@app/hooks/api/projects/types";
import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
import { VariablesCard } from "./components/VariablesCard";
+// Shared variables are an admin's alone, so a member sees only their personal ones, without tabs. Nobody can see
+// anyone else's personal variables, admins included.
export const AgentVaultVariablesPage = () => {
const { t } = useTranslation();
+ const navigate = useNavigate();
+ const { currentOrg } = useOrganization();
const { hasProjectRole } = useProjectPermission();
const isAdmin = hasProjectRole(ProjectMembershipRole.Admin);
+ const selectedTab = useSearch({
+ strict: false,
+ select: (el) => (el as { selectedTab?: string })?.selectedTab
+ });
+ const tab =
+ isAdmin && selectedTab !== AgentVaultVariableScope.Personal
+ ? AgentVaultVariableScope.Shared
+ : AgentVaultVariableScope.Personal;
+
+ const updateTab = (value: string) => {
+ navigate({
+ to: "/organizations/$orgId/agent-vault/variables",
+ search: (prev) => ({ ...prev, selectedTab: value }),
+ params: { orgId: currentOrg.id }
+ });
+ };
+
return (
<div className="mx-auto mb-6 flex w-full max-w-8xl flex-col">
<Helmet>
@@ -24,10 +47,28 @@ export const AgentVaultVariablesPage = () => {
scope={ProjectType.AgentVault}
icon={BracesIcon}
title="Variables"
- description="Store values once and reference them from services in any access bundle."
+ description={
+ tab === AgentVaultVariableScope.Personal
+ ? "Your own values, reused across every service you set up. Only you can read them."
+ : "Store values once and reference them from services in any access bundle."
+ }
/>
- {/* The variables routes are admin only. */}
- {isAdmin ? <VariablesCard /> : <AccessRestrictedDialog />}
+ {isAdmin ? (
+ <Tabs value={tab} onValueChange={updateTab}>
+ <TabsList variant="av" aria-label="Agent Vault variable lists">
+ <TabsTrigger value={AgentVaultVariableScope.Shared}>Shared Variables</TabsTrigger>
+ <TabsTrigger value={AgentVaultVariableScope.Personal}>Personal Variables</TabsTrigger>
+ </TabsList>
+ <TabsContent value={AgentVaultVariableScope.Shared}>
+ <VariablesCard scope={AgentVaultVariableScope.Shared} />
+ </TabsContent>
+ <TabsContent value={AgentVaultVariableScope.Personal}>
+ <VariablesCard scope={AgentVaultVariableScope.Personal} />
+ </TabsContent>
+ </Tabs>
+ ) : (
+ <VariablesCard scope={AgentVaultVariableScope.Personal} />
+ )}
</div>
);
};
diff --git a/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/DeleteVariableDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/DeleteVariableDialog.tsx
index b3ffd2f757..b19c909362 100644
--- a/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/DeleteVariableDialog.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/DeleteVariableDialog.tsx
@@ -13,7 +13,7 @@ import {
Button
} from "@app/components/v3";
import { useOrganization } from "@app/context";
-import { useDeleteAgentVaultVariable } from "@app/hooks/api/agentVault";
+import { AgentVaultVariableScope, useDeleteAgentVaultVariable } from "@app/hooks/api/agentVault";
import { TAgentVaultVariable } from "@app/hooks/api/agentVault/types";
type Props = {
@@ -24,6 +24,7 @@ type Props = {
export const DeleteVariableDialog = ({ variable, onOpenChange }: Props) => {
const { currentOrg } = useOrganization();
const deleteVariable = useDeleteAgentVaultVariable();
+ const isPersonal = variable?.scope === AgentVaultVariableScope.Personal;
const usedByServices = variable?.usedByServices ?? [];
const isInUse = usedByServices.length > 0;
@@ -44,9 +45,13 @@ export const DeleteVariableDialog = ({ variable, onOpenChange }: Props) => {
<AlertDialogHeader>
<AlertDialogTitle>Delete &quot;{variable?.key}&quot;</AlertDialogTitle>
<AlertDialogDescription>
- {isInUse
+ {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.`
+ : 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.`
- : "Its value is deleted with it. This cannot be undone."}
+ : null}
+ {!isInUse && "Its value is deleted with it. This cannot be undone."}
</AlertDialogDescription>
</AlertDialogHeader>
diff --git a/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/VariablesCard.tsx b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/VariablesCard.tsx
index 194eef2560..509d09720d 100644
--- a/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/VariablesCard.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/VariablesCard.tsx
@@ -47,7 +47,11 @@ import {
TooltipContent,
TooltipTrigger
} from "@app/components/v3";
-import { MAX_VARIABLES, toVariableReference } from "@app/helpers/agentVaultVariables";
+import {
+ MAX_PERSONAL_VARIABLES,
+ MAX_VARIABLES,
+ toVariableReference
+} from "@app/helpers/agentVaultVariables";
import {
getUserTablePreference,
PreferenceKey,
@@ -55,6 +59,7 @@ import {
} from "@app/helpers/userTablePreferences";
import { useDebounce, useResetPageHelper } from "@app/hooks";
import {
+ AgentVaultVariableScope,
useListAgentVaultVariables,
useRevealAgentVaultVariableValue
} from "@app/hooks/api/agentVault";
@@ -200,7 +205,13 @@ const TruncatedKey = ({ value }: { value: string }) => {
);
};
-export const VariablesCard = () => {
+type Props = {
+ /** Personal for the caller's own variables, which only their personal values use. */
+ scope?: AgentVaultVariableScope;
+};
+
+export const VariablesCard = ({ scope = AgentVaultVariableScope.Shared }: Props) => {
+ const isPersonal = scope === AgentVaultVariableScope.Personal;
const revealValue = useRevealAgentVaultVariableValue();
const [search, setSearch] = useState("");
@@ -227,6 +238,7 @@ export const VariablesCard = () => {
setPage(1);
}
const { data, isPending } = useListAgentVaultVariables({
+ scope,
search: searchTerm || undefined,
orderBy: sortColumn,
orderDirection: sortDirection === "ascending" ? "asc" : "desc",
@@ -237,7 +249,7 @@ export const VariablesCard = () => {
const totalCount = data?.totalCount ?? 0;
useResetPageHelper({ totalCount, offset: (page - 1) * perPage, setPage });
// A search narrows totalCount, so whether the cap is reached is read off an unfiltered count.
- const { data: unfilteredData } = useListAgentVaultVariables({ limit: 1 });
+ const { data: unfilteredData } = useListAgentVaultVariables({ scope, limit: 1 });
const handleSort = (column: SortColumn, direction: "ascending" | "descending" | "none") => {
setPage(1);
@@ -303,7 +315,8 @@ export const VariablesCard = () => {
};
const hasVariables = totalCount > 0 || Boolean(searchTerm);
- const isAtLimit = (unfilteredData?.totalCount ?? 0) >= MAX_VARIABLES;
+ const maxVariables = isPersonal ? MAX_PERSONAL_VARIABLES : MAX_VARIABLES;
+ const isAtLimit = (unfilteredData?.totalCount ?? 0) >= maxVariables;
const openForm = (variable: TAgentVaultVariable | null) => {
setVariableToEdit(variable);
@@ -314,12 +327,21 @@ export const VariablesCard = () => {
<Card>
<CardHeader>
<CardTitle>
- Variables
+ {isPersonal ? "Personal Variables" : "Shared Variables"}
<DocumentationLinkBadge href={AgentVaultDocsUrls.variables} />
</CardTitle>
<CardDescription>
- A variable stores one value that any service can use as{" "}
- <code className="font-mono">{toVariableReference("KEY")}</code>.
+ {isPersonal ? (
+ <>
+ Your own values, for the services that ask each member for one. Use one as{" "}
+ <code className="font-mono">{toVariableReference("KEY")}</code> when you set one up.
+ </>
+ ) : (
+ <>
+ A variable stores one value that any service can use as{" "}
+ <code className="font-mono">{toVariableReference("KEY")}</code>.
+ </>
+ )}
</CardDescription>
<CardAction>
{isAtLimit ? (
@@ -329,19 +351,20 @@ export const VariablesCard = () => {
<span tabIndex={0}>
<Button variant="av" isDisabled>
<PlusIcon />
- Add Variable
+ Add {isPersonal ? "Personal" : "Shared"} Variable
</Button>
</span>
</TooltipTrigger>
<TooltipContent className="max-w-xs">
- Agent Vault can hold at most {MAX_VARIABLES} variables. Delete one that no service
- uses first.
+ {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.`}
</TooltipContent>
</Tooltip>
) : (
<Button variant="av" onClick={() => openForm(null)}>
<PlusIcon />
- Add Variable
+ Add {isPersonal ? "Personal" : "Shared"} Variable
</Button>
)}
</CardAction>
@@ -370,9 +393,11 @@ export const VariablesCard = () => {
{hasVariables ? "No variables match your search" : "No variables yet"}
</EmptyTitle>
<EmptyDescription>
- {hasVariables
- ? "Try a different search term."
- : "Add a variable to use one value across services in any access bundle."}
+ {hasVariables && "Try a different search term."}
+ {!hasVariables &&
+ (isPersonal
+ ? "Add a variable to reuse one of your values across the services you set up."
+ : "Add a variable to use one value across services in any access bundle.")}
</EmptyDescription>
</EmptyHeader>
</Empty>
@@ -492,6 +517,7 @@ export const VariablesCard = () => {
)}
<VariableFormDialog
+ scope={scope}
isOpen={isFormOpen}
onOpenChange={setIsFormOpen}
variable={variableToEdit}
diff --git a/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts b/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts
index 535f814a00..e1182d205d 100644
--- a/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts
+++ b/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts
@@ -5,6 +5,7 @@ export const AgentVaultDocsUrls = {
quickstart: `${AGENT_VAULT_DOCS_BASE_URL}/quickstart`,
accessBundles: `${AGENT_VAULT_DOCS_BASE_URL}/access-bundles`,
services: `${AGENT_VAULT_DOCS_BASE_URL}/services`,
+ memberProvidedValues: `${AGENT_VAULT_DOCS_BASE_URL}/services#member-provided-values`,
variables: `${AGENT_VAULT_DOCS_BASE_URL}/variables`,
sessions: `${AGENT_VAULT_DOCS_BASE_URL}/sessions`,
proxies: `${AGENT_VAULT_DOCS_BASE_URL}/proxies`,